diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..c6a69a43b7 --- /dev/null +++ b/.clang-format @@ -0,0 +1,11 @@ +Language: Cpp +BasedOnStyle: Google +ColumnLimit: 120 + +DerivePointerAlignment: false +PointerAlignment: Left + +SortIncludes: true +IncludeBlocks: Preserve + +IndentPPDirectives: AfterHash diff --git a/include/pika_admin.h b/include/pika_admin.h index a832561013..886bd91f7d 100644 --- a/include/pika_admin.h +++ b/include/pika_admin.h @@ -6,10 +6,10 @@ #ifndef PIKA_ADMIN_H_ #define PIKA_ADMIN_H_ -#include -#include #include +#include #include +#include #include "storage/storage.h" @@ -20,14 +20,11 @@ */ class SlaveofCmd : public Cmd { public: - SlaveofCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), is_noone_(false) {} + SlaveofCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), is_noone_(false) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlaveofCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlaveofCmd(*this); } private: std::string master_ip_; @@ -43,14 +40,11 @@ class SlaveofCmd : public Cmd { class DbSlaveofCmd : public Cmd { public: - DbSlaveofCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + DbSlaveofCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new DbSlaveofCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new DbSlaveofCmd(*this); } private: std::string db_name_; @@ -70,14 +64,11 @@ class DbSlaveofCmd : public Cmd { class AuthCmd : public Cmd { public: - AuthCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + AuthCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new AuthCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new AuthCmd(*this); } private: std::string pwd_; @@ -86,33 +77,25 @@ class AuthCmd : public Cmd { class BgsaveCmd : public Cmd { public: - BgsaveCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + BgsaveCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new BgsaveCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new BgsaveCmd(*this); } private: virtual void DoInitial() override; - virtual void Clear() { - bgsave_tables_.clear(); - } + virtual void Clear() { bgsave_tables_.clear(); } std::set bgsave_tables_; }; class CompactCmd : public Cmd { public: - CompactCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + CompactCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new CompactCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new CompactCmd(*this); } private: virtual void DoInitial() override; @@ -126,14 +109,11 @@ class CompactCmd : public Cmd { class PurgelogstoCmd : public Cmd { public: - PurgelogstoCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), num_(0) {} + PurgelogstoCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), num_(0) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PurgelogstoCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PurgelogstoCmd(*this); } private: uint32_t num_; @@ -143,14 +123,11 @@ class PurgelogstoCmd : public Cmd { class PingCmd : public Cmd { public: - PingCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PingCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PingCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PingCmd(*this); } private: virtual void DoInitial() override; @@ -158,75 +135,55 @@ class PingCmd : public Cmd { class SelectCmd : public Cmd { public: - SelectCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SelectCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SelectCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SelectCmd(*this); } private: virtual void DoInitial() override; - virtual void Clear() { - table_name_.clear(); - } + virtual void Clear() { table_name_.clear(); } std::string table_name_; }; class FlushallCmd : public Cmd { public: - FlushallCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + FlushallCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new FlushallCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new FlushallCmd(*this); } private: virtual void DoInitial() override; - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class FlushdbCmd : public Cmd { public: - FlushdbCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + FlushdbCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new FlushdbCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new FlushdbCmd(*this); } private: std::string db_name_; virtual void DoInitial() override; - virtual void Clear() { - db_name_.clear(); - } + virtual void Clear() { db_name_.clear(); } }; class ClientCmd : public Cmd { public: - ClientCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ClientCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); const static std::string CLIENT_LIST_S; const static std::string CLIENT_KILL_S; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ClientCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ClientCmd(*this); } private: std::string operation_, info_; @@ -251,18 +208,15 @@ class InfoCmd : public Cmd { kInfoDebug }; - InfoCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), rescan_(false), off_(false) {} + InfoCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), rescan_(false), off_(false) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new InfoCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new InfoCmd(*this); } private: InfoSection info_section_; - bool rescan_; //whether to rescan the keyspace + bool rescan_; // whether to rescan the keyspace bool off_; std::set keyspace_scan_tables_; @@ -299,14 +253,11 @@ class InfoCmd : public Cmd { class ShutdownCmd : public Cmd { public: - ShutdownCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ShutdownCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ShutdownCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ShutdownCmd(*this); } private: virtual void DoInitial() override; @@ -314,34 +265,28 @@ class ShutdownCmd : public Cmd { class ConfigCmd : public Cmd { public: - ConfigCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ConfigCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ConfigCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ConfigCmd(*this); } private: std::vector config_args_v_; virtual void DoInitial() override; - void ConfigGet(std::string &ret); - void ConfigSet(std::string &ret); - void ConfigRewrite(std::string &ret); - void ConfigResetstat(std::string &ret); + void ConfigGet(std::string& ret); + void ConfigSet(std::string& ret); + void ConfigRewrite(std::string& ret); + void ConfigResetstat(std::string& ret); }; class MonitorCmd : public Cmd { public: - MonitorCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + MonitorCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new MonitorCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new MonitorCmd(*this); } private: virtual void DoInitial() override; @@ -349,14 +294,11 @@ class MonitorCmd : public Cmd { class DbsizeCmd : public Cmd { public: - DbsizeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + DbsizeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new DbsizeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new DbsizeCmd(*this); } private: virtual void DoInitial() override; @@ -364,14 +306,11 @@ class DbsizeCmd : public Cmd { class TimeCmd : public Cmd { public: - TimeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + TimeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new TimeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new TimeCmd(*this); } private: virtual void DoInitial() override; @@ -379,14 +318,11 @@ class TimeCmd : public Cmd { class DelbackupCmd : public Cmd { public: - DelbackupCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + DelbackupCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new DelbackupCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new DelbackupCmd(*this); } private: virtual void DoInitial() override; @@ -394,14 +330,11 @@ class DelbackupCmd : public Cmd { class EchoCmd : public Cmd { public: - EchoCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + EchoCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new EchoCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new EchoCmd(*this); } private: std::string body_; @@ -410,34 +343,27 @@ class EchoCmd : public Cmd { class ScandbCmd : public Cmd { public: - ScandbCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), type_(storage::kAll) {} + ScandbCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), type_(storage::kAll) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ScandbCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ScandbCmd(*this); } private: storage::DataType type_; virtual void DoInitial() override; - virtual void Clear() { - type_ = storage::kAll; - } + virtual void Clear() { type_ = storage::kAll; } }; class SlowlogCmd : public Cmd { public: - enum SlowlogCondition{kGET, kLEN, kRESET}; - SlowlogCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), condition_(kGET) {} + enum SlowlogCondition { kGET, kLEN, kRESET }; + SlowlogCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), condition_(kGET) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlowlogCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlowlogCmd(*this); } + private: int64_t number_; SlowlogCmd::SlowlogCondition condition_; @@ -450,36 +376,26 @@ class SlowlogCmd : public Cmd { class PaddingCmd : public Cmd { public: - PaddingCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PaddingCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PaddingCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PaddingCmd(*this); } private: virtual void DoInitial(); - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; #ifdef TCMALLOC_EXTENSION class TcmallocCmd : public Cmd { public: - TcmallocCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + TcmallocCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new TcmallocCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new TcmallocCmd(*this); } private: int64_t type_; @@ -489,33 +405,27 @@ class TcmallocCmd : public Cmd { #endif class PKPatternMatchDelCmd : public Cmd { - public: - PKPatternMatchDelCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + public: + PKPatternMatchDelCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PKPatternMatchDelCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PKPatternMatchDelCmd(*this); } private: storage::DataType type_; - std::string pattern_; + std::string pattern_; virtual void DoInitial() override; }; class DummyCmd : public Cmd { public: DummyCmd() : Cmd("", 0, 0) {} - DummyCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + DummyCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new DummyCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new DummyCmd(*this); } private: virtual void DoInitial() override; @@ -523,14 +433,11 @@ class DummyCmd : public Cmd { class QuitCmd : public Cmd { public: - QuitCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + QuitCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new QuitCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new QuitCmd(*this); } private: virtual void DoInitial() override; @@ -538,14 +445,11 @@ class QuitCmd : public Cmd { class HelloCmd : public Cmd { public: - HelloCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HelloCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HelloCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HelloCmd(*this); } private: virtual void DoInitial() override; diff --git a/include/pika_auxiliary_thread.h b/include/pika_auxiliary_thread.h index 6c69416a34..bf5decef19 100644 --- a/include/pika_auxiliary_thread.h +++ b/include/pika_auxiliary_thread.h @@ -12,14 +12,11 @@ class PikaAuxiliaryThread : public net::Thread { public: - PikaAuxiliaryThread() : - mu_(), - cv_(&mu_) { - set_thread_name("AuxiliaryThread"); - } + PikaAuxiliaryThread() : mu_(), cv_(&mu_) { set_thread_name("AuxiliaryThread"); } virtual ~PikaAuxiliaryThread(); pstd::Mutex mu_; pstd::CondVar cv_; + private: virtual void* ThreadMain(); }; diff --git a/include/pika_binlog.h b/include/pika_binlog.h index d4c0224994..a73f34875a 100644 --- a/include/pika_binlog.h +++ b/include/pika_binlog.h @@ -14,14 +14,14 @@ #include "include/pika_define.h" -using pstd::Status; using pstd::Slice; +using pstd::Status; std::string NewFileName(const std::string name, const uint32_t current); class Version { public: - Version(pstd::RWFile *save); + Version(pstd::RWFile* save); ~Version(); Status Init(); @@ -38,12 +38,11 @@ class Version { void debug() { pstd::RWLock(&rwlock_, false); - printf ("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); + printf("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); } private: - - pstd::RWFile *save_; + pstd::RWFile* save_; // No copying allowed; Version(const Version&); @@ -55,10 +54,10 @@ class Binlog { Binlog(const std::string& Binlog_path, const int file_size = 100 * 1024 * 1024); ~Binlog(); - void Lock() { mutex_.Lock(); } - void Unlock() { mutex_.Unlock(); } + void Lock() { mutex_.Lock(); } + void Unlock() { mutex_.Unlock(); } - Status Put(const std::string &item); + Status Put(const std::string& item); Status GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset, uint32_t* term = NULL, uint64_t* logic_id = NULL); /* @@ -68,17 +67,11 @@ class Binlog { // Need to hold Lock(); Status Truncate(uint32_t pro_num, uint64_t pro_offset, uint64_t index); - uint64_t file_size() { - return file_size_; - } + uint64_t file_size() { return file_size_; } - std::string filename() { - return filename_; - } + std::string filename() { return filename_; } - bool IsBinlogIoError() { - return binlog_io_error_; - } + bool IsBinlogIoError() { return binlog_io_error_; } // need to hold mutex_ void SetTerm(uint32_t term) { @@ -97,22 +90,21 @@ class Binlog { private: Status Put(const char* item, int len); static Status AppendPadding(pstd::WritableFile* file, uint64_t* len); - //pstd::WritableFile *queue() { return queue_; } + // pstd::WritableFile *queue() { return queue_; } void InitLogFile(); - Status EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset); - + Status EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset); /* * Produce */ - Status Produce(const Slice &item, int *pro_offset); + Status Produce(const Slice& item, int* pro_offset); std::atomic opened_; Version* version_; - pstd::WritableFile *queue_; - pstd::RWFile *versionfile_; + pstd::WritableFile* queue_; + pstd::RWFile* versionfile_; pstd::Mutex mutex_; @@ -130,7 +122,7 @@ class Binlog { std::atomic binlog_io_error_; // Not use - //int32_t retry_; + // int32_t retry_; // No copying allowed Binlog(const Binlog&); diff --git a/include/pika_binlog_reader.h b/include/pika_binlog_reader.h index 7dc350bf4f..02d6da6013 100644 --- a/include/pika_binlog_reader.h +++ b/include/pika_binlog_reader.h @@ -6,17 +6,17 @@ #ifndef PIKA_BINLOG_READER_H_ #define PIKA_BINLOG_READER_H_ -#include #include +#include -#include "pstd/include/pstd_status.h" #include "pstd/include/env.h" #include "pstd/include/pstd_slice.h" +#include "pstd/include/pstd_status.h" #include "include/pika_binlog.h" -using pstd::Status; using pstd::Slice; +using pstd::Status; class PikaBinlogReader { public: @@ -27,9 +27,10 @@ class PikaBinlogReader { int Seek(std::shared_ptr logger, uint32_t filenum, uint64_t offset); bool ReadToTheEnd(); void GetReaderStatus(uint32_t* cur_filenum, uint64_t* cur_offset); + private: bool GetNext(uint64_t* size); - unsigned int ReadPhysicalRecord(pstd::Slice *redult, uint32_t* filenum, uint64_t* offset); + unsigned int ReadPhysicalRecord(pstd::Slice* redult, uint32_t* filenum, uint64_t* offset); // Returns scratch binflog and corresponding offset Status Consume(std::string* scratch, uint32_t* filenum, uint64_t* offset); @@ -39,7 +40,7 @@ class PikaBinlogReader { uint64_t last_record_offset_; std::shared_ptr logger_; - pstd::SequentialFile *queue_; + pstd::SequentialFile* queue_; char* const backing_store_; Slice buffer_; diff --git a/include/pika_binlog_transverter.h b/include/pika_binlog_transverter.h index c81651b255..e02e64141e 100644 --- a/include/pika_binlog_transverter.h +++ b/include/pika_binlog_transverter.h @@ -6,16 +6,16 @@ #ifndef PIKA_BINLOG_TRANSVERTER_H_ #define PIKA_BINLOG_TRANSVERTER_H_ -#include +#include #include #include -#include - +#include /* - * ***********************************************Type First Binlog Item Format*********************************************** - * | | | | | | | | | - * 2 Bytes 4 Bytes 4 Bytes 8 Bytes 4 Bytes 8 Bytes 4 Bytes content length Bytes + * ***********************************************Type First Binlog Item + * Format*********************************************** | | | | | + * | | | | 2 Bytes 4 Bytes 4 Bytes 8 Bytes 4 + * Bytes 8 Bytes 4 Bytes content length Bytes * */ #define BINLOG_ENCODE_LEN 34 @@ -24,68 +24,52 @@ enum BinlogType { TypeFirst = 1, }; - const int BINLOG_ITEM_HEADER_SIZE = 34; const int PADDING_BINLOG_PROTOCOL_SIZE = 22; const int SPACE_STROE_PARAMETER_LENGTH = 5; class BinlogItem { - public: - BinlogItem() : - exec_time_(0), - term_id_(0), - logic_id_(0), - filenum_(0), - offset_(0), - content_("") {} - - friend class PikaBinlogTransverter; - - uint32_t exec_time() const; - uint32_t term_id() const; - uint64_t logic_id() const; - uint32_t filenum() const; - uint64_t offset() const; - std::string content() const; - std::string ToString() const; - - void set_exec_time(uint32_t exec_time); - void set_term_id(uint32_t term_id); - void set_logic_id(uint64_t logic_id); - void set_filenum(uint32_t filenum); - void set_offset(uint64_t offset); - - private: - uint32_t exec_time_; - uint32_t term_id_; - uint64_t logic_id_; - uint32_t filenum_; - uint64_t offset_; - std::string content_; - std::vector extends_; + public: + BinlogItem() : exec_time_(0), term_id_(0), logic_id_(0), filenum_(0), offset_(0), content_("") {} + + friend class PikaBinlogTransverter; + + uint32_t exec_time() const; + uint32_t term_id() const; + uint64_t logic_id() const; + uint32_t filenum() const; + uint64_t offset() const; + std::string content() const; + std::string ToString() const; + + void set_exec_time(uint32_t exec_time); + void set_term_id(uint32_t term_id); + void set_logic_id(uint64_t logic_id); + void set_filenum(uint32_t filenum); + void set_offset(uint64_t offset); + + private: + uint32_t exec_time_; + uint32_t term_id_; + uint64_t logic_id_; + uint32_t filenum_; + uint64_t offset_; + std::string content_; + std::vector extends_; }; -class PikaBinlogTransverter{ - public: - PikaBinlogTransverter() {}; - static std::string BinlogEncode(BinlogType type, - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset, - const std::string& content, - const std::vector& extends); +class PikaBinlogTransverter { + public: + PikaBinlogTransverter(){}; + static std::string BinlogEncode(BinlogType type, uint32_t exec_time, uint32_t term_id, uint64_t logic_id, + uint32_t filenum, uint64_t offset, const std::string& content, + const std::vector& extends); - static bool BinlogDecode(BinlogType type, - const std::string& binlog, - BinlogItem* binlog_item); + static bool BinlogDecode(BinlogType type, const std::string& binlog, BinlogItem* binlog_item); - static std::string ConstructPaddingBinlog(BinlogType type, uint32_t size); + static std::string ConstructPaddingBinlog(BinlogType type, uint32_t size); - static bool BinlogItemWithoutContentDecode(BinlogType type, - const std::string& binlog, - BinlogItem* binlog_item); + static bool BinlogItemWithoutContentDecode(BinlogType type, const std::string& binlog, BinlogItem* binlog_item); }; #endif diff --git a/include/pika_bit.h b/include/pika_bit.h index b8dcfc17de..873689da2a 100644 --- a/include/pika_bit.h +++ b/include/pika_bit.h @@ -16,22 +16,20 @@ */ class BitGetCmd : public Cmd { public: - BitGetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + BitGetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new BitGetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new BitGetCmd(*this); } + private: std::string key_; - int64_t bit_offset_; + int64_t bit_offset_; virtual void Clear() { key_ = ""; bit_offset_ = -1; @@ -41,23 +39,21 @@ class BitGetCmd : public Cmd { class BitSetCmd : public Cmd { public: - BitSetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + BitSetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new BitSetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new BitSetCmd(*this); } + private: std::string key_; - int64_t bit_offset_; - int64_t on_; + int64_t bit_offset_; + int64_t on_; virtual void Clear() { key_ = ""; bit_offset_ = -1; @@ -68,24 +64,22 @@ class BitSetCmd : public Cmd { class BitCountCmd : public Cmd { public: - BitCountCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + BitCountCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new BitCountCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new BitCountCmd(*this); } + private: std::string key_; - bool count_all_; - int64_t start_offset_; - int64_t end_offset_; + bool count_all_; + int64_t start_offset_; + int64_t end_offset_; virtual void Clear() { key_ = ""; count_all_ = false; @@ -97,26 +91,24 @@ class BitCountCmd : public Cmd { class BitPosCmd : public Cmd { public: - BitPosCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + BitPosCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new BitPosCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new BitPosCmd(*this); } + private: std::string key_; - bool pos_all_; - bool endoffset_set_; + bool pos_all_; + bool endoffset_set_; int64_t bit_val_; - int64_t start_offset_; - int64_t end_offset_; + int64_t start_offset_; + int64_t end_offset_; virtual void Clear() { key_ = ""; pos_all_ = false; @@ -130,14 +122,12 @@ class BitPosCmd : public Cmd { class BitOpCmd : public Cmd { public: - BitOpCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + BitOpCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new BitOpCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new BitOpCmd(*this); } + private: std::string dest_key_; std::vector src_keys_; diff --git a/include/pika_client_conn.h b/include/pika_client_conn.h index 7d2838497c..8eecf714cd 100644 --- a/include/pika_client_conn.h +++ b/include/pika_client_conn.h @@ -8,8 +8,7 @@ #include "include/pika_command.h" - -class PikaClientConn: public net::RedisConn { +class PikaClientConn : public net::RedisConn { public: using WriteCompleteCallback = std::function; @@ -29,6 +28,7 @@ class PikaClientConn: public net::RedisConn { void Init(); bool IsAuthed(const std::shared_ptr cmd_ptr); bool ChecknUpdate(const std::string& arg); + private: enum StatType { kNoAuthed = 0, @@ -38,19 +38,15 @@ class PikaClientConn: public net::RedisConn { StatType stat_; }; - PikaClientConn(int fd, std::string ip_port, - net::Thread *server_thread, - net::NetMultiplexer* mpx, - const net::HandleType& handle_type, - int max_conn_rubf_size); + PikaClientConn(int fd, std::string ip_port, net::Thread* server_thread, net::NetMultiplexer* mpx, + const net::HandleType& handle_type, int max_conn_rubf_size); virtual ~PikaClientConn() {} - virtual void ProcessRedisCmds(const std::vector& argvs, bool async, std::string* response) override; + virtual void ProcessRedisCmds(const std::vector& argvs, bool async, + std::string* response) override; void BatchExecRedisCmd(const std::vector& argvs); - int DealMessage(const net::RedisCmdArgsType& argv, std::string* response) { - return 0; - } + int DealMessage(const net::RedisCmdArgsType& argv, std::string* response) { return 0; } static void DoBackgroundTask(void* arg); static void DoExecTask(void* arg); @@ -59,16 +55,13 @@ class PikaClientConn: public net::RedisConn { void SetCurrentTable(const std::string& table_name) { current_table_ = table_name; } void SetWriteCompleteCallback(WriteCompleteCallback cb) { write_completed_cb_ = cb; } - net::ServerThread* server_thread() { - return server_thread_; - } + net::ServerThread* server_thread() { return server_thread_; } - AuthStat& auth_stat() { - return auth_stat_; - } + AuthStat& auth_stat() { return auth_stat_; } std::atomic resp_num; std::vector> resp_array; + private: net::ServerThread* const server_thread_; std::string current_table_; @@ -76,7 +69,7 @@ class PikaClientConn: public net::RedisConn { bool is_pubsub_; std::shared_ptr DoCmd(const PikaCmdArgsType& argv, const std::string& opt, - std::shared_ptr resp_ptr); + std::shared_ptr resp_ptr); void ProcessSlowlog(const PikaCmdArgsType& argv, uint64_t start_us, uint64_t do_duration); void ProcessMonitor(const PikaCmdArgsType& argv); diff --git a/include/pika_client_processor.h b/include/pika_client_processor.h index d1a1b0a987..5690bfa36b 100644 --- a/include/pika_client_processor.h +++ b/include/pika_client_processor.h @@ -6,24 +6,20 @@ #ifndef PIKA_CLIENT_PROCESSOR_H_ #define PIKA_CLIENT_PROCESSOR_H_ -#include #include +#include -#include "net/include/thread_pool.h" #include "net/include/bg_thread.h" +#include "net/include/thread_pool.h" class PikaClientProcessor { public: - PikaClientProcessor( - size_t worker_num, - size_t max_queue_size, - const std::string& name_prefix = "CliProcessor"); + PikaClientProcessor(size_t worker_num, size_t max_queue_size, const std::string& name_prefix = "CliProcessor"); ~PikaClientProcessor(); int Start(); void Stop(); void SchedulePool(net::TaskFunc func, void* arg); - void ScheduleBgThreads( - net::TaskFunc func, void* arg, const std::string& hash_str); + void ScheduleBgThreads(net::TaskFunc func, void* arg, const std::string& hash_str); size_t ThreadPoolCurQueueSize(); private: diff --git a/include/pika_cluster.h b/include/pika_cluster.h index 0541e76938..953ee0d455 100644 --- a/include/pika_cluster.h +++ b/include/pika_cluster.h @@ -8,31 +8,18 @@ #include "include/pika_command.h" - -Status ParseSlotGroup(const std::string& slot_group, - std::set* slots); +Status ParseSlotGroup(const std::string& slot_group, std::set* slots); class PkClusterInfoCmd : public Cmd { public: - enum InfoSection { - kInfoErr = 0x0, - kInfoSlot, - kInfoTable - }; - enum InfoRange { - kSingle = 0x0, - kAll, - kRange - }; + enum InfoSection { kInfoErr = 0x0, kInfoSlot, kInfoTable }; + enum InfoRange { kSingle = 0x0, kAll, kRange }; PkClusterInfoCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), - info_section_(kInfoErr), info_range_(kAll) {} + : Cmd(name, arity, flag), info_section_(kInfoErr), info_range_(kAll) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PkClusterInfoCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PkClusterInfoCmd(*this); } private: InfoSection info_section_; @@ -52,8 +39,7 @@ class PkClusterInfoCmd : public Cmd { const static std::string kTableSection; void ClusterInfoTableAll(std::string* info); void ClusterInfoTable(std::string* info); - void ClusterInfoSlotRange(const std::string& table_name, const std::set slots, - std::string* info); + void ClusterInfoSlotRange(const std::string& table_name, const std::set slots, std::string* info); void ClusterInfoSlotAll(std::string* info); Status GetSlotInfo(const std::string table_name, uint32_t partition_id, std::string* info); bool ParseInfoSlotSubCmd(); @@ -62,8 +48,7 @@ class PkClusterInfoCmd : public Cmd { class SlotParentCmd : public Cmd { public: - SlotParentCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotParentCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} protected: std::set slots_; @@ -78,14 +63,12 @@ class SlotParentCmd : public Cmd { class PkClusterAddSlotsCmd : public SlotParentCmd { public: - PkClusterAddSlotsCmd(const std::string& name, int arity, uint16_t flag) - : SlotParentCmd(name, arity, flag) {} - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PkClusterAddSlotsCmd(*this); - } + PkClusterAddSlotsCmd(const std::string& name, int arity, uint16_t flag) : SlotParentCmd(name, arity, flag) {} + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PkClusterAddSlotsCmd(*this); } virtual void Do(std::shared_ptr partition = nullptr); + private: virtual void DoInitial() override; Status AddSlotsSanityCheck(); @@ -93,14 +76,12 @@ class PkClusterAddSlotsCmd : public SlotParentCmd { class PkClusterDelSlotsCmd : public SlotParentCmd { public: - PkClusterDelSlotsCmd(const std::string& name, int32_t arity, uint16_t flag) - : SlotParentCmd(name, arity, flag) {} + PkClusterDelSlotsCmd(const std::string& name, int32_t arity, uint16_t flag) : SlotParentCmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PkClusterDelSlotsCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PkClusterDelSlotsCmd(*this); } + private: virtual void DoInitial() override; Status RemoveSlotsSanityCheck(); @@ -108,14 +89,12 @@ class PkClusterDelSlotsCmd : public SlotParentCmd { class PkClusterSlotsSlaveofCmd : public Cmd { public: - PkClusterSlotsSlaveofCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PkClusterSlotsSlaveofCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PkClusterSlotsSlaveofCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PkClusterSlotsSlaveofCmd(*this); } + private: std::string ip_; int64_t port_; @@ -133,19 +112,16 @@ class PkClusterSlotsSlaveofCmd : public Cmd { } }; - class PkClusterAddTableCmd : public Cmd { public: - PkClusterAddTableCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), slot_num_(0) {} - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - Cmd* Clone() override { - return new PkClusterAddTableCmd(*this); - } + PkClusterAddTableCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), slot_num_(0) {} + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + Cmd* Clone() override { return new PkClusterAddTableCmd(*this); } virtual void Do(std::shared_ptr partition = nullptr); + private: - int64_t slot_num_; + int64_t slot_num_; void DoInitial() override; Status AddTableSanityCheck(); void Clear() override { @@ -156,14 +132,12 @@ class PkClusterAddTableCmd : public Cmd { class PkClusterDelTableCmd : public PkClusterDelSlotsCmd { public: - PkClusterDelTableCmd(const std::string& name, int arity, uint16_t flag) - : PkClusterDelSlotsCmd(name, arity, flag) {} - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - Cmd* Clone() override { - return new PkClusterDelTableCmd(*this); - } + PkClusterDelTableCmd(const std::string& name, int arity, uint16_t flag) : PkClusterDelSlotsCmd(name, arity, flag) {} + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + Cmd* Clone() override { return new PkClusterDelTableCmd(*this); } virtual void Do(std::shared_ptr partition = nullptr); + private: void DoInitial() override; Status DelTableSanityCheck(const std::string& table_name); diff --git a/include/pika_cmd_table_manager.h b/include/pika_cmd_table_manager.h index a8e6197431..a93f9740cf 100644 --- a/include/pika_cmd_table_manager.h +++ b/include/pika_cmd_table_manager.h @@ -11,13 +11,13 @@ #include "include/pika_command.h" #include "include/pika_data_distribution.h" - class PikaCmdTableManager { public: PikaCmdTableManager(); virtual ~PikaCmdTableManager(); std::shared_ptr GetCmd(const std::string& opt); uint32_t DistributeKey(const std::string& key, uint32_t partition_num); + private: std::shared_ptr NewCommand(const std::string& opt); diff --git a/include/pika_command.h b/include/pika_command.h index a5cc0e7bc4..e4e4c0ff8a 100644 --- a/include/pika_command.h +++ b/include/pika_command.h @@ -8,8 +8,8 @@ #include -#include "net/include/redis_conn.h" #include "net/include/net_conn.h" +#include "net/include/redis_conn.h" #include "pstd/include/pstd_string.h" #include "include/pika_partition.h" @@ -17,8 +17,8 @@ class SyncMasterPartition; class SyncSlavePartition; -//Constant for command name -//Admin +// Constant for command name +// Admin const std::string kCmdNameSlaveof = "slaveof"; const std::string kCmdNameDbSlaveof = "dbslaveof"; const std::string kCmdNameAuth = "auth"; @@ -49,7 +49,7 @@ const std::string kCmdDummy = "dummy"; const std::string kCmdNameQuit = "quit"; const std::string kCmdNameHello = "hello"; -//Kv +// Kv const std::string kCmdNameSet = "set"; const std::string kCmdNameGet = "get"; const std::string kCmdNameDel = "del"; @@ -87,7 +87,7 @@ const std::string kCmdNamePKSetexAt = "pksetexat"; const std::string kCmdNamePKScanRange = "pkscanrange"; const std::string kCmdNamePKRScanRange = "pkrscanrange"; -//Hash +// Hash const std::string kCmdNameHDel = "hdel"; const std::string kCmdNameHSet = "hset"; const std::string kCmdNameHGet = "hget"; @@ -107,7 +107,7 @@ const std::string kCmdNameHScanx = "hscanx"; const std::string kCmdNamePKHScanRange = "pkhscanrange"; const std::string kCmdNamePKHRScanRange = "pkhrscanrange"; -//List +// List const std::string kCmdNameLIndex = "lindex"; const std::string kCmdNameLInsert = "linsert"; const std::string kCmdNameLLen = "llen"; @@ -123,14 +123,14 @@ const std::string kCmdNameRPopLPush = "rpoplpush"; const std::string kCmdNameRPush = "rpush"; const std::string kCmdNameRPushx = "rpushx"; -//BitMap +// BitMap const std::string kCmdNameBitSet = "setbit"; const std::string kCmdNameBitGet = "getbit"; const std::string kCmdNameBitPos = "bitpos"; const std::string kCmdNameBitOp = "bitop"; const std::string kCmdNameBitCount = "bitcount"; -//Zset +// Zset const std::string kCmdNameZAdd = "zadd"; const std::string kCmdNameZCard = "zcard"; const std::string kCmdNameZScan = "zscan"; @@ -155,7 +155,7 @@ const std::string kCmdNameZRemrangebyscore = "zremrangebyscore"; const std::string kCmdNameZPopmax = "zpopmax"; const std::string kCmdNameZPopmin = "zpopmin"; -//Set +// Set const std::string kCmdNameSAdd = "sadd"; const std::string kCmdNameSPop = "spop"; const std::string kCmdNameSCard = "scard"; @@ -172,12 +172,12 @@ const std::string kCmdNameSDiffstore = "sdiffstore"; const std::string kCmdNameSMove = "smove"; const std::string kCmdNameSRandmember = "srandmember"; -//HyperLogLog +// HyperLogLog const std::string kCmdNamePfAdd = "pfadd"; const std::string kCmdNamePfCount = "pfcount"; const std::string kCmdNamePfMerge = "pfmerge"; -//GEO +// GEO const std::string kCmdNameGeoAdd = "geoadd"; const std::string kCmdNameGeoPos = "geopos"; const std::string kCmdNameGeoDist = "geodist"; @@ -185,7 +185,7 @@ const std::string kCmdNameGeoHash = "geohash"; const std::string kCmdNameGeoRadius = "georadius"; const std::string kCmdNameGeoRadiusByMember = "georadiusbymember"; -//Pub/Sub +// Pub/Sub const std::string kCmdNamePublish = "publish"; const std::string kCmdNameSubscribe = "subscribe"; const std::string kCmdNameUnSubscribe = "unsubscribe"; @@ -193,7 +193,7 @@ const std::string kCmdNamePubSub = "pubsub"; const std::string kCmdNamePSubscribe = "psubscribe"; const std::string kCmdNamePUnSubscribe = "punsubscribe"; -//Codis Slots +// Codis Slots const std::string kCmdNameSlotsInfo = "slotsinfo"; const std::string kCmdNameSlotsHashKey = "slotshashkey"; const std::string kCmdNameSlotsMgrtTagSlotAsync = "slotsmgrttagslot-async"; @@ -208,8 +208,7 @@ const std::string kCmdNameSlotsMgrtTagSlot = "slotsmgrttagslot"; const std::string kCmdNameSlotsMgrtOne = "slotsmgrtone"; const std::string kCmdNameSlotsMgrtTagOne = "slotsmgrttagone"; - -//Cluster +// Cluster const std::string kCmdNamePkClusterInfo = "pkclusterinfo"; const std::string kCmdNamePkClusterAddSlots = "pkclusteraddslots"; const std::string kCmdNamePkClusterDelSlots = "pkclusterdelslots"; @@ -219,52 +218,51 @@ const std::string kCmdNamePkClusterDelTable = "pkclusterdeltable"; const std::string kClusterPrefix = "pkcluster"; typedef net::RedisCmdArgsType PikaCmdArgsType; -static const int RAW_ARGS_LEN = 1024 * 1024; +static const int RAW_ARGS_LEN = 1024 * 1024; enum CmdFlagsMask { - kCmdFlagsMaskRW = 1, - kCmdFlagsMaskType = 30, - kCmdFlagsMaskLocal = 32, - kCmdFlagsMaskSuspend = 64, - kCmdFlagsMaskPrior = 128, - kCmdFlagsMaskAdminRequire = 256, - kCmdFlagsMaskPartition = 1536 + kCmdFlagsMaskRW = 1, + kCmdFlagsMaskType = 30, + kCmdFlagsMaskLocal = 32, + kCmdFlagsMaskSuspend = 64, + kCmdFlagsMaskPrior = 128, + kCmdFlagsMaskAdminRequire = 256, + kCmdFlagsMaskPartition = 1536 }; enum CmdFlags { - kCmdFlagsRead = 0, //default rw - kCmdFlagsWrite = 1, - kCmdFlagsAdmin = 0, //default type - kCmdFlagsKv = 2, - kCmdFlagsHash = 4, - kCmdFlagsList = 6, - kCmdFlagsSet = 8, - kCmdFlagsZset = 10, - kCmdFlagsBit = 12, - kCmdFlagsHyperLogLog = 14, - kCmdFlagsGeo = 16, - kCmdFlagsPubSub = 18, - kCmdFlagsNoLocal = 0, //default nolocal - kCmdFlagsLocal = 32, - kCmdFlagsNoSuspend = 0, //default nosuspend - kCmdFlagsSuspend = 64, - kCmdFlagsNoPrior = 0, //default noprior - kCmdFlagsPrior = 128, - kCmdFlagsNoAdminRequire = 0, //default no need admin - kCmdFlagsAdminRequire = 256, - kCmdFlagsDoNotSpecifyPartition = 0, //default do not specify partition - kCmdFlagsSinglePartition = 512, - kCmdFlagsMultiPartition = 1024 + kCmdFlagsRead = 0, // default rw + kCmdFlagsWrite = 1, + kCmdFlagsAdmin = 0, // default type + kCmdFlagsKv = 2, + kCmdFlagsHash = 4, + kCmdFlagsList = 6, + kCmdFlagsSet = 8, + kCmdFlagsZset = 10, + kCmdFlagsBit = 12, + kCmdFlagsHyperLogLog = 14, + kCmdFlagsGeo = 16, + kCmdFlagsPubSub = 18, + kCmdFlagsNoLocal = 0, // default nolocal + kCmdFlagsLocal = 32, + kCmdFlagsNoSuspend = 0, // default nosuspend + kCmdFlagsSuspend = 64, + kCmdFlagsNoPrior = 0, // default noprior + kCmdFlagsPrior = 128, + kCmdFlagsNoAdminRequire = 0, // default no need admin + kCmdFlagsAdminRequire = 256, + kCmdFlagsDoNotSpecifyPartition = 0, // default do not specify partition + kCmdFlagsSinglePartition = 512, + kCmdFlagsMultiPartition = 1024 }; - void inline RedisAppendContent(std::string& str, const std::string& value); -void inline RedisAppendLen(std::string& str, int64_t ori, const std::string &prefix); +void inline RedisAppendLen(std::string& str, int64_t ori, const std::string& prefix); const std::string kNewLine = "\r\n"; class CmdRes { -public: + public: enum CmdRet { kNone = 0, kOk, @@ -291,112 +289,96 @@ class CmdRes { kErrOther }; - CmdRes():ret_(kNone) {} + CmdRes() : ret_(kNone) {} - bool none() const { - return ret_ == kNone && message_.empty(); - } - bool ok() const { - return ret_ == kOk || ret_ == kNone; - } + bool none() const { return ret_ == kNone && message_.empty(); } + bool ok() const { return ret_ == kOk || ret_ == kNone; } void clear() { message_.clear(); ret_ = kNone; } - std::string raw_message() const { - return message_; - } + std::string raw_message() const { return message_; } std::string message() const { std::string result; switch (ret_) { - case kNone: - return message_; - case kOk: - return "+OK\r\n"; - case kPong: - return "+PONG\r\n"; - case kSyntaxErr: - return "-ERR syntax error\r\n"; - case kInvalidInt: - return "-ERR value is not an integer or out of range\r\n"; - case kInvalidBitInt: - return "-ERR bit is not an integer or out of range\r\n"; - case kInvalidBitOffsetInt: - return "-ERR bit offset is not an integer or out of range\r\n"; - case kWrongBitOpNotNum: - return "-ERR BITOP NOT must be called with a single source key.\r\n"; - - case kInvalidBitPosArgument: - return "-ERR The bit argument must be 1 or 0.\r\n"; - case kInvalidFloat: - return "-ERR value is not a valid float\r\n"; - case kOverFlow: - return "-ERR increment or decrement would overflow\r\n"; - case kNotFound: - return "-ERR no such key\r\n"; - case kOutOfRange: - return "-ERR index out of range\r\n"; - case kInvalidPwd: - return "-ERR invalid password\r\n"; - case kNoneBgsave: - return "-ERR No BGSave Works now\r\n"; - case kPurgeExist: - return "-ERR binlog already in purging...\r\n"; - case kInvalidParameter: - return "-ERR Invalid Argument\r\n"; - case kWrongNum: - result = "-ERR wrong number of arguments for '"; - result.append(message_); - result.append("' command\r\n"); - break; - case kInvalidIndex: - result = "-ERR invalid DB index for '"; - result.append(message_); - result.append("'\r\n"); - break; - case kInvalidDbType: - result = "-ERR invalid DB for '"; - result.append(message_); - result.append("'\r\n"); - break; - case kInconsistentHashTag: - return "-ERR parameters hashtag is inconsistent\r\n"; - case kInvalidTable: - result = "-ERR invalid Table for '"; - result.append(message_); - result.append("'\r\n"); - break; - case kErrOther: - result = "-ERR "; - result.append(message_); - result.append(kNewLine); - break; - default: - break; + case kNone: + return message_; + case kOk: + return "+OK\r\n"; + case kPong: + return "+PONG\r\n"; + case kSyntaxErr: + return "-ERR syntax error\r\n"; + case kInvalidInt: + return "-ERR value is not an integer or out of range\r\n"; + case kInvalidBitInt: + return "-ERR bit is not an integer or out of range\r\n"; + case kInvalidBitOffsetInt: + return "-ERR bit offset is not an integer or out of range\r\n"; + case kWrongBitOpNotNum: + return "-ERR BITOP NOT must be called with a single source key.\r\n"; + + case kInvalidBitPosArgument: + return "-ERR The bit argument must be 1 or 0.\r\n"; + case kInvalidFloat: + return "-ERR value is not a valid float\r\n"; + case kOverFlow: + return "-ERR increment or decrement would overflow\r\n"; + case kNotFound: + return "-ERR no such key\r\n"; + case kOutOfRange: + return "-ERR index out of range\r\n"; + case kInvalidPwd: + return "-ERR invalid password\r\n"; + case kNoneBgsave: + return "-ERR No BGSave Works now\r\n"; + case kPurgeExist: + return "-ERR binlog already in purging...\r\n"; + case kInvalidParameter: + return "-ERR Invalid Argument\r\n"; + case kWrongNum: + result = "-ERR wrong number of arguments for '"; + result.append(message_); + result.append("' command\r\n"); + break; + case kInvalidIndex: + result = "-ERR invalid DB index for '"; + result.append(message_); + result.append("'\r\n"); + break; + case kInvalidDbType: + result = "-ERR invalid DB for '"; + result.append(message_); + result.append("'\r\n"); + break; + case kInconsistentHashTag: + return "-ERR parameters hashtag is inconsistent\r\n"; + case kInvalidTable: + result = "-ERR invalid Table for '"; + result.append(message_); + result.append("'\r\n"); + break; + case kErrOther: + result = "-ERR "; + result.append(message_); + result.append(kNewLine); + break; + default: + break; } return result; } // Inline functions for Create Redis protocol - void AppendStringLen(int64_t ori) { - RedisAppendLen(message_, ori, "$"); - } - void AppendArrayLen(int64_t ori) { - RedisAppendLen(message_, ori, "*"); - } - void AppendInteger(int64_t ori) { - RedisAppendLen(message_, ori, ":"); - } - void AppendContent(const std::string& value) { - RedisAppendContent(message_, value); - } + void AppendStringLen(int64_t ori) { RedisAppendLen(message_, ori, "$"); } + void AppendArrayLen(int64_t ori) { RedisAppendLen(message_, ori, "*"); } + void AppendInteger(int64_t ori) { RedisAppendLen(message_, ori, ":"); } + void AppendContent(const std::string& value) { RedisAppendContent(message_, value); } void AppendString(const std::string& value) { AppendStringLen(value.size()); AppendContent(value); } - void AppendStringRaw(const std::string& value) { - message_.append(value); - } + void AppendStringRaw(const std::string& value) { message_.append(value); } void SetRes(CmdRet _ret, const std::string content = "") { ret_ = _ret; if (!content.empty()) { @@ -404,42 +386,35 @@ class CmdRes { } } -private: + private: std::string message_; CmdRet ret_; }; -class Cmd: public std::enable_shared_from_this { +class Cmd : public std::enable_shared_from_this { public: - enum CmdStage { - kNone, - kBinlogStage, - kExecuteStage - }; + enum CmdStage { kNone, kBinlogStage, kExecuteStage }; struct HintKeys { HintKeys() {} void Push(const std::string& key, int hint) { keys.push_back(key); hints.push_back(hint); } - bool empty() const { - return keys.empty() && hints.empty(); - } + bool empty() const { return keys.empty() && hints.empty(); } std::vector keys; std::vector hints; }; struct ProcessArg { ProcessArg() {} - ProcessArg(std::shared_ptr _partition, - std::shared_ptr _sync_partition, - HintKeys _hint_keys) : partition(_partition), - sync_partition(_sync_partition), hint_keys(_hint_keys) {} + ProcessArg(std::shared_ptr _partition, std::shared_ptr _sync_partition, + HintKeys _hint_keys) + : partition(_partition), sync_partition(_sync_partition), hint_keys(_hint_keys) {} std::shared_ptr partition; std::shared_ptr sync_partition; HintKeys hint_keys; }; Cmd(const std::string& name, int arity, uint16_t flag) - : name_(name), arity_(arity), flag_(flag), stage_(kNone), do_duration_(0) {} + : name_(name), arity_(arity), flag_(flag), stage_(kNone), do_duration_(0) {} virtual ~Cmd() {} virtual std::vector current_key() const; @@ -455,16 +430,15 @@ class Cmd: public std::enable_shared_from_this { virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) = 0; virtual void Merge() = 0; - void Initial(const PikaCmdArgsType& argv, - const std::string& table_name); + void Initial(const PikaCmdArgsType& argv, const std::string& table_name); - bool is_write() const; - bool is_local() const; - bool is_suspend() const; - bool is_admin_require() const; + bool is_write() const; + bool is_local() const; + bool is_suspend() const; + bool is_admin_require() const; bool is_single_partition() const; - bool is_multi_partition() const; - bool is_classic_mode() const; + bool is_multi_partition() const; + bool is_classic_mode() const; bool HashtagIsConsistent(const std::string& lhs, const std::string& rhs) const; uint64_t GetDoDuration() const { return do_duration_; }; @@ -473,10 +447,7 @@ class Cmd: public std::enable_shared_from_this { std::string table_name() const; BinlogOffset binlog_offset() const; const PikaCmdArgsType& argv() const; - virtual std::string ToBinlog(uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, uint64_t offset); void SetConn(const std::shared_ptr conn); @@ -486,13 +457,14 @@ class Cmd: public std::enable_shared_from_this { std::shared_ptr GetResp(); void SetStage(CmdStage stage); + protected: // enable copy, used default copy - //Cmd(const Cmd&); - void ProcessCommand(std::shared_ptr partition, - std::shared_ptr sync_partition, const HintKeys& hint_key = HintKeys()); - void InternalProcessCommand(std::shared_ptr partition, - std::shared_ptr sync_partition, const HintKeys& hint_key); + // Cmd(const Cmd&); + void ProcessCommand(std::shared_ptr partition, std::shared_ptr sync_partition, + const HintKeys& hint_key = HintKeys()); + void InternalProcessCommand(std::shared_ptr partition, std::shared_ptr sync_partition, + const HintKeys& hint_key); void DoCommand(std::shared_ptr partition, const HintKeys& hint_key); void DoBinlog(std::shared_ptr partition); bool CheckArg(int num) const; @@ -513,7 +485,7 @@ class Cmd: public std::enable_shared_from_this { private: virtual void DoInitial() = 0; - virtual void Clear() {}; + virtual void Clear(){}; Cmd& operator=(const Cmd&); }; @@ -530,7 +502,7 @@ void RedisAppendContent(std::string& str, const std::string& value) { str.append(kNewLine); } -void RedisAppendLen(std::string& str, int64_t ori, const std::string &prefix) { +void RedisAppendLen(std::string& str, int64_t ori, const std::string& prefix) { char buf[32]; pstd::ll2string(buf, 32, static_cast(ori)); str.append(prefix); diff --git a/include/pika_conf.h b/include/pika_conf.h index 91d6b50f88..07f5b9d8b6 100644 --- a/include/pika_conf.h +++ b/include/pika_conf.h @@ -6,10 +6,10 @@ #ifndef PIKA_CONF_H_ #define PIKA_CONF_H_ +#include #include #include #include -#include #include "pstd/include/base_conf.h" #include "pstd/include/pstd_mutex.h" @@ -31,78 +31,249 @@ class PikaConf : public pstd::BaseConf { ~PikaConf(); // Getter - int port() { RWLock l(&rwlock_, false); return port_; } - std::string slaveof() { RWLock l(&rwlock_, false); return slaveof_;} - int slave_priority() { RWLock l(&rwlock_, false); return slave_priority_;} - bool write_binlog() { RWLock l(&rwlock_, false); return write_binlog_;} - int thread_num() { RWLock l(&rwlock_, false); return thread_num_; } - int thread_pool_size() { RWLock l(&rwlock_, false); return thread_pool_size_; } - int sync_thread_num() { RWLock l(&rwlock_, false); return sync_thread_num_; } - std::string log_path() { RWLock l(&rwlock_, false); return log_path_; } - std::string db_path() { RWLock l(&rwlock_, false); return db_path_; } - std::string db_sync_path() { RWLock l(&rwlock_, false); return db_sync_path_; } - int db_sync_speed() { RWLock l(&rwlock_, false); return db_sync_speed_; } - std::string compact_cron() { RWLock l(&rwlock_, false); return compact_cron_; } - std::string compact_interval() { RWLock l(&rwlock_, false); return compact_interval_; } - int64_t write_buffer_size() { RWLock l(&rwlock_, false); return write_buffer_size_; } - int64_t arena_block_size() { RWLock l(&rwlock_, false); return arena_block_size_; } - int64_t max_write_buffer_size() { RWLock l(&rwlock_, false); return max_write_buffer_size_; } - int max_write_buffer_number() { RWLock l(&rwlock_, false); return max_write_buffer_num_; } - int64_t max_client_response_size() { RWLock L(&rwlock_, false); return max_client_response_size_;} - int timeout() { RWLock l(&rwlock_, false); return timeout_; } - std::string server_id() { RWLock l(&rwlock_, false); return server_id_; } - std::string requirepass() { RWLock l(&rwlock_, false); return requirepass_; } - std::string masterauth() { RWLock l(&rwlock_, false); return masterauth_; } - std::string bgsave_path() { RWLock l(&rwlock_, false); return bgsave_path_; } - int expire_dump_days() { RWLock l(&rwlock_, false); return expire_dump_days_; } - std::string bgsave_prefix() { RWLock l(&rwlock_, false); return bgsave_prefix_; } - std::string userpass() { RWLock l(&rwlock_, false); return userpass_; } - const std::string suser_blacklist() { RWLock l(&rwlock_, false); return pstd::StringConcat(user_blacklist_, COMMA); } - const std::vector& vuser_blacklist() { RWLock l(&rwlock_, false); return user_blacklist_;} - bool classic_mode() { return classic_mode_.load();} - int databases() { RWLock l(&rwlock_, false); return databases_;} - int default_slot_num() { RWLock l(&rwlock_, false); return default_slot_num_;} - const std::vector& table_structs() { RWLock l(&rwlock_, false); return table_structs_; } - std::string default_table() { RWLock l(&rwlock_, false); return default_table_;} - std::string compression() { RWLock l(&rwlock_, false); return compression_; } - int target_file_size_base() { RWLock l(&rwlock_, false); return target_file_size_base_; } - int max_cache_statistic_keys() { RWLock l(&rwlock_, false); return max_cache_statistic_keys_;} - int small_compaction_threshold() { RWLock l(&rwlock_, false); return small_compaction_threshold_;} - int max_background_flushes() { RWLock l(&rwlock_, false); return max_background_flushes_; } - int max_background_compactions() { RWLock l(&rwlock_, false); return max_background_compactions_; } - int max_cache_files() { RWLock l(&rwlock_, false); return max_cache_files_; } - int max_bytes_for_level_multiplier() { RWLock l(&rwlock_, false); return max_bytes_for_level_multiplier_; } - int64_t block_size() { RWLock l(&rwlock_, false); return block_size_; } - int64_t block_cache() { RWLock l(&rwlock_, false); return block_cache_; } - int64_t num_shard_bits() { RWLock l(&rwlock_, false); return num_shard_bits_; } - bool share_block_cache() { RWLock l(&rwlock_, false); return share_block_cache_; } - bool cache_index_and_filter_blocks() { RWLock l(&rwlock_, false); return cache_index_and_filter_blocks_; } - bool pin_l0_filter_and_index_blocks_in_cache() { RWLock l(&rwlock_, false); return pin_l0_filter_and_index_blocks_in_cache_; } - bool optimize_filters_for_hits() { RWLock l(&rwlock_, false); return optimize_filters_for_hits_; } - bool level_compaction_dynamic_level_bytes() { RWLock l(&rwlock_, false); return level_compaction_dynamic_level_bytes_; } - int expire_logs_nums() { RWLock l(&rwlock_, false); return expire_logs_nums_; } - int expire_logs_days() { RWLock l(&rwlock_, false); return expire_logs_days_; } - std::string conf_path() { RWLock l(&rwlock_, false); return conf_path_; } - bool slave_read_only() { RWLock l(&rwlock_, false); return slave_read_only_; } - int maxclients() { RWLock l(&rwlock_, false); return maxclients_; } - int root_connection_num() { RWLock l(&rwlock_, false); return root_connection_num_; } - bool slowlog_write_errorlog() { return slowlog_write_errorlog_.load();} - int slowlog_slower_than() { return slowlog_log_slower_than_.load(); } - int slowlog_max_len() { RWLock L(&rwlock_, false); return slowlog_max_len_; } - std::string network_interface() { RWLock l(&rwlock_, false); return network_interface_; } - int sync_window_size() { return sync_window_size_.load(); } - int max_conn_rbuf_size() { return max_conn_rbuf_size_.load(); } - int consensus_level() { return consensus_level_.load(); } - int replication_num() { return replication_num_.load(); } - int64_t rate_limiter_bandwidth() { RWLock l(&rwlock_, false); return rate_limiter_bandwidth_; } + int port() { + RWLock l(&rwlock_, false); + return port_; + } + std::string slaveof() { + RWLock l(&rwlock_, false); + return slaveof_; + } + int slave_priority() { + RWLock l(&rwlock_, false); + return slave_priority_; + } + bool write_binlog() { + RWLock l(&rwlock_, false); + return write_binlog_; + } + int thread_num() { + RWLock l(&rwlock_, false); + return thread_num_; + } + int thread_pool_size() { + RWLock l(&rwlock_, false); + return thread_pool_size_; + } + int sync_thread_num() { + RWLock l(&rwlock_, false); + return sync_thread_num_; + } + std::string log_path() { + RWLock l(&rwlock_, false); + return log_path_; + } + std::string db_path() { + RWLock l(&rwlock_, false); + return db_path_; + } + std::string db_sync_path() { + RWLock l(&rwlock_, false); + return db_sync_path_; + } + int db_sync_speed() { + RWLock l(&rwlock_, false); + return db_sync_speed_; + } + std::string compact_cron() { + RWLock l(&rwlock_, false); + return compact_cron_; + } + std::string compact_interval() { + RWLock l(&rwlock_, false); + return compact_interval_; + } + int64_t write_buffer_size() { + RWLock l(&rwlock_, false); + return write_buffer_size_; + } + int64_t arena_block_size() { + RWLock l(&rwlock_, false); + return arena_block_size_; + } + int64_t max_write_buffer_size() { + RWLock l(&rwlock_, false); + return max_write_buffer_size_; + } + int max_write_buffer_number() { + RWLock l(&rwlock_, false); + return max_write_buffer_num_; + } + int64_t max_client_response_size() { + RWLock L(&rwlock_, false); + return max_client_response_size_; + } + int timeout() { + RWLock l(&rwlock_, false); + return timeout_; + } + std::string server_id() { + RWLock l(&rwlock_, false); + return server_id_; + } + std::string requirepass() { + RWLock l(&rwlock_, false); + return requirepass_; + } + std::string masterauth() { + RWLock l(&rwlock_, false); + return masterauth_; + } + std::string bgsave_path() { + RWLock l(&rwlock_, false); + return bgsave_path_; + } + int expire_dump_days() { + RWLock l(&rwlock_, false); + return expire_dump_days_; + } + std::string bgsave_prefix() { + RWLock l(&rwlock_, false); + return bgsave_prefix_; + } + std::string userpass() { + RWLock l(&rwlock_, false); + return userpass_; + } + const std::string suser_blacklist() { + RWLock l(&rwlock_, false); + return pstd::StringConcat(user_blacklist_, COMMA); + } + const std::vector& vuser_blacklist() { + RWLock l(&rwlock_, false); + return user_blacklist_; + } + bool classic_mode() { return classic_mode_.load(); } + int databases() { + RWLock l(&rwlock_, false); + return databases_; + } + int default_slot_num() { + RWLock l(&rwlock_, false); + return default_slot_num_; + } + const std::vector& table_structs() { + RWLock l(&rwlock_, false); + return table_structs_; + } + std::string default_table() { + RWLock l(&rwlock_, false); + return default_table_; + } + std::string compression() { + RWLock l(&rwlock_, false); + return compression_; + } + int target_file_size_base() { + RWLock l(&rwlock_, false); + return target_file_size_base_; + } + int max_cache_statistic_keys() { + RWLock l(&rwlock_, false); + return max_cache_statistic_keys_; + } + int small_compaction_threshold() { + RWLock l(&rwlock_, false); + return small_compaction_threshold_; + } + int max_background_flushes() { + RWLock l(&rwlock_, false); + return max_background_flushes_; + } + int max_background_compactions() { + RWLock l(&rwlock_, false); + return max_background_compactions_; + } + int max_cache_files() { + RWLock l(&rwlock_, false); + return max_cache_files_; + } + int max_bytes_for_level_multiplier() { + RWLock l(&rwlock_, false); + return max_bytes_for_level_multiplier_; + } + int64_t block_size() { + RWLock l(&rwlock_, false); + return block_size_; + } + int64_t block_cache() { + RWLock l(&rwlock_, false); + return block_cache_; + } + int64_t num_shard_bits() { + RWLock l(&rwlock_, false); + return num_shard_bits_; + } + bool share_block_cache() { + RWLock l(&rwlock_, false); + return share_block_cache_; + } + bool cache_index_and_filter_blocks() { + RWLock l(&rwlock_, false); + return cache_index_and_filter_blocks_; + } + bool pin_l0_filter_and_index_blocks_in_cache() { + RWLock l(&rwlock_, false); + return pin_l0_filter_and_index_blocks_in_cache_; + } + bool optimize_filters_for_hits() { + RWLock l(&rwlock_, false); + return optimize_filters_for_hits_; + } + bool level_compaction_dynamic_level_bytes() { + RWLock l(&rwlock_, false); + return level_compaction_dynamic_level_bytes_; + } + int expire_logs_nums() { + RWLock l(&rwlock_, false); + return expire_logs_nums_; + } + int expire_logs_days() { + RWLock l(&rwlock_, false); + return expire_logs_days_; + } + std::string conf_path() { + RWLock l(&rwlock_, false); + return conf_path_; + } + bool slave_read_only() { + RWLock l(&rwlock_, false); + return slave_read_only_; + } + int maxclients() { + RWLock l(&rwlock_, false); + return maxclients_; + } + int root_connection_num() { + RWLock l(&rwlock_, false); + return root_connection_num_; + } + bool slowlog_write_errorlog() { return slowlog_write_errorlog_.load(); } + int slowlog_slower_than() { return slowlog_log_slower_than_.load(); } + int slowlog_max_len() { + RWLock L(&rwlock_, false); + return slowlog_max_len_; + } + std::string network_interface() { + RWLock l(&rwlock_, false); + return network_interface_; + } + int sync_window_size() { return sync_window_size_.load(); } + int max_conn_rbuf_size() { return max_conn_rbuf_size_.load(); } + int consensus_level() { return consensus_level_.load(); } + int replication_num() { return replication_num_.load(); } + int64_t rate_limiter_bandwidth() { + RWLock l(&rwlock_, false); + return rate_limiter_bandwidth_; + } // Immutable config items, we don't use lock. - bool daemonize() { return daemonize_; } - std::string pidfile() { return pidfile_; } - int binlog_file_size() { return binlog_file_size_; } - PikaMeta * local_meta() { return local_meta_; } + bool daemonize() { return daemonize_; } + std::string pidfile() { return pidfile_; } + int binlog_file_size() { return binlog_file_size_; } + PikaMeta* local_meta() { return local_meta_; } std::vector compression_per_level(); - static rocksdb::CompressionType GetCompression(const std::string &value); + static rocksdb::CompressionType GetCompression(const std::string& value); // Setter void SetPort(const int value) { @@ -152,7 +323,7 @@ class PikaConf : public pstd::BaseConf { TryPushDiffCommands("max-client-response-size", std::to_string(value)); max_client_response_size_ = value; } - void SetBgsavePath(const std::string &value) { + void SetBgsavePath(const std::string& value) { RWLock l(&rwlock_, true); bgsave_path_ = value; if (value[value.length() - 1] != '/') { @@ -164,27 +335,27 @@ class PikaConf : public pstd::BaseConf { TryPushDiffCommands("dump-expire", std::to_string(value)); expire_dump_days_ = value; } - void SetBgsavePrefix(const std::string &value) { + void SetBgsavePrefix(const std::string& value) { RWLock l(&rwlock_, true); TryPushDiffCommands("dump-prefix", value); bgsave_prefix_ = value; } - void SetRequirePass(const std::string &value) { + void SetRequirePass(const std::string& value) { RWLock l(&rwlock_, true); TryPushDiffCommands("requirepass", value); requirepass_ = value; } - void SetMasterAuth(const std::string &value) { + void SetMasterAuth(const std::string& value) { RWLock l(&rwlock_, true); TryPushDiffCommands("masterauth", value); masterauth_ = value; } - void SetUserPass(const std::string &value) { + void SetUserPass(const std::string& value) { RWLock l(&rwlock_, true); TryPushDiffCommands("userpass", value); userpass_ = value; } - void SetUserBlackList(const std::string &value) { + void SetUserBlackList(const std::string& value) { RWLock l(&rwlock_, true); TryPushDiffCommands("userblacklist", value); pstd::StringSplit(value, COMMA, user_blacklist_); @@ -232,17 +403,17 @@ class PikaConf : public pstd::BaseConf { TryPushDiffCommands("db-sync-speed", std::to_string(value)); db_sync_speed_ = value; } - void SetCompactCron(const std::string &value) { + void SetCompactCron(const std::string& value) { RWLock l(&rwlock_, true); TryPushDiffCommands("compact-cron", value); compact_cron_ = value; } - void SetCompactInterval(const std::string &value) { + void SetCompactInterval(const std::string& value) { RWLock l(&rwlock_, true); TryPushDiffCommands("compact-interval", value); compact_interval_ = value; } - void SetSyncWindowSize(const int &value) { + void SetSyncWindowSize(const int& value) { TryPushDiffCommands("sync-window-size", std::to_string(value)); sync_window_size_.store(value); } @@ -276,24 +447,20 @@ class PikaConf : public pstd::BaseConf { arena_block_size_ = value; } - Status TablePartitionsSanityCheck(const std::string& table_name, - const std::set& partition_ids, + Status TablePartitionsSanityCheck(const std::string& table_name, const std::set& partition_ids, bool is_add); - Status AddTablePartitions(const std::string& table_name, - const std::set& partition_ids); - Status RemoveTablePartitions(const std::string& table_name, - const std::set& partition_ids); - Status AddTable(const std::string &table_name, uint32_t slot_num); - Status AddTableSanityCheck(const std::string &table_name); - Status DelTable(const std::string &table_name); - Status DelTableSanityCheck(const std::string &table_name); + Status AddTablePartitions(const std::string& table_name, const std::set& partition_ids); + Status RemoveTablePartitions(const std::string& table_name, const std::set& partition_ids); + Status AddTable(const std::string& table_name, uint32_t slot_num); + Status AddTableSanityCheck(const std::string& table_name); + Status DelTable(const std::string& table_name); + Status DelTableSanityCheck(const std::string& table_name); int Load(); int ConfigRewrite(); private: - Status InternalGetTargetTable(const std::string& table_name, - uint32_t* const target); + Status InternalGetTargetTable(const std::string& table_name, uint32_t* const target); int port_; std::string slaveof_; @@ -354,7 +521,7 @@ class PikaConf : public pstd::BaseConf { bool pin_l0_filter_and_index_blocks_in_cache_; bool optimize_filters_for_hits_; bool level_compaction_dynamic_level_bytes_; - int64_t rate_limiter_bandwidth_ = 200 * 1024 * 1024; // 200M + int64_t rate_limiter_bandwidth_ = 200 * 1024 * 1024; // 200M std::atomic sync_window_size_; std::atomic max_conn_rbuf_size_; std::atomic consensus_level_; diff --git a/include/pika_consensus.h b/include/pika_consensus.h index 11ef2fd79d..e7874712d4 100644 --- a/include/pika_consensus.h +++ b/include/pika_consensus.h @@ -5,11 +5,11 @@ #ifndef PIKA_CONSENSUS_H_ #define PIKA_CONSENSUS_H_ +#include "include/pika_binlog_transverter.h" #include "include/pika_client_conn.h" #include "include/pika_define.h" #include "include/pika_slave_node.h" #include "include/pika_stable_log.h" -#include "include/pika_binlog_transverter.h" #include "pstd/include/env.h" class Context { @@ -38,7 +38,7 @@ class Context { private: std::string path_; - pstd::RWFile *save_; + pstd::RWFile* save_; // No copying allowed; Context(const Context&); void operator=(const Context&); @@ -51,16 +51,15 @@ class SyncProgress { std::shared_ptr GetSlaveNode(const std::string& ip, int port); std::unordered_map> GetAllSlaveNodes(); std::unordered_map GetAllMatchIndex(); - Status AddSlaveNode(const std::string& ip, int port, - const std::string& table_name, uint32_t partition_id, int session_id); + Status AddSlaveNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, + int session_id); Status RemoveSlaveNode(const std::string& ip, int port); - Status Update(const std::string& ip, int port, const LogOffset& start, - const LogOffset& end, LogOffset* committed_index); + Status Update(const std::string& ip, int port, const LogOffset& start, const LogOffset& end, + LogOffset* committed_index); int SlaveSize(); private: - LogOffset InternalCalCommittedIndex( - std::unordered_map match_index); + LogOffset InternalCalCommittedIndex(std::unordered_map match_index); pthread_rwlock_t rwlock_; std::unordered_map> slaves_; @@ -70,13 +69,9 @@ class SyncProgress { class MemLog { public: struct LogItem { - LogItem( - LogOffset _offset, - std::shared_ptr _cmd_ptr, - std::shared_ptr _conn_ptr, - std::shared_ptr _resp_ptr) - : offset(_offset), cmd_ptr(_cmd_ptr), conn_ptr(_conn_ptr), resp_ptr(_resp_ptr) { - } + LogItem(LogOffset _offset, std::shared_ptr _cmd_ptr, std::shared_ptr _conn_ptr, + std::shared_ptr _resp_ptr) + : offset(_offset), cmd_ptr(_cmd_ptr), conn_ptr(_conn_ptr), resp_ptr(_resp_ptr) {} LogOffset offset; std::shared_ptr cmd_ptr; std::shared_ptr conn_ptr; @@ -94,7 +89,7 @@ class MemLog { Status GetRangeLogs(int start, int end, std::vector* logs); Status TruncateTo(const LogOffset& offset); - void Reset(const LogOffset& offset); + void Reset(const LogOffset& offset); LogOffset last_offset() { pstd::MutexLock l_logs(&logs_mu_); @@ -123,12 +118,9 @@ class ConsensusCoordinator { // invoked by dbsync process Status Reset(const LogOffset& offset); - Status ProposeLog( - std::shared_ptr cmd_ptr, - std::shared_ptr conn_ptr, - std::shared_ptr resp_ptr); - Status UpdateSlave(const std::string& ip, int port, - const LogOffset& start, const LogOffset& end); + Status ProposeLog(std::shared_ptr cmd_ptr, std::shared_ptr conn_ptr, + std::shared_ptr resp_ptr); + Status UpdateSlave(const std::string& ip, int port, const LogOffset& start, const LogOffset& end); Status AddSlaveNode(const std::string& ip, int port, int session_id); Status RemoveSlaveNode(const std::string& ip, int port); void UpdateTerm(uint32_t term); @@ -136,24 +128,16 @@ class ConsensusCoordinator { Status CheckEnoughFollower(); // invoked by follower - Status ProcessLeaderLog(std::shared_ptr cmd_ptr, - const BinlogItem& attribute); + Status ProcessLeaderLog(std::shared_ptr cmd_ptr, const BinlogItem& attribute); Status ProcessLocalUpdate(const LogOffset& leader_commit); // Negotiate - Status LeaderNegotiate( - const LogOffset& f_last_offset, bool* reject, std::vector* hints); + Status LeaderNegotiate(const LogOffset& f_last_offset, bool* reject, std::vector* hints); Status FollowerNegotiate(const std::vector& hints, LogOffset* reply_offset); - SyncProgress& SyncPros() { - return sync_pros_; - } - std::shared_ptr StableLogger() { - return stable_logger_; - } - std::shared_ptr MemLogger() { - return mem_logger_; - } + SyncProgress& SyncPros() { return sync_pros_; } + std::shared_ptr StableLogger() { return stable_logger_; } + std::shared_ptr MemLogger() { return mem_logger_; } LogOffset committed_index() { pstd::MutexLock l(&index_mu_); @@ -165,14 +149,11 @@ class ConsensusCoordinator { return context_->applied_index_; } - std::shared_ptr context() { - return context_; - } + std::shared_ptr context() { return context_; } // redis parser cb struct CmdPtrArg { - CmdPtrArg(std::shared_ptr ptr) : cmd_ptr(ptr) { - } + CmdPtrArg(std::shared_ptr ptr) : cmd_ptr(ptr) {} std::shared_ptr cmd_ptr; }; static int InitCmd(net::RedisParser* parser, const net::RedisCmdArgsType& argv); @@ -183,18 +164,19 @@ class ConsensusCoordinator { pstd::MutexLock l(&index_mu_); tmp_stream << " Committed_index: " << committed_index_.ToString() << "\r\n"; } - tmp_stream << " Context: " << "\r\n" << context_->ToString(); + tmp_stream << " Context: " + << "\r\n" + << context_->ToString(); { pstd::RWLock l(&term_rwlock_, false); tmp_stream << " Term: " << term_ << "\r\n"; } - tmp_stream << " Mem_logger size: " << mem_logger_->Size() << - " last offset " << mem_logger_->last_offset().ToString() << "\r\n"; + tmp_stream << " Mem_logger size: " << mem_logger_->Size() << " last offset " + << mem_logger_->last_offset().ToString() << "\r\n"; tmp_stream << " Stable_logger first offset " << stable_logger_->first_offset().ToString() << "\r\n"; LogOffset log_status; - stable_logger_->Logger()->GetProducerStatus( - &(log_status.b_offset.filenum), &(log_status.b_offset.offset), - &(log_status.l_offset.term), &(log_status.l_offset.index)); + stable_logger_->Logger()->GetProducerStatus(&(log_status.b_offset.filenum), &(log_status.b_offset.offset), + &(log_status.l_offset.term), &(log_status.l_offset.index)); tmp_stream << " Physical Binlog Status: " << log_status.ToString() << "\r\n"; return tmp_stream.str(); } @@ -205,30 +187,21 @@ class ConsensusCoordinator { bool MatchConsensusLevel(); Status TruncateTo(const LogOffset& offset); - Status InternalAppendLog(const BinlogItem& item, - std::shared_ptr cmd_ptr, - std::shared_ptr conn_ptr, - std::shared_ptr resp_ptr); - Status InternalAppendBinlog(const BinlogItem& item, - std::shared_ptr cmd_ptr, - LogOffset* log_offset); + Status InternalAppendLog(const BinlogItem& item, std::shared_ptr cmd_ptr, + std::shared_ptr conn_ptr, std::shared_ptr resp_ptr); + Status InternalAppendBinlog(const BinlogItem& item, std::shared_ptr cmd_ptr, LogOffset* log_offset); void InternalApply(const MemLog::LogItem& log); void InternalApplyFollower(const MemLog::LogItem& log); - bool InternalUpdateCommittedIndex(const LogOffset& slaves_committed_index, - LogOffset* updated_committed_index); + bool InternalUpdateCommittedIndex(const LogOffset& slaves_committed_index, LogOffset* updated_committed_index); Status GetBinlogOffset(const BinlogOffset& start_offset, LogOffset* log_offset); - Status GetBinlogOffset( - const BinlogOffset& start_offset, - const BinlogOffset& end_offset, std::vector* log_offset); - Status FindBinlogFileNum( - const std::map binlogs, - uint64_t target_index, uint32_t start_filenum, - uint32_t* founded_filenum); - Status FindLogicOffsetBySearchingBinlog( - const BinlogOffset& hint_offset, uint64_t target_index, LogOffset* found_offset); - Status FindLogicOffset( - const BinlogOffset& start_offset, uint64_t target_index, LogOffset* found_offset); + Status GetBinlogOffset(const BinlogOffset& start_offset, const BinlogOffset& end_offset, + std::vector* log_offset); + Status FindBinlogFileNum(const std::map binlogs, uint64_t target_index, uint32_t start_filenum, + uint32_t* founded_filenum); + Status FindLogicOffsetBySearchingBinlog(const BinlogOffset& hint_offset, uint64_t target_index, + LogOffset* found_offset); + Status FindLogicOffset(const BinlogOffset& start_offset, uint64_t target_index, LogOffset* found_offset); Status GetLogsBefore(const BinlogOffset& start_offset, std::vector* hints); // keep members in this class works in order diff --git a/include/pika_data_distribution.h b/include/pika_data_distribution.h index c99403565f..a06416d3ab 100644 --- a/include/pika_data_distribution.h +++ b/include/pika_data_distribution.h @@ -13,7 +13,7 @@ const uint32_t IEEE_POLY = 0xedb88320; class PikaDataDistribution { public: - virtual ~PikaDataDistribution() = default; + virtual ~PikaDataDistribution() = default; // Initialization virtual void Init() = 0; // key map to partition id @@ -31,6 +31,7 @@ class Crc32 : public PikaDataDistribution { public: virtual void Init(); virtual uint32_t Distribute(const std::string& str, uint32_t partition_num); + private: void Crc32TableInit(uint32_t poly); uint32_t Crc32Update(uint32_t crc, const char* buf, int len); diff --git a/include/pika_define.h b/include/pika_define.h index ea3976e8ff..960935928d 100644 --- a/include/pika_define.h +++ b/include/pika_define.h @@ -6,25 +6,25 @@ #ifndef PIKA_DEFINE_H_ #define PIKA_DEFINE_H_ -#include #include +#include #include "net/include/redis_cli.h" -#define PIKA_SYNC_BUFFER_SIZE 1000 -#define PIKA_MAX_WORKER_THREAD_NUM 24 -#define PIKA_REPL_SERVER_TP_SIZE 3 -#define PIKA_META_SYNC_MAX_WAIT_TIME 10 -#define PIKA_SCAN_STEP_LENGTH 1000 -#define PIKA_MAX_CONN_RBUF (1 << 28) // 256MB -#define PIKA_MAX_CONN_RBUF_LB (1 << 26) // 64MB -#define PIKA_MAX_CONN_RBUF_HB (1 << 29) // 512MB -#define PIKA_SERVER_ID_MAX 65535 +#define PIKA_SYNC_BUFFER_SIZE 1000 +#define PIKA_MAX_WORKER_THREAD_NUM 24 +#define PIKA_REPL_SERVER_TP_SIZE 3 +#define PIKA_META_SYNC_MAX_WAIT_TIME 10 +#define PIKA_SCAN_STEP_LENGTH 1000 +#define PIKA_MAX_CONN_RBUF (1 << 28) // 256MB +#define PIKA_MAX_CONN_RBUF_LB (1 << 26) // 64MB +#define PIKA_MAX_CONN_RBUF_HB (1 << 29) // 512MB +#define PIKA_SERVER_ID_MAX 65535 class PikaServer; /* Port shift */ -const int kPortShiftRSync = 1000; +const int kPortShiftRSync = 1000; const int kPortShiftReplServer = 2000; const std::string kPikaPidFile = "pika.pid"; @@ -32,15 +32,12 @@ const std::string kPikaSecretFile = "rsync.secret"; const std::string kDefaultRsyncAuth = "default"; struct TableStruct { - TableStruct(const std::string& tn, - const uint32_t pn, - const std::set& pi) + TableStruct(const std::string& tn, const uint32_t pn, const std::set& pi) : table_name(tn), partition_num(pn), partition_ids(pi) {} - bool operator == (const TableStruct& table_struct) const { - return table_name == table_struct.table_name - && partition_num == table_struct.partition_num - && partition_ids == table_struct.partition_ids; + bool operator==(const TableStruct& table_struct) const { + return table_name == table_struct.table_name && partition_num == table_struct.partition_num && + partition_ids == table_struct.partition_ids; } std::string table_name; uint32_t partition_num; @@ -52,11 +49,11 @@ struct WorkerCronTask { std::string ip_port; }; typedef WorkerCronTask MonitorCronTask; -//task define +// task define #define TASK_KILL 0 #define TASK_KILLALL 1 -//slave item +// slave item struct SlaveItem { std::string ip_port; std::string ip; @@ -68,28 +65,20 @@ struct SlaveItem { }; enum ReplState { - kNoConnect = 0, - kTryConnect = 1, - kTryDBSync = 2, - kWaitDBSync = 3, - kWaitReply = 4, - kConnected = 5, - kError = 6, -// set to kDBNoConnect if execute cmd 'dbslaveof db no one' + kNoConnect = 0, + kTryConnect = 1, + kTryDBSync = 2, + kWaitDBSync = 3, + kWaitReply = 4, + kConnected = 5, + kError = 6, + // set to kDBNoConnect if execute cmd 'dbslaveof db no one' kDBNoConnect = 7 }; // debug only -const std::string ReplStateMsg[] = { - "kNoConnect", - "kTryConnect", - "kTryDBSync", - "kWaitDBSync", - "kWaitReply", - "kConnected", - "kError", - "kDBNoConnect" -}; +const std::string ReplStateMsg[] = {"kNoConnect", "kTryConnect", "kTryDBSync", "kWaitDBSync", + "kWaitReply", "kConnected", "kError", "kDBNoConnect"}; enum SlotState { INFREE = 0, @@ -99,41 +88,28 @@ enum SlotState { struct LogicOffset { uint32_t term; uint64_t index; - LogicOffset() - : term(0), index(0) {} - LogicOffset(uint32_t _term, uint64_t _index) - : term(_term), index(_index) {} + LogicOffset() : term(0), index(0) {} + LogicOffset(uint32_t _term, uint64_t _index) : term(_term), index(_index) {} LogicOffset(const LogicOffset& other) { term = other.term; index = other.index; } - bool operator==(const LogicOffset& other) const { - return term == other.term && index == other.index; - } - bool operator!=(const LogicOffset& other) const { - return term != other.term || index != other.index; - } - + bool operator==(const LogicOffset& other) const { return term == other.term && index == other.index; } + bool operator!=(const LogicOffset& other) const { return term != other.term || index != other.index; } - std::string ToString() const { - return "term: " + std::to_string(term) + " index: " + std::to_string(index); - } + std::string ToString() const { return "term: " + std::to_string(term) + " index: " + std::to_string(index); } }; struct BinlogOffset { uint32_t filenum; uint64_t offset; - BinlogOffset() - : filenum(0), offset(0) {} - BinlogOffset(uint32_t num, uint64_t off) - : filenum(num), offset(off) {} + BinlogOffset() : filenum(0), offset(0) {} + BinlogOffset(uint32_t num, uint64_t off) : filenum(num), offset(off) {} BinlogOffset(const BinlogOffset& other) { filenum = other.filenum; offset = other.offset; } - std::string ToString() const { - return "filenum: " + std::to_string(filenum) + " offset: " + std::to_string(offset); - } + std::string ToString() const { return "filenum: " + std::to_string(filenum) + " offset: " + std::to_string(offset); } bool operator==(const BinlogOffset& other) const { if (filenum == other.filenum && offset == other.offset) { return true; @@ -148,29 +124,25 @@ struct BinlogOffset { } bool operator>(const BinlogOffset& other) const { - if (filenum > other.filenum - || (filenum == other.filenum && offset > other.offset)) { + if (filenum > other.filenum || (filenum == other.filenum && offset > other.offset)) { return true; } return false; } bool operator<(const BinlogOffset& other) const { - if (filenum < other.filenum - || (filenum == other.filenum && offset < other.offset)) { + if (filenum < other.filenum || (filenum == other.filenum && offset < other.offset)) { return true; } return false; } bool operator<=(const BinlogOffset& other) const { - if (filenum < other.filenum - || (filenum == other.filenum && offset <= other.offset)) { + if (filenum < other.filenum || (filenum == other.filenum && offset <= other.offset)) { return true; } return false; } bool operator>=(const BinlogOffset& other) const { - if (filenum > other.filenum - || (filenum == other.filenum && offset >= other.offset)) { + if (filenum > other.filenum || (filenum == other.filenum && offset >= other.offset)) { return true; } return false; @@ -182,81 +154,53 @@ struct LogOffset { b_offset = _log_offset.b_offset; l_offset = _log_offset.l_offset; } - LogOffset() : b_offset(), l_offset() { - } - LogOffset(BinlogOffset _b_offset, LogicOffset _l_offset) - : b_offset(_b_offset), l_offset(_l_offset) { - } - bool operator<(const LogOffset& other) const { - return b_offset < other.b_offset; - } - bool operator==(const LogOffset& other) const { - return b_offset == other.b_offset; - } - bool operator<=(const LogOffset& other) const { - return b_offset <= other.b_offset; - } - bool operator>=(const LogOffset& other) const { - return b_offset >= other.b_offset; - } - bool operator>(const LogOffset& other) const { - return b_offset > other.b_offset; - } - std::string ToString() const { - return b_offset.ToString() + " " + l_offset.ToString(); - } + LogOffset() : b_offset(), l_offset() {} + LogOffset(BinlogOffset _b_offset, LogicOffset _l_offset) : b_offset(_b_offset), l_offset(_l_offset) {} + bool operator<(const LogOffset& other) const { return b_offset < other.b_offset; } + bool operator==(const LogOffset& other) const { return b_offset == other.b_offset; } + bool operator<=(const LogOffset& other) const { return b_offset <= other.b_offset; } + bool operator>=(const LogOffset& other) const { return b_offset >= other.b_offset; } + bool operator>(const LogOffset& other) const { return b_offset > other.b_offset; } + std::string ToString() const { return b_offset.ToString() + " " + l_offset.ToString(); } BinlogOffset b_offset; - LogicOffset l_offset; + LogicOffset l_offset; }; -//dbsync arg +// dbsync arg struct DBSyncArg { PikaServer* p; std::string ip; int port; std::string table_name; uint32_t partition_id; - DBSyncArg(PikaServer* const _p, - const std::string& _ip, - int _port, - const std::string& _table_name, + DBSyncArg(PikaServer* const _p, const std::string& _ip, int _port, const std::string& _table_name, uint32_t _partition_id) - : p(_p), ip(_ip), port(_port), - table_name(_table_name), partition_id(_partition_id) {} + : p(_p), ip(_ip), port(_port), table_name(_table_name), partition_id(_partition_id) {} }; // rm define enum SlaveState { - kSlaveNotSync = 0, - kSlaveDbSync = 1, + kSlaveNotSync = 0, + kSlaveDbSync = 1, kSlaveBinlogSync = 2, }; // debug only -const std::string SlaveStateMsg[] = { - "SlaveNotSync", - "SlaveDbSync", - "SlaveBinlogSync" -}; +const std::string SlaveStateMsg[] = {"SlaveNotSync", "SlaveDbSync", "SlaveBinlogSync"}; enum BinlogSyncState { - kNotSync = 0, - kReadFromCache = 1, - kReadFromFile = 2, + kNotSync = 0, + kReadFromCache = 1, + kReadFromFile = 2, }; // debug only -const std::string BinlogSyncStateMsg[] = { - "NotSync", - "ReadFromCache", - "ReadFromFile" -}; +const std::string BinlogSyncStateMsg[] = {"NotSync", "ReadFromCache", "ReadFromFile"}; struct BinlogChip { LogOffset offset_; std::string binlog_; - BinlogChip(LogOffset offset, std::string binlog) : offset_(offset), binlog_(binlog) { - } + BinlogChip(LogOffset offset, std::string binlog) : offset_(offset), binlog_(binlog) {} BinlogChip(const BinlogChip& binlog_chip) { offset_ = binlog_chip.offset_; binlog_ = binlog_chip.binlog_; @@ -265,13 +209,10 @@ struct BinlogChip { struct PartitionInfo { PartitionInfo(const std::string& table_name, uint32_t partition_id) - : table_name_(table_name), partition_id_(partition_id) { - } - PartitionInfo() : partition_id_(0) { - } + : table_name_(table_name), partition_id_(partition_id) {} + PartitionInfo() : partition_id_(0) {} bool operator==(const PartitionInfo& other) const { - if (table_name_ == other.table_name_ - && partition_id_ == other.partition_id_) { + if (table_name_ == other.table_name_ && partition_id_ == other.partition_id_) { return true; } return false; @@ -289,9 +230,7 @@ struct PartitionInfo { } return ret; } - std::string ToString() const { - return "(" + table_name_ + ":" + std::to_string(partition_id_) + ")"; - } + std::string ToString() const { return "(" + table_name_ + ":" + std::to_string(partition_id_) + ")"; } std::string table_name_; uint32_t partition_id_; }; @@ -304,20 +243,13 @@ struct hash_partition_info { class Node { public: - Node(const std::string& ip, int port) : ip_(ip), port_(port) { - } + Node(const std::string& ip, int port) : ip_(ip), port_(port) {} virtual ~Node() = default; - Node() : port_(0) { - } - const std::string& Ip() const { - return ip_; - } - int Port() const { - return port_; - } - std::string ToString() const { - return ip_ + ":" + std::to_string(port_); - } + Node() : port_(0) {} + const std::string& Ip() const { return ip_; } + int Port() const { return port_; } + std::string ToString() const { return ip_ + ":" + std::to_string(port_); } + private: std::string ip_; int port_; @@ -325,90 +257,50 @@ class Node { class RmNode : public Node { public: - RmNode(const std::string& ip, int port, - const PartitionInfo& partition_info) - : Node(ip, port), - partition_info_(partition_info), - session_id_(0), - last_send_time_(0), - last_recv_time_(0) {} - - RmNode(const std::string& ip, - int port, - const std::string& table_name, - uint32_t partition_id) + RmNode(const std::string& ip, int port, const PartitionInfo& partition_info) + : Node(ip, port), partition_info_(partition_info), session_id_(0), last_send_time_(0), last_recv_time_(0) {} + + RmNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id) : Node(ip, port), partition_info_(table_name, partition_id), session_id_(0), last_send_time_(0), last_recv_time_(0) {} - RmNode(const std::string& ip, - int port, - const std::string& table_name, - uint32_t partition_id, - int32_t session_id) + RmNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, int32_t session_id) : Node(ip, port), partition_info_(table_name, partition_id), session_id_(session_id), last_send_time_(0), last_recv_time_(0) {} - RmNode(const std::string& table_name, - uint32_t partition_id) - : Node(), - partition_info_(table_name, partition_id), - session_id_(0), - last_send_time_(0), - last_recv_time_(0) {} - RmNode() - : Node(), - partition_info_(), - session_id_(0), - last_send_time_(0), - last_recv_time_(0) {} + RmNode(const std::string& table_name, uint32_t partition_id) + : Node(), partition_info_(table_name, partition_id), session_id_(0), last_send_time_(0), last_recv_time_(0) {} + RmNode() : Node(), partition_info_(), session_id_(0), last_send_time_(0), last_recv_time_(0) {} virtual ~RmNode() = default; bool operator==(const RmNode& other) const { - if (partition_info_.table_name_ == other.TableName() - && partition_info_.partition_id_ == other.PartitionId() - && Ip() == other.Ip() && Port() == other.Port()) { + if (partition_info_.table_name_ == other.TableName() && partition_info_.partition_id_ == other.PartitionId() && + Ip() == other.Ip() && Port() == other.Port()) { return true; } return false; } - const std::string& TableName() const { - return partition_info_.table_name_; - } - uint32_t PartitionId() const { - return partition_info_.partition_id_; - } - const PartitionInfo& NodePartitionInfo() const { - return partition_info_; - } - void SetSessionId(uint32_t session_id) { - session_id_ = session_id; - } - int32_t SessionId() const { - return session_id_; - } + const std::string& TableName() const { return partition_info_.table_name_; } + uint32_t PartitionId() const { return partition_info_.partition_id_; } + const PartitionInfo& NodePartitionInfo() const { return partition_info_; } + void SetSessionId(uint32_t session_id) { session_id_ = session_id; } + int32_t SessionId() const { return session_id_; } std::string ToString() const { - return "partition=" + TableName() + "_" + std::to_string(PartitionId()) + ",ip_port=" - + Ip() + ":" + std::to_string(Port()) + ",session id=" + std::to_string(SessionId()); - } - void SetLastSendTime(uint64_t last_send_time) { - last_send_time_ = last_send_time; - } - uint64_t LastSendTime() const { - return last_send_time_; - } - void SetLastRecvTime(uint64_t last_recv_time) { - last_recv_time_ = last_recv_time; - } - uint64_t LastRecvTime() const { - return last_recv_time_; + return "partition=" + TableName() + "_" + std::to_string(PartitionId()) + ",ip_port=" + Ip() + ":" + + std::to_string(Port()) + ",session id=" + std::to_string(SessionId()); } + void SetLastSendTime(uint64_t last_send_time) { last_send_time_ = last_send_time; } + uint64_t LastSendTime() const { return last_send_time_; } + void SetLastRecvTime(uint64_t last_recv_time) { last_recv_time_ = last_recv_time; } + uint64_t LastRecvTime() const { return last_recv_time_; } + private: PartitionInfo partition_info_; int32_t session_id_; @@ -418,7 +310,8 @@ class RmNode : public Node { struct hash_rm_node { size_t operator()(const RmNode& n) const { - return std::hash()(n.TableName()) ^ std::hash()(n.PartitionId()) ^ std::hash()(n.Ip()) ^ std::hash()(n.Port()); + return std::hash()(n.TableName()) ^ std::hash()(n.PartitionId()) ^ + std::hash()(n.Ip()) ^ std::hash()(n.Port()); } }; @@ -426,16 +319,15 @@ struct WriteTask { struct RmNode rm_node_; struct BinlogChip binlog_chip_; LogOffset prev_offset_; - WriteTask(RmNode rm_node, BinlogChip binlog_chip, LogOffset prev_offset) : - rm_node_(rm_node), binlog_chip_(binlog_chip), prev_offset_(prev_offset) { - } + WriteTask(RmNode rm_node, BinlogChip binlog_chip, LogOffset prev_offset) + : rm_node_(rm_node), binlog_chip_(binlog_chip), prev_offset_(prev_offset) {} }; -//slowlog define +// slowlog define #define SLOWLOG_ENTRY_MAX_ARGC 32 #define SLOWLOG_ENTRY_MAX_STRING 128 -//slowlog entry +// slowlog entry struct SlowlogEntry { int64_t id; int64_t start_time; @@ -445,25 +337,25 @@ struct SlowlogEntry { #define PIKA_MIN_RESERVED_FDS 5000 -const int SLAVE_ITEM_STAGE_ONE = 1; -const int SLAVE_ITEM_STAGE_TWO = 2; +const int SLAVE_ITEM_STAGE_ONE = 1; +const int SLAVE_ITEM_STAGE_TWO = 2; -//repl_state_ -const int PIKA_REPL_NO_CONNECT = 0; -const int PIKA_REPL_SHOULD_META_SYNC = 1; -const int PIKA_REPL_META_SYNC_DONE = 2; -const int PIKA_REPL_ERROR = 3; +// repl_state_ +const int PIKA_REPL_NO_CONNECT = 0; +const int PIKA_REPL_SHOULD_META_SYNC = 1; +const int PIKA_REPL_META_SYNC_DONE = 2; +const int PIKA_REPL_ERROR = 3; -//role -const int PIKA_ROLE_SINGLE = 0; -const int PIKA_ROLE_SLAVE = 1; -const int PIKA_ROLE_MASTER = 2; +// role +const int PIKA_ROLE_SINGLE = 0; +const int PIKA_ROLE_SLAVE = 1; +const int PIKA_ROLE_MASTER = 2; /* * The size of Binlogfile */ -//static uint64_t kBinlogSize = 128; -//static const uint64_t kBinlogSize = 1024 * 1024 * 100; +// static uint64_t kBinlogSize = 128; +// static const uint64_t kBinlogSize = 1024 * 1024 * 100; enum RecordType { kZeroType = 0, @@ -498,7 +390,7 @@ const size_t kBinlogPrefixLen = 10; const std::string kPikaMeta = "meta"; const std::string kManifest = "manifest"; -const std::string kContext = "context"; +const std::string kContext = "context"; /* * define common character diff --git a/include/pika_dispatch_thread.h b/include/pika_dispatch_thread.h index fb5e8f6f09..1e427fb221 100644 --- a/include/pika_dispatch_thread.h +++ b/include/pika_dispatch_thread.h @@ -10,44 +10,35 @@ class PikaDispatchThread { public: - PikaDispatchThread(std::set &ips, int port, int work_num, - int cron_interval, int queue_limit, int max_conn_rbuf_size); + PikaDispatchThread(std::set& ips, int port, int work_num, int cron_interval, int queue_limit, + int max_conn_rbuf_size); ~PikaDispatchThread(); int StartThread(); - int64_t ThreadClientList(std::vector *clients); + int64_t ThreadClientList(std::vector* clients); bool ClientKill(const std::string& ip_port); void ClientKillAll(); - void SetQueueLimit(int queue_limit) { - thread_rep_->SetQueueLimit(queue_limit); - } + void SetQueueLimit(int queue_limit) { thread_rep_->SetQueueLimit(queue_limit); } private: class ClientConnFactory : public net::ConnFactory { public: - explicit ClientConnFactory(int max_conn_rbuf_size) - : max_conn_rbuf_size_(max_conn_rbuf_size) { - } - virtual std::shared_ptr NewNetConn( - int connfd, - const std::string &ip_port, - net::Thread* server_thread, - void* worker_specific_data, - net::NetMultiplexer* net) const { - return std::static_pointer_cast - (std::make_shared(connfd, ip_port, server_thread, net, net::HandleType::kAsynchronous, max_conn_rbuf_size_)); - } + explicit ClientConnFactory(int max_conn_rbuf_size) : max_conn_rbuf_size_(max_conn_rbuf_size) {} + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, net::Thread* server_thread, + void* worker_specific_data, net::NetMultiplexer* net) const { + return std::static_pointer_cast(std::make_shared( + connfd, ip_port, server_thread, net, net::HandleType::kAsynchronous, max_conn_rbuf_size_)); + } + private: - int max_conn_rbuf_size_; + int max_conn_rbuf_size_; }; class Handles : public net::ServerHandle { public: - explicit Handles(PikaDispatchThread* pika_disptcher) - : pika_disptcher_(pika_disptcher) { - } + explicit Handles(PikaDispatchThread* pika_disptcher) : pika_disptcher_(pika_disptcher) {} using net::ServerHandle::AccessHandle; bool AccessHandle(std::string& ip) const override; void CronHandle() const override; diff --git a/include/pika_geo.h b/include/pika_geo.h index b7db85bdb7..2ce0c6eb13 100644 --- a/include/pika_geo.h +++ b/include/pika_geo.h @@ -13,7 +13,7 @@ * zset */ enum Sort { - Unsort, //default + Unsort, // default Asc, Desc }; @@ -50,19 +50,17 @@ struct GeoRange { class GeoAddCmd : public Cmd { public: - GeoAddCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + GeoAddCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GeoAddCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GeoAddCmd(*this); } + private: std::string key_; std::vector pos_; @@ -71,19 +69,17 @@ class GeoAddCmd : public Cmd { class GeoPosCmd : public Cmd { public: - GeoPosCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + GeoPosCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GeoPosCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GeoPosCmd(*this); } + private: std::string key_; std::vector members_; @@ -92,19 +88,17 @@ class GeoPosCmd : public Cmd { class GeoDistCmd : public Cmd { public: - GeoDistCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + GeoDistCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GeoDistCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GeoDistCmd(*this); } + private: std::string key_, first_pos_, second_pos_, unit_; virtual void DoInitial(); @@ -112,19 +106,17 @@ class GeoDistCmd : public Cmd { class GeoHashCmd : public Cmd { public: - GeoHashCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + GeoHashCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GeoHashCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GeoHashCmd(*this); } + private: std::string key_; std::vector members_; @@ -133,14 +125,12 @@ class GeoHashCmd : public Cmd { class GeoRadiusCmd : public Cmd { public: - GeoRadiusCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + GeoRadiusCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GeoRadiusCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GeoRadiusCmd(*this); } + private: std::string key_; GeoRange range_; @@ -160,14 +150,12 @@ class GeoRadiusCmd : public Cmd { class GeoRadiusByMemberCmd : public Cmd { public: - GeoRadiusByMemberCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + GeoRadiusByMemberCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GeoRadiusByMemberCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GeoRadiusByMemberCmd(*this); } + private: std::string key_; GeoRange range_; diff --git a/include/pika_geohash.h b/include/pika_geohash.h index e963839a4a..d0d3b8aa0d 100644 --- a/include/pika_geohash.h +++ b/include/pika_geohash.h @@ -34,7 +34,6 @@ #include #include -#include #if defined(__cplusplus) extern "C" { @@ -53,64 +52,61 @@ extern "C" { #define GEO_LONG_MAX 180 typedef enum { - GEOHASH_NORTH = 0, - GEOHASH_EAST, - GEOHASH_WEST, - GEOHASH_SOUTH, - GEOHASH_SOUTH_WEST, - GEOHASH_SOUTH_EAST, - GEOHASH_NORT_WEST, - GEOHASH_NORT_EAST + GEOHASH_NORTH = 0, + GEOHASH_EAST, + GEOHASH_WEST, + GEOHASH_SOUTH, + GEOHASH_SOUTH_WEST, + GEOHASH_SOUTH_EAST, + GEOHASH_NORT_WEST, + GEOHASH_NORT_EAST } GeoDirection; typedef struct { - uint64_t bits; - uint8_t step; + uint64_t bits; + uint8_t step; } GeoHashBits; typedef struct { - double min; - double max; + double min; + double max; } GeoHashRange; typedef struct { - GeoHashBits hash; - GeoHashRange longitude; - GeoHashRange latitude; + GeoHashBits hash; + GeoHashRange longitude; + GeoHashRange latitude; } GeoHashArea; typedef struct { - GeoHashBits north; - GeoHashBits east; - GeoHashBits west; - GeoHashBits south; - GeoHashBits north_east; - GeoHashBits south_east; - GeoHashBits north_west; - GeoHashBits south_west; + GeoHashBits north; + GeoHashBits east; + GeoHashBits west; + GeoHashBits south; + GeoHashBits north_east; + GeoHashBits south_east; + GeoHashBits north_west; + GeoHashBits south_west; } GeoHashNeighbors; /* * 0:success * -1:failed */ -void geohashGetCoordRange(GeoHashRange *long_range, GeoHashRange *lat_range); -int geohashEncode(const GeoHashRange *long_range, const GeoHashRange *lat_range, - double longitude, double latitude, uint8_t step, - GeoHashBits *hash); -int geohashEncodeType(double longitude, double latitude, - uint8_t step, GeoHashBits *hash); -int geohashEncodeWGS84(double longitude, double latitude, uint8_t step, - GeoHashBits *hash); -int geohashDecode(const GeoHashRange long_range, const GeoHashRange lat_range, - const GeoHashBits hash, GeoHashArea *area); -int geohashDecodeType(const GeoHashBits hash, GeoHashArea *area); -int geohashDecodeWGS84(const GeoHashBits hash, GeoHashArea *area); -int geohashDecodeAreaToLongLat(const GeoHashArea *area, double *xy); -int geohashDecodeToLongLatType(const GeoHashBits hash, double *xy); -int geohashDecodeToLongLatWGS84(const GeoHashBits hash, double *xy); -int geohashDecodeToLongLatMercator(const GeoHashBits hash, double *xy); -void geohashNeighbors(const GeoHashBits *hash, GeoHashNeighbors *neighbors); +void geohashGetCoordRange(GeoHashRange* long_range, GeoHashRange* lat_range); +int geohashEncode(const GeoHashRange* long_range, const GeoHashRange* lat_range, double longitude, double latitude, + uint8_t step, GeoHashBits* hash); +int geohashEncodeType(double longitude, double latitude, uint8_t step, GeoHashBits* hash); +int geohashEncodeWGS84(double longitude, double latitude, uint8_t step, GeoHashBits* hash); +int geohashDecode(const GeoHashRange long_range, const GeoHashRange lat_range, const GeoHashBits hash, + GeoHashArea* area); +int geohashDecodeType(const GeoHashBits hash, GeoHashArea* area); +int geohashDecodeWGS84(const GeoHashBits hash, GeoHashArea* area); +int geohashDecodeAreaToLongLat(const GeoHashArea* area, double* xy); +int geohashDecodeToLongLatType(const GeoHashBits hash, double* xy); +int geohashDecodeToLongLatWGS84(const GeoHashBits hash, double* xy); +int geohashDecodeToLongLatMercator(const GeoHashBits hash, double* xy); +void geohashNeighbors(const GeoHashBits* hash, GeoHashNeighbors* neighbors); #if defined(__cplusplus) } diff --git a/include/pika_geohash_helper.h b/include/pika_geohash_helper.h index 0642455fa4..dec4471839 100644 --- a/include/pika_geohash_helper.h +++ b/include/pika_geohash_helper.h @@ -42,29 +42,20 @@ typedef uint64_t GeoHashFix52Bits; typedef uint64_t GeoHashVarBits; typedef struct { - GeoHashBits hash; - GeoHashArea area; - GeoHashNeighbors neighbors; + GeoHashBits hash; + GeoHashArea area; + GeoHashNeighbors neighbors; } GeoHashRadius; -int GeoHashBitsComparator(const GeoHashBits *a, const GeoHashBits *b); +int GeoHashBitsComparator(const GeoHashBits* a, const GeoHashBits* b); uint8_t geohashEstimateStepsByRadius(double range_meters, double lat); -int geohashBoundingBox(double longitude, double latitude, double radius_meters, - double *bounds); -GeoHashRadius geohashGetAreasByRadius(double longitude, - double latitude, double radius_meters); -GeoHashRadius geohashGetAreasByRadiusWGS84(double longitude, double latitude, - double radius_meters); -GeoHashRadius geohashGetAreasByRadiusMercator(double longitude, double latitude, - double radius_meters); +int geohashBoundingBox(double longitude, double latitude, double radius_meters, double* bounds); +GeoHashRadius geohashGetAreasByRadius(double longitude, double latitude, double radius_meters); +GeoHashRadius geohashGetAreasByRadiusWGS84(double longitude, double latitude, double radius_meters); +GeoHashRadius geohashGetAreasByRadiusMercator(double longitude, double latitude, double radius_meters); GeoHashFix52Bits geohashAlign52Bits(const GeoHashBits hash); -double geohashGetDistance(double lon1d, double lat1d, - double lon2d, double lat2d); -int geohashGetDistanceIfInRadius(double x1, double y1, - double x2, double y2, double radius, - double *distance); -int geohashGetDistanceIfInRadiusWGS84(double x1, double y1, double x2, - double y2, double radius, - double *distance); +double geohashGetDistance(double lon1d, double lat1d, double lon2d, double lat2d); +int geohashGetDistanceIfInRadius(double x1, double y1, double x2, double y2, double radius, double* distance); +int geohashGetDistanceIfInRadiusWGS84(double x1, double y1, double x2, double y2, double radius, double* distance); #endif /* PIKA_GEOHASH_HELPER_HPP_ */ diff --git a/include/pika_hash.h b/include/pika_hash.h index 3eb8856ffe..74bf0721c1 100644 --- a/include/pika_hash.h +++ b/include/pika_hash.h @@ -16,19 +16,17 @@ */ class HDelCmd : public Cmd { public: - HDelCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HDelCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HDelCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HDelCmd(*this); } + private: std::string key_; std::vector fields_; @@ -37,19 +35,17 @@ class HDelCmd : public Cmd { class HGetCmd : public Cmd { public: - HGetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HGetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HGetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HGetCmd(*this); } + private: std::string key_, field_; virtual void DoInitial() override; @@ -57,19 +53,17 @@ class HGetCmd : public Cmd { class HGetallCmd : public Cmd { public: - HGetallCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HGetallCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HGetallCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HGetallCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -77,19 +71,17 @@ class HGetallCmd : public Cmd { class HSetCmd : public Cmd { public: - HSetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HSetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HSetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HSetCmd(*this); } + private: std::string key_, field_, value_; virtual void DoInitial() override; @@ -97,19 +89,17 @@ class HSetCmd : public Cmd { class HExistsCmd : public Cmd { public: - HExistsCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HExistsCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HExistsCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HExistsCmd(*this); } + private: std::string key_, field_; virtual void DoInitial() override; @@ -117,19 +107,17 @@ class HExistsCmd : public Cmd { class HIncrbyCmd : public Cmd { public: - HIncrbyCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HIncrbyCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HIncrbyCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HIncrbyCmd(*this); } + private: std::string key_, field_; int64_t by_; @@ -138,19 +126,17 @@ class HIncrbyCmd : public Cmd { class HIncrbyfloatCmd : public Cmd { public: - HIncrbyfloatCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HIncrbyfloatCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HIncrbyfloatCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HIncrbyfloatCmd(*this); } + private: std::string key_, field_, by_; virtual void DoInitial() override; @@ -158,19 +144,17 @@ class HIncrbyfloatCmd : public Cmd { class HKeysCmd : public Cmd { public: - HKeysCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HKeysCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HKeysCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HKeysCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -178,19 +162,17 @@ class HKeysCmd : public Cmd { class HLenCmd : public Cmd { public: - HLenCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HLenCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HLenCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HLenCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -198,19 +180,17 @@ class HLenCmd : public Cmd { class HMgetCmd : public Cmd { public: - HMgetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HMgetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HMgetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HMgetCmd(*this); } + private: std::string key_; std::vector fields_; @@ -219,19 +199,17 @@ class HMgetCmd : public Cmd { class HMsetCmd : public Cmd { public: - HMsetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HMsetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HMsetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HMsetCmd(*this); } + private: std::string key_; std::vector fvs_; @@ -240,19 +218,17 @@ class HMsetCmd : public Cmd { class HSetnxCmd : public Cmd { public: - HSetnxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HSetnxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HSetnxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HSetnxCmd(*this); } + private: std::string key_, field_, value_; virtual void DoInitial() override; @@ -260,19 +236,17 @@ class HSetnxCmd : public Cmd { class HStrlenCmd : public Cmd { public: - HStrlenCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HStrlenCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HStrlenCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HStrlenCmd(*this); } + private: std::string key_, field_; virtual void DoInitial() override; @@ -280,19 +254,17 @@ class HStrlenCmd : public Cmd { class HValsCmd : public Cmd { public: - HValsCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + HValsCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HValsCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HValsCmd(*this); } + private: std::string key_, field_; virtual void DoInitial() override; @@ -300,19 +272,17 @@ class HValsCmd : public Cmd { class HScanCmd : public Cmd { public: - HScanCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), pattern_("*"), count_(10) {} + HScanCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), pattern_("*"), count_(10) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HScanCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HScanCmd(*this); } + private: std::string key_, pattern_; int64_t cursor_, count_; @@ -325,19 +295,17 @@ class HScanCmd : public Cmd { class HScanxCmd : public Cmd { public: - HScanxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), pattern_("*"), count_(10) {} + HScanxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), pattern_("*"), count_(10) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new HScanxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new HScanxCmd(*this); } + private: std::string key_, start_field_, pattern_; int64_t count_; @@ -358,11 +326,10 @@ class PKHScanRangeCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PKHScanRangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PKHScanRangeCmd(*this); } + private: std::string key_; std::string field_start_; @@ -386,11 +353,10 @@ class PKHRScanRangeCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PKHRScanRangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PKHRScanRangeCmd(*this); } + private: std::string key_; std::string field_start_; diff --git a/include/pika_hyperloglog.h b/include/pika_hyperloglog.h index 2f2704a946..d6ca344a59 100644 --- a/include/pika_hyperloglog.h +++ b/include/pika_hyperloglog.h @@ -14,62 +14,50 @@ */ class PfAddCmd : public Cmd { public: - PfAddCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PfAddCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PfAddCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PfAddCmd(*this); } + private: std::string key_; std::vector values_; virtual void DoInitial() override; - virtual void Clear() { - values_.clear(); - } + virtual void Clear() { values_.clear(); } }; class PfCountCmd : public Cmd { public: - PfCountCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PfCountCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PfCountCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PfCountCmd(*this); } + private: std::vector keys_; virtual void DoInitial() override; - virtual void Clear() { - keys_.clear(); - } + virtual void Clear() { keys_.clear(); } }; class PfMergeCmd : public Cmd { public: - PfMergeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PfMergeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PfMergeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PfMergeCmd(*this); } + private: std::vector keys_; virtual void DoInitial() override; - virtual void Clear() { - keys_.clear(); - } + virtual void Clear() { keys_.clear(); } }; #endif diff --git a/include/pika_kv.h b/include/pika_kv.h index ef70e93f11..a06ccb9238 100644 --- a/include/pika_kv.h +++ b/include/pika_kv.h @@ -11,26 +11,22 @@ #include "include/pika_command.h" #include "include/pika_partition.h" - /* * kv */ class SetCmd : public Cmd { public: - enum SetCondition {kNONE, kNX, kXX, kVX, kEXORPX}; - SetCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag), sec_(0), condition_(kNONE) {}; + enum SetCondition { kNONE, kNX, kXX, kVX, kEXORPX }; + SetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), sec_(0), condition_(kNONE){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SetCmd(*this); } private: std::string key_; @@ -45,29 +41,23 @@ class SetCmd : public Cmd { success_ = 0; condition_ = kNONE; } - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class GetCmd : public Cmd { public: - GetCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + GetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GetCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -75,17 +65,12 @@ class GetCmd : public Cmd { class DelCmd : public Cmd { public: - DelCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag), split_res_(0) {}; + DelCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), split_res_(0){}; virtual void Do(std::shared_ptr partition = nullptr); - virtual std::vector current_key() const { - return keys_; - } + virtual std::vector current_key() const { return keys_; } virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys); virtual void Merge(); - virtual Cmd* Clone() override { - return new DelCmd(*this); - } + virtual Cmd* Clone() override { return new DelCmd(*this); } private: std::vector keys_; @@ -95,19 +80,17 @@ class DelCmd : public Cmd { class IncrCmd : public Cmd { public: - IncrCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + IncrCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new IncrCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new IncrCmd(*this); } + private: std::string key_; int64_t new_value_; @@ -116,19 +99,17 @@ class IncrCmd : public Cmd { class IncrbyCmd : public Cmd { public: - IncrbyCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + IncrbyCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new IncrbyCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new IncrbyCmd(*this); } + private: std::string key_; int64_t by_, new_value_; @@ -137,19 +118,17 @@ class IncrbyCmd : public Cmd { class IncrbyfloatCmd : public Cmd { public: - IncrbyfloatCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + IncrbyfloatCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new IncrbyfloatCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new IncrbyfloatCmd(*this); } + private: std::string key_, value_, new_value_; double by_; @@ -158,19 +137,17 @@ class IncrbyfloatCmd : public Cmd { class DecrCmd : public Cmd { public: - DecrCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + DecrCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new DecrCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new DecrCmd(*this); } + private: std::string key_; int64_t new_value_; @@ -179,19 +156,17 @@ class DecrCmd : public Cmd { class DecrbyCmd : public Cmd { public: - DecrbyCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + DecrbyCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new DecrbyCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new DecrbyCmd(*this); } + private: std::string key_; int64_t by_, new_value_; @@ -200,19 +175,17 @@ class DecrbyCmd : public Cmd { class GetsetCmd : public Cmd { public: - GetsetCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + GetsetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GetsetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GetsetCmd(*this); } + private: std::string key_; std::string new_value_; @@ -221,19 +194,17 @@ class GetsetCmd : public Cmd { class AppendCmd : public Cmd { public: - AppendCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + AppendCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new AppendCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new AppendCmd(*this); } + private: std::string key_; std::string value_; @@ -242,17 +213,12 @@ class AppendCmd : public Cmd { class MgetCmd : public Cmd { public: - MgetCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + MgetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual void Do(std::shared_ptr partition = nullptr); - virtual std::vector current_key() const { - return keys_; - } + virtual std::vector current_key() const { return keys_; } virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys); virtual void Merge(); - virtual Cmd* Clone() override { - return new MgetCmd(*this); - } + virtual Cmd* Clone() override { return new MgetCmd(*this); } private: std::vector keys_; @@ -262,122 +228,98 @@ class MgetCmd : public Cmd { class KeysCmd : public Cmd { public: - KeysCmd(const std::string& name , int arity, uint16_t flag) - : Cmd(name, arity, flag), type_(storage::DataType::kAll) {} + KeysCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), type_(storage::DataType::kAll) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new KeysCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new KeysCmd(*this); } + private: std::string pattern_; storage::DataType type_; virtual void DoInitial() override; - virtual void Clear() { - type_ = storage::DataType::kAll; - } + virtual void Clear() { type_ = storage::DataType::kAll; } }; class SetnxCmd : public Cmd { public: - SetnxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SetnxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SetnxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SetnxCmd(*this); } + private: std::string key_; std::string value_; int32_t success_; virtual void DoInitial() override; - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class SetexCmd : public Cmd { public: - SetexCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SetexCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SetexCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SetexCmd(*this); } + private: std::string key_; int64_t sec_; std::string value_; virtual void DoInitial() override; - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class PsetexCmd : public Cmd { public: - PsetexCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PsetexCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PsetexCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PsetexCmd(*this); } + private: std::string key_; int64_t usec_; std::string value_; virtual void DoInitial() override; - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class DelvxCmd : public Cmd { public: - DelvxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + DelvxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new DelvxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new DelvxCmd(*this); } + private: std::string key_; std::string value_; @@ -387,8 +329,7 @@ class DelvxCmd : public Cmd { class MsetCmd : public Cmd { public: - MsetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + MsetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); virtual std::vector current_key() const { std::vector res; @@ -399,9 +340,8 @@ class MsetCmd : public Cmd { } virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys); virtual void Merge(); - virtual Cmd* Clone() override { - return new MsetCmd(*this); - } + virtual Cmd* Clone() override { return new MsetCmd(*this); } + private: std::vector kvs_; virtual void DoInitial() override; @@ -409,14 +349,12 @@ class MsetCmd : public Cmd { class MsetnxCmd : public Cmd { public: - MsetnxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + MsetnxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new MsetnxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new MsetnxCmd(*this); } + private: std::vector kvs_; int32_t success_; @@ -425,19 +363,17 @@ class MsetnxCmd : public Cmd { class GetrangeCmd : public Cmd { public: - GetrangeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + GetrangeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new GetrangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new GetrangeCmd(*this); } + private: std::string key_; int64_t start_; @@ -447,19 +383,17 @@ class GetrangeCmd : public Cmd { class SetrangeCmd : public Cmd { public: - SetrangeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SetrangeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SetrangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SetrangeCmd(*this); } + private: std::string key_; int64_t offset_; @@ -469,19 +403,17 @@ class SetrangeCmd : public Cmd { class StrlenCmd : public Cmd { public: - StrlenCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + StrlenCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new StrlenCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new StrlenCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -489,17 +421,12 @@ class StrlenCmd : public Cmd { class ExistsCmd : public Cmd { public: - ExistsCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), split_res_(0) {} + ExistsCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), split_res_(0) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual std::vector current_key() const { - return keys_; - } + virtual std::vector current_key() const { return keys_; } virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys); virtual void Merge(); - virtual Cmd* Clone() override { - return new ExistsCmd(*this); - } + virtual Cmd* Clone() override { return new ExistsCmd(*this); } private: std::vector keys_; @@ -509,73 +436,59 @@ class ExistsCmd : public Cmd { class ExpireCmd : public Cmd { public: - ExpireCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ExpireCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ExpireCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ExpireCmd(*this); } + private: std::string key_; int64_t sec_; virtual void DoInitial() override; - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class PexpireCmd : public Cmd { public: - PexpireCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PexpireCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PexpireCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PexpireCmd(*this); } + private: std::string key_; int64_t msec_; virtual void DoInitial() override; - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class ExpireatCmd : public Cmd { public: - ExpireatCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ExpireatCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ExpireatCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ExpireatCmd(*this); } + private: std::string key_; int64_t time_stamp_; @@ -584,46 +497,38 @@ class ExpireatCmd : public Cmd { class PexpireatCmd : public Cmd { public: - PexpireatCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PexpireatCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PexpireatCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PexpireatCmd(*this); } + private: std::string key_; int64_t time_stamp_ms_; virtual void DoInitial() override; - virtual std::string ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) override; + virtual std::string ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) override; }; class TtlCmd : public Cmd { public: - TtlCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + TtlCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new TtlCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new TtlCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -631,19 +536,17 @@ class TtlCmd : public Cmd { class PttlCmd : public Cmd { public: - PttlCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PttlCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PttlCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PttlCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -651,19 +554,17 @@ class PttlCmd : public Cmd { class PersistCmd : public Cmd { public: - PersistCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PersistCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PersistCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PersistCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -671,19 +572,17 @@ class PersistCmd : public Cmd { class TypeCmd : public Cmd { public: - TypeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + TypeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new TypeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new TypeCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -691,14 +590,12 @@ class TypeCmd : public Cmd { class ScanCmd : public Cmd { public: - ScanCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), pattern_("*"), count_(10) {} + ScanCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), pattern_("*"), count_(10) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ScanCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ScanCmd(*this); } + private: int64_t cursor_; std::string pattern_; @@ -712,14 +609,12 @@ class ScanCmd : public Cmd { class ScanxCmd : public Cmd { public: - ScanxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), pattern_("*"), count_(10) {} + ScanxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), pattern_("*"), count_(10) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ScanxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ScanxCmd(*this); } + private: storage::DataType type_; std::string start_key_; @@ -733,28 +628,24 @@ class ScanxCmd : public Cmd { }; class PKSetexAtCmd : public Cmd { -public: - PKSetexAtCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), time_stamp_(0) {} + public: + PKSetexAtCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), time_stamp_(0) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PKSetexAtCmd(*this); - } -private: + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PKSetexAtCmd(*this); } + + private: std::string key_; std::string value_; int64_t time_stamp_; virtual void DoInitial() override; - virtual void Clear() { - time_stamp_ = 0; - } + virtual void Clear() { time_stamp_ = 0; } }; class PKScanRangeCmd : public Cmd { @@ -767,11 +658,10 @@ class PKScanRangeCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PKScanRangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PKScanRangeCmd(*this); } + private: storage::DataType type_; std::string key_start_; @@ -797,11 +687,10 @@ class PKRScanRangeCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PKRScanRangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PKRScanRangeCmd(*this); } + private: storage::DataType type_; std::string key_start_; diff --git a/include/pika_list.h b/include/pika_list.h index d3b80366dc..6b0634c5e4 100644 --- a/include/pika_list.h +++ b/include/pika_list.h @@ -16,43 +16,37 @@ */ class LIndexCmd : public Cmd { public: - LIndexCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), index_(0) {}; + LIndexCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), index_(0){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LIndexCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LIndexCmd(*this); } + private: std::string key_; int64_t index_; virtual void DoInitial() override; - virtual void Clear() { - index_ = 0; - } + virtual void Clear() { index_ = 0; } }; class LInsertCmd : public Cmd { public: - LInsertCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), dir_(storage::After) {}; + LInsertCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), dir_(storage::After){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LInsertCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LInsertCmd(*this); } + private: std::string key_; storage::BeforeOrAfter dir_; @@ -63,19 +57,17 @@ class LInsertCmd : public Cmd { class LLenCmd : public Cmd { public: - LLenCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + LLenCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LLenCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LLenCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -83,19 +75,17 @@ class LLenCmd : public Cmd { class LPopCmd : public Cmd { public: - LPopCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + LPopCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LPopCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LPopCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -103,43 +93,37 @@ class LPopCmd : public Cmd { class LPushCmd : public Cmd { public: - LPushCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + LPushCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LPushCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LPushCmd(*this); } + private: std::string key_; std::vector values_; virtual void DoInitial() override; - virtual void Clear() { - values_.clear(); - } + virtual void Clear() { values_.clear(); } }; class LPushxCmd : public Cmd { public: - LPushxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + LPushxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LPushxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LPushxCmd(*this); } + private: std::string key_; std::string value_; @@ -148,19 +132,17 @@ class LPushxCmd : public Cmd { class LRangeCmd : public Cmd { public: - LRangeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), left_(0), right_(0) {}; + LRangeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), left_(0), right_(0){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LRangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LRangeCmd(*this); } + private: std::string key_; int64_t left_; @@ -170,19 +152,17 @@ class LRangeCmd : public Cmd { class LRemCmd : public Cmd { public: - LRemCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), count_(0) {}; + LRemCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), count_(0){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LRemCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LRemCmd(*this); } + private: std::string key_; int64_t count_; @@ -192,19 +172,17 @@ class LRemCmd : public Cmd { class LSetCmd : public Cmd { public: - LSetCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), index_(0) {}; + LSetCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), index_(0){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LSetCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LSetCmd(*this); } + private: std::string key_; int64_t index_; @@ -214,19 +192,17 @@ class LSetCmd : public Cmd { class LTrimCmd : public Cmd { public: - LTrimCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), start_(0), stop_(0) {}; + LTrimCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), start_(0), stop_(0){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new LTrimCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new LTrimCmd(*this); } + private: std::string key_; int64_t start_; @@ -236,19 +212,17 @@ class LTrimCmd : public Cmd { class RPopCmd : public Cmd { public: - RPopCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + RPopCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new RPopCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new RPopCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -256,19 +230,17 @@ class RPopCmd : public Cmd { class RPopLPushCmd : public Cmd { public: - RPopLPushCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; - std::vector current_key() const override{ + RPopLPushCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; + std::vector current_key() const override { std::vector res; res.push_back(source_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new RPopLPushCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new RPopLPushCmd(*this); } + private: std::string source_; std::string receiver_; @@ -277,43 +249,37 @@ class RPopLPushCmd : public Cmd { class RPushCmd : public Cmd { public: - RPushCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + RPushCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new RPushCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new RPushCmd(*this); } + private: std::string key_; std::vector values_; virtual void DoInitial() override; - virtual void Clear() { - values_.clear(); - } + virtual void Clear() { values_.clear(); } }; class RPushxCmd : public Cmd { public: - RPushxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {}; + RPushxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag){}; virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new RPushxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new RPushxCmd(*this); } + private: std::string key_; std::string value_; diff --git a/include/pika_monitor_thread.h b/include/pika_monitor_thread.h index 9d08d6fd7f..fe6e525173 100644 --- a/include/pika_monitor_thread.h +++ b/include/pika_monitor_thread.h @@ -3,19 +3,19 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#ifndef PIKA_MONITOR_THREAD_H_ -#define PIKA_MONITOR_THREAD_H_ +#ifndef PIKA_MONITOR_THREAD_H_ +#define PIKA_MONITOR_THREAD_H_ -#include +#include #include +#include #include -#include #include "net/include/net_thread.h" #include "pstd/include/pstd_mutex.h" -#include "include/pika_define.h" #include "include/pika_client_conn.h" +#include "include/pika_define.h" class PikaMonitorThread : public net::Thread { public: @@ -23,7 +23,7 @@ class PikaMonitorThread : public net::Thread { virtual ~PikaMonitorThread(); void AddMonitorClient(std::shared_ptr client_ptr); - void AddMonitorMessage(const std::string &monitor_message); + void AddMonitorMessage(const std::string& monitor_message); int32_t ThreadClientList(std::vector* client = NULL); bool ThreadClientKill(const std::string& ip_port = "all"); bool HasMonitorClients(); diff --git a/include/pika_partition.h b/include/pika_partition.h index de04f6b75e..f3acb70c34 100644 --- a/include/pika_partition.h +++ b/include/pika_partition.h @@ -6,9 +6,9 @@ #ifndef PIKA_PARTITION_H_ #define PIKA_PARTITION_H_ -#include "storage/storage.h" -#include "storage/backupable.h" #include "pstd/include/scope_record_lock.h" +#include "storage/backupable.h" +#include "storage/storage.h" #include "include/pika_binlog.h" @@ -21,18 +21,16 @@ struct KeyScanInfo { time_t start_time; std::string s_start_time; int32_t duration; - std::vector key_infos; //the order is strings, hashes, lists, zsets, sets + std::vector key_infos; // the order is strings, hashes, lists, zsets, sets bool key_scaning_; - KeyScanInfo() : - start_time(0), - s_start_time("1970-01-01 08:00:00"), - duration(-3), - key_infos({{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}), - key_scaning_(false) { - } + KeyScanInfo() + : start_time(0), + s_start_time("1970-01-01 08:00:00"), + duration(-3), + key_infos({{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}), + key_scaning_(false) {} }; - struct BgSaveInfo { bool bgsaving; time_t start_time; @@ -49,9 +47,7 @@ struct BgSaveInfo { class Partition : public std::enable_shared_from_this { public: - Partition(const std::string& table_name, - uint32_t partition_id, - const std::string& table_db_path); + Partition(const std::string& table_name, uint32_t partition_id, const std::string& table_db_path); virtual ~Partition(); std::string GetTableName() const; @@ -129,7 +125,6 @@ class Partition : public std::enable_shared_from_this { */ Partition(const Partition&); void operator=(const Partition&); - }; #endif diff --git a/include/pika_pubsub.h b/include/pika_pubsub.h index 79b43bf484..41b4a0ff2f 100644 --- a/include/pika_pubsub.h +++ b/include/pika_pubsub.h @@ -13,14 +13,12 @@ */ class PublishCmd : public Cmd { public: - PublishCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PublishCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PublishCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PublishCmd(*this); } + private: std::string channel_; std::string msg_; @@ -29,77 +27,65 @@ class PublishCmd : public Cmd { class SubscribeCmd : public Cmd { public: - SubscribeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SubscribeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SubscribeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SubscribeCmd(*this); } + private: virtual void DoInitial() override; }; class UnSubscribeCmd : public Cmd { public: - UnSubscribeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + UnSubscribeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new UnSubscribeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new UnSubscribeCmd(*this); } + private: virtual void DoInitial() override; }; class PUnSubscribeCmd : public Cmd { public: - PUnSubscribeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PUnSubscribeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PUnSubscribeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PUnSubscribeCmd(*this); } + private: virtual void DoInitial() override; }; class PSubscribeCmd : public Cmd { public: - PSubscribeCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PSubscribeCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PSubscribeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PSubscribeCmd(*this); } + private: virtual void DoInitial() override; }; class PubSubCmd : public Cmd { public: - PubSubCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + PubSubCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr) override; - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new PubSubCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new PubSubCmd(*this); } + private: std::string subcommand_; - std::vector arguments_; + std::vector arguments_; virtual void DoInitial() override; - virtual void Clear() { - arguments_.clear(); - } + virtual void Clear() { arguments_.clear(); } }; #endif // INCLUDE_PIKA_PUBSUB_H_ diff --git a/include/pika_repl_bgworker.h b/include/pika_repl_bgworker.h index 3a2035d203..6d8b84eb11 100644 --- a/include/pika_repl_bgworker.h +++ b/include/pika_repl_bgworker.h @@ -9,14 +9,14 @@ #include #include -#include "net/include/pb_conn.h" #include "net/include/bg_thread.h" +#include "net/include/pb_conn.h" #include "net/include/thread_pool.h" #include "pika_inner_message.pb.h" -#include "include/pika_command.h" #include "include/pika_binlog_transverter.h" +#include "include/pika_command.h" class PikaReplBgWorker { public: diff --git a/include/pika_repl_client.h b/include/pika_repl_client.h index 59a4ceb814..2bef1f03ea 100644 --- a/include/pika_repl_client.h +++ b/include/pika_repl_client.h @@ -6,17 +6,17 @@ #ifndef PIKA_REPL_CLIENT_H_ #define PIKA_REPL_CLIENT_H_ -#include #include +#include -#include "net/include/net_conn.h" #include "net/include/client_thread.h" +#include "net/include/net_conn.h" #include "net/include/thread_pool.h" #include "pstd/include/pstd_status.h" +#include "include/pika_binlog_reader.h" #include "include/pika_define.h" #include "include/pika_partition.h" -#include "include/pika_binlog_reader.h" #include "include/pika_repl_bgworker.h" #include "include/pika_repl_client_thread.h" @@ -28,8 +28,7 @@ using pstd::Status; struct ReplClientTaskArg { std::shared_ptr res; std::shared_ptr conn; - ReplClientTaskArg(std::shared_ptr _res, - std::shared_ptr _conn) + ReplClientTaskArg(std::shared_ptr _res, std::shared_ptr _conn) : res(_res), conn(_conn) {} }; @@ -38,13 +37,9 @@ struct ReplClientWriteBinlogTaskArg { std::shared_ptr conn; void* res_private_data; PikaReplBgWorker* worker; - ReplClientWriteBinlogTaskArg( - const std::shared_ptr _res, - std::shared_ptr _conn, - void* _res_private_data, - PikaReplBgWorker* _worker) : - res(_res), conn(_conn), - res_private_data(_res_private_data), worker(_worker) {} + ReplClientWriteBinlogTaskArg(const std::shared_ptr _res, + std::shared_ptr _conn, void* _res_private_data, PikaReplBgWorker* _worker) + : res(_res), conn(_conn), res_private_data(_res_private_data), worker(_worker) {} }; struct ReplClientWriteDBTaskArg { @@ -52,18 +47,12 @@ struct ReplClientWriteDBTaskArg { LogOffset offset; std::string table_name; uint32_t partition_id; - ReplClientWriteDBTaskArg(const std::shared_ptr _cmd_ptr, - const LogOffset _offset, - const std::string _table_name, + ReplClientWriteDBTaskArg(const std::shared_ptr _cmd_ptr, const LogOffset _offset, const std::string _table_name, uint32_t _partition_id) - : cmd_ptr(_cmd_ptr), - offset(_offset), - table_name(_table_name), partition_id(_partition_id) {} - ~ReplClientWriteDBTaskArg() { - } + : cmd_ptr(_cmd_ptr), offset(_offset), table_name(_table_name), partition_id(_partition_id) {} + ~ReplClientWriteDBTaskArg() {} }; - class PikaReplClient { public: PikaReplClient(int cron_interval, int keepalive_timeout); @@ -76,44 +65,25 @@ class PikaReplClient { pstd::Status Close(const std::string& ip, const int port); void Schedule(net::TaskFunc func, void* arg); - void ScheduleWriteBinlogTask(std::string table_partition, - const std::shared_ptr res, - std::shared_ptr conn, - void* req_private_data); - void ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, const LogOffset& offset, - const std::string& table_name, uint32_t partition_id); + void ScheduleWriteBinlogTask(std::string table_partition, const std::shared_ptr res, + std::shared_ptr conn, void* req_private_data); + void ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, const LogOffset& offset, const std::string& table_name, + uint32_t partition_id); Status SendMetaSync(); - Status SendPartitionDBSync(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, - const BinlogOffset& boffset, - const std::string& local_ip); - Status SendPartitionTrySync(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, - const BinlogOffset& boffset, - const std::string& local_ip); - Status SendPartitionBinlogSync(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, - const LogOffset& ack_start, - const LogOffset& ack_end, - const std::string& local_ip, - bool is_frist_send); - Status SendRemoveSlaveNode(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, + Status SendPartitionDBSync(const std::string& ip, uint32_t port, const std::string& table_name, uint32_t partition_id, + const BinlogOffset& boffset, const std::string& local_ip); + Status SendPartitionTrySync(const std::string& ip, uint32_t port, const std::string& table_name, + uint32_t partition_id, const BinlogOffset& boffset, const std::string& local_ip); + Status SendPartitionBinlogSync(const std::string& ip, uint32_t port, const std::string& table_name, + uint32_t partition_id, const LogOffset& ack_start, const LogOffset& ack_end, + const std::string& local_ip, bool is_frist_send); + Status SendRemoveSlaveNode(const std::string& ip, uint32_t port, const std::string& table_name, uint32_t partition_id, const std::string& local_ip); + private: size_t GetHashIndex(std::string key, bool upper_half); - void UpdateNextAvail() { - next_avail_ = (next_avail_ + 1) % bg_workers_.size(); - } + void UpdateNextAvail() { next_avail_ = (next_avail_ + 1) % bg_workers_.size(); } PikaReplClientThread* client_thread_; int next_avail_; diff --git a/include/pika_repl_client_conn.h b/include/pika_repl_client_conn.h index 6c58b7caea..0c45fb861a 100644 --- a/include/pika_repl_client_conn.h +++ b/include/pika_repl_client_conn.h @@ -16,9 +16,10 @@ class SyncMasterPartition; class SyncSlavePartition; -class PikaReplClientConn: public net::PbConn { +class PikaReplClientConn : public net::PbConn { public: - PikaReplClientConn(int fd, const std::string& ip_port, net::Thread *thread, void* worker_specific_data, net::NetMultiplexer* mpx); + PikaReplClientConn(int fd, const std::string& ip_port, net::Thread* thread, void* worker_specific_data, + net::NetMultiplexer* mpx); virtual ~PikaReplClientConn() = default; static void HandleMetaSyncResponse(void* arg); @@ -26,13 +27,11 @@ class PikaReplClientConn: public net::PbConn { static void HandleTrySyncResponse(void* arg); static void HandleRemoveSlaveNodeResponse(void* arg); - static Status TrySyncConsensusCheck( - const InnerMessage::ConsensusMeta& consensus_meta, - const std::shared_ptr& partition, - const std::shared_ptr& slave_partition); - static bool IsTableStructConsistent( - const std::vector& current_tables, - const std::vector& expect_tables); + static Status TrySyncConsensusCheck(const InnerMessage::ConsensusMeta& consensus_meta, + const std::shared_ptr& partition, + const std::shared_ptr& slave_partition); + static bool IsTableStructConsistent(const std::vector& current_tables, + const std::vector& expect_tables); int DealMessage() override; private: @@ -42,8 +41,8 @@ class PikaReplClientConn: public net::PbConn { struct ReplRespArg { std::shared_ptr resp; std::shared_ptr conn; - ReplRespArg(std::shared_ptr _resp, std::shared_ptr _conn) : resp(_resp), conn(_conn) { - } + ReplRespArg(std::shared_ptr _resp, std::shared_ptr _conn) + : resp(_resp), conn(_conn) {} }; }; diff --git a/include/pika_repl_client_thread.h b/include/pika_repl_client_thread.h index 04f01e9ebf..94c0ea029f 100644 --- a/include/pika_repl_client_thread.h +++ b/include/pika_repl_client_thread.h @@ -6,13 +6,13 @@ #ifndef PIKA_REPL_CLIENT_THREAD_H_ #define PIKA_REPL_CLIENT_THREAD_H_ -#include #include +#include #include "include/pika_repl_client_conn.h" -#include "net/include/net_conn.h" #include "net/include/client_thread.h" +#include "net/include/net_conn.h" class PikaReplClientThread : public net::ClientThread { public: @@ -23,20 +23,16 @@ class PikaReplClientThread : public net::ClientThread { private: class ReplClientConnFactory : public net::ConnFactory { public: - virtual std::shared_ptr NewNetConn( - int connfd, - const std::string &ip_port, - net::Thread *thread, - void* worker_specific_data, - net::NetMultiplexer* net) const override { - return std::static_pointer_cast - (std::make_shared(connfd, ip_port, thread, worker_specific_data, net)); + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, net::Thread* thread, + void* worker_specific_data, + net::NetMultiplexer* net) const override { + return std::static_pointer_cast( + std::make_shared(connfd, ip_port, thread, worker_specific_data, net)); } }; class ReplClientHandle : public net::ClientHandle { public: - void CronHandle() const override { - } + void CronHandle() const override {} void FdTimeoutHandle(int fd, const std::string& ip_port) const override; void FdClosedHandle(int fd, const std::string& ip_port) const override; bool AccessHandle(std::string& ip) const override { @@ -47,14 +43,9 @@ class PikaReplClientThread : public net::ClientThread { // } return true; } - int CreateWorkerSpecificData(void** data) const override { - return 0; - } - int DeleteWorkerSpecificData(void* data) const override { - return 0; - } - void DestConnectFailedHandle(std::string ip_port, std::string reason) const override { - } + int CreateWorkerSpecificData(void** data) const override { return 0; } + int DeleteWorkerSpecificData(void* data) const override { return 0; } + void DestConnectFailedHandle(std::string ip_port, std::string reason) const override {} }; ReplClientConnFactory conn_factory_; diff --git a/include/pika_repl_server_conn.h b/include/pika_repl_server_conn.h index 48d5072ea8..178ea1d991 100644 --- a/include/pika_repl_server_conn.h +++ b/include/pika_repl_server_conn.h @@ -8,41 +8,36 @@ #include -#include "net/include/pb_conn.h" #include "net/include/net_thread.h" +#include "net/include/pb_conn.h" #include "include/pika_define.h" #include "pika_inner_message.pb.h" class SyncMasterPartition; -class PikaReplServerConn: public net::PbConn { +class PikaReplServerConn : public net::PbConn { public: - PikaReplServerConn(int fd, std::string ip_port, net::Thread* thread, void* worker_specific_data, net::NetMultiplexer* mpx); + PikaReplServerConn(int fd, std::string ip_port, net::Thread* thread, void* worker_specific_data, + net::NetMultiplexer* mpx); virtual ~PikaReplServerConn(); static void HandleMetaSyncRequest(void* arg); static void HandleTrySyncRequest(void* arg); - static bool TrySyncOffsetCheck( - const std::shared_ptr& partition, - const InnerMessage::InnerRequest::TrySync& try_sync_request, - InnerMessage::InnerResponse::TrySync* try_sync_response); - static bool TrySyncConsensusOffsetCheck( - const std::shared_ptr& partition, - const InnerMessage::ConsensusMeta& meta, - InnerMessage::InnerResponse* response, - InnerMessage::InnerResponse::TrySync* try_sync_response); - static bool TrySyncUpdateSlaveNode( - const std::shared_ptr& partition, - const InnerMessage::InnerRequest::TrySync& try_sync_request, - const std::shared_ptr& conn, - InnerMessage::InnerResponse::TrySync* try_sync_response); - static void BuildConsensusMeta( - const bool& reject, - const std::vector& hints, - const uint32_t& term, - InnerMessage::InnerResponse* response); + static bool TrySyncOffsetCheck(const std::shared_ptr& partition, + const InnerMessage::InnerRequest::TrySync& try_sync_request, + InnerMessage::InnerResponse::TrySync* try_sync_response); + static bool TrySyncConsensusOffsetCheck(const std::shared_ptr& partition, + const InnerMessage::ConsensusMeta& meta, + InnerMessage::InnerResponse* response, + InnerMessage::InnerResponse::TrySync* try_sync_response); + static bool TrySyncUpdateSlaveNode(const std::shared_ptr& partition, + const InnerMessage::InnerRequest::TrySync& try_sync_request, + const std::shared_ptr& conn, + InnerMessage::InnerResponse::TrySync* try_sync_response); + static void BuildConsensusMeta(const bool& reject, const std::vector& hints, const uint32_t& term, + InnerMessage::InnerResponse* response); static void HandleDBSyncRequest(void* arg); static void HandleBinlogSyncRequest(void* arg); diff --git a/include/pika_repl_server_thread.h b/include/pika_repl_server_thread.h index 7ec049de76..6e1254fca6 100644 --- a/include/pika_repl_server_thread.h +++ b/include/pika_repl_server_thread.h @@ -18,28 +18,22 @@ class PikaReplServerThread : public net::HolyThread { int ListenPort(); // for ProcessBinlogData use - uint64_t GetnPlusSerial() { - return serial_++; - } + uint64_t GetnPlusSerial() { return serial_++; } private: class ReplServerConnFactory : public net::ConnFactory { public: - explicit ReplServerConnFactory(PikaReplServerThread* binlog_receiver) - : binlog_receiver_(binlog_receiver) { - } + explicit ReplServerConnFactory(PikaReplServerThread* binlog_receiver) : binlog_receiver_(binlog_receiver) {} - virtual std::shared_ptr NewNetConn( - int connfd, - const std::string& ip_port, - net::Thread* thread, - void* worker_specific_data, - net::NetMultiplexer* net) const override { - return std::static_pointer_cast - (std::make_shared(connfd, ip_port, thread, binlog_receiver_, net)); + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, net::Thread* thread, + void* worker_specific_data, + net::NetMultiplexer* net) const override { + return std::static_pointer_cast( + std::make_shared(connfd, ip_port, thread, binlog_receiver_, net)); } - private: - PikaReplServerThread* binlog_receiver_; + + private: + PikaReplServerThread* binlog_receiver_; }; class ReplServerHandle : public net::ServerHandle { diff --git a/include/pika_rm.h b/include/pika_rm.h index 557de60e1f..6705f99fe3 100644 --- a/include/pika_rm.h +++ b/include/pika_rm.h @@ -6,20 +6,20 @@ #ifndef PIKA_RM_H_ #define PIKA_RM_H_ -#include #include -#include #include +#include +#include #include #include "pstd/include/pstd_status.h" #include "include/pika_binlog_reader.h" +#include "include/pika_consensus.h" #include "include/pika_repl_client.h" #include "include/pika_repl_server.h" -#include "include/pika_stable_log.h" -#include "include/pika_consensus.h" #include "include/pika_slave_node.h" +#include "include/pika_stable_log.h" #define kBinlogSendPacketNum 40 #define kBinlogSendBatchNum 100 @@ -35,9 +35,7 @@ class SyncPartition { SyncPartition(const std::string& table_name, uint32_t partition_id); virtual ~SyncPartition() = default; - PartitionInfo& SyncPartitionInfo() { - return partition_info_; - } + PartitionInfo& SyncPartitionInfo() { return partition_info_; } std::string PartitionName(); @@ -82,19 +80,13 @@ class SyncMasterPartition : public SyncPartition { std::string ToStringStatus(); int32_t GenSessionId(); - bool CheckSessionId(const std::string& ip, int port, - const std::string& table_name, - uint64_t partition_id, int session_id); + bool CheckSessionId(const std::string& ip, int port, const std::string& table_name, uint64_t partition_id, + int session_id); // consensus use - Status ConsensusUpdateSlave( - const std::string& ip, int port, - const LogOffset& start, - const LogOffset& end); - Status ConsensusProposeLog( - std::shared_ptr cmd_ptr, - std::shared_ptr conn_ptr, - std::shared_ptr resp_ptr); + Status ConsensusUpdateSlave(const std::string& ip, int port, const LogOffset& start, const LogOffset& end); + Status ConsensusProposeLog(std::shared_ptr cmd_ptr, std::shared_ptr conn_ptr, + std::shared_ptr resp_ptr); Status ConsensusSanityCheck(); Status ConsensusProcessLeaderLog(std::shared_ptr cmd_ptr, const BinlogItem& attribute); Status ConsensusProcessLocalUpdate(const LogOffset& leader_commit); @@ -104,16 +96,12 @@ class SyncMasterPartition : public SyncPartition { void ConsensusUpdateTerm(uint32_t term); Status ConsensusUpdateAppliedIndex(const LogOffset& offset); LogOffset ConsensusAppliedIndex(); - Status ConsensusLeaderNegotiate(const LogOffset& f_last_offset, - bool* reject, std::vector* hints); - Status ConsensusFollowerNegotiate( - const std::vector& hints, LogOffset* reply_offset); + Status ConsensusLeaderNegotiate(const LogOffset& f_last_offset, bool* reject, std::vector* hints); + Status ConsensusFollowerNegotiate(const std::vector& hints, LogOffset* reply_offset); Status ConsensusReset(LogOffset applied_offset); void CommitPreviousLogs(const uint32_t& term); - std::shared_ptr StableLogger() { - return coordinator_.StableLogger(); - } + std::shared_ptr StableLogger() { return coordinator_.StableLogger(); } std::shared_ptr Logger() { if (!coordinator_.StableLogger()) { @@ -201,9 +189,8 @@ class PikaReplicaManager { Status SendRemoveSlaveNodeRequest(const std::string& table, uint32_t partition_id); Status SendPartitionTrySyncRequest(const std::string& table_name, size_t partition_id); Status SendPartitionDBSyncRequest(const std::string& table_name, size_t partition_id); - Status SendPartitionBinlogSyncAckRequest(const std::string& table, uint32_t partition_id, - const LogOffset& ack_start, const LogOffset& ack_end, - bool is_first_send = false); + Status SendPartitionBinlogSyncAckRequest(const std::string& table, uint32_t partition_id, const LogOffset& ack_start, + const LogOffset& ack_end, bool is_first_send = false); Status CloseReplClientConn(const std::string& ip, int32_t port); // For Pika Repl Server Thread @@ -221,13 +208,11 @@ class PikaReplicaManager { // To check partition info // For pkcluster info command - Status GetPartitionInfo( - const std::string& table, uint32_t partition_id, std::string* info); + Status GetPartitionInfo(const std::string& table, uint32_t partition_id, std::string* info); void FindCompleteReplica(std::vector* replica); void FindCommonMaster(std::string* master); - Status CheckPartitionRole( - const std::string& table, uint32_t partition_id, int* role); + Status CheckPartitionRole(const std::string& table, uint32_t partition_id, int* role); void RmStatus(std::string* debug_info); @@ -251,25 +236,24 @@ class PikaReplicaManager { void ScheduleWriteBinlogTask(const std::string& table_partition, const std::shared_ptr res, std::shared_ptr conn, void* res_private_data); - void ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, const LogOffset& offset, - const std::string& table_name, uint32_t partition_id); + void ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, const LogOffset& offset, const std::string& table_name, + uint32_t partition_id); void ReplServerRemoveClientConn(int fd); void ReplServerUpdateClientConnMap(const std::string& ip_port, int fd); private: void InitPartition(); - Status SelectLocalIp(const std::string& remote_ip, - const int remote_port, - std::string* const local_ip); + Status SelectLocalIp(const std::string& remote_ip, const int remote_port, std::string* const local_ip); pthread_rwlock_t partitions_rw_; std::unordered_map, hash_partition_info> sync_master_partitions_; std::unordered_map, hash_partition_info> sync_slave_partitions_; - pstd::Mutex write_queue_mu_; + pstd::Mutex write_queue_mu_; // every host owns a queue - std::unordered_map>> write_queues_; // map>> + std::unordered_map>> + write_queues_; // map>> PikaReplClient* pika_repl_client_; PikaReplServer* pika_repl_server_; diff --git a/include/pika_rsync_service.h b/include/pika_rsync_service.h index f728f52b57..72a43584c0 100644 --- a/include/pika_rsync_service.h +++ b/include/pika_rsync_service.h @@ -3,15 +3,14 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#ifndef PIKA_RSYNC_SERVICE_H_ -#define PIKA_RSYNC_SERVICE_H_ +#ifndef PIKA_RSYNC_SERVICE_H_ +#define PIKA_RSYNC_SERVICE_H_ #include "iostream" class PikaRsyncService { public: - PikaRsyncService(const std::string& raw_path, - const int port); + PikaRsyncService(const std::string& raw_path, const int port); ~PikaRsyncService(); int StartRsync(); bool CheckRsyncAlive(); diff --git a/include/pika_server.h b/include/pika_server.h index dbea92d391..473cc1dd35 100644 --- a/include/pika_server.h +++ b/include/pika_server.h @@ -7,37 +7,37 @@ #define PIKA_SERVER_H_ #if defined(__APPLE__) -#include -#include +# include +# include #else -#include +# include #endif #include +#include "net/include/bg_thread.h" +#include "net/include/net_pubsub.h" +#include "net/include/thread_pool.h" #include "pstd/include/pstd_mutex.h" #include "pstd/include/pstd_status.h" #include "pstd/include/pstd_string.h" -#include "net/include/bg_thread.h" -#include "net/include/thread_pool.h" -#include "net/include/net_pubsub.h" -#include "storage/storage.h" #include "storage/backupable.h" +#include "storage/storage.h" -#include "include/pika_conf.h" -#include "include/pika_table.h" +#include "include/pika_auxiliary_thread.h" #include "include/pika_binlog.h" +#include "include/pika_client_processor.h" +#include "include/pika_conf.h" #include "include/pika_define.h" -#include "include/pika_monitor_thread.h" -#include "include/pika_rsync_service.h" #include "include/pika_dispatch_thread.h" +#include "include/pika_monitor_thread.h" #include "include/pika_repl_client.h" #include "include/pika_repl_server.h" -#include "include/pika_auxiliary_thread.h" -#include "include/pika_client_processor.h" +#include "include/pika_rsync_service.h" #include "include/pika_statistic.h" +#include "include/pika_table.h" -using pstd::Status; using pstd::Slice; +using pstd::Status; /* static std::set MultiKvCommands {kCmdNameDel, @@ -53,31 +53,64 @@ static std::set MultiKvCommands {kCmdNameDel, kCmdNameGeoRadius, kCmdNameGeoRadiusByMember}; */ -static std::set ConsensusNotSupportCommands { - kCmdNameMsetnx, kCmdNameScan, kCmdNameKeys, - kCmdNameRPopLPush, kCmdNameZUnionstore, kCmdNameZInterstore, - kCmdNameSUnion, kCmdNameSUnionstore, kCmdNameSInter, - kCmdNameSInterstore, kCmdNameSDiff, kCmdNameSDiffstore, - kCmdNameSMove, kCmdNameBitOp, kCmdNamePfAdd, - kCmdNamePfCount, kCmdNamePfMerge, kCmdNameGeoAdd, - kCmdNameGeoPos, kCmdNameGeoDist, kCmdNameGeoHash, - kCmdNameGeoRadius, kCmdNameGeoRadiusByMember, kCmdNamePKPatternMatchDel, - kCmdNameSlaveof, kCmdNameDbSlaveof, kCmdNameMset, - kCmdNameMget, kCmdNameScanx}; - -static std::set ShardingModeNotSupportCommands { - kCmdNameMsetnx, kCmdNameScan, kCmdNameKeys, - kCmdNameScanx, kCmdNameZUnionstore, kCmdNameZInterstore, - kCmdNameSUnion, kCmdNameSUnionstore, kCmdNameSInter, - kCmdNameSInterstore, kCmdNameSDiff, kCmdNameSDiffstore, - kCmdNameSMove, kCmdNameBitOp, kCmdNamePfAdd, - kCmdNamePfCount, kCmdNamePfMerge, kCmdNameGeoAdd, - kCmdNameGeoPos, kCmdNameGeoDist, kCmdNameGeoHash, - kCmdNameGeoRadius, kCmdNameGeoRadiusByMember, kCmdNamePKPatternMatchDel, - kCmdNameSlaveof, kCmdNameDbSlaveof}; - - -extern PikaConf *g_pika_conf; +static std::set ConsensusNotSupportCommands{kCmdNameMsetnx, + kCmdNameScan, + kCmdNameKeys, + kCmdNameRPopLPush, + kCmdNameZUnionstore, + kCmdNameZInterstore, + kCmdNameSUnion, + kCmdNameSUnionstore, + kCmdNameSInter, + kCmdNameSInterstore, + kCmdNameSDiff, + kCmdNameSDiffstore, + kCmdNameSMove, + kCmdNameBitOp, + kCmdNamePfAdd, + kCmdNamePfCount, + kCmdNamePfMerge, + kCmdNameGeoAdd, + kCmdNameGeoPos, + kCmdNameGeoDist, + kCmdNameGeoHash, + kCmdNameGeoRadius, + kCmdNameGeoRadiusByMember, + kCmdNamePKPatternMatchDel, + kCmdNameSlaveof, + kCmdNameDbSlaveof, + kCmdNameMset, + kCmdNameMget, + kCmdNameScanx}; + +static std::set ShardingModeNotSupportCommands{kCmdNameMsetnx, + kCmdNameScan, + kCmdNameKeys, + kCmdNameScanx, + kCmdNameZUnionstore, + kCmdNameZInterstore, + kCmdNameSUnion, + kCmdNameSUnionstore, + kCmdNameSInter, + kCmdNameSInterstore, + kCmdNameSDiff, + kCmdNameSDiffstore, + kCmdNameSMove, + kCmdNameBitOp, + kCmdNamePfAdd, + kCmdNamePfCount, + kCmdNamePfMerge, + kCmdNameGeoAdd, + kCmdNameGeoPos, + kCmdNameGeoDist, + kCmdNameGeoHash, + kCmdNameGeoRadius, + kCmdNameGeoRadiusByMember, + kCmdNamePKPatternMatchDel, + kCmdNameSlaveof, + kCmdNameDbSlaveof}; + +extern PikaConf* g_pika_conf; enum TaskType { kCompactAll, @@ -146,32 +179,24 @@ class PikaServer { void PreparePartitionTrySync(); void PartitionSetMaxCacheStatisticKeys(uint32_t max_cache_statistic_keys); void PartitionSetSmallCompactionThreshold(uint32_t small_compaction_threshold); - bool GetTablePartitionBinlogOffset(const std::string& table_name, - uint32_t partition_id, - BinlogOffset* const boffset); + bool GetTablePartitionBinlogOffset(const std::string& table_name, uint32_t partition_id, BinlogOffset* const boffset); std::shared_ptr GetPartitionByDbName(const std::string& db_name); - std::shared_ptr GetTablePartitionById( - const std::string& table_name, - uint32_t partition_id); - std::shared_ptr GetTablePartitionByKey( - const std::string& table_name, - const std::string& key); + std::shared_ptr GetTablePartitionById(const std::string& table_name, uint32_t partition_id); + std::shared_ptr GetTablePartitionByKey(const std::string& table_name, const std::string& key); Status DoSameThingEveryPartition(const TaskType& type); /* * Master use */ void BecomeMaster(); - void DeleteSlave(int fd); //conn fd + void DeleteSlave(int fd); // conn fd int32_t CountSyncSlaves(); int32_t GetSlaveListString(std::string& slave_list_str); int32_t GetShardingSlaveListString(std::string& slave_list_str); - bool TryAddSlave(const std::string& ip, int64_t port, int fd, - const std::vector& table_structs); - pstd::Mutex slave_mutex_; // protect slaves_; + bool TryAddSlave(const std::string& ip, int64_t port, int fd, const std::vector& table_structs); + pstd::Mutex slave_mutex_; // protect slaves_; std::vector slaves_; - /* * Slave use */ @@ -221,18 +246,10 @@ class PikaServer { /* * DBSync used */ - void DBSync(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id); - void TryDBSync(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id, int32_t top); - void DbSyncSendFile(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id); - std::string DbSyncTaskIndex(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id); + void DBSync(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id); + void TryDBSync(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, int32_t top); + void DbSyncSendFile(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id); + std::string DbSyncTaskIndex(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id); /* * Keyscan used @@ -243,14 +260,14 @@ class PikaServer { * Client used */ void ClientKillAll(); - int ClientKill(const std::string &ip_port); - int64_t ClientList(std::vector *clients = nullptr); + int ClientKill(const std::string& ip_port); + int64_t ClientList(std::vector* clients = nullptr); /* * Monitor used */ bool HasMonitorClients(); - void AddMonitorMessage(const std::string &monitor_message); + void AddMonitorMessage(const std::string& monitor_message); void AddMonitorClient(std::shared_ptr client_ptr); /* @@ -271,9 +288,7 @@ class PikaServer { uint64_t accumulative_connections(); void incr_accumulative_connections(); void ResetLastSecQuerynum(); - void UpdateQueryNumAndExecCountTable( - const std::string& table_name, - const std::string& command, bool is_write); + void UpdateQueryNumAndExecCountTable(const std::string& table_name, const std::string& command, bool is_write); std::unordered_map ServerExecCountTable(); QpsStatistic ServerTableStat(const std::string& table_name); std::unordered_map ServerAllTableStat(); @@ -290,21 +305,14 @@ class PikaServer { int PubSubNumPat(); int Publish(const std::string& channel, const std::string& msg); void EnablePublish(int fd); - int UnSubscribe(std::shared_ptr conn, - const std::vector& channels, - const bool pattern, + int UnSubscribe(std::shared_ptr conn, const std::vector& channels, const bool pattern, std::vector>* result); - void Subscribe(std::shared_ptr conn, - const std::vector& channels, - const bool pattern, + void Subscribe(std::shared_ptr conn, const std::vector& channels, const bool pattern, std::vector>* result); - void PubSubChannels(const std::string& pattern, - std::vector* result); - void PubSubNumSub(const std::vector& channels, - std::vector>* result); + void PubSubChannels(const std::string& pattern, std::vector* result); + void PubSubNumSub(const std::vector& channels, std::vector>* result); - Status GetCmdRouting(std::vector& redis_cmds, - std::vector* dst, bool* all_local); + Status GetCmdRouting(std::vector& redis_cmds, std::vector* dst, bool* all_local); // info debug use void ServerStatus(std::string* info); @@ -313,7 +321,7 @@ class PikaServer { * StorageOptions used */ storage::Status RewriteStorageOptions(const storage::OptionType& option_type, - const std::unordered_map& options); + const std::unordered_map& options); friend class Cmd; friend class InfoCmd; @@ -364,7 +372,6 @@ class PikaServer { PikaClientProcessor* pika_client_processor_; PikaDispatchThread* pika_dispatch_thread_; - /* * Slave used */ @@ -376,8 +383,8 @@ class PikaServer { bool first_meta_sync_; bool loop_partition_state_machine_; bool force_full_sync_; - bool leader_protected_mode_; // reject request after master slave sync done - pthread_rwlock_t state_protector_; //protect below, use for master-slave mode + bool leader_protected_mode_; // reject request after master slave sync done + pthread_rwlock_t state_protector_; // protect below, use for master-slave mode /* * Bgsave used @@ -432,8 +439,8 @@ class PikaServer { */ Statistic statistic_; - PikaServer(PikaServer &ps); - void operator =(const PikaServer &ps); + PikaServer(PikaServer& ps); + void operator=(const PikaServer& ps); }; #endif diff --git a/include/pika_set.h b/include/pika_set.h index 19f88418f7..996d4e390f 100644 --- a/include/pika_set.h +++ b/include/pika_set.h @@ -14,19 +14,17 @@ */ class SAddCmd : public Cmd { public: - SAddCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SAddCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SAddCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SAddCmd(*this); } + private: std::string key_; std::vector members_; @@ -35,19 +33,17 @@ class SAddCmd : public Cmd { class SPopCmd : public Cmd { public: - SPopCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SPopCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SPopCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SPopCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -55,19 +51,17 @@ class SPopCmd : public Cmd { class SCardCmd : public Cmd { public: - SCardCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SCardCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SCardCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SCardCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -75,19 +69,17 @@ class SCardCmd : public Cmd { class SMembersCmd : public Cmd { public: - SMembersCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SMembersCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SMembersCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SMembersCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -95,19 +87,17 @@ class SMembersCmd : public Cmd { class SScanCmd : public Cmd { public: - SScanCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), pattern_("*"), count_(10) {} + SScanCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), pattern_("*"), count_(10) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SScanCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SScanCmd(*this); } + private: std::string key_, pattern_; int64_t cursor_, count_; @@ -120,19 +110,17 @@ class SScanCmd : public Cmd { class SRemCmd : public Cmd { public: - SRemCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SRemCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SRemCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SRemCmd(*this); } + private: std::string key_; std::vector members_; @@ -141,14 +129,12 @@ class SRemCmd : public Cmd { class SUnionCmd : public Cmd { public: - SUnionCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SUnionCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SUnionCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SUnionCmd(*this); } + private: std::vector keys_; virtual void DoInitial() override; @@ -156,14 +142,12 @@ class SUnionCmd : public Cmd { class SUnionstoreCmd : public Cmd { public: - SUnionstoreCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SUnionstoreCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SUnionstoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SUnionstoreCmd(*this); } + private: std::string dest_key_; std::vector keys_; @@ -172,14 +156,12 @@ class SUnionstoreCmd : public Cmd { class SInterCmd : public Cmd { public: - SInterCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SInterCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SInterCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SInterCmd(*this); } + private: std::vector keys_; virtual void DoInitial() override; @@ -187,14 +169,12 @@ class SInterCmd : public Cmd { class SInterstoreCmd : public Cmd { public: - SInterstoreCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SInterstoreCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SInterstoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SInterstoreCmd(*this); } + private: std::string dest_key_; std::vector keys_; @@ -203,19 +183,17 @@ class SInterstoreCmd : public Cmd { class SIsmemberCmd : public Cmd { public: - SIsmemberCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SIsmemberCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SIsmemberCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SIsmemberCmd(*this); } + private: std::string key_, member_; virtual void DoInitial() override; @@ -223,14 +201,12 @@ class SIsmemberCmd : public Cmd { class SDiffCmd : public Cmd { public: - SDiffCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SDiffCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SDiffCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SDiffCmd(*this); } + private: std::vector keys_; virtual void DoInitial() override; @@ -238,14 +214,12 @@ class SDiffCmd : public Cmd { class SDiffstoreCmd : public Cmd { public: - SDiffstoreCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SDiffstoreCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SDiffstoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SDiffstoreCmd(*this); } + private: std::string dest_key_; std::vector keys_; @@ -254,14 +228,12 @@ class SDiffstoreCmd : public Cmd { class SMoveCmd : public Cmd { public: - SMoveCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SMoveCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SMoveCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SMoveCmd(*this); } + private: std::string src_key_, dest_key_, member_; virtual void DoInitial() override; @@ -269,19 +241,17 @@ class SMoveCmd : public Cmd { class SRandmemberCmd : public Cmd { public: - SRandmemberCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), count_(1) {} + SRandmemberCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), count_(1) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SRandmemberCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SRandmemberCmd(*this); } + private: std::string key_; int64_t count_; diff --git a/include/pika_slave_node.h b/include/pika_slave_node.h index eedb912d9f..5e5a31a232 100644 --- a/include/pika_slave_node.h +++ b/include/pika_slave_node.h @@ -9,30 +9,27 @@ #include #include -#include "include/pika_define.h" #include "include/pika_binlog_reader.h" +#include "include/pika_define.h" struct SyncWinItem { LogOffset offset_; std::size_t binlog_size_; bool acked_; bool operator==(const SyncWinItem& other) const { - return offset_.b_offset.filenum == other.offset_.b_offset.filenum - && offset_.b_offset.offset == other.offset_.b_offset.offset; + return offset_.b_offset.filenum == other.offset_.b_offset.filenum && + offset_.b_offset.offset == other.offset_.b_offset.offset; } explicit SyncWinItem(const LogOffset& offset, std::size_t binlog_size = 0) - : offset_(offset), binlog_size_(binlog_size), acked_(false) { - } + : offset_(offset), binlog_size_(binlog_size), acked_(false) {} std::string ToString() const { - return offset_.ToString() + " binglog size: " + std::to_string(binlog_size_) + - " acked: " + std::to_string(acked_); + return offset_.ToString() + " binglog size: " + std::to_string(binlog_size_) + " acked: " + std::to_string(acked_); } }; class SyncWindow { public: - SyncWindow() :total_size_(0) { - } + SyncWindow() : total_size_(0) {} void Push(const SyncWinItem& item); bool Update(const SyncWinItem& start_item, const SyncWinItem& end_item, LogOffset* acked_offset); int Remaining(); @@ -47,9 +44,7 @@ class SyncWindow { return res; } } - std::size_t GetTotalBinlogSize() { - return total_size_; - } + std::size_t GetTotalBinlogSize() { return total_size_; } void Reset() { win_.clear(); total_size_ = 0; @@ -66,12 +61,8 @@ class SlaveNode : public RmNode { public: SlaveNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, int session_id); ~SlaveNode(); - void Lock() { - slave_mu.Lock(); - } - void Unlock() { - slave_mu.Unlock(); - } + void Lock() { slave_mu.Lock(); } + void Unlock() { slave_mu.Unlock(); } SlaveState slave_state; BinlogSyncState b_state; diff --git a/include/pika_slaveping_thread.h b/include/pika_slaveping_thread.h index 8eb0d113e2..41291db643 100644 --- a/include/pika_slaveping_thread.h +++ b/include/pika_slaveping_thread.h @@ -8,16 +8,15 @@ #include -#include "pstd/include/pstd_status.h" #include "net/include/net_cli.h" #include "net/include/net_thread.h" +#include "pstd/include/pstd_status.h" using pstd::Status; class PikaSlavepingThread : public net::Thread { public: - PikaSlavepingThread(int64_t sid) - : sid_(sid), is_first_send_(true) { + PikaSlavepingThread(int64_t sid) : sid_(sid), is_first_send_(true) { cli_ = net::NewPbCli(); cli_->set_connect_timeout(1500); set_thread_name("SlavePingThread"); @@ -36,7 +35,7 @@ class PikaSlavepingThread : public net::Thread { bool is_first_send_; int sockfd_; - net::NetCli *cli_; + net::NetCli* cli_; virtual void* ThreadMain(); }; diff --git a/include/pika_slot.h b/include/pika_slot.h index 8332003da5..5394684f28 100644 --- a/include/pika_slot.h +++ b/include/pika_slot.h @@ -10,42 +10,36 @@ class SlotsInfoCmd : public Cmd { public: - SlotsInfoCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsInfoCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsInfoCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsInfoCmd(*this); } + private: virtual void DoInitial() override; }; class SlotsHashKeyCmd : public Cmd { public: - SlotsHashKeyCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsHashKeyCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsHashKeyCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsHashKeyCmd(*this); } + private: virtual void DoInitial() override; }; class SlotsMgrtSlotAsyncCmd : public Cmd { public: - SlotsMgrtSlotAsyncCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtSlotAsyncCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtSlotAsyncCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtSlotAsyncCmd(*this); } + private: virtual void DoInitial() override; }; @@ -53,13 +47,12 @@ class SlotsMgrtSlotAsyncCmd : public Cmd { class SlotsMgrtTagSlotAsyncCmd : public Cmd { public: SlotsMgrtTagSlotAsyncCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), dest_port_(0), slot_num_(-1) {} + : Cmd(name, arity, flag), dest_port_(0), slot_num_(-1) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtTagSlotAsyncCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtTagSlotAsyncCmd(*this); } + private: virtual void DoInitial() override; std::string dest_ip_; @@ -74,14 +67,12 @@ class SlotsMgrtTagSlotAsyncCmd : public Cmd { class SlotsScanCmd : public Cmd { public: - SlotsScanCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), pattern_("*"), count_(10) {} + SlotsScanCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), pattern_("*"), count_(10) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsScanCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsScanCmd(*this); } + private: int64_t cursor_; uint32_t slotnum_; @@ -96,120 +87,100 @@ class SlotsScanCmd : public Cmd { class SlotsDelCmd : public Cmd { public: - SlotsDelCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsDelCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsDelCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsDelCmd(*this); } + private: std::vector slots_; virtual void DoInitial() override; - virtual void Clear() { - slots_.clear(); - } + virtual void Clear() { slots_.clear(); } }; class SlotsMgrtExecWrapperCmd : public Cmd { public: - SlotsMgrtExecWrapperCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtExecWrapperCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtExecWrapperCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtExecWrapperCmd(*this); } + private: std::string key_; virtual void DoInitial() override; - virtual void Clear() { - key_.clear(); - } + virtual void Clear() { key_.clear(); } }; class SlotsMgrtAsyncStatusCmd : public Cmd { public: - SlotsMgrtAsyncStatusCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtAsyncStatusCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtAsyncStatusCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtAsyncStatusCmd(*this); } + private: virtual void DoInitial() override; }; class SlotsMgrtAsyncCancelCmd : public Cmd { public: - SlotsMgrtAsyncCancelCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtAsyncCancelCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtAsyncCancelCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtAsyncCancelCmd(*this); } + private: virtual void DoInitial() override; }; class SlotsMgrtSlotCmd : public Cmd { public: - SlotsMgrtSlotCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtSlotCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtSlotCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtSlotCmd(*this); } + private: virtual void DoInitial() override; }; class SlotsMgrtTagSlotCmd : public Cmd { public: - SlotsMgrtTagSlotCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtTagSlotCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtTagSlotCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtTagSlotCmd(*this); } + private: virtual void DoInitial() override; }; class SlotsMgrtOneCmd : public Cmd { public: - SlotsMgrtOneCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtOneCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtOneCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtOneCmd(*this); } + private: virtual void DoInitial() override; }; class SlotsMgrtTagOneCmd : public Cmd { public: - SlotsMgrtTagOneCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + SlotsMgrtTagOneCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new SlotsMgrtTagOneCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new SlotsMgrtTagOneCmd(*this); } + private: virtual void DoInitial() override; }; diff --git a/include/pika_stable_log.h b/include/pika_stable_log.h index 75691bd352..d69c9a4f08 100644 --- a/include/pika_stable_log.h +++ b/include/pika_stable_log.h @@ -6,19 +6,16 @@ #ifndef PIKA_STABLE_LOG_H_ #define PIKA_STABLE_LOG_H_ -#include #include +#include #include "include/pika_binlog.h" class StableLog : public std::enable_shared_from_this { public: - StableLog(const std::string table_name, - uint32_t partition_id, const std::string& log_path); + StableLog(const std::string table_name, uint32_t partition_id, const std::string& log_path); ~StableLog(); - std::shared_ptr Logger() { - return stable_logger_; - } + std::shared_ptr Logger() { return stable_logger_; } void Leave(); void SetFirstOffset(const LogOffset& offset) { pstd::RWLock l(&offset_rwlock_, true); diff --git a/include/pika_statistic.h b/include/pika_statistic.h index e50a729a4c..cd88e093e1 100644 --- a/include/pika_statistic.h +++ b/include/pika_statistic.h @@ -47,8 +47,7 @@ struct Statistic { QpsStatistic TableStat(const std::string& table_name); std::unordered_map AllTableStat(); - void UpdateTableQps( - const std::string& table_name, const std::string& command, bool is_write); + void UpdateTableQps(const std::string& table_name, const std::string& command, bool is_write); void ResetTableLastSecQuerynum(); // statistic shows accumulated data of all tables @@ -60,4 +59,3 @@ struct Statistic { }; #endif // PIKA_STATISTIC_H_ - diff --git a/include/pika_table.h b/include/pika_table.h index bbebad572c..eb5a45078d 100644 --- a/include/pika_table.h +++ b/include/pika_table.h @@ -11,12 +11,9 @@ #include "include/pika_command.h" #include "include/pika_partition.h" -class Table : public std::enable_shared_from_this{ +class Table : public std::enable_shared_from_this
{ public: - Table(const std::string& table_name, - uint32_t partition_num, - const std::string& db_path, - const std::string& log_path); + Table(const std::string& table_name, uint32_t partition_num, const std::string& db_path, const std::string& log_path); virtual ~Table(); friend class Cmd; @@ -74,7 +71,7 @@ class Table : public std::enable_shared_from_this
{ /* * KeyScan use */ - static void DoKeyScan(void *arg); + static void DoKeyScan(void* arg); void InitKeyScan(); pstd::Mutex key_scan_protector_; KeyScanInfo key_scan_info_; @@ -91,5 +88,4 @@ struct BgTaskArg { std::shared_ptr partition; }; - #endif diff --git a/include/pika_zset.h b/include/pika_zset.h index eaa40086a8..10214009f9 100644 --- a/include/pika_zset.h +++ b/include/pika_zset.h @@ -16,19 +16,17 @@ */ class ZAddCmd : public Cmd { public: - ZAddCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ZAddCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZAddCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZAddCmd(*this); } + private: std::string key_; std::vector score_members; @@ -37,19 +35,17 @@ class ZAddCmd : public Cmd { class ZCardCmd : public Cmd { public: - ZCardCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ZCardCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZCardCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZCardCmd(*this); } + private: std::string key_; virtual void DoInitial() override; @@ -57,19 +53,17 @@ class ZCardCmd : public Cmd { class ZScanCmd : public Cmd { public: - ZScanCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), pattern_("*"), count_(10) {} + ZScanCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), pattern_("*"), count_(10) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZScanCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZScanCmd(*this); } + private: std::string key_, pattern_; int64_t cursor_, count_; @@ -82,19 +76,17 @@ class ZScanCmd : public Cmd { class ZIncrbyCmd : public Cmd { public: - ZIncrbyCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ZIncrbyCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZIncrbyCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZIncrbyCmd(*this); } + private: std::string key_, member_; double by_; @@ -103,52 +95,46 @@ class ZIncrbyCmd : public Cmd { class ZsetRangeParentCmd : public Cmd { public: - ZsetRangeParentCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag), is_ws_(false) {} + ZsetRangeParentCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), is_ws_(false) {} + protected: std::string key_; int64_t start_, stop_; bool is_ws_; virtual void DoInitial() override; - virtual void Clear() { - is_ws_ = false; - } + virtual void Clear() { is_ws_ = false; } }; class ZRangeCmd : public ZsetRangeParentCmd { public: - ZRangeCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRangeParentCmd(name, arity, flag) {} + ZRangeCmd(const std::string& name, int arity, uint16_t flag) : ZsetRangeParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRangeCmd(*this); } + private: virtual void DoInitial() override; }; class ZRevrangeCmd : public ZsetRangeParentCmd { public: - ZRevrangeCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRangeParentCmd(name, arity, flag) {} + ZRevrangeCmd(const std::string& name, int arity, uint16_t flag) : ZsetRangeParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRevrangeCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRevrangeCmd(*this); } + private: virtual void DoInitial() override; }; @@ -157,6 +143,7 @@ class ZsetRangebyscoreParentCmd : public Cmd { public: ZsetRangebyscoreParentCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), left_close_(true), right_close_(true), with_scores_(false), offset_(0), count_(-1) {} + protected: std::string key_; double min_score_, max_score_; @@ -173,19 +160,17 @@ class ZsetRangebyscoreParentCmd : public Cmd { class ZRangebyscoreCmd : public ZsetRangebyscoreParentCmd { public: - ZRangebyscoreCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRangebyscoreParentCmd(name, arity, flag) {} + ZRangebyscoreCmd(const std::string& name, int arity, uint16_t flag) : ZsetRangebyscoreParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRangebyscoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRangebyscoreCmd(*this); } + private: virtual void DoInitial() override; }; @@ -200,11 +185,10 @@ class ZRevrangebyscoreCmd : public ZsetRangebyscoreParentCmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRevrangebyscoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRevrangebyscoreCmd(*this); } + private: virtual void DoInitial() override; }; @@ -219,11 +203,10 @@ class ZCountCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZCountCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZCountCmd(*this); } + private: std::string key_; double min_score_, max_score_; @@ -237,19 +220,17 @@ class ZCountCmd : public Cmd { class ZRemCmd : public Cmd { public: - ZRemCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ZRemCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRemCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRemCmd(*this); } + private: std::string key_; std::vector members_; @@ -260,6 +241,7 @@ class ZsetUIstoreParentCmd : public Cmd { public: ZsetUIstoreParentCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), aggregate_(storage::SUM) {} + protected: std::string dest_key_; int64_t num_keys_; @@ -267,43 +249,37 @@ class ZsetUIstoreParentCmd : public Cmd { std::vector keys_; std::vector weights_; virtual void DoInitial() override; - virtual void Clear() { - aggregate_ = storage::SUM; - } + virtual void Clear() { aggregate_ = storage::SUM; } }; class ZUnionstoreCmd : public ZsetUIstoreParentCmd { public: - ZUnionstoreCmd(const std::string& name, int arity, uint16_t flag) - : ZsetUIstoreParentCmd(name, arity, flag) {} + ZUnionstoreCmd(const std::string& name, int arity, uint16_t flag) : ZsetUIstoreParentCmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZUnionstoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZUnionstoreCmd(*this); } + private: virtual void DoInitial() override; }; class ZInterstoreCmd : public ZsetUIstoreParentCmd { public: - ZInterstoreCmd(const std::string& name, int arity, uint16_t flag) - : ZsetUIstoreParentCmd(name, arity, flag) {} + ZInterstoreCmd(const std::string& name, int arity, uint16_t flag) : ZsetUIstoreParentCmd(name, arity, flag) {} virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZInterstoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZInterstoreCmd(*this); } + private: virtual void DoInitial() override; }; class ZsetRankParentCmd : public Cmd { public: - ZsetRankParentCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ZsetRankParentCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} + protected: std::string key_, member_; virtual void DoInitial() override; @@ -311,67 +287,61 @@ class ZsetRankParentCmd : public Cmd { class ZRankCmd : public ZsetRankParentCmd { public: - ZRankCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRankParentCmd(name, arity, flag) {} + ZRankCmd(const std::string& name, int arity, uint16_t flag) : ZsetRankParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRankCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRankCmd(*this); } + private: virtual void DoInitial() override; }; class ZRevrankCmd : public ZsetRankParentCmd { public: - ZRevrankCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRankParentCmd(name, arity, flag) {} + ZRevrankCmd(const std::string& name, int arity, uint16_t flag) : ZsetRankParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRevrankCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRevrankCmd(*this); } + private: virtual void DoInitial() override; }; class ZScoreCmd : public ZsetRankParentCmd { public: - ZScoreCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRankParentCmd(name, arity, flag) {} + ZScoreCmd(const std::string& name, int arity, uint16_t flag) : ZsetRankParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZScoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZScoreCmd(*this); } + private: std::string key_, member_; virtual void DoInitial() override; }; - class ZsetRangebylexParentCmd : public Cmd { public: ZsetRangebylexParentCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag), left_close_(true), right_close_(true), offset_(0), count_(-1) {} + protected: std::string key_, min_member_, max_member_; bool left_close_, right_close_; @@ -386,39 +356,35 @@ class ZsetRangebylexParentCmd : public Cmd { class ZRangebylexCmd : public ZsetRangebylexParentCmd { public: - ZRangebylexCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRangebylexParentCmd(name, arity, flag) {} + ZRangebylexCmd(const std::string& name, int arity, uint16_t flag) : ZsetRangebylexParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRangebylexCmd(*this); - } - private: + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRangebylexCmd(*this); } + + private: virtual void DoInitial() override; }; class ZRevrangebylexCmd : public ZsetRangebylexParentCmd { public: - ZRevrangebylexCmd(const std::string& name, int arity, uint16_t flag) - : ZsetRangebylexParentCmd(name, arity, flag) {} + ZRevrangebylexCmd(const std::string& name, int arity, uint16_t flag) : ZsetRangebylexParentCmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRevrangebylexCmd(*this); - } - private: + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRevrangebylexCmd(*this); } + + private: virtual void DoInitial() override; }; @@ -432,35 +398,30 @@ class ZLexcountCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZLexcountCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZLexcountCmd(*this); } + private: std::string key_, min_member_, max_member_; bool left_close_, right_close_; virtual void DoInitial() override; - virtual void Clear() { - left_close_ = right_close_ = true; - } + virtual void Clear() { left_close_ = right_close_ = true; } }; class ZRemrangebyrankCmd : public Cmd { public: - ZRemrangebyrankCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} + ZRemrangebyrankCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} virtual std::vector current_key() const { std::vector res; res.push_back(key_); return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRemrangebyrankCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRemrangebyrankCmd(*this); } + private: std::string key_; int64_t start_rank_, stop_rank_; @@ -477,19 +438,16 @@ class ZRemrangebyscoreCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRemrangebyscoreCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRemrangebyscoreCmd(*this); } + private: std::string key_; double min_score_, max_score_; bool left_close_, right_close_; virtual void DoInitial() override; - virtual void Clear() { - left_close_ = right_close_ = true; - } + virtual void Clear() { left_close_ = right_close_ = true; } }; class ZRemrangebylexCmd : public Cmd { @@ -502,36 +460,31 @@ class ZRemrangebylexCmd : public Cmd { return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZRemrangebylexCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZRemrangebylexCmd(*this); } + private: std::string key_; std::string min_member_, max_member_; bool left_close_, right_close_; virtual void DoInitial() override; - virtual void Clear() { - left_close_ = right_close_ = true; - } + virtual void Clear() { left_close_ = right_close_ = true; } }; class ZPopmaxCmd : public Cmd { public: - ZPopmaxCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} - virtual std::vector current_key() const { + ZPopmaxCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} + virtual std::vector current_key() const { std::vector res; res.emplace_back(key_); - return res; + return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZPopmaxCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZPopmaxCmd(*this); } + private: virtual void DoInitial() override; std::string key_; @@ -540,19 +493,17 @@ class ZPopmaxCmd : public Cmd { class ZPopminCmd : public Cmd { public: - ZPopminCmd(const std::string& name, int arity, uint16_t flag) - : Cmd(name, arity, flag) {} - virtual std::vector current_key() const { + ZPopminCmd(const std::string& name, int arity, uint16_t flag) : Cmd(name, arity, flag) {} + virtual std::vector current_key() const { std::vector res; res.push_back(key_); - return res; + return res; } virtual void Do(std::shared_ptr partition = nullptr); - virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys) {}; - virtual void Merge() {}; - virtual Cmd* Clone() override { - return new ZPopminCmd(*this); - } + virtual void Split(std::shared_ptr partition, const HintKeys& hint_keys){}; + virtual void Merge(){}; + virtual Cmd* Clone() override { return new ZPopminCmd(*this); } + private: virtual void DoInitial() override; std::string key_; diff --git a/pika-tools/aof_to_pika/include/aof_info.h b/pika-tools/aof_to_pika/include/aof_info.h index e70d9382d3..658cb27982 100644 --- a/pika-tools/aof_to_pika/include/aof_info.h +++ b/pika-tools/aof_to_pika/include/aof_info.h @@ -3,21 +3,20 @@ #include -#define AOF_LOG_DEBUG 1 -#define AOF_LOG_TRACE 2 -#define AOF_LOG_INFO 3 -#define AOF_LOG_WARN 4 -#define AOF_LOG_ERR 5 -#define AOF_LOG_FATAL 6 +#define AOF_LOG_DEBUG 1 +#define AOF_LOG_TRACE 2 +#define AOF_LOG_INFO 3 +#define AOF_LOG_WARN 4 +#define AOF_LOG_ERR 5 +#define AOF_LOG_FATAL 6 -#define LOG_FATAL(content) info_print(AOF_LOG_FATAL, content) -#define LOG_ERR(content) info_print(AOF_LOG_ERR, content) -#define LOG_WARN(content) info_print(AOF_LOG_WARN, content) -#define LOG_INFO(content) info_print(AOF_LOG_INFO, content) -#define LOG_TRACE(content) info_print(AOF_LOG_TRACE, content) -#define LOG_DEBUG(content) info_print(AOF_LOG_DEBUG, content) +#define LOG_FATAL(content) info_print(AOF_LOG_FATAL, content) +#define LOG_ERR(content) info_print(AOF_LOG_ERR, content) +#define LOG_WARN(content) info_print(AOF_LOG_WARN, content) +#define LOG_INFO(content) info_print(AOF_LOG_INFO, content) +#define LOG_TRACE(content) info_print(AOF_LOG_TRACE, content) +#define LOG_DEBUG(content) info_print(AOF_LOG_DEBUG, content) void set_info_level(int); void info_print(int, const std::string&); #endif - diff --git a/pika-tools/aof_to_pika/include/aof_lock.h b/pika-tools/aof_to_pika/include/aof_lock.h index 2424f6e803..ac0cbb7fdd 100644 --- a/pika-tools/aof_to_pika/include/aof_lock.h +++ b/pika-tools/aof_to_pika/include/aof_lock.h @@ -4,33 +4,34 @@ class CondVar; class Mutex { - public: - Mutex(); - ~Mutex(); + public: + Mutex(); + ~Mutex(); - void Lock(); - void Unlock(); - void AssertHeld() { } + void Lock(); + void Unlock(); + void AssertHeld() {} - private: - friend class CondVar; - pthread_mutex_t mu_; + private: + friend class CondVar; + pthread_mutex_t mu_; - // No copying - Mutex(const Mutex&); - void operator=(const Mutex&); + // No copying + Mutex(const Mutex&); + void operator=(const Mutex&); }; class CondVar { - public: - explicit CondVar(Mutex* mu); - ~CondVar(); - void Wait(); - void Signal(); - void SignalAll(); - private: - pthread_cond_t cv_; - Mutex* mu_; + public: + explicit CondVar(Mutex* mu); + ~CondVar(); + void Wait(); + void Signal(); + void SignalAll(); + + private: + pthread_cond_t cv_; + Mutex* mu_; }; #endif // AOF_LOCK_H diff --git a/pika-tools/aof_to_pika/include/aof_sender.h b/pika-tools/aof_to_pika/include/aof_sender.h index 3c247e6069..28fb8b2ae2 100644 --- a/pika-tools/aof_to_pika/include/aof_sender.h +++ b/pika-tools/aof_to_pika/include/aof_sender.h @@ -1,52 +1,53 @@ #ifndef AOF_SENDER_H #define AOF_SENDER_H -#include #include -#include "aof_lock.h" +#include #include "aof_info.h" +#include "aof_lock.h" -#define RM_NONE 0 -#define RM_READBLE 1 +#define RM_NONE 0 +#define RM_READBLE 1 #define RM_WRITABLE 2 -#define RM_RECONN 4 +#define RM_RECONN 4 #define READ_BUF_MAX 100 #define MSG_BLOCK_MAX 512 * 1024 -typedef struct ConnInfo{ - ConnInfo(){} - ConnInfo(const std::string &h, const std::string &p, const std::string &a):host_(h),port_(p),auth_(a){} - std::string host_; - std::string port_; - std::string auth_; +typedef struct ConnInfo { + ConnInfo() {} + ConnInfo(const std::string& h, const std::string& p, const std::string& a) : host_(h), port_(p), auth_(a) {} + std::string host_; + std::string port_; + std::string auth_; } ConnInfo; - -class AOFSender -{ -public: - AOFSender():buf_wcond_(&buf_mutex_), buf_rcond_(&buf_mutex_){ sockfd_ = -1; nsucc_ = nfail_ = 0; } - ~AOFSender(); - bool rconnect(const std::string&, const std::string&, const std::string&); - bool message_add(const std::string&); - bool process(); - void print_result(); - -private: - int sockfd_; - int nsucc_, nfail_; - ConnInfo *conn_info_; - Mutex buf_mutex_; - CondVar buf_wcond_; - CondVar buf_rcond_; - std::deque read_buffer_; - std::string to_send_; - std::string current_bulk_; - bool message_get_(); - bool check_succ_(const std::string&, long&, long&); - int mask_wait_(int fd, int mask, long long milliseconds); - bool set_nonblock_(int fd); +class AOFSender { + public: + AOFSender() : buf_wcond_(&buf_mutex_), buf_rcond_(&buf_mutex_) { + sockfd_ = -1; + nsucc_ = nfail_ = 0; + } + ~AOFSender(); + bool rconnect(const std::string&, const std::string&, const std::string&); + bool message_add(const std::string&); + bool process(); + void print_result(); + + private: + int sockfd_; + int nsucc_, nfail_; + ConnInfo* conn_info_; + Mutex buf_mutex_; + CondVar buf_wcond_; + CondVar buf_rcond_; + std::deque read_buffer_; + std::string to_send_; + std::string current_bulk_; + bool message_get_(); + bool check_succ_(const std::string&, long&, long&); + int mask_wait_(int fd, int mask, long long milliseconds); + bool set_nonblock_(int fd); }; #endif diff --git a/pika-tools/aof_to_pika/src/aof_info.cc b/pika-tools/aof_to_pika/src/aof_info.cc index 3bc86b8255..bb635a79b2 100644 --- a/pika-tools/aof_to_pika/src/aof_info.cc +++ b/pika-tools/aof_to_pika/src/aof_info.cc @@ -1,19 +1,16 @@ -#include #include "aof_info.h" +#include short aof_info_level_ = AOF_LOG_INFO; -void set_info_level(int l){ - aof_info_level_ = l; -} +void set_info_level(int l) { aof_info_level_ = l; } -void info_print(int l, const std::string &content) { - if (l > AOF_LOG_FATAL || l < AOF_LOG_DEBUG || content.empty()) return; +void info_print(int l, const std::string& content) { + if (l > AOF_LOG_FATAL || l < AOF_LOG_DEBUG || content.empty()) return; - if (l < aof_info_level_) return; - if (l >= AOF_LOG_ERR) - std::cerr << content << std::endl; - else - std::cout << content << std::endl; + if (l < aof_info_level_) return; + if (l >= AOF_LOG_ERR) + std::cerr << content << std::endl; + else + std::cout << content << std::endl; } - diff --git a/pika-tools/aof_to_pika/src/aof_lock.cc b/pika-tools/aof_to_pika/src/aof_lock.cc index f56386e3d6..d028de38a9 100644 --- a/pika-tools/aof_to_pika/src/aof_lock.cc +++ b/pika-tools/aof_to_pika/src/aof_lock.cc @@ -1,16 +1,15 @@ #include #include -#include #include +#include #include "aof_lock.h" - -static void PthreadCall(const std::string &label, int result) { - if (result != 0) { - std::cout << "pthread " << label << " : " << result << std::endl; - abort(); - } +static void PthreadCall(const std::string& label, int result) { + if (result != 0) { + std::cout << "pthread " << label << " : " << result << std::endl; + abort(); + } } Mutex::Mutex() { PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL)); } @@ -21,21 +20,12 @@ void Mutex::Lock() { PthreadCall("lock", pthread_mutex_lock(&mu_)); } void Mutex::Unlock() { PthreadCall("unlock", pthread_mutex_unlock(&mu_)); } -CondVar::CondVar(Mutex* mu) - : mu_(mu) { - PthreadCall("init cv", pthread_cond_init(&cv_, NULL)); - } +CondVar::CondVar(Mutex* mu) : mu_(mu) { PthreadCall("init cv", pthread_cond_init(&cv_, NULL)); } CondVar::~CondVar() { PthreadCall("destroy cv", pthread_cond_destroy(&cv_)); } -void CondVar::Wait() { - PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_)); -} +void CondVar::Wait() { PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_)); } -void CondVar::Signal() { - PthreadCall("signal", pthread_cond_signal(&cv_)); -} +void CondVar::Signal() { PthreadCall("signal", pthread_cond_signal(&cv_)); } -void CondVar::SignalAll() { - PthreadCall("broadcast", pthread_cond_broadcast(&cv_)); -} +void CondVar::SignalAll() { PthreadCall("broadcast", pthread_cond_broadcast(&cv_)); } diff --git a/pika-tools/aof_to_pika/src/aof_reader.cc b/pika-tools/aof_to_pika/src/aof_reader.cc index 91bb11bb51..9c1354efb0 100644 --- a/pika-tools/aof_to_pika/src/aof_reader.cc +++ b/pika-tools/aof_to_pika/src/aof_reader.cc @@ -1,202 +1,192 @@ -#include -#include +#include #include +#include +#include #include -#include -#include +#include #include #include -#include +#include #include "aof_sender.h" #define VERSION "1.0.0" #define EOFMSG "EOAOF" static std::time_t begin_time; -static AOFSender *sender = NULL; - -static void split_send(const std::string &line){ - static std::string send_buf_; - if (EOFMSG == line){ - if (!send_buf_.empty()) { // end of the AOF file - sender->message_add(send_buf_); - send_buf_.clear(); - } - return; - } - - // Record - send_buf_ += line; - - // Split and send - std::size_t pos = 0; - std::string str_block; - while (send_buf_.size() - pos >= MSG_BLOCK_MAX){ - str_block.assign(send_buf_.substr(pos, MSG_BLOCK_MAX)); - sender->message_add(str_block); - pos += MSG_BLOCK_MAX; +static AOFSender* sender = NULL; + +static void split_send(const std::string& line) { + static std::string send_buf_; + if (EOFMSG == line) { + if (!send_buf_.empty()) { // end of the AOF file + sender->message_add(send_buf_); + send_buf_.clear(); } - if (pos != 0) - send_buf_.assign(send_buf_.substr(pos)); + return; + } + + // Record + send_buf_ += line; + + // Split and send + std::size_t pos = 0; + std::string str_block; + while (send_buf_.size() - pos >= MSG_BLOCK_MAX) { + str_block.assign(send_buf_.substr(pos, MSG_BLOCK_MAX)); + sender->message_add(str_block); + pos += MSG_BLOCK_MAX; + } + if (pos != 0) send_buf_.assign(send_buf_.substr(pos)); } -static void print_cur_time(){ - std::time_t now = time(0); - struct tm * time = localtime( &now); - std::stringstream ss; - ss <<(time->tm_mon + 1) << '-' - << time->tm_mday << " " - << time->tm_hour << ":" - << time->tm_min << "." - << time->tm_sec; - LOG_INFO(ss.str()); - +static void print_cur_time() { + std::time_t now = time(0); + struct tm* time = localtime(&now); + std::stringstream ss; + ss << (time->tm_mon + 1) << '-' << time->tm_mday << " " << time->tm_hour << ":" << time->tm_min << "." + << time->tm_sec; + LOG_INFO(ss.str()); } -static int file_read(const std::string &path) -{ - std::ifstream ifs(path.c_str(), std::ios::binary | std::ios::in); - if (!ifs || !ifs.is_open()){ - LOG_ERR("ERROR: opening aof file: " + path); - return 1; +static int file_read(const std::string& path) { + std::ifstream ifs(path.c_str(), std::ios::binary | std::ios::in); + if (!ifs || !ifs.is_open()) { + LOG_ERR("ERROR: opening aof file: " + path); + return 1; + } + + LOG_INFO("Begin reading.... "); + print_cur_time(); + + std::ios::streampos gpos = ifs.tellg(); + std::string line; + bool dirty = false; + while (true) { + ifs.clear(); + ifs.seekg(gpos); + + while (std::getline(ifs, line)) { + dirty = true; + gpos = ifs.tellg(); + split_send(line + '\n'); + line.clear(); } - LOG_INFO("Begin reading.... "); - print_cur_time(); - - std::ios::streampos gpos = ifs.tellg(); - std::string line; - bool dirty = false; - while(true) - { - ifs.clear(); - ifs.seekg(gpos); - - while(std::getline(ifs, line)){ - dirty = true; - gpos = ifs.tellg(); - split_send(line + '\n'); - line.clear(); - } - - if (!ifs.eof()) { - break; - } - - if (dirty) { - // Flush current send buf - split_send(EOFMSG); - dirty = false; - print_cur_time(); - } else { - LOG_INFO("Read the end of aof..."); - } - usleep(1000 * 1000); + if (!ifs.eof()) { + break; } - ifs.close(); - return 0; + if (dirty) { + // Flush current send buf + split_send(EOFMSG); + dirty = false; + print_cur_time(); + } else { + LOG_INFO("Read the end of aof..."); + } + usleep(1000 * 1000); + } + + ifs.close(); + return 0; } -static void* msg_process(void *p){ - sender->process(); - pthread_exit(NULL); +static void* msg_process(void* p) { + sender->process(); + pthread_exit(NULL); } void intHandler(int sig) { - LOG_ERR("Catched"); - std::time_t current = time(0); - double diff = difftime(current, begin_time); - std::stringstream ss; - ss << "Elapse time(s): " << diff; - LOG_ERR(ss.str()); - exit(0); + LOG_ERR("Catched"); + std::time_t current = time(0); + double diff = difftime(current, begin_time); + std::stringstream ss; + ss << "Elapse time(s): " << diff; + LOG_ERR(ss.str()); + exit(0); } -static void usage() -{ - fprintf(stderr, - "aof transfor tool %s\n" - "Parameters: \n" - " -i: aof file \n" - " -h: the target host \n" - " -p: the target port \n" - " -a: the target auth \n" - " -v: show more information\n" - "Example: ./aof_to_pika -i ./appendonly.aof -h 128.0.0.1 -p 6379 -a abc -v\n", VERSION - ); +static void usage() { + fprintf(stderr, + "aof transfor tool %s\n" + "Parameters: \n" + " -i: aof file \n" + " -h: the target host \n" + " -p: the target port \n" + " -a: the target auth \n" + " -v: show more information\n" + "Example: ./aof_to_pika -i ./appendonly.aof -h 128.0.0.1 -p 6379 -a abc -v\n", + VERSION); } -int main(int argc, char **argv) -{ - char c; - std::string path, host, port, auth; - bool verbose = false; - while (-1 != (c = getopt(argc, argv, "i:h:p:a:v"))) { - switch (c) { - case 'i': - path.assign(optarg); - break; - case 'h': - host.assign(optarg); - break; - case 'p': - port.assign(optarg); - break; - case 'a': - auth.assign(optarg); - break; - case 'v': - verbose = true; - break; - default: - usage(); - return 0; - } - } - - if (path.empty() || host.empty() || port.empty()) { +int main(int argc, char** argv) { + char c; + std::string path, host, port, auth; + bool verbose = false; + while (-1 != (c = getopt(argc, argv, "i:h:p:a:v"))) { + switch (c) { + case 'i': + path.assign(optarg); + break; + case 'h': + host.assign(optarg); + break; + case 'p': + port.assign(optarg); + break; + case 'a': + auth.assign(optarg); + break; + case 'v': + verbose = true; + break; + default: usage(); return 0; } + } - int info_level = verbose ? AOF_LOG_TRACE : AOF_LOG_INFO; - set_info_level(info_level); - - std::ifstream ifs(path.c_str(), std::ios::binary); - if(!ifs){ - LOG_ERR("Error aof file path"); - usage(); - return 0; - } - ifs.close(); - - sender = new AOFSender(); - if (false == sender->rconnect(host, port, auth)) { - LOG_ERR("Failed to connect remote server! host: " + host + " port : " + port); - delete sender; - return -1; - } + if (path.empty() || host.empty() || port.empty()) { + usage(); + return 0; + } - // We need output something when ctrl c catched - begin_time = time(0); - signal(SIGINT, intHandler); - - int ret = 0; - pthread_t send_thread; - // Send thread - ret = pthread_create(&send_thread, NULL, msg_process, NULL); - if (0 != ret) - { - LOG_ERR("Failed to create assist_watcher_thread!"); - delete sender; - return -1; - } + int info_level = verbose ? AOF_LOG_TRACE : AOF_LOG_INFO; + set_info_level(info_level); - // Main thread - file_read(path); + std::ifstream ifs(path.c_str(), std::ios::binary); + if (!ifs) { + LOG_ERR("Error aof file path"); + usage(); + return 0; + } + ifs.close(); - pthread_join(send_thread, NULL); + sender = new AOFSender(); + if (false == sender->rconnect(host, port, auth)) { + LOG_ERR("Failed to connect remote server! host: " + host + " port : " + port); delete sender; - return 0; + return -1; + } + + // We need output something when ctrl c catched + begin_time = time(0); + signal(SIGINT, intHandler); + + int ret = 0; + pthread_t send_thread; + // Send thread + ret = pthread_create(&send_thread, NULL, msg_process, NULL); + if (0 != ret) { + LOG_ERR("Failed to create assist_watcher_thread!"); + delete sender; + return -1; + } + + // Main thread + file_read(path); + + pthread_join(send_thread, NULL); + delete sender; + return 0; } diff --git a/pika-tools/aof_to_pika/src/aof_sender.cc b/pika-tools/aof_to_pika/src/aof_sender.cc index 6109d8703b..cbbc3f3231 100644 --- a/pika-tools/aof_to_pika/src/aof_sender.cc +++ b/pika-tools/aof_to_pika/src/aof_sender.cc @@ -1,19 +1,19 @@ -#include -#include #include -#include -#include -#include -#include +#include #include #include -#include +#include +#include +#include +#include +#include #include +#include -#include "aof_sender.h" #include "aof_info.h" +#include "aof_sender.h" -bool AOFSender::rconnect(const std::string &host, const std::string &port, const std::string &auth){ +bool AOFSender::rconnect(const std::string& host, const std::string& port, const std::string& auth) { if (host.empty() || port.empty()) return false; int s = -1, ret; struct addrinfo hints, *servinfo, *p; @@ -26,21 +26,20 @@ bool AOFSender::rconnect(const std::string &host, const std::string &port, const } for (p = servinfo; p != NULL; p = p->ai_next) { - if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1) - continue; - //connect + if ((s = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) continue; + // connect if (connect(s, p->ai_addr, p->ai_addrlen) < 0) { close(s); break; } - //set non block + // set non block if (!set_nonblock_(s)) { LOG_ERR("Failed to set non block"); close(s); break; } sockfd_ = s; - if (!auth.empty()){ + if (!auth.empty()) { std::stringstream auth_info; auth_info << "*2\r\n$4\r\nauth\r\n$" << auth.size() << "\r\n" << auth << "\r\n"; to_send_.assign(auth_info.str()); @@ -54,7 +53,7 @@ bool AOFSender::rconnect(const std::string &host, const std::string &port, const return false; } -AOFSender::~AOFSender(){ +AOFSender::~AOFSender() { buf_mutex_.Lock(); buf_rcond_.SignalAll(); buf_wcond_.SignalAll(); @@ -63,11 +62,11 @@ AOFSender::~AOFSender(){ close(sockfd_); } -bool AOFSender::message_add(const std::string &message){ +bool AOFSender::message_add(const std::string& message) { if (message.empty()) return false; buf_mutex_.Lock(); - while (read_buffer_.size() >= READ_BUF_MAX){ + while (read_buffer_.size() >= READ_BUF_MAX) { LOG_DEBUG("Reader waiting for write buffer."); buf_wcond_.Wait(); } @@ -80,15 +79,13 @@ bool AOFSender::message_add(const std::string &message){ return true; } -bool AOFSender::message_get_(){ +bool AOFSender::message_get_() { buf_mutex_.Lock(); - while (read_buffer_.size() == 0) - { + while (read_buffer_.size() == 0) { LOG_DEBUG("Sender waiting for read buffer."); - buf_rcond_.Wait(); // awake when the the wait send queue not empty + buf_rcond_.Wait(); // awake when the the wait send queue not empty } - if (read_buffer_.size() > 0) - { + if (read_buffer_.size() > 0) { to_send_ = read_buffer_.front(); read_buffer_.pop_front(); buf_wcond_.SignalAll(); @@ -98,25 +95,25 @@ bool AOFSender::message_get_(){ return true; } - -bool AOFSender::process(){ - if (sockfd_ == -1){ +bool AOFSender::process() { + if (sockfd_ == -1) { LOG_ERR("Invalid socket fd!"); return false; } char ibuf[1024 * 16]; memset(&ibuf, 0, sizeof(ibuf)); - long nsucc = 0, nfail = 0, inter = 0;; + long nsucc = 0, nfail = 0, inter = 0; + ; while (true) { - int mask = RM_READBLE | RM_WRITABLE; + int mask = RM_READBLE | RM_WRITABLE; mask = mask_wait_(sockfd_, mask, 1000); if (mask & RM_RECONN) { close(sockfd_); if (false == rconnect(conn_info_->host_, conn_info_->port_, conn_info_->auth_)) { - LOG_ERR("Failed to reconnect remote server! host: " + conn_info_->host_ + " port : " + conn_info_->port_ + - " try again 1 second later!"); + LOG_ERR("Failed to reconnect remote server! host: " + conn_info_->host_ + " port : " + conn_info_->port_ + + " try again 1 second later!"); usleep(1000000); } } else if (mask & RM_READBLE) { @@ -137,27 +134,30 @@ bool AOFSender::process(){ } while (count > 0); // Success read data - if (!reply.empty()){ + if (!reply.empty()) { std::stringstream ss; if (check_succ_(reply, nsucc, nfail)) { - ss << "Process OK!" << " SUCC : " << nsucc << ", FAILED: " << nfail; + ss << "Process OK!" + << " SUCC : " << nsucc << ", FAILED: " << nfail; if ((nsucc - inter) > 10000) { - LOG_INFO(ss.str()); inter = nsucc; - } else { LOG_TRACE(ss.str()); } + LOG_INFO(ss.str()); + inter = nsucc; + } else { + LOG_TRACE(ss.str()); + } } else { - ss << "Process Failed current bulk :[" << current_bulk_ - << "] size: " << current_bulk_.size() << ", remain send size: " << to_send_.size() - << ", with reply : [" << reply + "]"; + ss << "Process Failed current bulk :[" << current_bulk_ << "] size: " << current_bulk_.size() + << ", remain send size: " << to_send_.size() << ", with reply : [" << reply + "]"; LOG_ERR(ss.str()); ss.str(std::string()); ss << "SUCC : " << nsucc << ", FAILED: " << nfail; LOG_INFO(ss.str()); - //return -1; + // return -1; } } - } else if (mask & RM_WRITABLE) { - //Read from queue - if (to_send_.empty()) { + } else if (mask & RM_WRITABLE) { + // Read from queue + if (to_send_.empty()) { message_get_(); current_bulk_ = to_send_; } @@ -176,12 +176,11 @@ bool AOFSender::process(){ } total_nwritten += nwritten; - } while((unsigned)total_nwritten < to_send_.size()); + } while ((unsigned)total_nwritten < to_send_.size()); to_send_.assign(to_send_.substr(total_nwritten)); } } - } return 0; } @@ -197,12 +196,11 @@ int AOFSender::mask_wait_(int fd, int mask, long long milliseconds) { pfd.events |= POLLERR; pfd.events |= POLLHUP; - switch (poll(&pfd, 1, milliseconds)) { case 1: if (pfd.revents & POLLIN) retmask |= RM_READBLE; if (pfd.revents & POLLOUT) retmask |= RM_WRITABLE; - if (pfd.revents & POLLERR || pfd.revents & POLLHUP){ + if (pfd.revents & POLLERR || pfd.revents & POLLHUP) { retmask |= RM_RECONN; close(fd); } @@ -236,18 +234,20 @@ bool AOFSender::set_nonblock_(int fd) { return true; } -bool AOFSender::check_succ_(const std::string &reply, long &succ, long &fail){ +bool AOFSender::check_succ_(const std::string& reply, long& succ, long& fail) { if (reply.empty()) return false; std::string line; std::stringstream ss(reply); int tmp_fail = fail; - while(std::getline(ss, line)){ + while (std::getline(ss, line)) { if (line.empty() || line[0] == '\r') continue; - if (line.find("ERR") != std::string::npos) fail++; - else succ++; + if (line.find("ERR") != std::string::npos) + fail++; + else + succ++; } - //skip last empty line + // skip last empty line if (tmp_fail != fail) return false; return true; @@ -255,6 +255,7 @@ bool AOFSender::check_succ_(const std::string &reply, long &succ, long &fail){ void AOFSender::print_result() { std::stringstream ss; - ss << "Process FINISH!" << " SUCC : " << nsucc_ << ", FAILED: " << nfail_; + ss << "Process FINISH!" + << " SUCC : " << nsucc_ << ", FAILED: " << nfail_; LOG_WARN(ss.str()); } diff --git a/pika-tools/benchmark_client/benchmark_client.cc b/pika-tools/benchmark_client/benchmark_client.cc index a60da253e6..b0c26fbbaa 100644 --- a/pika-tools/benchmark_client/benchmark_client.cc +++ b/pika-tools/benchmark_client/benchmark_client.cc @@ -1,63 +1,56 @@ +#include #include #include -#include #include -#include -#include +#include #include -#include +#include +#include #include #include -#include +#include #include "hiredis.h" -#include "slash/include/slash_string.h" #include "slash/include/slash_status.h" +#include "slash/include/slash_string.h" -#define TIME_OF_LOOP 1000000 +#define TIME_OF_LOOP 1000000 -using std::default_random_engine; using slash::Status; - +using std::default_random_engine; Status RunSetCommand(redisContext* c); Status RunSetCommandPipeline(redisContext* c); Status RunZAddCommand(redisContext* c); -struct ThreadArg{ +struct ThreadArg { pthread_t tid; std::string table_name; size_t idx; }; -enum TransmitMode { - kNormal = 0, - kPipeline =1 -}; +enum TransmitMode { kNormal = 0, kPipeline = 1 }; -static int32_t last_seed = 0; +static int32_t last_seed = 0; std::string tables_str = "0"; std::vector tables; -std::string hostname = "127.0.0.1"; -int port = 9221; -std::string password = ""; -uint32_t payload_size = 50; -uint32_t number_of_request = 100000; -uint32_t thread_num_each_table = 1; -TransmitMode transmit_mode = kNormal; -int pipeline_num = 0; +std::string hostname = "127.0.0.1"; +int port = 9221; +std::string password = ""; +uint32_t payload_size = 50; +uint32_t number_of_request = 100000; +uint32_t thread_num_each_table = 1; +TransmitMode transmit_mode = kNormal; +int pipeline_num = 0; void GenerateRandomString(int32_t len, std::string* target) { target->clear(); - char c_map[67] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', - 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', - 'E', 'F', 'G', 'H', 'I', 'G', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', - 'Y', 'Z', '~', '!', '@', '#', '$', '%', '^', '&', - '*', '(', ')', '-', '=', '_', '+'}; + char c_map[67] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'g', 'k', 'l', 'm', 'n', 'o', 'p', 'q', + 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', + 'I', 'G', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', + 'Z', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+'}; default_random_engine e; for (int i = 0; i < len; i++) { @@ -96,11 +89,11 @@ void Usage() { std::vector thread_args; -void *ThreadMain(void* arg) { +void* ThreadMain(void* arg) { ThreadArg* ta = reinterpret_cast(arg); - redisContext *c; - redisReply *res = NULL; - struct timeval timeout = { 1, 500000 }; // 1.5 seconds + redisContext* c; + redisReply* res = NULL; + struct timeval timeout = {1, 500000}; // 1.5 seconds c = redisConnectWithTimeout(hostname.data(), port, timeout); if (c == NULL || c->err) { @@ -116,9 +109,7 @@ void *ThreadMain(void* arg) { if (!password.empty()) { const char* auth_argv[2] = {"AUTH", password.data()}; size_t auth_argv_len[2] = {4, password.size()}; - res = reinterpret_cast(redisCommandArgv(c, - 2, - reinterpret_cast(auth_argv), + res = reinterpret_cast(redisCommandArgv(c, 2, reinterpret_cast(auth_argv), reinterpret_cast(auth_argv_len))); if (res == NULL) { printf("Thread %lu Auth Failed, Get reply Error\n", ta->tid); @@ -138,10 +129,8 @@ void *ThreadMain(void* arg) { } const char* select_argv[2] = {"SELECT", ta->table_name.data()}; - size_t select_argv_len[2] = {6, ta->table_name.size()}; - res = reinterpret_cast(redisCommandArgv(c, - 2, - reinterpret_cast(select_argv), + size_t select_argv_len[2] = {6, ta->table_name.size()}; + res = reinterpret_cast(redisCommandArgv(c, 2, reinterpret_cast(select_argv), reinterpret_cast(select_argv_len))); if (res == NULL) { printf("Thread %lu Select Table %s Failed, Get reply Error\n", ta->tid, ta->table_name.data()); @@ -183,7 +172,7 @@ void *ThreadMain(void* arg) { } Status RunSetCommandPipeline(redisContext* c) { - redisReply *res = NULL; + redisReply* res = NULL; for (size_t idx = 0; idx < number_of_request; (idx += pipeline_num)) { const char* argv[3] = {"SET", NULL, NULL}; size_t argv_len[3] = {3, 0, 0}; @@ -198,12 +187,12 @@ Status RunSetCommandPipeline(redisContext* c) { GenerateRandomString(rand_num, &key); GenerateRandomString(payload_size, &value); - argv[1] = key.c_str(); argv_len[1] = key.size(); - argv[2] = value.c_str(); argv_len[2] = value.size(); + argv[1] = key.c_str(); + argv_len[1] = key.size(); + argv[2] = value.c_str(); + argv_len[2] = value.size(); - if (redisAppendCommandArgv(c, - 3, - reinterpret_cast(argv), + if (redisAppendCommandArgv(c, 3, reinterpret_cast(argv), reinterpret_cast(argv_len)) == REDIS_ERR) { return Status::Corruption("Redis Append Command Argv Error"); } @@ -226,7 +215,7 @@ Status RunSetCommandPipeline(redisContext* c) { } Status RunSetCommand(redisContext* c) { - redisReply *res = NULL; + redisReply* res = NULL; for (size_t idx = 0; idx < number_of_request; ++idx) { const char* set_argv[3]; size_t set_argvlen[3]; @@ -240,14 +229,15 @@ Status RunSetCommand(redisContext* c) { GenerateRandomString(rand_num, &key); GenerateRandomString(payload_size, &value); - set_argv[0] = "set"; set_argvlen[0] = 3; - set_argv[1] = key.c_str(); set_argvlen[1] = key.size(); - set_argv[2] = value.c_str(); set_argvlen[2] = value.size(); + set_argv[0] = "set"; + set_argvlen[0] = 3; + set_argv[1] = key.c_str(); + set_argvlen[1] = key.size(); + set_argv[2] = value.c_str(); + set_argvlen[2] = value.size(); - res = reinterpret_cast(redisCommandArgv(c, - 3, - reinterpret_cast(set_argv), - reinterpret_cast(set_argvlen))); + res = reinterpret_cast( + redisCommandArgv(c, 3, reinterpret_cast(set_argv), reinterpret_cast(set_argvlen))); if (res == NULL || strcasecmp(res->str, "OK")) { std::string res_str = "Exec command error: " + (res != NULL ? std::string(res->str) : ""); freeReplyObject(res); @@ -259,7 +249,7 @@ Status RunSetCommand(redisContext* c) { } Status RunZAddCommand(redisContext* c) { - redisReply *res = NULL; + redisReply* res = NULL; for (size_t idx = 0; idx < 1; ++idx) { const char* zadd_argv[4]; size_t zadd_argvlen[4]; @@ -268,17 +258,19 @@ Status RunZAddCommand(redisContext* c) { std::string member; GenerateRandomString(10, &key); - zadd_argv[0] = "zadd"; zadd_argvlen[0] = 4; - zadd_argv[1] = key.c_str(); zadd_argvlen[1] = key.size(); + zadd_argv[0] = "zadd"; + zadd_argvlen[0] = 4; + zadd_argv[1] = key.c_str(); + zadd_argvlen[1] = key.size(); for (size_t sidx = 0; sidx < 10000; ++sidx) { score = std::to_string(sidx * 2); GenerateRandomString(payload_size, &member); - zadd_argv[2] = score.c_str(); zadd_argvlen[2] = score.size(); - zadd_argv[3] = member.c_str(); zadd_argvlen[3] = member.size(); + zadd_argv[2] = score.c_str(); + zadd_argvlen[2] = score.size(); + zadd_argv[3] = member.c_str(); + zadd_argvlen[3] = member.size(); - res = reinterpret_cast(redisCommandArgv(c, - 4, - reinterpret_cast(zadd_argv), + res = reinterpret_cast(redisCommandArgv(c, 4, reinterpret_cast(zadd_argv), reinterpret_cast(zadd_argvlen))); if (res == NULL || res->integer == 0) { std::string res_str = "Exec command error: " + (res != NULL ? std::string(res->str) : ""); @@ -291,41 +283,39 @@ Status RunZAddCommand(redisContext* c) { return Status::OK(); } - - // ./benchmark_client // ./benchmark_client -h // ./benchmark_client -b db1:5:10000,db2:3:10000 -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { int opt; while ((opt = getopt(argc, argv, "P:h:p:a:t:c:d:n:")) != -1) { switch (opt) { - case 'h' : + case 'h': hostname = std::string(optarg); break; - case 'p' : + case 'p': port = atoi(optarg); break; - case 'P' : + case 'P': transmit_mode = kPipeline; pipeline_num = atoi(optarg); break; - case 'a' : + case 'a': password = std::string(optarg); break; - case 't' : + case 't': thread_num_each_table = atoi(optarg); break; - case 'c' : + case 'c': tables_str = std::string(optarg); break; - case 'd' : + case 'd': payload_size = atoi(optarg); break; - case 'n' : + case 'n': number_of_request = atoi(optarg); break; - default : + default: Usage(); exit(-1); } @@ -364,10 +354,7 @@ int main(int argc, char *argv[]) { auto minutes = std::chrono::duration_cast(end_time - start_time).count(); auto seconds = std::chrono::duration_cast(end_time - start_time).count(); - std::cout << "Total Time Cost : " - << hours << " hours " - << minutes % 60 << " minutes " - << seconds % 60 << " seconds " + std::cout << "Total Time Cost : " << hours << " hours " << minutes % 60 << " minutes " << seconds % 60 << " seconds " << std::endl; return 0; } diff --git a/pika-tools/binlog_sender/binlog_consumer.cc b/pika-tools/binlog_sender/binlog_consumer.cc index 37bfce1342..3fbcfc0d5e 100644 --- a/pika-tools/binlog_sender/binlog_consumer.cc +++ b/pika-tools/binlog_sender/binlog_consumer.cc @@ -5,25 +5,21 @@ #include "binlog_consumer.h" -BinlogConsumer::BinlogConsumer(const std::string& binlog_path, - uint32_t first_filenum, - uint32_t last_filenum, +BinlogConsumer::BinlogConsumer(const std::string& binlog_path, uint32_t first_filenum, uint32_t last_filenum, uint64_t offset) : filename_(binlog_path + kBinlogPrefix), first_filenum_(first_filenum), last_filenum_(last_filenum), current_offset_(offset), backing_store_(new char[kBlockSize]), - queue_(nullptr) { -}; + queue_(nullptr){}; BinlogConsumer::~BinlogConsumer() { delete[] backing_store_; delete queue_; } -std::string BinlogConsumer::NewFileName(const std::string& name, - const uint32_t current) { +std::string BinlogConsumer::NewFileName(const std::string& name, const uint32_t current) { char buf[256]; snprintf(buf, sizeof(buf), "%s%u", name.c_str(), current); return std::string(buf); @@ -77,13 +73,9 @@ bool BinlogConsumer::trim() { return true; } -uint32_t BinlogConsumer::current_filenum() { - return current_filenum_; -} +uint32_t BinlogConsumer::current_filenum() { return current_filenum_; } -uint64_t BinlogConsumer::current_offset() { - return current_offset_; -} +uint64_t BinlogConsumer::current_offset() { return current_offset_; } uint64_t BinlogConsumer::get_next(bool* is_error) { uint64_t offset = 0; @@ -127,7 +119,7 @@ uint64_t BinlogConsumer::get_next(bool* is_error) { return offset; } -uint32_t BinlogConsumer::ReadPhysicalRecord(slash::Slice *result) { +uint32_t BinlogConsumer::ReadPhysicalRecord(slash::Slice* result) { slash::Status s; if (kBlockSize - last_record_offset_ <= kHeaderSize) { queue_->Skip(kBlockSize - last_record_offset_); @@ -203,18 +195,15 @@ slash::Status BinlogConsumer::Consume(std::string* scratch) { return slash::Status::OK(); } - -// Get a whole message; +// Get a whole message; // the status will be OK, IOError or Corruption; slash::Status BinlogConsumer::Parse(std::string* scratch) { slash::Status s; scratch->clear(); while (true) { - s = Consume(scratch); if (s.IsEndFile()) { - if (current_filenum_ == last_filenum_) { return slash::Status::Complete("finish"); } else { @@ -222,7 +211,7 @@ slash::Status BinlogConsumer::Parse(std::string* scratch) { // Roll to next File if (slash::FileExists(confile)) { - //DLOG(INFO) << "BinlogSender roll to new binlog" << confile; + // DLOG(INFO) << "BinlogSender roll to new binlog" << confile; delete queue_; queue_ = NULL; @@ -241,6 +230,3 @@ slash::Status BinlogConsumer::Parse(std::string* scratch) { } return s; } - - - diff --git a/pika-tools/binlog_sender/binlog_consumer.h b/pika-tools/binlog_sender/binlog_consumer.h index fb2038ecbb..748be06fde 100644 --- a/pika-tools/binlog_sender/binlog_consumer.h +++ b/pika-tools/binlog_sender/binlog_consumer.h @@ -9,10 +9,10 @@ #include "stddef.h" #include "stdint.h" -#include "slash/include/slash_slice.h" -#include "slash/include/slash_status.h" #include "slash/include/env.h" #include "slash/include/slash_mutex.h" +#include "slash/include/slash_slice.h" +#include "slash/include/slash_status.h" enum RecordType { kZeroType = 0, @@ -33,37 +33,32 @@ static const size_t kBlockSize = 64 * 1024; static const std::string kBinlogPrefix = "write2file"; class BinlogConsumer { - public: - BinlogConsumer(const std::string& binlog_path, - uint32_t first_filenum, - uint32_t last_filenum, - uint64_t offset); - virtual ~BinlogConsumer(); - - std::string NewFileName(const std::string& name, - const uint32_t current); - bool Init(); - bool trim(); - uint32_t current_filenum(); - uint64_t current_offset(); - slash::Status Parse(std::string* scratch); + public: + BinlogConsumer(const std::string& binlog_path, uint32_t first_filenum, uint32_t last_filenum, uint64_t offset); + virtual ~BinlogConsumer(); - private: - uint64_t get_next(bool* is_error); - uint32_t ReadPhysicalRecord(slash::Slice* result); - slash::Status Consume(std::string* scratch); - std::string filename_; - uint32_t first_filenum_; - uint32_t last_filenum_; + std::string NewFileName(const std::string& name, const uint32_t current); + bool Init(); + bool trim(); + uint32_t current_filenum(); + uint64_t current_offset(); + slash::Status Parse(std::string* scratch); - uint32_t current_filenum_; - uint64_t current_offset_; - uint64_t last_record_offset_; + private: + uint64_t get_next(bool* is_error); + uint32_t ReadPhysicalRecord(slash::Slice* result); + slash::Status Consume(std::string* scratch); + std::string filename_; + uint32_t first_filenum_; + uint32_t last_filenum_; + uint32_t current_filenum_; + uint64_t current_offset_; + uint64_t last_record_offset_; - slash::Slice buffer_; - char* const backing_store_; - slash::SequentialFile* queue_; + slash::Slice buffer_; + char* const backing_store_; + slash::SequentialFile* queue_; }; -#endif // INCLUDE_BINLOG_Consumber_H_ +#endif // INCLUDE_BINLOG_Consumber_H_ diff --git a/pika-tools/binlog_sender/binlog_sender.cc b/pika-tools/binlog_sender/binlog_sender.cc index 08ea03141d..e1a60a8cc6 100644 --- a/pika-tools/binlog_sender/binlog_sender.cc +++ b/pika-tools/binlog_sender/binlog_sender.cc @@ -7,19 +7,18 @@ #include "ctime" #include "iostream" -#include "stdlib.h" -#include "unistd.h" #include "stdint.h" +#include "stdlib.h" #include "string.h" +#include "unistd.h" #include "net/include/net_cli.h" #include "net/include/redis_cli.h" -#include "utils.h" -#include "progress_thread.h" #include "binlog_consumer.h" #include "binlog_transverter.h" - +#include "progress_thread.h" +#include "utils.h" std::string binlog_path = "./log/"; std::string ip = "127.0.0.1"; @@ -61,11 +60,12 @@ void Usage() { std::cout << "\t-e -- end time , default: '2100-01-30 24:00:01'" << std::endl; std::cout << "\t-a -- password of the pika server" << std::endl; std::cout << "\texample1: ./binlog_sender -n ./log -i 127.0.0.1 -p 9221 -f 526 -o 8749409" << std::endl; - std::cout << "\texample2: ./binlog_sender -n ./log -i 127.0.0.1 -p 9221 -f 526-530 -s '2001-10-11 11:11:11' -e '2020-12-11 11:11:11'" << std::endl; + std::cout << "\texample2: ./binlog_sender -n ./log -i 127.0.0.1 -p 9221 -f 526-530 -s '2001-10-11 11:11:11' -e " + "'2020-12-11 11:11:11'" + << std::endl; } void TryToCommunicate() { - cli = net::NewRedisCli(); cli->set_connect_timeout(3000); Status net_s = cli->Connect(ip, port, ""); @@ -118,39 +118,38 @@ void TryToCommunicate() { } } -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { int32_t opt; while ((opt = getopt(argc, argv, "hi:p:n:f:s:e:o:a:")) != -1) { switch (opt) { - case 'h' : + case 'h': Usage(); exit(0); - case 'i' : + case 'i': ip = optarg; break; - case 'p' : + case 'p': port = std::atoi(optarg); break; - case 'n' : + case 'n': binlog_path = optarg; if (!binlog_path.empty() && binlog_path.back() != '/') { binlog_path += "/"; } break; - case 'f' : + case 'f': files_to_send = optarg; break; - case 's' : + case 's': start_time_str = optarg; break; - case 'e' : + case 'e': end_time_str = optarg; break; - case 'o' : + case 'o': file_offset = std::atoi(optarg); break; - case 'a' : + case 'a': need_auth = true; pass_wd = optarg; break; @@ -163,13 +162,12 @@ int main(int argc, char *argv[]) { PrintInfo(now); std::vector files; - if (!CheckFilesStr(files_to_send) - || !GetFileList(files_to_send, &files)) { + if (!CheckFilesStr(files_to_send) || !GetFileList(files_to_send, &files)) { std::cout << "input illlegal binlog scope of the sequence, exit..." << std::endl; exit(-1); } - uint32_t tv_start,tv_end; + uint32_t tv_start, tv_end; struct tm tm; time_t timet; strptime(start_time_str.c_str(), "%Y-%m-%d %H:%M:%S", &tm); @@ -227,7 +225,7 @@ int main(int argc, char *argv[]) { } else if (s.IsComplete()) { break; } else { - fprintf (stderr, "Binlog Parse err: %s, exit...\n", s.ToString().c_str()); + fprintf(stderr, "Binlog Parse err: %s, exit...\n", s.ToString().c_str()); exit(-1); } } @@ -247,12 +245,8 @@ int main(int argc, char *argv[]) { auto minutes = std::chrono::duration_cast(end_time - start_time).count(); auto seconds = std::chrono::duration_cast(end_time - start_time).count(); - std::cout << "Total Time Cost : " - << hours << " hours " - << minutes % 60 << " minutes " - << seconds % 60 << " seconds " + std::cout << "Total Time Cost : " << hours << " hours " << minutes % 60 << " minutes " << seconds % 60 << " seconds " << std::endl; return 0; } - diff --git a/pika-tools/binlog_sender/binlog_transverter.cc b/pika-tools/binlog_sender/binlog_transverter.cc index 0423972556..f5c7d8779e 100644 --- a/pika-tools/binlog_sender/binlog_transverter.cc +++ b/pika-tools/binlog_sender/binlog_transverter.cc @@ -5,57 +5,35 @@ #include "binlog_transverter.h" -uint32_t BinlogItem::exec_time() const { - return exec_time_; -} +uint32_t BinlogItem::exec_time() const { return exec_time_; } -uint32_t BinlogItem::server_id() const { - return server_id_; -} +uint32_t BinlogItem::server_id() const { return server_id_; } -uint64_t BinlogItem::logic_id() const { - return logic_id_; -} +uint64_t BinlogItem::logic_id() const { return logic_id_; } -uint32_t BinlogItem::filenum() const { - return filenum_; -} +uint32_t BinlogItem::filenum() const { return filenum_; } -uint64_t BinlogItem::offset() const { - return offset_; -} +uint64_t BinlogItem::offset() const { return offset_; } -std::string BinlogItem::content() const { - return content_; -} +std::string BinlogItem::content() const { return content_; } -void BinlogItem::set_exec_time(uint32_t exec_time) { - exec_time_ = exec_time; -} +void BinlogItem::set_exec_time(uint32_t exec_time) { exec_time_ = exec_time; } -void BinlogItem::set_server_id(uint32_t server_id) { - server_id_ = server_id; -} +void BinlogItem::set_server_id(uint32_t server_id) { server_id_ = server_id; } -void BinlogItem::set_logic_id(uint64_t logic_id) { - logic_id_ = logic_id; -} +void BinlogItem::set_logic_id(uint64_t logic_id) { logic_id_ = logic_id; } -void BinlogItem::set_filenum(uint32_t filenum) { - filenum_ = filenum; -} +void BinlogItem::set_filenum(uint32_t filenum) { filenum_ = filenum; } -void BinlogItem::set_offset(uint64_t offset) { - offset_ = offset; -} +void BinlogItem::set_offset(uint64_t offset) { offset_ = offset; } std::string BinlogItem::ToString() const { std::string str; - str.append("exec_time: " + std::to_string(exec_time_)); + str.append("exec_time: " + std::to_string(exec_time_)); str.append(",server_id: " + std::to_string(server_id_)); - str.append(",logic_id: " + std::to_string(logic_id_)); - str.append(",filenum: " + std::to_string(filenum_)); - str.append(",offset: " + std::to_string(offset_)); + str.append(",logic_id: " + std::to_string(logic_id_)); + str.append(",filenum: " + std::to_string(filenum_)); + str.append(",offset: " + std::to_string(offset_)); str.append("\ncontent: "); for (size_t idx = 0; idx < content_.size(); ++idx) { if (content_[idx] == '\n') { @@ -70,14 +48,9 @@ std::string BinlogItem::ToString() const { return str; } -std::string PikaBinlogTransverter::BinlogEncode(BinlogType type, - uint32_t exec_time, - uint32_t server_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset, - const std::string& content, - const std::vector& extends) { +std::string PikaBinlogTransverter::BinlogEncode(BinlogType type, uint32_t exec_time, uint32_t server_id, + uint64_t logic_id, uint32_t filenum, uint64_t offset, + const std::string& content, const std::vector& extends) { std::string binlog; slash::PutFixed16(&binlog, type); slash::PutFixed32(&binlog, exec_time); @@ -91,9 +64,7 @@ std::string PikaBinlogTransverter::BinlogEncode(BinlogType type, return binlog; } -bool PikaBinlogTransverter::BinlogDecode(BinlogType type, - const std::string& binlog, - BinlogItem* binlog_item) { +bool PikaBinlogTransverter::BinlogDecode(BinlogType type, const std::string& binlog, BinlogItem* binlog_item) { uint16_t binlog_type = 0; uint32_t content_length = 0; std::string binlog_str = binlog; diff --git a/pika-tools/binlog_sender/binlog_transverter.h b/pika-tools/binlog_sender/binlog_transverter.h index 317848929b..49b46f9f90 100644 --- a/pika-tools/binlog_sender/binlog_transverter.h +++ b/pika-tools/binlog_sender/binlog_transverter.h @@ -12,9 +12,10 @@ #include "slash/include/slash_coding.h" /* - * ***********************************************Type First Binlog Item Format*********************************************** - * | | | | | | | | | - * 2 Bytes 4 Bytes 4 Bytes 8 Bytes 4 Bytes 8 Bytes 4 Bytes content length Bytes + * ***********************************************Type First Binlog Item + * Format*********************************************** | | | | | + * | | | | 2 Bytes 4 Bytes 4 Bytes 8 Bytes + * 4 Bytes 8 Bytes 4 Bytes content length Bytes * */ enum BinlogType { @@ -22,57 +23,43 @@ enum BinlogType { }; class BinlogItem { - public: - BinlogItem() : - exec_time_(0), - server_id_(0), - logic_id_(0), - filenum_(0), - offset_(0), - content_("") {} + public: + BinlogItem() : exec_time_(0), server_id_(0), logic_id_(0), filenum_(0), offset_(0), content_("") {} - friend class PikaBinlogTransverter; + friend class PikaBinlogTransverter; - uint32_t exec_time() const; - uint32_t server_id() const; - uint64_t logic_id() const; - uint32_t filenum() const; - uint64_t offset() const; - std::string content() const; - std::string ToString() const; + uint32_t exec_time() const; + uint32_t server_id() const; + uint64_t logic_id() const; + uint32_t filenum() const; + uint64_t offset() const; + std::string content() const; + std::string ToString() const; - void set_exec_time(uint32_t exec_time); - void set_server_id(uint32_t server_id); - void set_logic_id(uint64_t logic_id); - void set_filenum(uint32_t filenum); - void set_offset(uint64_t offset); + void set_exec_time(uint32_t exec_time); + void set_server_id(uint32_t server_id); + void set_logic_id(uint64_t logic_id); + void set_filenum(uint32_t filenum); + void set_offset(uint64_t offset); - private: - uint32_t exec_time_; - uint32_t server_id_; - uint64_t logic_id_; - uint32_t filenum_; - uint64_t offset_; - std::string content_; - std::vector extends_; + private: + uint32_t exec_time_; + uint32_t server_id_; + uint64_t logic_id_; + uint32_t filenum_; + uint64_t offset_; + std::string content_; + std::vector extends_; }; -class PikaBinlogTransverter{ - public: - PikaBinlogTransverter() {}; - static std::string BinlogEncode(BinlogType type, - uint32_t exec_time, - uint32_t server_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset, - const std::string& content, - const std::vector& extends); - - static bool BinlogDecode(BinlogType type, - const std::string& binlog, - BinlogItem* binlog_item); +class PikaBinlogTransverter { + public: + PikaBinlogTransverter(){}; + static std::string BinlogEncode(BinlogType type, uint32_t exec_time, uint32_t server_id, uint64_t logic_id, + uint32_t filenum, uint64_t offset, const std::string& content, + const std::vector& extends); + static bool BinlogDecode(BinlogType type, const std::string& binlog, BinlogItem* binlog_item); }; #endif diff --git a/pika-tools/binlog_sender/progress_thread.cc b/pika-tools/binlog_sender/progress_thread.cc index 96644719cc..516d5b0b11 100644 --- a/pika-tools/binlog_sender/progress_thread.cc +++ b/pika-tools/binlog_sender/progress_thread.cc @@ -5,17 +5,14 @@ #include "progress_thread.h" -ProgressThread::ProgressThread(BinlogConsumer* binlog_consumer) - : binlog_consumer_(binlog_consumer) { -} +ProgressThread::ProgressThread(BinlogConsumer* binlog_consumer) : binlog_consumer_(binlog_consumer) {} void* ProgressThread::ThreadMain() { while (!should_stop_) { - printf("\rSending binlog, current file num: %d, offset: %9ld", - binlog_consumer_->current_filenum(), binlog_consumer_->current_offset()); + printf("\rSending binlog, current file num: %d, offset: %9ld", binlog_consumer_->current_filenum(), + binlog_consumer_->current_offset()); fflush(stdout); } printf("\n"); return NULL; } - diff --git a/pika-tools/binlog_sender/progress_thread.h b/pika-tools/binlog_sender/progress_thread.h index 297e8086f7..d4cf8928f2 100644 --- a/pika-tools/binlog_sender/progress_thread.h +++ b/pika-tools/binlog_sender/progress_thread.h @@ -16,11 +16,12 @@ extern slash::Mutex mutex; class ProgressThread : public net::Thread { - public: - ProgressThread(BinlogConsumer* binlog_consumer); - private: - virtual void *ThreadMain(); - BinlogConsumer* binlog_consumer_; + public: + ProgressThread(BinlogConsumer* binlog_consumer); + + private: + virtual void* ThreadMain(); + BinlogConsumer* binlog_consumer_; }; #endif // INCLUDE_PROGRESS_THREAD_H_ diff --git a/pika-tools/binlog_sender/utils.h b/pika-tools/binlog_sender/utils.h index 55c165ddb5..4096ed6a23 100644 --- a/pika-tools/binlog_sender/utils.h +++ b/pika-tools/binlog_sender/utils.h @@ -11,12 +11,12 @@ #include "slash/include/env.h" -#define COMMA_STR "," -#define COLON_STR ":" -#define NEG_STR "-" -#define NEG_CHAR '-' -#define SPACE_STR " " -#define WRITE2FILE "write2file" +#define COMMA_STR "," +#define COLON_STR ":" +#define NEG_STR "-" +#define NEG_CHAR '-' +#define SPACE_STR " " +#define WRITE2FILE "write2file" bool Exists(const std::string& base, const std::string& pattern); bool CheckFilesStr(const std::string& files_str); diff --git a/pika-tools/manifest_generator/include/pika_binlog.h b/pika-tools/manifest_generator/include/pika_binlog.h index f7860ca262..630fc44208 100644 --- a/pika-tools/manifest_generator/include/pika_binlog.h +++ b/pika-tools/manifest_generator/include/pika_binlog.h @@ -12,14 +12,14 @@ #include "include/pika_define.h" -using slash::Status; using slash::Slice; +using slash::Status; std::string NewFileName(const std::string name, const uint32_t current); class Version { public: - Version(slash::RWFile *save); + Version(slash::RWFile* save); ~Version(); Status Init(); @@ -35,12 +35,11 @@ class Version { void debug() { slash::RWLock(&rwlock_, false); - printf ("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); + printf("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); } private: - - slash::RWFile *save_; + slash::RWFile* save_; // No copying allowed; Version(const Version&); @@ -52,10 +51,10 @@ class Binlog { Binlog(const std::string& Binlog_path, const int file_size = 100 * 1024 * 1024); ~Binlog(); - void Lock() { mutex_.Lock(); } - void Unlock() { mutex_.Unlock(); } + void Lock() { mutex_.Lock(); } + void Unlock() { mutex_.Unlock(); } - Status Put(const std::string &item); + Status Put(const std::string& item); Status Put(const char* item, int len); Status GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset, uint64_t* logic_id = NULL); @@ -64,33 +63,29 @@ class Binlog { */ Status SetProducerStatus(uint32_t filenum, uint64_t pro_offset); - static Status AppendBlank(slash::WritableFile *file, uint64_t len); + static Status AppendBlank(slash::WritableFile* file, uint64_t len); - slash::WritableFile *queue() { return queue_; } + slash::WritableFile* queue() { return queue_; } - uint64_t file_size() { - return file_size_; - } + uint64_t file_size() { return file_size_; } std::string filename; private: - void InitLogFile(); - Status EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset); - + Status EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset); /* * Produce */ - Status Produce(const Slice &item, int *pro_offset); + Status Produce(const Slice& item, int* pro_offset); uint32_t consumer_num_; uint64_t item_num_; Version* version_; - slash::WritableFile *queue_; - slash::RWFile *versionfile_; + slash::WritableFile* queue_; + slash::RWFile* versionfile_; slash::Mutex mutex_; @@ -105,7 +100,7 @@ class Binlog { uint64_t file_size_; // Not use - //int32_t retry_; + // int32_t retry_; // No copying allowed Binlog(const Binlog&); diff --git a/pika-tools/manifest_generator/include/pika_define.h b/pika-tools/manifest_generator/include/pika_define.h index 8c717ac256..1653f3a51a 100644 --- a/pika-tools/manifest_generator/include/pika_define.h +++ b/pika-tools/manifest_generator/include/pika_define.h @@ -6,18 +6,18 @@ #ifndef PIKA_DEFINE_H_ #define PIKA_DEFINE_H_ -#include "net/include/redis_cli.h" #include +#include "net/include/redis_cli.h" -#define PIKA_SYNC_BUFFER_SIZE 10 -#define PIKA_MAX_WORKER_THREAD_NUM 24 -#define PIKA_REPL_SERVER_TP_SIZE 3 -#define PIKA_META_SYNC_MAX_WAIT_TIME 5 +#define PIKA_SYNC_BUFFER_SIZE 10 +#define PIKA_MAX_WORKER_THREAD_NUM 24 +#define PIKA_REPL_SERVER_TP_SIZE 3 +#define PIKA_META_SYNC_MAX_WAIT_TIME 5 class PikaServer; /* Port shift */ -const int kPortShiftRSync = 1000; +const int kPortShiftRSync = 1000; const int kPortShiftReplServer = 2000; const std::string kPikaPidFile = "pika.pid"; @@ -29,35 +29,31 @@ struct WorkerCronTask { std::string ip_port; }; typedef WorkerCronTask MonitorCronTask; -//task define +// task define #define TASK_KILL 0 #define TASK_KILLALL 1 ////slave item -//struct SlaveItem { -// std::string ip_port; -// std::string ip; -// int port; -// int conn_fd; -// int stage; -// std::vector table_structs; -// struct timeval create_time; -//}; +// struct SlaveItem { +// std::string ip_port; +// std::string ip; +// int port; +// int conn_fd; +// int stage; +// std::vector table_structs; +// struct timeval create_time; +// }; struct BinlogOffset { uint32_t filenum; uint64_t offset; - BinlogOffset() - : filenum(0), offset(0) {} - BinlogOffset(uint32_t num, uint64_t off) - : filenum(num), offset(off) {} + BinlogOffset() : filenum(0), offset(0) {} + BinlogOffset(uint32_t num, uint64_t off) : filenum(num), offset(off) {} BinlogOffset(const BinlogOffset& other) { filenum = other.filenum; offset = other.offset; } - std::string ToString() const { - return "filenum: " + std::to_string(filenum) + " offset: " + std::to_string(offset); - } + std::string ToString() const { return "filenum: " + std::to_string(filenum) + " offset: " + std::to_string(offset); } bool operator==(const BinlogOffset& other) const { if (filenum == other.filenum && offset == other.offset) { return true; @@ -66,55 +62,42 @@ struct BinlogOffset { } }; -//dbsync arg +// dbsync arg struct DBSyncArg { PikaServer* p; std::string ip; int port; std::string table_name; uint32_t partition_id; - DBSyncArg(PikaServer* const _p, - const std::string& _ip, - int _port, - const std::string& _table_name, + DBSyncArg(PikaServer* const _p, const std::string& _ip, int _port, const std::string& _table_name, uint32_t _partition_id) - : p(_p), ip(_ip), port(_port), - table_name(_table_name), partition_id(_partition_id) {} + : p(_p), ip(_ip), port(_port), table_name(_table_name), partition_id(_partition_id) {} }; // rm define enum SlaveState { - kSlaveNotSync = 0, - kSlaveDbSync = 1, + kSlaveNotSync = 0, + kSlaveDbSync = 1, kSlaveBinlogSync = 2, }; // debug only -const std::string SlaveStateMsg[] = { - "kSlaveNotSync", - "kSlaveDbSync", - "kSlaveBinlogSync" -}; +const std::string SlaveStateMsg[] = {"kSlaveNotSync", "kSlaveDbSync", "kSlaveBinlogSync"}; enum BinlogSyncState { - kNotSync = 0, - kReadFromCache = 1, - kReadFromFile = 2, + kNotSync = 0, + kReadFromCache = 1, + kReadFromFile = 2, }; // debug only -const std::string BinlogSyncStateMsg[] = { - "kNotSync", - "kReadFromCache", - "kReadFromFile" -}; +const std::string BinlogSyncStateMsg[] = {"kNotSync", "kReadFromCache", "kReadFromFile"}; struct BinlogChip { BinlogOffset offset_; std::string binlog_; - BinlogChip(BinlogOffset offset, std::string binlog) : offset_(offset), binlog_(binlog) { - } + BinlogChip(BinlogOffset offset, std::string binlog) : offset_(offset), binlog_(binlog) {} BinlogChip(const BinlogChip& binlog_chip) { offset_ = binlog_chip.offset_; binlog_ = binlog_chip.binlog_; @@ -123,24 +106,19 @@ struct BinlogChip { struct PartitionInfo { PartitionInfo(const std::string& table_name, uint32_t partition_id) - : table_name_(table_name), partition_id_(partition_id) { - } + : table_name_(table_name), partition_id_(partition_id) {} PartitionInfo(const PartitionInfo& other) { table_name_ = other.table_name_; partition_id_ = other.partition_id_; } - PartitionInfo() : partition_id_(0) { - } + PartitionInfo() : partition_id_(0) {} bool operator==(const PartitionInfo& other) const { - if (table_name_ == other.table_name_ - && partition_id_ == other.partition_id_) { + if (table_name_ == other.table_name_ && partition_id_ == other.partition_id_) { return true; } return false; } - std::string ToString() const { - return table_name_ + "_" + std::to_string(partition_id_); - } + std::string ToString() const { return table_name_ + "_" + std::to_string(partition_id_); } std::string table_name_; uint32_t partition_id_; }; @@ -153,20 +131,13 @@ struct hash_partition_info { class Node { public: - Node(const std::string& ip, int port) : ip_(ip), port_(port) { - } + Node(const std::string& ip, int port) : ip_(ip), port_(port) {} virtual ~Node() = default; - Node() : port_(0) { - } - const std::string& Ip() const { - return ip_; - } - int Port() const { - return port_; - } - std::string ToString() const { - return ip_ + ":" + std::to_string(port_); - } + Node() : port_(0) {} + const std::string& Ip() const { return ip_; } + int Port() const { return port_; } + std::string ToString() const { return ip_ + ":" + std::to_string(port_); } + private: std::string ip_; int port_; @@ -174,84 +145,49 @@ class Node { class RmNode : public Node { public: - RmNode(const std::string& ip, int port, - const PartitionInfo& partition_info) - : Node(ip, port), - partition_info_(partition_info), - session_id_(0), - last_send_time_(0), - last_recv_time_(0) {} - - RmNode(const std::string& ip, - int port, - const std::string& table_name, - uint32_t partition_id) + RmNode(const std::string& ip, int port, const PartitionInfo& partition_info) + : Node(ip, port), partition_info_(partition_info), session_id_(0), last_send_time_(0), last_recv_time_(0) {} + + RmNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id) : Node(ip, port), partition_info_(table_name, partition_id), session_id_(0), last_send_time_(0), last_recv_time_(0) {} - RmNode(const std::string& ip, - int port, - const std::string& table_name, - uint32_t partition_id, - int32_t session_id) + RmNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, int32_t session_id) : Node(ip, port), partition_info_(table_name, partition_id), session_id_(session_id), last_send_time_(0), last_recv_time_(0) {} - RmNode(const std::string& table_name, - uint32_t partition_id) - : Node(), - partition_info_(table_name, partition_id), - session_id_(0), - last_send_time_(0), - last_recv_time_(0) {} + RmNode(const std::string& table_name, uint32_t partition_id) + : Node(), partition_info_(table_name, partition_id), session_id_(0), last_send_time_(0), last_recv_time_(0) {} virtual ~RmNode() = default; bool operator==(const RmNode& other) const { - if (partition_info_.table_name_ == other.TableName() - && partition_info_.partition_id_ == other.PartitionId() - && Ip() == other.Ip() && Port() == other.Port()) { + if (partition_info_.table_name_ == other.TableName() && partition_info_.partition_id_ == other.PartitionId() && + Ip() == other.Ip() && Port() == other.Port()) { return true; } return false; } - const std::string& TableName() const { - return partition_info_.table_name_; - } - uint32_t PartitionId() const { - return partition_info_.partition_id_; - } - const PartitionInfo& NodePartitionInfo() const { - return partition_info_; - } - void SetSessionId(uint32_t session_id) { - session_id_ = session_id; - } - int32_t SessionId() const { - return session_id_; - } + const std::string& TableName() const { return partition_info_.table_name_; } + uint32_t PartitionId() const { return partition_info_.partition_id_; } + const PartitionInfo& NodePartitionInfo() const { return partition_info_; } + void SetSessionId(uint32_t session_id) { session_id_ = session_id; } + int32_t SessionId() const { return session_id_; } std::string ToString() const { - return "partition=" + TableName() + "_" + std::to_string(PartitionId()) + ",ip_port=" - + Ip() + ":" + std::to_string(Port()) + ",session id=" + std::to_string(SessionId()); - } - void SetLastSendTime(uint64_t last_send_time) { - last_send_time_ = last_send_time; - } - uint64_t LastSendTime() const { - return last_send_time_; - } - void SetLastRecvTime(uint64_t last_recv_time) { - last_recv_time_ = last_recv_time; - } - uint64_t LastRecvTime() const { - return last_recv_time_; + return "partition=" + TableName() + "_" + std::to_string(PartitionId()) + ",ip_port=" + Ip() + ":" + + std::to_string(Port()) + ",session id=" + std::to_string(SessionId()); } + void SetLastSendTime(uint64_t last_send_time) { last_send_time_ = last_send_time; } + uint64_t LastSendTime() const { return last_send_time_; } + void SetLastRecvTime(uint64_t last_recv_time) { last_recv_time_ = last_recv_time; } + uint64_t LastRecvTime() const { return last_recv_time_; } + private: PartitionInfo partition_info_; int32_t session_id_; @@ -261,22 +197,22 @@ class RmNode : public Node { struct hash_rm_node { size_t operator()(const RmNode& n) const { - return std::hash()(n.TableName()) ^ std::hash()(n.PartitionId()) ^ std::hash()(n.Ip()) ^ std::hash()(n.Port()); + return std::hash()(n.TableName()) ^ std::hash()(n.PartitionId()) ^ + std::hash()(n.Ip()) ^ std::hash()(n.Port()); } }; struct WriteTask { struct RmNode rm_node_; struct BinlogChip binlog_chip_; - WriteTask(RmNode rm_node, BinlogChip binlog_chip) : rm_node_(rm_node), binlog_chip_(binlog_chip) { - } + WriteTask(RmNode rm_node, BinlogChip binlog_chip) : rm_node_(rm_node), binlog_chip_(binlog_chip) {} }; -//slowlog define +// slowlog define #define SLOWLOG_ENTRY_MAX_ARGC 32 #define SLOWLOG_ENTRY_MAX_STRING 128 -//slowlog entry +// slowlog entry struct SlowlogEntry { int64_t id; int64_t start_time; @@ -286,28 +222,28 @@ struct SlowlogEntry { #define PIKA_MIN_RESERVED_FDS 5000 -const int SLAVE_ITEM_STAGE_ONE = 1; -const int SLAVE_ITEM_STAGE_TWO = 2; +const int SLAVE_ITEM_STAGE_ONE = 1; +const int SLAVE_ITEM_STAGE_TWO = 2; -//repl_state_ -const int PIKA_REPL_NO_CONNECT = 0; -const int PIKA_REPL_SHOULD_META_SYNC = 1; -const int PIKA_REPL_WAIT_META_SYNC_RESPONSE = 2; -const int PIKA_REPL_SHOULD_MARK_TRY_CONNECT = 3; -const int PIKA_REPL_CONNECTING = 4; -const int PIKA_REPL_ESTABLISH_SUCCESS = 5; -const int PIKA_REPL_ERROR = 6; +// repl_state_ +const int PIKA_REPL_NO_CONNECT = 0; +const int PIKA_REPL_SHOULD_META_SYNC = 1; +const int PIKA_REPL_WAIT_META_SYNC_RESPONSE = 2; +const int PIKA_REPL_SHOULD_MARK_TRY_CONNECT = 3; +const int PIKA_REPL_CONNECTING = 4; +const int PIKA_REPL_ESTABLISH_SUCCESS = 5; +const int PIKA_REPL_ERROR = 6; -//role -const int PIKA_ROLE_SINGLE = 0; -const int PIKA_ROLE_SLAVE = 1; -const int PIKA_ROLE_MASTER = 2; +// role +const int PIKA_ROLE_SINGLE = 0; +const int PIKA_ROLE_SLAVE = 1; +const int PIKA_ROLE_MASTER = 2; /* * The size of Binlogfile */ -//static uint64_t kBinlogSize = 128; -//static const uint64_t kBinlogSize = 1024 * 1024 * 100; +// static uint64_t kBinlogSize = 128; +// static const uint64_t kBinlogSize = 1024 * 1024 * 100; enum RecordType { kZeroType = 0, diff --git a/pika-tools/manifest_generator/manifest_generator.cc b/pika-tools/manifest_generator/manifest_generator.cc index 118e857f25..3fe89f12e6 100644 --- a/pika-tools/manifest_generator/manifest_generator.cc +++ b/pika-tools/manifest_generator/manifest_generator.cc @@ -9,9 +9,9 @@ #include #include +#include "include/pika_binlog.h" #include "slash/include/slash_status.h" #include "slash/include/slash_string.h" -#include "include/pika_binlog.h" std::string db_dump_path; int32_t db_dump_filenum; @@ -44,9 +44,13 @@ void ParseInfoFile(const std::string& path) { is.close(); exit(-1); } - if (lineno == 3) { master_port = tmp; } - else if (lineno == 4) { filenum = tmp; } - else { offset = tmp; } + if (lineno == 3) { + master_port = tmp; + } else if (lineno == 4) { + filenum = tmp; + } else { + offset = tmp; + } } else if (lineno > 5) { std::cout << "Format of info file " << info_file << " error, line : " << line; @@ -59,10 +63,10 @@ void ParseInfoFile(const std::string& path) { db_dump_filenum = filenum; db_dump_offset = offset; std::cout << "Information from info_file " << info_file << std::endl - << " db_dump_ip: " << master_ip << std::endl - << " db_dump_port: " << master_port << std::endl - << " filenum: " << filenum << std::endl - << " offset: " << offset << std::endl; + << " db_dump_ip: " << master_ip << std::endl + << " db_dump_port: " << master_port << std::endl + << " filenum: " << filenum << std::endl + << " offset: " << offset << std::endl; } void PrintInfo() { @@ -78,20 +82,21 @@ void Usage() { std::cout << "Usage: " << std::endl; std::cout << " -d -- db dump path (required)" << std::endl; std::cout << " -l -- new pika log_path (required)" << std::endl; - std::cout << " example: ./manifest_generator -d /data1/pika_old/dump/20190508/ -l /data01/pika_new/log/db0" << std::endl; + std::cout << " example: ./manifest_generator -d /data1/pika_old/dump/20190508/ -l /data01/pika_new/log/db0" + << std::endl; } int main(int argc, char* argv[]) { int opt; while ((opt = getopt(argc, argv, "d:l:")) != -1) { switch (opt) { - case 'd' : + case 'd': db_dump_path = std::string(optarg); break; - case 'l' : + case 'l': new_pika_log_path = std::string(optarg); break; - default : + default: Usage(); exit(-1); } @@ -101,7 +106,7 @@ int main(int argc, char* argv[]) { exit(-1); } if (db_dump_path.back() != '/') { - db_dump_path.push_back('/'); + db_dump_path.push_back('/'); } if (new_pika_log_path.back() != '/') { new_pika_log_path.push_back('/'); diff --git a/pika-tools/manifest_generator/pika_binlog.cc b/pika-tools/manifest_generator/pika_binlog.cc index cda2ccd476..30ba654801 100644 --- a/pika-tools/manifest_generator/pika_binlog.cc +++ b/pika-tools/manifest_generator/pika_binlog.cc @@ -20,11 +20,7 @@ std::string NewFileName(const std::string name, const uint32_t current) { /* * Version */ -Version::Version(slash::RWFile *save) - : pro_num_(0), - pro_offset_(0), - logic_id_(0), - save_(save) { +Version::Version(slash::RWFile* save) : pro_num_(0), pro_offset_(0), logic_id_(0), save_(save) { assert(save_ != NULL); pthread_rwlock_init(&rwlock_, NULL); @@ -36,7 +32,7 @@ Version::~Version() { } Status Version::StableSave() { - char *p = save_->GetData(); + char* p = save_->GetData(); memcpy(p, &pro_num_, sizeof(uint32_t)); p += 4; memcpy(p, &pro_offset_, sizeof(uint64_t)); @@ -61,20 +57,19 @@ Status Version::Init() { /* * Binlog */ -Binlog::Binlog(const std::string& binlog_path, const int file_size) : - consumer_num_(0), - version_(NULL), - queue_(NULL), - versionfile_(NULL), - pro_num_(0), - pool_(NULL), - exit_all_consume_(false), - binlog_path_(binlog_path), - file_size_(file_size) { - +Binlog::Binlog(const std::string& binlog_path, const int file_size) + : consumer_num_(0), + version_(NULL), + queue_(NULL), + versionfile_(NULL), + pro_num_(0), + pool_(NULL), + exit_all_consume_(false), + binlog_path_(binlog_path), + file_size_(file_size) { // To intergrate with old version, we don't set mmap file size to 100M; - //slash::SetMmapBoundSize(file_size); - //slash::kMmapBoundSize = 1024 * 1024 * 100; + // slash::SetMmapBoundSize(file_size); + // slash::kMmapBoundSize = 1024 * 1024 * 100; Status s; @@ -90,11 +85,10 @@ Binlog::Binlog(const std::string& binlog_path, const int file_size) : profile = NewFileName(filename, pro_num_); s = slash::NewWritableFile(profile, &queue_); if (!s.ok()) { - std::cout << "Binlog: new " << filename << " " << s.ToString(); + std::cout << "Binlog: new " << filename << " " << s.ToString(); exit(-1); } - s = slash::NewRWFile(manifest, &versionfile_); if (!s.ok()) { std::cout << "Binlog: new versionfile error " << s.ToString(); @@ -113,7 +107,7 @@ Binlog::Binlog(const std::string& binlog_path, const int file_size) : pro_num_ = version_->pro_num_; // Debug - //version_->debug(); + // version_->debug(); } else { std::cout << "Binlog: open versionfile error"; exit(-1); @@ -157,9 +151,7 @@ Status Binlog::GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset, uint64 } // Note: mutex lock should be held -Status Binlog::Put(const std::string &item) { - return Put(item.c_str(), item.size()); -} +Status Binlog::Put(const std::string& item) { return Put(item.c_str(), item.size()); } // Note: mutex lock should be held Status Binlog::Put(const char* item, int len) { @@ -195,43 +187,43 @@ Status Binlog::Put(const char* item, int len) { return s; } - -Status Binlog::EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset) { - Status s; - assert(n <= 0xffffff); - assert(block_offset_ + kHeaderSize + n <= kBlockSize); - - char buf[kHeaderSize]; - - uint64_t now; - struct timeval tv; - gettimeofday(&tv, NULL); - now = tv.tv_sec; - buf[0] = static_cast(n & 0xff); - buf[1] = static_cast((n & 0xff00) >> 8); - buf[2] = static_cast(n >> 16); - buf[3] = static_cast(now & 0xff); - buf[4] = static_cast((now & 0xff00) >> 8); - buf[5] = static_cast((now & 0xff0000) >> 16); - buf[6] = static_cast((now & 0xff000000) >> 24); - buf[7] = static_cast(t); - - s = queue_->Append(Slice(buf, kHeaderSize)); + +Status Binlog::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset) { + Status s; + assert(n <= 0xffffff); + assert(block_offset_ + kHeaderSize + n <= kBlockSize); + + char buf[kHeaderSize]; + + uint64_t now; + struct timeval tv; + gettimeofday(&tv, NULL); + now = tv.tv_sec; + buf[0] = static_cast(n & 0xff); + buf[1] = static_cast((n & 0xff00) >> 8); + buf[2] = static_cast(n >> 16); + buf[3] = static_cast(now & 0xff); + buf[4] = static_cast((now & 0xff00) >> 8); + buf[5] = static_cast((now & 0xff0000) >> 16); + buf[6] = static_cast((now & 0xff000000) >> 24); + buf[7] = static_cast(t); + + s = queue_->Append(Slice(buf, kHeaderSize)); + if (s.ok()) { + s = queue_->Append(Slice(ptr, n)); if (s.ok()) { - s = queue_->Append(Slice(ptr, n)); - if (s.ok()) { - s = queue_->Flush(); - } + s = queue_->Flush(); } - block_offset_ += static_cast(kHeaderSize + n); + } + block_offset_ += static_cast(kHeaderSize + n); - *temp_pro_offset += kHeaderSize + n; - return s; + *temp_pro_offset += kHeaderSize + n; + return s; } -Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { +Status Binlog::Produce(const Slice& item, int* temp_pro_offset) { Status s; - const char *ptr = item.data(); + const char* ptr = item.data(); size_t left = item.size(); bool begin = true; @@ -272,8 +264,8 @@ Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { return s; } - -Status Binlog::AppendBlank(slash::WritableFile *file, uint64_t len) { + +Status Binlog::AppendBlank(slash::WritableFile* file, uint64_t len) { if (len < kHeaderSize) { return Status::OK(); } @@ -291,7 +283,7 @@ Status Binlog::AppendBlank(slash::WritableFile *file, uint64_t len) { if (len % kBlockSize < kHeaderSize) { n = 0; } else { - n = (uint32_t) ((len % kBlockSize) - kHeaderSize); + n = (uint32_t)((len % kBlockSize) - kHeaderSize); } char buf[kBlockSize]; diff --git a/pika-tools/nemo_to_blackwidow/classify_thread.cc b/pika-tools/nemo_to_blackwidow/classify_thread.cc index aa972bd62f..4eb3131398 100644 --- a/pika-tools/nemo_to_blackwidow/classify_thread.cc +++ b/pika-tools/nemo_to_blackwidow/classify_thread.cc @@ -6,18 +6,11 @@ #include "classify_thread.h" ClassifyThread::ClassifyThread(nemo::Nemo* nemo_db, std::vector migrators, const std::string& type) - : is_finish_(false), - key_num_(0), - consume_index_(0), - nemo_db_(nemo_db), - migrators_(migrators), - type_(type) { + : is_finish_(false), key_num_(0), consume_index_(0), nemo_db_(nemo_db), migrators_(migrators), type_(type) { pthread_rwlock_init(&rwlock_, NULL); } -ClassifyThread::~ClassifyThread() { - pthread_rwlock_destroy(&rwlock_); -}; +ClassifyThread::~ClassifyThread() { pthread_rwlock_destroy(&rwlock_); }; int64_t ClassifyThread::key_num() { slash::RWLock l(&rwlock_, false); diff --git a/pika-tools/nemo_to_blackwidow/classify_thread.h b/pika-tools/nemo_to_blackwidow/classify_thread.h index 3909a5bf72..5f18610e22 100644 --- a/pika-tools/nemo_to_blackwidow/classify_thread.h +++ b/pika-tools/nemo_to_blackwidow/classify_thread.h @@ -15,31 +15,32 @@ #include "net/include/net_thread.h" #include "slash/include/slash_mutex.h" -#include "utils.h" #include "migrator.h" +#include "utils.h" extern slash::Mutex mutex; class ClassifyThread : public net::Thread { - public: - ClassifyThread(nemo::Nemo* nemo_db, std::vector migrators, const std::string& type); - virtual ~ClassifyThread(); - int64_t key_num(); - bool is_finish() { return is_finish_;} - std::string type() { return type_;} - int64_t consume_index() { return consume_index_;} - private: - void PlusProcessKeyNum(); - void DispatchItem(const std::string& item); - virtual void *ThreadMain(); - - bool is_finish_; - int64_t key_num_; - int64_t consume_index_; - pthread_rwlock_t rwlock_; - nemo::Nemo* nemo_db_; - std::vector migrators_; - std::string type_; + public: + ClassifyThread(nemo::Nemo* nemo_db, std::vector migrators, const std::string& type); + virtual ~ClassifyThread(); + int64_t key_num(); + bool is_finish() { return is_finish_; } + std::string type() { return type_; } + int64_t consume_index() { return consume_index_; } + + private: + void PlusProcessKeyNum(); + void DispatchItem(const std::string& item); + virtual void* ThreadMain(); + + bool is_finish_; + int64_t key_num_; + int64_t consume_index_; + pthread_rwlock_t rwlock_; + nemo::Nemo* nemo_db_; + std::vector migrators_; + std::string type_; }; #endif // INCLUDE_CLASSIFY_THREAD_H_ diff --git a/pika-tools/nemo_to_blackwidow/migrator.cc b/pika-tools/nemo_to_blackwidow/migrator.cc index 92864fa2c4..ea12d76299 100644 --- a/pika-tools/nemo_to_blackwidow/migrator.cc +++ b/pika-tools/nemo_to_blackwidow/migrator.cc @@ -3,9 +3,9 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. +#include "migrator.h" #include "nemo.h" #include "utils.h" -#include "migrator.h" extern int32_t need_write_log; extern int32_t max_batch_limit; @@ -14,9 +14,7 @@ int32_t Migrator::queue_size() { return items_queue_.size(); } -void Migrator::PlusMigrateKey() { - migrate_key_num_++; -} +void Migrator::PlusMigrateKey() { migrate_key_num_++; } void Migrator::SetShouldExit() { queue_mutex_.Lock(); @@ -39,7 +37,6 @@ bool Migrator::LoadItem(const std::string& item) { } void* Migrator::ThreadMain() { - char prefix; int32_t int32_ret; uint64_t uint64_ret; @@ -48,7 +45,6 @@ void* Migrator::ThreadMain() { rocksdb::Status s; std::map type_status; while (items_queue_.size() || !should_exit_) { - queue_mutex_.Lock(); while (items_queue_.empty() && !should_exit_) { queue_cond_.Wait(); @@ -73,19 +69,18 @@ void* Migrator::ThreadMain() { } if (need_write_log) { - LOG(INFO) << "migrator id: " << migrator_id_ << " queue size: " << queue_size() << " type : " << prefix << " key: " << key; + LOG(INFO) << "migrator id: " << migrator_id_ << " queue size: " << queue_size() << " type : " << prefix + << " key: " << key; } if (prefix == nemo::DataType::kKv) { blackwidow_db_->Set(key, value); } else if (prefix == nemo::DataType::kHSize) { std::vector field_values; - nemo::HIterator *iter = nemo_db_->HScan(key, "", "", -1, false); + nemo::HIterator* iter = nemo_db_->HScan(key, "", "", -1, false); while (iter->Valid()) { field_values.clear(); - for (int32_t idx = 0; - idx < max_batch_limit && iter->Valid(); - idx++, iter->Next()) { + for (int32_t idx = 0; idx < max_batch_limit && iter->Valid(); idx++, iter->Next()) { field_values.push_back({iter->field(), iter->value()}); } blackwidow_db_->HMSet(iter->key(), field_values); @@ -109,13 +104,10 @@ void* Migrator::ThreadMain() { } } else if (prefix == nemo::DataType::kZSize) { std::vector score_members; - nemo::ZIterator *iter = nemo_db_->ZScan(key, nemo::ZSET_SCORE_MIN, - nemo::ZSET_SCORE_MAX, -1, false); + nemo::ZIterator* iter = nemo_db_->ZScan(key, nemo::ZSET_SCORE_MIN, nemo::ZSET_SCORE_MAX, -1, false); while (iter->Valid()) { score_members.clear(); - for (int32_t idx = 0; - idx < max_batch_limit && iter->Valid(); - idx++, iter->Next()) { + for (int32_t idx = 0; idx < max_batch_limit && iter->Valid(); idx++, iter->Next()) { score_members.push_back({iter->score(), iter->member()}); } blackwidow_db_->ZAdd(iter->key(), score_members, &int32_ret); @@ -124,12 +116,10 @@ void* Migrator::ThreadMain() { } else if (prefix == nemo::DataType::kSSize) { std::vector members; - nemo::SIterator *iter = nemo_db_->SScan(key, -1, false); + nemo::SIterator* iter = nemo_db_->SScan(key, -1, false); while (iter->Valid()) { members.clear(); - for (int32_t idx = 0; - idx < max_batch_limit && iter->Valid(); - idx++, iter->Next()) { + for (int32_t idx = 0; idx < max_batch_limit && iter->Valid(); idx++, iter->Next()) { members.push_back(iter->member()); } blackwidow_db_->SAdd(iter->key(), members, &int32_ret); diff --git a/pika-tools/nemo_to_blackwidow/migrator.h b/pika-tools/nemo_to_blackwidow/migrator.h index d64c4850c0..2c38eb5a1e 100644 --- a/pika-tools/nemo_to_blackwidow/migrator.h +++ b/pika-tools/nemo_to_blackwidow/migrator.h @@ -16,33 +16,33 @@ extern slash::Mutex mutex; -class Migrator: public net::Thread { - public: - Migrator(int32_t migrator_id, nemo::Nemo* nemo_db, blackwidow::BlackWidow* blackwidow_db) - : nemo_db_(nemo_db), - blackwidow_db_(blackwidow_db), - migrator_id_(migrator_id), - migrate_key_num_(0), - should_exit_(false), - queue_cond_(&queue_mutex_) {} - virtual ~Migrator() {} - - int32_t queue_size(); - void PlusMigrateKey(); - void SetShouldExit(); - bool LoadItem(const std::string& item); - - private: - virtual void *ThreadMain(); - nemo::Nemo* nemo_db_; - blackwidow::BlackWidow* blackwidow_db_; - - int32_t migrator_id_; - int64_t migrate_key_num_; - std::atomic should_exit_; - slash::Mutex queue_mutex_; - slash::CondVar queue_cond_; - std::queue items_queue_; +class Migrator : public net::Thread { + public: + Migrator(int32_t migrator_id, nemo::Nemo* nemo_db, blackwidow::BlackWidow* blackwidow_db) + : nemo_db_(nemo_db), + blackwidow_db_(blackwidow_db), + migrator_id_(migrator_id), + migrate_key_num_(0), + should_exit_(false), + queue_cond_(&queue_mutex_) {} + virtual ~Migrator() {} + + int32_t queue_size(); + void PlusMigrateKey(); + void SetShouldExit(); + bool LoadItem(const std::string& item); + + private: + virtual void* ThreadMain(); + nemo::Nemo* nemo_db_; + blackwidow::BlackWidow* blackwidow_db_; + + int32_t migrator_id_; + int64_t migrate_key_num_; + std::atomic should_exit_; + slash::Mutex queue_mutex_; + slash::CondVar queue_cond_; + std::queue items_queue_; }; #endif // INCLUDE_MIGRATOR_H_ diff --git a/pika-tools/nemo_to_blackwidow/nemo_to_blackwidow.cc b/pika-tools/nemo_to_blackwidow/nemo_to_blackwidow.cc index a88a14553e..a9b9740aff 100644 --- a/pika-tools/nemo_to_blackwidow/nemo_to_blackwidow.cc +++ b/pika-tools/nemo_to_blackwidow/nemo_to_blackwidow.cc @@ -5,13 +5,13 @@ #include +#include "blackwidow/blackwidow.h" #include "nemo.h" #include "slash/include/env.h" -#include "blackwidow/blackwidow.h" +#include "classify_thread.h" #include "migrator.h" #include "progress_thread.h" -#include "classify_thread.h" int32_t thread_num = 6; int32_t need_write_log = 0; @@ -40,7 +40,7 @@ void Usage() { std::cout << "\tNemo_to_Blackwidow reads data from Nemo DB and send to Blackwidow DB" << std::endl; std::cout << "\t-h -- displays this help information and exits" << std::endl; std::cout << "\t-n -- numbers of migrator, default = 6" << std::endl; - std::cout << "\t-l -- whether write log, default = 0"<< std::endl; + std::cout << "\t-l -- whether write log, default = 0" << std::endl; std::cout << "\t-b -- number of members in multiple data structures per migration, default = 512" << std::endl; std::cout << "\texample: ./nemo_to_blackwidow ./nemo_db ./blackwidow_db -n 10 -l 0 -b 512" << std::endl; } @@ -51,15 +51,12 @@ static void GlogInit() { } FLAGS_log_dir = "./log"; - FLAGS_max_log_size = 2048; // log file 2GB + FLAGS_max_log_size = 2048; // log file 2GB ::google::InitGoogleLogging("nemo_to_blackwidow"); } -int main(int argc, char **argv) { - if (argc != 3 - && argc != 5 - && argc != 7 - && argc != 9) { +int main(int argc, char** argv) { + if (argc != 3 && argc != 5 && argc != 7 && argc != 9) { Usage(); exit(-1); } @@ -103,8 +100,8 @@ int main(int argc, char **argv) { // Init nemo db nemo::Options nemo_option; nemo_option.create_if_missing = false; - nemo_option.write_buffer_size = 256 * 1024 * 1024; // 256M - nemo_option.target_file_size_base = 20 * 1024 * 1024; // 20M + nemo_option.write_buffer_size = 256 * 1024 * 1024; // 256M + nemo_option.target_file_size_base = 20 * 1024 * 1024; // 20M nemo::Nemo* nemo_db = new nemo::Nemo(nemo_db_path, nemo_option); if (nemo_db != NULL) { std::cout << "Open Nemo db success..." << std::endl; @@ -120,15 +117,13 @@ int main(int argc, char **argv) { bw_option.options.write_buffer_size = 256 * 1024 * 1024; // 256M bw_option.options.target_file_size_base = 20 * 1024 * 1024; // 20M blackwidow::BlackWidow* blackwidow_db = new blackwidow::BlackWidow(); - if (blackwidow_db != NULL - && (status = blackwidow_db->Open(bw_option, blackwidow_db_path)).ok()) { + if (blackwidow_db != NULL && (status = blackwidow_db->Open(bw_option, blackwidow_db_path)).ok()) { std::cout << "Open BlackWidow db success..." << std::endl; } else { std::cout << "Open BlackWidow db failed..." << std::endl; return -1; } - for (size_t idx = 0; idx < static_cast(thread_num); ++idx) { migrators.push_back(new Migrator(idx, nemo_db, blackwidow_db)); } @@ -179,10 +174,7 @@ int main(int argc, char **argv) { auto minutes = std::chrono::duration_cast(end_time - start_time).count(); auto seconds = std::chrono::duration_cast(end_time - start_time).count(); - std::cout << "Total Time Cost : " - << hours << " hours " - << minutes % 60 << " minutes " - << seconds % 60 << " seconds " + std::cout << "Total Time Cost : " << hours << " hours " << minutes % 60 << " minutes " << seconds % 60 << " seconds " << std::endl; return 0; } diff --git a/pika-tools/nemo_to_blackwidow/progress_thread.cc b/pika-tools/nemo_to_blackwidow/progress_thread.cc index 89651f50b4..61a4ad0dbe 100644 --- a/pika-tools/nemo_to_blackwidow/progress_thread.cc +++ b/pika-tools/nemo_to_blackwidow/progress_thread.cc @@ -5,9 +5,7 @@ #include "progress_thread.h" -ProgressThread::ProgressThread(std::vector* classify_threads) - : classify_threads_(classify_threads) { -} +ProgressThread::ProgressThread(std::vector* classify_threads) : classify_threads_(classify_threads) {} bool ProgressThread::AllClassifyTreadFinish() { for (const auto& classify_thread : *classify_threads_) { @@ -23,11 +21,8 @@ void* ProgressThread::ThreadMain() { slash::MutexLock l(&mutex); bool is_finish = AllClassifyTreadFinish(); printf("\rstring keys: %5ld, hashes keys: %5ld, lists keys: %5ld, sets keys: %5ld, zsets keys: %5ld ", - (*classify_threads_)[0]->key_num(), - (*classify_threads_)[1]->key_num(), - (*classify_threads_)[2]->key_num(), - (*classify_threads_)[3]->key_num(), - (*classify_threads_)[4]->key_num()); + (*classify_threads_)[0]->key_num(), (*classify_threads_)[1]->key_num(), (*classify_threads_)[2]->key_num(), + (*classify_threads_)[3]->key_num(), (*classify_threads_)[4]->key_num()); fflush(stdout); if (is_finish) { break; @@ -38,4 +33,3 @@ void* ProgressThread::ThreadMain() { printf("\nClassify keys finished\n"); return NULL; } - diff --git a/pika-tools/nemo_to_blackwidow/progress_thread.h b/pika-tools/nemo_to_blackwidow/progress_thread.h index 0d176b4e4b..5fba197339 100644 --- a/pika-tools/nemo_to_blackwidow/progress_thread.h +++ b/pika-tools/nemo_to_blackwidow/progress_thread.h @@ -16,12 +16,13 @@ extern slash::Mutex mutex; class ProgressThread : public net::Thread { - public: - ProgressThread(std::vector* classify_threads); - private: - bool AllClassifyTreadFinish(); - virtual void *ThreadMain(); - std::vector* classify_threads_; + public: + ProgressThread(std::vector* classify_threads); + + private: + bool AllClassifyTreadFinish(); + virtual void* ThreadMain(); + std::vector* classify_threads_; }; #endif // INCLUDE_PROGRESS_THREAD_H_ diff --git a/pika-tools/nemo_to_blackwidow/utils.cc b/pika-tools/nemo_to_blackwidow/utils.cc index 4199b9552c..4f46ac5e03 100644 --- a/pika-tools/nemo_to_blackwidow/utils.cc +++ b/pika-tools/nemo_to_blackwidow/utils.cc @@ -3,12 +3,10 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include "iostream" #include "utils.h" +#include "iostream" -void EncodeKeyValue(const std::string& key, - const std::string& value, - std::string* dst) { +void EncodeKeyValue(const std::string& key, const std::string& value, std::string* dst) { dst->clear(); int32_t key_size = key.size(); int32_t value_size = value.size(); @@ -19,9 +17,7 @@ void EncodeKeyValue(const std::string& key, return; } -void DecodeKeyValue(const std::string& dst, - std::string* key, - std::string* value) { +void DecodeKeyValue(const std::string& dst, std::string* key, std::string* value) { const char* p = dst.data(); int32_t key_size = *(reinterpret_cast(p)); p += sizeof(int32_t); @@ -34,4 +30,3 @@ void DecodeKeyValue(const std::string& dst, p += value_size; return; } - diff --git a/pika-tools/pika-port/pika_port_2/binlog.cc b/pika-tools/pika-port/pika_port_2/binlog.cc index 9c16efb6b5..529a7eb994 100644 --- a/pika-tools/pika-port/pika_port_2/binlog.cc +++ b/pika-tools/pika-port/pika_port_2/binlog.cc @@ -6,11 +6,11 @@ #include "binlog.h" #include "binlog_log.h" -#include -#include -#include #include +#include #include +#include +#include #include #include @@ -28,10 +28,7 @@ std::string NewFileName(const std::string name, const uint32_t current) { /* * Version */ -Version::Version(slash::RWFile *save) - : pro_offset_(0), - pro_num_(0), - save_(save) { +Version::Version(slash::RWFile* save) : pro_offset_(0), pro_num_(0), save_(save) { assert(save_ != NULL); pthread_rwlock_init(&rwlock_, NULL); @@ -43,17 +40,17 @@ Version::~Version() { } Status Version::StableSave() { - char *p = save_->GetData(); + char* p = save_->GetData(); memcpy(p, &pro_offset_, sizeof(uint64_t)); p += 20; - //memcpy(p, &con_offset_, sizeof(uint64_t)); - //p += 8; - //memcpy(p, &item_num_, sizeof(uint32_t)); - //p += 4; + // memcpy(p, &con_offset_, sizeof(uint64_t)); + // p += 8; + // memcpy(p, &item_num_, sizeof(uint32_t)); + // p += 4; memcpy(p, &pro_num_, sizeof(uint32_t)); - //p += 4; - //memcpy(p, &con_num_, sizeof(uint32_t)); - //p += 4; + // p += 4; + // memcpy(p, &con_num_, sizeof(uint32_t)); + // p += 4; return Status::OK(); } @@ -61,11 +58,12 @@ Status Version::Init() { Status s; if (save_->GetData() != NULL) { memcpy((char*)(&pro_offset_), save_->GetData(), sizeof(uint64_t)); - //memcpy((char*)(&con_offset_), save_->GetData() + 8, sizeof(uint64_t)); + // memcpy((char*)(&con_offset_), save_->GetData() + 8, sizeof(uint64_t)); memcpy((char*)(&item_num_), save_->GetData() + 16, sizeof(uint32_t)); memcpy((char*)(&pro_num_), save_->GetData() + 20, sizeof(uint32_t)); - //memcpy((char*)(&con_num_), save_->GetData() + 24, sizeof(uint32_t)); - // DLOG(INFO) << "Version Init pro_offset "<< pro_offset_ << " itemnum " << item_num << " pro_num " << pro_num_ << " con_num " << con_num_; + // memcpy((char*)(&con_num_), save_->GetData() + 24, sizeof(uint32_t)); + // DLOG(INFO) << "Version Init pro_offset "<< pro_offset_ << " itemnum " << item_num << " pro_num " << pro_num_ << + // " con_num " << con_num_; return Status::OK(); } else { return Status::Corruption("version init error"); @@ -75,21 +73,20 @@ Status Version::Init() { /* * Binlog */ -Binlog::Binlog(const std::string& binlog_path, const int file_size) : - consumer_num_(0), - item_num_(0), - version_(NULL), - queue_(NULL), - versionfile_(NULL), - pro_num_(0), - pool_(NULL), - exit_all_consume_(false), - binlog_path_(binlog_path), - file_size_(file_size) { - +Binlog::Binlog(const std::string& binlog_path, const int file_size) + : consumer_num_(0), + item_num_(0), + version_(NULL), + queue_(NULL), + versionfile_(NULL), + pro_num_(0), + pool_(NULL), + exit_all_consume_(false), + binlog_path_(binlog_path), + file_size_(file_size) { // To intergrate with old version, we don't set mmap file size to 100M; - //slash::SetMmapBoundSize(file_size); - //slash::kMmapBoundSize = 1024 * 1024 * 100; + // slash::SetMmapBoundSize(file_size); + // slash::kMmapBoundSize = 1024 * 1024 * 100; Status s; @@ -126,7 +123,7 @@ Binlog::Binlog(const std::string& binlog_path, const int file_size) : pro_num_ = version_->pro_num_; // Debug - //version_->debug(); + // version_->debug(); } else { LOG(WARNING) << "Binlog: open versionfile error"; } @@ -167,7 +164,7 @@ Status Binlog::GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset) { } // Note: mutex lock should be held -Status Binlog::Put(const std::string &item) { +Status Binlog::Put(const std::string& item) { Status s; /* Check to roll log file */ @@ -184,10 +181,10 @@ Status Binlog::Put(const std::string &item) { slash::RWLock(&(version_->rwlock_), true); version_->pro_offset_ = 0; version_->pro_num_ = pro_num_; - //version_->set_pro_offset(0); - //version_->set_pro_num(pro_num_); + // version_->set_pro_offset(0); + // version_->set_pro_num(pro_num_); version_->StableSave(); - //version_->debug(); + // version_->debug(); } InitLogFile(); } @@ -196,9 +193,9 @@ Status Binlog::Put(const std::string &item) { s = Produce(Slice(item.data(), item.size()), &pro_offset); if (s.ok()) { slash::RWLock(&(version_->rwlock_), true); - //version_->plus_item_num(); + // version_->plus_item_num(); version_->pro_offset_ = pro_offset; - //version_->set_pro_offset(pro_offset); + // version_->set_pro_offset(pro_offset); version_->StableSave(); } @@ -223,11 +220,11 @@ Status Binlog::Put(const char* item, int len) { slash::RWLock(&(version_->rwlock_), true); version_->pro_offset_ = 0; version_->pro_num_ = pro_num_; - //version_->set_pro_offset(0); - //version_->set_pro_num(pro_num_); + // version_->set_pro_offset(0); + // version_->set_pro_num(pro_num_); version_->StableSave(); } - //version_->debug(); + // version_->debug(); InitLogFile(); } @@ -237,53 +234,53 @@ Status Binlog::Put(const char* item, int len) { if (s.ok()) { slash::RWLock(&(version_->rwlock_), true); version_->pro_offset_ = pro_offset; - //version_->plus_item_num(); - //version_->set_pro_offset(pro_offset); + // version_->plus_item_num(); + // version_->set_pro_offset(pro_offset); version_->StableSave(); } return s; } - -Status Binlog::EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset) { - Status s; - assert(n <= 0xffffff); - assert(block_offset_ + kHeaderSize + n <= kBlockSize); - - char buf[kHeaderSize]; - - uint64_t now ; - struct timeval tv; - gettimeofday(&tv, NULL); - now = tv.tv_sec; - buf[0] = static_cast(n & 0xff); - buf[1] = static_cast((n & 0xff00) >> 8); - buf[2] = static_cast(n >> 16); - buf[3] = static_cast(now & 0xff); - buf[4] = static_cast((now & 0xff00) >> 8); - buf[5] = static_cast((now & 0xff0000) >> 16); - buf[6] = static_cast((now & 0xff000000) >> 24); - buf[7] = static_cast(t); - - s = queue_->Append(Slice(buf, kHeaderSize)); + +Status Binlog::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset) { + Status s; + assert(n <= 0xffffff); + assert(block_offset_ + kHeaderSize + n <= kBlockSize); + + char buf[kHeaderSize]; + + uint64_t now; + struct timeval tv; + gettimeofday(&tv, NULL); + now = tv.tv_sec; + buf[0] = static_cast(n & 0xff); + buf[1] = static_cast((n & 0xff00) >> 8); + buf[2] = static_cast(n >> 16); + buf[3] = static_cast(now & 0xff); + buf[4] = static_cast((now & 0xff00) >> 8); + buf[5] = static_cast((now & 0xff0000) >> 16); + buf[6] = static_cast((now & 0xff000000) >> 24); + buf[7] = static_cast(t); + + s = queue_->Append(Slice(buf, kHeaderSize)); + if (s.ok()) { + s = queue_->Append(Slice(ptr, n)); if (s.ok()) { - s = queue_->Append(Slice(ptr, n)); - if (s.ok()) { - s = queue_->Flush(); - } + s = queue_->Flush(); } - block_offset_ += static_cast(kHeaderSize + n); - // log_info("block_offset %d", (kHeaderSize + n)); + } + block_offset_ += static_cast(kHeaderSize + n); + // log_info("block_offset %d", (kHeaderSize + n)); - *temp_pro_offset += kHeaderSize + n; - //version_->rise_pro_offset((uint64_t)(kHeaderSize + n)); - //version_->StableSave(); - return s; + *temp_pro_offset += kHeaderSize + n; + // version_->rise_pro_offset((uint64_t)(kHeaderSize + n)); + // version_->StableSave(); + return s; } -Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { +Status Binlog::Produce(const Slice& item, int* temp_pro_offset) { Status s; - const char *ptr = item.data(); + const char* ptr = item.data(); size_t left = item.size(); bool begin = true; @@ -294,9 +291,9 @@ Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { if (static_cast(leftover) < kHeaderSize) { if (leftover > 0) { queue_->Append(Slice("\x00\x00\x00\x00\x00\x00\x00", leftover)); - //version_->rise_pro_offset(leftover); + // version_->rise_pro_offset(leftover); *temp_pro_offset += leftover; - //version_->StableSave(); + // version_->StableSave(); } block_offset_ = 0; } @@ -323,12 +320,12 @@ Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { return s; } - -Status Binlog::AppendBlank(slash::WritableFile *file, uint64_t len) { + +Status Binlog::AppendBlank(slash::WritableFile* file, uint64_t len) { if (len < kHeaderSize) { return Status::OK(); } - + uint64_t pos = 0; std::string blank(kBlockSize, ' '); @@ -342,7 +339,7 @@ Status Binlog::AppendBlank(slash::WritableFile *file, uint64_t len) { if (len % kBlockSize < kHeaderSize) { n = 0; } else { - n = (uint32_t) ((len % kBlockSize) - kHeaderSize); + n = (uint32_t)((len % kBlockSize) - kHeaderSize); } char buf[kBlockSize]; @@ -395,8 +392,8 @@ Status Binlog::SetProducerStatus(uint32_t pro_num, uint64_t pro_offset) { slash::RWLock(&(version_->rwlock_), true); version_->pro_num_ = pro_num; version_->pro_offset_ = pro_offset; - //version_->set_pro_num(pro_num); - //version_->set_pro_offset(pro_offset); + // version_->set_pro_num(pro_num); + // version_->set_pro_offset(pro_offset); version_->StableSave(); } diff --git a/pika-tools/pika-port/pika_port_2/binlog.h b/pika-tools/pika-port/pika_port_2/binlog.h index c800ef5c20..b4c7e613ac 100644 --- a/pika-tools/pika-port/pika_port_2/binlog.h +++ b/pika-tools/pika-port/pika_port_2/binlog.h @@ -6,40 +6,38 @@ #ifndef BINLOG_H_ #define BINLOG_H_ +#include #include +#include #include #include -#include -#include #ifndef __STDC_FORMAT_MACROS -# define __STDC_FORMAT_MACROS -# include -#endif +# define __STDC_FORMAT_MACROS +# include +#endif +#include "pika_define.h" #include "slash/include/env.h" -#include "slash/include/slash_status.h" #include "slash/include/slash_mutex.h" -#include "pika_define.h" +#include "slash/include/slash_status.h" -using slash::Status; using slash::Slice; - +using slash::Status; std::string NewFileName(const std::string name, const uint32_t current); class Version; -class Binlog -{ +class Binlog { public: Binlog(const std::string& Binlog_path, const int file_size = 100 * 1024 * 1024); ~Binlog(); - void Lock() { mutex_.Lock(); } - void Unlock() { mutex_.Unlock(); } + void Lock() { mutex_.Lock(); } + void Unlock() { mutex_.Unlock(); } - Status Put(const std::string &item); + Status Put(const std::string& item); Status Put(const char* item, int len); Status GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset); @@ -48,34 +46,29 @@ class Binlog */ Status SetProducerStatus(uint32_t filenum, uint64_t pro_offset); - static Status AppendBlank(slash::WritableFile *file, uint64_t len); - - slash::WritableFile *queue() { return queue_; } + static Status AppendBlank(slash::WritableFile* file, uint64_t len); + slash::WritableFile* queue() { return queue_; } - uint64_t file_size() { - return file_size_; - } + uint64_t file_size() { return file_size_; } std::string filename; private: - void InitLogFile(); - Status EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset); - + Status EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset); /* * Produce */ - Status Produce(const Slice &item, int *pro_offset); + Status Produce(const Slice& item, int* pro_offset); uint32_t consumer_num_; uint64_t item_num_; Version* version_; - slash::WritableFile *queue_; - slash::RWFile *versionfile_; + slash::WritableFile* queue_; + slash::RWFile* versionfile_; slash::Mutex mutex_; @@ -90,7 +83,7 @@ class Binlog uint64_t file_size_; // Not use - //int32_t retry_; + // int32_t retry_; // No copying allowed Binlog(const Binlog&); @@ -101,7 +94,7 @@ class Binlog // to be compatable with version 1.x . class Version { public: - Version(slash::RWFile *save); + Version(slash::RWFile* save); ~Version(); Status Init(); @@ -109,10 +102,10 @@ class Version { // RWLock should be held when access members. Status StableSave(); - uint32_t item_num() { return item_num_; } + uint32_t item_num() { return item_num_; } void set_item_num(uint32_t item_num) { item_num_ = item_num; } - void plus_item_num() { item_num_++; } - void minus_item_num() { item_num_--; } + void plus_item_num() { item_num_++; } + void minus_item_num() { item_num_--; } uint64_t pro_offset_; uint32_t pro_num_; @@ -120,12 +113,11 @@ class Version { void debug() { slash::RWLock(&rwlock_, false); - printf ("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); + printf("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); } private: - - slash::RWFile *save_; + slash::RWFile* save_; // Not used uint64_t con_offset_; diff --git a/pika-tools/pika-port/pika_port_2/binlog_const.cc b/pika-tools/pika-port/pika_port_2/binlog_const.cc index 9c43be7419..1bfb7d65b9 100644 --- a/pika-tools/pika-port/pika_port_2/binlog_const.cc +++ b/pika-tools/pika-port/pika_port_2/binlog_const.cc @@ -5,25 +5,25 @@ std::string PikaState(int state) { switch (state) { case PIKA_REPL_NO_CONNECT: - return "PIKA_REPL_NO_CONNECT"; + return "PIKA_REPL_NO_CONNECT"; case PIKA_REPL_CONNECT: - return "PIKA_REPL_CONNECT"; + return "PIKA_REPL_CONNECT"; case PIKA_REPL_CONNECTING: - return "PIKA_REPL_CONNECTING"; + return "PIKA_REPL_CONNECTING"; case PIKA_REPL_CONNECTED: - return "PIKA_REPL_CONNECTED"; + return "PIKA_REPL_CONNECTED"; case PIKA_REPL_WAIT_DBSYNC: - return "PIKA_REPL_WAIT_DBSYNC"; + return "PIKA_REPL_WAIT_DBSYNC"; case PIKA_REPL_ERROR: - return "PIKA_REPL_ERROR"; + return "PIKA_REPL_ERROR"; default: - return "PIKA_REPL_UNKNOWN"; + return "PIKA_REPL_UNKNOWN"; } return "PIKA_REPL_UNKNOWN"; @@ -53,4 +53,3 @@ std::string PikaRole(int role) { return roleStr; } - diff --git a/pika-tools/pika-port/pika_port_2/binlog_const.h b/pika-tools/pika-port/pika_port_2/binlog_const.h index a90a58a311..ea633bac19 100644 --- a/pika-tools/pika-port/pika_port_2/binlog_const.h +++ b/pika-tools/pika-port/pika_port_2/binlog_const.h @@ -17,7 +17,6 @@ const int64_t kDataSetNum = 5; #include std::string PikaState(int state); -std::string PikaRole(int role) ; +std::string PikaRole(int role); #endif - diff --git a/pika-tools/pika-port/pika_port_2/binlog_log.h b/pika-tools/pika-port/pika_port_2/binlog_log.h index e8f03be262..43e1e1b72e 100644 --- a/pika-tools/pika-port/pika_port_2/binlog_log.h +++ b/pika-tools/pika-port/pika_port_2/binlog_log.h @@ -1,13 +1,11 @@ #ifndef BINLOG_LOG_H__ #define BINLOG_LOG_H__ -#define pline(fmt, ...) printf(fmt "\n", ##__VA_ARGS__) -#define pinfo(fmt, ...) \ - printf("\033[1;34;40m%s-%s-%d: " fmt "\033[0m\n", ((char*)__FILE__), \ - (char*)__func__, (int)__LINE__, ##__VA_ARGS__) -#define perr(fmt, ...) \ - fprintf(stderr, "\033[1;31;40m%s-%s-%d: error: " fmt "\033[0m\n", \ - (char*)__FILE__, (char*)__func__, (int)__LINE__, ##__VA_ARGS__) +#define pline(fmt, ...) printf(fmt "\n", ##__VA_ARGS__) +#define pinfo(fmt, ...) \ + printf("\033[1;34;40m%s-%s-%d: " fmt "\033[0m\n", ((char*)__FILE__), (char*)__func__, (int)__LINE__, ##__VA_ARGS__) +#define perr(fmt, ...) \ + fprintf(stderr, "\033[1;31;40m%s-%s-%d: error: " fmt "\033[0m\n", (char*)__FILE__, (char*)__func__, (int)__LINE__, \ + ##__VA_ARGS__) #endif - diff --git a/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.cc b/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.cc index 7f6f8e66ae..ae316b219e 100644 --- a/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.cc +++ b/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.cc @@ -5,9 +5,9 @@ #include -#include "net/include/net_conn.h" #include "binlog_receiver_thread.h" #include "master_conn.h" +#include "net/include/net_conn.h" #include "pika_port.h" #include "port_conf.h" @@ -15,11 +15,10 @@ extern PikaPort* g_pika_port; BinlogReceiverThread::BinlogReceiverThread(std::string host, int port, int cron_interval) - : conn_factory_(this), handles_(this) { + : conn_factory_(this), handles_(this) { // thread_rep_ = net::NewHolyThread(port, &conn_factory_, // cron_interval, &handles_); - thread_rep_ = net::NewHolyThread(host, port, &conn_factory_, - cron_interval, &handles_); + thread_rep_ = net::NewHolyThread(host, port, &conn_factory_, cron_interval, &handles_); // to prevent HolyThread::DoCronTask close the pika sender connection thread_rep_->set_keepalive_timeout(0); } @@ -27,19 +26,16 @@ BinlogReceiverThread::BinlogReceiverThread(std::string host, int port, int cron_ BinlogReceiverThread::~BinlogReceiverThread() { thread_rep_->StopThread(); DLOG(INFO) << "BinlogReceiver thread " << thread_rep_->thread_id() << " exit!!!"; - delete thread_rep_; + delete thread_rep_; } -int BinlogReceiverThread::StartThread() { - return thread_rep_->StartThread(); -} +int BinlogReceiverThread::StartThread() { return thread_rep_->StartThread(); } bool BinlogReceiverThread::Handles::AccessHandle(std::string& ip) const { if (ip == "127.0.0.1") { ip = g_port_conf.local_ip; } - if (binlog_receiver_->thread_rep_->conn_num() != 0 || - !g_pika_port->ShouldAccessConnAsMaster(ip)) { + if (binlog_receiver_->thread_rep_->conn_num() != 0 || !g_pika_port->ShouldAccessConnAsMaster(ip)) { DLOG(INFO) << "BinlogReceiverThread AccessHandle failed"; return false; } @@ -47,6 +43,4 @@ bool BinlogReceiverThread::Handles::AccessHandle(std::string& ip) const { return true; } -void BinlogReceiverThread::KillBinlogSender() { - thread_rep_->KillAllConns(); -} +void BinlogReceiverThread::KillBinlogSender() { thread_rep_->KillAllConns(); } diff --git a/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.h b/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.h index 7de4a4a30e..ca88eb7829 100644 --- a/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.h +++ b/pika-tools/pika-port/pika_port_2/binlog_receiver_thread.h @@ -6,16 +6,16 @@ #ifndef BINLOG_RECEIVER_THREAD_H_ #define BINLOG_RECEIVER_THREAD_H_ -#include #include +#include -#include "net/include/server_thread.h" -#include "slash/include/slash_mutex.h" #include "include/pika_define.h" #include "master_conn.h" +#include "net/include/server_thread.h" +#include "slash/include/slash_mutex.h" class BinlogReceiverThread { -public: + public: BinlogReceiverThread(std::string host, int port, int cron_interval = 0); virtual ~BinlogReceiverThread(); int StartThread(); @@ -25,15 +25,10 @@ class BinlogReceiverThread { private: class MasterConnFactory : public net::ConnFactory { public: - explicit MasterConnFactory(BinlogReceiverThread* binlog_receiver) - : binlog_receiver_(binlog_receiver) { - } + explicit MasterConnFactory(BinlogReceiverThread* binlog_receiver) : binlog_receiver_(binlog_receiver) {} - virtual net::PinkConn *NewPinkConn( - int connfd, - const std::string &ip_port, - net::ServerThread *thread, - void* worker_specific_data) const override { + virtual net::PinkConn* NewPinkConn(int connfd, const std::string& ip_port, net::ServerThread* thread, + void* worker_specific_data) const override { return new MasterConn(connfd, ip_port, binlog_receiver_); } @@ -42,14 +37,12 @@ class BinlogReceiverThread { }; class Handles : public net::ServerHandle { - public: - explicit Handles(BinlogReceiverThread* binlog_receiver) - : binlog_receiver_(binlog_receiver) { - } + public: + explicit Handles(BinlogReceiverThread* binlog_receiver) : binlog_receiver_(binlog_receiver) {} bool AccessHandle(std::string& ip) const override; - private: + private: BinlogReceiverThread* binlog_receiver_; }; diff --git a/pika-tools/pika-port/pika_port_2/main.cc b/pika-tools/pika-port/pika_port_2/main.cc index e2e804e25b..571b82f94e 100644 --- a/pika-tools/pika-port/pika_port_2/main.cc +++ b/pika-tools/pika-port/pika_port_2/main.cc @@ -3,12 +3,12 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. +#include #include -#include #include -#include #include -#include +#include +#include #include "pika_port.h" #include "port_conf.h" @@ -19,7 +19,7 @@ PikaPort* g_pika_port; static void GlogInit(std::string& log_path, bool is_daemon) { if (!slash::FileExists(log_path)) { - slash::CreatePath(log_path); + slash::CreatePath(log_path); } if (!is_daemon) { @@ -34,7 +34,7 @@ static void GlogInit(std::string& log_path, bool is_daemon) { static void daemonize() { if (fork() != 0) exit(0); /* parent exits */ - setsid(); /* create a new session */ + setsid(); /* create a new session */ } static void close_std() { @@ -62,33 +62,31 @@ static void SignalSetup() { signal(SIGTERM, &IntSigHandle); } -static void Usage() -{ - fprintf(stderr, - "Usage: pika_port [-h] [-t local_ip -p local_port -i master_ip -o master_port " - "-m forward_ip -n forward_port -x forward_thread_num -y forward_passwd]\n" - "-f filenum -s offset -w password -r rsync_dump_path -l log_path " - "\t-h -- show this help\n" - "\t-t -- local host ip(OPTIONAL default: 127.0.0.1) \n" - "\t-p -- local port(OPTIONAL) \n" - "\t-i -- master ip(OPTIONAL default: 127.0.0.1) \n" - "\t-o -- master port(REQUIRED) \n" - "\t-m -- forward ip(OPTIONAL default: 127.0.0.1) \n" - "\t-n -- forward port(REQUIRED) \n" - "\t-x -- forward thread num(OPTIONAL default: 1) \n" - "\t-y -- forward password(OPTIONAL) \n" - "\t-f -- binlog filenum(OPTIONAL default: local offset) \n" - "\t-s -- binlog offset(OPTIONAL default: local offset) \n" - "\t-w -- password for master(OPTIONAL) \n" - "\t-r -- rsync dump data path(OPTIONAL default: ./rsync_dump) \n" - "\t-l -- local log path(OPTIONAL default: ./log) \n" - "\t-d -- daemonize(OPTIONAL) \n" - " example: ./pika_port -t 127.0.0.1 -p 12345 -i 127.0.0.1 -o 9221 " - "-m 127.0.0.1 -n 6379 -x 7 -f 0 -s 0 -w abc -l ./log -r ./rsync_dump -d\n" - ); +static void Usage() { + fprintf(stderr, + "Usage: pika_port [-h] [-t local_ip -p local_port -i master_ip -o master_port " + "-m forward_ip -n forward_port -x forward_thread_num -y forward_passwd]\n" + "-f filenum -s offset -w password -r rsync_dump_path -l log_path " + "\t-h -- show this help\n" + "\t-t -- local host ip(OPTIONAL default: 127.0.0.1) \n" + "\t-p -- local port(OPTIONAL) \n" + "\t-i -- master ip(OPTIONAL default: 127.0.0.1) \n" + "\t-o -- master port(REQUIRED) \n" + "\t-m -- forward ip(OPTIONAL default: 127.0.0.1) \n" + "\t-n -- forward port(REQUIRED) \n" + "\t-x -- forward thread num(OPTIONAL default: 1) \n" + "\t-y -- forward password(OPTIONAL) \n" + "\t-f -- binlog filenum(OPTIONAL default: local offset) \n" + "\t-s -- binlog offset(OPTIONAL default: local offset) \n" + "\t-w -- password for master(OPTIONAL) \n" + "\t-r -- rsync dump data path(OPTIONAL default: ./rsync_dump) \n" + "\t-l -- local log path(OPTIONAL default: ./log) \n" + "\t-d -- daemonize(OPTIONAL) \n" + " example: ./pika_port -t 127.0.0.1 -p 12345 -i 127.0.0.1 -o 9221 " + "-m 127.0.0.1 -n 6379 -x 7 -f 0 -s 0 -w abc -l ./log -r ./rsync_dump -d\n"); } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { if (argc < 2) { Usage(); exit(-1); @@ -155,14 +153,14 @@ int main(int argc, char *argv[]) { case 'r': snprintf(buf, 1024, "%s", optarg); g_port_conf.dump_path = std::string(buf); - if (g_port_conf.dump_path[g_port_conf.dump_path.length() - 1] != '/' ) { + if (g_port_conf.dump_path[g_port_conf.dump_path.length() - 1] != '/') { g_port_conf.dump_path.append("/"); } break; case 'l': snprintf(buf, 1024, "%s", optarg); g_port_conf.log_path = std::string(buf); - if (g_port_conf.log_path[g_port_conf.log_path.length() - 1] != '/' ) { + if (g_port_conf.log_path[g_port_conf.log_path.length() - 1] != '/') { g_port_conf.log_path.append("/"); } break; @@ -188,19 +186,19 @@ int main(int argc, char *argv[]) { std::cout << "local_ip:" << g_port_conf.local_ip << " " << "local_port:" << g_port_conf.local_port << " " - << "master_ip:" << g_port_conf.master_ip << " " - << "master_port:" << g_port_conf.master_port << " " - << "forward_ip:" << g_port_conf.forward_ip << " " - << "forward_port:" << g_port_conf.forward_port << " " - << "forward_passwd:" << g_port_conf.forward_passwd << " " + << "master_ip:" << g_port_conf.master_ip << " " + << "master_port:" << g_port_conf.master_port << " " + << "forward_ip:" << g_port_conf.forward_ip << " " + << "forward_port:" << g_port_conf.forward_port << " " + << "forward_passwd:" << g_port_conf.forward_passwd << " " << "forward_thread_num:" << g_port_conf.forward_thread_num << " " - << "log_path:" << g_port_conf.log_path << " " - << "dump_path:" << g_port_conf.dump_path << " " - << "filenum:" << g_port_conf.filenum << " " - << "offset:" << g_port_conf.offset << " " - << "passwd:" << g_port_conf.passwd << std::endl; + << "log_path:" << g_port_conf.log_path << " " + << "dump_path:" << g_port_conf.dump_path << " " + << "filenum:" << g_port_conf.filenum << " " + << "offset:" << g_port_conf.offset << " " + << "passwd:" << g_port_conf.passwd << std::endl; if (g_port_conf.master_port == 0 || g_port_conf.forward_port == 0) { - fprintf (stderr, "Invalid Arguments\n" ); + fprintf(stderr, "Invalid Arguments\n"); Usage(); exit(-1); } diff --git a/pika-tools/pika-port/pika_port_2/master_conn.cc b/pika-tools/pika-port/pika_port_2/master_conn.cc index 2113b11f71..2601585e9a 100644 --- a/pika-tools/pika-port/pika_port_2/master_conn.cc +++ b/pika-tools/pika-port/pika_port_2/master_conn.cc @@ -3,45 +3,42 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include #include "master_conn.h" +#include #include "binlog_receiver_thread.h" #include "include/pika_command.h" #include "include/pika_slot.h" #include "pika_port.h" -extern PikaPort *g_pika_port; +extern PikaPort* g_pika_port; -MasterConn::MasterConn(int fd, std::string ip_port, - BinlogReceiverThread* binlog_receiver) - : RedisConn(fd, ip_port, NULL), - self_thread_(binlog_receiver) { -} +MasterConn::MasterConn(int fd, std::string ip_port, BinlogReceiverThread* binlog_receiver) + : RedisConn(fd, ip_port, NULL), self_thread_(binlog_receiver) {} void MasterConn::RestoreArgs(net::RedisCmdArgsType& argv) { raw_args_.clear(); size_t num = argv.size(); if (argv.size() > 4 && *(argv.end() - 4) == kPikaBinlogMagic) { - num = argv.size()- 4; + num = argv.size() - 4; } if (argv[1].find(SlotKeyPrefix) != std::string::npos) { - return; + return; } RedisAppendLen(raw_args_, num, "*"); PikaCmdArgsType::const_iterator it = argv.begin(); - for (size_t idx = 0; idx < num && it != argv.end(); ++ it, ++ idx) { + for (size_t idx = 0; idx < num && it != argv.end(); ++it, ++idx) { RedisAppendLen(raw_args_, (*it).size(), "$"); RedisAppendContent(raw_args_, *it); } } int MasterConn::DealMessage(net::RedisCmdArgsType& argv, std::string* response) { - //no reply - //eq set_is_reply(false); + // no reply + // eq set_is_reply(false); // if (argv.empty()) { - if (argv.size() < 5) { // special chars: __PIKA_X#$SKGI\r\n1\r\n[\r\n + if (argv.size() < 5) { // special chars: __PIKA_X#$SKGI\r\n1\r\n[\r\n // return -2; return 0; } diff --git a/pika-tools/pika-port/pika_port_2/master_conn.h b/pika-tools/pika-port/pika_port_2/master_conn.h index 4ee7c20664..6e0058f064 100644 --- a/pika-tools/pika-port/pika_port_2/master_conn.h +++ b/pika-tools/pika-port/pika_port_2/master_conn.h @@ -6,19 +6,19 @@ #ifndef MASTER_CONN_H_ #define MASTER_CONN_H_ -#include "net/include/redis_conn.h" -#include "net/include/net_thread.h" #include "include/pika_command.h" +#include "net/include/net_thread.h" +#include "net/include/redis_conn.h" class BinlogReceiverThread; -class MasterConn: public net::RedisConn { -public: +class MasterConn : public net::RedisConn { + public: MasterConn(int fd, std::string ip_port, BinlogReceiverThread* binlog_receiver); virtual ~MasterConn() {} virtual int DealMessage(net::RedisCmdArgsType& argv, std::string* response); -private: + private: BinlogReceiverThread* self_thread_; void RestoreArgs(net::RedisCmdArgsType&); std::string raw_args_; diff --git a/pika-tools/pika-port/pika_port_2/migrator_thread.cc b/pika-tools/pika-port/pika_port_2/migrator_thread.cc index 1271cd11c7..27386ed3ca 100644 --- a/pika-tools/pika-port/pika_port_2/migrator_thread.cc +++ b/pika-tools/pika-port/pika_port_2/migrator_thread.cc @@ -1,70 +1,69 @@ #include "migrator_thread.h" -MigratorThread::~MigratorThread() { -} +MigratorThread::~MigratorThread() {} void MigratorThread::MigrateDB(const char type) { - if (type == nemo::DataType::kKv) { - nemo::KIterator *it = db_->KScan("", "", -1, false); - std::string key, value; + if (type == nemo::DataType::kKv) { + nemo::KIterator* it = db_->KScan("", "", -1, false); + std::string key, value; - while (it->Valid()) { - key = it->key(); - value = it->value(); - net::RedisCmdArgsType argv; - std::string cmd; + while (it->Valid()) { + key = it->key(); + value = it->value(); + net::RedisCmdArgsType argv; + std::string cmd; - int64_t ttl; - db_->TTL(key, &ttl); + int64_t ttl; + db_->TTL(key, &ttl); - argv.push_back("SET"); - argv.push_back(key); - argv.push_back(value); - if (ttl > 0) { - argv.push_back("EX"); - argv.push_back(std::to_string(ttl)); - } - - it->Next(); - net::SerializeRedisCommand(argv, &cmd); - PlusNum(); - cmd = 'k' + cmd; - DispatchKey(cmd); + argv.push_back("SET"); + argv.push_back(key); + argv.push_back(value); + if (ttl > 0) { + argv.push_back("EX"); + argv.push_back(std::to_string(ttl)); } - delete it; - } else { - char c_type = 'a'; - switch (type) { - case nemo::DataType::kHSize: - c_type = 'h'; - break; - case nemo::DataType::kSSize: - c_type = 's'; - break; - case nemo::DataType::kLMeta: - c_type = 'l'; - break; - case nemo::DataType::kZSize: - c_type = 'z'; - break; - } - rocksdb::Iterator *it = db_->Scanbytype(c_type); - std::string key_start = "a"; - key_start[0] = type; - it->Seek(key_start); - for (; it->Valid(); it->Next()) { - PlusNum(); - DispatchKey(it->key().ToString()); - } + + it->Next(); + net::SerializeRedisCommand(argv, &cmd); + PlusNum(); + cmd = 'k' + cmd; + DispatchKey(cmd); + } + delete it; + } else { + char c_type = 'a'; + switch (type) { + case nemo::DataType::kHSize: + c_type = 'h'; + break; + case nemo::DataType::kSSize: + c_type = 's'; + break; + case nemo::DataType::kLMeta: + c_type = 'l'; + break; + case nemo::DataType::kZSize: + c_type = 'z'; + break; + } + rocksdb::Iterator* it = db_->Scanbytype(c_type); + std::string key_start = "a"; + key_start[0] = type; + it->Seek(key_start); + for (; it->Valid(); it->Next()) { + PlusNum(); + DispatchKey(it->key().ToString()); } + } } -void MigratorThread::DispatchKey(const std::string &key) { +void MigratorThread::DispatchKey(const std::string& key) { (*senders_)[thread_index_]->LoadKey(key); thread_index_ = (thread_index_ + 1) % thread_num_; } -void *MigratorThread::ThreadMain() { +void* MigratorThread::ThreadMain() { MigrateDB(type_); should_exit_ = true; log_info("%c keys have been dispatched completly", static_cast(type_)); diff --git a/pika-tools/pika-port/pika_port_2/migrator_thread.h b/pika-tools/pika-port/pika_port_2/migrator_thread.h index 60652e0282..a13480aea6 100644 --- a/pika-tools/pika-port/pika_port_2/migrator_thread.h +++ b/pika-tools/pika-port/pika_port_2/migrator_thread.h @@ -8,32 +8,26 @@ class MigratorThread : public net::Thread { public: - MigratorThread(nemo::Nemo *db, std::vector *senders, char type, int thread_num) : - db_(db), - senders_(senders), - type_(type), - thread_num_(thread_num), - thread_index_(0), - num_(0) - { - } + MigratorThread(nemo::Nemo* db, std::vector* senders, char type, int thread_num) + : db_(db), senders_(senders), type_(type), thread_num_(thread_num), thread_index_(0), num_(0) {} int64_t num() { slash::MutexLock l(&num_mutex_); return num_; } - - virtual ~ MigratorThread(); + + virtual ~MigratorThread(); bool should_exit_; + private: - nemo::Nemo *db_; - std::vector *senders_; + nemo::Nemo* db_; + std::vector* senders_; char type_; int thread_num_; int thread_index_; void MigrateDB(const char type); - void DispatchKey(const std::string &key); + void DispatchKey(const std::string& key); int64_t num_; slash::Mutex num_mutex_; @@ -42,6 +36,6 @@ class MigratorThread : public net::Thread { slash::MutexLock l(&num_mutex_); ++num_; } - virtual void *ThreadMain(); + virtual void* ThreadMain(); }; #endif diff --git a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_binlog.h b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_binlog.h index 5d7dfc53bc..0bf0e2238e 100644 --- a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_binlog.h +++ b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_binlog.h @@ -6,24 +6,24 @@ #ifndef PIKA_BINLOG_H_ #define PIKA_BINLOG_H_ +#include #include +#include #include #include -#include -#include #ifndef __STDC_FORMAT_MACROS -# define __STDC_FORMAT_MACROS -# include -#endif +# define __STDC_FORMAT_MACROS +# include +#endif -#include "slash/include/slash_status.h" -#include "slash/include/slash_mutex.h" -#include "slash/include/env.h" #include "include/pika_define.h" +#include "slash/include/env.h" +#include "slash/include/slash_mutex.h" +#include "slash/include/slash_status.h" -using slash::Status; using slash::Slice; +using slash::Status; std::string NewFileName(const std::string name, const uint32_t current); @@ -34,10 +34,10 @@ class Binlog { Binlog(const std::string& Binlog_path, const int file_size = 100 * 1024 * 1024); ~Binlog(); - void Lock() { mutex_.Lock(); } - void Unlock() { mutex_.Unlock(); } + void Lock() { mutex_.Lock(); } + void Unlock() { mutex_.Unlock(); } - Status Put(const std::string &item); + Status Put(const std::string& item); Status Put(const char* item, int len); Status GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset); @@ -51,33 +51,29 @@ class Binlog { Status SetDoubleRecvInfo(uint32_t double_filenum, uint64_t double_offset); - static Status AppendBlank(slash::WritableFile *file, uint64_t len); + static Status AppendBlank(slash::WritableFile* file, uint64_t len); - slash::WritableFile *queue() { return queue_; } + slash::WritableFile* queue() { return queue_; } - uint64_t file_size() { - return file_size_; - } + uint64_t file_size() { return file_size_; } std::string filename; private: - void InitLogFile(); - Status EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset); - + Status EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset); /* * Produce */ - Status Produce(const Slice &item, int *pro_offset); + Status Produce(const Slice& item, int* pro_offset); uint32_t consumer_num_; uint64_t item_num_; Version* version_; - slash::WritableFile *queue_; - slash::RWFile *versionfile_; + slash::WritableFile* queue_; + slash::RWFile* versionfile_; slash::Mutex mutex_; @@ -92,7 +88,7 @@ class Binlog { uint64_t file_size_; // Not use - //int32_t retry_; + // int32_t retry_; // No copying allowed Binlog(const Binlog&); @@ -103,7 +99,7 @@ class Binlog { // to be compatable with version 1.x . class Version { public: - Version(slash::RWFile *save); + Version(slash::RWFile* save); ~Version(); Status Init(); @@ -111,10 +107,10 @@ class Version { // RWLock should be held when access members. Status StableSave(); - uint32_t item_num() { return item_num_; } + uint32_t item_num() { return item_num_; } void set_item_num(uint32_t item_num) { item_num_ = item_num; } - void plus_item_num() { item_num_++; } - void minus_item_num() { item_num_--; } + void plus_item_num() { item_num_++; } + void minus_item_num() { item_num_--; } uint64_t pro_offset_; uint32_t pro_num_; @@ -127,12 +123,11 @@ class Version { void debug() { slash::RWLock(&rwlock_, false); - printf ("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); + printf("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); } private: - - slash::RWFile *save_; + slash::RWFile* save_; // Not used uint64_t con_offset_; diff --git a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_client_conn.h b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_client_conn.h index c9b496454f..da2cc0649c 100644 --- a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_client_conn.h +++ b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_client_conn.h @@ -9,16 +9,15 @@ #include #include -#include "net/include/redis_conn.h" -#include "net/include/net_thread.h" #include "include/pika_command.h" +#include "net/include/net_thread.h" +#include "net/include/redis_conn.h" class PikaWorkerSpecificData; -class PikaClientConn: public net::RedisConn { +class PikaClientConn : public net::RedisConn { public: - PikaClientConn(int fd, std::string ip_port, net::ServerThread *server_thread, - void* worker_specific_data); + PikaClientConn(int fd, std::string ip_port, net::ServerThread* server_thread, void* worker_specific_data); virtual ~PikaClientConn() {} int DealMessage(PikaCmdArgsType& argv, std::string* response) override; @@ -38,6 +37,7 @@ class PikaClientConn: public net::RedisConn { void Init(); bool IsAuthed(const CmdInfo* const cinfo_ptr); bool ChecknUpdate(const std::string& arg); + private: enum StatType { kNoAuthed = 0, diff --git a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_command.h b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_command.h index 49ee64d95b..b6ac00fb67 100644 --- a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_command.h +++ b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_command.h @@ -7,17 +7,17 @@ #define PIKA_COMMAND_H_ #include -#include #include +#include #include -#include "slash/include/slash_string.h" #include "net/include/redis_conn.h" +#include "slash/include/slash_string.h" const std::string kPikaBinlogMagic = "__PIKA_X#$SKGI"; -//Constant for command name -//Admin +// Constant for command name +// Admin const std::string kCmdNameSlaveof = "slaveof"; const std::string kCmdNameTrysync = "trysync"; const std::string kCmdNameInternalTrysync = "internaltrysync"; @@ -44,7 +44,7 @@ const std::string kCmdNameEcho = "echo"; const std::string kCmdNameTcmalloc = "tcmalloc"; #endif -//Migrate slot +// Migrate slot const std::string kCmdNameSlotsMgrtSlot = "slotsmgrtslot"; const std::string kCmdNameSlotsMgrtTagSlot = "slotsmgrttagslot"; const std::string kCmdNameSlotsMgrtOne = "slotsmgrtone"; @@ -63,7 +63,7 @@ const std::string kCmdNameSlotsMgrtExecWrapper = "slotsmgrt-exec-wrapper"; const std::string kCmdNameSlotsMgrtAsyncStatus = "slotsmgrt-async-status"; const std::string kCmdNameSlotsMgrtAsyncCancel = "slotsmgrt-async-cancel"; -//Kv +// Kv const std::string kCmdNameSet = "set"; const std::string kCmdNameGet = "get"; const std::string kCmdNameDel = "del"; @@ -93,7 +93,7 @@ const std::string kCmdNamePttl = "pttl"; const std::string kCmdNamePersist = "persist"; const std::string kCmdNameType = "type"; const std::string kCmdNameScan = "scan"; -//Hash +// Hash const std::string kCmdNameHDel = "hdel"; const std::string kCmdNameHSet = "hset"; const std::string kCmdNameHGet = "hget"; @@ -110,7 +110,7 @@ const std::string kCmdNameHStrlen = "hstrlen"; const std::string kCmdNameHVals = "hvals"; const std::string kCmdNameHScan = "hscan"; -//List +// List const std::string kCmdNameLIndex = "lindex"; const std::string kCmdNameLInsert = "linsert"; const std::string kCmdNameLLen = "llen"; @@ -126,14 +126,14 @@ const std::string kCmdNameRPopLPush = "rpoplpush"; const std::string kCmdNameRPush = "rpush"; const std::string kCmdNameRPushx = "rpushx"; -//BitMap +// BitMap const std::string kCmdNameBitSet = "setbit"; const std::string kCmdNameBitGet = "getbit"; const std::string kCmdNameBitPos = "bitpos"; const std::string kCmdNameBitOp = "bitop"; const std::string kCmdNameBitCount = "bitcount"; -//Zset +// Zset const std::string kCmdNameZAdd = "zadd"; const std::string kCmdNameZCard = "zcard"; const std::string kCmdNameZScan = "zscan"; @@ -156,7 +156,7 @@ const std::string kCmdNameZRemrangebyrank = "zremrangebyrank"; const std::string kCmdNameZRemrangebylex = "zremrangebylex"; const std::string kCmdNameZRemrangebyscore = "zremrangebyscore"; -//Set +// Set const std::string kCmdNameSAdd = "sadd"; const std::string kCmdNameSPop = "spop"; const std::string kCmdNameSCard = "scard"; @@ -173,12 +173,12 @@ const std::string kCmdNameSDiffstore = "sdiffstore"; const std::string kCmdNameSMove = "smove"; const std::string kCmdNameSRandmember = "srandmember"; -//HyperLogLog +// HyperLogLog const std::string kCmdNamePfAdd = "pfadd"; const std::string kCmdNamePfCount = "pfcount"; const std::string kCmdNamePfMerge = "pfmerge"; -//GEO +// GEO const std::string kCmdNameGeoAdd = "geoadd"; const std::string kCmdNameGeoPos = "geopos"; const std::string kCmdNameGeoDist = "geodist"; @@ -186,7 +186,7 @@ const std::string kCmdNameGeoHash = "geohash"; const std::string kCmdNameGeoRadius = "georadius"; const std::string kCmdNameGeoRadiusByMember = "georadiusbymember"; -//Pub/Sub +// Pub/Sub const std::string kCmdNamePublish = "publish"; const std::string kCmdNameSubscribe = "subscribe"; const std::string kCmdNameUnSubscribe = "unsubscribe"; @@ -195,75 +195,60 @@ const std::string kCmdNamePSubscribe = "psubscribe"; const std::string kCmdNamePUnSubscribe = "punsubscribe"; typedef net::RedisCmdArgsType PikaCmdArgsType; -static const int RAW_ARGS_LEN = 1024 * 1024; +static const int RAW_ARGS_LEN = 1024 * 1024; enum CmdFlagsMask { - kCmdFlagsMaskRW = 1, - kCmdFlagsMaskType = 30, - kCmdFlagsMaskLocal = 32, - kCmdFlagsMaskSuspend = 64, - kCmdFlagsMaskPrior = 128, - kCmdFlagsMaskAdminRequire = 256 + kCmdFlagsMaskRW = 1, + kCmdFlagsMaskType = 30, + kCmdFlagsMaskLocal = 32, + kCmdFlagsMaskSuspend = 64, + kCmdFlagsMaskPrior = 128, + kCmdFlagsMaskAdminRequire = 256 }; enum CmdFlags { - kCmdFlagsRead = 0, //default rw - kCmdFlagsWrite = 1, - kCmdFlagsAdmin = 0, //default type - kCmdFlagsKv = 2, - kCmdFlagsHash = 4, - kCmdFlagsList = 6, - kCmdFlagsSet = 8, - kCmdFlagsZset = 10, - kCmdFlagsBit = 12, - kCmdFlagsHyperLogLog = 14, - kCmdFlagsGeo = 16, - kCmdFlagsPubSub = 18, - kCmdFlagsNoLocal = 0, //default nolocal - kCmdFlagsLocal = 32, - kCmdFlagsNoSuspend = 0, //default nosuspend - kCmdFlagsSuspend = 64, - kCmdFlagsNoPrior = 0, //default noprior - kCmdFlagsPrior = 128, - kCmdFlagsNoAdminRequire = 0, //default no need admin - kCmdFlagsAdminRequire = 256 + kCmdFlagsRead = 0, // default rw + kCmdFlagsWrite = 1, + kCmdFlagsAdmin = 0, // default type + kCmdFlagsKv = 2, + kCmdFlagsHash = 4, + kCmdFlagsList = 6, + kCmdFlagsSet = 8, + kCmdFlagsZset = 10, + kCmdFlagsBit = 12, + kCmdFlagsHyperLogLog = 14, + kCmdFlagsGeo = 16, + kCmdFlagsPubSub = 18, + kCmdFlagsNoLocal = 0, // default nolocal + kCmdFlagsLocal = 32, + kCmdFlagsNoSuspend = 0, // default nosuspend + kCmdFlagsSuspend = 64, + kCmdFlagsNoPrior = 0, // default noprior + kCmdFlagsPrior = 128, + kCmdFlagsNoAdminRequire = 0, // default no need admin + kCmdFlagsAdminRequire = 256 }; - class CmdInfo { -public: - CmdInfo(const std::string _name, int _num, uint16_t _flag) - : name_(_name), arity_(_num), flag_(_flag) {} + public: + CmdInfo(const std::string _name, int _num, uint16_t _flag) : name_(_name), arity_(_num), flag_(_flag) {} bool CheckArg(int num) const { if ((arity_ > 0 && num != arity_) || (arity_ < 0 && num < -arity_)) { return false; } return true; } - bool is_write() const { - return ((flag_ & kCmdFlagsMaskRW) == kCmdFlagsWrite); - } - uint16_t flag_type() const { - return flag_ & kCmdFlagsMaskType; - } - bool is_local() const { - return ((flag_ & kCmdFlagsMaskLocal) == kCmdFlagsLocal); - } + bool is_write() const { return ((flag_ & kCmdFlagsMaskRW) == kCmdFlagsWrite); } + uint16_t flag_type() const { return flag_ & kCmdFlagsMaskType; } + bool is_local() const { return ((flag_ & kCmdFlagsMaskLocal) == kCmdFlagsLocal); } // Others need to be suspended when a suspend command run - bool is_suspend() const { - return ((flag_ & kCmdFlagsMaskSuspend) == kCmdFlagsSuspend); - } - bool is_prior() const { - return ((flag_ & kCmdFlagsMaskPrior) == kCmdFlagsPrior); - } + bool is_suspend() const { return ((flag_ & kCmdFlagsMaskSuspend) == kCmdFlagsSuspend); } + bool is_prior() const { return ((flag_ & kCmdFlagsMaskPrior) == kCmdFlagsPrior); } // Must with admin auth - bool is_admin_require() const { - return ((flag_ & kCmdFlagsMaskAdminRequire) == kCmdFlagsAdminRequire); - } - std::string name() const { - return name_; - } -private: + bool is_admin_require() const { return ((flag_ & kCmdFlagsMaskAdminRequire) == kCmdFlagsAdminRequire); } + std::string name() const { return name_; } + + private: std::string name_; int arity_; uint16_t flag_; @@ -273,12 +258,12 @@ class CmdInfo { }; void inline RedisAppendContent(std::string& str, const std::string& value); -void inline RedisAppendLen(std::string& str, int ori, const std::string &prefix); +void inline RedisAppendLen(std::string& str, int ori, const std::string& prefix); const std::string kNewLine = "\r\n"; class CmdRes { -public: + public: enum CmdRet { kNone = 0, kOk, @@ -303,101 +288,85 @@ class CmdRes { kErrOther, }; - CmdRes():ret_(kNone) {} + CmdRes() : ret_(kNone) {} - bool none() const { - return ret_ == kNone && message_.empty(); - } - bool ok() const { - return ret_ == kOk || ret_ == kNone; - } + bool none() const { return ret_ == kNone && message_.empty(); } + bool ok() const { return ret_ == kOk || ret_ == kNone; } void clear() { message_.clear(); ret_ = kNone; } - std::string raw_message() const { - return message_; - } + std::string raw_message() const { return message_; } std::string message() const { std::string result; switch (ret_) { - case kNone: - return message_; - case kOk: - return "+OK\r\n"; - case kPong: - return "+PONG\r\n"; - case kSyntaxErr: - return "-ERR syntax error\r\n"; - case kInvalidInt: - return "-ERR value is not an integer or out of range\r\n"; - case kInvalidBitInt: - return "-ERR bit is not an integer or out of range\r\n"; - case kInvalidBitOffsetInt: - return "-ERR bit offset is not an integer or out of range\r\n"; - case kWrongBitOpNotNum: - return "-ERR BITOP NOT must be called with a single source key.\r\n"; - - case kInvalidBitPosArgument: - return "-ERR The bit argument must be 1 or 0.\r\n"; - case kInvalidFloat: - return "-ERR value is not an float\r\n"; - case kOverFlow: - return "-ERR increment or decrement would overflow\r\n"; - case kNotFound: - return "-ERR no such key\r\n"; - case kOutOfRange: - return "-ERR index out of range\r\n"; - case kInvalidPwd: - return "-ERR invalid password\r\n"; - case kNoneBgsave: - return "-ERR No BGSave Works now\r\n"; - case kPurgeExist: - return "-ERR binlog already in purging...\r\n"; - case kInvalidParameter: - return "-ERR Invalid Argument\r\n"; - case kWrongNum: - result = "-ERR wrong number of arguments for '"; - result.append(message_); - result.append("' command\r\n"); - break; - case kInvalidIndex: - result = "-ERR invalid DB index\r\n"; - break; - case kInvalidDbType: - result = "-ERR invalid DB type\r\n"; - break; - case kErrOther: - result = "-ERR "; - result.append(message_); - result.append(kNewLine); - break; - default: - break; + case kNone: + return message_; + case kOk: + return "+OK\r\n"; + case kPong: + return "+PONG\r\n"; + case kSyntaxErr: + return "-ERR syntax error\r\n"; + case kInvalidInt: + return "-ERR value is not an integer or out of range\r\n"; + case kInvalidBitInt: + return "-ERR bit is not an integer or out of range\r\n"; + case kInvalidBitOffsetInt: + return "-ERR bit offset is not an integer or out of range\r\n"; + case kWrongBitOpNotNum: + return "-ERR BITOP NOT must be called with a single source key.\r\n"; + + case kInvalidBitPosArgument: + return "-ERR The bit argument must be 1 or 0.\r\n"; + case kInvalidFloat: + return "-ERR value is not an float\r\n"; + case kOverFlow: + return "-ERR increment or decrement would overflow\r\n"; + case kNotFound: + return "-ERR no such key\r\n"; + case kOutOfRange: + return "-ERR index out of range\r\n"; + case kInvalidPwd: + return "-ERR invalid password\r\n"; + case kNoneBgsave: + return "-ERR No BGSave Works now\r\n"; + case kPurgeExist: + return "-ERR binlog already in purging...\r\n"; + case kInvalidParameter: + return "-ERR Invalid Argument\r\n"; + case kWrongNum: + result = "-ERR wrong number of arguments for '"; + result.append(message_); + result.append("' command\r\n"); + break; + case kInvalidIndex: + result = "-ERR invalid DB index\r\n"; + break; + case kInvalidDbType: + result = "-ERR invalid DB type\r\n"; + break; + case kErrOther: + result = "-ERR "; + result.append(message_); + result.append(kNewLine); + break; + default: + break; } return result; } // Inline functions for Create Redis protocol - void AppendStringLen(int ori) { - RedisAppendLen(message_, ori, "$"); - } - void AppendArrayLen(int ori) { - RedisAppendLen(message_, ori, "*"); - } - void AppendInteger(int ori) { - RedisAppendLen(message_, ori, ":"); - } - void AppendContent(const std::string &value) { - RedisAppendContent(message_, value); - } - void AppendString(const std::string &value) { + void AppendStringLen(int ori) { RedisAppendLen(message_, ori, "$"); } + void AppendArrayLen(int ori) { RedisAppendLen(message_, ori, "*"); } + void AppendInteger(int ori) { RedisAppendLen(message_, ori, ":"); } + void AppendContent(const std::string& value) { RedisAppendContent(message_, value); } + void AppendString(const std::string& value) { AppendStringLen(value.size()); AppendContent(value); } - void AppendStringRaw(std::string &value) { - message_.append(value); - } + void AppendStringRaw(std::string& value) { message_.append(value); } void SetRes(CmdRet _ret, const std::string content = "") { ret_ = _ret; if (!content.empty()) { @@ -405,7 +374,7 @@ class CmdRes { } } -private: + private: std::string message_; CmdRet ret_; }; @@ -417,21 +386,16 @@ class Cmd { virtual void Do() = 0; - void Initial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info) { - res_.clear(); // Clear res content - Clear(); // Clear cmd, Derived class can has own implement + void Initial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info) { + res_.clear(); // Clear res content + Clear(); // Clear cmd, Derived class can has own implement DoInitial(argvs, ptr_info); }; - CmdRes& res() { - return res_; - } + CmdRes& res() { return res_; } - virtual std::string ToBinlog( - const PikaCmdArgsType& argv, - const std::string& server_id, - const std::string& binlog_info, - bool need_send_to_hub) { + virtual std::string ToBinlog(const PikaCmdArgsType& argv, const std::string& server_id, + const std::string& binlog_info, bool need_send_to_hub) { std::string res; res.reserve(RAW_ARGS_LEN); RedisAppendLen(res, argv.size() + 4, "*"); @@ -449,11 +413,8 @@ class Cmd { protected: CmdRes res_; - void AppendAffiliatedInfo( - std::string& res, - const std::string& server_id, - const std::string& binlog_info, - bool need_send_to_hub) { + void AppendAffiliatedInfo(std::string& res, const std::string& server_id, const std::string& binlog_info, + bool need_send_to_hub) { // kPikaBinlogMagic RedisAppendLen(res, kPikaBinlogMagic.size(), "$"); RedisAppendContent(res, kPikaBinlogMagic); @@ -470,8 +431,8 @@ class Cmd { } private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info) = 0; - virtual void Clear() {}; + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info) = 0; + virtual void Clear(){}; Cmd(const Cmd&); Cmd& operator=(const Cmd&); @@ -494,7 +455,7 @@ void RedisAppendContent(std::string& str, const std::string& value) { str.append(kNewLine); } -void RedisAppendLen(std::string& str, int ori, const std::string &prefix) { +void RedisAppendLen(std::string& str, int ori, const std::string& prefix) { char buf[32]; slash::ll2string(buf, 32, static_cast(ori)); str.append(prefix); diff --git a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_define.h b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_define.h index bee2c0c6bc..c98449c11a 100644 --- a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_define.h +++ b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_define.h @@ -6,7 +6,6 @@ #ifndef PIKA_DEFINE_H_ #define PIKA_DEFINE_H_ - #define PIKA_MAX_WORKER_THREAD_NUM 24 const std::string kPikaPidFile = "pika.pid"; @@ -16,11 +15,11 @@ struct WorkerCronTask { std::string ip_port; }; typedef WorkerCronTask MonitorCronTask; -//task define +// task define #define TASK_KILL 0 #define TASK_KILLALL 1 -//slave item +// slave item struct SlaveItem { int64_t sid; std::string ip_port; @@ -37,7 +36,7 @@ struct SlaveItem { #define SLAVE_ITEM_STAGE_ONE 1 #define SLAVE_ITEM_STAGE_TWO 2 -//repl_state_ +// repl_state_ #define PIKA_REPL_NO_CONNECT 0 #define PIKA_REPL_CONNECT 1 #define PIKA_REPL_CONNECTING 2 @@ -45,7 +44,7 @@ struct SlaveItem { #define PIKA_REPL_WAIT_DBSYNC 4 #define PIKA_REPL_ERROR 5 -//role +// role #define PIKA_ROLE_SINGLE 0 #define PIKA_ROLE_SLAVE 1 #define PIKA_ROLE_MASTER 2 @@ -54,8 +53,8 @@ struct SlaveItem { /* * The size of Binlogfile */ -//static uint64_t kBinlogSize = 128; -//static const uint64_t kBinlogSize = 1024 * 1024 * 100; +// static uint64_t kBinlogSize = 128; +// static const uint64_t kBinlogSize = 1024 * 1024 * 100; enum RecordType { kZeroType = 0, diff --git a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_slot.h b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_slot.h index 58f4632f7c..b7cbefb07f 100644 --- a/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_slot.h +++ b/pika-tools/pika-port/pika_port_2/pika2.3.6/include/pika_slot.h @@ -1,15 +1,15 @@ #ifndef PIKA_SLOT_H_ #define PIKA_SLOT_H_ -#include "net/include/net_thread.h" -#include "net/include/net_cli.h" -#include "include/pika_command.h" #include "include/pika_client_conn.h" +#include "include/pika_command.h" +#include "net/include/net_cli.h" +#include "net/include/net_thread.h" #include "strings.h" const std::string SlotKeyPrefix = "_internal:slotkey:4migrate:"; const size_t MaxKeySendSize = 10 * 1024; -//crc 32 +// crc 32 #define HASH_SLOTS_MASK 0x000003ff #define HASH_SLOTS_SIZE (HASH_SLOTS_MASK + 1) @@ -20,10 +20,10 @@ void CRC32TableInit(uint32_t poly); extern void InitCRC32Table(); -extern uint32_t CRC32Update(uint32_t crc, const char *buf, int len); +extern uint32_t CRC32Update(uint32_t crc, const char* buf, int len); -extern int SlotNum(const std::string &str); -extern int KeyType(const std::string key, std::string &key_type); +extern int SlotNum(const std::string& str); +extern int KeyType(const std::string key, std::string& key_type); extern void SlotKeyAdd(const std::string type, const std::string key); extern void SlotKeyRem(const std::string key); @@ -31,88 +31,96 @@ extern void KeyNotExistsRem(const std::string type, const std::string key); extern int KeyDelete(const std::string key, const char key_type); class SlotsMgrtTagSlotCmd : public Cmd { -public: - SlotsMgrtTagSlotCmd() {} - virtual void Do(); -private: - std::string dest_ip_; - int64_t dest_port_; - int64_t timeout_ms_; - int64_t slot_num_; - std::string key_; - char key_type_; - - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); - int SlotKeyPop(); + public: + SlotsMgrtTagSlotCmd() {} + virtual void Do(); + + private: + std::string dest_ip_; + int64_t dest_port_; + int64_t timeout_ms_; + int64_t slot_num_; + std::string key_; + char key_type_; + + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); + int SlotKeyPop(); }; class SlotsMgrtTagOneCmd : public Cmd { -public: - SlotsMgrtTagOneCmd() {} - virtual void Do(); -private: - std::string dest_ip_; - int64_t dest_port_; - int64_t timeout_ms_; - std::string key_; - int64_t slot_num_; - char key_type_; - - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); - int KeyTypeCheck(); - int SlotKeyRemCheck(); + public: + SlotsMgrtTagOneCmd() {} + virtual void Do(); + + private: + std::string dest_ip_; + int64_t dest_port_; + int64_t timeout_ms_; + std::string key_; + int64_t slot_num_; + char key_type_; + + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); + int KeyTypeCheck(); + int SlotKeyRemCheck(); }; class SlotsInfoCmd : public Cmd { -public: - SlotsInfoCmd() {} - virtual void Do(); -private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsInfoCmd() {} + virtual void Do(); + + private: + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsHashKeyCmd : public Cmd { -public: - SlotsHashKeyCmd() {} - virtual void Do(); -private: - std::vector keys_; - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsHashKeyCmd() {} + virtual void Do(); + + private: + std::vector keys_; + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsReloadCmd : public Cmd { -public: - SlotsReloadCmd() {} - virtual void Do(); -private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsReloadCmd() {} + virtual void Do(); + + private: + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsReloadOffCmd : public Cmd { -public: - SlotsReloadOffCmd() {} - virtual void Do(); -private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsReloadOffCmd() {} + virtual void Do(); + + private: + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsDelCmd : public Cmd { -public: - SlotsDelCmd() {} - virtual void Do(); -private: - std::vector slots_; - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsDelCmd() {} + virtual void Do(); + + private: + std::vector slots_; + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsScanCmd : public Cmd { -public: + public: SlotsScanCmd() : pattern_("*"), count_(10) {} virtual void Do(); -private: + + private: std::string key_, pattern_; int64_t cursor_, count_; - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); virtual void Clear() { pattern_ = "*"; count_ = 10; @@ -120,94 +128,102 @@ class SlotsScanCmd : public Cmd { }; class SlotsCleanupCmd : public Cmd { -public: - SlotsCleanupCmd() {} - virtual void Do(); - std::vector cleanup_slots_; -private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsCleanupCmd() {} + virtual void Do(); + std::vector cleanup_slots_; + + private: + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsCleanupOffCmd : public Cmd { -public: - SlotsCleanupOffCmd() {} - virtual void Do(); -private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsCleanupOffCmd() {} + virtual void Do(); + + private: + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsMgrtTagSlotAsyncCmd : public Cmd { -public: - SlotsMgrtTagSlotAsyncCmd() {} - virtual void Do(); -private: - std::string dest_ip_; - int64_t dest_port_; - int64_t timeout_ms_; - int64_t max_bulks_; - int64_t max_bytes_; - int64_t slot_num_; - int64_t keys_num_; - - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsMgrtTagSlotAsyncCmd() {} + virtual void Do(); + + private: + std::string dest_ip_; + int64_t dest_port_; + int64_t timeout_ms_; + int64_t max_bulks_; + int64_t max_bytes_; + int64_t slot_num_; + int64_t keys_num_; + + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsMgrtExecWrapperCmd : public Cmd { -public: - SlotsMgrtExecWrapperCmd() {} - virtual void Do(); -private: - std::string key_; - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsMgrtExecWrapperCmd() {} + virtual void Do(); + + private: + std::string key_; + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsMgrtAsyncStatusCmd : public Cmd { -public: - SlotsMgrtAsyncStatusCmd() {} - virtual void Do(); -private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsMgrtAsyncStatusCmd() {} + virtual void Do(); + + private: + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; class SlotsMgrtAsyncCancelCmd : public Cmd { -public: - SlotsMgrtAsyncCancelCmd() {} - virtual void Do(); -private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info); + public: + SlotsMgrtAsyncCancelCmd() {} + virtual void Do(); + + private: + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info); }; -class SlotsMgrtSenderThread: public net::Thread { -public: - SlotsMgrtSenderThread(); - virtual ~SlotsMgrtSenderThread(); - int SlotsMigrateOne(const std::string &key); - bool SlotsMigrateBatch(const std::string &ip, int64_t port, int64_t time_out, int64_t slot, int64_t keys_num); - bool GetSlotsMigrateResul(int64_t *moved, int64_t *remained); - void GetSlotsMgrtSenderStatus(std::string *ip, int64_t *port, int64_t *slot, bool *migrating, int64_t *moved, int64_t *remained); - bool SlotsMigrateAsyncCancel(); -private: - std::string dest_ip_; - int64_t dest_port_; - int64_t timeout_ms_; - int64_t slot_num_; - int64_t keys_num_; - int64_t moved_keys_num_; // during one batch moved - int64_t moved_keys_all_; // all keys moved in the slot - int64_t remained_keys_num_; - std::vector> migrating_batch_; - std::vector> migrating_ones_; - net::PinkCli *cli_; - pthread_rwlock_t rwlock_db_; - pthread_rwlock_t rwlock_batch_; - pthread_rwlock_t rwlock_ones_; - slash::CondVar slotsmgrt_cond_; - slash::Mutex slotsmgrt_cond_mutex_; - std::atomic is_migrating_; - std::atomic should_exit_; - - bool ElectMigrateKeys(); - virtual void* ThreadMain(); +class SlotsMgrtSenderThread : public net::Thread { + public: + SlotsMgrtSenderThread(); + virtual ~SlotsMgrtSenderThread(); + int SlotsMigrateOne(const std::string& key); + bool SlotsMigrateBatch(const std::string& ip, int64_t port, int64_t time_out, int64_t slot, int64_t keys_num); + bool GetSlotsMigrateResul(int64_t* moved, int64_t* remained); + void GetSlotsMgrtSenderStatus(std::string* ip, int64_t* port, int64_t* slot, bool* migrating, int64_t* moved, + int64_t* remained); + bool SlotsMigrateAsyncCancel(); + + private: + std::string dest_ip_; + int64_t dest_port_; + int64_t timeout_ms_; + int64_t slot_num_; + int64_t keys_num_; + int64_t moved_keys_num_; // during one batch moved + int64_t moved_keys_all_; // all keys moved in the slot + int64_t remained_keys_num_; + std::vector> migrating_batch_; + std::vector> migrating_ones_; + net::PinkCli* cli_; + pthread_rwlock_t rwlock_db_; + pthread_rwlock_t rwlock_batch_; + pthread_rwlock_t rwlock_ones_; + slash::CondVar slotsmgrt_cond_; + slash::Mutex slotsmgrt_cond_mutex_; + std::atomic is_migrating_; + std::atomic should_exit_; + + bool ElectMigrateKeys(); + virtual void* ThreadMain(); }; #endif diff --git a/pika-tools/pika-port/pika_port_2/pika_port.cc b/pika-tools/pika-port/pika_port_2/pika_port.cc index c8375128a0..5ca75e1495 100644 --- a/pika-tools/pika-port/pika_port_2/pika_port.cc +++ b/pika-tools/pika-port/pika_port_2/pika_port.cc @@ -5,55 +5,53 @@ #include -#include +#include #include -#include +#include #include -#include #include -#include +#include +#include -#include "slash/include/env.h" -#include "slash/include/slash_string.h" -#include "slash/include/rsync.h" -#include "pika_port.h" #include "binlog_const.h" +#include "pika_port.h" #include "port_conf.h" +#include "slash/include/env.h" +#include "slash/include/rsync.h" +#include "slash/include/slash_string.h" PikaPort::PikaPort(std::string& master_ip, int master_port, std::string& passwd) - : sid_(0), - ping_thread_(NULL), - master_ip_(master_ip), - master_port_(master_port), - master_connection_(0), - role_(PIKA_ROLE_PORT), - repl_state_(PIKA_REPL_NO_CONNECT), - requirepass_(passwd), - // cli_(NULL), - should_exit_(false) { - + : sid_(0), + ping_thread_(NULL), + master_ip_(master_ip), + master_port_(master_port), + master_connection_(0), + role_(PIKA_ROLE_PORT), + repl_state_(PIKA_REPL_NO_CONNECT), + requirepass_(passwd), + // cli_(NULL), + should_exit_(false) { pthread_rwlockattr_t attr; pthread_rwlockattr_init(&attr); pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); pthread_rwlock_init(&rwlock_, &attr); - - //Init ip host + + // Init ip host if (!Init()) { LOG(FATAL) << "Init iotcl error"; } - // Create redis sender + // Create redis sender size_t thread_num = g_port_conf.forward_thread_num; - for (size_t i = 0; i < thread_num; i++) { - senders_.emplace_back(new RedisSender(int(i), g_port_conf.forward_ip, - g_port_conf.forward_port, g_port_conf.forward_passwd)); + for (size_t i = 0; i < thread_num; i++) { + senders_.emplace_back( + new RedisSender(int(i), g_port_conf.forward_ip, g_port_conf.forward_port, g_port_conf.forward_passwd)); } // Create thread - binlog_receiver_thread_ = new BinlogReceiverThread(g_port_conf.local_ip, - g_port_conf.local_port + 1000, 1000); + binlog_receiver_thread_ = new BinlogReceiverThread(g_port_conf.local_ip, g_port_conf.local_port + 1000, 1000); trysync_thread_ = new TrysyncThread(); - + pthread_rwlock_init(&state_protector_, NULL); logger_ = new Binlog(g_port_conf.log_path, 104857600); } @@ -67,7 +65,6 @@ PikaPort::~PikaPort() { delete logger_; - pthread_rwlock_destroy(&state_protector_); pthread_rwlock_destroy(&rwlock_); @@ -81,16 +78,16 @@ bool PikaPort::Init() { void PikaPort::Cleanup() { // shutdown server -// if (g_port_conf->daemonize()) { -// unlink(g_port_conf->pidfile().c_str()); -// } + // if (g_port_conf->daemonize()) { + // unlink(g_port_conf->pidfile().c_str()); + // } // sender_->Stop(); // sender_->JoinThread(); // delete cli_; // delete sender_; size_t thread_num = g_port_conf.forward_thread_num; - for(size_t i = 0; i < thread_num; i++) { + for (size_t i = 0; i < thread_num; i++) { senders_[i]->Stop(); } for (size_t i = 0; i < thread_num; i++) { @@ -104,7 +101,7 @@ void PikaPort::Cleanup() { DLOG(INFO) << "=============== Syncing =====================" << std::endl; DLOG(INFO) << "Total replies : " << replies << " received from redis server"; - delete this; // PikaPort is a global object + delete this; // PikaPort is a global object ::google::ShutdownGoogleLogging(); } @@ -132,15 +129,13 @@ void PikaPort::Start() { Cleanup(); } -void PikaPort::Stop() { - mutex_.Unlock(); -} +void PikaPort::Stop() { mutex_.Unlock(); } -int PikaPort::SendRedisCommand(std::string &command, std::string &key) { +int PikaPort::SendRedisCommand(std::string& command, std::string& key) { // Send command size_t idx = std::hash()(key) % g_port_conf.forward_thread_num; senders_[idx]->SendRedisCommand(command); - + return 0; } @@ -178,8 +173,8 @@ void PikaPort::ConnectMasterDone() { bool PikaPort::ShouldStartPingMaster() { slash::RWLock l(&state_protector_, false); - DLOG(INFO) << "ShouldStartPingMaster: master_connection " << master_connection_ - << " repl_state " << PikaState(repl_state_); + DLOG(INFO) << "ShouldStartPingMaster: master_connection " << master_connection_ << " repl_state " + << PikaState(repl_state_); if (repl_state_ == PIKA_REPL_CONNECTING && master_connection_ < 2) { return true; } @@ -193,10 +188,10 @@ void PikaPort::MinusMasterConnection() { if ((--master_connection_) <= 0) { // two connection with master has been deleted if ((role_ & PIKA_ROLE_SLAVE) || (role_ & PIKA_ROLE_PORT)) { - // not change by slaveof no one, so set repl_state = PIKA_REPL_CONNECT, continue to connect master + // not change by slaveof no one, so set repl_state = PIKA_REPL_CONNECT, continue to connect master repl_state_ = PIKA_REPL_CONNECT; } else { - // change by slaveof no one, so set repl_state = PIKA_REPL_NO_CONNECT, reset to SINGLE state + // change by slaveof no one, so set repl_state = PIKA_REPL_NO_CONNECT, reset to SINGLE state repl_state_ = PIKA_REPL_NO_CONNECT; } master_connection_ = 0; @@ -218,8 +213,8 @@ void PikaPort::PlusMasterConnection() { bool PikaPort::ShouldAccessConnAsMaster(const std::string& ip) { slash::RWLock l(&state_protector_, false); - DLOG(INFO) << "ShouldAccessConnAsMaster, repl_state_: " << PikaState(repl_state_) - << " ip: " << ip << " master_ip: " << master_ip_; + DLOG(INFO) << "ShouldAccessConnAsMaster, repl_state_: " << PikaState(repl_state_) << " ip: " << ip + << " master_ip: " << master_ip_; if (repl_state_ != PIKA_REPL_NO_CONNECT && ip == master_ip_) { return true; } @@ -266,4 +261,3 @@ void PikaPort::WaitDBSyncFinish() { repl_state_ = PIKA_REPL_CONNECT; } } - diff --git a/pika-tools/pika-port/pika_port_2/pika_port.h b/pika-tools/pika-port/pika_port_2/pika_port.h index bdd388a4f3..3494394133 100644 --- a/pika-tools/pika-port/pika_port_2/pika_port.h +++ b/pika-tools/pika-port/pika_port_2/pika_port.h @@ -6,43 +6,34 @@ #ifndef BINLOG_SYNC_H_ #define BINLOG_SYNC_H_ -#include "slash/include/slash_status.h" -#include "slash/include/slash_mutex.h" +#include "binlog_receiver_thread.h" #include "include/pika_binlog.h" #include "include/pika_define.h" -#include "binlog_receiver_thread.h" +#include "redis_sender.h" +#include "slash/include/slash_mutex.h" +#include "slash/include/slash_status.h" #include "slaveping_thread.h" #include "trysync_thread.h" -#include "redis_sender.h" #include -using slash::Status; using slash::Slice; +using slash::Status; -class PikaPort -{ -public: +class PikaPort { + public: PikaPort(std::string& master_ip, int master_port, std::string& passwd); ~PikaPort(); /* - * Get & Set + * Get & Set */ - std::string& master_ip() { - return master_ip_; - } - int master_port() { - return master_port_; - } + std::string& master_ip() { return master_ip_; } + int master_port() { return master_port_; } - int64_t sid() { - return sid_; - } + int64_t sid() { return sid_; } - void SetSid(int64_t sid) { - sid_ = sid; - } + void SetSid(int64_t sid) { sid_ = sid; } int role() { slash::RWLock(&state_protector_, false); @@ -52,23 +43,13 @@ class PikaPort slash::RWLock(&state_protector_, false); return repl_state_; } - std::string requirepass() { - return requirepass_; - } - pthread_rwlock_t* rwlock() { - return &rwlock_; - } - BinlogReceiverThread* binlog_receiver_thread() { - return binlog_receiver_thread_; - } - TrysyncThread* trysync_thread() { - return trysync_thread_; - } - Binlog* logger() { - return logger_; - } + std::string requirepass() { return requirepass_; } + pthread_rwlock_t* rwlock() { return &rwlock_; } + BinlogReceiverThread* binlog_receiver_thread() { return binlog_receiver_thread_; } + TrysyncThread* trysync_thread() { return trysync_thread_; } + Binlog* logger() { return logger_; } - int SendRedisCommand(std::string &command, std::string &key); + int SendRedisCommand(std::string& command, std::string& key); bool SetMaster(std::string& master_ip, int master_port); bool ShouldConnectMaster(); @@ -89,7 +70,7 @@ class PikaPort bool Init(); SlavepingThread* ping_thread_; -private: + private: std::string master_ip_; int master_port_; int master_connection_; @@ -100,7 +81,7 @@ class PikaPort std::string dump_path_; pthread_rwlock_t rwlock_; - slash::Mutex mutex_; // double lock to block main thread + slash::Mutex mutex_; // double lock to block main thread // redis client // net::PinkCli *cli_; @@ -115,12 +96,12 @@ class PikaPort BinlogReceiverThread* binlog_receiver_thread_; TrysyncThread* trysync_thread_; - Binlog *logger_; + Binlog* logger_; - pthread_rwlock_t state_protector_; //protect below, use for master-slave mode + pthread_rwlock_t state_protector_; // protect below, use for master-slave mode - PikaPort(PikaPort &bs); - void operator =(const PikaPort &bs); + PikaPort(PikaPort& bs); + void operator=(const PikaPort& bs); void ConnectRedis(); }; diff --git a/pika-tools/pika-port/pika_port_2/pika_sender.cc b/pika-tools/pika-port/pika_port_2/pika_sender.cc index 97c53e50f6..2031985e6b 100644 --- a/pika-tools/pika-port/pika_port_2/pika_sender.cc +++ b/pika-tools/pika-port/pika_port_2/pika_sender.cc @@ -2,21 +2,18 @@ #include "include/pika_slot.h" -PikaSender::PikaSender(nemo::Nemo *db, std::string ip, int64_t port, std::string password): - cli_(NULL), - rsignal_(&keys_mutex_), - wsignal_(&keys_mutex_), - db_(db), - ip_(ip), - port_(port), - password_(password), - should_exit_(false), - elements_(0) - { - } - -PikaSender::~PikaSender() { -} +PikaSender::PikaSender(nemo::Nemo* db, std::string ip, int64_t port, std::string password) + : cli_(NULL), + rsignal_(&keys_mutex_), + wsignal_(&keys_mutex_), + db_(db), + ip_(ip), + port_(port), + password_(password), + should_exit_(false), + elements_(0) {} + +PikaSender::~PikaSender() {} void PikaSender::ConnectRedis() { while (cli_ == NULL) { @@ -90,7 +87,7 @@ void PikaSender::ConnectRedis() { } } -void PikaSender::LoadKey(const std::string &key) { +void PikaSender::LoadKey(const std::string& key) { keys_mutex_.Lock(); if (keys_queue_.size() < 100000) { keys_queue_.push(key); @@ -106,7 +103,7 @@ void PikaSender::LoadKey(const std::string &key) { } } -void PikaSender::SendCommand(std::string &command, const std::string &key) { +void PikaSender::SendCommand(std::string& command, const std::string& key) { // Send command slash::Status s = cli_->Send(&command); if (!s.ok()) { @@ -119,7 +116,7 @@ void PikaSender::SendCommand(std::string &command, const std::string &key) { } } -void *PikaSender::ThreadMain() { +void* PikaSender::ThreadMain() { log_info("Start sender thread..."); expire_command_.clear(); int cnt = 0; @@ -171,9 +168,9 @@ void *PikaSender::ThreadMain() { keys_mutex_.Unlock(); char type = key[0]; - if (type == nemo::DataType::kHSize) { // Hash + if (type == nemo::DataType::kHSize) { // Hash std::string h_key = key.substr(1); - nemo::HIterator *iter = db_->HScan(h_key, "", "", -1, false); + nemo::HIterator* iter = db_->HScan(h_key, "", "", -1, false); for (; iter->Valid(); iter->Next()) { net::RedisCmdArgsType argv; @@ -193,7 +190,7 @@ void *PikaSender::ThreadMain() { continue; } - nemo::SIterator *iter = db_->SScan(s_key, -1, false); + nemo::SIterator* iter = db_->SScan(s_key, -1, false); for (; iter->Valid(); iter->Next()) { net::RedisCmdArgsType argv; @@ -213,7 +210,7 @@ void *PikaSender::ThreadMain() { int64_t pos = 0; int64_t len = 512; - db_->LRange(l_key, pos, pos+len-1, ivs); + db_->LRange(l_key, pos, pos + len - 1, ivs); while (!ivs.empty()) { net::RedisCmdArgsType argv; @@ -231,12 +228,11 @@ void *PikaSender::ThreadMain() { pos += len; ivs.clear(); - db_->LRange(l_key, pos, pos+len-1, ivs); + db_->LRange(l_key, pos, pos + len - 1, ivs); } } else if (type == nemo::DataType::kZSize) { // Zset std::string z_key = key.substr(1); - nemo::ZIterator *iter = db_->ZScan(z_key, nemo::ZSET_SCORE_MIN, - nemo::ZSET_SCORE_MAX, -1, false); + nemo::ZIterator* iter = db_->ZScan(z_key, nemo::ZSET_SCORE_MIN, nemo::ZSET_SCORE_MAX, -1, false); for (; iter->Valid(); iter->Next()) { net::RedisCmdArgsType argv; @@ -252,7 +248,7 @@ void *PikaSender::ThreadMain() { cnt++; } delete iter; - } else if (type == nemo::DataType::kKv) { // Kv + } else if (type == nemo::DataType::kKv) { // Kv std::string k_key = key.substr(1); command = k_key; SendCommand(command, key); @@ -260,7 +256,7 @@ void *PikaSender::ThreadMain() { } if (cnt >= 200) { - for(; cnt > 0; cnt--) { + for (; cnt > 0; cnt--) { cli_->Recv(NULL); } } @@ -294,7 +290,7 @@ void *PikaSender::ThreadMain() { } } } - for(; cnt > 0; cnt--) { + for (; cnt > 0; cnt--) { cli_->Recv(NULL); } @@ -303,4 +299,3 @@ void *PikaSender::ThreadMain() { log_info("PikaSender thread complete"); return NULL; } - diff --git a/pika-tools/pika-port/pika_port_2/pika_sender.h b/pika-tools/pika-port/pika_port_2/pika_sender.h index d5f1d0108d..cd8daef64c 100644 --- a/pika-tools/pika-port/pika_port_2/pika_sender.h +++ b/pika-tools/pika-port/pika_port_2/pika_sender.h @@ -1,52 +1,51 @@ #ifndef PIKA_SENDER_H_ #define PIKA_SENDER_H_ -#include #include #include #include +#include +#include "nemo.h" #include "net/include/bg_thread.h" #include "net/include/net_cli.h" #include "net/include/redis_cli.h" -#include "nemo.h" class PikaSender : public net::Thread { -public: - PikaSender(nemo::Nemo *db, std::string ip, int64_t port, std::string password); - virtual ~PikaSender(); - void LoadKey(const std::string &cmd); - void Stop() { - should_exit_ = true; - keys_mutex_.Lock(); - rsignal_.Signal(); - keys_mutex_.Unlock(); - } - int64_t elements() { - return elements_; - } + public: + PikaSender(nemo::Nemo* db, std::string ip, int64_t port, std::string password); + virtual ~PikaSender(); + void LoadKey(const std::string& cmd); + void Stop() { + should_exit_ = true; + keys_mutex_.Lock(); + rsignal_.Signal(); + keys_mutex_.Unlock(); + } + int64_t elements() { return elements_; } + + void SendCommand(std::string& command, const std::string& key); + int QueueSize() { + slash::MutexLock l(&keys_mutex_); + int len = keys_queue_.size(); + return len; + } + void ConnectRedis(); - void SendCommand(std::string &command, const std::string &key); - int QueueSize() { - slash::MutexLock l(&keys_mutex_); - int len = keys_queue_.size(); - return len; - } - void ConnectRedis(); -private: - net::PinkCli *cli_; - slash::CondVar rsignal_; - slash::CondVar wsignal_; - nemo::Nemo *db_; - slash::Mutex keys_mutex_; - std::queue keys_queue_; - std::string expire_command_; - std::string ip_; - int port_; - std::string password_; - bool should_exit_; - int64_t elements_; + private: + net::PinkCli* cli_; + slash::CondVar rsignal_; + slash::CondVar wsignal_; + nemo::Nemo* db_; + slash::Mutex keys_mutex_; + std::queue keys_queue_; + std::string expire_command_; + std::string ip_; + int port_; + std::string password_; + bool should_exit_; + int64_t elements_; - virtual void *ThreadMain(); + virtual void* ThreadMain(); }; #endif diff --git a/pika-tools/pika-port/pika_port_2/port_conf.h b/pika-tools/pika-port/pika_port_2/port_conf.h index 71be539293..ec2e2c1271 100644 --- a/pika-tools/pika-port/pika_port_2/port_conf.h +++ b/pika-tools/pika-port/pika_port_2/port_conf.h @@ -4,7 +4,7 @@ #include class PortConf { -public: + public: PortConf() { local_ip = "127.0.0.1"; local_port = 0; @@ -12,27 +12,27 @@ class PortConf { master_port = 0; forward_ip = "127.0.0.1"; forward_port = 0; - forward_thread_num = 1; - filenum = size_t(UINT32_MAX); // src/pika_trysync_thread.cc:48 + forward_thread_num = 1; + filenum = size_t(UINT32_MAX); // src/pika_trysync_thread.cc:48 offset = 0; log_path = "./log/"; dump_path = "./rsync_dump/"; } -public: - size_t filenum; - size_t offset; - std::string local_ip; - int local_port; - std::string master_ip; - int master_port; - std::string forward_ip; - int forward_port; - std::string forward_passwd; - int forward_thread_num; - std::string passwd; - std::string log_path; - std::string dump_path; + public: + size_t filenum; + size_t offset; + std::string local_ip; + int local_port; + std::string master_ip; + int master_port; + std::string forward_ip; + int forward_port; + std::string forward_passwd; + int forward_thread_num; + std::string passwd; + std::string log_path; + std::string dump_path; }; extern PortConf g_port_conf; diff --git a/pika-tools/pika-port/pika_port_2/redis_sender.cc b/pika-tools/pika-port/pika_port_2/redis_sender.cc index 8e2e1bc8fe..f88a4bc2c3 100644 --- a/pika-tools/pika-port/pika_port_2/redis_sender.cc +++ b/pika-tools/pika-port/pika_port_2/redis_sender.cc @@ -1,28 +1,25 @@ +#include "redis_sender.h" +#include #include #include -#include -#include "redis_sender.h" // #include "binlog_log.h" static time_t kCheckDiff = 1; -RedisSender::RedisSender(int id, std::string ip, int64_t port, std::string password): - id_(id), - cli_(NULL), - rsignal_(&commands_mutex_), - wsignal_(&commands_mutex_), - ip_(ip), - port_(port), - password_(password), - should_exit_(false), - elements_(0) { - +RedisSender::RedisSender(int id, std::string ip, int64_t port, std::string password) + : id_(id), + cli_(NULL), + rsignal_(&commands_mutex_), + wsignal_(&commands_mutex_), + ip_(ip), + port_(port), + password_(password), + should_exit_(false), + elements_(0) { last_write_time_ = ::time(NULL); } -RedisSender::~RedisSender() { - DLOG(INFO) << "RedisSender thread " << id_ << " exit!!!"; -} +RedisSender::~RedisSender() { DLOG(INFO) << "RedisSender thread " << id_ << " exit!!!"; } void RedisSender::ConnectRedis() { while (cli_ == NULL) { @@ -103,7 +100,7 @@ void RedisSender::Stop() { commands_mutex_.Unlock(); } -void RedisSender::SendRedisCommand(const std::string &command) { +void RedisSender::SendRedisCommand(const std::string& command) { commands_mutex_.Lock(); if (commands_queue_.size() < 100000) { commands_queue_.push(command); @@ -121,7 +118,7 @@ void RedisSender::SendRedisCommand(const std::string &command) { commands_mutex_.Unlock(); } -int RedisSender::SendCommand(std::string &command) { +int RedisSender::SendCommand(std::string& command) { time_t now = ::time(NULL); if (kCheckDiff < now - last_write_time_) { int ret = cli_->CheckAliveness(); @@ -139,17 +136,17 @@ int RedisSender::SendCommand(std::string &command) { return 0; } - DLOG(WARNING) << "RedisSender " << id_ << " fails to send redis command " << command << ", times:" << (idx+1); + DLOG(WARNING) << "RedisSender " << id_ << " fails to send redis command " << command << ", times:" << (idx + 1); cli_->Close(); log_info("%s", s.ToString().data()); cli_ = NULL; ConnectRedis(); - } while(++idx < 3); + } while (++idx < 3); return -1; } -void *RedisSender::ThreadMain() { +void* RedisSender::ThreadMain() { DLOG(INFO) << "Start sender " << id_ << " thread..."; // sleep(15); int cnt = 0; @@ -189,12 +186,12 @@ void *RedisSender::ThreadMain() { } if (cnt >= 200) { - for(; cnt > 0; cnt--) { + for (; cnt > 0; cnt--) { cli_->Recv(NULL); } } } - for(; cnt > 0; cnt--) { + for (; cnt > 0; cnt--) { cli_->Recv(NULL); } @@ -203,4 +200,3 @@ void *RedisSender::ThreadMain() { DLOG(INFO) << "RedisSender thread " << id_ << " complete"; return NULL; } - diff --git a/pika-tools/pika-port/pika_port_2/redis_sender.h b/pika-tools/pika-port/pika_port_2/redis_sender.h index efbf77df33..410391e80c 100644 --- a/pika-tools/pika-port/pika_port_2/redis_sender.h +++ b/pika-tools/pika-port/pika_port_2/redis_sender.h @@ -2,46 +2,44 @@ #define REDIS_SENDER_H_ #include -#include #include #include #include +#include +#include "nemo.h" #include "net/include/bg_thread.h" #include "net/include/net_cli.h" #include "net/include/redis_cli.h" -#include "nemo.h" class RedisSender : public net::Thread { -public: - RedisSender(int id, std::string ip, int64_t port, std::string password); - virtual ~RedisSender(); - void Stop(void); - int64_t elements() { - return elements_; - } - - void SendRedisCommand(const std::string &command); - -private: - int SendCommand(std::string &command); - void ConnectRedis(); - -private: - int id_; - net::PinkCli *cli_; - slash::CondVar rsignal_; - slash::CondVar wsignal_; - slash::Mutex commands_mutex_; - std::queue commands_queue_; - std::string ip_; - int port_; - std::string password_; - bool should_exit_; - int64_t elements_; - std::atomic last_write_time_; - - virtual void *ThreadMain(); + public: + RedisSender(int id, std::string ip, int64_t port, std::string password); + virtual ~RedisSender(); + void Stop(void); + int64_t elements() { return elements_; } + + void SendRedisCommand(const std::string& command); + + private: + int SendCommand(std::string& command); + void ConnectRedis(); + + private: + int id_; + net::PinkCli* cli_; + slash::CondVar rsignal_; + slash::CondVar wsignal_; + slash::Mutex commands_mutex_; + std::queue commands_queue_; + std::string ip_; + int port_; + std::string password_; + bool should_exit_; + int64_t elements_; + std::atomic last_write_time_; + + virtual void* ThreadMain(); }; #endif diff --git a/pika-tools/pika-port/pika_port_2/slaveping_thread.cc b/pika-tools/pika-port/pika_port_2/slaveping_thread.cc index a557fe18f1..e95f24d246 100644 --- a/pika-tools/pika-port/pika_port_2/slaveping_thread.cc +++ b/pika-tools/pika-port/pika_port_2/slaveping_thread.cc @@ -3,9 +3,9 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. +#include "slaveping_thread.h" #include #include -#include "slaveping_thread.h" #include "pika_port.h" extern PikaPort* g_pika_port; @@ -13,10 +13,10 @@ extern PikaPort* g_pika_port; Status SlavepingThread::Send() { std::string wbuf_str; if (!is_first_send_) { - net::SerializeRedisCommand(&wbuf_str, "ping"); // reply == pong + net::SerializeRedisCommand(&wbuf_str, "ping"); // reply == pong } else { net::RedisCmdArgsType argv; - argv.push_back("spci"); // reply == pong + argv.push_back("spci"); // reply == pong argv.push_back(std::to_string(sid_)); net::SerializeRedisCommand(argv, &wbuf_str); is_first_send_ = false; @@ -74,7 +74,7 @@ void* SlavepingThread::ThreadMain() { DLOG(INFO) << "Slaveping timeout once"; gettimeofday(&now, NULL); if (now.tv_sec - last_interaction.tv_sec > 30) { - //timeout; + // timeout; DLOG(INFO) << "Ping master timeout"; close(cli_->fd()); g_pika_port->binlog_receiver_thread()->KillBinlogSender(); diff --git a/pika-tools/pika-port/pika_port_2/slaveping_thread.h b/pika-tools/pika-port/pika_port_2/slaveping_thread.h index d7d16aa40b..07afb5ee0d 100644 --- a/pika-tools/pika-port/pika_port_2/slaveping_thread.h +++ b/pika-tools/pika-port/pika_port_2/slaveping_thread.h @@ -6,8 +6,8 @@ #ifndef SLAVEPING_THREAD_H_ #define SLAVEPING_THREAD_H_ -#include "net/include/net_thread.h" #include "net/include/net_cli.h" +#include "net/include/net_thread.h" #include "net/include/redis_cli.h" #include "slash/include/slash_mutex.h" #include "slash/include/slash_status.h" @@ -15,30 +15,28 @@ using slash::Status; class SlavepingThread : public net::Thread { -public: - SlavepingThread(int64_t sid) : sid_(sid), - is_first_send_(true) { + public: + SlavepingThread(int64_t sid) : sid_(sid), is_first_send_(true) { cli_ = net::NewRedisCli(); cli_->set_connect_timeout(1500); - }; + }; virtual ~SlavepingThread() { StopThread(); delete cli_; DLOG(INFO) << " Slaveping thread " << pthread_self() << " exit!!!"; - }; + }; Status Send(); Status RecvProc(); -private: + private: int64_t sid_; bool is_first_send_; int sockfd_; - net::PinkCli *cli_; + net::PinkCli* cli_; virtual void* ThreadMain(); - }; #endif diff --git a/pika-tools/pika-port/pika_port_2/trysync_thread.cc b/pika-tools/pika-port/pika_port_2/trysync_thread.cc index 4ac577183d..eeda17e759 100644 --- a/pika-tools/pika-port/pika_port_2/trysync_thread.cc +++ b/pika-tools/pika-port/pika_port_2/trysync_thread.cc @@ -3,23 +3,23 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include #include #include +#include #include #include -#include +#include -#include "slash/include/slash_status.h" #include "slash/include/rsync.h" +#include "slash/include/slash_status.h" #include "slaveping_thread.h" #include "include/pika_define.h" -#include "trysync_thread.h" +#include "binlog_const.h" #include "pika_port.h" #include "port_conf.h" -#include "binlog_const.h" +#include "trysync_thread.h" extern PikaPort* g_pika_port; @@ -68,13 +68,13 @@ bool TrysyncThread::Send() { net::SerializeRedisCommand(argv, &tbuf_str); wbuf_str.append(tbuf_str); - DLOG(INFO) << "redis command: trysync " << g_port_conf.local_ip << " " - << g_port_conf.local_port << " " << filenum << " " << pro_offset; + DLOG(INFO) << "redis command: trysync " << g_port_conf.local_ip << " " << g_port_conf.local_port << " " << filenum + << " " << pro_offset; slash::Status s; s = cli_->Send(&wbuf_str); if (!s.ok()) { - LOG(WARNING) << "Connect master, Send, error: " <Recv(&argv); if (!s.ok()) { - LOG(WARNING) << "Connect master, Recv, error: " <SetSid(sid_); @@ -170,24 +169,25 @@ bool TrysyncThread::TryUpdateMasterOffset() { is.close(); return false; } - if (lineno == 3) { master_port = tmp; } - else if (lineno == 4) { filenum = tmp; } - else { offset = tmp; } - } else if (lineno > 5) { + if (lineno == 3) { + master_port = tmp; + } else if (lineno == 4) { + filenum = tmp; + } else { + offset = tmp; + } + } else if (lineno > 5) { LOG(WARNING) << "Format of info file after db sync error, line : " << line; is.close(); return false; } } is.close(); - LOG(INFO) << "Information from dbsync info. master_ip: " << master_ip - << ", master_port: " << master_port - << ", filenum: " << filenum - << ", offset: " << offset; + LOG(INFO) << "Information from dbsync info. master_ip: " << master_ip << ", master_port: " << master_port + << ", filenum: " << filenum << ", offset: " << offset; // Sanity check - if (master_ip != g_port_conf.master_ip || - master_port != g_port_conf.master_port) { + if (master_ip != g_port_conf.master_ip || master_port != g_port_conf.master_port) { LOG(WARNING) << "Error master ip port: " << master_ip << ":" << master_port; return false; } @@ -206,13 +206,13 @@ bool TrysyncThread::TryUpdateMasterOffset() { } #include +#include #include #include -#include +#include "migrator_thread.h" #include "nemo.h" #include "pika_sender.h" -#include "migrator_thread.h" using std::chrono::high_resolution_clock; using std::chrono::milliseconds; @@ -235,8 +235,8 @@ int TrysyncThread::Retransmit() { // Init db nemo::Options option; - option.write_buffer_size = 512 * 1024 * 1024; // 512M - option.target_file_size_base = 40 * 1024 * 1024; // 40M + option.write_buffer_size = 512 * 1024 * 1024; // 512M + option.target_file_size_base = 40 * 1024 * 1024; // 40M db = std::unique_ptr(new nemo::Nemo(db_path, option)); // Init SenderThread @@ -258,10 +258,10 @@ int TrysyncThread::Retransmit() { senders[i]->StartThread(); } - for(size_t i = 0; i < kDataSetNum; i++) { + for (size_t i = 0; i < kDataSetNum; i++) { migrators[i]->JoinThread(); } - for(size_t i = 0; i < thread_num; i++) { + for (size_t i = 0; i < thread_num; i++) { senders[i]->Stop(); } for (size_t i = 0; i < thread_num; i++) { @@ -279,13 +279,14 @@ int TrysyncThread::Retransmit() { } high_resolution_clock::time_point end = high_resolution_clock::now(); - std::chrono::hours h = std::chrono::duration_cast(end - start); - std::chrono::minutes m = std::chrono::duration_cast(end - start); - std::chrono::seconds s = std::chrono::duration_cast(end - start); + std::chrono::hours h = std::chrono::duration_cast(end - start); + std::chrono::minutes m = std::chrono::duration_cast(end - start); + std::chrono::seconds s = std::chrono::duration_cast(end - start); DLOG(INFO) << "=============== Retransmitting =====================" << std::endl; DLOG(INFO) << "Running time :"; - DLOG(INFO) << h.count() << " hour " << m.count() - h.count() * 60 << " min " << s.count() - h.count() * 60 * 60 << " s"; + DLOG(INFO) << h.count() << " hour " << m.count() - h.count() * 60 << " min " << s.count() - h.count() * 60 * 60 + << " s"; DLOG(INFO) << "Total records : " << records << " have been Scaned"; DLOG(INFO) << "Total replies : " << replies << " received from redis server"; // delete db @@ -299,7 +300,7 @@ void* TrysyncThread::ThreadMain() { if (g_pika_port->IsWaitingDBSync()) { LOG(INFO) << "Waiting db sync"; - //Try to update offset by db sync + // Try to update offset by db sync if (TryUpdateMasterOffset()) { LOG(INFO) << "Success Update Master Offset"; } @@ -318,8 +319,8 @@ void* TrysyncThread::ThreadMain() { // Start rsync service PrepareRsync(); std::string ip_port = slash::IpPortString(g_port_conf.master_ip, g_port_conf.master_port); - int ret = slash::StartRsync(dbsync_path, kDBSyncModule + "_" + ip_port, - g_port_conf.local_ip, g_port_conf.local_port + 3000); + int ret = slash::StartRsync(dbsync_path, kDBSyncModule + "_" + ip_port, g_port_conf.local_ip, + g_port_conf.local_port + 3000); if (0 != ret) { LOG(WARNING) << "Failed to start rsync, path:" << dbsync_path << " error : " << ret; return false; diff --git a/pika-tools/pika-port/pika_port_2/trysync_thread.h b/pika-tools/pika-port/pika_port_2/trysync_thread.h index bbf4bdaae7..4492bec870 100644 --- a/pika-tools/pika-port/pika_port_2/trysync_thread.h +++ b/pika-tools/pika-port/pika_port_2/trysync_thread.h @@ -9,25 +9,24 @@ #include "net/include/net_thread.h" #include "net/include/redis_cli.h" - class TrysyncThread : public net::Thread { -public: + public: TrysyncThread() { cli_ = net::NewRedisCli(); cli_->set_connect_timeout(1500); }; virtual ~TrysyncThread(); -private: + private: int sockfd_; int64_t sid_; - net::PinkCli *cli_; + net::PinkCli* cli_; bool Send(); bool RecvProc(); void PrepareRsync(); bool TryUpdateMasterOffset(); - int Retransmit(); + int Retransmit(); virtual void* ThreadMain(); }; diff --git a/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.cc b/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.cc index 1e174f417e..5405a67f0f 100644 --- a/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.cc +++ b/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.cc @@ -5,9 +5,9 @@ #include -#include "net/include/net_conn.h" #include "binlog_receiver_thread.h" #include "master_conn.h" +#include "net/include/net_conn.h" #include "pika_port.h" #include "conf.h" @@ -15,11 +15,10 @@ extern PikaPort* g_pika_port; BinlogReceiverThread::BinlogReceiverThread(std::string host, int port, int cron_interval) - : conn_factory_(this), handles_(this) { + : conn_factory_(this), handles_(this) { // thread_rep_ = net::NewHolyThread(port, &conn_factory_, // cron_interval, &handles_); - thread_rep_ = net::NewHolyThread(host, port, &conn_factory_, - cron_interval, &handles_); + thread_rep_ = net::NewHolyThread(host, port, &conn_factory_, cron_interval, &handles_); // to prevent HolyThread::DoCronTask close the pika sender connection thread_rep_->set_keepalive_timeout(0); } @@ -30,9 +29,7 @@ BinlogReceiverThread::~BinlogReceiverThread() { delete thread_rep_; } -int BinlogReceiverThread::StartThread() { - return thread_rep_->StartThread(); -} +int BinlogReceiverThread::StartThread() { return thread_rep_->StartThread(); } bool BinlogReceiverThread::Handles::AccessHandle(std::string& ip) const { if (ip == "127.0.0.1") { @@ -48,6 +45,4 @@ bool BinlogReceiverThread::Handles::AccessHandle(std::string& ip) const { return true; } -void BinlogReceiverThread::KillBinlogSender() { - thread_rep_->KillAllConns(); -} +void BinlogReceiverThread::KillBinlogSender() { thread_rep_->KillAllConns(); } diff --git a/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.h b/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.h index e8a9be29f1..a05c48fefb 100644 --- a/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.h +++ b/pika-tools/pika-port/pika_port_3/binlog_receiver_thread.h @@ -6,16 +6,16 @@ #ifndef BINLOG_RECEIVER_THREAD_H_ #define BINLOG_RECEIVER_THREAD_H_ -#include #include +#include +#include "master_conn.h" #include "net/include/server_thread.h" -#include "slash/include/slash_mutex.h" #include "pika_define.h" -#include "master_conn.h" +#include "slash/include/slash_mutex.h" class BinlogReceiverThread { -public: + public: BinlogReceiverThread(std::string host, int port, int cron_interval = 0); virtual ~BinlogReceiverThread(); int StartThread(); @@ -30,19 +30,13 @@ class BinlogReceiverThread { // return GetCmdFromTable(opt, cmds_); // } - private: class MasterConnFactory : public net::ConnFactory { public: - explicit MasterConnFactory(BinlogReceiverThread* binlog_receiver) - : binlog_receiver_(binlog_receiver) { - } + explicit MasterConnFactory(BinlogReceiverThread* binlog_receiver) : binlog_receiver_(binlog_receiver) {} - virtual net::PinkConn *NewPinkConn( - int connfd, - const std::string &ip_port, - net::ServerThread *thread, - void* worker_specific_data) const override { + virtual net::PinkConn* NewPinkConn(int connfd, const std::string& ip_port, net::ServerThread* thread, + void* worker_specific_data) const override { return new MasterConn(connfd, ip_port, binlog_receiver_); } @@ -51,14 +45,12 @@ class BinlogReceiverThread { }; class Handles : public net::ServerHandle { - public: - explicit Handles(BinlogReceiverThread* binlog_receiver) - : binlog_receiver_(binlog_receiver) { - } + public: + explicit Handles(BinlogReceiverThread* binlog_receiver) : binlog_receiver_(binlog_receiver) {} bool AccessHandle(std::string& ip) const override; - private: + private: BinlogReceiverThread* binlog_receiver_; }; diff --git a/pika-tools/pika-port/pika_port_3/binlog_transverter.cc b/pika-tools/pika-port/pika_port_3/binlog_transverter.cc index 6cd6c3ab89..8c6a4d86ae 100644 --- a/pika-tools/pika-port/pika_port_3/binlog_transverter.cc +++ b/pika-tools/pika-port/pika_port_3/binlog_transverter.cc @@ -6,57 +6,35 @@ #include "binlog_transverter.h" #include -uint32_t PortBinlogItem::exec_time() const { - return exec_time_; -} +uint32_t PortBinlogItem::exec_time() const { return exec_time_; } -uint32_t PortBinlogItem::server_id() const { - return server_id_; -} +uint32_t PortBinlogItem::server_id() const { return server_id_; } -uint64_t PortBinlogItem::logic_id() const { - return logic_id_; -} +uint64_t PortBinlogItem::logic_id() const { return logic_id_; } -uint32_t PortBinlogItem::filenum() const { - return filenum_; -} +uint32_t PortBinlogItem::filenum() const { return filenum_; } -uint64_t PortBinlogItem::offset() const { - return offset_; -} +uint64_t PortBinlogItem::offset() const { return offset_; } -const std::string& PortBinlogItem::content() const { - return content_; -} +const std::string& PortBinlogItem::content() const { return content_; } -void PortBinlogItem::set_exec_time(uint32_t exec_time) { - exec_time_ = exec_time; -} +void PortBinlogItem::set_exec_time(uint32_t exec_time) { exec_time_ = exec_time; } -void PortBinlogItem::set_server_id(uint32_t server_id) { - server_id_ = server_id; -} +void PortBinlogItem::set_server_id(uint32_t server_id) { server_id_ = server_id; } -void PortBinlogItem::set_logic_id(uint64_t logic_id) { - logic_id_ = logic_id; -} +void PortBinlogItem::set_logic_id(uint64_t logic_id) { logic_id_ = logic_id; } -void PortBinlogItem::set_filenum(uint32_t filenum) { - filenum_ = filenum; -} +void PortBinlogItem::set_filenum(uint32_t filenum) { filenum_ = filenum; } -void PortBinlogItem::set_offset(uint64_t offset) { - offset_ = offset; -} +void PortBinlogItem::set_offset(uint64_t offset) { offset_ = offset; } std::string PortBinlogItem::ToString() const { std::string str; - str.append("exec_time: " + std::to_string(exec_time_)); + str.append("exec_time: " + std::to_string(exec_time_)); str.append(",server_id: " + std::to_string(server_id_)); - str.append(",logic_id: " + std::to_string(logic_id_)); - str.append(",filenum: " + std::to_string(filenum_)); - str.append(",offset: " + std::to_string(offset_)); + str.append(",logic_id: " + std::to_string(logic_id_)); + str.append(",filenum: " + std::to_string(filenum_)); + str.append(",offset: " + std::to_string(offset_)); str.append("\ncontent: "); for (size_t idx = 0; idx < content_.size(); ++idx) { if (content_[idx] == '\n') { @@ -71,14 +49,10 @@ std::string PortBinlogItem::ToString() const { return str; } -std::string PortBinlogTransverter::PortBinlogEncode(PortBinlogType type, - uint32_t exec_time, - uint32_t server_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset, - const std::string& content, - const std::vector& extends) { +std::string PortBinlogTransverter::PortBinlogEncode(PortBinlogType type, uint32_t exec_time, uint32_t server_id, + uint64_t logic_id, uint32_t filenum, uint64_t offset, + const std::string& content, + const std::vector& extends) { std::string binlog; slash::PutFixed16(&binlog, type); slash::PutFixed32(&binlog, exec_time); @@ -92,14 +66,15 @@ std::string PortBinlogTransverter::PortBinlogEncode(PortBinlogType type, return binlog; } -bool PortBinlogTransverter::PortBinlogDecode(PortBinlogType type, const std::string& binlog, PortBinlogItem* binlog_item) { +bool PortBinlogTransverter::PortBinlogDecode(PortBinlogType type, const std::string& binlog, + PortBinlogItem* binlog_item) { uint16_t binlog_type = 0; uint32_t content_length = 0; std::string binlog_str = binlog; slash::GetFixed16(&binlog_str, &binlog_type); if (binlog_type != type) { - LOG(WARNING) << "PortBinlog Item type error, expect type: " - << static_cast(type) << " actualy type: " << binlog_type; + LOG(WARNING) << "PortBinlog Item type error, expect type: " << static_cast(type) + << " actualy type: " << binlog_type; return false; } slash::GetFixed32(&binlog_str, &binlog_item->exec_time_); @@ -111,8 +86,8 @@ bool PortBinlogTransverter::PortBinlogDecode(PortBinlogType type, const std::str if (binlog_str.size() >= content_length) { binlog_item->content_.assign(binlog_str.data(), content_length); } else { - LOG(WARNING) << "PortBinlog Item get content error, expect length: " - << content_length << ", left length: " << binlog_str.size(); + LOG(WARNING) << "PortBinlog Item get content error, expect length: " << content_length + << ", left length: " << binlog_str.size(); return false; } binlog_str.erase(0, content_length); diff --git a/pika-tools/pika-port/pika_port_3/binlog_transverter.h b/pika-tools/pika-port/pika_port_3/binlog_transverter.h index c0d7b4f204..a058745fbb 100644 --- a/pika-tools/pika-port/pika_port_3/binlog_transverter.h +++ b/pika-tools/pika-port/pika_port_3/binlog_transverter.h @@ -13,8 +13,9 @@ /* * *****************Type First PortBinlog Item Format***************** - * | | | | | | | | | - * 2 Bytes 4 Bytes 4 Bytes 8 Bytes 4 Bytes 8 Bytes 4 Bytes content length Bytes + * | | | | | | | | + * | 2 Bytes 4 Bytes 4 Bytes 8 Bytes 4 Bytes 8 Bytes 4 Bytes content + * length Bytes * */ @@ -23,58 +24,43 @@ enum PortBinlogType { }; class PortBinlogItem { - public: - PortBinlogItem() : - exec_time_(0), - server_id_(0), - logic_id_(0), - filenum_(0), - offset_(0), - content_("") {} + public: + PortBinlogItem() : exec_time_(0), server_id_(0), logic_id_(0), filenum_(0), offset_(0), content_("") {} - friend class PortBinlogTransverter; + friend class PortBinlogTransverter; - uint32_t exec_time() const; - uint32_t server_id() const; - uint64_t logic_id() const; - uint32_t filenum() const; - uint64_t offset() const; - const std::string& content() const; - std::string ToString() const; + uint32_t exec_time() const; + uint32_t server_id() const; + uint64_t logic_id() const; + uint32_t filenum() const; + uint64_t offset() const; + const std::string& content() const; + std::string ToString() const; - void set_exec_time(uint32_t exec_time); - void set_server_id(uint32_t server_id); - void set_logic_id(uint64_t logic_id); - void set_filenum(uint32_t filenum); - void set_offset(uint64_t offset); + void set_exec_time(uint32_t exec_time); + void set_server_id(uint32_t server_id); + void set_logic_id(uint64_t logic_id); + void set_filenum(uint32_t filenum); + void set_offset(uint64_t offset); - private: - uint32_t exec_time_; - uint32_t server_id_; - uint64_t logic_id_; - uint32_t filenum_; - uint64_t offset_; - std::string content_; - std::vector extends_; + private: + uint32_t exec_time_; + uint32_t server_id_; + uint64_t logic_id_; + uint32_t filenum_; + uint64_t offset_; + std::string content_; + std::vector extends_; }; -class PortBinlogTransverter{ - public: - PortBinlogTransverter() {}; - static std::string PortBinlogEncode(PortBinlogType type, - uint32_t exec_time, - uint32_t server_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset, - const std::string& content, - const std::vector& extends); - - static bool PortBinlogDecode(PortBinlogType type, - const std::string& binlog, - PortBinlogItem* binlog_item); +class PortBinlogTransverter { + public: + PortBinlogTransverter(){}; + static std::string PortBinlogEncode(PortBinlogType type, uint32_t exec_time, uint32_t server_id, uint64_t logic_id, + uint32_t filenum, uint64_t offset, const std::string& content, + const std::vector& extends); + static bool PortBinlogDecode(PortBinlogType type, const std::string& binlog, PortBinlogItem* binlog_item); }; #endif - diff --git a/pika-tools/pika-port/pika_port_3/conf.h b/pika-tools/pika-port/pika_port_3/conf.h index c3fe48cfcd..dcf8e668cf 100644 --- a/pika-tools/pika-port/pika_port_3/conf.h +++ b/pika-tools/pika-port/pika_port_3/conf.h @@ -1,26 +1,26 @@ #ifndef BINLOG_CONF_H_ #define BINLOG_CONF_H_ -#include #include +#include class Conf { public: Conf() { - local_ip = "127.0.0.1"; - local_port = 0; - master_ip = "127.0.0.1"; - master_port = 0; - forward_ip = "127.0.0.1"; - forward_port = 0; - forward_thread_num = 1; - filenum = size_t(UINT32_MAX); // src/pika_trysync_thread.cc:48 - offset = 0; - log_path = "./log/"; - dump_path = "./rsync_dump/"; - sync_batch_num = 512; - wait_bgsave_timeout = 1800; //30 minutes - exit_if_dbsync = false; + local_ip = "127.0.0.1"; + local_port = 0; + master_ip = "127.0.0.1"; + master_port = 0; + forward_ip = "127.0.0.1"; + forward_port = 0; + forward_thread_num = 1; + filenum = size_t(UINT32_MAX); // src/pika_trysync_thread.cc:48 + offset = 0; + log_path = "./log/"; + dump_path = "./rsync_dump/"; + sync_batch_num = 512; + wait_bgsave_timeout = 1800; // 30 minutes + exit_if_dbsync = false; } public: diff --git a/pika-tools/pika-port/pika_port_3/const.cc b/pika-tools/pika-port/pika_port_3/const.cc index af7f5a5885..dafc7d9261 100644 --- a/pika-tools/pika-port/pika_port_3/const.cc +++ b/pika-tools/pika-port/pika_port_3/const.cc @@ -7,25 +7,25 @@ std::string PikaState(int state) { switch (state) { case PIKA_REPL_NO_CONNECT: - return "PIKA_REPL_NO_CONNECT"; + return "PIKA_REPL_NO_CONNECT"; case PIKA_REPL_CONNECT: - return "PIKA_REPL_CONNECT"; + return "PIKA_REPL_CONNECT"; case PIKA_REPL_CONNECTING: - return "PIKA_REPL_CONNECTING"; + return "PIKA_REPL_CONNECTING"; case PIKA_REPL_CONNECTED: - return "PIKA_REPL_CONNECTED"; + return "PIKA_REPL_CONNECTED"; case PIKA_REPL_WAIT_DBSYNC: - return "PIKA_REPL_WAIT_DBSYNC"; + return "PIKA_REPL_WAIT_DBSYNC"; case PIKA_REPL_ERROR: - return "PIKA_REPL_ERROR"; + return "PIKA_REPL_ERROR"; default: - return "PIKA_REPL_UNKNOWN"; + return "PIKA_REPL_UNKNOWN"; } return "PIKA_REPL_UNKNOWN"; @@ -58,28 +58,28 @@ std::string PikaRole(int role) { const char* GetDBTypeString(int type) { switch (type) { - case int(blackwidow::kStrings) : { - return "blackwidow::kStrings"; + case int(blackwidow::kStrings): { + return "blackwidow::kStrings"; } - case int(blackwidow::kLists) : { - return "blackwidow::kLists"; + case int(blackwidow::kLists): { + return "blackwidow::kLists"; } - case int(blackwidow::kHashes) : { - return "blackwidow::kHashes"; + case int(blackwidow::kHashes): { + return "blackwidow::kHashes"; } - case int(blackwidow::kSets) : { - return "blackwidow::kSets"; + case int(blackwidow::kSets): { + return "blackwidow::kSets"; } - case int(blackwidow::kZSets) : { - return "blackwidow::kZSets"; + case int(blackwidow::kZSets): { + return "blackwidow::kZSets"; } default: { - return "blackwidow::Unknown"; + return "blackwidow::Unknown"; } } } diff --git a/pika-tools/pika-port/pika_port_3/const.h b/pika-tools/pika-port/pika_port_3/const.h index 8708e24b9f..4173f7ce28 100644 --- a/pika-tools/pika-port/pika_port_3/const.h +++ b/pika-tools/pika-port/pika_port_3/const.h @@ -18,11 +18,10 @@ const int64_t kTestNum = LLONG_MAX; const int64_t kDataSetNum = 5; std::string PikaState(int state); -std::string PikaRole(int role) ; +std::string PikaRole(int role); const std::string SlotKeyPrefix = "_internal:slotkey:4migrate:"; const char* GetDBTypeString(int type); #endif - diff --git a/pika-tools/pika-port/pika_port_3/main.cc b/pika-tools/pika-port/pika_port_3/main.cc index e3ecc8ec66..03beff3dba 100644 --- a/pika-tools/pika-port/pika_port_3/main.cc +++ b/pika-tools/pika-port/pika_port_3/main.cc @@ -4,17 +4,17 @@ // of patent rights can be found in the PATENTS file in the same directory. // #include -#include +#include #include -#include #include -#include +#include #include +#include #include -#include "pika_port.h" #include "conf.h" +#include "pika_port.h" Conf g_conf; PikaPort* g_pika_port; @@ -48,7 +48,7 @@ static void createPidFile(const char* file) { static void daemonize() { if (fork() != 0) exit(0); /* parent exits */ - setsid(); /* create a new session */ + setsid(); /* create a new session */ } static void close_std() { @@ -87,7 +87,7 @@ static void GlogInit(const std::string& log_path, bool is_daemon) { } FLAGS_log_dir = log_path; - FLAGS_max_log_size = 2048; // log file 2GB + FLAGS_max_log_size = 2048; // log file 2GB ::google::InitGoogleLogging("pika_port_3"); } @@ -103,7 +103,8 @@ void Usage() { std::cout << "\t-n -- forward port(REQUIRED)" << std::endl; std::cout << "\t-x -- forward thread num(OPTIONAL default: 1)" << std::endl; std::cout << "\t-y -- forward password(OPTIONAL)" << std::endl; - std::cout << "\t-z -- max timeout duration for waiting pika master bgsave data (OPTIONAL default 1800s)" << std::endl; + std::cout << "\t-z -- max timeout duration for waiting pika master bgsave data (OPTIONAL default 1800s)" + << std::endl; std::cout << "\t-f -- binlog filenum(OPTIONAL default: local offset)" << std::endl; std::cout << "\t-s -- binlog offset(OPTIONAL default: local offset)" << std::endl; std::cout << "\t-w -- password for master(OPTIONAL)" << std::endl; @@ -112,32 +113,33 @@ void Usage() { std::cout << "\t-b -- max batch number when port rsync dump data (OPTIONAL default: 512)" << std::endl; std::cout << "\t-d -- daemonize(OPTIONAL)" << std::endl; std::cout << "\t-e -- exit(return -1) if dbsync start(OPTIONAL)" << std::endl; - std::cout << "\texample: ./pika_port -t 127.0.0.1 -p 12345 -i 127.0.0.1 -o 9221 -m 127.0.0.1 -n 6379 -x 7 -f 0 -s 0 -w abc -l ./log -r ./rsync_dump -b 512 -d -e" << std::endl; + std::cout << "\texample: ./pika_port -t 127.0.0.1 -p 12345 -i 127.0.0.1 -o 9221 -m 127.0.0.1 -n 6379 -x 7 -f 0 -s 0 " + "-w abc -l ./log -r ./rsync_dump -b 512 -d -e" + << std::endl; } void PrintInfo(const std::time_t& now) { std::cout << "================== Pika Port 3 ==================" << std::endl; std::cout << "local_ip:" << g_conf.local_ip << std::endl; std::cout << "Local_port:" << g_conf.local_port << std::endl; - std::cout << "Master_ip:" << g_conf.master_ip << std::endl; - std::cout << "Master_port:" << g_conf.master_port << std::endl; - std::cout << "Forward_ip:" << g_conf.forward_ip << std::endl; - std::cout << "Forward_port:" << g_conf.forward_port << std::endl; - std::cout << "Forward_passwd:" << g_conf.forward_passwd << std::endl; + std::cout << "Master_ip:" << g_conf.master_ip << std::endl; + std::cout << "Master_port:" << g_conf.master_port << std::endl; + std::cout << "Forward_ip:" << g_conf.forward_ip << std::endl; + std::cout << "Forward_port:" << g_conf.forward_port << std::endl; + std::cout << "Forward_passwd:" << g_conf.forward_passwd << std::endl; std::cout << "Forward_thread_num:" << g_conf.forward_thread_num << std::endl; - std::cout << "Wait_bgsave_timeout:" << g_conf.wait_bgsave_timeout << std::endl; - std::cout << "Log_path:" << g_conf.log_path << std::endl; - std::cout << "Dump_path:" << g_conf.dump_path << std::endl; - std::cout << "Filenum:" << g_conf.filenum << std::endl; - std::cout << "Offset:" << g_conf.offset << std::endl; - std::cout << "Passwd:" << g_conf.passwd << std::endl; - std::cout << "Sync_batch_num:" << g_conf.sync_batch_num << std::endl; + std::cout << "Wait_bgsave_timeout:" << g_conf.wait_bgsave_timeout << std::endl; + std::cout << "Log_path:" << g_conf.log_path << std::endl; + std::cout << "Dump_path:" << g_conf.dump_path << std::endl; + std::cout << "Filenum:" << g_conf.filenum << std::endl; + std::cout << "Offset:" << g_conf.offset << std::endl; + std::cout << "Passwd:" << g_conf.passwd << std::endl; + std::cout << "Sync_batch_num:" << g_conf.sync_batch_num << std::endl; std::cout << "Startup Time : " << asctime(localtime(&now)); std::cout << "========================================================" << std::endl; } -int main(int argc, char *argv[]) -{ +int main(int argc, char* argv[]) { if (argc < 2) { Usage(); exit(-1); @@ -209,14 +211,14 @@ int main(int argc, char *argv[]) case 'r': snprintf(buf, 1024, "%s", optarg); g_conf.dump_path = std::string(buf); - if (g_conf.dump_path[g_conf.dump_path.length() - 1] != '/' ) { + if (g_conf.dump_path[g_conf.dump_path.length() - 1] != '/') { g_conf.dump_path.append("/"); } break; case 'l': snprintf(buf, 1024, "%s", optarg); g_conf.log_path = std::string(buf); - if (g_conf.log_path[g_conf.log_path.length() - 1] != '/' ) { + if (g_conf.log_path[g_conf.log_path.length() - 1] != '/') { g_conf.log_path.append("/"); } break; @@ -255,9 +257,9 @@ int main(int argc, char *argv[]) std::time_t now = std::chrono::system_clock::to_time_t(start_time); PrintInfo(now); - if (g_conf.master_port == 0 || g_conf.forward_port == 0 - || g_conf.sync_batch_num == 0 || g_conf.wait_bgsave_timeout <= 0) { - fprintf (stderr, "Invalid Arguments\n" ); + if (g_conf.master_port == 0 || g_conf.forward_port == 0 || g_conf.sync_batch_num == 0 || + g_conf.wait_bgsave_timeout <= 0) { + fprintf(stderr, "Invalid Arguments\n"); Usage(); exit(-1); } @@ -281,4 +283,3 @@ int main(int argc, char *argv[]) return 0; } - diff --git a/pika-tools/pika-port/pika_port_3/master_conn.cc b/pika-tools/pika-port/pika_port_3/master_conn.cc index 21737d2984..ff68ecd966 100644 --- a/pika-tools/pika-port/pika_port_3/master_conn.cc +++ b/pika-tools/pika-port/pika_port_3/master_conn.cc @@ -3,19 +3,18 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. - #include -#include "slash/include/slash_string.h" #include "slash/include/slash_coding.h" +#include "slash/include/slash_string.h" +#include "binlog_receiver_thread.h" #include "binlog_transverter.h" #include "const.h" #include "master_conn.h" -#include "binlog_receiver_thread.h" #include "pika_port.h" -extern PikaPort *g_pika_port; +extern PikaPort* g_pika_port; MasterConn::MasterConn(int fd, std::string ip_port, void* worker_specific_data) : PinkConn(fd, ip_port, NULL), @@ -28,9 +27,7 @@ MasterConn::MasterConn(int fd, std::string ip_port, void* worker_specific_data) rbuf_ = static_cast(realloc(rbuf_, REDIS_IOBUF_LEN)); } -MasterConn::~MasterConn() { - free(rbuf_); -} +MasterConn::~MasterConn() { free(rbuf_); } net::ReadStatus MasterConn::ReadRaw(uint32_t count) { if (rbuf_cur_pos_ + count > rbuf_size_) { @@ -72,7 +69,7 @@ net::ReadStatus MasterConn::ReadBody(uint32_t body_length) { return net::kReadAll; } else if (rbuf_len_ > HEADER_LEN + body_length) { LOG(INFO) << "rbuf_len_ larger than sum of header length (6 Byte)" - << " and body_length, rbuf_len_: " << rbuf_len_ << ", body_length: " << body_length; + << " and body_length, rbuf_len_: " << rbuf_len_ << ", body_length: " << body_length; } net::ReadStatus status = ReadRaw(body_length); @@ -105,7 +102,7 @@ int32_t MasterConn::GetNextNum(const std::string& content, int32_t left_pos, int // 012 3 // num range [left_pos + 1, right_pos - 2] assert(left_pos < right_pos); - if (slash::string2l(content.data() + left_pos + 1, right_pos - left_pos - 2, value)) { + if (slash::string2l(content.data() + left_pos + 1, right_pos - left_pos - 2, value)) { return 0; } return -1; @@ -171,7 +168,6 @@ void MasterConn::ResetStatus() { rbuf_cur_pos_ = 0; } - net::ReadStatus MasterConn::GetRequest() { // Read Header net::ReadStatus status; @@ -240,12 +236,9 @@ net::ReadStatus MasterConn::GetRequest() { return net::kReadAll; } -net::WriteStatus MasterConn::SendReply() { - return net::kWriteAll; -} +net::WriteStatus MasterConn::SendReply() { return net::kWriteAll; } -void MasterConn::TryResizeBuffer() { -} +void MasterConn::TryResizeBuffer() {} bool MasterConn::ProcessAuth(const net::RedisCmdArgsType& argv) { if (argv.empty() || argv.size() != 2) { @@ -255,14 +248,14 @@ bool MasterConn::ProcessAuth(const net::RedisCmdArgsType& argv) { if (argv[0] == "auth") { if (argv[1] == std::to_string(g_pika_port->sid())) { is_authed_ = true; - LOG(INFO) << "BinlogReceiverThread AccessHandle succeeded, My server id: " - << g_pika_port->sid() << ", Master auth server id: " << argv[1]; + LOG(INFO) << "BinlogReceiverThread AccessHandle succeeded, My server id: " << g_pika_port->sid() + << ", Master auth server id: " << argv[1]; return true; } } - LOG(INFO) << "BinlogReceiverThread AccessHandle failed, My server id: " - << g_pika_port->sid() << ", Master auth server id: " << argv[1]; + LOG(INFO) << "BinlogReceiverThread AccessHandle failed, My server id: " << g_pika_port->sid() + << ", Master auth server id: " << argv[1]; return false; } @@ -286,4 +279,3 @@ bool MasterConn::ProcessBinlogData(const net::RedisCmdArgsType& argv, const Port return true; } - diff --git a/pika-tools/pika-port/pika_port_3/master_conn.h b/pika-tools/pika-port/pika_port_3/master_conn.h index 86f99368ef..d264e750cd 100644 --- a/pika-tools/pika-port/pika_port_3/master_conn.h +++ b/pika-tools/pika-port/pika_port_3/master_conn.h @@ -20,12 +20,9 @@ class BinlogReceiverThread; -enum PortTransferOperate{ - kTypePortAuth = 1, - kTypePortBinlog = 2 -}; +enum PortTransferOperate { kTypePortAuth = 1, kTypePortBinlog = 2 }; -class MasterConn: public net::PinkConn { +class MasterConn : public net::PinkConn { public: MasterConn(int fd, std::string ip_port, void* worker_specific_data); virtual ~MasterConn(); diff --git a/pika-tools/pika-port/pika_port_3/migrator_thread.cc b/pika-tools/pika-port/pika_port_3/migrator_thread.cc index 95f71c4b82..833bb273de 100644 --- a/pika-tools/pika-port/pika_port_3/migrator_thread.cc +++ b/pika-tools/pika-port/pika_port_3/migrator_thread.cc @@ -3,23 +3,22 @@ #include -#include -#include #include +#include +#include #include "blackwidow/blackwidow.h" -#include "src/redis_strings.h" -#include "src/redis_lists.h" #include "src/redis_hashes.h" +#include "src/redis_lists.h" #include "src/redis_sets.h" +#include "src/redis_strings.h" #include "src/redis_zsets.h" #include "src/scope_snapshot.h" #include "src/strings_value_format.h" const int64_t MAX_BATCH_NUM = 30000; -MigratorThread::~MigratorThread() { -} +MigratorThread::~MigratorThread() {} void MigratorThread::MigrateStringsDB() { blackwidow::RedisStrings* db = (blackwidow::RedisStrings*)(db_); @@ -96,7 +95,8 @@ void MigratorThread::MigrateListsDB() { int64_t count = batch_count; std::vector keys; fin = db->Scan(start_key, pattern, &keys, &count, &next_key); - //LOG(INFO) << "batch count: " << count << ", fin: " << fin << ", keys.size(): " << keys.size() << ", next_key: " << next_key; + // LOG(INFO) << "batch count: " << count << ", fin: " << fin << ", keys.size(): " << keys.size() << ", next_key: " + // << next_key; if (fin && keys.size() == 0) { break; } @@ -111,8 +111,8 @@ void MigratorThread::MigrateListsDB() { std::vector list; blackwidow::Status s = db->LRange(k, pos, pos + g_conf.sync_batch_num - 1, &list); if (!s.ok()) { - LOG(WARNING) << "db->LRange(key:" << k << ", pos:" << pos - << ", batch size: " << g_conf.sync_batch_num << ") = " << s.ToString(); + LOG(WARNING) << "db->LRange(key:" << k << ", pos:" << pos << ", batch size: " << g_conf.sync_batch_num + << ") = " << s.ToString(); continue; } @@ -136,8 +136,8 @@ void MigratorThread::MigrateListsDB() { list.clear(); s = db->LRange(k, pos, pos + g_conf.sync_batch_num - 1, &list); if (!s.ok()) { - LOG(WARNING) << "db->LRange(key:" << k << ", pos:" << pos - << ", batch size:" << g_conf.sync_batch_num << ") = " << s.ToString(); + LOG(WARNING) << "db->LRange(key:" << k << ", pos:" << pos << ", batch size:" << g_conf.sync_batch_num + << ") = " << s.ToString(); } } @@ -154,8 +154,8 @@ void MigratorThread::MigrateListsDB() { PlusNum(); DispatchKey(cmd); } - } // for - } // while + } // for + } // while } void MigratorThread::MigrateHashesDB() { @@ -200,9 +200,7 @@ void MigratorThread::MigrateHashesDB() { argv.push_back("HMSET"); argv.push_back(k); - for (size_t idx = 0; - idx < g_conf.sync_batch_num && !should_exit_ && it != fvs.end(); - idx ++, it ++) { + for (size_t idx = 0; idx < g_conf.sync_batch_num && !should_exit_ && it != fvs.end(); idx++, it++) { argv.push_back(it->field); argv.push_back(it->value); // PlusNum(); @@ -227,8 +225,8 @@ void MigratorThread::MigrateHashesDB() { PlusNum(); DispatchKey(cmd); } - } // for - } // while + } // for + } // while } void MigratorThread::MigrateSetsDB() { @@ -272,9 +270,7 @@ void MigratorThread::MigrateSetsDB() { argv.push_back("SADD"); argv.push_back(k); - for (size_t idx = 0; - idx < g_conf.sync_batch_num && !should_exit_ && it != members.end(); - idx ++, it ++) { + for (size_t idx = 0; idx < g_conf.sync_batch_num && !should_exit_ && it != members.end(); idx++, it++) { argv.push_back(*it); } @@ -297,8 +293,8 @@ void MigratorThread::MigrateSetsDB() { PlusNum(); DispatchKey(cmd); } - } // for - } // while + } // for + } // while } void MigratorThread::MigrateZsetsDB() { @@ -343,9 +339,7 @@ void MigratorThread::MigrateZsetsDB() { argv.push_back("ZADD"); argv.push_back(k); - for (size_t idx = 0; - idx < g_conf.sync_batch_num && !should_exit_ && it != score_members.end(); - idx ++, it ++) { + for (size_t idx = 0; idx < g_conf.sync_batch_num && !should_exit_ && it != score_members.end(); idx++, it++) { argv.push_back(std::to_string(it->score)); argv.push_back(it->member); } @@ -369,33 +363,33 @@ void MigratorThread::MigrateZsetsDB() { PlusNum(); DispatchKey(cmd); } - } // for - } // while + } // for + } // while } void MigratorThread::MigrateDB() { switch (int(type_)) { - case int(blackwidow::kStrings) : { + case int(blackwidow::kStrings): { MigrateStringsDB(); break; } - case int(blackwidow::kLists) : { + case int(blackwidow::kLists): { MigrateListsDB(); break; } - case int(blackwidow::kHashes) : { + case int(blackwidow::kHashes): { MigrateHashesDB(); break; } - case int(blackwidow::kSets) : { + case int(blackwidow::kSets): { MigrateSetsDB(); break; } - case int(blackwidow::kZSets) : { + case int(blackwidow::kZSets): { MigrateZsetsDB(); break; } @@ -407,19 +401,18 @@ void MigratorThread::MigrateDB() { } } -void MigratorThread::DispatchKey(const std::string &command, const std::string& key) { +void MigratorThread::DispatchKey(const std::string& command, const std::string& key) { thread_index_ = (thread_index_ + 1) % thread_num_; size_t idx = thread_index_; - if (key.size()) { // no empty + if (key.size()) { // no empty idx = std::hash()(key) % thread_num_; } (*senders_)[idx]->LoadKey(command); } -void *MigratorThread::ThreadMain() { +void* MigratorThread::ThreadMain() { MigrateDB(); should_exit_ = true; LOG(INFO) << GetDBTypeString(type_) << " keys have been dispatched completly"; return NULL; } - diff --git a/pika-tools/pika-port/pika_port_3/migrator_thread.h b/pika-tools/pika-port/pika_port_3/migrator_thread.h index 45fbef37bb..67a09f8f3c 100644 --- a/pika-tools/pika-port/pika_port_3/migrator_thread.h +++ b/pika-tools/pika-port/pika_port_3/migrator_thread.h @@ -10,34 +10,31 @@ class MigratorThread : public net::Thread { public: - MigratorThread(void *db, std::vector *senders, int type, int thread_num) : - db_(db), - should_exit_(false), - senders_(senders), - type_(type), - thread_num_(thread_num), - thread_index_(0), - num_(0) { - } + MigratorThread(void* db, std::vector* senders, int type, int thread_num) + : db_(db), + should_exit_(false), + senders_(senders), + type_(type), + thread_num_(thread_num), + thread_index_(0), + num_(0) {} - virtual ~ MigratorThread(); + virtual ~MigratorThread(); int64_t num() { slash::MutexLock l(&num_mutex_); return num_; } - void Stop() { - should_exit_ = true; - } - + void Stop() { should_exit_ = true; } + private: void PlusNum() { slash::MutexLock l(&num_mutex_); ++num_; } - void DispatchKey(const std::string &command, const std::string& key = ""); + void DispatchKey(const std::string& command, const std::string& key = ""); void MigrateDB(); void MigrateStringsDB(); @@ -46,13 +43,13 @@ class MigratorThread : public net::Thread { void MigrateSetsDB(); void MigrateZsetsDB(); - virtual void *ThreadMain(); + virtual void* ThreadMain(); private: void* db_; bool should_exit_; - std::vector *senders_; + std::vector* senders_; int type_; int thread_num_; int thread_index_; @@ -62,4 +59,3 @@ class MigratorThread : public net::Thread { }; #endif - diff --git a/pika-tools/pika-port/pika_port_3/pika_binlog.cc b/pika-tools/pika-port/pika_port_3/pika_binlog.cc index 7f8c90b108..7cb71f20ac 100644 --- a/pika-tools/pika-port/pika_port_3/pika_binlog.cc +++ b/pika-tools/pika-port/pika_port_3/pika_binlog.cc @@ -5,12 +5,12 @@ #include "pika_binlog.h" -#include -#include -#include #include -#include +#include #include +#include +#include +#include #include @@ -27,11 +27,7 @@ std::string NewFileName(const std::string name, const uint32_t current) { /* * Version */ -Version::Version(slash::RWFile *save) - : pro_num_(0), - pro_offset_(0), - logic_id_(0), - save_(save) { +Version::Version(slash::RWFile* save) : pro_num_(0), pro_offset_(0), logic_id_(0), save_(save) { assert(save_ != NULL); pthread_rwlock_init(&rwlock_, NULL); @@ -43,7 +39,7 @@ Version::~Version() { } Status Version::StableSave() { - char *p = save_->GetData(); + char* p = save_->GetData(); memcpy(p, &pro_num_, sizeof(uint32_t)); p += 4; memcpy(p, &pro_offset_, sizeof(uint64_t)); @@ -74,20 +70,19 @@ Status Version::Init() { /* * Binlog */ -Binlog::Binlog(const std::string& binlog_path, const int file_size) : - consumer_num_(0), - version_(NULL), - queue_(NULL), - versionfile_(NULL), - pro_num_(0), - pool_(NULL), - exit_all_consume_(false), - binlog_path_(binlog_path), - file_size_(file_size) { - +Binlog::Binlog(const std::string& binlog_path, const int file_size) + : consumer_num_(0), + version_(NULL), + queue_(NULL), + versionfile_(NULL), + pro_num_(0), + pool_(NULL), + exit_all_consume_(false), + binlog_path_(binlog_path), + file_size_(file_size) { // To intergrate with old version, we don't set mmap file size to 100M; - //slash::SetMmapBoundSize(file_size); - //slash::kMmapBoundSize = 1024 * 1024 * 100; + // slash::SetMmapBoundSize(file_size); + // slash::kMmapBoundSize = 1024 * 1024 * 100; Status s; @@ -106,7 +101,6 @@ Binlog::Binlog(const std::string& binlog_path, const int file_size) : LOG(FATAL) << "Binlog: NewWritableFile(" << filename << ") = " << s.ToString(); } - s = slash::NewRWFile(manifest, &versionfile_); if (!s.ok()) { LOG(FATAL) << "Binlog: new versionfile error " << s.ToString(); @@ -124,7 +118,7 @@ Binlog::Binlog(const std::string& binlog_path, const int file_size) : pro_num_ = version_->pro_num_; // Debug - //version_->debug(); + // version_->debug(); } else { LOG(FATAL) << "Binlog: open versionfile error"; } @@ -170,9 +164,7 @@ Status Binlog::GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset, uint64 } // Note: mutex lock should be held -Status Binlog::Put(const std::string &item) { - return Put(item.c_str(), item.size()); -} +Status Binlog::Put(const std::string& item) { return Put(item.c_str(), item.size()); } // Note: mutex lock should be held Status Binlog::Put(const char* item, int len) { @@ -208,43 +200,43 @@ Status Binlog::Put(const char* item, int len) { return s; } - -Status Binlog::EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset) { - Status s; - assert(n <= 0xffffff); - assert(block_offset_ + kHeaderSize + n <= kBlockSize); - - char buf[kHeaderSize]; - - uint64_t now; - struct timeval tv; - gettimeofday(&tv, NULL); - now = tv.tv_sec; - buf[0] = static_cast(n & 0xff); - buf[1] = static_cast((n & 0xff00) >> 8); - buf[2] = static_cast(n >> 16); - buf[3] = static_cast(now & 0xff); - buf[4] = static_cast((now & 0xff00) >> 8); - buf[5] = static_cast((now & 0xff0000) >> 16); - buf[6] = static_cast((now & 0xff000000) >> 24); - buf[7] = static_cast(t); - - s = queue_->Append(Slice(buf, kHeaderSize)); + +Status Binlog::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset) { + Status s; + assert(n <= 0xffffff); + assert(block_offset_ + kHeaderSize + n <= kBlockSize); + + char buf[kHeaderSize]; + + uint64_t now; + struct timeval tv; + gettimeofday(&tv, NULL); + now = tv.tv_sec; + buf[0] = static_cast(n & 0xff); + buf[1] = static_cast((n & 0xff00) >> 8); + buf[2] = static_cast(n >> 16); + buf[3] = static_cast(now & 0xff); + buf[4] = static_cast((now & 0xff00) >> 8); + buf[5] = static_cast((now & 0xff0000) >> 16); + buf[6] = static_cast((now & 0xff000000) >> 24); + buf[7] = static_cast(t); + + s = queue_->Append(Slice(buf, kHeaderSize)); + if (s.ok()) { + s = queue_->Append(Slice(ptr, n)); if (s.ok()) { - s = queue_->Append(Slice(ptr, n)); - if (s.ok()) { - s = queue_->Flush(); - } + s = queue_->Flush(); } - block_offset_ += static_cast(kHeaderSize + n); + } + block_offset_ += static_cast(kHeaderSize + n); - *temp_pro_offset += kHeaderSize + n; - return s; + *temp_pro_offset += kHeaderSize + n; + return s; } -Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { +Status Binlog::Produce(const Slice& item, int* temp_pro_offset) { Status s; - const char *ptr = item.data(); + const char* ptr = item.data(); size_t left = item.size(); bool begin = true; @@ -285,8 +277,8 @@ Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { return s; } - -Status Binlog::AppendBlank(slash::WritableFile *file, uint64_t len) { + +Status Binlog::AppendBlank(slash::WritableFile* file, uint64_t len) { if (len < kHeaderSize) { return Status::OK(); } @@ -304,7 +296,7 @@ Status Binlog::AppendBlank(slash::WritableFile *file, uint64_t len) { if (len % kBlockSize < kHeaderSize) { n = 0; } else { - n = (uint32_t) ((len % kBlockSize) - kHeaderSize); + n = (uint32_t)((len % kBlockSize) - kHeaderSize); } char buf[kBlockSize]; diff --git a/pika-tools/pika-port/pika_port_3/pika_binlog.h b/pika-tools/pika-port/pika_port_3/pika_binlog.h index 50a9d68150..302c2f222a 100644 --- a/pika-tools/pika-port/pika_port_3/pika_binlog.h +++ b/pika-tools/pika-port/pika_port_3/pika_binlog.h @@ -6,24 +6,24 @@ #ifndef PIKA_BINLOG_H_ #define PIKA_BINLOG_H_ +#include #include +#include #include #include -#include -#include #ifndef __STDC_FORMAT_MACROS -# define __STDC_FORMAT_MACROS -# include -#endif +# define __STDC_FORMAT_MACROS +# include +#endif -#include "slash/include/slash_status.h" -#include "slash/include/slash_mutex.h" -#include "slash/include/env.h" #include "pika_define.h" +#include "slash/include/env.h" +#include "slash/include/slash_mutex.h" +#include "slash/include/slash_status.h" -using slash::Status; using slash::Slice; +using slash::Status; std::string NewFileName(const std::string name, const uint32_t current); @@ -34,10 +34,10 @@ class Binlog { Binlog(const std::string& Binlog_path, const int file_size = 100 * 1024 * 1024); ~Binlog(); - void Lock() { mutex_.Lock(); } - void Unlock() { mutex_.Unlock(); } + void Lock() { mutex_.Lock(); } + void Unlock() { mutex_.Unlock(); } - Status Put(const std::string &item); + Status Put(const std::string& item); Status Put(const char* item, int len); Status GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset, uint64_t* logic_id = NULL); @@ -46,33 +46,29 @@ class Binlog { */ Status SetProducerStatus(uint32_t filenum, uint64_t pro_offset); - static Status AppendBlank(slash::WritableFile *file, uint64_t len); + static Status AppendBlank(slash::WritableFile* file, uint64_t len); - slash::WritableFile *queue() { return queue_; } + slash::WritableFile* queue() { return queue_; } - uint64_t file_size() { - return file_size_; - } + uint64_t file_size() { return file_size_; } std::string filename; private: - void InitLogFile(); - Status EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset); - + Status EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset); /* * Produce */ - Status Produce(const Slice &item, int *pro_offset); + Status Produce(const Slice& item, int* pro_offset); uint32_t consumer_num_; uint64_t item_num_; Version* version_; - slash::WritableFile *queue_; - slash::RWFile *versionfile_; + slash::WritableFile* queue_; + slash::RWFile* versionfile_; slash::Mutex mutex_; @@ -93,7 +89,7 @@ class Binlog { class Version { public: - Version(slash::RWFile *save); + Version(slash::RWFile* save); ~Version(); Status Init(); @@ -109,12 +105,11 @@ class Version { void debug() { slash::RWLock(&rwlock_, false); - printf ("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); + printf("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); } private: - - slash::RWFile *save_; + slash::RWFile* save_; // No copying allowed; Version(const Version&); diff --git a/pika-tools/pika-port/pika_port_3/pika_command.h b/pika-tools/pika-port/pika_port_3/pika_command.h index 06a28a49a2..0a9fe603cb 100644 --- a/pika-tools/pika-port/pika_port_3/pika_command.h +++ b/pika-tools/pika-port/pika_port_3/pika_command.h @@ -7,19 +7,19 @@ #define PIKA_COMMAND_H_ #include -#include #include +#include #include -#include "slash/include/slash_string.h" #include "net/include/redis_conn.h" +#include "slash/include/slash_string.h" #include "binlog_transverter.h" const std::string kPikaBinlogMagic = "__PIKA_X#$SKGI"; -//Constant for command name -//Admin +// Constant for command name +// Admin const std::string kCmdNameSlaveof = "slaveof"; const std::string kCmdNameTrysync = "trysync"; const std::string kCmdNameAuth = "auth"; @@ -47,7 +47,7 @@ const std::string kCmdNameSlowlog = "slowlog"; const std::string kCmdNameTcmalloc = "tcmalloc"; #endif -//Migrate slot +// Migrate slot const std::string kCmdNameSlotsMgrtSlot = "slotsmgrtslot"; const std::string kCmdNameSlotsMgrtTagSlot = "slotsmgrttagslot"; const std::string kCmdNameSlotsMgrtOne = "slotsmgrtone"; @@ -66,7 +66,7 @@ const std::string kCmdNameSlotsMgrtExecWrapper = "slotsmgrt-exec-wrapper"; const std::string kCmdNameSlotsMgrtAsyncStatus = "slotsmgrt-async-status"; const std::string kCmdNameSlotsMgrtAsyncCancel = "slotsmgrt-async-cancel"; -//Kv +// Kv const std::string kCmdNameSet = "set"; const std::string kCmdNameGet = "get"; const std::string kCmdNameDel = "del"; @@ -100,7 +100,7 @@ const std::string kCmdNameType = "type"; const std::string kCmdNameScan = "scan"; const std::string kCmdNameScanx = "scanx"; -//Hash +// Hash const std::string kCmdNameHDel = "hdel"; const std::string kCmdNameHSet = "hset"; const std::string kCmdNameHGet = "hget"; @@ -118,7 +118,7 @@ const std::string kCmdNameHVals = "hvals"; const std::string kCmdNameHScan = "hscan"; const std::string kCmdNameHScanx = "hscanx"; -//List +// List const std::string kCmdNameLIndex = "lindex"; const std::string kCmdNameLInsert = "linsert"; const std::string kCmdNameLLen = "llen"; @@ -134,14 +134,14 @@ const std::string kCmdNameRPopLPush = "rpoplpush"; const std::string kCmdNameRPush = "rpush"; const std::string kCmdNameRPushx = "rpushx"; -//BitMap +// BitMap const std::string kCmdNameBitSet = "setbit"; const std::string kCmdNameBitGet = "getbit"; const std::string kCmdNameBitPos = "bitpos"; const std::string kCmdNameBitOp = "bitop"; const std::string kCmdNameBitCount = "bitcount"; -//Zset +// Zset const std::string kCmdNameZAdd = "zadd"; const std::string kCmdNameZCard = "zcard"; const std::string kCmdNameZScan = "zscan"; @@ -165,7 +165,7 @@ const std::string kCmdNameZRemrangebyrank = "zremrangebyrank"; const std::string kCmdNameZRemrangebylex = "zremrangebylex"; const std::string kCmdNameZRemrangebyscore = "zremrangebyscore"; -//Set +// Set const std::string kCmdNameSAdd = "sadd"; const std::string kCmdNameSPop = "spop"; const std::string kCmdNameSCard = "scard"; @@ -182,12 +182,12 @@ const std::string kCmdNameSDiffstore = "sdiffstore"; const std::string kCmdNameSMove = "smove"; const std::string kCmdNameSRandmember = "srandmember"; -//HyperLogLog +// HyperLogLog const std::string kCmdNamePfAdd = "pfadd"; const std::string kCmdNamePfCount = "pfcount"; const std::string kCmdNamePfMerge = "pfmerge"; -//GEO +// GEO const std::string kCmdNameGeoAdd = "geoadd"; const std::string kCmdNameGeoPos = "geopos"; const std::string kCmdNameGeoDist = "geodist"; @@ -195,7 +195,7 @@ const std::string kCmdNameGeoHash = "geohash"; const std::string kCmdNameGeoRadius = "georadius"; const std::string kCmdNameGeoRadiusByMember = "georadiusbymember"; -//Pub/Sub +// Pub/Sub const std::string kCmdNamePublish = "publish"; const std::string kCmdNameSubscribe = "subscribe"; const std::string kCmdNameUnSubscribe = "unsubscribe"; @@ -204,75 +204,60 @@ const std::string kCmdNamePSubscribe = "psubscribe"; const std::string kCmdNamePUnSubscribe = "punsubscribe"; typedef net::RedisCmdArgsType PikaCmdArgsType; -static const int RAW_ARGS_LEN = 1024 * 1024; +static const int RAW_ARGS_LEN = 1024 * 1024; enum CmdFlagsMask { - kCmdFlagsMaskRW = 1, - kCmdFlagsMaskType = 30, - kCmdFlagsMaskLocal = 32, - kCmdFlagsMaskSuspend = 64, - kCmdFlagsMaskPrior = 128, - kCmdFlagsMaskAdminRequire = 256 + kCmdFlagsMaskRW = 1, + kCmdFlagsMaskType = 30, + kCmdFlagsMaskLocal = 32, + kCmdFlagsMaskSuspend = 64, + kCmdFlagsMaskPrior = 128, + kCmdFlagsMaskAdminRequire = 256 }; enum CmdFlags { - kCmdFlagsRead = 0, //default rw - kCmdFlagsWrite = 1, - kCmdFlagsAdmin = 0, //default type - kCmdFlagsKv = 2, - kCmdFlagsHash = 4, - kCmdFlagsList = 6, - kCmdFlagsSet = 8, - kCmdFlagsZset = 10, - kCmdFlagsBit = 12, - kCmdFlagsHyperLogLog = 14, - kCmdFlagsGeo = 16, - kCmdFlagsPubSub = 18, - kCmdFlagsNoLocal = 0, //default nolocal - kCmdFlagsLocal = 32, - kCmdFlagsNoSuspend = 0, //default nosuspend - kCmdFlagsSuspend = 64, - kCmdFlagsNoPrior = 0, //default noprior - kCmdFlagsPrior = 128, - kCmdFlagsNoAdminRequire = 0, //default no need admin - kCmdFlagsAdminRequire = 256 + kCmdFlagsRead = 0, // default rw + kCmdFlagsWrite = 1, + kCmdFlagsAdmin = 0, // default type + kCmdFlagsKv = 2, + kCmdFlagsHash = 4, + kCmdFlagsList = 6, + kCmdFlagsSet = 8, + kCmdFlagsZset = 10, + kCmdFlagsBit = 12, + kCmdFlagsHyperLogLog = 14, + kCmdFlagsGeo = 16, + kCmdFlagsPubSub = 18, + kCmdFlagsNoLocal = 0, // default nolocal + kCmdFlagsLocal = 32, + kCmdFlagsNoSuspend = 0, // default nosuspend + kCmdFlagsSuspend = 64, + kCmdFlagsNoPrior = 0, // default noprior + kCmdFlagsPrior = 128, + kCmdFlagsNoAdminRequire = 0, // default no need admin + kCmdFlagsAdminRequire = 256 }; - class CmdInfo { -public: - CmdInfo(const std::string _name, int _num, uint16_t _flag) - : name_(_name), arity_(_num), flag_(_flag) {} + public: + CmdInfo(const std::string _name, int _num, uint16_t _flag) : name_(_name), arity_(_num), flag_(_flag) {} bool CheckArg(int num) const { if ((arity_ > 0 && num != arity_) || (arity_ < 0 && num < -arity_)) { return false; } return true; } - bool is_write() const { - return ((flag_ & kCmdFlagsMaskRW) == kCmdFlagsWrite); - } - uint16_t flag_type() const { - return flag_ & kCmdFlagsMaskType; - } - bool is_local() const { - return ((flag_ & kCmdFlagsMaskLocal) == kCmdFlagsLocal); - } + bool is_write() const { return ((flag_ & kCmdFlagsMaskRW) == kCmdFlagsWrite); } + uint16_t flag_type() const { return flag_ & kCmdFlagsMaskType; } + bool is_local() const { return ((flag_ & kCmdFlagsMaskLocal) == kCmdFlagsLocal); } // Others need to be suspended when a suspend command run - bool is_suspend() const { - return ((flag_ & kCmdFlagsMaskSuspend) == kCmdFlagsSuspend); - } - bool is_prior() const { - return ((flag_ & kCmdFlagsMaskPrior) == kCmdFlagsPrior); - } + bool is_suspend() const { return ((flag_ & kCmdFlagsMaskSuspend) == kCmdFlagsSuspend); } + bool is_prior() const { return ((flag_ & kCmdFlagsMaskPrior) == kCmdFlagsPrior); } // Must with admin auth - bool is_admin_require() const { - return ((flag_ & kCmdFlagsMaskAdminRequire) == kCmdFlagsAdminRequire); - } - std::string name() const { - return name_; - } -private: + bool is_admin_require() const { return ((flag_ & kCmdFlagsMaskAdminRequire) == kCmdFlagsAdminRequire); } + std::string name() const { return name_; } + + private: std::string name_; int arity_; uint16_t flag_; @@ -282,12 +267,12 @@ class CmdInfo { }; void inline RedisAppendContent(std::string& str, const std::string& value); -void inline RedisAppendLen(std::string& str, int64_t ori, const std::string &prefix); +void inline RedisAppendLen(std::string& str, int64_t ori, const std::string& prefix); const std::string kNewLine = "\r\n"; class CmdRes { -public: + public: enum CmdRet { kNone = 0, kOk, @@ -312,101 +297,85 @@ class CmdRes { kErrOther, }; - CmdRes():ret_(kNone) {} + CmdRes() : ret_(kNone) {} - bool none() const { - return ret_ == kNone && message_.empty(); - } - bool ok() const { - return ret_ == kOk || ret_ == kNone; - } + bool none() const { return ret_ == kNone && message_.empty(); } + bool ok() const { return ret_ == kOk || ret_ == kNone; } void clear() { message_.clear(); ret_ = kNone; } - std::string raw_message() const { - return message_; - } + std::string raw_message() const { return message_; } std::string message() const { std::string result; switch (ret_) { - case kNone: - return message_; - case kOk: - return "+OK\r\n"; - case kPong: - return "+PONG\r\n"; - case kSyntaxErr: - return "-ERR syntax error\r\n"; - case kInvalidInt: - return "-ERR value is not an integer or out of range\r\n"; - case kInvalidBitInt: - return "-ERR bit is not an integer or out of range\r\n"; - case kInvalidBitOffsetInt: - return "-ERR bit offset is not an integer or out of range\r\n"; - case kWrongBitOpNotNum: - return "-ERR BITOP NOT must be called with a single source key.\r\n"; - - case kInvalidBitPosArgument: - return "-ERR The bit argument must be 1 or 0.\r\n"; - case kInvalidFloat: - return "-ERR value is not a valid float\r\n"; - case kOverFlow: - return "-ERR increment or decrement would overflow\r\n"; - case kNotFound: - return "-ERR no such key\r\n"; - case kOutOfRange: - return "-ERR index out of range\r\n"; - case kInvalidPwd: - return "-ERR invalid password\r\n"; - case kNoneBgsave: - return "-ERR No BGSave Works now\r\n"; - case kPurgeExist: - return "-ERR binlog already in purging...\r\n"; - case kInvalidParameter: - return "-ERR Invalid Argument\r\n"; - case kWrongNum: - result = "-ERR wrong number of arguments for '"; - result.append(message_); - result.append("' command\r\n"); - break; - case kInvalidIndex: - result = "-ERR invalid DB index\r\n"; - break; - case kInvalidDbType: - result = "-ERR invalid DB type\r\n"; - break; - case kErrOther: - result = "-ERR "; - result.append(message_); - result.append(kNewLine); - break; - default: - break; + case kNone: + return message_; + case kOk: + return "+OK\r\n"; + case kPong: + return "+PONG\r\n"; + case kSyntaxErr: + return "-ERR syntax error\r\n"; + case kInvalidInt: + return "-ERR value is not an integer or out of range\r\n"; + case kInvalidBitInt: + return "-ERR bit is not an integer or out of range\r\n"; + case kInvalidBitOffsetInt: + return "-ERR bit offset is not an integer or out of range\r\n"; + case kWrongBitOpNotNum: + return "-ERR BITOP NOT must be called with a single source key.\r\n"; + + case kInvalidBitPosArgument: + return "-ERR The bit argument must be 1 or 0.\r\n"; + case kInvalidFloat: + return "-ERR value is not a valid float\r\n"; + case kOverFlow: + return "-ERR increment or decrement would overflow\r\n"; + case kNotFound: + return "-ERR no such key\r\n"; + case kOutOfRange: + return "-ERR index out of range\r\n"; + case kInvalidPwd: + return "-ERR invalid password\r\n"; + case kNoneBgsave: + return "-ERR No BGSave Works now\r\n"; + case kPurgeExist: + return "-ERR binlog already in purging...\r\n"; + case kInvalidParameter: + return "-ERR Invalid Argument\r\n"; + case kWrongNum: + result = "-ERR wrong number of arguments for '"; + result.append(message_); + result.append("' command\r\n"); + break; + case kInvalidIndex: + result = "-ERR invalid DB index\r\n"; + break; + case kInvalidDbType: + result = "-ERR invalid DB type\r\n"; + break; + case kErrOther: + result = "-ERR "; + result.append(message_); + result.append(kNewLine); + break; + default: + break; } return result; } // Inline functions for Create Redis protocol - void AppendStringLen(int64_t ori) { - RedisAppendLen(message_, ori, "$"); - } - void AppendArrayLen(int64_t ori) { - RedisAppendLen(message_, ori, "*"); - } - void AppendInteger(int64_t ori) { - RedisAppendLen(message_, ori, ":"); - } - void AppendContent(const std::string &value) { - RedisAppendContent(message_, value); - } - void AppendString(const std::string &value) { + void AppendStringLen(int64_t ori) { RedisAppendLen(message_, ori, "$"); } + void AppendArrayLen(int64_t ori) { RedisAppendLen(message_, ori, "*"); } + void AppendInteger(int64_t ori) { RedisAppendLen(message_, ori, ":"); } + void AppendContent(const std::string& value) { RedisAppendContent(message_, value); } + void AppendString(const std::string& value) { AppendStringLen(value.size()); AppendContent(value); } - void AppendStringRaw(std::string &value) { - message_.append(value); - } + void AppendStringRaw(std::string& value) { message_.append(value); } void SetRes(CmdRet _ret, const std::string content = "") { ret_ = _ret; if (!content.empty()) { @@ -414,7 +383,7 @@ class CmdRes { } } -private: + private: std::string message_; CmdRet ret_; }; @@ -426,22 +395,16 @@ class Cmd { virtual void Do() = 0; - void Initial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info) { - res_.clear(); // Clear res content - Clear(); // Clear cmd, Derived class can has own implement + void Initial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info) { + res_.clear(); // Clear res content + Clear(); // Clear cmd, Derived class can has own implement DoInitial(argvs, ptr_info); }; - CmdRes& res() { - return res_; - } + CmdRes& res() { return res_; } - virtual std::string ToBinlog(const PikaCmdArgsType& argv, - uint32_t exec_time, - const std::string& server_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { + virtual std::string ToBinlog(const PikaCmdArgsType& argv, uint32_t exec_time, const std::string& server_id, + uint64_t logic_id, uint32_t filenum, uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, argv.size(), "*"); @@ -451,22 +414,16 @@ class Cmd { RedisAppendContent(content, v); } - return PortBinlogTransverter::PortBinlogEncode(PortBinlogType::PortTypeFirst, - exec_time, - std::stoi(server_id), - logic_id, - filenum, - offset, - content, - {}); + return PortBinlogTransverter::PortBinlogEncode(PortBinlogType::PortTypeFirst, exec_time, std::stoi(server_id), + logic_id, filenum, offset, content, {}); } protected: CmdRes res_; private: - virtual void DoInitial(PikaCmdArgsType &argvs, const CmdInfo* const ptr_info) = 0; - virtual void Clear() {}; + virtual void DoInitial(PikaCmdArgsType& argvs, const CmdInfo* const ptr_info) = 0; + virtual void Clear(){}; Cmd(const Cmd&); Cmd& operator=(const Cmd&); @@ -489,7 +446,7 @@ void RedisAppendContent(std::string& str, const std::string& value) { str.append(kNewLine); } -void RedisAppendLen(std::string& str, int64_t ori, const std::string &prefix) { +void RedisAppendLen(std::string& str, int64_t ori, const std::string& prefix) { char buf[32]; slash::ll2string(buf, 32, static_cast(ori)); str.append(prefix); diff --git a/pika-tools/pika-port/pika_port_3/pika_define.h b/pika-tools/pika-port/pika_port_3/pika_define.h index f54f324338..dc8fc0d860 100644 --- a/pika-tools/pika-port/pika_port_3/pika_define.h +++ b/pika-tools/pika-port/pika_port_3/pika_define.h @@ -17,11 +17,11 @@ struct WorkerCronTask { std::string ip_port; }; typedef WorkerCronTask MonitorCronTask; -//task define +// task define #define TASK_KILL 0 #define TASK_KILLALL 1 -//slave item +// slave item struct SlaveItem { int64_t sid; std::string ip_port; @@ -33,11 +33,11 @@ struct SlaveItem { struct timeval create_time; }; -//slowlog define +// slowlog define #define SLOWLOG_ENTRY_MAX_ARGC 32 #define SLOWLOG_ENTRY_MAX_STRING 128 -//slowlog entry +// slowlog entry struct SlowlogEntry { int64_t id; int64_t start_time; @@ -47,28 +47,28 @@ struct SlowlogEntry { #define PIKA_MIN_RESERVED_FDS 5000 -const int SLAVE_ITEM_STAGE_ONE = 1; -const int SLAVE_ITEM_STAGE_TWO = 2; - -//repl_state_ -const int PIKA_REPL_NO_CONNECT = 0; -const int PIKA_REPL_CONNECT = 1; -const int PIKA_REPL_CONNECTING = 2; -const int PIKA_REPL_CONNECTED = 3; -const int PIKA_REPL_WAIT_DBSYNC = 4; -const int PIKA_REPL_ERROR = 5; - -//role -const int PIKA_ROLE_SINGLE = 0; -const int PIKA_ROLE_SLAVE = 1; -const int PIKA_ROLE_MASTER = 2; +const int SLAVE_ITEM_STAGE_ONE = 1; +const int SLAVE_ITEM_STAGE_TWO = 2; + +// repl_state_ +const int PIKA_REPL_NO_CONNECT = 0; +const int PIKA_REPL_CONNECT = 1; +const int PIKA_REPL_CONNECTING = 2; +const int PIKA_REPL_CONNECTED = 3; +const int PIKA_REPL_WAIT_DBSYNC = 4; +const int PIKA_REPL_ERROR = 5; + +// role +const int PIKA_ROLE_SINGLE = 0; +const int PIKA_ROLE_SLAVE = 1; +const int PIKA_ROLE_MASTER = 2; const int PIKA_ROLE_DOUBLE_MASTER = 3; /* * The size of Binlogfile */ -//static uint64_t kBinlogSize = 128; -//static const uint64_t kBinlogSize = 1024 * 1024 * 100; +// static uint64_t kBinlogSize = 128; +// static const uint64_t kBinlogSize = 1024 * 1024 * 100; enum RecordType { kZeroType = 0, diff --git a/pika-tools/pika-port/pika_port_3/pika_port.cc b/pika-tools/pika-port/pika_port_3/pika_port.cc index da8c2fef1f..90dea95d60 100644 --- a/pika-tools/pika-port/pika_port_3/pika_port.cc +++ b/pika-tools/pika-port/pika_port_3/pika_port.cc @@ -3,58 +3,54 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. +#include #include -#include #include -#include #include -#include +#include +#include -#include #include +#include +#include "conf.h" +#include "const.h" +#include "pika_port.h" #include "slash/include/env.h" -#include "slash/include/slash_string.h" #include "slash/include/rsync.h" -#include "pika_port.h" -#include "const.h" -#include "conf.h" +#include "slash/include/slash_string.h" PikaPort::PikaPort(std::string& master_ip, int master_port, std::string& passwd) - : - ping_thread_(NULL), - master_ip_(master_ip), - master_port_(master_port), - master_connection_(0), - role_(PIKA_ROLE_PORT), - repl_state_(PIKA_REPL_NO_CONNECT), - requirepass_(passwd), - // cli_(NULL), - should_exit_(false), - sid_(0) { - + : ping_thread_(NULL), + master_ip_(master_ip), + master_port_(master_port), + master_connection_(0), + role_(PIKA_ROLE_PORT), + repl_state_(PIKA_REPL_NO_CONNECT), + requirepass_(passwd), + // cli_(NULL), + should_exit_(false), + sid_(0) { pthread_rwlockattr_t attr; pthread_rwlockattr_init(&attr); pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); pthread_rwlock_init(&rwlock_, &attr); - - //Init ip host + + // Init ip host if (!Init()) { LOG(FATAL) << "Init iotcl error"; } - // Create redis sender + // Create redis sender size_t thread_num = g_conf.forward_thread_num; - for (size_t i = 0; i < thread_num; i++) { - senders_.emplace_back(new RedisSender(int(i), g_conf.forward_ip, - g_conf.forward_port, g_conf.forward_passwd)); + for (size_t i = 0; i < thread_num; i++) { + senders_.emplace_back(new RedisSender(int(i), g_conf.forward_ip, g_conf.forward_port, g_conf.forward_passwd)); } // Create thread - binlog_receiver_thread_ = new BinlogReceiverThread(g_conf.local_ip, - g_conf.local_port + 1000, 1000); + binlog_receiver_thread_ = new BinlogReceiverThread(g_conf.local_ip, g_conf.local_port + 1000, 1000); trysync_thread_ = new TrysyncThread(); - + pthread_rwlock_init(&state_protector_, NULL); logger_ = new Binlog(g_conf.log_path, 104857600); } @@ -68,11 +64,10 @@ PikaPort::~PikaPort() { delete logger_; - pthread_rwlock_destroy(&state_protector_); pthread_rwlock_destroy(&rwlock_); - LOG(INFO) << "PikaPort "<< pthread_self() << " exit!!!"; + LOG(INFO) << "PikaPort " << pthread_self() << " exit!!!"; } bool PikaPort::Init() { @@ -87,7 +82,7 @@ void PikaPort::Cleanup() { } trysync_thread_->Stop(); size_t thread_num = g_conf.forward_thread_num; - for(size_t i = 0; i < thread_num; i++) { + for (size_t i = 0; i < thread_num; i++) { senders_[i]->Stop(); } for (size_t i = 0; i < thread_num; i++) { @@ -102,7 +97,7 @@ void PikaPort::Cleanup() { LOG(INFO) << "=============== Syncing ====================="; LOG(INFO) << "Total replies : " << replies << " received from redis server"; - delete this; // PikaPort is a global object + delete this; // PikaPort is a global object // ::google::ShutdownGoogleLogging(); } @@ -130,15 +125,13 @@ void PikaPort::Start() { Cleanup(); } -void PikaPort::Stop() { - mutex_.Unlock(); -} +void PikaPort::Stop() { mutex_.Unlock(); } -int PikaPort::SendRedisCommand(const std::string &command, const std::string &key) { +int PikaPort::SendRedisCommand(const std::string& command, const std::string& key) { // Send command size_t idx = std::hash()(key) % g_conf.forward_thread_num; senders_[idx]->SendRedisCommand(command); - + return 0; } @@ -177,8 +170,8 @@ void PikaPort::ConnectMasterDone() { bool PikaPort::ShouldStartPingMaster() { slash::RWLock l(&state_protector_, false); - LOG(INFO) << "ShouldStartPingMaster: master_connection " - << master_connection_ << ", repl_state " << PikaState(repl_state_); + LOG(INFO) << "ShouldStartPingMaster: master_connection " << master_connection_ << ", repl_state " + << PikaState(repl_state_); if (repl_state_ == PIKA_REPL_CONNECTING && master_connection_ < 2) { return true; } @@ -192,10 +185,10 @@ void PikaPort::MinusMasterConnection() { if ((--master_connection_) <= 0) { // two connection with master has been deleted if ((role_ & PIKA_ROLE_SLAVE) || (role_ & PIKA_ROLE_PORT)) { - // not change by slaveof no one, so set repl_state = PIKA_REPL_CONNECT, continue to connect master + // not change by slaveof no one, so set repl_state = PIKA_REPL_CONNECT, continue to connect master repl_state_ = PIKA_REPL_CONNECT; } else { - // change by slaveof no one, so set repl_state = PIKA_REPL_NO_CONNECT, reset to SINGLE state + // change by slaveof no one, so set repl_state = PIKA_REPL_NO_CONNECT, reset to SINGLE state repl_state_ = PIKA_REPL_NO_CONNECT; } master_connection_ = 0; @@ -217,8 +210,8 @@ void PikaPort::PlusMasterConnection() { bool PikaPort::ShouldAccessConnAsMaster(const std::string& ip) { slash::RWLock l(&state_protector_, false); - LOG(INFO) << "ShouldAccessConnAsMaster, repl_state_: " - << PikaState(repl_state_) << ", ip: " << ip << ", master_ip: " << master_ip_; + LOG(INFO) << "ShouldAccessConnAsMaster, repl_state_: " << PikaState(repl_state_) << ", ip: " << ip + << ", master_ip: " << master_ip_; if (repl_state_ != PIKA_REPL_NO_CONNECT && ip == master_ip_) { return true; } @@ -262,4 +255,3 @@ void PikaPort::WaitDBSyncFinish() { repl_state_ = PIKA_REPL_CONNECT; } } - diff --git a/pika-tools/pika-port/pika_port_3/pika_port.h b/pika-tools/pika-port/pika_port_3/pika_port.h index 59ddc45590..c43e2030eb 100644 --- a/pika-tools/pika-port/pika_port_3/pika_port.h +++ b/pika-tools/pika-port/pika_port_3/pika_port.h @@ -6,43 +6,34 @@ #ifndef BINLOG_SYNC_H_ #define BINLOG_SYNC_H_ -#include "slash/include/slash_status.h" -#include "slash/include/slash_mutex.h" +#include "binlog_receiver_thread.h" #include "pika_binlog.h" #include "pika_define.h" -#include "binlog_receiver_thread.h" +#include "redis_sender.h" +#include "slash/include/slash_mutex.h" +#include "slash/include/slash_status.h" #include "slaveping_thread.h" #include "trysync_thread.h" -#include "redis_sender.h" #include -using slash::Status; using slash::Slice; +using slash::Status; -class PikaPort -{ -public: +class PikaPort { + public: PikaPort(std::string& master_ip, int master_port, std::string& passwd); ~PikaPort(); /* - * Get & Set + * Get & Set */ - std::string& master_ip() { - return master_ip_; - } - int master_port() { - return master_port_; - } + std::string& master_ip() { return master_ip_; } + int master_port() { return master_port_; } - int64_t sid() { - return sid_; - } + int64_t sid() { return sid_; } - void SetSid(int64_t sid) { - sid_ = sid; - } + void SetSid(int64_t sid) { sid_ = sid; } int role() { slash::RWLock(&state_protector_, false); @@ -52,23 +43,13 @@ class PikaPort slash::RWLock(&state_protector_, false); return repl_state_; } - std::string requirepass() { - return requirepass_; - } - pthread_rwlock_t* rwlock() { - return &rwlock_; - } - BinlogReceiverThread* binlog_receiver_thread() { - return binlog_receiver_thread_; - } - TrysyncThread* trysync_thread() { - return trysync_thread_; - } - Binlog* logger() { - return logger_; - } + std::string requirepass() { return requirepass_; } + pthread_rwlock_t* rwlock() { return &rwlock_; } + BinlogReceiverThread* binlog_receiver_thread() { return binlog_receiver_thread_; } + TrysyncThread* trysync_thread() { return trysync_thread_; } + Binlog* logger() { return logger_; } - int SendRedisCommand(const std::string &command, const std::string &key); + int SendRedisCommand(const std::string& command, const std::string& key); bool SetMaster(std::string& master_ip, int master_port); bool ShouldConnectMaster(); @@ -89,7 +70,7 @@ class PikaPort bool Init(); SlavepingThread* ping_thread_; -private: + private: std::string master_ip_; int master_port_; int master_connection_; @@ -100,7 +81,7 @@ class PikaPort std::string dump_path_; pthread_rwlock_t rwlock_; - slash::Mutex mutex_; // double lock to block main thread + slash::Mutex mutex_; // double lock to block main thread // redis client // net::PinkCli *cli_; @@ -115,12 +96,12 @@ class PikaPort BinlogReceiverThread* binlog_receiver_thread_; TrysyncThread* trysync_thread_; - Binlog *logger_; + Binlog* logger_; - pthread_rwlock_t state_protector_; //protect below, use for master-slave mode + pthread_rwlock_t state_protector_; // protect below, use for master-slave mode - PikaPort(PikaPort &bs); - void operator =(const PikaPort &bs); + PikaPort(PikaPort& bs); + void operator=(const PikaPort& bs); void ConnectRedis(); }; diff --git a/pika-tools/pika-port/pika_port_3/pika_sender.cc b/pika-tools/pika-port/pika_port_3/pika_sender.cc index a3ea55f60e..4b1a60ef56 100644 --- a/pika-tools/pika-port/pika_port_3/pika_sender.cc +++ b/pika-tools/pika-port/pika_port_3/pika_sender.cc @@ -4,20 +4,17 @@ #include "pika_sender.h" #include "slash/include/xdebug.h" -PikaSender::PikaSender(std::string ip, int64_t port, std::string password): - cli_(NULL), - signal_(&keys_mutex_), - ip_(ip), - port_(port), - password_(password), - should_exit_(false), - cnt_(0), - elements_(0) - { - } - -PikaSender::~PikaSender() { -} +PikaSender::PikaSender(std::string ip, int64_t port, std::string password) + : cli_(NULL), + signal_(&keys_mutex_), + ip_(ip), + port_(port), + password_(password), + should_exit_(false), + cnt_(0), + elements_(0) {} + +PikaSender::~PikaSender() {} int PikaSender::QueueSize() { slash::MutexLock l(&keys_mutex_); @@ -104,7 +101,7 @@ void PikaSender::ConnectRedis() { } } -void PikaSender::LoadKey(const std::string &key) { +void PikaSender::LoadKey(const std::string& key) { keys_mutex_.Lock(); if (keys_queue_.size() < 100000) { keys_queue_.push(key); @@ -120,7 +117,7 @@ void PikaSender::LoadKey(const std::string &key) { } } -void PikaSender::SendCommand(std::string &command, const std::string &key) { +void PikaSender::SendCommand(std::string& command, const std::string& key) { // Send command slash::Status s = cli_->Send(&command); if (!s.ok()) { @@ -135,7 +132,7 @@ void PikaSender::SendCommand(std::string &command, const std::string &key) { } } -void *PikaSender::ThreadMain() { +void* PikaSender::ThreadMain() { LOG(INFO) << "Start sender thread..."; if (cli_ == NULL) { @@ -151,7 +148,7 @@ void *PikaSender::ThreadMain() { } keys_mutex_.Unlock(); if (QueueSize() == 0 && should_exit_) { - // if (should_exit_) { + // if (should_exit_) { return NULL; } @@ -164,12 +161,12 @@ void *PikaSender::ThreadMain() { SendCommand(key, key); cnt_++; if (cnt_ >= 200) { - for(; cnt_ > 0; cnt_--) { + for (; cnt_ > 0; cnt_--) { cli_->Recv(NULL); } } } - for(; cnt_ > 0; cnt_--) { + for (; cnt_ > 0; cnt_--) { cli_->Recv(NULL); } @@ -179,4 +176,3 @@ void *PikaSender::ThreadMain() { LOG(INFO) << "PikaSender thread complete"; return NULL; } - diff --git a/pika-tools/pika-port/pika_port_3/pika_sender.h b/pika-tools/pika-port/pika_port_3/pika_sender.h index e3fb57a9a3..e58b392af8 100644 --- a/pika-tools/pika-port/pika_port_3/pika_sender.h +++ b/pika-tools/pika-port/pika_port_3/pika_sender.h @@ -2,10 +2,10 @@ #define PIKA_SENDER_H_ #include -#include #include #include #include +#include #include "net/include/bg_thread.h" #include "net/include/net_cli.h" @@ -14,20 +14,20 @@ #include "conf.h" class PikaSender : public net::Thread { -public: + public: PikaSender(std::string ip, int64_t port, std::string password); virtual ~PikaSender(); - void LoadKey(const std::string &cmd); + void LoadKey(const std::string& cmd); void Stop(); int64_t elements() { return elements_; } - - void SendCommand(std::string &command, const std::string &key); + + void SendCommand(std::string& command, const std::string& key); int QueueSize(); void ConnectRedis(); -private: - net::PinkCli *cli_; + private: + net::PinkCli* cli_; slash::CondVar signal_; slash::Mutex keys_mutex_; std::queue keys_queue_; @@ -37,8 +37,8 @@ class PikaSender : public net::Thread { std::atomic should_exit_; int32_t cnt_; int64_t elements_; - - virtual void *ThreadMain(); + + virtual void* ThreadMain(); }; #endif diff --git a/pika-tools/pika-port/pika_port_3/redis_sender.cc b/pika-tools/pika-port/pika_port_3/redis_sender.cc index ec372689d9..812607df02 100644 --- a/pika-tools/pika-port/pika_port_3/redis_sender.cc +++ b/pika-tools/pika-port/pika_port_3/redis_sender.cc @@ -10,24 +10,21 @@ static time_t kCheckDiff = 1; -RedisSender::RedisSender(int id, std::string ip, int64_t port, std::string password): - id_(id), - cli_(NULL), - rsignal_(&commands_mutex_), - wsignal_(&commands_mutex_), - ip_(ip), - port_(port), - password_(password), - should_exit_(false), - cnt_(0), - elements_(0) { - +RedisSender::RedisSender(int id, std::string ip, int64_t port, std::string password) + : id_(id), + cli_(NULL), + rsignal_(&commands_mutex_), + wsignal_(&commands_mutex_), + ip_(ip), + port_(port), + password_(password), + should_exit_(false), + cnt_(0), + elements_(0) { last_write_time_ = ::time(NULL); } -RedisSender::~RedisSender() { - LOG(INFO) << "RedisSender thread " << id_ << " exit!!!"; -} +RedisSender::~RedisSender() { LOG(INFO) << "RedisSender thread " << id_ << " exit!!!"; } void RedisSender::ConnectRedis() { while (cli_ == NULL) { @@ -112,7 +109,7 @@ void RedisSender::Stop() { commands_mutex_.Unlock(); } -void RedisSender::SendRedisCommand(const std::string &command) { +void RedisSender::SendRedisCommand(const std::string& command) { commands_mutex_.Lock(); if (commands_queue_.size() < 100000) { commands_queue_.push(command); @@ -121,7 +118,7 @@ void RedisSender::SendRedisCommand(const std::string &command) { return; } - //LOG(WARNING) << id_ << "commands queue size is beyond 100000"; + // LOG(WARNING) << id_ << "commands queue size is beyond 100000"; while (commands_queue_.size() > 100000) { wsignal_.Wait(); } @@ -130,7 +127,7 @@ void RedisSender::SendRedisCommand(const std::string &command) { commands_mutex_.Unlock(); } -int RedisSender::SendCommand(std::string &command) { +int RedisSender::SendCommand(std::string& command) { time_t now = ::time(NULL); if (kCheckDiff < now - last_write_time_) { int ret = cli_->CheckAliveness(); @@ -155,12 +152,12 @@ int RedisSender::SendCommand(std::string &command) { LOG(INFO) << s.ToString(); cli_ = NULL; ConnectRedis(); - } while(++idx < 3); + } while (++idx < 3); return -1; } -void *RedisSender::ThreadMain() { +void* RedisSender::ThreadMain() { LOG(INFO) << "Start sender " << id_ << " thread..."; // sleep(15); int ret = 0; @@ -200,12 +197,12 @@ void *RedisSender::ThreadMain() { } if (cnt_ >= 200) { - for(; cnt_ > 0; cnt_--) { + for (; cnt_ > 0; cnt_--) { cli_->Recv(NULL); } } } - for(; cnt_ > 0; cnt_--) { + for (; cnt_ > 0; cnt_--) { cli_->Recv(NULL); } @@ -214,4 +211,3 @@ void *RedisSender::ThreadMain() { LOG(INFO) << "RedisSender thread " << id_ << " complete"; return NULL; } - diff --git a/pika-tools/pika-port/pika_port_3/redis_sender.h b/pika-tools/pika-port/pika_port_3/redis_sender.h index b1db52582a..4807eed6e6 100644 --- a/pika-tools/pika-port/pika_port_3/redis_sender.h +++ b/pika-tools/pika-port/pika_port_3/redis_sender.h @@ -2,10 +2,10 @@ #define REDIS_SENDER_H_ #include -#include #include #include #include +#include #include "net/include/bg_thread.h" #include "net/include/net_cli.h" @@ -16,19 +16,17 @@ class RedisSender : public net::Thread { RedisSender(int id, std::string ip, int64_t port, std::string password); virtual ~RedisSender(); void Stop(void); - int64_t elements() { - return elements_; - } + int64_t elements() { return elements_; } - void SendRedisCommand(const std::string &command); + void SendRedisCommand(const std::string& command); private: - int SendCommand(std::string &command); + int SendCommand(std::string& command); void ConnectRedis(); private: int id_; - net::PinkCli *cli_; + net::PinkCli* cli_; slash::CondVar rsignal_; slash::CondVar wsignal_; slash::Mutex commands_mutex_; @@ -41,7 +39,7 @@ class RedisSender : public net::Thread { int64_t elements_; std::atomic last_write_time_; - virtual void *ThreadMain(); + virtual void* ThreadMain(); }; #endif diff --git a/pika-tools/pika-port/pika_port_3/slaveping_thread.cc b/pika-tools/pika-port/pika_port_3/slaveping_thread.cc index b5076c8104..26712409ee 100644 --- a/pika-tools/pika-port/pika_port_3/slaveping_thread.cc +++ b/pika-tools/pika-port/pika_port_3/slaveping_thread.cc @@ -3,9 +3,9 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. +#include "slaveping_thread.h" #include #include -#include "slaveping_thread.h" #include "pika_port.h" extern PikaPort* g_pika_port; @@ -13,10 +13,10 @@ extern PikaPort* g_pika_port; Status SlavepingThread::Send() { std::string wbuf_str; if (!is_first_send_) { - net::SerializeRedisCommand(&wbuf_str, "ping"); // reply == pong + net::SerializeRedisCommand(&wbuf_str, "ping"); // reply == pong } else { net::RedisCmdArgsType argv; - argv.push_back("spci"); // reply == pong + argv.push_back("spci"); // reply == pong argv.push_back(std::to_string(sid_)); net::SerializeRedisCommand(argv, &wbuf_str); is_first_send_ = false; @@ -50,12 +50,12 @@ void* SlavepingThread::ThreadMain() { Status s; int connect_retry_times = 0; while (!should_stop() && g_pika_port->ShouldStartPingMaster()) { - if (!should_stop() - && (cli_->Connect(g_pika_port->master_ip(), - g_pika_port->master_port() + 2000, + if (!should_stop() && + (cli_->Connect( + g_pika_port->master_ip(), g_pika_port->master_port() + 2000, // Bug Fix By AS on 20190413 12:49pm: ping thread should bind the same network ip as trysync thread - g_conf.local_ip)).ok()) { - + g_conf.local_ip)) + .ok()) { cli_->set_send_timeout(1000); cli_->set_recv_timeout(1000); connect_retry_times = 0; @@ -78,7 +78,7 @@ void* SlavepingThread::ThreadMain() { LOG(WARNING) << "Slaveping timeout once"; gettimeofday(&now, NULL); if (now.tv_sec - last_interaction.tv_sec > 30) { - //timeout; + // timeout; LOG(INFO) << "Ping master timeout"; close(cli_->fd()); g_pika_port->binlog_receiver_thread()->KillBinlogSender(); diff --git a/pika-tools/pika-port/pika_port_3/slaveping_thread.h b/pika-tools/pika-port/pika_port_3/slaveping_thread.h index 4305169f6a..81992c1a4b 100644 --- a/pika-tools/pika-port/pika_port_3/slaveping_thread.h +++ b/pika-tools/pika-port/pika_port_3/slaveping_thread.h @@ -6,8 +6,8 @@ #ifndef SLAVEPING_THREAD_H_ #define SLAVEPING_THREAD_H_ -#include "net/include/net_thread.h" #include "net/include/net_cli.h" +#include "net/include/net_thread.h" #include "net/include/redis_cli.h" #include "slash/include/slash_mutex.h" #include "slash/include/slash_status.h" @@ -17,12 +17,11 @@ using slash::Status; class SlavepingThread : public net::Thread { -public: - SlavepingThread(int64_t sid) : sid_(sid), - is_first_send_(true) { + public: + SlavepingThread(int64_t sid) : sid_(sid), is_first_send_(true) { cli_ = net::NewRedisCli(); cli_->set_connect_timeout(1500); - }; + }; virtual ~SlavepingThread() { StopThread(); delete cli_; @@ -32,15 +31,14 @@ class SlavepingThread : public net::Thread { Status Send(); Status RecvProc(); -private: + private: int64_t sid_; bool is_first_send_; int sockfd_; - net::PinkCli *cli_; + net::PinkCli* cli_; virtual void* ThreadMain(); - }; #endif diff --git a/pika-tools/pika-port/pika_port_3/trysync_thread.cc b/pika-tools/pika-port/pika_port_3/trysync_thread.cc index bfe94cdb96..2d62bd8478 100644 --- a/pika-tools/pika-port/pika_port_3/trysync_thread.cc +++ b/pika-tools/pika-port/pika_port_3/trysync_thread.cc @@ -4,26 +4,26 @@ // of patent rights can be found in the PATENTS file in the same directory. #include "trysync_thread.h" -#include "pika_port.h" #include "conf.h" #include "const.h" +#include "pika_port.h" #include #include -#include #include #include +#include #include #include -#include +#include -#include "slash/include/slash_status.h" #include "slash/include/rsync.h" +#include "slash/include/slash_status.h" #include "slaveping_thread.h" -#include "pika_define.h" #include "blackwidow/blackwidow.h" +#include "pika_define.h" extern Conf g_conf; extern PikaPort* g_pika_port; @@ -89,8 +89,8 @@ bool TrysyncThread::Send(std::string lip) { net::SerializeRedisCommand(argv, &tbuf_str); wbuf_str.append(tbuf_str); - LOG(INFO) << "redis command: trysync " << g_conf.local_ip.c_str() << " " - << g_conf.local_port << " " << filenum << " " << pro_offset; + LOG(INFO) << "redis command: trysync " << g_conf.local_ip.c_str() << " " << g_conf.local_port << " " << filenum << " " + << pro_offset; slash::Status s; s = cli_->Send(&wbuf_str); @@ -128,8 +128,7 @@ bool TrysyncThread::RecvProc() { } is_authed = true; } else { - if (argv.size() == 1 && - slash::string2l(reply.data(), reply.size(), &sid_)) { + if (argv.size() == 1 && slash::string2l(reply.data(), reply.size(), &sid_)) { // Luckily, I got your point, the sync is comming LOG(INFO) << "Recv sid from master: " << sid_; g_pika_port->SetSid(sid_); @@ -195,26 +194,28 @@ bool TrysyncThread::TryUpdateMasterOffset() { is.close(); return false; } - if (lineno == 3) { master_port = tmp; } - else if (lineno == 4) { filenum = tmp; } - else { offset = tmp; } - } else if (lineno > 5) { + if (lineno == 3) { + master_port = tmp; + } else if (lineno == 4) { + filenum = tmp; + } else { + offset = tmp; + } + } else if (lineno > 5) { LOG(WARNING) << "Format of info file after db sync error, line: " << line; is.close(); return false; } } is.close(); - LOG(INFO) << "Information from dbsync info. master_ip: " << master_ip - << ", master_port: " << master_port - << ", filenum: " << filenum << ", offset: " << offset; + LOG(INFO) << "Information from dbsync info. master_ip: " << master_ip << ", master_port: " << master_port + << ", filenum: " << filenum << ", offset: " << offset; // Sanity check - if ( // master_ip != g_conf.master_ip || + if ( // master_ip != g_conf.master_ip || master_port != g_conf.master_port) { - LOG(WARNING) << "Error master{" << master_ip << ":" << master_port - << "} != g_config.master{" << "{" << g_conf.master_ip.c_str() - << ":" << g_conf.master_port << "}"; + LOG(WARNING) << "Error master{" << master_ip << ":" << master_port << "} != g_config.master{" + << "{" << g_conf.master_ip.c_str() << ":" << g_conf.master_port << "}"; return false; } @@ -234,13 +235,13 @@ bool TrysyncThread::TryUpdateMasterOffset() { #include #include "rocksdb/db.h" -#include "rocksdb/status.h" #include "rocksdb/slice.h" +#include "rocksdb/status.h" -#include "src/redis_strings.h" -#include "src/redis_lists.h" #include "src/redis_hashes.h" +#include "src/redis_lists.h" #include "src/redis_sets.h" +#include "src/redis_strings.h" #include "src/redis_zsets.h" using std::chrono::high_resolution_clock; @@ -271,8 +272,8 @@ int TrysyncThread::Retransmit() { options.keep_log_file_num = 10; options.max_manifest_file_size = 64 * 1024 * 1024; options.max_log_file_size = 512 * 1024 * 1024; - options.write_buffer_size = 512 * 1024 * 1024; // 512M - options.target_file_size_base = 40 * 1024 * 1024; // 40M + options.write_buffer_size = 512 * 1024 * 1024; // 512M + options.target_file_size_base = 40 * 1024 * 1024; // 40M blackwidow::BlackwidowOptions bwOptions; bwOptions.options = options; @@ -364,14 +365,14 @@ int TrysyncThread::Retransmit() { } high_resolution_clock::time_point end = high_resolution_clock::now(); - std::chrono::hours hours = std::chrono::duration_cast(end - start); - std::chrono::minutes minutes = std::chrono::duration_cast(end - start); - std::chrono::seconds seconds = std::chrono::duration_cast(end - start); + std::chrono::hours hours = std::chrono::duration_cast(end - start); + std::chrono::minutes minutes = std::chrono::duration_cast(end - start); + std::chrono::seconds seconds = std::chrono::duration_cast(end - start); LOG(INFO) << "=============== Retransmitting ====================="; LOG(INFO) << "Running time :"; - LOG(INFO) << hours.count() << " hour " << minutes.count() - hours.count() * 60 - << " min " << seconds.count() - hours.count() * 60 * 60 << " s"; + LOG(INFO) << hours.count() << " hour " << minutes.count() - hours.count() * 60 << " min " + << seconds.count() - hours.count() * 60 * 60 << " s"; LOG(INFO) << "Total records : " << records << " have been Scaned"; LOG(INFO) << "Total replies : " << replies << " received from redis server"; // delete db @@ -389,7 +390,7 @@ void* TrysyncThread::ThreadMain() { if (wait_start == 0) { wait_start = cur_time; } - //Try to update offset by db sync + // Try to update offset by db sync if (TryUpdateMasterOffset()) { LOG(INFO) << "Success Update Master Offset"; } else { @@ -414,7 +415,8 @@ void* TrysyncThread::ThreadMain() { PrepareRsync(); Status connectStatus = cli_->Connect(master_ip, master_port, g_conf.local_ip); if (!connectStatus.ok()) { - LOG(WARNING) << "Failed to connect to master " << master_ip << ":" << master_port << ", status: " << connectStatus.ToString(); + LOG(WARNING) << "Failed to connect to master " << master_ip << ":" << master_port + << ", status: " << connectStatus.ToString(); continue; } LOG(INFO) << "Connect to master " << master_ip << ":" << master_port; @@ -426,7 +428,7 @@ void* TrysyncThread::ThreadMain() { // the pika master module name rule is: document_${slave_ip}:master_port // // document_${slave_ip}:master_port - //std::string ip_port = slash::IpPortString(lip, master_port); + // std::string ip_port = slash::IpPortString(lip, master_port); // pika 3.0.0-3.0.15 uses document_${master_ip}:${master_port} // document_${master_ip}:${master_port} @@ -438,13 +440,12 @@ void* TrysyncThread::ThreadMain() { if (0 != ret) { LOG(WARNING) << "Failed to start rsync, path: " << dbsync_path << ", error: " << ret; } - LOG(INFO) << "Finish to start rsync, path: " << dbsync_path - << ", local address: " << lip << ":" << rsync_port; + LOG(INFO) << "Finish to start rsync, path: " << dbsync_path << ", local address: " << lip << ":" << rsync_port; // Make sure the listening addr of rsyncd is accessible, to avoid the corner case // that "rsync --daemon" process has started but can not bind its port which is // used by other process. - net::PinkCli *rsync = net::NewRedisCli(); + net::PinkCli* rsync = net::NewRedisCli(); int retry_times; for (retry_times = 0; retry_times < 5; retry_times++) { if (rsync->Connect(lip, rsync_port, "").ok()) { diff --git a/pika-tools/pika-port/pika_port_3/trysync_thread.h b/pika-tools/pika-port/pika_port_3/trysync_thread.h index 6405d952d5..bff556c70f 100644 --- a/pika-tools/pika-port/pika_port_3/trysync_thread.h +++ b/pika-tools/pika-port/pika_port_3/trysync_thread.h @@ -8,22 +8,22 @@ #include +#include "net/include/net_cli.h" #include "net/include/net_thread.h" #include "net/include/redis_cli.h" -#include "net/include/net_cli.h" -#include "pika_sender.h" #include "migrator_thread.h" +#include "pika_sender.h" class TrysyncThread : public net::Thread { public: TrysyncThread() { cli_ = net::NewRedisCli(); cli_->set_connect_timeout(1500); - set_thread_name("TrysyncThread"); + set_thread_name("TrysyncThread"); retransmit_flag_ = false; - senders_.resize(0); - migrators_.resize(0); + senders_.resize(0); + migrators_.resize(0); }; virtual ~TrysyncThread(); @@ -34,21 +34,20 @@ class TrysyncThread : public net::Thread { bool RecvProc(); void PrepareRsync(); bool TryUpdateMasterOffset(); - int Retransmit(); + int Retransmit(); virtual void* ThreadMain(); private: long sid_; int sockfd_; - net::PinkCli *cli_; + net::PinkCli* cli_; slash::Mutex retransmit_mutex_; bool retransmit_flag_; - std::vector senders_; - std::vector migrators_; + std::vector senders_; + std::vector migrators_; }; #endif - diff --git a/pika-tools/pika_to_txt/pika_to_txt.cc b/pika-tools/pika_to_txt/pika_to_txt.cc index f1bd24b46e..ef21635e1c 100644 --- a/pika-tools/pika_to_txt/pika_to_txt.cc +++ b/pika-tools/pika_to_txt/pika_to_txt.cc @@ -3,15 +3,15 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include "iostream" #include "chrono" +#include "iostream" #include "unistd.h" #include "blackwidow/blackwidow.h" +#include "progress_thread.h" #include "scan_thread.h" #include "write_thread.h" -#include "progress_thread.h" int32_t scan_batch_limit = 256; std::string blackwidow_db_path; @@ -36,9 +36,8 @@ void Usage() { std::cout << "\texample: ./pika_to_txt ./blackwidow_db ./data.txt" << std::endl; } -int main(int argc, char **argv) { - if (argc != 3 - && argc != 5) { +int main(int argc, char** argv) { + if (argc != 3 && argc != 5) { Usage(); exit(-1); } @@ -66,8 +65,7 @@ int main(int argc, char **argv) { bw_option.options.write_buffer_size = 256 * 1024 * 1024; // 256M bw_option.options.target_file_size_base = 20 * 1024 * 1024; // 20M blackwidow::BlackWidow* blackwidow_db = new blackwidow::BlackWidow(); - if (blackwidow_db != NULL - && (status = blackwidow_db->Open(bw_option, blackwidow_db_path)).ok()) { + if (blackwidow_db != NULL && (status = blackwidow_db->Open(bw_option, blackwidow_db_path)).ok()) { std::cout << "Open BlackWidow db success..." << std::endl; } else { std::cout << "Open BlackWidow db failed..." << std::endl; @@ -104,12 +102,8 @@ int main(int argc, char **argv) { auto minutes = std::chrono::duration_cast(end_time - start_time).count(); auto seconds = std::chrono::duration_cast(end_time - start_time).count(); - std::cout << "Total Time Cost : " - << hours << " hours " - << minutes % 60 << " minutes " - << seconds % 60 << " seconds " + std::cout << "Total Time Cost : " << hours << " hours " << minutes % 60 << " minutes " << seconds % 60 << " seconds " << std::endl; - return 0; + return 0; } - diff --git a/pika-tools/pika_to_txt/progress_thread.cc b/pika-tools/pika_to_txt/progress_thread.cc index f552523e34..20cd303f09 100644 --- a/pika-tools/pika_to_txt/progress_thread.cc +++ b/pika-tools/pika_to_txt/progress_thread.cc @@ -5,9 +5,7 @@ #include "progress_thread.h" -ProgressThread::ProgressThread(ScanThread* scan_thread) - : scan_thread_(scan_thread) { -} +ProgressThread::ProgressThread(ScanThread* scan_thread) : scan_thread_(scan_thread) {} void* ProgressThread::ThreadMain() { while (true) { @@ -21,4 +19,3 @@ void* ProgressThread::ThreadMain() { printf("\nScan strings finished\n"); return NULL; } - diff --git a/pika-tools/pika_to_txt/progress_thread.h b/pika-tools/pika_to_txt/progress_thread.h index 43433b396e..b8ce905ff3 100644 --- a/pika-tools/pika_to_txt/progress_thread.h +++ b/pika-tools/pika_to_txt/progress_thread.h @@ -16,9 +16,10 @@ class ProgressThread : public net::Thread { public: ProgressThread(ScanThread* scan_thread); + private: bool AllClassifyTreadFinish(); - virtual void *ThreadMain(); + virtual void* ThreadMain(); ScanThread* scan_thread_; }; diff --git a/pika-tools/pika_to_txt/scan_thread.cc b/pika-tools/pika_to_txt/scan_thread.cc index 89255a3a15..690e70cb8e 100644 --- a/pika-tools/pika_to_txt/scan_thread.cc +++ b/pika-tools/pika_to_txt/scan_thread.cc @@ -7,13 +7,9 @@ extern int32_t scan_batch_limit; -bool ScanThread::is_finish() { - return is_finish_; -} +bool ScanThread::is_finish() { return is_finish_; } -int32_t ScanThread::scan_number() { - return scan_number_; -} +int32_t ScanThread::scan_number() { return scan_number_; } void* ScanThread::ThreadMain() { std::string key_start = ""; @@ -24,8 +20,8 @@ void* ScanThread::ThreadMain() { std::vector kvs; do { - blackwidow_db_->PKScanRange(blackwidow::DataType::kStrings, key_start, key_end, - "*", scan_batch_limit, &keys, &kvs, &next_key); + blackwidow_db_->PKScanRange(blackwidow::DataType::kStrings, key_start, key_end, "*", scan_batch_limit, &keys, &kvs, + &next_key); if (!kvs.empty()) { scan_number_ += kvs.size(); std::string data; @@ -43,4 +39,3 @@ void* ScanThread::ThreadMain() { is_finish_ = true; return NULL; } - diff --git a/pika-tools/pika_to_txt/scan_thread.h b/pika-tools/pika_to_txt/scan_thread.h index dd4911ab56..5c8f676fff 100644 --- a/pika-tools/pika_to_txt/scan_thread.h +++ b/pika-tools/pika_to_txt/scan_thread.h @@ -9,23 +9,21 @@ #include "iostream" #include "vector" -#include "slash/include/slash_coding.h" -#include "net/include/net_thread.h" #include "blackwidow/blackwidow.h" +#include "net/include/net_thread.h" +#include "slash/include/slash_coding.h" #include "write_thread.h" class ScanThread : public net::Thread { public: - ScanThread(WriteThread* write_thread, blackwidow::BlackWidow* blackwidow_db) : - is_finish_(false), - scan_number_(0), - write_thread_(write_thread), - blackwidow_db_(blackwidow_db) {} + ScanThread(WriteThread* write_thread, blackwidow::BlackWidow* blackwidow_db) + : is_finish_(false), scan_number_(0), write_thread_(write_thread), blackwidow_db_(blackwidow_db) {} bool is_finish(); int32_t scan_number(); + private: - void *ThreadMain() override; + void* ThreadMain() override; bool is_finish_; int32_t scan_number_; WriteThread* write_thread_; diff --git a/pika-tools/pika_to_txt/write_thread.cc b/pika-tools/pika_to_txt/write_thread.cc index 60fd359358..5fcf45deb8 100644 --- a/pika-tools/pika_to_txt/write_thread.cc +++ b/pika-tools/pika_to_txt/write_thread.cc @@ -3,18 +3,15 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include "iostream" +#include "write_thread.h" #include "fstream" +#include "iostream" #include "string" -#include "write_thread.h" #define MAX_QUEUE_SIZE 1024 WriteThread::WriteThread(const std::string& file_name) - : should_stop_(false), - file_name_(file_name), - rsignal_(&data_queue_mutex_), - wsignal_(&data_queue_mutex_) {} + : should_stop_(false), file_name_(file_name), rsignal_(&data_queue_mutex_), wsignal_(&data_queue_mutex_) {} void WriteThread::Load(const std::string& data) { data_queue_mutex_.Lock(); diff --git a/pika-tools/pika_to_txt/write_thread.h b/pika-tools/pika_to_txt/write_thread.h index 9710ad8725..84cda71889 100644 --- a/pika-tools/pika_to_txt/write_thread.h +++ b/pika-tools/pika_to_txt/write_thread.h @@ -16,8 +16,9 @@ class WriteThread : public net::Thread { WriteThread(const std::string& file_name); void Load(const std::string& data); void Stop(); + private: - void *ThreadMain() override; + void* ThreadMain() override; bool should_stop_; std::string file_name_; slash::CondVar rsignal_; @@ -26,4 +27,4 @@ class WriteThread : public net::Thread { std::queue data_queue_; }; -#endif // INCLUDE_WRITE_THREAD_H_ +#endif // INCLUDE_WRITE_THREAD_H_ diff --git a/pika-tools/rdb_to_pika/protocoltopika.cc b/pika-tools/rdb_to_pika/protocoltopika.cc index b74e95672f..955a133f4a 100644 --- a/pika-tools/rdb_to_pika/protocoltopika.cc +++ b/pika-tools/rdb_to_pika/protocoltopika.cc @@ -1,9 +1,9 @@ -#include"hiredis.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include "hiredis.h" void Usage() { std::cout << "Usage:" << std::endl; @@ -12,7 +12,8 @@ void Usage() { std::cout << " --i pika ip address" << std::endl; std::cout << " --p pika port" << std::endl; std::cout << " [--a] password for pika db; default = NULL" << std::endl; - std::cout << "example " << "./redisConn protocol_file 127.0.0.1 9221 password" << std::endl; + std::cout << "example " + << "./redisConn protocol_file 127.0.0.1 9221 password" << std::endl; } int main(int argc, char** argv) { if (argc < 4) { @@ -20,41 +21,39 @@ int main(int argc, char** argv) { return -1; } const char* filename = argv[1]; - const char* ip = argv[2]; + const char* ip = argv[2]; std::ifstream fin(filename, std::ios::in); std::string strport(argv[3]); std::stringstream ss; ss << strport; int port; ss >> port; - redisContext *c = redisConnect(ip, port); - redisReply *reply; + redisContext* c = redisConnect(ip, port); + redisReply* reply; if (!c || c->err) { if (c) { redisFree(c); std::cout << "connection error" << std::endl; - return -1; - } - else { + return -1; + } else { std::cout << "conneciont error : can't allocate redis context." << std::endl; return -1; } } std::cout << "connection successful" << std::endl; - redisReply *r; + redisReply* r; if (argc == 5) { const char* password = argv[4]; r = (redisReply*)redisCommand(c, "AUTH %s", password); if (r->type == REDIS_REPLY_ERROR) { - std::cout << "authentication failed " << std::endl; + std::cout << "authentication failed " << std::endl; freeReplyObject(r); redisFree(c); - return -1; - } - else { - std::cout << "authentication success " << std::endl; + return -1; + } else { + std::cout << "authentication success " << std::endl; freeReplyObject(r); - } + } } char line[1000000]; while (fin.getline(line, sizeof(line))) { @@ -63,19 +62,19 @@ int main(int argc, char** argv) { for (int i = 1; i <= k; i++) { fin.getline(line, sizeof(line)); fin.getline(line, sizeof(line), '\r'); - //std::string tmp(line); + // std::string tmp(line); command.append(line); - command.append(" "); + command.append(" "); fin.getline(line, sizeof(line)); } - //std::cout << command << std::endl; + // std::cout << command << std::endl; r = (redisReply*)redisCommand(c, command.c_str()); if (r) { freeReplyObject(r); } } - std::cout << "transport finished" << std::endl; + std::cout << "transport finished" << std::endl; redisFree(c); - fin.close(); + fin.close(); return 0; } diff --git a/pika-tools/txt_to_pika/scan.cc b/pika-tools/txt_to_pika/scan.cc index aada51527e..a8a8b9fab4 100644 --- a/pika-tools/txt_to_pika/scan.cc +++ b/pika-tools/txt_to_pika/scan.cc @@ -1,30 +1,29 @@ -#include -#include #include "scan.h" +#include +#include -ScanThread::~ScanThread() { -} +ScanThread::~ScanThread() {} void ScanThread::ScanFile() { log_info("Start to scan"); std::ifstream fout(filename_, std::ios::binary); fout.seekg(0, std::ios::end); - uint64_t filesize = fout.tellg(); + uint64_t filesize = fout.tellg(); fout.seekg(0, std::ios::beg); uint64_t index = 0; while (index < filesize) { std::string str_key, str_value, cmd; uint32_t key_len; - fout.read(reinterpret_cast(&key_len), sizeof(uint32_t)); - char * key = new char[key_len]; + fout.read(reinterpret_cast(&key_len), sizeof(uint32_t)); + char* key = new char[key_len]; fout.read(key, key_len); str_key.append(key, key_len); uint32_t value_len; - fout.read(reinterpret_cast(&value_len), sizeof(uint32_t)); - char * value = new char[value_len]; + fout.read(reinterpret_cast(&value_len), sizeof(uint32_t)); + char* value = new char[value_len]; fout.read(value, value_len); str_value.append(value, value_len); @@ -39,26 +38,26 @@ void ScanThread::ScanFile() { argv.push_back(str_key); argv.push_back(str_value); } - + net::SerializeRedisCommand(argv, &cmd); - + DispatchCmd(cmd); num_++; - delete []key; - delete []value; - + delete[] key; + delete[] value; + index += key_len + value_len + sizeof(uint32_t) * 2; } fout.close(); } -void ScanThread::DispatchCmd(const std::string &cmd) { +void ScanThread::DispatchCmd(const std::string& cmd) { senders_[thread_index_]->LoadCmd(cmd); thread_index_ = (thread_index_ + 1) % senders_.size(); } -void *ScanThread::ThreadMain() { +void* ScanThread::ThreadMain() { ScanFile(); log_info("Scan file complete"); return NULL; diff --git a/pika-tools/txt_to_pika/scan.h b/pika-tools/txt_to_pika/scan.h index a7b2adb138..fa99584761 100644 --- a/pika-tools/txt_to_pika/scan.h +++ b/pika-tools/txt_to_pika/scan.h @@ -3,37 +3,29 @@ #include -#include "sender.h" #include "net/include/bg_thread.h" +#include "sender.h" #include class ScanThread : public net::Thread { - public: - ScanThread(std::string filename, std::vector senders, int ttl) : - filename_(filename), - num_(0), - senders_(senders), - thread_index_(0), - ttl_(ttl) - { - } - - virtual ~ScanThread(); - int Num() { - return num_; - } - void DispatchCmd(const std::string &cmd); - private: - void ScanFile(); - std::string filename_; - int num_; - std::vector senders_; - int thread_index_; - int ttl_; - - void* ThreadMain(); + public: + ScanThread(std::string filename, std::vector senders, int ttl) + : filename_(filename), num_(0), senders_(senders), thread_index_(0), ttl_(ttl) {} + + virtual ~ScanThread(); + int Num() { return num_; } + void DispatchCmd(const std::string& cmd); + + private: + void ScanFile(); + std::string filename_; + int num_; + std::vector senders_; + int thread_index_; + int ttl_; + + void* ThreadMain(); }; #endif - diff --git a/pika-tools/txt_to_pika/sender.cc b/pika-tools/txt_to_pika/sender.cc index 44db5b52fc..ad699a1a72 100644 --- a/pika-tools/txt_to_pika/sender.cc +++ b/pika-tools/txt_to_pika/sender.cc @@ -1,19 +1,16 @@ #include "sender.h" -SenderThread::SenderThread(std::string ip, int64_t port, std::string password): - cli_(NULL), - rsignal_(&cmd_mutex_), - wsignal_(&cmd_mutex_), - ip_(ip), - port_(port), - password_(password), - should_exit_(false), - elements_(0) - { - } +SenderThread::SenderThread(std::string ip, int64_t port, std::string password) + : cli_(NULL), + rsignal_(&cmd_mutex_), + wsignal_(&cmd_mutex_), + ip_(ip), + port_(port), + password_(password), + should_exit_(false), + elements_(0) {} -SenderThread::~SenderThread() { -} +SenderThread::~SenderThread() {} void SenderThread::ConnectPika() { while (cli_ == NULL) { @@ -86,7 +83,7 @@ void SenderThread::ConnectPika() { } } -void SenderThread::LoadCmd(const std::string &cmd) { +void SenderThread::LoadCmd(const std::string& cmd) { cmd_mutex_.Lock(); if (cmd_queue_.size() < 100000) { cmd_queue_.push(cmd); @@ -102,7 +99,7 @@ void SenderThread::LoadCmd(const std::string &cmd) { } } -void SenderThread::SendCommand(std::string &command) { +void SenderThread::SendCommand(std::string& command) { // Send command slash::Status s = cli_->Send(&command); if (!s.ok()) { @@ -115,12 +112,12 @@ void SenderThread::SendCommand(std::string &command) { } else { net::RedisCmdArgsType resp; s = cli_->Recv(&resp); - //std::cout << resp[0] << std::endl; - elements_++; + // std::cout << resp[0] << std::endl; + elements_++; } } -void *SenderThread::ThreadMain() { +void* SenderThread::ThreadMain() { log_info("Start sender thread..."); while (!should_exit_ || QueueSize() != 0) { @@ -131,7 +128,7 @@ void *SenderThread::ThreadMain() { cmd_mutex_.Unlock(); if (cli_ == NULL) { - ConnectPika(); + ConnectPika(); continue; } if (QueueSize() != 0) { @@ -148,4 +145,3 @@ void *SenderThread::ThreadMain() { log_info("Sender thread complete"); return NULL; } - diff --git a/pika-tools/txt_to_pika/sender.h b/pika-tools/txt_to_pika/sender.h index 3511c96cbb..66d670d41d 100644 --- a/pika-tools/txt_to_pika/sender.h +++ b/pika-tools/txt_to_pika/sender.h @@ -1,52 +1,50 @@ #ifndef SENDER_H_ #define SENDER_H_ -#include #include #include #include -#include "slash/include/xdebug.h" +#include #include "net/include/bg_thread.h" #include "net/include/net_cli.h" #include "net/include/redis_cli.h" +#include "slash/include/xdebug.h" class SenderThread : public net::Thread { -public: - SenderThread(std::string ip, int64_t port, std::string password); - virtual ~SenderThread(); - void LoadCmd(const std::string &cmd); - void Stop() { - should_exit_ = true; - cmd_mutex_.Lock(); - rsignal_.Signal(); + public: + SenderThread(std::string ip, int64_t port, std::string password); + virtual ~SenderThread(); + void LoadCmd(const std::string& cmd); + void Stop() { + should_exit_ = true; + cmd_mutex_.Lock(); + rsignal_.Signal(); cmd_mutex_.Unlock(); - } - int64_t elements() { - return elements_; } + int64_t elements() { return elements_; } + + void SendCommand(std::string& command); - void SendCommand(std::string &command); - int QueueSize() { - slash::MutexLock l(&cmd_mutex_); - int len = cmd_queue_.size(); - return len; + slash::MutexLock l(&cmd_mutex_); + int len = cmd_queue_.size(); + return len; } - void ConnectPika(); -private: - net::PinkCli *cli_; - slash::CondVar rsignal_; - slash::CondVar wsignal_; - slash::Mutex cmd_mutex_; - std::queue cmd_queue_; - std::string ip_; - int port_; - std::string password_; + void ConnectPika(); + + private: + net::PinkCli* cli_; + slash::CondVar rsignal_; + slash::CondVar wsignal_; + slash::Mutex cmd_mutex_; + std::queue cmd_queue_; + std::string ip_; + int port_; + std::string password_; bool should_exit_; int64_t elements_; - virtual void *ThreadMain(); + virtual void* ThreadMain(); }; #endif - diff --git a/pika-tools/txt_to_pika/txt_to_pika.cc b/pika-tools/txt_to_pika/txt_to_pika.cc index ba201133ab..a4ee1d84b4 100644 --- a/pika-tools/txt_to_pika/txt_to_pika.cc +++ b/pika-tools/txt_to_pika/txt_to_pika.cc @@ -1,5 +1,5 @@ -#include #include +#include #include "scan.h" #include "sender.h" @@ -11,7 +11,7 @@ void Usage() { std::cout << " example: ./txt_to_pika data.txt 127.0.0.1 9921 -n 10 -t 10 -p 123456" << std::endl; } -int main(int argc, char **argv) { +int main(int argc, char** argv) { if (argc < 4) { Usage(); return 0; @@ -25,28 +25,28 @@ int main(int argc, char **argv) { std::string ip = std::string(argv[2]); int port = std::stoi(std::string(argv[3])); int ttl = -1; - std::vector senders; + std::vector senders; int index = 4; if (argc > 4) { - while (index < (argc -1)) { + while (index < (argc - 1)) { int flag = index++; if (std::string(argv[flag]) == "-n") { thread_num = std::stoi(std::string(argv[index++])); if (index > (argc - 1)) { - break; + break; } } if (std::string(argv[flag]) == "-t") { ttl = std::stoi(std::string(argv[index++])); if (index > (argc - 1)) { - break; + break; } } if (std::string(argv[flag]) == "-p") { password = std::string(argv[index++]); if (index > (argc - 1)) { - break; + break; } } } @@ -66,43 +66,43 @@ int main(int argc, char **argv) { ScanThread* scan_thread = new ScanThread(filename, senders, ttl); for (int i = 0; i < thread_num; i++) { - senders[i]->StartThread(); + senders[i]->StartThread(); } scan_thread->StartThread(); scan_thread->JoinThread(); for (int i = 0; i < thread_num; i++) { - senders[i]->Stop(); + senders[i]->Stop(); } for (int i = 0; i < thread_num; i++) { senders[i]->JoinThread(); } - int records = 0; for (int i = 0; i < thread_num; i++) { records += senders[i]->elements(); } for (int i = 0; i < thread_num; i++) { - delete senders[i]; + delete senders[i]; } - - std::cout << std::endl << "Total " << scan_thread->Num() << " records has been scaned"<< std::endl; - std::cout <<"Total " << records << " records hash been executed by pika" << std::endl; + + std::cout << std::endl << "Total " << scan_thread->Num() << " records has been scaned" << std::endl; + std::cout << "Total " << records << " records hash been executed by pika" << std::endl; delete scan_thread; - + high_resolution_clock::time_point end = high_resolution_clock::now(); - std::chrono::hours h = std::chrono::duration_cast(end - start); - std::chrono::minutes m = std::chrono::duration_cast(end - start); - std::chrono::seconds s = std::chrono::duration_cast(end - start); + std::chrono::hours h = std::chrono::duration_cast(end - start); + std::chrono::minutes m = std::chrono::duration_cast(end - start); + std::chrono::seconds s = std::chrono::duration_cast(end - start); std::cout << "====================================" << std::endl; std::cout << "Running time :"; - std::cout << h.count() << " hour " << m.count() - h.count() * 60 << " min " << s.count() - h.count() * 60 * 60 << " s\n" << std::endl; - return 0; + std::cout << h.count() << " hour " << m.count() - h.count() * 60 << " min " << s.count() - h.count() * 60 * 60 + << " s\n" + << std::endl; + return 0; } - diff --git a/src/net/examples/bg_thread.cc b/src/net/examples/bg_thread.cc index 7fb1cf4dc2..6ff911b391 100644 --- a/src/net/examples/bg_thread.cc +++ b/src/net/examples/bg_thread.cc @@ -3,20 +3,20 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include "unistd.h" -#include -#include #include "net/include/bg_thread.h" +#include +#include #include "pstd/include/pstd_mutex.h" +#include "unistd.h" using namespace std; static pstd::Mutex print_lock; -void task(void *arg) { +void task(void* arg) { { - pstd::MutexLock l(&print_lock); - std::cout << " task : " << *((int *)arg) << std::endl; + pstd::MutexLock l(&print_lock); + std::cout << " task : " << *((int*)arg) << std::endl; } sleep(1); delete (int*)arg; @@ -24,15 +24,11 @@ void task(void *arg) { struct TimerItem { uint64_t exec_time; - void (*function)(void *); + void (*function)(void*); void* arg; - TimerItem(uint64_t _exec_time, void (*_function)(void*), void* _arg) : - exec_time(_exec_time), - function(_function), - arg(_arg) {} - bool operator < (const TimerItem& item) const { - return exec_time > item.exec_time; - } + TimerItem(uint64_t _exec_time, void (*_function)(void*), void* _arg) + : exec_time(_exec_time), function(_function), arg(_arg) {} + bool operator<(const TimerItem& item) const { return exec_time > item.exec_time; } }; int main() { @@ -43,7 +39,7 @@ int main() { std::cout << "Normal BGTask... " << std::endl; for (int i = 0; i < 10; i++) { - int *pi = new int(i); + int* pi = new int(i); t.Schedule(task, (void*)pi); t.QueueSize(&pqsize, &qsize); pstd::MutexLock l(&print_lock); @@ -56,11 +52,10 @@ int main() { sleep(1); } - qsize = pqsize = 0; std::cout << "Limit queue BGTask... " << std::endl; for (int i = 0; i < 10; i++) { - int *pi = new int(i); + int* pi = new int(i); t2.Schedule(task, (void*)pi); t2.QueueSize(&pqsize, &qsize); pstd::MutexLock l(&print_lock); @@ -72,7 +67,7 @@ int main() { t2.QueueSize(&pqsize, &qsize); sleep(1); } - + std::cout << "TimerItem Struct... " << std::endl; std::priority_queue pq; pq.push(TimerItem(1, task, NULL)); @@ -92,7 +87,7 @@ int main() { t.StartThread(); std::cout << "Time BGTask... " << std::endl; for (int i = 0; i < 10; i++) { - int *pi = new int(i); + int* pi = new int(i); t.DelaySchedule(i * 1000, task, (void*)pi); t.QueueSize(&pqsize, &qsize); pstd::MutexLock l(&print_lock); diff --git a/src/net/examples/binlog_parser_test.cc b/src/net/examples/binlog_parser_test.cc index 03bc4610e4..83594eb9fa 100644 --- a/src/net/examples/binlog_parser_test.cc +++ b/src/net/examples/binlog_parser_test.cc @@ -1,42 +1,41 @@ -#include #include -#include "pstd/include/xdebug.h" +#include #include "net/include/net_cli.h" #include "net/include/redis_cli.h" #include "pstd/include/pstd_coding.h" +#include "pstd/include/xdebug.h" using namespace net; - int main(int argc, char* argv[]) { if (argc < 3) { - printf ("Usage: ./redis_cli ip port\n"); + printf("Usage: ./redis_cli ip port\n"); exit(0); } std::string ip(argv[1]); int port = atoi(argv[2]); - NetCli *rcli = NewRedisCli(); + NetCli* rcli = NewRedisCli(); rcli->set_connect_timeout(3000); Status s = rcli->Connect(ip, port, "127.0.0.1"); printf(" RedisCli Connect(%s:%d) return %s\n", ip.c_str(), port, s.ToString().c_str()); if (!s.ok()) { - printf ("Connect failed, %s\n", s.ToString().c_str()); - exit(-1); + printf("Connect failed, %s\n", s.ToString().c_str()); + exit(-1); } net::RedisCmdArgsType redis_argv; std::string one_command = "*3\r\n$3\r\nSET\r\n$1\r\na\r\n$2\r\nab\r\n"; std::string binlog_body; - pstd::PutFixed16(&binlog_body, 1); // type - pstd::PutFixed32(&binlog_body, 0); //exec_time - pstd::PutFixed32(&binlog_body, 10); // server_id - pstd::PutFixed64(&binlog_body, 0); // logic_id - pstd::PutFixed32(&binlog_body, 0); // filenum - pstd::PutFixed64(&binlog_body, 0); // offset + pstd::PutFixed16(&binlog_body, 1); // type + pstd::PutFixed32(&binlog_body, 0); // exec_time + pstd::PutFixed32(&binlog_body, 10); // server_id + pstd::PutFixed64(&binlog_body, 0); // logic_id + pstd::PutFixed32(&binlog_body, 0); // filenum + pstd::PutFixed64(&binlog_body, 0); // offset uint32_t content_length = one_command.size(); pstd::PutFixed32(&binlog_body, content_length); binlog_body.append(one_command); @@ -47,22 +46,22 @@ int main(int argc, char* argv[]) { std::string command = header + binlog_body; { - for (size_t i = 0; i < command.size(); ++i) { - sleep(1); - std::string one_char_str(command, i, 1); - s = rcli->Send(&one_char_str); - printf("Send %d %s\n", i, s.ToString().c_str()); - } + for (size_t i = 0; i < command.size(); ++i) { + sleep(1); + std::string one_char_str(command, i, 1); + s = rcli->Send(&one_char_str); + printf("Send %d %s\n", i, s.ToString().c_str()); + } - s = rcli->Recv(&redis_argv); - printf("Recv return %s\n", s.ToString().c_str()); - if (redis_argv.size() > 0) { - printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); - } + s = rcli->Recv(&redis_argv); + printf("Recv return %s\n", s.ToString().c_str()); + if (redis_argv.size() > 0) { + printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); + } } char ch; - scanf ("%c", &ch); + scanf("%c", &ch); return 0; } diff --git a/src/net/examples/http_server.cc b/src/net/examples/http_server.cc index bdb5918d70..fae2ac1fee 100644 --- a/src/net/examples/http_server.cc +++ b/src/net/examples/http_server.cc @@ -3,16 +3,16 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include -#include -#include #include +#include +#include +#include -#include "pstd/include/pstd_status.h" -#include "pstd/include/pstd_hash.h" +#include "net/include/http_conn.h" #include "net/include/net_thread.h" #include "net/include/server_thread.h" -#include "net/include/http_conn.h" +#include "pstd/include/pstd_hash.h" +#include "pstd/include/pstd_status.h" using namespace net; @@ -62,13 +62,10 @@ class MyHTTPHandles : public net::HTTPHandles { class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, - Thread* thread, - void* worker_specific_data, - NetEpoll* net_epoll) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_specific_data, NetEpoll* net_epoll) const { auto my_handles = std::make_shared(); - return std::make_shared(connfd, ip_port, thread, my_handles, - worker_specific_data); + return std::make_shared(connfd, ip_port, thread, my_handles, worker_specific_data); } }; @@ -99,7 +96,7 @@ int main(int argc, char* argv[]) { SignalSetup(); ConnFactory* my_conn_factory = new MyConnFactory(); - ServerThread *st = NewDispatchThread(port, 4, my_conn_factory, 1000); + ServerThread* st = NewDispatchThread(port, 4, my_conn_factory, 1000); if (st->StartThread() != 0) { printf("StartThread error happened!\n"); diff --git a/src/net/examples/https_server.cc b/src/net/examples/https_server.cc index 23be2b8271..1d1709312b 100644 --- a/src/net/examples/https_server.cc +++ b/src/net/examples/https_server.cc @@ -3,16 +3,16 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include -#include -#include #include +#include +#include +#include -#include "pstd/include/pstd_status.h" -#include "pstd/include/pstd_hash.h" +#include "net/include/http_conn.h" #include "net/include/net_thread.h" #include "net/include/server_thread.h" -#include "net/include/http_conn.h" +#include "pstd/include/pstd_hash.h" +#include "pstd/include/pstd_status.h" using namespace net; @@ -62,12 +62,10 @@ class MyHTTPHandles : public net::HTTPHandles { class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, - ServerThread* thread, - void* worker_specific_data) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, ServerThread* thread, + void* worker_specific_data) const { auto my_handles = std::make_shared(); - return make_shared(connfd, ip_port, thread, my_handles, - worker_specific_data); + return make_shared(connfd, ip_port, thread, my_handles, worker_specific_data); } }; @@ -98,10 +96,9 @@ int main(int argc, char* argv[]) { SignalSetup(); ConnFactory* my_conn_factory = new MyConnFactory(); - ServerThread *st = NewDispatchThread(port, 4, my_conn_factory, 1000); + ServerThread* st = NewDispatchThread(port, 4, my_conn_factory, 1000); - if (st->EnableSecurity("/complete_path_to/host.crt", - "/complete_path_to/host.key") != 0) { + if (st->EnableSecurity("/complete_path_to/host.crt", "/complete_path_to/host.key") != 0) { printf("EnableSecurity error happened!\n"); exit(-1); } diff --git a/src/net/examples/mydispatch_srv.cc b/src/net/examples/mydispatch_srv.cc index 50ec098c00..697029d291 100644 --- a/src/net/examples/mydispatch_srv.cc +++ b/src/net/examples/mydispatch_srv.cc @@ -1,26 +1,26 @@ -#include #include +#include #include #include -#include "pstd/include/xdebug.h" #include "net/include/net_thread.h" #include "net/include/server_thread.h" +#include "pstd/include/xdebug.h" #include "myproto.pb.h" #include "net/include/pb_conn.h" -#include #include #include +#include using namespace net; -class MyConn: public PbConn { +class MyConn : public PbConn { public: - MyConn(int fd, const std::string& ip_port, Thread *thread, - void* worker_specific_data); + MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data); virtual ~MyConn(); + protected: virtual int DealMessage(); @@ -29,14 +29,12 @@ class MyConn: public PbConn { myproto::PingRes ping_res_; }; -MyConn::MyConn(int fd, const std::string& ip_port, Thread *thread, - void* worker_specific_data) +MyConn::MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data) : PbConn(fd, ip_port, thread) { // Handle worker_specific_data ... } -MyConn::~MyConn() { -} +MyConn::~MyConn() {} int MyConn::DealMessage() { printf("In the myconn DealMessage branch\n"); @@ -44,7 +42,7 @@ int MyConn::DealMessage() { ping_res_.Clear(); ping_res_.set_res(11234); ping_res_.set_mess("heiheidfdfdf"); - printf ("DealMessage receive (%s)\n", ping_res_.mess().c_str()); + printf("DealMessage receive (%s)\n", ping_res_.mess().c_str()); std::string res; ping_res_.SerializeToString(&res); WriteResp(res); @@ -53,10 +51,8 @@ int MyConn::DealMessage() { class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string &ip_port, - Thread *thread, - void* worker_specific_data, - NetEpoll* net_epoll) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_specific_data, NetEpoll* net_epoll) const { return std::make_shared(connfd, ip_port, thread, worker_specific_data); } }; @@ -79,8 +75,8 @@ static void SignalSetup() { int main() { SignalSetup(); - ConnFactory *my_conn_factory = new MyConnFactory(); - ServerThread *st = NewDispatchThread(9211, 10, my_conn_factory, 1000); + ConnFactory* my_conn_factory = new MyConnFactory(); + ServerThread* st = NewDispatchThread(9211, 10, my_conn_factory, 1000); if (st->StartThread() != 0) { printf("StartThread error happened!\n"); diff --git a/src/net/examples/myholy_srv.cc b/src/net/examples/myholy_srv.cc index 0ff5b6d230..dcdee5aaef 100644 --- a/src/net/examples/myholy_srv.cc +++ b/src/net/examples/myholy_srv.cc @@ -1,20 +1,19 @@ -#include #include +#include #include #include -#include "net/include/server_thread.h" +#include "myproto.pb.h" #include "net/include/net_conn.h" -#include "net/include/pb_conn.h" #include "net/include/net_thread.h" -#include "myproto.pb.h" +#include "net/include/pb_conn.h" +#include "net/include/server_thread.h" using namespace net; -class MyConn: public PbConn { +class MyConn : public PbConn { public: - MyConn(int fd, const std::string& ip_port, Thread *thread, - void* worker_specific_data); + MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data); virtual ~MyConn(); protected: @@ -25,19 +24,17 @@ class MyConn: public PbConn { myproto::PingRes ping_res_; }; -MyConn::MyConn(int fd, const std::string& ip_port, - Thread *thread, void* worker_specific_data) +MyConn::MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data) : PbConn(fd, ip_port, thread) { // Handle worker_specific_data ... } -MyConn::~MyConn() { -} +MyConn::~MyConn() {} int MyConn::DealMessage() { printf("In the myconn DealMessage branch\n"); ping_.ParseFromArray(rbuf_ + cur_pos_ - header_len_, header_len_); - printf ("DealMessage receive (%s) port %d \n", ping_.address().c_str(), ping_.port()); + printf("DealMessage receive (%s) port %d \n", ping_.address().c_str(), ping_.port()); ping_res_.Clear(); ping_res_.set_res(11234); @@ -50,10 +47,8 @@ int MyConn::DealMessage() { class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string &ip_port, - Thread *thread, - void* worker_specific_data, - NetEpoll* net_epoll) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_specific_data, NetEpoll* net_epoll) const { return std::make_shared(connfd, ip_port, thread, worker_specific_data); } }; @@ -76,7 +71,7 @@ static void SignalSetup() { int main(int argc, char* argv[]) { if (argc < 2) { - printf ("Usage: ./server port\n"); + printf("Usage: ./server port\n"); exit(0); } @@ -84,7 +79,7 @@ int main(int argc, char* argv[]) { SignalSetup(); - ConnFactory *conn_factory = new MyConnFactory(); + ConnFactory* conn_factory = new MyConnFactory(); ServerThread* my_thread = NewHolyThread(my_port, conn_factory); if (my_thread->StartThread() != 0) { diff --git a/src/net/examples/myholy_srv_chandle.cc b/src/net/examples/myholy_srv_chandle.cc index 22944d390d..09a6d22fbf 100644 --- a/src/net/examples/myholy_srv_chandle.cc +++ b/src/net/examples/myholy_srv_chandle.cc @@ -1,49 +1,42 @@ -#include #include +#include #include #include -#include "net/include/server_thread.h" +#include "myproto.pb.h" #include "net/include/net_conn.h" -#include "net/include/pb_conn.h" #include "net/include/net_thread.h" -#include "myproto.pb.h" +#include "net/include/pb_conn.h" +#include "net/include/server_thread.h" using namespace net; -class MyConn: public PbConn { +class MyConn : public PbConn { public: - MyConn(int fd, std::string ip_port, Thread *thread, void* private_data); + MyConn(int fd, std::string ip_port, Thread* thread, void* private_data); virtual ~MyConn(); - Thread* thread() { - return thread_; - } + Thread* thread() { return thread_; } protected: virtual int DealMessage(); private: - Thread *thread_; + Thread* thread_; int* private_data_; myproto::Ping ping_; myproto::PingRes ping_res_; }; -MyConn::MyConn(int fd, ::std::string ip_port, Thread *thread, - void* worker_specific_data) - : PbConn(fd, ip_port, thread), - thread_(thread), - private_data_(static_cast(worker_specific_data)) { -} +MyConn::MyConn(int fd, ::std::string ip_port, Thread* thread, void* worker_specific_data) + : PbConn(fd, ip_port, thread), thread_(thread), private_data_(static_cast(worker_specific_data)) {} -MyConn::~MyConn() { -} +MyConn::~MyConn() {} int MyConn::DealMessage() { printf("In the myconn DealMessage branch\n"); ping_.ParseFromArray(rbuf_ + cur_pos_ - header_len_, header_len_); - printf ("DealMessage receive (%s) port %d \n", ping_.address().c_str(), ping_.port()); + printf("DealMessage receive (%s) port %d \n", ping_.address().c_str(), ping_.port()); int* data = static_cast(private_data_); printf("Worker's Env: %d\n", *data); @@ -59,26 +52,22 @@ int MyConn::DealMessage() { class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string &ip_port, - Thread *thread, - void* worker_specific_data, - NetEpoll* net_epoll) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_specific_data, NetEpoll* net_epoll) const { return std::make_shared(connfd, ip_port, thread, worker_specific_data); } }; class MyServerHandle : public ServerHandle { -public: - virtual void CronHandle() const override { - printf ("Cron operation\n"); - } + public: + virtual void CronHandle() const override { printf("Cron operation\n"); } using ServerHandle::AccessHandle; virtual bool AccessHandle(std::string& ip) const override { - printf ("Access operation, receive:%s\n", ip.c_str()); + printf("Access operation, receive:%s\n", ip.c_str()); return true; } virtual int CreateWorkerSpecificData(void** data) const { - int *num = new int(1234); + int* num = new int(1234); *data = static_cast(num); return 0; } @@ -106,7 +95,7 @@ static void SignalSetup() { int main(int argc, char* argv[]) { if (argc < 2) { - printf ("Usage: ./server port\n"); + printf("Usage: ./server port\n"); exit(0); } diff --git a/src/net/examples/myproto_cli.cc b/src/net/examples/myproto_cli.cc index c02786c05e..898a56eb94 100644 --- a/src/net/examples/myproto_cli.cc +++ b/src/net/examples/myproto_cli.cc @@ -1,7 +1,7 @@ -#include -#include -#include #include +#include +#include +#include #include "myproto.pb.h" #include "net/include/net_cli.h" @@ -10,28 +10,28 @@ using namespace net; int main(int argc, char* argv[]) { - if (argc < 3) { - printf ("Usage: ./client ip port\n"); + if (argc < 3) { + printf("Usage: ./client ip port\n"); exit(0); } std::string ip(argv[1]); int port = atoi(argv[2]); - + NetCli* cli = NewPbCli(); Status s = cli->Connect(ip, port); if (!s.ok()) { - printf ("Connect (%s:%d) failed, %s\n", ip.c_str(), port, s.ToString().c_str()); + printf("Connect (%s:%d) failed, %s\n", ip.c_str(), port, s.ToString().c_str()); } - printf ("Connect (%s:%d) ok, fd is %d\n", ip.c_str(), port, cli->fd()); + printf("Connect (%s:%d) ok, fd is %d\n", ip.c_str(), port, cli->fd()); for (int i = 0; i < 100000; i++) { myproto::Ping msg; msg.set_address("127.00000"); msg.set_port(2222); - s = cli->Send((void *)&msg); + s = cli->Send((void*)&msg); if (!s.ok()) { printf("Send failed %s\n", s.ToString().c_str()); break; @@ -39,12 +39,12 @@ int main(int argc, char* argv[]) { printf("Send sussces\n"); myproto::PingRes req; - s = cli->Recv((void *)&req); + s = cli->Recv((void*)&req); if (!s.ok()) { - printf ("Recv failed %s\n", s.ToString().c_str()); + printf("Recv failed %s\n", s.ToString().c_str()); break; } - printf ("Recv res %d mess (%s)\n", req.res(), req.mess().c_str()); + printf("Recv res %d mess (%s)\n", req.res(), req.mess().c_str()); } cli->Close(); diff --git a/src/net/examples/myredis_cli.cc b/src/net/examples/myredis_cli.cc index f181e43204..64e461904b 100644 --- a/src/net/examples/myredis_cli.cc +++ b/src/net/examples/myredis_cli.cc @@ -1,5 +1,5 @@ -#include #include +#include #include #include #include @@ -7,15 +7,14 @@ #include "net/include/client_thread.h" #include "net/include/net_conn.h" -#include "net/include/redis_conn.h" #include "net/include/net_thread.h" +#include "net/include/redis_conn.h" using namespace net; -class MyConn: public RedisConn { +class MyConn : public RedisConn { public: - MyConn(int fd, const std::string& ip_port, Thread *thread, - void* worker_specific_data); + MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data); virtual ~MyConn() = default; protected: @@ -24,8 +23,7 @@ class MyConn: public RedisConn { private: }; -MyConn::MyConn(int fd, const std::string& ip_port, - Thread *thread, void* worker_specific_data) +MyConn::MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data) : RedisConn(fd, ip_port, thread) { // Handle worker_specific_data ... } @@ -34,38 +32,29 @@ ClientThread* client; int sendto_port; int MyConn::DealMessage(const RedisCmdArgsType& argv, std::string* response) { sleep(1); - std::cout << "DealMessage" << std::endl; - std::string set = "*3\r\n$3\r\nSet\r\n$3\r\nabc\r\n$3\r\nabc\r\n"; + std::cout << "DealMessage" << std::endl; + std::string set = "*3\r\n$3\r\nSet\r\n$3\r\nabc\r\n$3\r\nabc\r\n"; client->Write("127.0.0.1", sendto_port, set); return 0; } class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string &ip_port, - Thread *thread, - void* worker_specific_data, net::NetEpoll* net_epoll=nullptr) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_specific_data, net::NetEpoll* net_epoll = nullptr) const { return std::make_shared(connfd, ip_port, thread, worker_specific_data); } }; class MyClientHandle : public net::ClientHandle { public: - void CronHandle() const override { - } + void CronHandle() const override {} void FdTimeoutHandle(int fd, const std::string& ip_port) const override; void FdClosedHandle(int fd, const std::string& ip_port) const override; - bool AccessHandle(std::string& ip) const override { - return true; - } - int CreateWorkerSpecificData(void** data) const override { - return 0; - } - int DeleteWorkerSpecificData(void* data) const override { - return 0; - } - void DestConnectFailedHandle(std::string ip_port, std::string reason) const override { - } + bool AccessHandle(std::string& ip) const override { return true; } + int CreateWorkerSpecificData(void** data) const override { return 0; } + int DeleteWorkerSpecificData(void* data) const override { return 0; } + void DestConnectFailedHandle(std::string ip_port, std::string reason) const override {} }; static std::atomic running(false); @@ -103,12 +92,12 @@ int main(int argc, char* argv[]) { sendto_port = (argc > 1) ? atoi(argv[1]) : 6379; SignalSetup(); - - ConnFactory *conn_factory = new MyConnFactory(); - ClientHandle *handle = new ClientHandle(); + + ConnFactory* conn_factory = new MyConnFactory(); + ClientHandle* handle = new ClientHandle(); client = new ClientThread(conn_factory, 3000, 60, handle, NULL); - + if (client->StartThread() != 0) { printf("StartThread error happened!\n"); exit(-1); diff --git a/src/net/examples/myredis_srv.cc b/src/net/examples/myredis_srv.cc index 8e1c648a76..502769f7ce 100644 --- a/src/net/examples/myredis_srv.cc +++ b/src/net/examples/myredis_srv.cc @@ -1,24 +1,22 @@ -#include #include +#include #include #include #include -#include "net/include/server_thread.h" #include "net/include/net_conn.h" -#include "net/include/redis_conn.h" #include "net/include/net_thread.h" +#include "net/include/redis_conn.h" +#include "net/include/server_thread.h" #include "net/src/holy_thread.h" using namespace net; std::map db; - -class MyConn: public RedisConn { +class MyConn : public RedisConn { public: - MyConn(int fd, const std::string& ip_port, Thread *thread, - void* worker_specific_data); + MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data); virtual ~MyConn() = default; protected: @@ -27,8 +25,7 @@ class MyConn: public RedisConn { private: }; -MyConn::MyConn(int fd, const std::string& ip_port, - Thread *thread, void* worker_specific_data) +MyConn::MyConn(int fd, const std::string& ip_port, Thread* thread, void* worker_specific_data) : RedisConn(fd, ip_port, thread) { // Handle worker_specific_data ... } @@ -66,9 +63,8 @@ int MyConn::DealMessage(const RedisCmdArgsType& argv, std::string* response) { class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string &ip_port, - Thread *thread, - void* worker_specific_data, net::NetEpoll* net_epoll=nullptr) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_specific_data, net::NetEpoll* net_epoll = nullptr) const { return std::make_shared(connfd, ip_port, thread, worker_specific_data); } }; @@ -99,7 +95,7 @@ int main(int argc, char* argv[]) { SignalSetup(); - ConnFactory *conn_factory = new MyConnFactory(); + ConnFactory* conn_factory = new MyConnFactory(); ServerThread* my_thread = new HolyThread(my_port, conn_factory, 1000, NULL, false); if (my_thread->StartThread() != 0) { diff --git a/src/net/examples/performance/client.cc b/src/net/examples/performance/client.cc index 73ece739d2..3f73577ef0 100644 --- a/src/net/examples/performance/client.cc +++ b/src/net/examples/performance/client.cc @@ -1,7 +1,7 @@ -#include -#include -#include #include +#include +#include +#include #include "message.pb.h" #include "net/include/net_cli.h" @@ -10,38 +10,37 @@ using namespace net; int main(int argc, char* argv[]) { - if (argc < 3) { - printf ("Usage: ./client ip port\n"); + if (argc < 3) { + printf("Usage: ./client ip port\n"); exit(0); } std::string ip(argv[1]); int port = atoi(argv[2]); - + NetCli* cli = NewPbCli(); Status s = cli->Connect(ip, port); if (!s.ok()) { - printf ("Connect (%s:%d) failed, %s\n", ip.c_str(), port, s.ToString().c_str()); + printf("Connect (%s:%d) failed, %s\n", ip.c_str(), port, s.ToString().c_str()); } for (int i = 0; i < 100000000; i++) { Ping msg; msg.set_ping("ping"); - s = cli->Send((void *)&msg); + s = cli->Send((void*)&msg); if (!s.ok()) { - printf ("Send failed %s\n", s.ToString().c_str()); + printf("Send failed %s\n", s.ToString().c_str()); break; } Pong req; - s = cli->Recv((void *)&req); + s = cli->Recv((void*)&req); if (!s.ok()) { - printf ("Recv failed %s\n", s.ToString().c_str()); + printf("Recv failed %s\n", s.ToString().c_str()); break; } // printf ("Recv (%s)\n", req.pong().c_str()); - } cli->Close(); diff --git a/src/net/examples/performance/server.cc b/src/net/examples/performance/server.cc index 71ff9df76d..dd96894a83 100644 --- a/src/net/examples/performance/server.cc +++ b/src/net/examples/performance/server.cc @@ -1,15 +1,15 @@ +#include +#include #include +#include #include #include -#include -#include -#include -#include "net/include/server_thread.h" +#include "message.pb.h" #include "net/include/net_conn.h" -#include "net/include/pb_conn.h" #include "net/include/net_thread.h" -#include "message.pb.h" +#include "net/include/pb_conn.h" +#include "net/include/server_thread.h" using namespace net; using namespace std; @@ -24,9 +24,7 @@ static atomic num(0); class PingConn : public PbConn { public: - PingConn(int fd, std::string ip_port, net::ServerThread* pself_thread = NULL) : - PbConn(fd, ip_port, pself_thread) { - } + PingConn(int fd, std::string ip_port, net::ServerThread* pself_thread = NULL) : PbConn(fd, ip_port, pself_thread) {} virtual ~PingConn() {} int DealMessage() { @@ -43,7 +41,6 @@ class PingConn : public PbConn { } private: - Ping request_; Pong response_; @@ -51,23 +48,17 @@ class PingConn : public PbConn { PingConn& operator=(PingConn&); }; - class PingConnFactory : public ConnFactory { public: - virtual NetConn *NewNetConn( - int connfd, - const std::string &ip_port, - ServerThread *thread, - void* worker_specific_data) const { + virtual NetConn* NewNetConn(int connfd, const std::string& ip_port, ServerThread* thread, + void* worker_specific_data) const { return new PingConn(connfd, ip_port, thread); } }; std::atomic should_stop(false); -static void IntSigHandle(const int sig) { - should_stop.store(true); -} +static void IntSigHandle(const int sig) { should_stop.store(true); } static void SignalSetup() { signal(SIGHUP, SIG_IGN); @@ -79,7 +70,7 @@ static void SignalSetup() { int main(int argc, char* argv[]) { if (argc < 2) { - printf ("Usage: ./server ip port\n"); + printf("Usage: ./server ip port\n"); exit(0); } @@ -90,7 +81,7 @@ int main(int argc, char* argv[]) { SignalSetup(); - ServerThread *st_thread = NewDispatchThread(ip, port, 24, &conn_factory, 1000); + ServerThread* st_thread = NewDispatchThread(ip, port, 24, &conn_factory, 1000); st_thread->StartThread(); uint64_t st, ed; diff --git a/src/net/examples/redis_cli_test.cc b/src/net/examples/redis_cli_test.cc index 4addad678a..6decf32080 100644 --- a/src/net/examples/redis_cli_test.cc +++ b/src/net/examples/redis_cli_test.cc @@ -1,14 +1,14 @@ -#include +#include "net/include/redis_cli.h" #include -#include "pstd/include/xdebug.h" +#include #include "net/include/net_cli.h" -#include "net/include/redis_cli.h" +#include "pstd/include/xdebug.h" using namespace net; int main(int argc, char* argv[]) { if (argc < 3) { - printf ("Usage: ./redis_cli ip port\n"); + printf("Usage: ./redis_cli ip port\n"); exit(0); } @@ -18,9 +18,9 @@ int main(int argc, char* argv[]) { std::string str; int i = 5; - printf ("\nTest Serialize\n"); + printf("\nTest Serialize\n"); int ret = net::SerializeRedisCommand(&str, "HSET %s %d", "key", i); - printf (" 1. Serialize by va return %d, (%s)\n", ret, str.c_str()); + printf(" 1. Serialize by va return %d, (%s)\n", ret, str.c_str()); RedisCmdArgsType vec; vec.push_back("hset"); @@ -28,23 +28,23 @@ int main(int argc, char* argv[]) { vec.push_back(std::to_string(5)); ret = net::SerializeRedisCommand(vec, &str); - printf (" 2. Serialize by vec return %d, (%s)\n", ret, str.c_str()); + printf(" 2. Serialize by vec return %d, (%s)\n", ret, str.c_str()); - NetCli *rcli = NewRedisCli(); + NetCli* rcli = NewRedisCli(); rcli->set_connect_timeout(3000); // redis v3.2+ protect mode will block other ip - //printf (" Connect with bind_ip(101.199.114.205)\n"); - //Status s = rcli->Connect(ip, port, "101.199.114.205"); + // printf (" Connect with bind_ip(101.199.114.205)\n"); + // Status s = rcli->Connect(ip, port, "101.199.114.205"); Status s = rcli->Connect(ip, port, "101.199.114.205"); // Test connect timeout with a non-routable IP - //Status s = rcli->Connect("10.255.255.1", 9824); + // Status s = rcli->Connect("10.255.255.1", 9824); printf(" RedisCli Connect(%s:%d) return %s\n", ip.c_str(), port, s.ToString().c_str()); if (!s.ok()) { - printf ("Connect failed, %s\n", s.ToString().c_str()); - exit(-1); + printf("Connect failed, %s\n", s.ToString().c_str()); + exit(-1); } ret = rcli->set_send_timeout(100); @@ -59,7 +59,7 @@ int main(int argc, char* argv[]) { */ net::RedisCmdArgsType redis_argv; - printf ("\nTest Send and Recv Ping\n"); + printf("\nTest Send and Recv Ping\n"); std::string ping = "*1\r\n$4\r\nping\r\n"; for (int i = 0; i < 1; i++) { s = rcli->Send(&ping); @@ -72,11 +72,11 @@ int main(int argc, char* argv[]) { } } - printf ("\nTest Send and Recv Mutli\n"); + printf("\nTest Send and Recv Mutli\n"); net::SerializeRedisCommand(&str, "MSET a 1 b 2 c 3 d 4"); - printf ("Send mset parse (%s)\n", str.c_str()); + printf("Send mset parse (%s)\n", str.c_str()); s = rcli->Send(&str); - printf ("Send mset return %s\n", s.ToString().c_str()); + printf("Send mset return %s\n", s.ToString().c_str()); s = rcli->Recv(&redis_argv); printf("Recv mset return %s with %lu elements\n", s.ToString().c_str(), redis_argv.size()); @@ -84,40 +84,40 @@ int main(int argc, char* argv[]) { printf(" redis_argv[%lu] = (%s)", i, redis_argv[i].c_str()); } - printf ("\n\nTest Mget case 1: send 1 time, and recv 1 time\n"); + printf("\n\nTest Mget case 1: send 1 time, and recv 1 time\n"); net::SerializeRedisCommand(&str, "MGET a b c d "); - printf ("Send mget parse (%s)\n", str.c_str()); + printf("Send mget parse (%s)\n", str.c_str()); for (int si = 0; si < 2; si++) { s = rcli->Send(&str); - printf ("Send mget case 1: i=%d, return %s\n", si, s.ToString().c_str()); + printf("Send mget case 1: i=%d, return %s\n", si, s.ToString().c_str()); s = rcli->Recv(&redis_argv); - printf ("Recv mget case 1: i=%d, return %s with %lu elements\n", si, s.ToString().c_str(), redis_argv.size()); + printf("Recv mget case 1: i=%d, return %s with %lu elements\n", si, s.ToString().c_str(), redis_argv.size()); for (size_t i = 0; i < redis_argv.size(); i++) { printf(" redis_argv[%lu] = (%s)\n", i, redis_argv[i].c_str()); } } - printf ("\nTest Mget case 2: send 2 times, then recv 2 times\n"); + printf("\nTest Mget case 2: send 2 times, then recv 2 times\n"); net::SerializeRedisCommand(&str, "MGET a b c d "); - printf ("\nSend mget parse (%s)\n", str.c_str()); + printf("\nSend mget parse (%s)\n", str.c_str()); for (int si = 0; si < 2; si++) { s = rcli->Send(&str); - printf ("Send mget case 2: i=%d, return %s\n", si, s.ToString().c_str()); + printf("Send mget case 2: i=%d, return %s\n", si, s.ToString().c_str()); } for (int si = 0; si < 2; si++) { s = rcli->Recv(&redis_argv); - printf ("Recv mget case 1: i=%d, return %s with %lu elements\n", si, s.ToString().c_str(), redis_argv.size()); + printf("Recv mget case 1: i=%d, return %s with %lu elements\n", si, s.ToString().c_str(), redis_argv.size()); for (size_t i = 0; i < redis_argv.size(); i++) { - printf (" redis_argv[%lu] = (%s)\n", i, redis_argv[i].c_str()); + printf(" redis_argv[%lu] = (%s)\n", i, redis_argv[i].c_str()); } } char ch; - scanf ("%c", &ch); + scanf("%c", &ch); return 0; } diff --git a/src/net/examples/redis_parser_test.cc b/src/net/examples/redis_parser_test.cc index 9bb979f26d..0b3cd72522 100644 --- a/src/net/examples/redis_parser_test.cc +++ b/src/net/examples/redis_parser_test.cc @@ -1,28 +1,28 @@ -#include #include -#include "pstd/include/xdebug.h" +#include #include "net/include/net_cli.h" #include "net/include/redis_cli.h" +#include "pstd/include/xdebug.h" using namespace net; int main(int argc, char* argv[]) { if (argc < 3) { - printf ("Usage: ./redis_parser_test ip port\n"); + printf("Usage: ./redis_parser_test ip port\n"); exit(0); } std::string ip(argv[1]); int port = atoi(argv[2]); - NetCli *rcli = NewRedisCli(); + NetCli* rcli = NewRedisCli(); rcli->set_connect_timeout(3000); Status s = rcli->Connect(ip, port, "127.0.0.1"); printf(" RedisCli Connect(%s:%d) return %s\n", ip.c_str(), port, s.ToString().c_str()); if (!s.ok()) { - printf ("Connect failed, %s\n", s.ToString().c_str()); - exit(-1); + printf("Connect failed, %s\n", s.ToString().c_str()); + exit(-1); } net::RedisCmdArgsType redis_argv; @@ -30,77 +30,79 @@ int main(int argc, char* argv[]) { std::string one_command = "*3\r\n$3\r\nSET\r\n$1\r\na\r\n$2\r\nab\r\n"; { - printf ("\nTest Send One whole command\n"); - std::string one_command = "*3\r\n$3\r\nSET\r\n$1\r\na\r\n$2\r\nab\r\n"; - s = rcli->Send(&one_command); - printf("Send %s\n", s.ToString().c_str()); - - s = rcli->Recv(&redis_argv); - printf("Recv return %s\n", s.ToString().c_str()); - if (redis_argv.size() > 0) { - printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); - } + printf("\nTest Send One whole command\n"); + std::string one_command = "*3\r\n$3\r\nSET\r\n$1\r\na\r\n$2\r\nab\r\n"; + s = rcli->Send(&one_command); + printf("Send %s\n", s.ToString().c_str()); + + s = rcli->Recv(&redis_argv); + printf("Recv return %s\n", s.ToString().c_str()); + if (redis_argv.size() > 0) { + printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); + } } { - printf ("\nTest Send command into two times bulk itself break\n"); - std::string half_command = "*3\r\n$3\r\nSET\r\n$3\r\nabc\r\n$10\r\n12345"; - std::string another_half_command = "67890\r\n"; - std::string one_command_and_a_half = one_command + half_command; - s = rcli->Send(&one_command_and_a_half); - printf("Send %s\n", s.ToString().c_str()); - sleep(1); - s = rcli->Send(&another_half_command); - printf("Send %s\n", s.ToString().c_str()); - - s = rcli->Recv(&redis_argv); - printf("Recv return %s\n", s.ToString().c_str()); - if (redis_argv.size() > 0) { - printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); - } - } - - { - printf ("\nTest Send command into two times bulk num break\n"); - std::string half_command = "*3\r\n$3\r\nSET\r\n$1"; - std::string another_half_command = "0\r\n0123456789\r\n$10\r\n1234567890\r\n"; - std::string one_command_and_a_half = one_command + half_command; - s = rcli->Send(&one_command_and_a_half); - printf("Send %s\n", s.ToString().c_str()); - sleep(1); - s = rcli->Send(&another_half_command); - printf("Send %s\n", s.ToString().c_str()); - - s = rcli->Recv(&redis_argv); - printf("Recv return %s\n", s.ToString().c_str()); - if (redis_argv.size() > 0) { - printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); - } + printf("\nTest Send command into two times bulk itself break\n"); + std::string half_command = "*3\r\n$3\r\nSET\r\n$3\r\nabc\r\n$10\r\n12345"; + std::string another_half_command = "67890\r\n"; + std::string one_command_and_a_half = one_command + half_command; + s = rcli->Send(&one_command_and_a_half); + printf("Send %s\n", s.ToString().c_str()); + sleep(1); + s = rcli->Send(&another_half_command); + printf("Send %s\n", s.ToString().c_str()); + + s = rcli->Recv(&redis_argv); + printf("Recv return %s\n", s.ToString().c_str()); + if (redis_argv.size() > 0) { + printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); + } } { - printf ("\nTest Send command byte by byte\n"); - std::string half_command = "*"; - std::string another_half_command = "11\r\n$4\r\nMSET\r\n$10\r\n0123456789\r\n$10\r\n1234567890\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n"; - std::string one_command_and_a_half = one_command + half_command; - s = rcli->Send(&one_command_and_a_half); - printf("Send %s\n", s.ToString().c_str()); - for (size_t i = 0; i < another_half_command.size(); ++i) { + printf("\nTest Send command into two times bulk num break\n"); + std::string half_command = "*3\r\n$3\r\nSET\r\n$1"; + std::string another_half_command = "0\r\n0123456789\r\n$10\r\n1234567890\r\n"; + std::string one_command_and_a_half = one_command + half_command; + s = rcli->Send(&one_command_and_a_half); + printf("Send %s\n", s.ToString().c_str()); sleep(1); - std::string one_char_str(another_half_command, i, 1); - s = rcli->Send(&one_char_str); - printf("Send %d %s\n", i, s.ToString().c_str()); + s = rcli->Send(&another_half_command); + printf("Send %s\n", s.ToString().c_str()); + + s = rcli->Recv(&redis_argv); + printf("Recv return %s\n", s.ToString().c_str()); + if (redis_argv.size() > 0) { + printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); + } } - s = rcli->Recv(&redis_argv); - printf("Recv return %s\n", s.ToString().c_str()); - if (redis_argv.size() > 0) { - printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); - } + { + printf("\nTest Send command byte by byte\n"); + std::string half_command = "*"; + std::string another_half_command = + "11\r\n$4\r\nMSET\r\n$10\r\n0123456789\r\n$10\r\n1234567890\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$" + "1\r\na\r\n$1\r\na\r\n$1\r\na\r\n$1\r\na\r\n"; + std::string one_command_and_a_half = one_command + half_command; + s = rcli->Send(&one_command_and_a_half); + printf("Send %s\n", s.ToString().c_str()); + for (size_t i = 0; i < another_half_command.size(); ++i) { + sleep(1); + std::string one_char_str(another_half_command, i, 1); + s = rcli->Send(&one_char_str); + printf("Send %d %s\n", i, s.ToString().c_str()); + } + + s = rcli->Recv(&redis_argv); + printf("Recv return %s\n", s.ToString().c_str()); + if (redis_argv.size() > 0) { + printf(" redis_argv[0] is (%s)\n", redis_argv[0].c_str()); + } } char ch; - scanf ("%c", &ch); + scanf("%c", &ch); return 0; } diff --git a/src/net/examples/simple_http_server.cc b/src/net/examples/simple_http_server.cc index a896f427c1..e44c347e45 100644 --- a/src/net/examples/simple_http_server.cc +++ b/src/net/examples/simple_http_server.cc @@ -3,28 +3,26 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include -#include #include +#include +#include -#include "pstd/include/pstd_status.h" #include "net/include/net_thread.h" #include "net/include/server_thread.h" #include "net/include/simple_http_conn.h" +#include "pstd/include/pstd_status.h" using namespace net; class MyHTTPConn : public net::SimpleHTTPConn { public: - MyHTTPConn(const int fd, const std::string& ip_port, Thread* worker) : - SimpleHTTPConn(fd, ip_port, worker) { - } + MyHTTPConn(const int fd, const std::string& ip_port, Thread* worker) : SimpleHTTPConn(fd, ip_port, worker) {} virtual void DealMessage(const net::Request* req, net::Response* res) { - std::cout << "handle get"<< std::endl; + std::cout << "handle get" << std::endl; std::cout << " + method: " << req->method << std::endl; std::cout << " + path: " << req->path << std::endl; std::cout << " + version: " << req->version << std::endl; - std::cout << " + content: " << req->content<< std::endl; + std::cout << " + content: " << req->content << std::endl; std::cout << " + headers: " << std::endl; for (auto& h : req->headers) { std::cout << " + " << h.first << ":" << h.second << std::endl; @@ -45,10 +43,8 @@ class MyHTTPConn : public net::SimpleHTTPConn { class MyConnFactory : public ConnFactory { public: - virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, - Thread* thread, - void* worker_specific_data, - NetEpoll* net_epoll) const { + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_specific_data, NetEpoll* net_epoll) const { return std::make_shared(connfd, ip_port, thread); } }; @@ -80,7 +76,7 @@ int main(int argc, char* argv[]) { SignalSetup(); ConnFactory* my_conn_factory = new MyConnFactory(); - ServerThread *st = NewDispatchThread(port, 4, my_conn_factory, 1000); + ServerThread* st = NewDispatchThread(port, 4, my_conn_factory, 1000); if (st->StartThread() != 0) { printf("StartThread error happened!\n"); diff --git a/src/net/examples/thread_pool_test.cc b/src/net/examples/thread_pool_test.cc index 58edd01981..f56dfe70c5 100644 --- a/src/net/examples/thread_pool_test.cc +++ b/src/net/examples/thread_pool_test.cc @@ -5,10 +5,10 @@ #include "unistd.h" -#include -#include #include #include +#include +#include #include "net/include/thread_pool.h" #include "pstd/include/pstd_mutex.h" @@ -23,16 +23,16 @@ uint64_t NowMicros() { static pstd::Mutex print_lock; -void task(void *arg) { +void task(void* arg) { { - pstd::MutexLock l(&print_lock); - std::cout << " task : " << *((int *)arg) << " time(micros) " << NowMicros() << " thread id: "<< pthread_self() << std::endl; + pstd::MutexLock l(&print_lock); + std::cout << " task : " << *((int*)arg) << " time(micros) " << NowMicros() << " thread id: " << pthread_self() + << std::endl; } sleep(1); delete (int*)arg; } - int main() { // 10 threads net::ThreadPool t(10, 1000), t2(10, 5); @@ -42,7 +42,7 @@ int main() { std::cout << "Test Normal Task... " << std::endl; for (int i = 0; i < 10; i++) { - int *pi = new int(i); + int* pi = new int(i); t.Schedule(task, (void*)pi); t.cur_queue_size(&qsize); t.cur_time_queue_size(&pqsize); @@ -62,12 +62,13 @@ int main() { t.stop_thread_pool(); t.start_thread_pool(); for (int i = 0; i < 10; i++) { - int *pi = new int(i); + int* pi = new int(i); t.DelaySchedule(i * 1000, task, (void*)pi); t.cur_queue_size(&qsize); t.cur_time_queue_size(&pqsize); pstd::MutexLock l(&print_lock); - std::cout << "Schedule task " << i << " time(micros) " << NowMicros() << " for " << i * 1000 * 1000 << " micros "<< std::endl; + std::cout << "Schedule task " << i << " time(micros) " << NowMicros() << " for " << i * 1000 * 1000 << " micros " + << std::endl; } while (pqsize > 0) { t.cur_time_queue_size(&pqsize); @@ -80,7 +81,7 @@ int main() { t.start_thread_pool(); std::cout << "Test Drop Task... " << std::endl; for (int i = 0; i < 10; i++) { - int *pi = new int(i); + int* pi = new int(i); t.DelaySchedule(i * 1000, task, (void*)pi); t.cur_queue_size(&qsize); t.cur_time_queue_size(&pqsize); diff --git a/src/net/include/backend_thread.h b/src/net/include/backend_thread.h index 6992a4845b..6e2b2aebf8 100644 --- a/src/net/include/backend_thread.h +++ b/src/net/include/backend_thread.h @@ -6,21 +6,24 @@ #ifndef NET_INCLUDE_BACKEND_THREAD_H_ #define NET_INCLUDE_BACKEND_THREAD_H_ -#include -#include #include #include +#include +#include #include -#include "pstd/include/pstd_status.h" -#include "pstd/include/pstd_mutex.h" #include "net/include/net_thread.h" #include "net/src/net_multiplexer.h" +#include "pstd/include/pstd_mutex.h" +#include "pstd/include/pstd_status.h" // remove 'unused parameter' warning -#define UNUSED(expr) do { (void)(expr); } while (0) +#define UNUSED(expr) \ + do { \ + (void)(expr); \ + } while (0) -#define kConnWriteBuf (1024*1024*100) // cache 100 MB data per connection +#define kConnWriteBuf (1024 * 1024 * 100) // cache 100 MB data per connection namespace net { @@ -67,7 +70,6 @@ class BackendHandle { return true; } - /* * CreateWorkerSpecificData(...) will be invoked in StartThread() routine. * 'data' pointer should be assigned. @@ -97,10 +99,10 @@ class BackendHandle { } }; - class BackendThread : public Thread { public: - BackendThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, BackendHandle* handle, void* private_data); + BackendThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, BackendHandle* handle, + void* private_data); virtual ~BackendThread(); /* * StartThread will return the error code as pthread_create return @@ -112,11 +114,11 @@ class BackendThread : public Thread { pstd::Status Close(const int fd); // Try to connect fd noblock, if return EINPROGRESS or EAGAIN or EWOULDBLOCK // put this fd in epoll (SetWaitConnectOnEpoll), process in ProcessConnectStatus - pstd::Status Connect(const std::string& dst_ip, const int dst_port, int *fd); + pstd::Status Connect(const std::string& dst_ip, const int dst_port, int* fd); std::shared_ptr GetConn(int fd); private: - virtual void *ThreadMain() override; + virtual void* ThreadMain() override; void InternalDebugPrint(); // Set connect fd into epoll @@ -145,14 +147,13 @@ class BackendThread : public Thread { */ std::unique_ptr net_multiplexer_; - ConnFactory *conn_factory_; + ConnFactory* conn_factory_; pstd::Mutex mu_; std::map> to_send_; // ip+":"+port, to_send_msg std::map> conns_; std::set connecting_fds_; - }; } // namespace net diff --git a/src/net/include/bg_thread.h b/src/net/include/bg_thread.h index 47183d3901..c5e6129c67 100644 --- a/src/net/include/bg_thread.h +++ b/src/net/include/bg_thread.h @@ -17,30 +17,18 @@ namespace net { struct TimerItem { uint64_t exec_time; - void (*function)(void *); + void (*function)(void*); void* arg; - TimerItem(uint64_t _exec_time, void (*_function)(void*), void* _arg) : - exec_time(_exec_time), - function(_function), - arg(_arg) {} - bool operator < (const TimerItem& item) const { - return exec_time > item.exec_time; - } + TimerItem(uint64_t _exec_time, void (*_function)(void*), void* _arg) + : exec_time(_exec_time), function(_function), arg(_arg) {} + bool operator<(const TimerItem& item) const { return exec_time > item.exec_time; } }; class BGThread : public Thread { public: - explicit BGThread(int full = 100000) : - Thread::Thread(), - full_(full), - mu_(), - rsignal_(&mu_), - wsignal_(&mu_) { - } - - virtual ~BGThread() { - StopThread(); - } + explicit BGThread(int full = 100000) : Thread::Thread(), full_(full), mu_(), rsignal_(&mu_), wsignal_(&mu_) {} + + virtual ~BGThread() { StopThread(); } virtual int StopThread() override { should_stop_ = true; @@ -54,19 +42,17 @@ class BGThread : public Thread { /* * timeout is in millionsecond */ - void DelaySchedule(uint64_t timeout, void (*function)(void *), void* arg); + void DelaySchedule(uint64_t timeout, void (*function)(void*), void* arg); void QueueSize(int* pri_size, int* qu_size); void QueueClear(); void SwallowReadyTasks(); private: - struct BGItem { void (*function)(void*); void* arg; - BGItem(void (*_function)(void*), void* _arg) - : function(_function), arg(_arg) {} + BGItem(void (*_function)(void*), void* _arg) : function(_function), arg(_arg) {} }; std::queue queue_; @@ -76,7 +62,7 @@ class BGThread : public Thread { pstd::Mutex mu_; pstd::CondVar rsignal_; pstd::CondVar wsignal_; - virtual void *ThreadMain() override; + virtual void* ThreadMain() override; }; } // namespace net diff --git a/src/net/include/build_version.h b/src/net/include/build_version.h index 031d156bae..f3726d8e7b 100644 --- a/src/net/include/build_version.h +++ b/src/net/include/build_version.h @@ -18,4 +18,3 @@ extern const char* net_build_git_sha; extern const char* net_build_compile_date; #endif // NET_INCLUDE_BUILD_VERSION_H_ - diff --git a/src/net/include/client_thread.h b/src/net/include/client_thread.h index a27e38fe47..fc87b0a1de 100644 --- a/src/net/include/client_thread.h +++ b/src/net/include/client_thread.h @@ -6,21 +6,24 @@ #ifndef NET_INCLUDE_CLIENT_THREAD_H_ #define NET_INCLUDE_CLIENT_THREAD_H_ -#include -#include #include #include +#include +#include #include -#include "pstd/include/pstd_status.h" -#include "pstd/include/pstd_mutex.h" #include "net/include/net_thread.h" #include "net/src/net_multiplexer.h" +#include "pstd/include/pstd_mutex.h" +#include "pstd/include/pstd_status.h" // remove 'unused parameter' warning -#define UNUSED(expr) do { (void)(expr); } while (0) +#define UNUSED(expr) \ + do { \ + (void)(expr); \ + } while (0) -#define kConnWriteBuf (1024*1024*100) // cache 100 MB data per connection +#define kConnWriteBuf (1024 * 1024 * 100) // cache 100 MB data per connection namespace net { @@ -67,7 +70,6 @@ class ClientHandle { return true; } - /* * CreateWorkerSpecificData(...) will be invoked in StartThread() routine. * 'data' pointer should be assigned. @@ -97,10 +99,10 @@ class ClientHandle { } }; - class ClientThread : public Thread { public: - ClientThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, ClientHandle* handle, void* private_data); + ClientThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, ClientHandle* handle, + void* private_data); virtual ~ClientThread(); /* * StartThread will return the error code as pthread_create return @@ -112,7 +114,7 @@ class ClientThread : public Thread { pstd::Status Close(const std::string& ip, const int port); private: - virtual void *ThreadMain() override; + virtual void* ThreadMain() override; void InternalDebugPrint(); // Set connect fd into epoll @@ -142,7 +144,7 @@ class ClientThread : public Thread { */ std::unique_ptr net_multiplexer_; - ConnFactory *conn_factory_; + ConnFactory* conn_factory_; pstd::Mutex mu_; std::map> to_send_; // ip+":"+port, to_send_msg diff --git a/src/net/include/http_conn.h b/src/net/include/http_conn.h index 2b1fad037d..e040a6e01b 100644 --- a/src/net/include/http_conn.h +++ b/src/net/include/http_conn.h @@ -6,9 +6,9 @@ #ifndef NET_INCLUDE_HTTP_CONN_H_ #define NET_INCLUDE_HTTP_CONN_H_ #include -#include -#include #include +#include +#include #include "pstd/include/pstd_status.h" #include "pstd/include/xdebug.h" @@ -159,13 +159,10 @@ class HTTPHandles { virtual int WriteResponseBody(char* buf, size_t max_size) = 0; // Close handle - virtual void HandleConnClosed() { - } + virtual void HandleConnClosed() {} - HTTPHandles() { - } - virtual ~HTTPHandles() { - } + HTTPHandles() {} + virtual ~HTTPHandles() {} protected: /* @@ -184,10 +181,9 @@ class HTTPHandles { void operator=(const HTTPHandles&); }; -class HTTPConn: public NetConn { +class HTTPConn : public NetConn { public: - HTTPConn(const int fd, const std::string &ip_port, - Thread *sthread, std::shared_ptr handles_, + HTTPConn(const int fd, const std::string& ip_port, Thread* sthread, std::shared_ptr handles_, void* worker_specific_data); ~HTTPConn(); diff --git a/src/net/include/net_cli.h b/src/net/include/net_cli.h index d8e1815cb7..6bbef7a049 100644 --- a/src/net/include/net_cli.h +++ b/src/net/include/net_cli.h @@ -20,15 +20,14 @@ class NetCli { virtual ~NetCli(); Status Connect(const std::string& bind_ip = ""); - Status Connect(const std::string &peer_ip, const int peer_port, - const std::string& bind_ip = ""); + Status Connect(const std::string& peer_ip, const int peer_port, const std::string& bind_ip = ""); // Check whether the connection got fin from peer or not virtual int CheckAliveness(void); // Compress and write the message - virtual Status Send(void *msg) = 0; + virtual Status Send(void* msg) = 0; // Read, parse and store the reply - virtual Status Recv(void *result = NULL) = 0; + virtual Status Recv(void* result = NULL) = 0; void Close(); @@ -55,11 +54,9 @@ class NetCli { void operator=(const NetCli&); }; -extern NetCli *NewPbCli( - const std::string& peer_ip = "", - const int peer_port = 0); +extern NetCli* NewPbCli(const std::string& peer_ip = "", const int peer_port = 0); -extern NetCli *NewRedisCli(); +extern NetCli* NewRedisCli(); } // namespace net #endif // NET_INCLUDE_NET_CLI_H_ diff --git a/src/net/include/net_conn.h b/src/net/include/net_conn.h index 182f48eafa..9bb2dc1c7f 100644 --- a/src/net/include/net_conn.h +++ b/src/net/include/net_conn.h @@ -10,8 +10,8 @@ #include #ifdef __ENABLE_SSL -#include -#include +# include +# include #endif #include "net/include/net_define.h" @@ -24,7 +24,7 @@ class Thread; class NetConn : public std::enable_shared_from_this { public: - NetConn(const int fd, const std::string &ip_port, Thread *thread, NetMultiplexer* mpx = nullptr); + NetConn(const int fd, const std::string& ip_port, Thread* thread, NetMultiplexer* mpx = nullptr); virtual ~NetConn(); /* @@ -38,47 +38,27 @@ class NetConn : public std::enable_shared_from_this { virtual ReadStatus GetRequest() = 0; virtual WriteStatus SendReply() = 0; - virtual int WriteResp(const std::string& resp) { - return 0; - } + virtual int WriteResp(const std::string& resp) { return 0; } virtual void TryResizeBuffer() {} - int flags() const { - return flags_; - } + int flags() const { return flags_; } - void set_fd(const int fd) { - fd_ = fd; - } + void set_fd(const int fd) { fd_ = fd; } - int fd() const { - return fd_; - } + int fd() const { return fd_; } - std::string ip_port() const { - return ip_port_; - } + std::string ip_port() const { return ip_port_; } - bool is_ready_to_reply() { - return is_writable() && is_reply(); - } + bool is_ready_to_reply() { return is_writable() && is_reply(); } - virtual void set_is_writable(const bool is_writable) { - is_writable_ = is_writable; - } + virtual void set_is_writable(const bool is_writable) { is_writable_ = is_writable; } - virtual bool is_writable() { - return is_writable_; - } + virtual bool is_writable() { return is_writable_; } - virtual void set_is_reply(const bool is_reply) { - is_reply_ = is_reply; - } + virtual void set_is_reply(const bool is_reply) { is_reply_ = is_reply; } - virtual bool is_reply() { - return is_reply_; - } + virtual bool is_reply() { return is_reply_; } std::string name() { return name_; } void set_name(std::string name) { name_ = std::move(name); } @@ -86,34 +66,20 @@ class NetConn : public std::enable_shared_from_this { bool IsClose() { return close_; } void SetClose(bool close) { close_ = close; } - void set_last_interaction(const struct timeval &now) { - last_interaction_ = now; - } + void set_last_interaction(const struct timeval& now) { last_interaction_ = now; } - struct timeval last_interaction() const { - return last_interaction_; - } + struct timeval last_interaction() const { return last_interaction_; } - Thread *thread() const { - return thread_; - } + Thread* thread() const { return thread_; } - void set_net_multiplexer(NetMultiplexer* ep) { - net_multiplexer_ = ep; - } + void set_net_multiplexer(NetMultiplexer* ep) { net_multiplexer_ = ep; } - NetMultiplexer* net_multiplexer() const { - return net_multiplexer_; - } + NetMultiplexer* net_multiplexer() const { return net_multiplexer_; } #ifdef __ENABLE_SSL - SSL* ssl() { - return ssl_; - } + SSL* ssl() { return ssl_; } - bool security() { - return ssl_ != nullptr; - } + bool security() { return ssl_ != nullptr; } #endif private: @@ -131,9 +97,9 @@ class NetConn : public std::enable_shared_from_this { #endif // thread this conn belong to - Thread *thread_; + Thread* thread_; // the net epoll this conn belong to - NetMultiplexer *net_multiplexer_; + NetMultiplexer* net_multiplexer_; /* * No allowed copy and copy assign operator @@ -142,19 +108,15 @@ class NetConn : public std::enable_shared_from_this { void operator=(const NetConn&); }; - /* * for every conn, we need create a corresponding ConnFactory */ class ConnFactory { public: virtual ~ConnFactory() {} - virtual std::shared_ptr NewNetConn( - int connfd, - const std::string &ip_port, - Thread *thread, - void* worker_private_data, /* Has set in ThreadEnvHandle */ - NetMultiplexer* net_mpx = nullptr) const = 0; + virtual std::shared_ptr NewNetConn(int connfd, const std::string& ip_port, Thread* thread, + void* worker_private_data, /* Has set in ThreadEnvHandle */ + NetMultiplexer* net_mpx = nullptr) const = 0; }; } // namespace net diff --git a/src/net/include/net_define.h b/src/net/include/net_define.h index 9559594aec..4ec16cc4e3 100644 --- a/src/net/include/net_define.h +++ b/src/net/include/net_define.h @@ -17,7 +17,7 @@ namespace net { #define NET_NAME_LEN 1024 const int kProtoMaxMessage = 512 * 1024 * 1024; // 512MB -#define PB_IOBUF_LEN 67108864 // 64MB +#define PB_IOBUF_LEN 67108864 // 64MB /* * The pb head and code length */ @@ -88,11 +88,11 @@ enum RetCode { /* * define the redis protocol */ -#define REDIS_MAX_MESSAGE (1 << 28) // 256MB -#define REDIS_MBULK_BIG_ARG (1024 * 32) // 32KB -#define DEFAULT_WBUF_SIZE 262144 // 256KB -#define REDIS_INLINE_MAXLEN (1024 * 64) // 64KB -#define REDIS_IOBUF_LEN 16384 // 16KB +#define REDIS_MAX_MESSAGE (1 << 28) // 256MB +#define REDIS_MBULK_BIG_ARG (1024 * 32) // 32KB +#define DEFAULT_WBUF_SIZE 262144 // 256KB +#define REDIS_INLINE_MAXLEN (1024 * 64) // 64KB +#define REDIS_IOBUF_LEN 16384 // 16KB #define REDIS_REQ_INLINE 1 #define REDIS_REQ_MULTIBULK 2 @@ -109,7 +109,6 @@ enum RetCode { #define NET_LINE_SIZE 1024 #define NET_CONF_MAX_NUM 1024 - /* * define common character */ diff --git a/src/net/include/net_pubsub.h b/src/net/include/net_pubsub.h index 736ffba24a..8891f3dc35 100644 --- a/src/net/include/net_pubsub.h +++ b/src/net/include/net_pubsub.h @@ -6,23 +6,23 @@ #ifndef NET_INCLUDE_PUBSUB_H_ #define NET_INCLUDE_PUBSUB_H_ -#include +#include +#include #include -#include #include +#include +#include +#include #include -#include #include -#include -#include -#include "pstd/include/xdebug.h" #include "pstd/include/pstd_mutex.h" #include "pstd/include/pstd_string.h" +#include "pstd/include/xdebug.h" -#include "net/src/net_multiplexer.h" -#include "net/include/net_thread.h" #include "net/include/net_define.h" +#include "net/include/net_thread.h" +#include "net/src/net_multiplexer.h" namespace net { @@ -39,21 +39,15 @@ class PubSubThread : public Thread { int Publish(const std::string& channel, const std::string& msg); - void Subscribe(std::shared_ptr conn, - const std::vector& channels, - const bool pattern, + void Subscribe(std::shared_ptr conn, const std::vector& channels, const bool pattern, std::vector>* result); - int UnSubscribe(std::shared_ptr conn, - const std::vector& channels, - const bool pattern, + int UnSubscribe(std::shared_ptr conn, const std::vector& channels, const bool pattern, std::vector>* result); - void PubSubChannels(const std::string& pattern, - std::vector* result); + void PubSubChannels(const std::string& pattern, std::vector* result); - void PubSubNumSub(const std::vector& channels, - std::vector>* result); + void PubSubNumSub(const std::vector& channels, std::vector>* result); int PubSubNumPat(); @@ -68,8 +62,7 @@ class PubSubThread : public Thread { }; struct ConnHandle { - ConnHandle(std::shared_ptr pc, ReadyState state = kNotReady) - : conn(pc), ready_state(state) { } + ConnHandle(std::shared_ptr pc, ReadyState state = kNotReady) : conn(pc), ready_state(state) {} void UpdateReadyState(const ReadyState& state); bool IsReady(); std::shared_ptr conn; @@ -89,7 +82,7 @@ class PubSubThread : public Thread { bool should_exit_; mutable pstd::RWMutex rwlock_; /* For external statistics */ - std::map > conns_; + std::map> conns_; pstd::Mutex pub_mutex_; pstd::CondVar receiver_rsignal_; @@ -110,7 +103,7 @@ class PubSubThread : public Thread { */ std::unique_ptr net_multiplexer_; - virtual void *ThreadMain(); + virtual void* ThreadMain(); // clean conns void Cleanup(); @@ -119,8 +112,8 @@ class PubSubThread : public Thread { pstd::Mutex channel_mutex_; pstd::Mutex pattern_mutex_; - std::map >> pubsub_channel_; // channel <---> conns - std::map >> pubsub_pattern_; // channel <---> conns + std::map>> pubsub_channel_; // channel <---> conns + std::map>> pubsub_pattern_; // channel <---> conns // No copying allowed PubSubThread(const PubSubThread&); diff --git a/src/net/include/net_thread.h b/src/net/include/net_thread.h index 5f336319cd..50163f15ef 100644 --- a/src/net/include/net_thread.h +++ b/src/net/include/net_thread.h @@ -7,8 +7,8 @@ #define NET_INCLUDE_NET_THREAD_H_ #include -#include #include +#include #include "pstd/include/pstd_mutex.h" @@ -23,36 +23,24 @@ class Thread { virtual int StopThread(); int JoinThread(); - bool should_stop() { - return should_stop_.load(); - } + bool should_stop() { return should_stop_.load(); } - void set_should_stop() { - should_stop_.store(true); - } + void set_should_stop() { should_stop_.store(true); } - bool is_running() { - return running_; - } + bool is_running() { return running_; } - pthread_t thread_id() const { - return thread_id_; - } + pthread_t thread_id() const { return thread_id_; } - std::string thread_name() const { - return thread_name_; - } + std::string thread_name() const { return thread_name_; } - void set_thread_name(const std::string& name) { - thread_name_ = name; - } + void set_thread_name(const std::string& name) { thread_name_ = name; } protected: std::atomic should_stop_; private: static void* RunThread(void* arg); - virtual void *ThreadMain() = 0; + virtual void* ThreadMain() = 0; pstd::Mutex running_mu_; bool running_; diff --git a/src/net/include/pb_conn.h b/src/net/include/pb_conn.h index 8db06c3161..306d8a8be6 100644 --- a/src/net/include/pb_conn.h +++ b/src/net/include/pb_conn.h @@ -6,33 +6,33 @@ #ifndef NET_INCLUDE_PB_CONN_H_ #define NET_INCLUDE_PB_CONN_H_ -#include #include #include +#include #include "google/protobuf/message.h" -#include "pstd/include/pstd_status.h" #include "net/include/net_conn.h" #include "net/include/net_define.h" +#include "pstd/include/pstd_status.h" namespace net { using pstd::Status; -class PbConn: public NetConn { +class PbConn : public NetConn { public: - struct WriteBuf{ - WriteBuf(const size_t item_pos = 0) : item_pos_(item_pos) {} - std::queue queue_; - size_t item_pos_; - }; - PbConn(const int fd, const std::string &ip_port, Thread *thread, NetMultiplexer* net_mpx = nullptr); + struct WriteBuf { + WriteBuf(const size_t item_pos = 0) : item_pos_(item_pos) {} + std::queue queue_; + size_t item_pos_; + }; + PbConn(const int fd, const std::string& ip_port, Thread* thread, NetMultiplexer* net_mpx = nullptr); virtual ~PbConn(); ReadStatus GetRequest() override; WriteStatus SendReply() override; void TryResizeBuffer() override; - int WriteResp(const std::string& resp) override ; + int WriteResp(const std::string& resp) override; void NotifyWrite(); void NotifyClose(); void set_is_reply(const bool reply) override; @@ -57,24 +57,23 @@ class PbConn: public NetConn { // 1. protocol parsing error // 2. service logic error // - // protocol parsing error means that we receive a message that is not + // protocol parsing error means that we receive a message that is not // a protobuf message that we know, // in this situation we should close this connection. // why we should close connection? - // beacause if we parse protocol error, it means that the content in this + // beacause if we parse protocol error, it means that the content in this // connection can't not be parse, we can't recognize the next message. // The only thing we can do is close this connection. // in this condition the DealMessage should return -1; // // - // the logic error means that we have receive the message, and the + // the logic error means that we have receive the message, and the // message is protobuf message that we define in proto file. // After receiving this message, we start execute our service logic. // the service logic error we should put it in res_, and return 0 // since this is the service logic error, not the network error. // this connection we can use again. - // If you want to send response back, build your pb version response yourself, // serializeToString and invoke WriteResp and NotifyWrite if necessary. virtual int DealMessage() = 0; diff --git a/src/net/include/period_thread.h b/src/net/include/period_thread.h index ec7af14813..98aee0f5b9 100644 --- a/src/net/include/period_thread.h +++ b/src/net/include/period_thread.h @@ -15,7 +15,7 @@ namespace net { class PeriodThread : public Thread { public: explicit PeriodThread(struct timeval period = (struct timeval){1, 0}); - virtual void *ThreadMain(); + virtual void* ThreadMain(); virtual void PeriodMain() = 0; private: diff --git a/src/net/include/redis_cli.h b/src/net/include/redis_cli.h index 5420b3b386..9980f795af 100644 --- a/src/net/include/redis_cli.h +++ b/src/net/include/redis_cli.h @@ -6,12 +6,11 @@ #ifndef NET_INCLUDE_REDIS_CLI_H_ #define NET_INCLUDE_REDIS_CLI_H_ -#include #include +#include namespace net { - typedef std::vector RedisCmdArgsType; // We can serialize redis command by 2 ways: // 1. by variable argmuments; @@ -20,9 +19,9 @@ typedef std::vector RedisCmdArgsType; // 2. by a string vector; // eg. RedisCli::Serialize(argv, cmd); // also cmd will be set as the result string. -extern int SerializeRedisCommand(std::string *cmd, const char *format, ...); -extern int SerializeRedisCommand(RedisCmdArgsType argv, std::string *cmd); +extern int SerializeRedisCommand(std::string* cmd, const char* format, ...); +extern int SerializeRedisCommand(RedisCmdArgsType argv, std::string* cmd); -} // namespace net +} // namespace net #endif // NET_INCLUDE_REDIS_CLI_H_ diff --git a/src/net/include/redis_conn.h b/src/net/include/redis_conn.h index 54e3c3011e..1d2b370e95 100644 --- a/src/net/include/redis_conn.h +++ b/src/net/include/redis_conn.h @@ -7,31 +7,24 @@ #define NET_INCLUDE_REDIS_CONN_H_ #include -#include #include +#include -#include "pstd/include/pstd_status.h" -#include "net/include/net_define.h" #include "net/include/net_conn.h" +#include "net/include/net_define.h" #include "net/include/redis_parser.h" +#include "pstd/include/pstd_status.h" namespace net { typedef std::vector RedisCmdArgsType; -enum HandleType { - kSynchronous, - kAsynchronous -}; +enum HandleType { kSynchronous, kAsynchronous }; -class RedisConn: public NetConn { +class RedisConn : public NetConn { public: - RedisConn(const int fd, - const std::string& ip_port, - Thread* thread, - NetMultiplexer* net_mpx = nullptr, - const HandleType& handle_type = kSynchronous, - const int rbuf_max_len = REDIS_MAX_MESSAGE); + RedisConn(const int fd, const std::string& ip_port, Thread* thread, NetMultiplexer* net_mpx = nullptr, + const HandleType& handle_type = kSynchronous, const int rbuf_max_len = REDIS_MAX_MESSAGE); virtual ~RedisConn(); ReadStatus GetRequest() override; diff --git a/src/net/include/redis_parser.h b/src/net/include/redis_parser.h index 136af23adf..ced6ff97ce 100644 --- a/src/net/include/redis_parser.h +++ b/src/net/include/redis_parser.h @@ -18,9 +18,9 @@ namespace net { class RedisParser; typedef std::vector RedisCmdArgsType; -typedef int (*RedisParserDataCb) (RedisParser*, const RedisCmdArgsType&); -typedef int (*RedisParserMultiDataCb) (RedisParser*, const std::vector&); -typedef int (*RedisParserCb) (RedisParser*); +typedef int (*RedisParserDataCb)(RedisParser*, const RedisCmdArgsType&); +typedef int (*RedisParserMultiDataCb)(RedisParser*, const std::vector&); +typedef int (*RedisParserCb)(RedisParser*); typedef int RedisParserType; enum RedisParserStatus { @@ -34,7 +34,7 @@ enum RedisParserStatus { enum RedisParserError { kRedisParserOk = 0, kRedisParserInitError = 1, - kRedisParserFullError = 2, // input overwhelm internal buffer + kRedisParserFullError = 2, // input overwhelm internal buffer kRedisParserProtoError = 3, kRedisParserDealError = 4, kRedisParserCompleteError = 5, @@ -54,13 +54,9 @@ class RedisParser { RedisParser(); RedisParserStatus RedisParserInit(RedisParserType type, const RedisParserSettings& settings); RedisParserStatus ProcessInputBuffer(const char* input_buf, int length, int* parsed_len); - long get_bulk_len() { - return bulk_len_; - } - RedisParserError get_error_code() { - return error_code_; - } - void *data; /* A pointer to get hook to the "connection" or "socket" object */ + long get_bulk_len() { return bulk_len_; } + RedisParserError get_error_code() { return error_code_; } + void* data; /* A pointer to get hook to the "connection" or "socket" object */ private: // for DEBUG void PrintCurrentStatus(); @@ -80,13 +76,13 @@ class RedisParser { RedisParserStatus status_code_; RedisParserError error_code_; - int redis_type_; // REDIS_REQ_INLINE or REDIS_REQ_MULTIBULK + int redis_type_; // REDIS_REQ_INLINE or REDIS_REQ_MULTIBULK long multibulk_len_; long bulk_len_; std::string half_argv_; - int redis_parser_type_; // REDIS_PARSER_REQUEST or REDIS_PARSER_RESPONSE + int redis_parser_type_; // REDIS_PARSER_REQUEST or REDIS_PARSER_RESPONSE RedisCmdArgsType argv_; std::vector argvs_; @@ -99,4 +95,3 @@ class RedisParser { } // namespace net #endif // NET_INCLUDE_REDIS_PARSER_H_ - diff --git a/src/net/include/server_thread.h b/src/net/include/server_thread.h index 9c23629831..3c44880211 100644 --- a/src/net/include/server_thread.h +++ b/src/net/include/server_thread.h @@ -6,25 +6,28 @@ #ifndef NET_INCLUDE_SERVER_THREAD_H_ #define NET_INCLUDE_SERVER_THREAD_H_ -#include -#include #include +#include #include +#include #ifdef __ENABLE_SSL -#include -#include -#include +# include +# include +# include #endif -#include "pstd/include/pstd_status.h" -#include "pstd/include/pstd_mutex.h" #include "net/include/net_define.h" #include "net/include/net_thread.h" #include "net/src/net_multiplexer.h" +#include "pstd/include/pstd_mutex.h" +#include "pstd/include/pstd_status.h" // remove 'unused parameter' warning -#define UNUSED(expr) do { (void)(expr); } while (0) +#define UNUSED(expr) \ + do { \ + (void)(expr); \ + } while (0) namespace net { @@ -108,11 +111,9 @@ const int kDefaultKeepAliveTime = 60; // (s) class ServerThread : public Thread { public: - ServerThread(int port, int cron_interval, const ServerHandle *handle); - ServerThread(const std::string& bind_ip, int port, int cron_interval, - const ServerHandle *handle); - ServerThread(const std::set& bind_ips, int port, - int cron_interval, const ServerHandle *handle); + ServerThread(int port, int cron_interval, const ServerHandle* handle); + ServerThread(const std::string& bind_ip, int port, int cron_interval, const ServerHandle* handle); + ServerThread(const std::set& bind_ips, int port, int cron_interval, const ServerHandle* handle); #ifdef __ENABLE_SSL /* @@ -153,7 +154,7 @@ class ServerThread : public Thread { virtual void HandleNewConn(int connfd, const std::string& ip_port) = 0; - virtual void SetQueueLimit(int queue_limit) { } + virtual void SetQueueLimit(int queue_limit) {} virtual ~ServerThread(); @@ -174,7 +175,7 @@ class ServerThread : public Thread { // process events in notify_queue virtual void ProcessNotifyEvents(const NetFiredEvent* pfe); - const ServerHandle *handle_; + const ServerHandle* handle_; bool own_handle_; #ifdef __ENABLE_SSL @@ -191,37 +192,25 @@ class ServerThread : public Thread { std::set server_fds_; virtual int InitHandle(); - virtual void *ThreadMain() override; + virtual void* ThreadMain() override; /* * The server event handle */ - virtual void HandleConnEvent(NetFiredEvent *pfe) = 0; + virtual void HandleConnEvent(NetFiredEvent* pfe) = 0; }; // !!!Attention: If u use this constructor, the keepalive_timeout_ will // be equal to kDefaultKeepAliveTime(60s). In master-slave mode, the slave // binlog receiver will close the binlog sync connection in HolyThread::DoCronTask // if master did not send data in kDefaultKeepAliveTime. -extern ServerThread *NewHolyThread( - int port, - ConnFactory *conn_factory, - int cron_interval = 0, - const ServerHandle* handle = nullptr); -extern ServerThread *NewHolyThread( - const std::string &bind_ip, int port, - ConnFactory *conn_factory, - int cron_interval = 0, - const ServerHandle* handle = nullptr); -extern ServerThread *NewHolyThread( - const std::set& bind_ips, int port, - ConnFactory *conn_factory, - int cron_interval = 0, - const ServerHandle* handle = nullptr); -extern ServerThread *NewHolyThread( - const std::set& bind_ips, int port, - ConnFactory *conn_factory, bool async, - int cron_interval = 0, - const ServerHandle* handle = nullptr); +extern ServerThread* NewHolyThread(int port, ConnFactory* conn_factory, int cron_interval = 0, + const ServerHandle* handle = nullptr); +extern ServerThread* NewHolyThread(const std::string& bind_ip, int port, ConnFactory* conn_factory, + int cron_interval = 0, const ServerHandle* handle = nullptr); +extern ServerThread* NewHolyThread(const std::set& bind_ips, int port, ConnFactory* conn_factory, + int cron_interval = 0, const ServerHandle* handle = nullptr); +extern ServerThread* NewHolyThread(const std::set& bind_ips, int port, ConnFactory* conn_factory, + bool async, int cron_interval = 0, const ServerHandle* handle = nullptr); /** * This type Dispatch thread just get Connection and then Dispatch the fd to @@ -236,21 +225,14 @@ extern ServerThread *NewHolyThread( * @param handle the server's handle (e.g. CronHandle, AccessHandle...) * @param ehandle the worker's enviroment setting handle */ -extern ServerThread *NewDispatchThread( - int port, - int work_num, ConnFactory* conn_factory, - int cron_interval = 0, int queue_limit = 1000, - const ServerHandle* handle = nullptr); -extern ServerThread *NewDispatchThread( - const std::string &ip, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval = 0, int queue_limit = 1000, - const ServerHandle* handle = nullptr); -extern ServerThread *NewDispatchThread( - const std::set& ips, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval = 0, int queue_limit = 1000, - const ServerHandle* handle = nullptr); +extern ServerThread* NewDispatchThread(int port, int work_num, ConnFactory* conn_factory, int cron_interval = 0, + int queue_limit = 1000, const ServerHandle* handle = nullptr); +extern ServerThread* NewDispatchThread(const std::string& ip, int port, int work_num, ConnFactory* conn_factory, + int cron_interval = 0, int queue_limit = 1000, + const ServerHandle* handle = nullptr); +extern ServerThread* NewDispatchThread(const std::set& ips, int port, int work_num, + ConnFactory* conn_factory, int cron_interval = 0, int queue_limit = 1000, + const ServerHandle* handle = nullptr); } // namespace net #endif // NET_INCLUDE_SERVER_THREAD_H_ diff --git a/src/net/include/simple_http_conn.h b/src/net/include/simple_http_conn.h index cded93cf7b..cd529f8ad7 100644 --- a/src/net/include/simple_http_conn.h +++ b/src/net/include/simple_http_conn.h @@ -7,8 +7,8 @@ #define NET_INCLUDE_SIMPLE_HTTP_CONN_H_ #include -#include #include +#include #include "pstd/include/pstd_status.h" #include "pstd/include/xdebug.h" @@ -42,50 +42,28 @@ class Request { bool ParseBodyFromArray(const char* data, const int size); private: - enum ParseStatus { - kHeaderMethod, - kHeaderPath, - kHeaderVersion, - kHeaderParamKey, - kHeaderParamValue, - kBody - }; + enum ParseStatus { kHeaderMethod, kHeaderPath, kHeaderVersion, kHeaderParamKey, kHeaderParamValue, kBody }; bool ParseGetUrl(); - bool ParseHeadLine( - const char* data, int line_start, - int line_end, ParseStatus* parseStatus); - bool ParseParameters( - const std::string data, - size_t line_start = 0, - bool from_url = true); + bool ParseHeadLine(const char* data, int line_start, int line_end, ParseStatus* parseStatus); + bool ParseParameters(const std::string data, size_t line_start = 0, bool from_url = true); }; class Response { public: - Response(): - status_code_(0) { - } + Response() : status_code_(0) {} void Clear(); int SerializeHeaderToArray(char* data, size_t size); - int SerializeBodyToArray(char* data, size_t size, int *pos); - bool HasMoreBody(size_t pos) { - return pos < body_.size(); - } + int SerializeBodyToArray(char* data, size_t size, int* pos); + bool HasMoreBody(size_t pos) { return pos < body_.size(); } void SetStatusCode(int code); - void SetHeaders(const std::string &key, const std::string &value) { - headers_[key] = value; - } + void SetHeaders(const std::string& key, const std::string& value) { headers_[key] = value; } - void SetHeaders(const std::string &key, const int value) { - headers_[key] = std::to_string(value); - } + void SetHeaders(const std::string& key, const int value) { headers_[key] = std::to_string(value); } - void SetBody(const std::string &body) { - body_.assign(body); - } + void SetBody(const std::string& body) { body_.assign(body); } private: int status_code_; @@ -94,12 +72,9 @@ class Response { std::string body_; }; -class SimpleHTTPConn: public NetConn { +class SimpleHTTPConn : public NetConn { public: - SimpleHTTPConn( - const int fd, - const std::string &ip_port, - Thread *thread); + SimpleHTTPConn(const int fd, const std::string& ip_port, Thread* thread); virtual ~SimpleHTTPConn(); virtual ReadStatus GetRequest() override; diff --git a/src/net/include/thread_pool.h b/src/net/include/thread_pool.h index fe62e18008..f2cf26c0a2 100644 --- a/src/net/include/thread_pool.h +++ b/src/net/include/thread_pool.h @@ -6,63 +6,55 @@ #ifndef NET_INCLUDE_THREAD_POOL_H_ #define NET_INCLUDE_THREAD_POOL_H_ -#include -#include -#include #include +#include +#include +#include -#include "pstd/include/pstd_mutex.h" #include "net/include/net_define.h" +#include "pstd/include/pstd_mutex.h" namespace net { typedef void (*TaskFunc)(void*); struct Task { - TaskFunc func; - void* arg; - Task (TaskFunc _func, void* _arg) - : func(_func), arg(_arg) {} + TaskFunc func; + void* arg; + Task(TaskFunc _func, void* _arg) : func(_func), arg(_arg) {} }; struct TimeTask { uint64_t exec_time; TaskFunc func; void* arg; - TimeTask(uint64_t _exec_time, TaskFunc _func, void* _arg) : - exec_time(_exec_time), - func(_func), - arg(_arg) {} - bool operator < (const TimeTask& task) const { - return exec_time > task.exec_time; - } + TimeTask(uint64_t _exec_time, TaskFunc _func, void* _arg) : exec_time(_exec_time), func(_func), arg(_arg) {} + bool operator<(const TimeTask& task) const { return exec_time > task.exec_time; } }; class ThreadPool { - public: class Worker { - public: - explicit Worker(ThreadPool* tp) : start_(false), thread_pool_(tp) {}; - static void* WorkerMain(void* arg); - - int start(); - int stop(); - private: - pthread_t thread_id_; - std::atomic start_; - ThreadPool* const thread_pool_; - std::string worker_name_; - /* - * No allowed copy and copy assign - */ - Worker(const Worker&); - void operator=(const Worker&); + public: + explicit Worker(ThreadPool* tp) : start_(false), thread_pool_(tp){}; + static void* WorkerMain(void* arg); + + int start(); + int stop(); + + private: + pthread_t thread_id_; + std::atomic start_; + ThreadPool* const thread_pool_; + std::string worker_name_; + /* + * No allowed copy and copy assign + */ + Worker(const Worker&); + void operator=(const Worker&); }; - explicit ThreadPool(size_t worker_num, - size_t max_queue_size, - const std::string& thread_pool_name = "ThreadPool"); + explicit ThreadPool(size_t worker_num, size_t max_queue_size, const std::string& thread_pool_name = "ThreadPool"); virtual ~ThreadPool(); int start_thread_pool(); diff --git a/src/net/src/backend_thread.cc b/src/net/src/backend_thread.cc index 51973b4a91..f56ba2e6b9 100644 --- a/src/net/src/backend_thread.cc +++ b/src/net/src/backend_thread.cc @@ -6,23 +6,24 @@ #include "net/include/backend_thread.h" #include -#include #include -#include -#include #include #include +#include +#include +#include -#include "pstd/include/xdebug.h" -#include "pstd/include/pstd_string.h" -#include "net/src/server_socket.h" #include "net/include/net_conn.h" +#include "net/src/server_socket.h" +#include "pstd/include/pstd_string.h" +#include "pstd/include/xdebug.h" namespace net { using pstd::Status; -BackendThread::BackendThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, BackendHandle* handle, void* private_data) +BackendThread::BackendThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, BackendHandle* handle, + void* private_data) : keepalive_timeout_(keepalive_timeout), cron_interval_(cron_interval), handle_(handle), @@ -33,8 +34,7 @@ BackendThread::BackendThread(ConnFactory* conn_factory, int cron_interval, int k net_multiplexer_->Initialize(); } -BackendThread::~BackendThread() { -} +BackendThread::~BackendThread() {} int BackendThread::StartThread() { if (!handle_) { @@ -68,7 +68,7 @@ Status BackendThread::Write(const int fd, const std::string& msg) { pstd::MutexLock l(&mu_); if (conns_.find(fd) == conns_.end()) { return Status::Corruption(std::to_string(fd) + " cannot find !"); - } + } auto addr = conns_.find(fd)->second->ip_port(); if (!handle_->AccessHandle(addr)) { return Status::Corruption(addr + " is baned by user!"); @@ -92,7 +92,7 @@ Status BackendThread::Close(const int fd) { if (conns_.find(fd) == conns_.end()) { return Status::OK(); } - } + } NotifyClose(fd); return Status::OK(); } @@ -131,10 +131,10 @@ void BackendThread::AddConnection(const std::string& peer_ip, int peer_port, int { pstd::MutexLock l(&mu_); conns_.insert(std::make_pair(sockfd, tc)); - } + } } -Status BackendThread::Connect(const std::string& dst_ip, const int dst_port, int *fd) { +Status BackendThread::Connect(const std::string& dst_ip, const int dst_port, int* fd) { Status s; int sockfd = -1; int rv; @@ -153,8 +153,7 @@ Status BackendThread::Connect(const std::string& dst_ip, const int dst_port, int return Status::IOError("connect getaddrinfo error for ", dst_ip); } for (p = servinfo; p != NULL; p = p->ai_next) { - if ((sockfd = socket( - p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { + if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } int flags = fcntl(sockfd, F_GETFL, 0); @@ -164,9 +163,7 @@ Status BackendThread::Connect(const std::string& dst_ip, const int dst_port, int if (errno == EHOSTUNREACH) { CloseFd(sockfd); continue; - } else if (errno == EINPROGRESS || - errno == EAGAIN || - errno == EWOULDBLOCK) { + } else if (errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK) { AddConnection(dst_ip, dst_port, sockfd); SetWaitConnectOnEpoll(sockfd); freeaddrinfo(servinfo); @@ -175,8 +172,7 @@ Status BackendThread::Connect(const std::string& dst_ip, const int dst_port, int } else { CloseFd(sockfd); freeaddrinfo(servinfo); - return Status::IOError("EHOSTUNREACH", - "The target host cannot be reached"); + return Status::IOError("EHOSTUNREACH", "The target host cannot be reached"); } } @@ -184,7 +180,7 @@ Status BackendThread::Connect(const std::string& dst_ip, const int dst_port, int net_multiplexer_->NetAddEvent(sockfd, kReadable | kWritable); struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); - getsockname(sockfd, (struct sockaddr*) &laddr, &llen); + getsockname(sockfd, (struct sockaddr*)&laddr, &llen); std::string lip(inet_ntoa(laddr.sin_addr)); int lport = ntohs(laddr.sin_port); if (dst_ip == lip && dst_port == lport) { @@ -209,11 +205,10 @@ Status BackendThread::Connect(const std::string& dst_ip, const int dst_port, int std::shared_ptr BackendThread::GetConn(int fd) { pstd::MutexLock l(&mu_); auto iter = conns_.find(fd); - if(iter == conns_.end()) { + if (iter == conns_.end()) { return nullptr; } return iter->second; - } void BackendThread::CloseFd(std::shared_ptr conn) { @@ -243,8 +238,7 @@ void BackendThread::DoCronTask() { std::shared_ptr conn = iter->second; // Check keepalive timeout connection - if (keepalive_timeout_ > 0 && - (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { + if (keepalive_timeout_ > 0 && (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { log_info("Do cron task del fd %d\n", conn->fd()); net_multiplexer_->NetDelEvent(conn->fd(), 0); close(conn->fd()); @@ -264,23 +258,22 @@ void BackendThread::DoCronTask() { ++iter; } - } void BackendThread::InternalDebugPrint() { log_info("___________________________________\n"); { - pstd::MutexLock l(&mu_); - log_info("To send map: \n"); - for (const auto& to_send : to_send_) { - UNUSED(to_send); - const std::vector& tmp = to_send.second; - for (const auto& tmp_to_send : tmp) { - UNUSED(tmp_to_send); - log_info("%s %s\n", to_send.first.c_str(), tmp_to_send.c_str()); + pstd::MutexLock l(&mu_); + log_info("To send map: \n"); + for (const auto& to_send : to_send_) { + UNUSED(to_send); + const std::vector& tmp = to_send.second; + for (const auto& tmp_to_send : tmp) { + UNUSED(tmp_to_send); + log_info("%s %s\n", to_send.first.c_str(), tmp_to_send.c_str()); + } } } - } log_info("Connected fd map: \n"); pstd::MutexLock l(&mu_); for (const auto& fd_conn : conns_) { @@ -326,23 +319,23 @@ void BackendThread::ProcessNotifyEvents(const NetFiredEvent* pfe) { pstd::MutexLock l(&mu_); if (ti.notify_type() == kNotiWrite) { if (conns_.find(fd) == conns_.end()) { - //TODO: need clean and notify? + // TODO: need clean and notify? continue; } else { // connection exist net_multiplexer_->NetModEvent(fd, 0, kReadable | kWritable); } { - auto iter = to_send_.find(fd); - if (iter == to_send_.end()) { - continue; - } - // get msg from to_send_ - std::vector& msgs = iter->second; - for (auto& msg : msgs) { - conns_[fd]->WriteResp(msg); - } - to_send_.erase(iter); + auto iter = to_send_.find(fd); + if (iter == to_send_.end()) { + continue; + } + // get msg from to_send_ + std::vector& msgs = iter->second; + for (auto& msg : msgs) { + conns_[fd]->WriteResp(msg); + } + to_send_.erase(iter); } } else if (ti.notify_type() == kNotiClose) { log_info("received kNotiClose\n"); @@ -356,9 +349,9 @@ void BackendThread::ProcessNotifyEvents(const NetFiredEvent* pfe) { } } -void *BackendThread::ThreadMain() { +void* BackendThread::ThreadMain() { int nfds = 0; - NetFiredEvent *pfe = NULL; + NetFiredEvent* pfe = NULL; struct timeval when; gettimeofday(&when, NULL); @@ -376,10 +369,8 @@ void *BackendThread::ThreadMain() { while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, nullptr); - if (when.tv_sec > now.tv_sec || - (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { - timeout = (when.tv_sec - now.tv_sec) * 1000 + - (when.tv_usec - now.tv_usec) / 1000; + if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { + timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { // do user defined cron handle_->CronHandle(); @@ -391,7 +382,7 @@ void *BackendThread::ThreadMain() { } } //{ - //InternalDebugPrint(); + // InternalDebugPrint(); //} nfds = net_multiplexer_->NetPoll(timeout); for (int i = 0; i < nfds; i++) { @@ -452,7 +443,7 @@ void *BackendThread::ThreadMain() { } } - if ((pfe->mask & kErrorEvent) || should_close) { + if ((pfe->mask & kErrorEvent) || should_close) { { log_info("close connection %d reason %d %d\n", pfe->fd, pfe->mask, should_close); net_multiplexer_->NetDelEvent(pfe->fd, 0); diff --git a/src/net/src/bg_thread.cc b/src/net/src/bg_thread.cc index 6089b83233..33c5e82fff 100644 --- a/src/net/src/bg_thread.cc +++ b/src/net/src/bg_thread.cc @@ -54,7 +54,7 @@ void BGThread::SwallowReadyTasks() { gettimeofday(&now, NULL); uint64_t unow = now.tv_sec * 1000000 + now.tv_usec; mu_.Lock(); - while(!timer_queue_.empty()) { + while (!timer_queue_.empty()) { TimerItem top_item = timer_queue_.top(); if (unow / 1000 < top_item.exec_time / 1000) { break; @@ -70,7 +70,7 @@ void BGThread::SwallowReadyTasks() { mu_.Unlock(); } -void *BGThread::ThreadMain() { +void* BGThread::ThreadMain() { while (!should_stop()) { mu_.Lock(); while (queue_.empty() && timer_queue_.empty() && !should_stop()) { @@ -94,8 +94,7 @@ void *BGThread::ThreadMain() { (*function)(arg); continue; } else if (queue_.empty() && !should_stop()) { - rsignal_.TimedWait( - static_cast((timer_item.exec_time - unow) / 1000)); + rsignal_.TimedWait(static_cast((timer_item.exec_time - unow) / 1000)); mu_.Unlock(); continue; } @@ -117,8 +116,7 @@ void *BGThread::ThreadMain() { /* * timeout is in millisecond */ -void BGThread::DelaySchedule( - uint64_t timeout, void (*function)(void *), void* arg) { +void BGThread::DelaySchedule(uint64_t timeout, void (*function)(void*), void* arg) { /* * pthread_cond_timedwait api use absolute API * so we need gettimeofday + timeout diff --git a/src/net/src/client_thread.cc b/src/net/src/client_thread.cc index 3ccc8d07f1..2945e75922 100644 --- a/src/net/src/client_thread.cc +++ b/src/net/src/client_thread.cc @@ -6,23 +6,24 @@ #include "net/include/client_thread.h" #include -#include #include -#include -#include #include #include +#include +#include +#include -#include "pstd/include/xdebug.h" -#include "pstd/include/pstd_string.h" -#include "net/src/server_socket.h" #include "net/include/net_conn.h" +#include "net/src/server_socket.h" +#include "pstd/include/pstd_string.h" +#include "pstd/include/xdebug.h" namespace net { using pstd::Status; -ClientThread::ClientThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, ClientHandle* handle, void* private_data) +ClientThread::ClientThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, ClientHandle* handle, + void* private_data) : keepalive_timeout_(keepalive_timeout), cron_interval_(cron_interval), handle_(handle), @@ -33,8 +34,7 @@ ClientThread::ClientThread(ConnFactory* conn_factory, int cron_interval, int kee net_multiplexer_->Initialize(); } -ClientThread::~ClientThread() { -} +ClientThread::~ClientThread() {} int ClientThread::StartThread() { if (!handle_) { @@ -69,15 +69,15 @@ Status ClientThread::Write(const std::string& ip, const int port, const std::str return Status::Corruption(ip_port + " is baned by user!"); } { - pstd::MutexLock l(&mu_); - size_t size = 0; - for (auto& str : to_send_[ip_port]) { - size += str.size(); - } - if (size > kConnWriteBuf) { - return Status::Corruption("Connection buffer over maximum size"); - } - to_send_[ip_port].push_back(msg); + pstd::MutexLock l(&mu_); + size_t size = 0; + for (auto& str : to_send_[ip_port]) { + size += str.size(); + } + if (size > kConnWriteBuf) { + return Status::Corruption("Connection buffer over maximum size"); + } + to_send_[ip_port].push_back(msg); } NotifyWrite(ip_port); return Status::OK(); @@ -85,8 +85,8 @@ Status ClientThread::Write(const std::string& ip, const int port, const std::str Status ClientThread::Close(const std::string& ip, const int port) { { - pstd::MutexLock l(&to_del_mu_); - to_del_.push_back(ip + ":" + std::to_string(port)); + pstd::MutexLock l(&to_del_mu_); + to_del_.push_back(ip + ":" + std::to_string(port)); } return Status::OK(); } @@ -142,8 +142,7 @@ Status ClientThread::ScheduleConnect(const std::string& dst_ip, int dst_port) { return Status::IOError("connect getaddrinfo error for ", dst_ip); } for (p = servinfo; p != NULL; p = p->ai_next) { - if ((sockfd = socket( - p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { + if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } int flags = fcntl(sockfd, F_GETFL, 0); @@ -153,9 +152,7 @@ Status ClientThread::ScheduleConnect(const std::string& dst_ip, int dst_port) { if (errno == EHOSTUNREACH) { CloseFd(sockfd, dst_ip + ":" + std::to_string(dst_port)); continue; - } else if (errno == EINPROGRESS || - errno == EAGAIN || - errno == EWOULDBLOCK) { + } else if (errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK) { NewConnection(dst_ip, dst_port, sockfd); SetWaitConnectOnEpoll(sockfd); freeaddrinfo(servinfo); @@ -163,8 +160,7 @@ Status ClientThread::ScheduleConnect(const std::string& dst_ip, int dst_port) { } else { CloseFd(sockfd, dst_ip + ":" + std::to_string(dst_port)); freeaddrinfo(servinfo); - return Status::IOError("EHOSTUNREACH", - "The target host cannot be reached"); + return Status::IOError("EHOSTUNREACH", "The target host cannot be reached"); } } @@ -172,7 +168,7 @@ Status ClientThread::ScheduleConnect(const std::string& dst_ip, int dst_port) { net_multiplexer_->NetAddEvent(sockfd, kReadable | kWritable); struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); - getsockname(sockfd, (struct sockaddr*) &laddr, &llen); + getsockname(sockfd, (struct sockaddr*)&laddr, &llen); std::string lip(inet_ntoa(laddr.sin_addr)); int lport = ntohs(laddr.sin_port); if (dst_ip == lip && dst_port == lport) { @@ -219,8 +215,7 @@ void ClientThread::DoCronTask() { std::shared_ptr conn = iter->second; // Check keepalive timeout connection - if (keepalive_timeout_ > 0 && - (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { + if (keepalive_timeout_ > 0 && (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { log_info("Do cron task del fd %d\n", conn->fd()); net_multiplexer_->NetDelEvent(conn->fd(), 0); // did not clean up content in to_send queue @@ -267,17 +262,17 @@ void ClientThread::DoCronTask() { void ClientThread::InternalDebugPrint() { log_info("___________________________________\n"); { - pstd::MutexLock l(&mu_); - log_info("To send map: \n"); - for (const auto& to_send : to_send_) { - UNUSED(to_send); - const std::vector& tmp = to_send.second; - for (const auto& tmp_to_send : tmp) { - UNUSED(tmp_to_send); - log_info("%s %s\n", to_send.first.c_str(), tmp_to_send.c_str()); + pstd::MutexLock l(&mu_); + log_info("To send map: \n"); + for (const auto& to_send : to_send_) { + UNUSED(to_send); + const std::vector& tmp = to_send.second; + for (const auto& tmp_to_send : tmp) { + UNUSED(tmp_to_send); + log_info("%s %s\n", to_send.first.c_str(), tmp_to_send.c_str()); + } } } - } log_info("Ipport conn map: \n"); for (const auto& ipport_conn : ipport_conns_) { UNUSED(ipport_conn); @@ -303,7 +298,6 @@ void ClientThread::NotifyWrite(const std::string ip_port) { net_multiplexer_->Register(ti, true); } - void ClientThread::ProcessNotifyEvents(const NetFiredEvent* pfe) { if (pfe->mask & kReadable) { char bb[2048]; @@ -334,20 +328,20 @@ void ClientThread::ProcessNotifyEvents(const NetFiredEvent* pfe) { net_multiplexer_->NetModEvent(ipport_conns_[ip_port]->fd(), 0, kReadable | kWritable); } { - pstd::MutexLock l(&mu_); - auto iter = to_send_.find(ip_port); - if (iter == to_send_.end()) { - continue; - } - // get msg from to_send_ - std::vector& msgs = iter->second; - for (auto& msg : msgs) { - if (ipport_conns_[ip_port]->WriteResp(msg)) { - to_send_[ip_port].push_back(msg); - NotifyWrite(ip_port); + pstd::MutexLock l(&mu_); + auto iter = to_send_.find(ip_port); + if (iter == to_send_.end()) { + continue; } - } - to_send_.erase(iter); + // get msg from to_send_ + std::vector& msgs = iter->second; + for (auto& msg : msgs) { + if (ipport_conns_[ip_port]->WriteResp(msg)) { + to_send_[ip_port].push_back(msg); + NotifyWrite(ip_port); + } + } + to_send_.erase(iter); } } else if (ti.notify_type() == kNotiClose) { log_info("received kNotiClose\n"); @@ -362,9 +356,9 @@ void ClientThread::ProcessNotifyEvents(const NetFiredEvent* pfe) { } } -void *ClientThread::ThreadMain() { +void* ClientThread::ThreadMain() { int nfds = 0; - NetFiredEvent *pfe = NULL; + NetFiredEvent* pfe = NULL; struct timeval when; gettimeofday(&when, NULL); @@ -382,10 +376,8 @@ void *ClientThread::ThreadMain() { while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, nullptr); - if (when.tv_sec > now.tv_sec || - (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { - timeout = (when.tv_sec - now.tv_sec) * 1000 + - (when.tv_usec - now.tv_usec) / 1000; + if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { + timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { // do user defined cron handle_->CronHandle(); @@ -397,7 +389,7 @@ void *ClientThread::ThreadMain() { } } //{ - //InternalDebugPrint(); + // InternalDebugPrint(); //} nfds = net_multiplexer_->NetPoll(timeout); for (int i = 0; i < nfds; i++) { diff --git a/src/net/src/dispatch_thread.cc b/src/net/src/dispatch_thread.cc index 2b25cb1899..d5ab3e26da 100644 --- a/src/net/src/dispatch_thread.cc +++ b/src/net/src/dispatch_thread.cc @@ -13,42 +13,36 @@ namespace net { -DispatchThread::DispatchThread(int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, int queue_limit, +DispatchThread::DispatchThread(int port, int work_num, ConnFactory* conn_factory, int cron_interval, int queue_limit, const ServerHandle* handle) - : ServerThread::ServerThread(port, cron_interval, handle), - last_thread_(0), - work_num_(work_num), - queue_limit_(queue_limit) { + : ServerThread::ServerThread(port, cron_interval, handle), + last_thread_(0), + work_num_(work_num), + queue_limit_(queue_limit) { worker_thread_ = new WorkerThread*[work_num_]; for (int i = 0; i < work_num_; i++) { worker_thread_[i] = new WorkerThread(conn_factory, this, queue_limit, cron_interval); } } -DispatchThread::DispatchThread(const std::string &ip, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, int queue_limit, - const ServerHandle* handle) - : ServerThread::ServerThread(ip, port, cron_interval, handle), - last_thread_(0), - work_num_(work_num), - queue_limit_(queue_limit) { +DispatchThread::DispatchThread(const std::string& ip, int port, int work_num, ConnFactory* conn_factory, + int cron_interval, int queue_limit, const ServerHandle* handle) + : ServerThread::ServerThread(ip, port, cron_interval, handle), + last_thread_(0), + work_num_(work_num), + queue_limit_(queue_limit) { worker_thread_ = new WorkerThread*[work_num_]; for (int i = 0; i < work_num_; i++) { worker_thread_[i] = new WorkerThread(conn_factory, this, queue_limit, cron_interval); } } -DispatchThread::DispatchThread(const std::set& ips, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, int queue_limit, - const ServerHandle* handle) - : ServerThread::ServerThread(ips, port, cron_interval, handle), - last_thread_(0), - work_num_(work_num), - queue_limit_(queue_limit) { +DispatchThread::DispatchThread(const std::set& ips, int port, int work_num, ConnFactory* conn_factory, + int cron_interval, int queue_limit, const ServerHandle* handle) + : ServerThread::ServerThread(ips, port, cron_interval, handle), + last_thread_(0), + work_num_(work_num), + queue_limit_(queue_limit) { worker_thread_ = new WorkerThread*[work_num_]; for (int i = 0; i < work_num_; i++) { worker_thread_[i] = new WorkerThread(conn_factory, this, queue_limit, cron_interval); @@ -64,8 +58,7 @@ DispatchThread::~DispatchThread() { int DispatchThread::StartThread() { for (int i = 0; i < work_num_; i++) { - int ret = handle_->CreateWorkerSpecificData( - &(worker_thread_[i]->private_data_)); + int ret = handle_->CreateWorkerSpecificData(&(worker_thread_[i]->private_data_)); if (ret != 0) { return ret; } @@ -119,10 +112,7 @@ std::vector DispatchThread::conns_info() const { std::vector result; for (int i = 0; i < work_num_; ++i) { const auto worker_conns_info = worker_thread_[i]->conns_info(); - result.insert( - result.end(), - worker_conns_info.begin(), - worker_conns_info.end()); + result.insert(result.end(), worker_conns_info.begin(), worker_conns_info.end()); } return result; } @@ -154,12 +144,9 @@ bool DispatchThread::KillConn(const std::string& ip_port) { return result; } -void DispatchThread::KillAllConns() { - KillConn(kKillAllConnsTask); -} +void DispatchThread::KillAllConns() { KillConn(kKillAllConnsTask); } -void DispatchThread::HandleNewConn( - const int connfd, const std::string& ip_port) { +void DispatchThread::HandleNewConn(const int connfd, const std::string& ip_port) { // Slow workers may consume many fds. // We simply loop to find next legal worker. NetItem ti(connfd, ip_port); @@ -170,8 +157,7 @@ void DispatchThread::HandleNewConn( find = worker_thread->MoveConnIn(ti, false); if (find) { last_thread_ = (next_thread + 1) % work_num_; - log_info("find worker(%d), refresh the last_thread_ to %d", - next_thread, last_thread_); + log_info("find worker(%d), refresh the last_thread_ to %d", next_thread, last_thread_); break; } next_thread = (next_thread + 1) % work_num_; @@ -185,33 +171,20 @@ void DispatchThread::HandleNewConn( } } -void DispatchThread::SetQueueLimit(int queue_limit) { - queue_limit_ = queue_limit; -} - -extern ServerThread *NewDispatchThread( - int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, int queue_limit, - const ServerHandle* handle) { - return new DispatchThread(port, work_num, conn_factory, - cron_interval, queue_limit, handle); -} -extern ServerThread *NewDispatchThread( - const std::string &ip, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, int queue_limit, - const ServerHandle* handle) { - return new DispatchThread(ip, port, work_num, conn_factory, - cron_interval, queue_limit, handle); -} -extern ServerThread *NewDispatchThread( - const std::set& ips, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, int queue_limit, - const ServerHandle* handle) { - return new DispatchThread(ips, port, work_num, conn_factory, - cron_interval, queue_limit, handle); +void DispatchThread::SetQueueLimit(int queue_limit) { queue_limit_ = queue_limit; } + +extern ServerThread* NewDispatchThread(int port, int work_num, ConnFactory* conn_factory, int cron_interval, + int queue_limit, const ServerHandle* handle) { + return new DispatchThread(port, work_num, conn_factory, cron_interval, queue_limit, handle); +} +extern ServerThread* NewDispatchThread(const std::string& ip, int port, int work_num, ConnFactory* conn_factory, + int cron_interval, int queue_limit, const ServerHandle* handle) { + return new DispatchThread(ip, port, work_num, conn_factory, cron_interval, queue_limit, handle); +} +extern ServerThread* NewDispatchThread(const std::set& ips, int port, int work_num, + ConnFactory* conn_factory, int cron_interval, int queue_limit, + const ServerHandle* handle) { + return new DispatchThread(ips, port, work_num, conn_factory, cron_interval, queue_limit, handle); } }; // namespace net diff --git a/src/net/src/dispatch_thread.h b/src/net/src/dispatch_thread.h index eea2d83058..a3887b3ae2 100644 --- a/src/net/src/dispatch_thread.h +++ b/src/net/src/dispatch_thread.h @@ -6,15 +6,15 @@ #ifndef NET_SRC_DISPATCH_THREAD_H_ #define NET_SRC_DISPATCH_THREAD_H_ -#include #include #include +#include #include #include -#include "pstd/include/xdebug.h" -#include "net/include/server_thread.h" #include "net/include/net_conn.h" +#include "net/include/server_thread.h" +#include "pstd/include/xdebug.h" namespace net { @@ -24,21 +24,12 @@ class WorkerThread; class DispatchThread : public ServerThread { public: - DispatchThread(int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, - int queue_limit, - const ServerHandle* handle); - DispatchThread(const std::string &ip, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, - int queue_limit, - const ServerHandle* handle); - DispatchThread(const std::set& ips, int port, - int work_num, ConnFactory* conn_factory, - int cron_interval, - int queue_limit, + DispatchThread(int port, int work_num, ConnFactory* conn_factory, int cron_interval, int queue_limit, const ServerHandle* handle); + DispatchThread(const std::string& ip, int port, int work_num, ConnFactory* conn_factory, int cron_interval, + int queue_limit, const ServerHandle* handle); + DispatchThread(const std::set& ips, int port, int work_num, ConnFactory* conn_factory, int cron_interval, + int queue_limit, const ServerHandle* handle); virtual ~DispatchThread(); @@ -63,6 +54,7 @@ class DispatchThread : public ServerThread { void HandleNewConn(const int connfd, const std::string& ip_port) override; void SetQueueLimit(int queue_limit) override; + private: /* * Here we used auto poll to find the next work thread, @@ -77,9 +69,7 @@ class DispatchThread : public ServerThread { int queue_limit_; std::map localdata_; - void HandleConnEvent(NetFiredEvent *pfe) override { - UNUSED(pfe); - } + void HandleConnEvent(NetFiredEvent* pfe) override { UNUSED(pfe); } // No copying allowed DispatchThread(const DispatchThread&); diff --git a/src/net/src/holy_thread.cc b/src/net/src/holy_thread.cc index d35a9a1aee..97d82fd36c 100644 --- a/src/net/src/holy_thread.cc +++ b/src/net/src/holy_thread.cc @@ -7,42 +7,29 @@ #include "net/src/holy_thread.h" -#include "net/src/net_multiplexer.h" -#include "net/src/net_item.h" #include "net/include/net_conn.h" +#include "net/src/net_item.h" +#include "net/src/net_multiplexer.h" #include "pstd/include/xdebug.h" namespace net { -HolyThread::HolyThread(int port, - ConnFactory* conn_factory, - int cron_interval, const ServerHandle* handle, bool async) +HolyThread::HolyThread(int port, ConnFactory* conn_factory, int cron_interval, const ServerHandle* handle, bool async) : ServerThread::ServerThread(port, cron_interval, handle), conn_factory_(conn_factory), private_data_(nullptr), keepalive_timeout_(kDefaultKeepAliveTime), - async_(async) { -} + async_(async) {} -HolyThread::HolyThread(const std::string& bind_ip, int port, - ConnFactory* conn_factory, - int cron_interval, const ServerHandle* handle, bool async) - : ServerThread::ServerThread(bind_ip, port, cron_interval, handle), - conn_factory_(conn_factory), - async_(async) { -} +HolyThread::HolyThread(const std::string& bind_ip, int port, ConnFactory* conn_factory, int cron_interval, + const ServerHandle* handle, bool async) + : ServerThread::ServerThread(bind_ip, port, cron_interval, handle), conn_factory_(conn_factory), async_(async) {} -HolyThread::HolyThread(const std::set& bind_ips, int port, - ConnFactory* conn_factory, - int cron_interval, const ServerHandle* handle, bool async) - : ServerThread::ServerThread(bind_ips, port, cron_interval, handle), - conn_factory_(conn_factory), - async_(async) { -} +HolyThread::HolyThread(const std::set& bind_ips, int port, ConnFactory* conn_factory, int cron_interval, + const ServerHandle* handle, bool async) + : ServerThread::ServerThread(bind_ips, port, cron_interval, handle), conn_factory_(conn_factory), async_(async) {} -HolyThread::~HolyThread() { - Cleanup(); -} +HolyThread::~HolyThread() { Cleanup(); } int HolyThread::conn_num() const { pstd::ReadLock l(&rwlock_); @@ -53,11 +40,7 @@ std::vector HolyThread::conns_info() const { std::vector result; pstd::ReadLock l(&rwlock_); for (auto& conn : conns_) { - result.push_back({ - conn.first, - conn.second->ip_port(), - conn.second->last_interaction() - }); + result.push_back({conn.first, conn.second->ip_port(), conn.second->last_interaction()}); } return result; } @@ -104,9 +87,8 @@ int HolyThread::StopThread() { return ServerThread::StopThread(); } -void HolyThread::HandleNewConn(const int connfd, const std::string &ip_port) { - std::shared_ptr tc = conn_factory_->NewNetConn( - connfd, ip_port, this, private_data_, net_multiplexer_.get()); +void HolyThread::HandleNewConn(const int connfd, const std::string& ip_port) { + std::shared_ptr tc = conn_factory_->NewNetConn(connfd, ip_port, this, private_data_, net_multiplexer_.get()); tc->SetNonblock(); { pstd::WriteLock l(&rwlock_); @@ -116,7 +98,7 @@ void HolyThread::HandleNewConn(const int connfd, const std::string &ip_port) { net_multiplexer_->NetAddEvent(connfd, kReadable); } -void HolyThread::HandleConnEvent(NetFiredEvent *pfe) { +void HolyThread::HandleConnEvent(NetFiredEvent* pfe) { if (pfe == nullptr) { return; } @@ -138,7 +120,7 @@ void HolyThread::HandleConnEvent(NetFiredEvent *pfe) { gettimeofday(&now, nullptr); in_conn->set_last_interaction(now); if (read_status == kReadAll) { - // do nothing still watch EPOLLIN + // do nothing still watch EPOLLIN } else if (read_status == kReadHalf) { return; } else { @@ -227,9 +209,7 @@ void HolyThread::DoCronTask() { } // Check keepalive timeout connection - if (keepalive_timeout_ > 0 && - (now.tv_sec - conn->last_interaction().tv_sec > - keepalive_timeout_)) { + if (keepalive_timeout_ > 0 && (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { to_timeout.push_back(conn); iter = conns_.erase(iter); continue; @@ -268,9 +248,7 @@ void HolyThread::Cleanup() { } } -void HolyThread::KillAllConns() { - KillConn(kKillAllConnsTask); -} +void HolyThread::KillAllConns() { KillConn(kKillAllConnsTask); } bool HolyThread::KillConn(const std::string& ip_port) { bool find = false; @@ -323,28 +301,19 @@ void HolyThread::ProcessNotifyEvents(const net::NetFiredEvent* pfe) { } } -extern ServerThread *NewHolyThread( - int port, - ConnFactory *conn_factory, - int cron_interval, const ServerHandle* handle) { +extern ServerThread* NewHolyThread(int port, ConnFactory* conn_factory, int cron_interval, const ServerHandle* handle) { return new HolyThread(port, conn_factory, cron_interval, handle); } -extern ServerThread *NewHolyThread( - const std::string &bind_ip, int port, - ConnFactory *conn_factory, - int cron_interval, const ServerHandle* handle) { +extern ServerThread* NewHolyThread(const std::string& bind_ip, int port, ConnFactory* conn_factory, int cron_interval, + const ServerHandle* handle) { return new HolyThread(bind_ip, port, conn_factory, cron_interval, handle); } -extern ServerThread *NewHolyThread( - const std::set& bind_ips, int port, - ConnFactory *conn_factory, - int cron_interval, const ServerHandle* handle) { +extern ServerThread* NewHolyThread(const std::set& bind_ips, int port, ConnFactory* conn_factory, + int cron_interval, const ServerHandle* handle) { return new HolyThread(bind_ips, port, conn_factory, cron_interval, handle); } -extern ServerThread *NewHolyThread( - const std::set& bind_ips, int port, - ConnFactory *conn_factory, bool async, - int cron_interval, const ServerHandle* handle) { +extern ServerThread* NewHolyThread(const std::set& bind_ips, int port, ConnFactory* conn_factory, + bool async, int cron_interval, const ServerHandle* handle) { return new HolyThread(bind_ips, port, conn_factory, cron_interval, handle, async); } }; // namespace net diff --git a/src/net/src/holy_thread.h b/src/net/src/holy_thread.h index 9036e26885..25ed65118a 100644 --- a/src/net/src/holy_thread.h +++ b/src/net/src/holy_thread.h @@ -6,40 +6,36 @@ #ifndef NET_SRC_HOLY_THREAD_H_ #define NET_SRC_HOLY_THREAD_H_ +#include #include #include #include -#include #include -#include "pstd/include/xdebug.h" -#include "pstd/include/pstd_mutex.h" -#include "net/include/server_thread.h" #include "net/include/net_conn.h" +#include "net/include/server_thread.h" +#include "pstd/include/pstd_mutex.h" +#include "pstd/include/xdebug.h" namespace net { class NetConn; -class HolyThread: public ServerThread { +class HolyThread : public ServerThread { public: // This type thread thread will listen and work self list redis thread - HolyThread(int port, ConnFactory* conn_factory, - int cron_interval = 0, const ServerHandle* handle = nullptr, bool async = true); - HolyThread(const std::string& bind_ip, int port, - ConnFactory* conn_factory, - int cron_interval = 0, const ServerHandle* handle = nullptr, bool async = true); - HolyThread(const std::set& bind_ips, int port, - ConnFactory* conn_factory, - int cron_interval = 0, const ServerHandle* handle = nullptr, bool async = true); + HolyThread(int port, ConnFactory* conn_factory, int cron_interval = 0, const ServerHandle* handle = nullptr, + bool async = true); + HolyThread(const std::string& bind_ip, int port, ConnFactory* conn_factory, int cron_interval = 0, + const ServerHandle* handle = nullptr, bool async = true); + HolyThread(const std::set& bind_ips, int port, ConnFactory* conn_factory, int cron_interval = 0, + const ServerHandle* handle = nullptr, bool async = true); virtual ~HolyThread(); virtual int StartThread() override; virtual int StopThread() override; - virtual void set_keepalive_timeout(int timeout) override { - keepalive_timeout_ = timeout; - } + virtual void set_keepalive_timeout(int timeout) override { keepalive_timeout_ = timeout; } virtual int conn_num() const override; @@ -47,7 +43,7 @@ class HolyThread: public ServerThread { virtual std::shared_ptr MoveConnOut(int fd) override; - virtual void MoveConnIn(std::shared_ptr conn, const NotifyType& type) override { } + virtual void MoveConnIn(std::shared_ptr conn, const NotifyType& type) override {} virtual void KillAllConns() override; @@ -61,7 +57,7 @@ class HolyThread: public ServerThread { mutable pstd::RWMutex rwlock_; /* For external statistics */ std::map> conns_; - ConnFactory *conn_factory_; + ConnFactory* conn_factory_; void* private_data_; std::atomic keepalive_timeout_; // keepalive second @@ -72,13 +68,12 @@ class HolyThread: public ServerThread { pstd::Mutex killer_mutex_; std::set deleting_conn_ipport_; - void HandleNewConn(int connfd, const std::string &ip_port) override; - void HandleConnEvent(NetFiredEvent *pfe) override; + void HandleNewConn(int connfd, const std::string& ip_port) override; + void HandleConnEvent(NetFiredEvent* pfe) override; void CloseFd(std::shared_ptr conn); void Cleanup(); }; // class HolyThread - } // namespace net #endif // NET_SRC_HOLY_THREAD_H_ diff --git a/src/net/src/http_conn.cc b/src/net/src/http_conn.cc index 6bccd440e6..9f6f1ad9d5 100644 --- a/src/net/src/http_conn.cc +++ b/src/net/src/http_conn.cc @@ -3,16 +3,16 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "net/include/http_conn.h" -#include #include #include +#include -#include #include +#include -#include "pstd/include/xdebug.h" -#include "pstd/include/pstd_string.h" #include "net/include/net_define.h" +#include "pstd/include/pstd_string.h" +#include "pstd/include/xdebug.h" namespace net { @@ -20,41 +20,41 @@ static const uint32_t kHTTPMaxMessage = 1024 * 1024 * 8; static const uint32_t kHTTPMaxHeader = 1024 * 1024; static const std::map http_status_map = { - {100, "Continue"}, - {101, "Switching Protocols"}, - {102, "Processing"}, - - {200, "OK"}, - {201, "Created"}, - {202, "Accepted"}, - {203, "Non-Authoritative Information"}, - {204, "No Content"}, - {205, "Reset Content"}, - {206, "Partial Content"}, - {207, "Multi-Status"}, - - {400, "Bad Request"}, - {401, "Unauthorized"}, - {402, ""}, // reserve - {403, "Forbidden"}, - {404, "Not Found"}, - {405, "Method Not Allowed"}, - {406, "Not Acceptable"}, - {407, "Proxy Authentication Required"}, - {408, "Request Timeout"}, - {409, "Conflict"}, - {416, "Requested Range not satisfiable"}, - - {500, "Internal Server Error"}, - {501, "Not Implemented"}, - {502, "Bad Gateway"}, - {503, "Service Unavailable"}, - {504, "Gateway Timeout"}, - {505, "HTTP Version Not Supported"}, - {506, "Variant Also Negotiates"}, - {507, "Insufficient Storage"}, - {508, "Bandwidth Limit Exceeded"}, - {509, "Not Extended"}, + {100, "Continue"}, + {101, "Switching Protocols"}, + {102, "Processing"}, + + {200, "OK"}, + {201, "Created"}, + {202, "Accepted"}, + {203, "Non-Authoritative Information"}, + {204, "No Content"}, + {205, "Reset Content"}, + {206, "Partial Content"}, + {207, "Multi-Status"}, + + {400, "Bad Request"}, + {401, "Unauthorized"}, + {402, ""}, // reserve + {403, "Forbidden"}, + {404, "Not Found"}, + {405, "Method Not Allowed"}, + {406, "Not Acceptable"}, + {407, "Proxy Authentication Required"}, + {408, "Request Timeout"}, + {409, "Conflict"}, + {416, "Requested Range not satisfiable"}, + + {500, "Internal Server Error"}, + {501, "Not Implemented"}, + {502, "Bad Gateway"}, + {503, "Service Unavailable"}, + {504, "Gateway Timeout"}, + {505, "HTTP Version Not Supported"}, + {506, "Variant Also Negotiates"}, + {507, "Insufficient Storage"}, + {508, "Bandwidth Limit Exceeded"}, + {509, "Not Extended"}, }; inline int find_lf(const char* data, int size) { @@ -70,8 +70,7 @@ inline int find_lf(const char* data, int size) { return count; } -bool HTTPRequest::ParseHeadLine( - const char* data, int line_start, int line_end) { +bool HTTPRequest::ParseHeadLine(const char* data, int line_start, int line_end) { std::string param_key; std::string param_value; for (int i = line_start; i <= line_end; i++) { @@ -123,8 +122,7 @@ bool HTTPRequest::ParseHeadLine( bool HTTPRequest::ParseGetUrl() { path_ = url_; // Format path - if (headers_.count("host") && - path_.find(headers_["host"]) != std::string::npos && + if (headers_.count("host") && path_.find(headers_["host"]) != std::string::npos && path_.size() > (7 + headers_["host"].size())) { // http://www.xxx.xxx/path_/to path_.assign(path_.substr(7 + headers_["host"].size())); @@ -158,8 +156,7 @@ bool HTTPRequest::ParseParameters(const std::string data, size_t line_start) { query_params_[data.substr(pre, end - pre)] = std::string(); pre = end + 1; } else { - query_params_[data.substr(pre, mid - pre)] = - data.substr(mid + 1, end - mid - 1); + query_params_[data.substr(pre, mid - pre)] = data.substr(mid + 1, end - mid - 1); pre = end + 1; } } @@ -168,7 +165,7 @@ bool HTTPRequest::ParseParameters(const std::string data, size_t line_start) { int HTTPRequest::ParseHeader() { rbuf_[rbuf_pos_] = '\0'; // Avoid strstr() parsing expire char - char *sep_pos = strstr(rbuf_, "\r\n\r\n"); + char* sep_pos = strstr(rbuf_, "\r\n\r\n"); if (!sep_pos) { // Haven't find header return 0; @@ -200,16 +197,14 @@ int HTTPRequest::ParseHeader() { return -1; } - remain_recv_len_ = headers_.count("content-length") ? - std::stoul(headers_.at("content-length")) : 0; + remain_recv_len_ = headers_.count("content-length") ? std::stoul(headers_.at("content-length")) : 0; if (headers_.count("content-type")) { content_type_.assign(headers_.at("content-type")); } if (headers_.count("expect") && - (headers_.at("expect") == "100-Continue" || - headers_.at("expect") == "100-continue")) { + (headers_.at("expect") == "100-Continue" || headers_.at("expect") == "100-continue")) { reply_100continue_ = true; } @@ -223,8 +218,7 @@ void HTTPRequest::Dump() const { std::cout << "Version: " << version_ << std::endl; std::cout << "Headers: " << std::endl; for (auto& header : headers_) { - std::cout << " ----- " - << header.first << ": " << header.second << std::endl; + std::cout << " ----- " << header.first << ": " << header.second << std::endl; } std::cout << "Query params: " << std::endl; for (auto& item : query_params_) { @@ -240,17 +234,15 @@ bool HTTPResponse::SerializeHeader() { std::string reason_phrase = http_status_map.at(status_code_); // Serialize statues line - ret = snprintf(wbuf_, kHTTPMaxHeader, "HTTP/1.1 %d %s\r\n", - status_code_, reason_phrase.c_str()); + ret = snprintf(wbuf_, kHTTPMaxHeader, "HTTP/1.1 %d %s\r\n", status_code_, reason_phrase.c_str()); serial_size += ret; if (ret < 0 || ret == static_cast(kHTTPMaxHeader)) { return false; } - for (auto &line : headers_) { - ret = snprintf(wbuf_ + serial_size, kHTTPMaxHeader - serial_size, - "%s: %s\r\n", - line.first.c_str(), line.second.c_str()); + for (auto& line : headers_) { + ret = snprintf(wbuf_ + serial_size, kHTTPMaxHeader - serial_size, "%s: %s\r\n", line.first.c_str(), + line.second.c_str()); serial_size += ret; if (ret < 0 || serial_size == static_cast(kHTTPMaxHeader)) { return false; @@ -267,14 +259,13 @@ bool HTTPResponse::SerializeHeader() { return true; } -HTTPConn::HTTPConn(const int fd, const std::string &ip_port, - Thread *thread, std::shared_ptr handles, +HTTPConn::HTTPConn(const int fd, const std::string& ip_port, Thread* thread, std::shared_ptr handles, void* worker_specific_data) - : NetConn(fd, ip_port, thread), + : NetConn(fd, ip_port, thread), #ifdef __ENABLE_SSL - security_(thread->security()), + security_(thread->security()), #endif - handles_(handles) { + handles_(handles) { handles_->worker_specific_data_ = worker_specific_data; // this pointer is safe here request_ = new HTTPRequest(this); @@ -296,17 +287,11 @@ HTTPRequest::HTTPRequest(HTTPConn* conn) rbuf_ = new char[kHTTPMaxMessage]; } -HTTPRequest::~HTTPRequest() { - delete[] rbuf_; -} +HTTPRequest::~HTTPRequest() { delete[] rbuf_; } -const std::string HTTPRequest::url() const { - return url_; -} +const std::string HTTPRequest::url() const { return url_; } -const std::string HTTPRequest::path() const { - return path_; -} +const std::string HTTPRequest::path() const { return path_; } const std::string HTTPRequest::query_value(const std::string& field) const { if (query_params_.count(field)) { @@ -322,29 +307,17 @@ const std::string HTTPRequest::postform_value(const std::string& field) const { return ""; } -const std::string HTTPRequest::method() const { - return method_; -} +const std::string HTTPRequest::method() const { return method_; } -const std::string HTTPRequest::content_type() const { - return content_type_; -} +const std::string HTTPRequest::content_type() const { return content_type_; } -const std::map HTTPRequest::query_params() const { - return query_params_; -} +const std::map HTTPRequest::query_params() const { return query_params_; } -const std::map HTTPRequest::postform_params() const { - return postform_params_; -} +const std::map HTTPRequest::postform_params() const { return postform_params_; } -const std::map HTTPRequest::headers() const { - return headers_; -} +const std::map HTTPRequest::headers() const { return headers_; } -const std::string HTTPRequest::client_ip_port() const { - return client_ip_port_; -} +const std::string HTTPRequest::client_ip_port() const { return client_ip_port_; } void HTTPRequest::Reset() { rbuf_pos_ = 0; @@ -366,8 +339,7 @@ ReadStatus HTTPRequest::DoRead() { ssize_t nread; #ifdef __ENABLE_SSL if (conn_->security_) { - nread = SSL_read(conn_->ssl(), rbuf_ + rbuf_pos_, - static_cast(kHTTPMaxMessage)); + nread = SSL_read(conn_->ssl(), rbuf_ + rbuf_pos_, static_cast(kHTTPMaxMessage)); if (nread <= 0) { int sslerr = SSL_get_error(conn_->ssl(), static_cast(nread)); switch (sslerr) { @@ -381,12 +353,10 @@ ReadStatus HTTPRequest::DoRead() { return kReadClose; } } - } - else + } else #endif { - nread = read(conn_->fd(), rbuf_ + rbuf_pos_, - kHTTPMaxMessage - rbuf_pos_); + nread = read(conn_->fd(), rbuf_ + rbuf_pos_, kHTTPMaxMessage - rbuf_pos_); } if (nread > 0) { rbuf_pos_ += nread; @@ -423,8 +393,7 @@ ReadStatus HTTPRequest::ReadData() { return s; } header_len = ParseHeader(); - if (header_len < 0 || - rbuf_pos_ > kHTTPMaxHeader) { + if (header_len < 0 || rbuf_pos_ > kHTTPMaxHeader) { // Parse header error conn_->handles_->HandleConnClosed(); return kReadError; @@ -461,8 +430,7 @@ ReadStatus HTTPRequest::ReadData() { conn_->handles_->HandleConnClosed(); return s; } - if (rbuf_pos_ == kHTTPMaxMessage || - remain_recv_len_ == 0) { + if (rbuf_pos_ == kHTTPMaxMessage || remain_recv_len_ == 0) { conn_->handles_->HandleBodyData(rbuf_, rbuf_pos_); rbuf_pos_ = 0; } @@ -501,9 +469,7 @@ HTTPResponse::HTTPResponse(HTTPConn* conn) wbuf_ = new char[kHTTPMaxMessage]; } -HTTPResponse::~HTTPResponse() { - delete[] wbuf_; -} +HTTPResponse::~HTTPResponse() { delete[] wbuf_; } void HTTPResponse::Reset() { headers_.clear(); @@ -515,32 +481,21 @@ void HTTPResponse::Reset() { resp_status_ = kPrepareHeader; } -bool HTTPResponse::Finished() { - return finished_; -} +bool HTTPResponse::Finished() { return finished_; } void HTTPResponse::SetStatusCode(int code) { - assert((code >= 100 && code <= 102) || - (code >= 200 && code <= 207) || - (code >= 400 && code <= 409) || - (code == 416) || - (code >= 500 && code <= 509)); + assert((code >= 100 && code <= 102) || (code >= 200 && code <= 207) || (code >= 400 && code <= 409) || + (code == 416) || (code >= 500 && code <= 509)); status_code_ = code; } -void HTTPResponse::SetHeaders( - const std::string& key, const std::string& value) { - headers_[key] = value; -} +void HTTPResponse::SetHeaders(const std::string& key, const std::string& value) { headers_[key] = value; } -void HTTPResponse::SetHeaders(const std::string& key, const size_t value) { - headers_[key] = std::to_string(value); -} +void HTTPResponse::SetHeaders(const std::string& key, const size_t value) { headers_[key] = std::to_string(value); } void HTTPResponse::SetContentLength(uint64_t size) { remain_send_len_ = size; - if (headers_.count("Content-Length") || - headers_.count("content-length")) { + if (headers_.count("Content-Length") || headers_.count("content-length")) { return; } SetHeaders("Content-Length", size); @@ -548,8 +503,7 @@ void HTTPResponse::SetContentLength(uint64_t size) { bool HTTPResponse::Flush() { if (resp_status_ == kPrepareHeader) { - if (!SerializeHeader() || - buf_len_ > kHTTPMaxHeader) { + if (!SerializeHeader() || buf_len_ > kHTTPMaxHeader) { return false; } resp_status_ = kSendingHeader; @@ -558,8 +512,7 @@ bool HTTPResponse::Flush() { ssize_t nwritten; #ifdef __ENABLE_SSL if (conn_->security_) { - nwritten = SSL_write(conn_->ssl(), wbuf_ + wbuf_pos_, - static_cast(buf_len_)); + nwritten = SSL_write(conn_->ssl(), wbuf_ + wbuf_pos_, static_cast(buf_len_)); if (nwritten <= 0) { // FIXME (gaodq) int sslerr = SSL_get_error(conn_->ssl(), static_cast(nwritten)); @@ -574,8 +527,7 @@ bool HTTPResponse::Flush() { return false; } } - } - else + } else #endif { nwritten = write(conn_->fd(), wbuf_ + wbuf_pos_, buf_len_); @@ -611,8 +563,7 @@ bool HTTPResponse::Flush() { if (buf_len_ == 0) { size_t remain_buf = static_cast(kHTTPMaxMessage) - wbuf_pos_; size_t needed_size = std::min(remain_buf, remain_send_len_); - buf_len_ = conn_->handles_->WriteResponseBody( - wbuf_ + wbuf_pos_, needed_size); + buf_len_ = conn_->handles_->WriteResponseBody(wbuf_ + wbuf_pos_, needed_size); } if (buf_len_ == -1) { @@ -622,8 +573,7 @@ bool HTTPResponse::Flush() { ssize_t nwritten; #ifdef __ENABLE_SSL if (conn_->security_) { - nwritten = SSL_write(conn_->ssl(), wbuf_ + wbuf_pos_, - static_cast(buf_len_)); + nwritten = SSL_write(conn_->ssl(), wbuf_ + wbuf_pos_, static_cast(buf_len_)); if (nwritten <= 0) { // FIXME (gaodq) int sslerr = SSL_get_error(conn_->ssl(), static_cast(nwritten)); @@ -638,8 +588,7 @@ bool HTTPResponse::Flush() { return false; } } - } - else + } else #endif { nwritten = write(conn_->fd(), wbuf_ + wbuf_pos_, buf_len_); diff --git a/src/net/src/net_cli.cc b/src/net/src/net_cli.cc index 3c1347a134..ec41d46ef4 100644 --- a/src/net/src/net_cli.cc +++ b/src/net/src/net_cli.cc @@ -5,14 +5,14 @@ #include "net/include/net_cli.h" -#include -#include -#include -#include #include +#include #include +#include +#include #include -#include +#include +#include namespace net { @@ -27,47 +27,39 @@ struct NetCli::Rep { int sockfd; bool available; - Rep() : send_timeout(0), - recv_timeout(0), - connect_timeout(1000), - keep_alive(0), - is_block(true), - sockfd(-1), - available(false) { - } + Rep() + : send_timeout(0), + recv_timeout(0), + connect_timeout(1000), + keep_alive(0), + is_block(true), + sockfd(-1), + available(false) {} Rep(const std::string& ip, int port) - : peer_ip(ip), - peer_port(port), - send_timeout(0), - recv_timeout(0), - connect_timeout(1000), - keep_alive(0), - is_block(true), - sockfd(-1), - available(false) { - } + : peer_ip(ip), + peer_port(port), + send_timeout(0), + recv_timeout(0), + connect_timeout(1000), + keep_alive(0), + is_block(true), + sockfd(-1), + available(false) {} }; -NetCli::NetCli(const std::string& ip, const int port) - : rep_(new Rep(ip, port)) { -} +NetCli::NetCli(const std::string& ip, const int port) : rep_(new Rep(ip, port)) {} NetCli::~NetCli() { Close(); delete rep_; } -bool NetCli::Available() const { - return rep_->available; -} +bool NetCli::Available() const { return rep_->available; } -Status NetCli::Connect(const std::string &bind_ip) { - return Connect(rep_->peer_ip, rep_->peer_port, bind_ip); -} +Status NetCli::Connect(const std::string& bind_ip) { return Connect(rep_->peer_ip, rep_->peer_port, bind_ip); } -Status NetCli::Connect(const std::string &ip, const int port, - const std::string &bind_ip) { +Status NetCli::Connect(const std::string& ip, const int port, const std::string& bind_ip) { Rep* r = rep_; Status s; int rv; @@ -83,8 +75,7 @@ Status NetCli::Connect(const std::string &ip, const int port, return Status::IOError("connect getaddrinfo error for ", ip); } for (p = servinfo; p != NULL; p = p->ai_next) { - if ((r->sockfd = socket( - p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { + if ((r->sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { continue; } @@ -94,10 +85,9 @@ Status NetCli::Connect(const std::string &ip, const int port, localaddr.sin_family = AF_INET; localaddr.sin_addr.s_addr = inet_addr(bind_ip.c_str()); localaddr.sin_port = 0; // Any local port will do - bind(r->sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr)); + bind(r->sockfd, (struct sockaddr*)&localaddr, sizeof(localaddr)); } - int flags = fcntl(r->sockfd, F_GETFL, 0); fcntl(r->sockfd, F_SETFL, flags | O_NONBLOCK); fcntl(r->sockfd, F_SETFD, fcntl(r->sockfd, F_GETFD) | FD_CLOEXEC); @@ -106,9 +96,7 @@ Status NetCli::Connect(const std::string &ip, const int port, if (errno == EHOSTUNREACH) { close(r->sockfd); continue; - } else if (errno == EINPROGRESS || - errno == EAGAIN || - errno == EWOULDBLOCK) { + } else if (errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK) { struct pollfd wfd[1]; wfd[0].fd = r->sockfd; @@ -130,8 +118,7 @@ Status NetCli::Connect(const std::string &ip, const int port, if (getsockopt(r->sockfd, SOL_SOCKET, SO_ERROR, &val, &lon) == -1) { close(r->sockfd); freeaddrinfo(servinfo); - return Status::IOError("EHOSTUNREACH", - "connect host getsockopt error"); + return Status::IOError("EHOSTUNREACH", "connect host getsockopt error"); } if (val) { @@ -142,14 +129,13 @@ Status NetCli::Connect(const std::string &ip, const int port, } else { close(r->sockfd); freeaddrinfo(servinfo); - return Status::IOError("EHOSTUNREACH", - "The target host cannot be reached"); + return Status::IOError("EHOSTUNREACH", "The target host cannot be reached"); } } struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); - getsockname(r->sockfd, (struct sockaddr*) &laddr, &llen); + getsockname(r->sockfd, (struct sockaddr*)&laddr, &llen); std::string lip(inet_ntoa(laddr.sin_addr)); int lport = ntohs(laddr.sin_port); if (ip == lip && port == lport) { @@ -182,7 +168,7 @@ static int PollFd(int fd, int events, int ms) { int ret = ::poll(fds, 1, ms); if (ret > 0) { - return fds[0].revents; + return fds[0].revents; } return ret; @@ -233,7 +219,7 @@ int NetCli::CheckAliveness() { return ret; } -Status NetCli::SendRaw(void *buf, size_t count) { +Status NetCli::SendRaw(void* buf, size_t count) { char* wbuf = reinterpret_cast(buf); size_t nleft = count; int pos = 0; @@ -259,7 +245,7 @@ Status NetCli::SendRaw(void *buf, size_t count) { return Status::OK(); } -Status NetCli::RecvRaw(void *buf, size_t *count) { +Status NetCli::RecvRaw(void* buf, size_t* count) { Rep* r = rep_; char* rbuf = reinterpret_cast(buf); size_t nleft = *count; @@ -286,9 +272,7 @@ Status NetCli::RecvRaw(void *buf, size_t *count) { return Status::OK(); } -int NetCli::fd() const { - return rep_->sockfd; -} +int NetCli::fd() const { return rep_->sockfd; } void NetCli::Close() { if (rep_->available) { @@ -298,19 +282,15 @@ void NetCli::Close() { } } -void NetCli::set_connect_timeout(int connect_timeout) { - rep_->connect_timeout = connect_timeout; -} +void NetCli::set_connect_timeout(int connect_timeout) { rep_->connect_timeout = connect_timeout; } int NetCli::set_send_timeout(int send_timeout) { Rep* r = rep_; int ret = 0; if (send_timeout > 0) { r->send_timeout = send_timeout; - struct timeval timeout = - {r->send_timeout / 1000, (r->send_timeout % 1000) * 1000}; - ret = setsockopt( - r->sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); + struct timeval timeout = {r->send_timeout / 1000, (r->send_timeout % 1000) * 1000}; + ret = setsockopt(r->sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); } return ret; } @@ -320,10 +300,8 @@ int NetCli::set_recv_timeout(int recv_timeout) { int ret = 0; if (recv_timeout > 0) { r->recv_timeout = recv_timeout; - struct timeval timeout = - {r->recv_timeout / 1000, (r->recv_timeout % 1000) * 1000}; - ret = setsockopt( - r->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + struct timeval timeout = {r->recv_timeout / 1000, (r->recv_timeout % 1000) * 1000}; + ret = setsockopt(r->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); } return ret; } diff --git a/src/net/src/net_conn.cc b/src/net/src/net_conn.cc index bfb57d40f3..160965bd04 100644 --- a/src/net/src/net_conn.cc +++ b/src/net/src/net_conn.cc @@ -6,17 +6,14 @@ #include #include -#include "pstd/include/xdebug.h" #include "net/include/net_conn.h" #include "net/include/net_thread.h" #include "net/src/net_util.h" +#include "pstd/include/xdebug.h" namespace net { -NetConn::NetConn(const int fd, - const std::string &ip_port, - Thread *thread, - NetMultiplexer* net_mpx) +NetConn::NetConn(const int fd, const std::string& ip_port, Thread* thread, NetMultiplexer* net_mpx) : fd_(fd), ip_port_(ip_port), is_reply_(false), diff --git a/src/net/src/net_epoll.cc b/src/net/src/net_epoll.cc index 5d9efee262..1b6a8ef58c 100644 --- a/src/net/src/net_epoll.cc +++ b/src/net/src/net_epoll.cc @@ -5,8 +5,8 @@ #include "net/src/net_epoll.h" -#include #include +#include #include #include "net/include/net_define.h" @@ -14,15 +14,13 @@ namespace net { -NetMultiplexer* CreateNetMultiplexer(int limit) { - return new NetEpoll(limit); -} +NetMultiplexer* CreateNetMultiplexer(int limit) { return new NetEpoll(limit); } NetEpoll::NetEpoll(int queue_limit) : NetMultiplexer(queue_limit) { #if defined(EPOLL_CLOEXEC) - multiplexer_ = epoll_create1(EPOLL_CLOEXEC); + multiplexer_ = epoll_create1(EPOLL_CLOEXEC); #else - multiplexer_ = epoll_create(1024); + multiplexer_ = epoll_create(1024); #endif fcntl(multiplexer_, F_SETFD, fcntl(multiplexer_, F_GETFD) | FD_CLOEXEC); @@ -40,10 +38,8 @@ int NetEpoll::NetAddEvent(int fd, int mask) { ee.data.fd = fd; ee.events = 0; - if (mask & kReadable) - ee.events |= EPOLLIN; - if (mask & kWritable) - ee.events |= EPOLLOUT; + if (mask & kReadable) ee.events |= EPOLLIN; + if (mask & kWritable) ee.events |= EPOLLOUT; return epoll_ctl(multiplexer_, EPOLL_CTL_ADD, fd, &ee); } @@ -54,10 +50,8 @@ int NetEpoll::NetModEvent(int fd, int old_mask, int mask) { ee.events = (old_mask | mask); ee.events = 0; - if ((old_mask | mask) & kReadable) - ee.events |= EPOLLIN; - if ((old_mask | mask) & kWritable) - ee.events |= EPOLLOUT; + if ((old_mask | mask) & kReadable) ee.events |= EPOLLIN; + if ((old_mask | mask) & kWritable) ee.events |= EPOLLOUT; return epoll_ctl(multiplexer_, EPOLL_CTL_MOD, fd, &ee); } @@ -72,8 +66,7 @@ int NetEpoll::NetDelEvent(int fd, int) { int NetEpoll::NetPoll(int timeout) { int num_events = epoll_wait(multiplexer_, &events_[0], NET_MAX_CLIENTS, timeout); - if (num_events <= 0) - return 0; + if (num_events <= 0) return 0; for (int i = 0; i < num_events; i++) { NetFiredEvent& ev = fired_events_[i]; diff --git a/src/net/src/net_interfaces.cc b/src/net/src/net_interfaces.cc index 49d9062b36..084af2e96e 100644 --- a/src/net/src/net_interfaces.cc +++ b/src/net/src/net_interfaces.cc @@ -7,22 +7,22 @@ #include -#include #include +#include #if defined(__APPLE__) -#include -#include -#include -#include +# include +# include +# include +# include -#include "pstd/include/pstd_defer.h" +# include "pstd/include/pstd_defer.h" #else -#include -#include -#include -#include +# include +# include +# include +# include #endif @@ -39,7 +39,7 @@ std::string GetDefaultInterface() { DEFER { close(fd); }; - struct ifreq *ifreq; + struct ifreq* ifreq; struct ifconf ifconf; char buf[16384]; @@ -61,7 +61,7 @@ std::string GetDefaultInterface() { break; } - ifreq = (struct ifreq*)((char*)ifreq+len); + ifreq = (struct ifreq*)((char*)ifreq + len); i += len; } @@ -69,16 +69,14 @@ std::string GetDefaultInterface() { #else std::string name("eth0"); std::ifstream routeFile("/proc/net/route", std::ios_base::in); - if (!routeFile.good()) - return name; + if (!routeFile.good()) return name; std::string line; std::vector tokens; - while(std::getline(routeFile, line)) { + while (std::getline(routeFile, line)) { std::istringstream stream(line); - std::copy(std::istream_iterator(stream), - std::istream_iterator(), - std::back_inserter >(tokens)); + std::copy(std::istream_iterator(stream), std::istream_iterator(), + std::back_inserter >(tokens)); // the default interface is the one having the second // field, Destination, set to "00000000" @@ -101,9 +99,9 @@ std::string GetIpByInterface(const std::string& network_interface) { log_info("Using Networker Interface: %s", network_interface.c_str()); - struct ifaddrs * ifAddrStruct = NULL; - struct ifaddrs * ifa = NULL; - void * tmpAddrPtr = NULL; + struct ifaddrs* ifAddrStruct = NULL; + struct ifaddrs* ifa = NULL; + void* tmpAddrPtr = NULL; if (getifaddrs(&ifAddrStruct) == -1) { log_err("getifaddrs failed"); @@ -116,16 +114,16 @@ std::string GetIpByInterface(const std::string& network_interface) { continue; } - if (ifa ->ifa_addr->sa_family==AF_INET) { // Check it is a valid IPv4 address - tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; + if (ifa->ifa_addr->sa_family == AF_INET) { // Check it is a valid IPv4 address + tmpAddrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); if (std::string(ifa->ifa_name) == network_interface) { host = addressBuffer; break; } - } else if (ifa->ifa_addr->sa_family==AF_INET6) { // Check it is a valid IPv6 address - tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr; + } else if (ifa->ifa_addr->sa_family == AF_INET6) { // Check it is a valid IPv6 address + tmpAddrPtr = &((struct sockaddr_in6*)ifa->ifa_addr)->sin6_addr; char addressBuffer[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); if (std::string(ifa->ifa_name) == network_interface) { @@ -135,7 +133,7 @@ std::string GetIpByInterface(const std::string& network_interface) { } } - if (ifAddrStruct ) { + if (ifAddrStruct) { freeifaddrs(ifAddrStruct); } @@ -146,4 +144,3 @@ std::string GetIpByInterface(const std::string& network_interface) { log_info("got ip %s", host.c_str()); return host; } - diff --git a/src/net/src/net_item.h b/src/net/src/net_item.h index 962fc85e82..9452d9d441 100644 --- a/src/net/src/net_item.h +++ b/src/net/src/net_item.h @@ -15,22 +15,13 @@ namespace net { class NetItem { public: NetItem() {} - NetItem(const int fd, const std::string &ip_port, const NotifyType& type = kNotiConnect) - : fd_(fd), - ip_port_(ip_port), - notify_type_(type) { - } - - int fd() const { - return fd_; - } - std::string ip_port() const { - return ip_port_; - } - - NotifyType notify_type() const { - return notify_type_; - } + NetItem(const int fd, const std::string& ip_port, const NotifyType& type = kNotiConnect) + : fd_(fd), ip_port_(ip_port), notify_type_(type) {} + + int fd() const { return fd_; } + std::string ip_port() const { return ip_port_; } + + NotifyType notify_type() const { return notify_type_; } private: int fd_; diff --git a/src/net/src/net_kqueue.cc b/src/net/src/net_kqueue.cc index 5c8011a08a..b22ffaebff 100644 --- a/src/net/src/net_kqueue.cc +++ b/src/net/src/net_kqueue.cc @@ -14,9 +14,7 @@ namespace net { -NetMultiplexer* CreateNetMultiplexer(int limit) { - return new NetKqueue(limit); -} +NetMultiplexer* CreateNetMultiplexer(int limit) { return new NetKqueue(limit); } NetKqueue::NetKqueue(int queue_limit) : NetMultiplexer(queue_limit) { multiplexer_ = ::kqueue(); @@ -38,23 +36,22 @@ int NetKqueue::NetAddEvent(int fd, int mask) { if (mask & kReadable) { EV_SET(change + cnt, fd, EVFILT_READ, EV_ADD, 0, 0, nullptr); - ++ cnt; + ++cnt; } if (mask & kWritable) { EV_SET(change + cnt, fd, EVFILT_WRITE, EV_ADD, 0, 0, nullptr); - ++ cnt; + ++cnt; } return kevent(multiplexer_, change, cnt, nullptr, 0, nullptr); } int NetKqueue::NetModEvent(int fd, int, int mask) { - int ret = NetDelEvent(fd, kReadable | kWritable); - if (mask == 0) - return ret; + int ret = NetDelEvent(fd, kReadable | kWritable); + if (mask == 0) return ret; - return NetAddEvent(fd, mask); + return NetAddEvent(fd, mask); } int NetKqueue::NetDelEvent(int fd, int mask) { @@ -63,32 +60,30 @@ int NetKqueue::NetDelEvent(int fd, int mask) { if (mask & kReadable) { EV_SET(change + cnt, fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr); - ++ cnt; + ++cnt; } if (mask & kWritable) { EV_SET(change + cnt, fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); - ++ cnt; + ++cnt; } - if (cnt == 0) - return -1; + if (cnt == 0) return -1; return kevent(multiplexer_, change, cnt, nullptr, 0, nullptr); } int NetKqueue::NetPoll(int timeout) { struct timespec* p_timeout = nullptr; - struct timespec s_timeout; + struct timespec s_timeout; if (timeout >= 0) { p_timeout = &s_timeout; - s_timeout.tv_sec = timeout / 1000; + s_timeout.tv_sec = timeout / 1000; s_timeout.tv_nsec = timeout % 1000 * 1000000; } int num_events = ::kevent(multiplexer_, nullptr, 0, &events_[0], NET_MAX_CLIENTS, p_timeout); - if (num_events <= 0) - return 0; + if (num_events <= 0) return 0; for (int i = 0; i < num_events; i++) { NetFiredEvent& ev = fired_events_[i]; diff --git a/src/net/src/net_multiplexer.cc b/src/net/src/net_multiplexer.cc index ceb73edb54..6de66b814b 100644 --- a/src/net/src/net_multiplexer.cc +++ b/src/net/src/net_multiplexer.cc @@ -5,9 +5,9 @@ #include "net/src/net_multiplexer.h" -#include -#include #include +#include +#include #include "pstd/include/xdebug.h" @@ -58,9 +58,7 @@ bool NetMultiplexer::Register(const NetItem& it, bool force) { bool success = false; notify_queue_protector_.Lock(); - if (force || - queue_limit_ == kUnlimitedQueue || - notify_queue_.size() < static_cast(queue_limit_)) { + if (force || queue_limit_ == kUnlimitedQueue || notify_queue_.size() < static_cast(queue_limit_)) { notify_queue_.push(it); success = true; } diff --git a/src/net/src/net_multiplexer.h b/src/net/src/net_multiplexer.h index a729a7ebd2..e66f4d77f2 100644 --- a/src/net/src/net_multiplexer.h +++ b/src/net/src/net_multiplexer.h @@ -15,13 +15,12 @@ namespace net { struct NetFiredEvent { int fd = -1; - int mask = 0; // EventStatus + int mask = 0; // EventStatus }; class NetMultiplexer { public: - explicit - NetMultiplexer(int queue_limit); + explicit NetMultiplexer(int queue_limit); virtual ~NetMultiplexer(); virtual int NetAddEvent(int fd, int mask) = 0; @@ -33,12 +32,8 @@ class NetMultiplexer { NetFiredEvent* FiredEvents() { return &fired_events_[0]; } - int NotifyReceiveFd() const { - return notify_receive_fd_; - } - int NotifySendFd() const { - return notify_send_fd_; - } + int NotifyReceiveFd() const { return notify_receive_fd_; } + int NotifySendFd() const { return notify_send_fd_; } NetItem NotifyQueuePop(); bool Register(const NetItem& it, bool force); diff --git a/src/net/src/net_pubsub.cc b/src/net/src/net_pubsub.cc index 8557b78450..9a0e89ab55 100644 --- a/src/net/src/net_pubsub.cc +++ b/src/net/src/net_pubsub.cc @@ -3,53 +3,52 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include #include #include +#include #include "net/src/worker_thread.h" #include "net/include/net_conn.h" -#include "net/src/net_item.h" #include "net/include/net_pubsub.h" +#include "net/src/net_item.h" namespace net { -static std::string ConstructPublishResp(const std::string& subscribe_channel, - const std::string& publish_channel, - const std::string& msg, - const bool pattern) { +static std::string ConstructPublishResp(const std::string& subscribe_channel, const std::string& publish_channel, + const std::string& msg, const bool pattern) { std::stringstream resp; std::string common_msg = "message"; std::string pattern_msg = "pmessage"; if (pattern) { - resp << "*4\r\n" << "$" << pattern_msg.length() << "\r\n" << pattern_msg << "\r\n" << - "$" << subscribe_channel.length() << "\r\n" << subscribe_channel << "\r\n" << - "$" << publish_channel.length() << "\r\n" << publish_channel << "\r\n" << - "$" << msg.length() << "\r\n" << msg << "\r\n"; + resp << "*4\r\n" + << "$" << pattern_msg.length() << "\r\n" + << pattern_msg << "\r\n" + << "$" << subscribe_channel.length() << "\r\n" + << subscribe_channel << "\r\n" + << "$" << publish_channel.length() << "\r\n" + << publish_channel << "\r\n" + << "$" << msg.length() << "\r\n" + << msg << "\r\n"; } else { - resp << "*3\r\n" << "$" << common_msg.length() << "\r\n" << common_msg << "\r\n" << - "$" << publish_channel.length() << "\r\n" << publish_channel << "\r\n" << - "$" << msg.length() << "\r\n" << msg << "\r\n"; + resp << "*3\r\n" + << "$" << common_msg.length() << "\r\n" + << common_msg << "\r\n" + << "$" << publish_channel.length() << "\r\n" + << publish_channel << "\r\n" + << "$" << msg.length() << "\r\n" + << msg << "\r\n"; } return resp.str(); } -void CloseFd(std::shared_ptr conn) { - close(conn->fd()); -} +void CloseFd(std::shared_ptr conn) { close(conn->fd()); } -void PubSubThread::ConnHandle::UpdateReadyState(const ReadyState& state) { - ready_state = state; -} +void PubSubThread::ConnHandle::UpdateReadyState(const ReadyState& state) { ready_state = state; } -bool PubSubThread::ConnHandle::IsReady() { - return ready_state == PubSubThread::ReadyState::kReady; -} +bool PubSubThread::ConnHandle::IsReady() { return ready_state == PubSubThread::ReadyState::kReady; } -PubSubThread::PubSubThread() - : receiver_rsignal_(&receiver_mutex_), - receivers_(-1) { +PubSubThread::PubSubThread() : receiver_rsignal_(&receiver_mutex_), receivers_(-1) { set_thread_name("PubSubThread"); net_multiplexer_.reset(CreateNetMultiplexer()); net_multiplexer_->Initialize(); @@ -62,9 +61,7 @@ PubSubThread::PubSubThread() net_multiplexer_->NetAddEvent(msg_pfd_[0], kReadable); } -PubSubThread::~PubSubThread() { - StopThread(); -} +PubSubThread::~PubSubThread() { StopThread(); } void PubSubThread::MoveConnOut(std::shared_ptr conn) { RemoveConn(conn); @@ -107,9 +104,7 @@ bool PubSubThread::IsReady(int fd) { void PubSubThread::RemoveConn(std::shared_ptr conn) { pattern_mutex_.Lock(); for (auto it = pubsub_pattern_.begin(); it != pubsub_pattern_.end(); it++) { - for (auto conn_ptr = it->second.begin(); - conn_ptr != it->second.end(); - conn_ptr++) { + for (auto conn_ptr = it->second.begin(); conn_ptr != it->second.end(); conn_ptr++) { if ((*conn_ptr) == conn) { conn_ptr = it->second.erase(conn_ptr); break; @@ -120,9 +115,7 @@ void PubSubThread::RemoveConn(std::shared_ptr conn) { channel_mutex_.Lock(); for (auto it = pubsub_channel_.begin(); it != pubsub_channel_.end(); it++) { - for (auto conn_ptr = it->second.begin(); - conn_ptr != it->second.end(); - conn_ptr++) { + for (auto conn_ptr = it->second.begin(); conn_ptr != it->second.end(); conn_ptr++) { if ((*conn_ptr) == conn) { conn_ptr = it->second.erase(conn_ptr); break; @@ -132,7 +125,7 @@ void PubSubThread::RemoveConn(std::shared_ptr conn) { channel_mutex_.Unlock(); } -int PubSubThread::Publish(const std::string& channel, const std::string &msg) { +int PubSubThread::Publish(const std::string& channel, const std::string& msg) { // TODO(LIBA-S): change the Publish Mode to Asynchronous int receivers; pub_mutex_.Lock(); @@ -161,9 +154,7 @@ int PubSubThread::ClientChannelSize(std::shared_ptr conn) { channel_mutex_.Lock(); for (auto& channel : pubsub_channel_) { - auto conn_ptr = std::find(channel.second.begin(), - channel.second.end(), - conn); + auto conn_ptr = std::find(channel.second.begin(), channel.second.end(), conn); if (conn_ptr != channel.second.end()) { subscribed++; } @@ -172,9 +163,7 @@ int PubSubThread::ClientChannelSize(std::shared_ptr conn) { pattern_mutex_.Lock(); for (auto& channel : pubsub_pattern_) { - auto conn_ptr = std::find(channel.second.begin(), - channel.second.end(), - conn); + auto conn_ptr = std::find(channel.second.begin(), channel.second.end(), conn); if (conn_ptr != channel.second.end()) { subscribed++; } @@ -184,10 +173,8 @@ int PubSubThread::ClientChannelSize(std::shared_ptr conn) { return subscribed; } -void PubSubThread::Subscribe(std::shared_ptr conn, - const std::vector& channels, - const bool pattern, - std::vector>* result) { +void PubSubThread::Subscribe(std::shared_ptr conn, const std::vector& channels, + const bool pattern, std::vector>* result) { int subscribed = ClientChannelSize(conn); if (subscribed == 0) { @@ -198,31 +185,27 @@ void PubSubThread::Subscribe(std::shared_ptr conn, if (pattern) { // if pattern mode, register channel to map pstd::MutexLock channel_lock(&pattern_mutex_); if (pubsub_pattern_.find(channels[i]) != pubsub_pattern_.end()) { - auto conn_ptr = std::find(pubsub_pattern_[channels[i]].begin(), - pubsub_pattern_[channels[i]].end(), - conn); - if (conn_ptr == pubsub_pattern_[channels[i]].end()) { // the connection first subscrbied + auto conn_ptr = std::find(pubsub_pattern_[channels[i]].begin(), pubsub_pattern_[channels[i]].end(), conn); + if (conn_ptr == pubsub_pattern_[channels[i]].end()) { // the connection first subscrbied pubsub_pattern_[channels[i]].push_back(conn); ++subscribed; } - } else { // the channel first subscribed - std::vector > conns = {conn}; + } else { // the channel first subscribed + std::vector> conns = {conn}; pubsub_pattern_[channels[i]] = conns; ++subscribed; } result->push_back(std::make_pair(channels[i], subscribed)); - } else { // if general mode, reigster channel to map + } else { // if general mode, reigster channel to map pstd::MutexLock channel_lock(&channel_mutex_); if (pubsub_channel_.find(channels[i]) != pubsub_channel_.end()) { - auto conn_ptr = std::find(pubsub_channel_[channels[i]].begin(), - pubsub_channel_[channels[i]].end(), - conn); - if (conn_ptr == pubsub_channel_[channels[i]].end()) { // the connection first subscribed + auto conn_ptr = std::find(pubsub_channel_[channels[i]].begin(), pubsub_channel_[channels[i]].end(), conn); + if (conn_ptr == pubsub_channel_[channels[i]].end()) { // the connection first subscribed pubsub_channel_[channels[i]].push_back(conn); ++subscribed; } - } else { // the channel first subscribed - std::vector > conns = {conn}; + } else { // the channel first subscribed + std::vector> conns = {conn}; pubsub_channel_[channels[i]] = conns; ++subscribed; } @@ -231,26 +214,22 @@ void PubSubThread::Subscribe(std::shared_ptr conn, } } -/* +/* * Unsubscribes the client from the given channels, or from all of them if none * is given. */ -int PubSubThread::UnSubscribe(std::shared_ptr conn, - const std::vector& channels, - const bool pattern, - std::vector>* result) { +int PubSubThread::UnSubscribe(std::shared_ptr conn, const std::vector& channels, + const bool pattern, std::vector>* result) { int subscribed = ClientChannelSize(conn); bool exist = true; if (subscribed == 0) { exist = false; } - if (channels.size() == 0) { // if client want to unsubscribe all of channels - if (pattern) { // all of pattern channels + if (channels.size() == 0) { // if client want to unsubscribe all of channels + if (pattern) { // all of pattern channels pstd::MutexLock l(&pattern_mutex_); for (auto& channel : pubsub_pattern_) { - auto conn_ptr = std::find(channel.second.begin(), - channel.second.end(), - conn); + auto conn_ptr = std::find(channel.second.begin(), channel.second.end(), conn); if (conn_ptr != channel.second.end()) { result->push_back(std::make_pair(channel.first, --subscribed)); } @@ -258,9 +237,7 @@ int PubSubThread::UnSubscribe(std::shared_ptr conn, } else { pstd::MutexLock l(&channel_mutex_); for (auto& channel : pubsub_channel_) { - auto conn_ptr = std::find(channel.second.begin(), - channel.second.end(), - conn); + auto conn_ptr = std::find(channel.second.begin(), channel.second.end(), conn); if (conn_ptr != channel.second.end()) { result->push_back(std::make_pair(channel.first, --subscribed)); } @@ -273,19 +250,14 @@ int PubSubThread::UnSubscribe(std::shared_ptr conn, } for (size_t i = 0; i < channels.size(); i++) { - if (pattern) { // if pattern mode, unsubscribe the channels of specified + if (pattern) { // if pattern mode, unsubscribe the channels of specified pstd::MutexLock l(&pattern_mutex_); auto channel_ptr = pubsub_pattern_.find(channels[i]); if (channel_ptr != pubsub_pattern_.end()) { - auto it = std::find(channel_ptr->second.begin(), - channel_ptr->second.end(), - conn); + auto it = std::find(channel_ptr->second.begin(), channel_ptr->second.end(), conn); if (it != channel_ptr->second.end()) { - channel_ptr->second.erase(std::remove( - channel_ptr->second.begin(), - channel_ptr->second.end(), - conn), - channel_ptr->second.end()); + channel_ptr->second.erase(std::remove(channel_ptr->second.begin(), channel_ptr->second.end(), conn), + channel_ptr->second.end()); result->push_back(std::make_pair(channels[i], --subscribed)); } else { result->push_back(std::make_pair(channels[i], subscribed)); @@ -293,19 +265,14 @@ int PubSubThread::UnSubscribe(std::shared_ptr conn, } else { result->push_back(std::make_pair(channels[i], 0)); } - } else { // if general mode, unsubscribe the channels of specified + } else { // if general mode, unsubscribe the channels of specified pstd::MutexLock l(&channel_mutex_); auto channel_ptr = pubsub_channel_.find(channels[i]); if (channel_ptr != pubsub_channel_.end()) { - auto it = std::find(channel_ptr->second.begin(), - channel_ptr->second.end(), - conn); + auto it = std::find(channel_ptr->second.begin(), channel_ptr->second.end(), conn); if (it != channel_ptr->second.end()) { - channel_ptr->second.erase(std::remove( - channel_ptr->second.begin(), - channel_ptr->second.end(), - conn), - channel_ptr->second.end()); + channel_ptr->second.erase(std::remove(channel_ptr->second.begin(), channel_ptr->second.end(), conn), + channel_ptr->second.end()); result->push_back(std::make_pair(channels[i], --subscribed)); } else { result->push_back(std::make_pair(channels[i], subscribed)); @@ -324,8 +291,7 @@ int PubSubThread::UnSubscribe(std::shared_ptr conn, return subscribed; } -void PubSubThread::PubSubChannels(const std::string& pattern, - std::vector* result) { +void PubSubThread::PubSubChannels(const std::string& pattern, std::vector* result) { if (pattern == "") { pstd::MutexLock l(&channel_mutex_); for (auto& channel : pubsub_channel_) { @@ -336,8 +302,7 @@ void PubSubThread::PubSubChannels(const std::string& pattern, } else { pstd::MutexLock l(&channel_mutex_); for (auto& channel : pubsub_channel_) { - if (pstd::stringmatchlen(channel.first.c_str(), channel.first.size(), - pattern.c_str(), pattern.size(), 0)) { + if (pstd::stringmatchlen(channel.first.c_str(), channel.first.size(), pattern.c_str(), pattern.size(), 0)) { if (channel.second.size() != 0) { result->push_back(channel.first); } @@ -346,7 +311,7 @@ void PubSubThread::PubSubChannels(const std::string& pattern, } } -void PubSubThread::PubSubNumSub(const std::vector & channels, +void PubSubThread::PubSubNumSub(const std::vector& channels, std::vector>* result) { int subscribed; pstd::MutexLock l(&channel_mutex_); @@ -370,9 +335,9 @@ int PubSubThread::PubSubNumPat() { return subscribed; } -void *PubSubThread::ThreadMain() { +void* PubSubThread::ThreadMain() { int nfds; - NetFiredEvent *pfe; + NetFiredEvent* pfe; pstd::Status s; std::shared_ptr in_conn = nullptr; char triger[1]; @@ -381,7 +346,7 @@ void *PubSubThread::ThreadMain() { nfds = net_multiplexer_->NetPoll(NET_CRON_INTERVAL); for (int i = 0; i < nfds; i++) { pfe = (net_multiplexer_->FiredEvents()) + i; - if (pfe->fd == net_multiplexer_->NotifyReceiveFd()) { // New connection comming + if (pfe->fd == net_multiplexer_->NotifyReceiveFd()) { // New connection comming if (pfe->mask & kReadable) { read(net_multiplexer_->NotifyReceiveFd(), triger, 1); { @@ -401,7 +366,7 @@ void *PubSubThread::ThreadMain() { continue; } } - if (pfe->fd == msg_pfd_[0]) { // Publish message + if (pfe->fd == msg_pfd_[0]) { // Publish message if (pfe->mask & kReadable) { read(msg_pfd_[0], triger, 1); std::string channel, msg; @@ -423,8 +388,7 @@ void *PubSubThread::ThreadMain() { it->second[i]->WriteResp(resp); WriteStatus write_status = it->second[i]->SendReply(); if (write_status == kWriteHalf) { - net_multiplexer_->NetModEvent(it->second[i]->fd(), - kReadable, kWritable); + net_multiplexer_->NetModEvent(it->second[i]->fd(), kReadable, kWritable); } else if (write_status == kWriteError) { channel_mutex_.Unlock(); @@ -443,8 +407,7 @@ void *PubSubThread::ThreadMain() { // Send message to clients pattern_mutex_.Lock(); for (auto it = pubsub_pattern_.begin(); it != pubsub_pattern_.end(); it++) { - if (pstd::stringmatchlen(it->first.c_str(), it->first.size(), - channel.c_str(), channel.size(), 0)) { + if (pstd::stringmatchlen(it->first.c_str(), it->first.size(), channel.c_str(), channel.size(), 0)) { for (size_t i = 0; i < it->second.size(); i++) { if (!IsReady(it->second[i]->fd())) { continue; @@ -453,8 +416,7 @@ void *PubSubThread::ThreadMain() { it->second[i]->WriteResp(resp); WriteStatus write_status = it->second[i]->SendReply(); if (write_status == kWriteHalf) { - net_multiplexer_->NetModEvent(it->second[i]->fd(), - kReadable, kWritable); + net_multiplexer_->NetModEvent(it->second[i]->fd(), kReadable, kWritable); } else if (write_status == kWriteError) { pattern_mutex_.Unlock(); @@ -483,7 +445,7 @@ void *PubSubThread::ThreadMain() { { pstd::ReadLock l(&rwlock_); - std::map >::iterator iter = conns_.find(pfe->fd); + std::map>::iterator iter = conns_.find(pfe->fd); if (iter == conns_.end()) { net_multiplexer_->NetDelEvent(pfe->fd, 0); continue; diff --git a/src/net/src/net_thread.cc b/src/net/src/net_thread.cc index 0b522215a8..2366d82eea 100644 --- a/src/net/src/net_thread.cc +++ b/src/net/src/net_thread.cc @@ -4,22 +4,17 @@ // of patent rights can be found in the PATENTS file in the same directory. #include "net/include/net_thread.h" +#include "net/include/net_define.h" #include "net/src/net_thread_name.h" #include "pstd/include/xdebug.h" -#include "net/include/net_define.h" namespace net { -Thread::Thread() - : should_stop_(false), - running_(false), - thread_id_(0) { -} +Thread::Thread() : should_stop_(false), running_(false), thread_id_(0) {} -Thread::~Thread() { -} +Thread::~Thread() {} -void* Thread::RunThread(void *arg) { +void* Thread::RunThread(void* arg) { Thread* thread = reinterpret_cast(arg); if (!(thread->thread_name().empty())) { SetThreadName(pthread_self(), thread->thread_name()); @@ -33,7 +28,7 @@ int Thread::StartThread() { should_stop_ = false; if (!running_) { running_ = true; - return pthread_create(&thread_id_, nullptr, RunThread, (void *)this); + return pthread_create(&thread_id_, nullptr, RunThread, (void*)this); } return 0; } @@ -48,8 +43,6 @@ int Thread::StopThread() { return 0; } -int Thread::JoinThread() { - return pthread_join(thread_id_, nullptr); -} +int Thread::JoinThread() { return pthread_join(thread_id_, nullptr); } } // namespace net diff --git a/src/net/src/net_thread_name.h b/src/net/src/net_thread_name.h index d44d3e3deb..355cd66f1a 100644 --- a/src/net/src/net_thread_name.h +++ b/src/net/src/net_thread_name.h @@ -5,29 +5,29 @@ #ifndef NET_THREAD_NAME_H #define NET_THREAD_NAME_H -#include #include +#include namespace net { #if defined(__GLIBC__) && !defined(__APPLE__) && !defined(__ANDROID__) -# if __GLIBC_PREREQ(2, 12) - // has pthread_setname_np(pthread_t, const char*) (2 params) -# define HAS_PTHREAD_SETNAME_NP 1 -# endif +# if __GLIBC_PREREQ(2, 12) +// has pthread_setname_np(pthread_t, const char*) (2 params) +# define HAS_PTHREAD_SETNAME_NP 1 +# endif #endif #ifdef HAS_PTHREAD_SETNAME_NP inline bool SetThreadName(pthread_t id, const std::string& name) { - //printf ("use pthread_setname_np(%s)\n", name.substr(0, 15).c_str()); + // printf ("use pthread_setname_np(%s)\n", name.substr(0, 15).c_str()); return 0 == pthread_setname_np(id, name.substr(0, 15).c_str()); } #else inline bool SetThreadName(pthread_t id, const std::string& name) { - //printf ("no pthread_setname\n"); + // printf ("no pthread_setname\n"); return false; } #endif -} +} // namespace net #endif diff --git a/src/net/src/pb_cli.cc b/src/net/src/pb_cli.cc index f79c6b5a0b..08b0e1e5c7 100644 --- a/src/net/src/pb_cli.cc +++ b/src/net/src/pb_cli.cc @@ -3,14 +3,14 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include #include -#include #include +#include +#include -#include "pstd/include/xdebug.h" #include "net/include/net_cli.h" #include "net/include/net_define.h" +#include "pstd/include/xdebug.h" namespace net { @@ -21,25 +21,23 @@ class PbCli : public NetCli { virtual ~PbCli(); // msg should have been parsed - virtual Status Send(void *msg_req) override; + virtual Status Send(void* msg_req) override; // Read, parse and store the reply - virtual Status Recv(void *msg_res) override; - + virtual Status Recv(void* msg_res) override; private: // BuildWbuf need to access rbuf_, wbuf_; - char *rbuf_; - char *wbuf_; + char* rbuf_; + char* wbuf_; PbCli(const PbCli&); - void operator= (const PbCli&); + void operator=(const PbCli&); }; -PbCli::PbCli(const std::string& ip, const int port) - : NetCli(ip, port) { - rbuf_ = reinterpret_cast(malloc(sizeof(char) * kProtoMaxMessage)); - wbuf_ = reinterpret_cast(malloc(sizeof(char) * kProtoMaxMessage)); +PbCli::PbCli(const std::string& ip, const int port) : NetCli(ip, port) { + rbuf_ = reinterpret_cast(malloc(sizeof(char) * kProtoMaxMessage)); + wbuf_ = reinterpret_cast(malloc(sizeof(char) * kProtoMaxMessage)); } PbCli::~PbCli() { @@ -47,9 +45,8 @@ PbCli::~PbCli() { free(rbuf_); } -Status PbCli::Send(void *msg) { - google::protobuf::Message *req = - reinterpret_cast(msg); +Status PbCli::Send(void* msg) { + google::protobuf::Message* req = reinterpret_cast(msg); int wbuf_len = req->ByteSizeLong(); req->SerializeToArray(wbuf_ + kCommandHeaderLength, wbuf_len); @@ -60,13 +57,12 @@ Status PbCli::Send(void *msg) { return NetCli::SendRaw(wbuf_, wbuf_len); } -Status PbCli::Recv(void *msg_res) { - google::protobuf::Message *res = - reinterpret_cast(msg_res); +Status PbCli::Recv(void* msg_res) { + google::protobuf::Message* res = reinterpret_cast(msg_res); // Read Header size_t read_len = kCommandHeaderLength; - Status s = RecvRaw(reinterpret_cast(rbuf_), &read_len); + Status s = RecvRaw(reinterpret_cast(rbuf_), &read_len); if (!s.ok()) { return s; } @@ -81,14 +77,12 @@ Status PbCli::Recv(void *msg_res) { return s; } - if (!res->ParseFromArray(rbuf_ , packet_len)) { + if (!res->ParseFromArray(rbuf_, packet_len)) { return Status::Corruption("PbCli::Recv Protobuf ParseFromArray error"); } return Status::OK(); } -NetCli *NewPbCli(const std::string& peer_ip, const int peer_port) { - return new PbCli(peer_ip, peer_port); -} +NetCli* NewPbCli(const std::string& peer_ip, const int peer_port) { return new PbCli(peer_ip, peer_port); } } // namespace net diff --git a/src/net/src/pb_conn.cc b/src/net/src/pb_conn.cc index ea72d3dbe8..cf351de710 100644 --- a/src/net/src/pb_conn.cc +++ b/src/net/src/pb_conn.cc @@ -8,27 +8,25 @@ #include #include -#include "pstd/include/xdebug.h" #include "net/include/net_define.h" +#include "pstd/include/xdebug.h" namespace net { -PbConn::PbConn(const int fd, const std::string &ip_port, Thread *thread, NetMultiplexer* mpx) : - NetConn(fd, ip_port, thread, mpx), - header_len_(-1), - cur_pos_(0), - rbuf_len_(0), - remain_packet_len_(0), - connStatus_(kHeader), - write_buf_(0), - is_reply_(0) { - rbuf_ = reinterpret_cast(malloc(sizeof(char) * PB_IOBUF_LEN)); +PbConn::PbConn(const int fd, const std::string& ip_port, Thread* thread, NetMultiplexer* mpx) + : NetConn(fd, ip_port, thread, mpx), + header_len_(-1), + cur_pos_(0), + rbuf_len_(0), + remain_packet_len_(0), + connStatus_(kHeader), + write_buf_(0), + is_reply_(0) { + rbuf_ = reinterpret_cast(malloc(sizeof(char) * PB_IOBUF_LEN)); rbuf_len_ = PB_IOBUF_LEN; } -PbConn::~PbConn() { - free(rbuf_); -} +PbConn::~PbConn() { free(rbuf_); } // Msg is [ length(COMMAND_HEADER_LENGTH) | body(length bytes) ] // step 1. kHeader, we read COMMAND_HEADER_LENGTH bytes; @@ -37,8 +35,7 @@ ReadStatus PbConn::GetRequest() { while (true) { switch (connStatus_) { case kHeader: { - ssize_t nread = read( - fd(), rbuf_ + cur_pos_, COMMAND_HEADER_LENGTH - cur_pos_); + ssize_t nread = read(fd(), rbuf_ + cur_pos_, COMMAND_HEADER_LENGTH - cur_pos_); if (nread == -1) { if (errno == EAGAIN) { return kReadHalf; @@ -51,8 +48,7 @@ ReadStatus PbConn::GetRequest() { cur_pos_ += nread; if (cur_pos_ == COMMAND_HEADER_LENGTH) { uint32_t integer = 0; - memcpy(reinterpret_cast(&integer), - rbuf_, sizeof(uint32_t)); + memcpy(reinterpret_cast(&integer), rbuf_, sizeof(uint32_t)); header_len_ = ntohl(integer); remain_packet_len_ = header_len_; connStatus_ = kPacket; @@ -65,7 +61,7 @@ ReadStatus PbConn::GetRequest() { if (header_len_ > rbuf_len_ - COMMAND_HEADER_LENGTH) { uint32_t new_size = header_len_ + COMMAND_HEADER_LENGTH; if (new_size < kProtoMaxMessage) { - rbuf_ = reinterpret_cast(realloc(rbuf_, sizeof(char) * new_size)); + rbuf_ = reinterpret_cast(realloc(rbuf_, sizeof(char) * new_size)); if (rbuf_ == NULL) { return kFullError; } @@ -166,7 +162,6 @@ bool PbConn::is_reply() { } int PbConn::WriteResp(const std::string& resp) { - std::string tag; BuildInternalTag(resp, &tag); pstd::MutexLock l(&resp_mu_); @@ -186,15 +181,12 @@ void PbConn::TryResizeBuffer() { struct timeval now; gettimeofday(&now, nullptr); int idletime = now.tv_sec - last_interaction().tv_sec; - if (rbuf_len_ > PB_IOBUF_LEN && - ((rbuf_len_ / (cur_pos_ + 1)) > 2 || idletime > 2)) { - uint32_t new_size = - ((cur_pos_ + PB_IOBUF_LEN) / PB_IOBUF_LEN) * PB_IOBUF_LEN; + if (rbuf_len_ > PB_IOBUF_LEN && ((rbuf_len_ / (cur_pos_ + 1)) > 2 || idletime > 2)) { + uint32_t new_size = ((cur_pos_ + PB_IOBUF_LEN) / PB_IOBUF_LEN) * PB_IOBUF_LEN; if (new_size < rbuf_len_) { rbuf_ = static_cast(realloc(rbuf_, new_size)); rbuf_len_ = new_size; - log_info("Thread_id %ld Shrink rbuf to %u, cur_pos_: %u\n", - pthread_self(), rbuf_len_, cur_pos_); + log_info("Thread_id %ld Shrink rbuf to %u, cur_pos_: %u\n", pthread_self(), rbuf_len_, cur_pos_); } } } diff --git a/src/net/src/period_thread.cc b/src/net/src/period_thread.cc index bd9d668093..0067d3820a 100644 --- a/src/net/src/period_thread.cc +++ b/src/net/src/period_thread.cc @@ -9,11 +9,9 @@ namespace net { -PeriodThread::PeriodThread(struct timeval period) : - period_(period) { -} +PeriodThread::PeriodThread(struct timeval period) : period_(period) {} -void *PeriodThread::ThreadMain() { +void* PeriodThread::ThreadMain() { PeriodMain(); select(0, NULL, NULL, NULL, &period_); return NULL; diff --git a/src/net/src/redis_cli.cc b/src/net/src/redis_cli.cc index 63c7225b12..604c54c3a4 100644 --- a/src/net/src/redis_cli.cc +++ b/src/net/src/redis_cli.cc @@ -5,18 +5,17 @@ #include "net/include/redis_cli.h" -#include #include -#include +#include #include +#include +#include #include #include -#include -#include "net/include/net_define.h" #include "net/include/net_cli.h" - +#include "net/include/net_define.h" namespace net { @@ -26,19 +25,19 @@ class RedisCli : public NetCli { virtual ~RedisCli(); // msg should have been parsed - virtual Status Send(void *msg); + virtual Status Send(void* msg); // Read, parse and store the reply - virtual Status Recv(void *result = NULL); + virtual Status Recv(void* result = NULL); private: - RedisCmdArgsType argv_; // The parsed result + RedisCmdArgsType argv_; // The parsed result - char *rbuf_; + char* rbuf_; int32_t rbuf_size_; int32_t rbuf_pos_; int32_t rbuf_offset_; - int elements_; // the elements number of this current reply + int elements_; // the elements number of this current reply int err_; int GetReply(); @@ -50,7 +49,7 @@ class RedisCli : public NetCli { ssize_t BufferRead(); char* ReadBytes(unsigned int bytes); - char* ReadLine(int *_len); + char* ReadLine(int* _len); // No copyable RedisCli(const RedisCli&); @@ -60,7 +59,7 @@ class RedisCli : public NetCli { enum REDIS_STATUS { REDIS_ETIMEOUT = -5, REDIS_EREAD_NULL = -4, - REDIS_EREAD = -3, // errno is set + REDIS_EREAD = -3, // errno is set REDIS_EPARSE_TYPE = -2, REDIS_ERR = -1, REDIS_OK = 0, @@ -73,26 +72,19 @@ enum REDIS_STATUS { REDIS_REPLY_ERROR }; -RedisCli::RedisCli() - : rbuf_size_(REDIS_IOBUF_LEN), - rbuf_pos_(0), - rbuf_offset_(0), - err_(REDIS_OK) { +RedisCli::RedisCli() : rbuf_size_(REDIS_IOBUF_LEN), rbuf_pos_(0), rbuf_offset_(0), err_(REDIS_OK) { rbuf_ = reinterpret_cast(malloc(sizeof(char) * rbuf_size_)); - } -RedisCli::~RedisCli() { - free(rbuf_); -} +RedisCli::~RedisCli() { free(rbuf_); } // We use passed-in send buffer here -Status RedisCli::Send(void *msg) { +Status RedisCli::Send(void* msg) { Status s; // TODO(anan) use socket_->SendRaw instead - std::string* storage = reinterpret_cast(msg); - const char *wbuf = storage->data(); + std::string* storage = reinterpret_cast(msg); + const char* wbuf = storage->data(); size_t nleft = storage->size(); int wbuf_pos = 0; @@ -103,8 +95,8 @@ Status RedisCli::Send(void *msg) { if (errno == EINTR) { nwritten = 0; continue; - // blocking fd after setting setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,...) - // will return EAGAIN | EWOULDBLOCK for timeout + // blocking fd after setting setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO,...) + // will return EAGAIN | EWOULDBLOCK for timeout } else if (errno == EAGAIN || errno == EWOULDBLOCK) { s = Status::Timeout("Send timeout"); } else { @@ -121,7 +113,7 @@ Status RedisCli::Send(void *msg) { } // The result is useless -Status RedisCli::Recv(void *trival) { +Status RedisCli::Recv(void* trival) { argv_.clear(); int result = GetReply(); switch (result) { @@ -139,8 +131,7 @@ Status RedisCli::Recv(void *trival) { case REDIS_EPARSE_TYPE: return Status::IOError("invalid type"); default: // other error - return Status::IOError( - "other error, maybe " + std::string(strerror(errno))); + return Status::IOError("other error, maybe " + std::string(strerror(errno))); } } @@ -161,14 +152,14 @@ ssize_t RedisCli::BufferRead() { if (nread == -1) { if (errno == EINTR) { continue; - // blocking fd after setting setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,...) - // will return EAGAIN for timeout + // blocking fd after setting setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,...) + // will return EAGAIN for timeout } else if (errno == EAGAIN || errno == EWOULDBLOCK) { return REDIS_ETIMEOUT; } else { return REDIS_EREAD; } - } else if (nread == 0) { // we consider read null an error + } else if (nread == 0) { // we consider read null an error return REDIS_EREAD_NULL; } @@ -178,7 +169,7 @@ ssize_t RedisCli::BufferRead() { } /* Find pointer to \r\n. */ -static char *seekNewline(char *s, size_t len) { +static char* seekNewline(char* s, size_t len) { int pos = 0; int _len = len - 1; @@ -192,9 +183,9 @@ static char *seekNewline(char *s, size_t len) { /* Not found. */ return NULL; } else { - if (s[pos+1] == '\n') { + if (s[pos + 1] == '\n') { /* Found. */ - return s+pos; + return s + pos; } else { /* Continue searching. */ pos++; @@ -206,7 +197,7 @@ static char *seekNewline(char *s, size_t len) { /* Read a long long value starting at *s, under the assumption that it will be * terminated by \r\n. Ambiguously returns -1 for unexpected input. */ -static long long readLongLong(char *s) { +static long long readLongLong(char* s) { long long v = 0; int dec, mult = 1; char c; @@ -230,11 +221,11 @@ static long long readLongLong(char *s) { } } - return mult*v; + return mult * v; } int RedisCli::ProcessLineItem() { - char *p; + char* p; int len; if ((p = ReadLine(&len)) == NULL) { @@ -269,7 +260,7 @@ int RedisCli::ProcessBulkItem() { argv_.push_back(std::string(p + bytelen, len)); elements_--; - bytelen += len + 2; /* include \r\n */ + bytelen += len + 2; /* include \r\n */ rbuf_pos_ += bytelen; rbuf_offset_ -= bytelen; return REDIS_OK; @@ -280,7 +271,7 @@ int RedisCli::ProcessBulkItem() { } int RedisCli::ProcessMultiBulkItem() { - char *p; + char* p; int len; if ((p = ReadLine(&len)) != NULL) { @@ -313,7 +304,7 @@ int RedisCli::GetReply() { } char* RedisCli::ReadBytes(unsigned int bytes) { - char *p = NULL; + char* p = NULL; if ((unsigned int)rbuf_offset_ >= bytes) { p = rbuf_ + rbuf_pos_; rbuf_pos_ += bytes; @@ -322,7 +313,7 @@ char* RedisCli::ReadBytes(unsigned int bytes) { return p; } -char *RedisCli::ReadLine(int *_len) { +char* RedisCli::ReadLine(int* _len) { char *p, *s; int len; @@ -347,7 +338,7 @@ int RedisCli::GetReplyFromReader() { return REDIS_HALF; } - char *p; + char* p; if ((p = ReadBytes(1)) == NULL) { return REDIS_HALF; } @@ -392,9 +383,7 @@ int RedisCli::GetReplyFromReader() { } } -NetCli *NewRedisCli() { - return new RedisCli(); -} +NetCli* NewRedisCli() { return new RedisCli(); } // // Redis protocol related funcitons // @@ -414,12 +403,10 @@ static int intlen(int i) { } // Helper that calculates the bulk length given a certain string length. -static size_t bulklen(size_t len) { - return 1 + intlen(len) + 2 + len + 2; -} +static size_t bulklen(size_t len) { return 1 + intlen(len) + 2 + len + 2; } -int redisvFormatCommand(std::string *cmd, const char *format, va_list ap) { - const char *c = format; +int redisvFormatCommand(std::string* cmd, const char* format, va_list ap) { + const char* c = format; std::string curarg; char buf[1048576]; std::vector args; @@ -440,7 +427,7 @@ int redisvFormatCommand(std::string *cmd, const char *format, va_list ap) { touched = 1; } } else { - char *arg = nullptr; + char* arg = nullptr; size_t size = 0; switch (c[1]) { @@ -466,7 +453,7 @@ int redisvFormatCommand(std::string *cmd, const char *format, va_list ap) { { static const char intfmts[] = "diouxX"; char _format[16]; - const char *_p = c+1; + const char* _p = c + 1; size_t _l = 0; va_list _cpy; bool fmt_valid = false; @@ -498,13 +485,13 @@ int redisvFormatCommand(std::string *cmd, const char *format, va_list ap) { /* Double conversion (without modifiers) */ va_arg(ap, double); fmt_valid = true; - } else if (_p[0] == 'h' && _p[1] == 'h') { /* Size: char */ + } else if (_p[0] == 'h' && _p[1] == 'h') { /* Size: char */ _p += 2; if (*_p != '\0' && strchr(intfmts, *_p) != NULL) { - va_arg(ap, int); /* char gets promoted to int */ + va_arg(ap, int); /* char gets promoted to int */ fmt_valid = true; } - } else if (_p[0] == 'h') { /* Size: short */ + } else if (_p[0] == 'h') { /* Size: short */ _p += 1; if (*_p != '\0' && strchr(intfmts, *_p) != NULL) { va_arg(ap, int); /* short gets promoted to int */ @@ -516,7 +503,7 @@ int redisvFormatCommand(std::string *cmd, const char *format, va_list ap) { va_arg(ap, long long); fmt_valid = true; } - } else if (_p[0] == 'l') { /* Size: long */ + } else if (_p[0] == 'l') { /* Size: long */ _p += 1; if (*_p != '\0' && strchr(intfmts, *_p) != NULL) { va_arg(ap, long); @@ -585,7 +572,7 @@ int redisvFormatCommand(std::string *cmd, const char *format, va_list ap) { return totlen; } -int redisvAppendCommand(std::string *cmd, const char *format, va_list ap) { +int redisvAppendCommand(std::string* cmd, const char* format, va_list ap) { int len = redisvFormatCommand(cmd, format, ap); if (len == -1) { return REDIS_ERR; @@ -594,13 +581,12 @@ int redisvAppendCommand(std::string *cmd, const char *format, va_list ap) { return REDIS_OK; } - -int redisFormatCommandArgv(RedisCmdArgsType argv, std::string *cmd) { +int redisFormatCommandArgv(RedisCmdArgsType argv, std::string* cmd) { size_t argc = argv.size(); int totlen = 1 + intlen(argc) + 2; for (size_t i = 0; i < argc; i++) { - totlen += bulklen(argv[i].size()); + totlen += bulklen(argv[i].size()); } cmd->clear(); @@ -620,7 +606,7 @@ int redisFormatCommandArgv(RedisCmdArgsType argv, std::string *cmd) { return REDIS_OK; } -int SerializeRedisCommand(std::string *cmd, const char *format, ...) { +int SerializeRedisCommand(std::string* cmd, const char* format, ...) { va_list ap; va_start(ap, format); int result = redisvAppendCommand(cmd, format, ap); @@ -628,8 +614,6 @@ int SerializeRedisCommand(std::string *cmd, const char *format, ...) { return result; } -int SerializeRedisCommand(RedisCmdArgsType argv, std::string *cmd) { - return redisFormatCommandArgv(argv, cmd); -} +int SerializeRedisCommand(RedisCmdArgsType argv, std::string* cmd) { return redisFormatCommandArgv(argv, cmd); } }; // namespace net diff --git a/src/net/src/redis_conn.cc b/src/net/src/redis_conn.cc index 5c45f4d09b..db270f60f7 100644 --- a/src/net/src/redis_conn.cc +++ b/src/net/src/redis_conn.cc @@ -5,23 +5,19 @@ #include "net/include/redis_conn.h" -#include #include +#include -#include #include +#include -#include "pstd/include/xdebug.h" #include "pstd/include/pstd_string.h" +#include "pstd/include/xdebug.h" namespace net { -RedisConn::RedisConn(const int fd, - const std::string& ip_port, - Thread* thread, - NetMultiplexer* net_mpx, - const HandleType& handle_type, - const int rbuf_max_len) +RedisConn::RedisConn(const int fd, const std::string& ip_port, Thread* thread, NetMultiplexer* net_mpx, + const HandleType& handle_type, const int rbuf_max_len) : NetConn(fd, ip_port, thread, net_mpx), handle_type_(handle_type), rbuf_(nullptr), @@ -39,9 +35,7 @@ RedisConn::RedisConn(const int fd, redis_parser_.data = this; } -RedisConn::~RedisConn() { - free(rbuf_); -} +RedisConn::~RedisConn() { free(rbuf_); } ReadStatus RedisConn::ParseRedisParserStatus(RedisParserStatus status) { if (status == kRedisParserInitDone) { @@ -53,17 +47,17 @@ ReadStatus RedisConn::ParseRedisParserStatus(RedisParserStatus status) { } else if (status == kRedisParserError) { RedisParserError error_code = redis_parser_.get_error_code(); switch (error_code) { - case kRedisParserOk : + case kRedisParserOk: return kReadError; - case kRedisParserInitError : + case kRedisParserInitError: return kReadError; - case kRedisParserFullError : + case kRedisParserFullError: return kFullError; - case kRedisParserProtoError : + case kRedisParserProtoError: return kParseError; - case kRedisParserDealError : + case kRedisParserDealError: return kDealError; - default : + default: return kReadError; } } else { @@ -99,7 +93,7 @@ ReadStatus RedisConn::GetRequest() { if (nread == -1) { if (errno == EAGAIN) { nread = 0; - return kReadHalf; // HALF + return kReadHalf; // HALF } else { // error happened, close client return kReadError; @@ -118,8 +112,7 @@ ReadStatus RedisConn::GetRequest() { } int processed_len = 0; - RedisParserStatus ret = redis_parser_.ProcessInputBuffer( - rbuf_ + next_read_pos, nread, &processed_len); + RedisParserStatus ret = redis_parser_.ProcessInputBuffer(rbuf_ + next_read_pos, nread, &processed_len); ReadStatus read_status = ParseRedisParserStatus(ret); if (read_status == kReadAll || read_status == kReadHalf) { if (read_status == kReadAll) { @@ -131,7 +124,7 @@ ReadStatus RedisConn::GetRequest() { if (!response_.empty()) { set_is_reply(true); } - return read_status; // OK || HALF || FULL_ERROR || PARSE_ERROR + return read_status; // OK || HALF || FULL_ERROR || PARSE_ERROR } WriteStatus RedisConn::SendReply() { @@ -181,30 +174,22 @@ void RedisConn::TryResizeBuffer() { struct timeval now; gettimeofday(&now, nullptr); int idletime = now.tv_sec - last_interaction().tv_sec; - if (rbuf_len_ > REDIS_MBULK_BIG_ARG && - ((rbuf_len_ / (msg_peak_ + 1)) > 2 || idletime > 2)) { - int new_size = - ((last_read_pos_ + REDIS_IOBUF_LEN) / REDIS_IOBUF_LEN) * REDIS_IOBUF_LEN; + if (rbuf_len_ > REDIS_MBULK_BIG_ARG && ((rbuf_len_ / (msg_peak_ + 1)) > 2 || idletime > 2)) { + int new_size = ((last_read_pos_ + REDIS_IOBUF_LEN) / REDIS_IOBUF_LEN) * REDIS_IOBUF_LEN; if (new_size < rbuf_len_) { rbuf_ = static_cast(realloc(rbuf_, new_size)); rbuf_len_ = new_size; - log_info("Resize buffer to %d, last_read_pos_: %d\n", - rbuf_len_, last_read_pos_); + log_info("Resize buffer to %d, last_read_pos_: %d\n", rbuf_len_, last_read_pos_); } msg_peak_ = 0; } } -void RedisConn::SetHandleType(const HandleType& handle_type) { - handle_type_ = handle_type; -} +void RedisConn::SetHandleType(const HandleType& handle_type) { handle_type_ = handle_type; } -HandleType RedisConn::GetHandleType() { - return handle_type_; -} +HandleType RedisConn::GetHandleType() { return handle_type_; } -void RedisConn::ProcessRedisCmds(const std::vector& argvs, bool async, std::string* response) { -} +void RedisConn::ProcessRedisCmds(const std::vector& argvs, bool async, std::string* response) {} void RedisConn::NotifyEpoll(bool success) { NetItem ti(fd(), ip_port(), success ? kNotiEpolloutAndEpollin : kNotiClose); diff --git a/src/net/src/redis_parser.cc b/src/net/src/redis_parser.cc index 37a5784de0..8f8205eabf 100644 --- a/src/net/src/redis_parser.cc +++ b/src/net/src/redis_parser.cc @@ -5,7 +5,7 @@ #include "net/include/redis_parser.h" -#include /* assert */ +#include /* assert */ #include "pstd/include/pstd_string.h" #include "pstd/include/xdebug.h" @@ -13,23 +13,23 @@ namespace net { static bool IsHexDigit(char ch) { - return (ch>='0' && ch<='9') || (ch>='a' && ch<='f') || (ch>='A' && ch<='F'); + return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); } static int HexDigitToInt32(char ch) { if (ch <= '9' && ch >= '0') { - return ch-'0'; + return ch - '0'; } else if (ch <= 'F' && ch >= 'A') { - return ch-'A'; + return ch - 'A'; } else if (ch <= 'f' && ch >= 'a') { - return ch-'a'; + return ch - 'a'; } else { return 0; } } static int split2args(const std::string& req_buf, RedisCmdArgsType& argv) { - const char *p = req_buf.data(); + const char* p = req_buf.data(); std::string arg; while (1) { @@ -37,17 +37,15 @@ static int split2args(const std::string& req_buf, RedisCmdArgsType& argv) { while (*p && isspace(*p)) p++; if (*p) { // get a token - int inq = 0; // set to 1 if we are in "quotes" + int inq = 0; // set to 1 if we are in "quotes" int insq = 0; // set to 1 if we are in 'single quotes' int done = 0; arg.clear(); while (!done) { if (inq) { - if (*p == '\\' && *(p+1) == 'x' && - IsHexDigit(*(p+2)) && - IsHexDigit(*(p+3))) { - unsigned char byte = HexDigitToInt32(*(p+2))*16 + HexDigitToInt32(*(p+3)); + if (*p == '\\' && *(p + 1) == 'x' && IsHexDigit(*(p + 2)) && IsHexDigit(*(p + 3))) { + unsigned char byte = HexDigitToInt32(*(p + 2)) * 16 + HexDigitToInt32(*(p + 3)); arg.append(1, byte); p += 3; } else if (*p == '\\' && *(p + 1)) { @@ -55,18 +53,30 @@ static int split2args(const std::string& req_buf, RedisCmdArgsType& argv) { p++; switch (*p) { - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'b': c = '\b'; break; - case 'a': c = '\a'; break; - default: c = *p; break; + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + case 'b': + c = '\b'; + break; + case 'a': + c = '\a'; + break; + default: + c = *p; + break; } arg.append(1, c); } else if (*p == '"') { /* closing quote must be followed by a space or - * nothing at all. */ - if (*(p+1) && !isspace(*(p+1))) { + * nothing at all. */ + if (*(p + 1) && !isspace(*(p + 1))) { argv.clear(); return -1; } @@ -79,13 +89,13 @@ static int split2args(const std::string& req_buf, RedisCmdArgsType& argv) { arg.append(1, *p); } } else if (insq) { - if (*p == '\\' && *(p+1) == '\'') { + if (*p == '\\' && *(p + 1) == '\'') { p++; arg.append(1, '\''); } else if (*p == '\'') { /* closing quote must be followed by a space or - * nothing at all. */ - if (*(p+1) && !isspace(*(p+1))) { + * nothing at all. */ + if (*(p + 1) && !isspace(*(p + 1))) { argv.clear(); return -1; } @@ -105,13 +115,13 @@ static int split2args(const std::string& req_buf, RedisCmdArgsType& argv) { case '\t': case '\0': done = 1; - break; + break; case '"': inq = 1; - break; + break; case '\'': insq = 1; - break; + break; default: // current = sdscatlen(current,p,1); arg.append(1, *p); @@ -127,7 +137,6 @@ static int split2args(const std::string& req_buf, RedisCmdArgsType& argv) { } } - int RedisParser::FindNextSeparators() { if (cur_pos_ > length_ - 1) { return -1; @@ -149,28 +158,24 @@ int RedisParser::GetNextNum(int pos, long* value) { // | | // *3\r\n // [cur_pos_ + 1, pos - cur_pos_ - 2] - if (pstd::string2int(input_buf_ + cur_pos_ + 1, - pos - cur_pos_ - 2, - value)) { - return 0; // Success + if (pstd::string2int(input_buf_ + cur_pos_ + 1, pos - cur_pos_ - 2, value)) { + return 0; // Success } - return -1; // Failed + return -1; // Failed } RedisParser::RedisParser() - : status_code_(kRedisParserNone), - error_code_(kRedisParserOk), - redis_type_(0), - multibulk_len_(0), - bulk_len_(-1), - redis_parser_type_(REDIS_PARSER_REQUEST), - cur_pos_(0), - input_buf_(NULL), - length_(0) { -} + : status_code_(kRedisParserNone), + error_code_(kRedisParserOk), + redis_type_(0), + multibulk_len_(0), + bulk_len_(-1), + redis_parser_type_(REDIS_PARSER_REQUEST), + cur_pos_(0), + input_buf_(NULL), + length_(0) {} -void RedisParser::SetParserStatus(RedisParserStatus status, - RedisParserError error) { +void RedisParser::SetParserStatus(RedisParserStatus status, RedisParserError error) { if (status == kRedisParserHalf) { CacheHalfArgv(); } @@ -184,8 +189,7 @@ void RedisParser::CacheHalfArgv() { cur_pos_ = length_; } -RedisParserStatus RedisParser::RedisParserInit( - RedisParserType type, const RedisParserSettings& settings) { +RedisParserStatus RedisParser::RedisParserInit(RedisParserType type, const RedisParserSettings& settings) { if (status_code_ != kRedisParserNone) { SetParserStatus(kRedisParserError, kRedisParserInitError); return status_code_; @@ -260,7 +264,7 @@ RedisParserStatus RedisParser::ProcessMultibulkBuffer() { } if (GetNextNum(pos, &bulk_len_) != 0) { - // Protocol error: invalid bulk length + // Protocol error: invalid bulk length SetParserStatus(kRedisParserError, kRedisParserProtoError); return status_code_; } @@ -293,11 +297,12 @@ RedisParserStatus RedisParser::ProcessMultibulkBuffer() { void RedisParser::PrintCurrentStatus() { log_info("status_code %d error_code %d", status_code_, error_code_); - log_info("multibulk_len_ %ld bulk_len %ld redis_type %d redis_parser_type %d", multibulk_len_, bulk_len_, redis_type_, redis_parser_type_); - //for (auto& i : argv_) { - // UNUSED(i); - // log_info("parsed arguments: %s", i.c_str()); - //} + log_info("multibulk_len_ %ld bulk_len %ld redis_type %d redis_parser_type %d", multibulk_len_, bulk_len_, redis_type_, + redis_parser_type_); + // for (auto& i : argv_) { + // UNUSED(i); + // log_info("parsed arguments: %s", i.c_str()); + // } log_info("cur_pos : %d", cur_pos_); log_info("input_buf_ is clean ? %d", input_buf_ == NULL); if (input_buf_ != NULL) { @@ -307,11 +312,8 @@ void RedisParser::PrintCurrentStatus() { log_info("input_buf len %d", length_); } -RedisParserStatus RedisParser::ProcessInputBuffer( - const char* input_buf, int length, int* parsed_len) { - if (status_code_ == kRedisParserInitDone || - status_code_ == kRedisParserHalf || - status_code_ == kRedisParserDone) { +RedisParserStatus RedisParser::ProcessInputBuffer(const char* input_buf, int length, int* parsed_len) { + if (status_code_ == kRedisParserInitDone || status_code_ == kRedisParserHalf || status_code_ == kRedisParserDone) { // TODO AZ: avoid copy std::string tmp_str(input_buf, length); input_str_ = half_argv_ + tmp_str; @@ -328,7 +330,7 @@ RedisParserStatus RedisParser::ProcessInputBuffer( // cur_pos_ starts from 0, val of cur_pos_ is the parsed_len *parsed_len = cur_pos_; ResetRedisParser(); - //PrintCurrentStatus(); + // PrintCurrentStatus(); return status_code_; } SetParserStatus(kRedisParserError, kRedisParserInitError); @@ -359,7 +361,7 @@ RedisParserStatus RedisParser::ProcessRequestBuffer() { } } else if (redis_type_ == REDIS_REQ_MULTIBULK) { ret = ProcessMultibulkBuffer(); - if (ret != kRedisParserDone) { // FULL_ERROR || HALF || PARSE_ERROR + if (ret != kRedisParserDone) { // FULL_ERROR || HALF || PARSE_ERROR return ret; } } else { @@ -387,7 +389,7 @@ RedisParserStatus RedisParser::ProcessRequestBuffer() { } argvs_.clear(); SetParserStatus(kRedisParserDone); - return status_code_; // OK + return status_code_; // OK } void RedisParser::ResetCommandStatus() { diff --git a/src/net/src/server_socket.cc b/src/net/src/server_socket.cc index c51f628578..6f223ca424 100644 --- a/src/net/src/server_socket.cc +++ b/src/net/src/server_socket.cc @@ -3,18 +3,18 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include -#include -#include -#include #include -#include #include +#include +#include +#include #include +#include +#include -#include "net/src/server_socket.h" -#include "net/src/net_util.h" #include "net/include/net_define.h" +#include "net/src/net_util.h" +#include "net/src/server_socket.h" namespace net { @@ -28,18 +28,15 @@ ServerSocket::ServerSocket(int port, bool is_block) tcp_recv_buffer_(0), keep_alive_(false), listening_(false), - is_block_(is_block) { -} + is_block_(is_block) {} -ServerSocket::~ServerSocket() { - Close(); -} +ServerSocket::~ServerSocket() { Close(); } /* * Listen to a specific ip addr on a multi eth machine * Return 0 if Listen success, other wise */ -int ServerSocket::Listen(const std::string &bind_ip) { +int ServerSocket::Listen(const std::string& bind_ip) { int ret = 0; sockfd_ = socket(AF_INET, SOCK_STREAM, 0); memset(&servaddr_, 0, sizeof(servaddr_)); @@ -60,7 +57,7 @@ int ServerSocket::Listen(const std::string &bind_ip) { fcntl(sockfd_, F_SETFD, fcntl(sockfd_, F_GETFD) | FD_CLOEXEC); - ret = bind(sockfd_, (struct sockaddr *) &servaddr_, sizeof(servaddr_)); + ret = bind(sockfd_, (struct sockaddr*)&servaddr_, sizeof(servaddr_)); if (ret < 0) { return kBindError; } @@ -84,8 +81,6 @@ int ServerSocket::SetNonBlock() { return 0; } -void ServerSocket::Close() { - close(sockfd_); -} +void ServerSocket::Close() { close(sockfd_); } } // namespace net diff --git a/src/net/src/server_socket.h b/src/net/src/server_socket.h index 20f0870615..5efc62f5b2 100644 --- a/src/net/src/server_socket.h +++ b/src/net/src/server_socket.h @@ -9,8 +9,8 @@ #include #include -#include #include +#include namespace net { @@ -24,50 +24,30 @@ class ServerSocket { * Listen to a specific ip addr on a multi eth machine * Return 0 if Listen success, <0 other wise */ - int Listen(const std::string &bind_ip = std::string()); + int Listen(const std::string& bind_ip = std::string()); void Close(); /* * The get and set functions */ - void set_port(int port) { - port_ = port; - } - - int port() { - return port_; - } - - void set_keep_alive(bool keep_alive) { - keep_alive_ = keep_alive; - } - bool keep_alive() const { - return keep_alive_; - } - - void set_send_timeout(int send_timeout) { - send_timeout_ = send_timeout; - } - int send_timeout() const { - return send_timeout_; - } - - void set_recv_timeout(int recv_timeout) { - recv_timeout_ = recv_timeout; - } - - int recv_timeout() const { - return recv_timeout_; - } - - int sockfd() const { - return sockfd_; - } - - void set_sockfd(int sockfd) { - sockfd_ = sockfd; - } + void set_port(int port) { port_ = port; } + + int port() { return port_; } + + void set_keep_alive(bool keep_alive) { keep_alive_ = keep_alive; } + bool keep_alive() const { return keep_alive_; } + + void set_send_timeout(int send_timeout) { send_timeout_ = send_timeout; } + int send_timeout() const { return send_timeout_; } + + void set_recv_timeout(int recv_timeout) { recv_timeout_ = recv_timeout; } + + int recv_timeout() const { return recv_timeout_; } + + int sockfd() const { return sockfd_; } + + void set_sockfd(int sockfd) { sockfd_ = sockfd; } private: int SetNonBlock(); diff --git a/src/net/src/server_thread.cc b/src/net/src/server_thread.cc index 9ef0f69559..0445d4723d 100644 --- a/src/net/src/server_thread.cc +++ b/src/net/src/server_thread.cc @@ -6,15 +6,14 @@ #include "net/include/server_thread.h" #include -#include #include -#include #include #include +#include +#include - -#include "pstd/include/xdebug.h" #include "net/src/server_socket.h" +#include "pstd/include/xdebug.h" namespace net { @@ -23,13 +22,11 @@ using pstd::Status; class DefaultServerHandle : public ServerHandle { public: virtual void CronHandle() const override {} - virtual void FdTimeoutHandle( - int fd, const std::string& ip_port) const override { + virtual void FdTimeoutHandle(int fd, const std::string& ip_port) const override { UNUSED(fd); UNUSED(ip_port); } - virtual void FdClosedHandle( - int fd, const std::string& ip_port) const override { + virtual void FdClosedHandle(int fd, const std::string& ip_port) const override { UNUSED(fd); UNUSED(ip_port); } @@ -59,8 +56,7 @@ static const ServerHandle* SanitizeHandle(const ServerHandle* raw_handle) { return raw_handle; } -ServerThread::ServerThread(int port, - int cron_interval, const ServerHandle* handle) +ServerThread::ServerThread(int port, int cron_interval, const ServerHandle* handle) : cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), @@ -73,8 +69,7 @@ ServerThread::ServerThread(int port, ips_.insert("0.0.0.0"); } -ServerThread::ServerThread(const std::string& bind_ip, int port, - int cron_interval, const ServerHandle* handle) +ServerThread::ServerThread(const std::string& bind_ip, int port, int cron_interval, const ServerHandle* handle) : cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), @@ -87,8 +82,8 @@ ServerThread::ServerThread(const std::string& bind_ip, int port, ips_.insert(bind_ip); } -ServerThread::ServerThread(const std::set& bind_ips, int port, - int cron_interval, const ServerHandle* handle) +ServerThread::ServerThread(const std::set& bind_ips, int port, int cron_interval, + const ServerHandle* handle) : cron_interval_(cron_interval), handle_(SanitizeHandle(handle)), own_handle_(handle_ != handle), @@ -108,9 +103,7 @@ ServerThread::~ServerThread() { EVP_cleanup(); } #endif - for (std::vector::iterator iter = server_sockets_.begin(); - iter != server_sockets_.end(); - ++iter) { + for (std::vector::iterator iter = server_sockets_.begin(); iter != server_sockets_.end(); ++iter) { delete *iter; } if (own_handle_) { @@ -126,8 +119,7 @@ int ServerThread::SetTcpNoDelay(int connfd) { int ServerThread::StartThread() { int ret = 0; ret = InitHandle(); - if (ret != kSuccess) - return ret; + if (ret != kSuccess) return ret; return Thread::StartThread(); } @@ -138,9 +130,7 @@ int ServerThread::InitHandle() { ips_.clear(); ips_.insert("0.0.0.0"); } - for (std::set::iterator iter = ips_.begin(); - iter != ips_.end(); - ++iter) { + for (std::set::iterator iter = ips_.begin(); iter != ips_.end(); ++iter) { socket_p = new ServerSocket(port_); server_sockets_.push_back(socket_p); ret = socket_p->Listen(*iter); @@ -149,23 +139,19 @@ int ServerThread::InitHandle() { } // init pool - net_multiplexer_->NetAddEvent( - socket_p->sockfd(), kReadable | kWritable); + net_multiplexer_->NetAddEvent(socket_p->sockfd(), kReadable | kWritable); server_fds_.insert(socket_p->sockfd()); } return kSuccess; } -void ServerThread::DoCronTask() { -} +void ServerThread::DoCronTask() {} -void ServerThread::ProcessNotifyEvents(const NetFiredEvent* pfe) { - UNUSED(pfe); -} +void ServerThread::ProcessNotifyEvents(const NetFiredEvent* pfe) { UNUSED(pfe); } -void *ServerThread::ThreadMain() { +void* ServerThread::ThreadMain() { int nfds; - NetFiredEvent *pfe; + NetFiredEvent* pfe; Status s; struct sockaddr_in cliaddr; socklen_t clilen = sizeof(struct sockaddr); @@ -189,10 +175,8 @@ void *ServerThread::ThreadMain() { while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, nullptr); - if (when.tv_sec > now.tv_sec || - (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { - timeout = (when.tv_sec - now.tv_sec) * 1000 + - (when.tv_usec - now.tv_usec) / 1000; + if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { + timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { // Do own cron task as well as user's DoCronTask(); @@ -219,28 +203,24 @@ void *ServerThread::ThreadMain() { */ if (server_fds_.find(fd) != server_fds_.end()) { if (pfe->mask & kReadable) { - connfd = accept(fd, (struct sockaddr *) &cliaddr, &clilen); + connfd = accept(fd, (struct sockaddr*)&cliaddr, &clilen); if (connfd == -1) { - log_warn("accept error, errno numberis %d, error reason %s", - errno, strerror(errno)); + log_warn("accept error, errno numberis %d, error reason %s", errno, strerror(errno)); continue; } fcntl(connfd, F_SETFD, fcntl(connfd, F_GETFD) | FD_CLOEXEC); // not use nagel to avoid tcp 40ms delay if (SetTcpNoDelay(connfd) == -1) { - log_warn("setsockopt error, errno numberis %d, error reason %s", - errno, strerror(errno)); + log_warn("setsockopt error, errno numberis %d, error reason %s", errno, strerror(errno)); close(connfd); continue; } // Just ip - ip_port = - inet_ntop(AF_INET, &cliaddr.sin_addr, ip_addr, sizeof(ip_addr)); + ip_port = inet_ntop(AF_INET, &cliaddr.sin_addr, ip_addr, sizeof(ip_addr)); - if (!handle_->AccessHandle(ip_port) || - !handle_->AccessHandle(connfd, ip_port)) { + if (!handle_->AccessHandle(ip_port) || !handle_->AccessHandle(connfd, ip_port)) { close(connfd); continue; } @@ -272,8 +252,7 @@ void *ServerThread::ThreadMain() { } } - for (auto iter = server_sockets_.begin(); iter != server_sockets_.end(); - iter++) { + for (auto iter = server_sockets_.begin(); iter != server_sockets_.end(); iter++) { delete *iter; } server_sockets_.clear(); @@ -293,12 +272,9 @@ static void SSLLockingCallback(int mode, int type, const char* file, int line) { } } -static unsigned long SSLIdCallback() { - return (unsigned long)pthread_self(); -} +static unsigned long SSLIdCallback() { return (unsigned long)pthread_self(); } -int ServerThread::EnableSecurity(const std::string& cert_file, - const std::string& key_file) { +int ServerThread::EnableSecurity(const std::string& cert_file, const std::string& key_file) { if (cert_file.empty() || key_file.empty()) { log_warn("cert_file and key_file can not be empty!"); } @@ -327,14 +303,12 @@ int ServerThread::EnableSecurity(const std::string& cert_file, } // 5. Set cert file and key file, then check key file - if (SSL_CTX_use_certificate_file( - ssl_ctx_, cert_file.c_str(), SSL_FILETYPE_PEM) != 1) { + if (SSL_CTX_use_certificate_file(ssl_ctx_, cert_file.c_str(), SSL_FILETYPE_PEM) != 1) { log_warn("SSL_CTX_use_certificate_file(%s) failed", cert_file.c_str()); return -1; } - if (SSL_CTX_use_PrivateKey_file( - ssl_ctx_, key_file.c_str(), SSL_FILETYPE_PEM) != 1) { + if (SSL_CTX_use_PrivateKey_file(ssl_ctx_, key_file.c_str(), SSL_FILETYPE_PEM) != 1) { log_warn("SSL_CTX_use_PrivateKey_file(%s)", key_file.c_str()); return -1; } @@ -357,7 +331,7 @@ int ServerThread::EnableSecurity(const std::string& cert_file, // https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman // https://wiki.openssl.org/index.php/Diffie_Hellman // https://wiki.openssl.org/index.php/Diffie-Hellman_parameters - EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + EC_KEY* ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (!ecdh) { log_warn("EC_KEY_new_by_curve_name(%d)", NID_X9_62_prime256v1); return -1; diff --git a/src/net/src/simple_http_conn.cc b/src/net/src/simple_http_conn.cc index 8c497bd6fd..3796dabb32 100644 --- a/src/net/src/simple_http_conn.cc +++ b/src/net/src/simple_http_conn.cc @@ -4,16 +4,16 @@ // of patent rights can be found in the PATENTS file in the same directory. #include "net/include/simple_http_conn.h" -#include #include #include +#include -#include #include +#include -#include "pstd/include/xdebug.h" -#include "pstd/include/pstd_string.h" #include "net/include/net_define.h" +#include "pstd/include/pstd_string.h" +#include "pstd/include/xdebug.h" namespace net { @@ -21,47 +21,44 @@ static const uint32_t kHTTPMaxMessage = 1024 * 1024 * 8; static const uint32_t kHTTPMaxHeader = 1024 * 64; static const std::map http_status_map = { - {100, "Continue"}, - {101, "Switching Protocols"}, - {102, "Processing"}, - - {200, "OK"}, - {201, "Created"}, - {202, "Accepted"}, - {203, "Non-Authoritative Information"}, - {204, "No Content"}, - {205, "Reset Content"}, - {206, "Partial Content"}, - {207, "Multi-Status"}, - - {400, "Bad Request"}, - {401, "Unauthorized"}, - {402, ""}, // reserve - {403, "Forbidden"}, - {404, "Not Found"}, - {405, "Method Not Allowed"}, - {406, "Not Acceptable"}, - {407, "Proxy Authentication Required"}, - {408, "Request Timeout"}, - {409, "Conflict"}, - {416, "Requested Range not satisfiable"}, - - {500, "Internal Server Error"}, - {501, "Not Implemented"}, - {502, "Bad Gateway"}, - {503, "Service Unavailable"}, - {504, "Gateway Timeout"}, - {505, "HTTP Version Not Supported"}, - {506, "Variant Also Negotiates"}, - {507, "Insufficient Storage"}, - {508, "Bandwidth Limit Exceeded"}, - {509, "Not Extended"}, + {100, "Continue"}, + {101, "Switching Protocols"}, + {102, "Processing"}, + + {200, "OK"}, + {201, "Created"}, + {202, "Accepted"}, + {203, "Non-Authoritative Information"}, + {204, "No Content"}, + {205, "Reset Content"}, + {206, "Partial Content"}, + {207, "Multi-Status"}, + + {400, "Bad Request"}, + {401, "Unauthorized"}, + {402, ""}, // reserve + {403, "Forbidden"}, + {404, "Not Found"}, + {405, "Method Not Allowed"}, + {406, "Not Acceptable"}, + {407, "Proxy Authentication Required"}, + {408, "Request Timeout"}, + {409, "Conflict"}, + {416, "Requested Range not satisfiable"}, + + {500, "Internal Server Error"}, + {501, "Not Implemented"}, + {502, "Bad Gateway"}, + {503, "Service Unavailable"}, + {504, "Gateway Timeout"}, + {505, "HTTP Version Not Supported"}, + {506, "Variant Also Negotiates"}, + {507, "Insufficient Storage"}, + {508, "Bandwidth Limit Exceeded"}, + {509, "Not Extended"}, }; -Request::Request(): - method("GET"), - path("/index") { -} +Request::Request() : method("GET"), path("/index") {} inline int find_lf(const char* data, int size) { const char* c = data; @@ -76,8 +73,7 @@ inline int find_lf(const char* data, int size) { return count; } -bool Request::ParseHeadLine(const char* data, int line_start, - int line_end, ParseStatus* parseStatus) { +bool Request::ParseHeadLine(const char* data, int line_start, int line_end, ParseStatus* parseStatus) { std::string param_key; std::string param_value; for (int i = line_start; i <= line_end; i++) { @@ -128,8 +124,7 @@ bool Request::ParseHeadLine(const char* data, int line_start, bool Request::ParseGetUrl() { // Format path - if (path.find(headers["host"]) != std::string::npos && - path.size() > (7 + headers["host"].size())) { + if (path.find(headers["host"]) != std::string::npos && path.size() > (7 + headers["host"].size())) { // http://www.xxx.xxx/path/to path.assign(path.substr(7 + headers["host"].size())); } @@ -146,8 +141,7 @@ bool Request::ParseGetUrl() { // Parse query parameter from GET url or POST application/x-www-form-urlencoded // format: key1=value1&key2=value2&key3=value3 -bool Request::ParseParameters(const std::string data, - size_t line_start, bool from_url) { +bool Request::ParseParameters(const std::string data, size_t line_start, bool from_url) { size_t pre = line_start, mid, end; while (pre < data.size()) { mid = data.find('=', pre); @@ -161,20 +155,16 @@ bool Request::ParseParameters(const std::string data, if (end <= mid) { // empty value if (from_url) { - query_params[data.substr(pre, end - pre)] - = std::string(); + query_params[data.substr(pre, end - pre)] = std::string(); } else { - post_params[data.substr(pre, end - pre)] - = std::string(); + post_params[data.substr(pre, end - pre)] = std::string(); } pre = end + 1; } else { if (from_url) { - query_params[data.substr(pre, mid - pre)] - = data.substr(mid + 1, end - mid - 1); + query_params[data.substr(pre, mid - pre)] = data.substr(mid + 1, end - mid - 1); } else { - post_params[data.substr(pre, mid - pre)] - = data.substr(mid + 1, end - mid - 1); + post_params[data.substr(pre, mid - pre)] = data.substr(mid + 1, end - mid - 1); } pre = end + 1; } @@ -213,8 +203,7 @@ bool Request::ParseHeadFromArray(const char* data, const int size) { bool Request::ParseBodyFromArray(const char* data, const int size) { content.append(data, size); - if (method == "POST" && - headers["content-type"] == "application/x-www-form-urlencoded") { + if (method == "POST" && headers["content-type"] == "application/x-www-form-urlencoded") { return ParseParameters(content, 0, false); } return true; @@ -243,8 +232,7 @@ int Response::SerializeHeaderToArray(char* data, size_t size) { int ret; // Serialize statues line - ret = snprintf(data, size, "HTTP/1.1 %d %s\r\n", - status_code_, reason_phrase_.c_str()); + ret = snprintf(data, size, "HTTP/1.1 %d %s\r\n", status_code_, reason_phrase_.c_str()); if (ret < 0 || ret == static_cast(size)) { return ret; } @@ -254,9 +242,8 @@ int Response::SerializeHeaderToArray(char* data, size_t size) { if (headers_.find("Content-Length") == headers_.end()) { SetHeaders("Content-Length", body_.size()); } - for (auto &line : headers_) { - ret = snprintf(data + serial_size, size - serial_size, "%s: %s\r\n", - line.first.c_str(), line.second.c_str()); + for (auto& line : headers_) { + ret = snprintf(data + serial_size, size - serial_size, "%s: %s\r\n", line.first.c_str(), line.second.c_str()); if (ret < 0) { return ret; } @@ -284,17 +271,13 @@ int Response::SerializeBodyToArray(char* data, size_t size, int* pos) { } void Response::SetStatusCode(int code) { - assert((code >= 100 && code <= 102) || - (code >= 200 && code <= 207) || - (code >= 400 && code <= 409) || - (code == 416) || - (code >= 500 && code <= 509)); + assert((code >= 100 && code <= 102) || (code >= 200 && code <= 207) || (code >= 400 && code <= 409) || + (code == 416) || (code >= 500 && code <= 509)); status_code_ = code; reason_phrase_.assign(http_status_map.at(code)); } -SimpleHTTPConn::SimpleHTTPConn(const int fd, const std::string &ip_port, - Thread *thread) +SimpleHTTPConn::SimpleHTTPConn(const int fd, const std::string& ip_port, Thread* thread) : NetConn(fd, ip_port, thread), conn_status_(kHeader), rbuf_pos_(0), @@ -343,8 +326,7 @@ bool SimpleHTTPConn::BuildRequestHeader() { } bool SimpleHTTPConn::AppendRequestBody() { - return request_->ParseBodyFromArray(rbuf_ + header_len_, - rbuf_pos_ - header_len_); + return request_->ParseBodyFromArray(rbuf_ + header_len_, rbuf_pos_ - header_len_); } void SimpleHTTPConn::HandleMessage() { @@ -367,7 +349,7 @@ ReadStatus SimpleHTTPConn::GetRequest() { rbuf_pos_ += nread; // So that strstr will not parse the expire char rbuf_[rbuf_pos_] = '\0'; - char *sep_pos = strstr(rbuf_, "\r\n\r\n"); + char* sep_pos = strstr(rbuf_, "\r\n\r\n"); if (!sep_pos) { break; } @@ -376,16 +358,14 @@ ReadStatus SimpleHTTPConn::GetRequest() { return kReadError; } - std::string sign = request_->headers.count("expect") ? - request_->headers.at("expect") : ""; + std::string sign = request_->headers.count("expect") ? request_->headers.at("expect") : ""; if (sign == "100-continue" || sign == "100-Continue") { // Reply 100 Continue, then receive body response_->Clear(); response_->SetStatusCode(100); set_is_reply(true); conn_status_ = kPacket; - if (remain_packet_len_ > 0) - return kReadHalf; + if (remain_packet_len_ > 0) return kReadHalf; } conn_status_ = kPacket; } @@ -393,9 +373,9 @@ ReadStatus SimpleHTTPConn::GetRequest() { } case kPacket: { if (remain_packet_len_ > 0) { - nread = read(fd(), rbuf_ + rbuf_pos_, - (kHTTPMaxMessage - rbuf_pos_ > remain_packet_len_) - ? remain_packet_len_ : kHTTPMaxMessage - rbuf_pos_); + nread = read( + fd(), rbuf_ + rbuf_pos_, + (kHTTPMaxMessage - rbuf_pos_ > remain_packet_len_) ? remain_packet_len_ : kHTTPMaxMessage - rbuf_pos_); if (nread == -1 && errno == EAGAIN) { return kReadHalf; } else if (nread <= 0) { @@ -405,7 +385,7 @@ ReadStatus SimpleHTTPConn::GetRequest() { remain_packet_len_ -= nread; } } - if (remain_packet_len_ == 0 || // no more content + if (remain_packet_len_ == 0 || // no more content rbuf_pos_ == kHTTPMaxMessage) { // buffer full AppendRequestBody(); if (remain_packet_len_ == 0) { @@ -433,19 +413,16 @@ ReadStatus SimpleHTTPConn::GetRequest() { bool SimpleHTTPConn::FillResponseBuf() { if (response_pos_ < 0) { // Not ever serialize response header - int actual = response_->SerializeHeaderToArray(wbuf_ + wbuf_len_, - kHTTPMaxMessage - wbuf_len_); + int actual = response_->SerializeHeaderToArray(wbuf_ + wbuf_len_, kHTTPMaxMessage - wbuf_len_); if (actual < 0) { return false; } wbuf_len_ += actual; response_pos_ = 0; // Serialize body next time } - while (response_->HasMoreBody(response_pos_) - && wbuf_len_ < kHTTPMaxMessage) { + while (response_->HasMoreBody(response_pos_) && wbuf_len_ < kHTTPMaxMessage) { // Has more body and more space in wbuf_ - wbuf_len_ += response_->SerializeBodyToArray(wbuf_ + wbuf_len_, - kHTTPMaxMessage - wbuf_len_, &response_pos_); + wbuf_len_ += response_->SerializeBodyToArray(wbuf_ + wbuf_len_, kHTTPMaxMessage - wbuf_len_, &response_pos_); } return true; } diff --git a/src/net/src/test/net_thread_test.cc b/src/net/src/test/net_thread_test.cc index a7cc1c9722..dfbe289971 100644 --- a/src/net/src/test/net_thread_test.cc +++ b/src/net/src/test/net_thread_test.cc @@ -27,11 +27,9 @@ class MockThread : public net::Thread { TEST(NetThreadTest, ThreadOps) { MockThread t; - EXPECT_CALL(t, ThreadMain()) - .Times(AtLeast(1)); + EXPECT_CALL(t, ThreadMain()).Times(AtLeast(1)); - ON_CALL(t, ThreadMain()) - .WillByDefault(Invoke(&t, &MockThread::thread_loop)); + ON_CALL(t, ThreadMain()).WillByDefault(Invoke(&t, &MockThread::thread_loop)); EXPECT_EQ(0, t.StartThread()); diff --git a/src/net/src/thread_pool.cc b/src/net/src/thread_pool.cc index 7aee8fd6af..c1bbdc3e1b 100644 --- a/src/net/src/thread_pool.cc +++ b/src/net/src/thread_pool.cc @@ -39,21 +39,17 @@ int ThreadPool::Worker::stop() { return 0; } -ThreadPool::ThreadPool(size_t worker_num, - size_t max_queue_size, - const std::string& thread_pool_name) : - worker_num_(worker_num), - max_queue_size_(max_queue_size), - thread_pool_name_(thread_pool_name), - running_(false), - should_stop_(false), - mu_(), - rsignal_(&mu_), - wsignal_(&mu_) {} - -ThreadPool::~ThreadPool() { - stop_thread_pool(); -} +ThreadPool::ThreadPool(size_t worker_num, size_t max_queue_size, const std::string& thread_pool_name) + : worker_num_(worker_num), + max_queue_size_(max_queue_size), + thread_pool_name_(thread_pool_name), + running_(false), + should_stop_(false), + mu_(), + rsignal_(&mu_), + wsignal_(&mu_) {} + +ThreadPool::~ThreadPool() { stop_thread_pool(); } int ThreadPool::start_thread_pool() { if (!running_.load()) { @@ -90,13 +86,9 @@ int ThreadPool::stop_thread_pool() { return res; } -bool ThreadPool::should_stop() { - return should_stop_.load(); -} +bool ThreadPool::should_stop() { return should_stop_.load(); } -void ThreadPool::set_should_stop() { - should_stop_.store(true); -} +void ThreadPool::set_should_stop() { should_stop_.store(true); } void ThreadPool::Schedule(TaskFunc func, void* arg) { mu_.Lock(); @@ -113,8 +105,7 @@ void ThreadPool::Schedule(TaskFunc func, void* arg) { /* * timeout is in millisecond */ -void ThreadPool::DelaySchedule( - uint64_t timeout, TaskFunc func, void* arg) { +void ThreadPool::DelaySchedule(uint64_t timeout, TaskFunc func, void* arg) { /* * pthread_cond_timedwait api use absolute API * so we need gettimeofday + timeout @@ -132,9 +123,7 @@ void ThreadPool::DelaySchedule( mu_.Unlock(); } -size_t ThreadPool::max_queue_size() { - return max_queue_size_; -} +size_t ThreadPool::max_queue_size() { return max_queue_size_; } void ThreadPool::cur_queue_size(size_t* qsize) { pstd::MutexLock l(&mu_); @@ -146,9 +135,7 @@ void ThreadPool::cur_time_queue_size(size_t* qsize) { *qsize = time_queue_.size(); } -std::string ThreadPool::thread_pool_name() { - return thread_pool_name_; -} +std::string ThreadPool::thread_pool_name() { return thread_pool_name_; } void ThreadPool::runInThread() { while (!should_stop()) { @@ -174,8 +161,7 @@ void ThreadPool::runInThread() { (*func)(arg); continue; } else if (queue_.empty() && !should_stop()) { - rsignal_.TimedWait( - static_cast((time_task.exec_time - unow) / 1000)); + rsignal_.TimedWait(static_cast((time_task.exec_time - unow) / 1000)); mu_.Unlock(); continue; } diff --git a/src/net/src/worker_thread.cc b/src/net/src/worker_thread.cc index c0408af9c0..0234520320 100644 --- a/src/net/src/worker_thread.cc +++ b/src/net/src/worker_thread.cc @@ -12,16 +12,12 @@ namespace net { - -WorkerThread::WorkerThread(ConnFactory *conn_factory, - ServerThread* server_thread, - int queue_limit, - int cron_interval) - : private_data_(nullptr), - server_thread_(server_thread), - conn_factory_(conn_factory), - cron_interval_(cron_interval), - keepalive_timeout_(kDefaultKeepAliveTime) { +WorkerThread::WorkerThread(ConnFactory* conn_factory, ServerThread* server_thread, int queue_limit, int cron_interval) + : private_data_(nullptr), + server_thread_(server_thread), + conn_factory_(conn_factory), + cron_interval_(cron_interval), + keepalive_timeout_(kDefaultKeepAliveTime) { /* * install the protobuf handler here */ @@ -29,8 +25,7 @@ WorkerThread::WorkerThread(ConnFactory *conn_factory, net_multiplexer_->Initialize(); } -WorkerThread::~WorkerThread() { -} +WorkerThread::~WorkerThread() {} int WorkerThread::conn_num() const { pstd::ReadLock l(&rwlock_); @@ -41,11 +36,7 @@ std::vector WorkerThread::conns_info() const { std::vector result; pstd::ReadLock l(&rwlock_); for (auto& conn : conns_) { - result.push_back({ - conn.first, - conn.second->ip_port(), - conn.second->last_interaction() - }); + result.push_back({conn.first, conn.second->ip_port(), conn.second->last_interaction()}); } return result; } @@ -73,13 +64,11 @@ bool WorkerThread::MoveConnIn(std::shared_ptr conn, const NotifyType& n return success; } -bool WorkerThread::MoveConnIn(const NetItem& it, bool force) { - return net_multiplexer_->Register(it, force); -} +bool WorkerThread::MoveConnIn(const NetItem& it, bool force) { return net_multiplexer_->Register(it, force); } -void *WorkerThread::ThreadMain() { +void* WorkerThread::ThreadMain() { int nfds; - NetFiredEvent *pfe = NULL; + NetFiredEvent* pfe = NULL; char bb[2048]; NetItem ti; std::shared_ptr in_conn = nullptr; @@ -98,10 +87,8 @@ void *WorkerThread::ThreadMain() { while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, NULL); - if (when.tv_sec > now.tv_sec || - (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { - timeout = (when.tv_sec - now.tv_sec) * 1000 + - (when.tv_usec - now.tv_usec) / 1000; + if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { + timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { DoCronTask(); when.tv_sec = now.tv_sec + (cron_interval_ / 1000); @@ -123,17 +110,15 @@ void *WorkerThread::ThreadMain() { for (int32_t idx = 0; idx < nread; ++idx) { NetItem ti = net_multiplexer_->NotifyQueuePop(); if (ti.notify_type() == kNotiConnect) { - std::shared_ptr tc = conn_factory_->NewNetConn( - ti.fd(), ti.ip_port(), - server_thread_, private_data_, net_multiplexer_.get()); + std::shared_ptr tc = conn_factory_->NewNetConn(ti.fd(), ti.ip_port(), server_thread_, + private_data_, net_multiplexer_.get()); if (!tc || !tc->SetNonblock()) { continue; } #ifdef __ENABLE_SSL // Create SSL failed - if (server_thread_->security() && - !tc->CreateSSL(server_thread_->ssl_ctx())) { + if (server_thread_->security() && !tc->CreateSSL(server_thread_->ssl_ctx())) { CloseFd(tc); continue; } @@ -185,7 +170,7 @@ void *WorkerThread::ThreadMain() { net_multiplexer_->NetModEvent(pfe->fd, 0, kReadable); in_conn->set_is_reply(false); if (in_conn->IsClose()) { - should_close = 1; + should_close = 1; } } else if (write_status == kWriteHalf) { continue; @@ -219,8 +204,8 @@ void *WorkerThread::ThreadMain() { should_close = 0; } } // connection event - } // for (int i = 0; i < nfds; i++) - } // while (!should_stop()) + } // for (int i = 0; i < nfds; i++) + } // while (!should_stop()) Cleanup(); return NULL; @@ -257,8 +242,7 @@ void WorkerThread::DoCronTask() { } // Check keepalive timeout connection - if (keepalive_timeout_ > 0 && - (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { + if (keepalive_timeout_ > 0 && (now.tv_sec - conn->last_interaction().tv_sec > keepalive_timeout_)) { to_timeout.push_back(conn); iter = conns_.erase(iter); continue; @@ -313,7 +297,6 @@ void WorkerThread::Cleanup() { for (const auto& iter : to_close) { CloseFd(iter.second); } - } }; // namespace net diff --git a/src/net/src/worker_thread.h b/src/net/src/worker_thread.h index 4105afb951..3583834dad 100644 --- a/src/net/src/worker_thread.h +++ b/src/net/src/worker_thread.h @@ -6,20 +6,20 @@ #ifndef NET_SRC_WORKER_THREAD_H_ #define NET_SRC_WORKER_THREAD_H_ -#include +#include #include #include -#include -#include #include +#include +#include -#include "pstd/include/xdebug.h" #include "pstd/include/pstd_mutex.h" +#include "pstd/include/xdebug.h" +#include "net/include/net_define.h" +#include "net/include/net_thread.h" #include "net/include/server_thread.h" #include "net/src/net_multiplexer.h" -#include "net/include/net_thread.h" -#include "net/include/net_define.h" namespace net { @@ -30,14 +30,11 @@ class ConnFactory; class WorkerThread : public Thread { public: - explicit WorkerThread(ConnFactory *conn_factory, ServerThread* server_thread, - int queue_limit, int cron_interval = 0); + explicit WorkerThread(ConnFactory* conn_factory, ServerThread* server_thread, int queue_limit, int cron_interval = 0); virtual ~WorkerThread(); - void set_keepalive_timeout(int timeout) { - keepalive_timeout_ = timeout; - } + void set_keepalive_timeout(int timeout) { keepalive_timeout_ = timeout; } int conn_num() const; @@ -49,9 +46,7 @@ class WorkerThread : public Thread { bool MoveConnIn(const NetItem& it, bool force); - NetMultiplexer* net_multiplexer() { - return net_multiplexer_.get(); - } + NetMultiplexer* net_multiplexer() { return net_multiplexer_.get(); } bool TryKillConn(const std::string& ip_port); mutable pstd::RWMutex rwlock_; /* For external statistics */ @@ -61,10 +56,9 @@ class WorkerThread : public Thread { private: ServerThread* server_thread_; - ConnFactory *conn_factory_; + ConnFactory* conn_factory_; int cron_interval_; - /* * The epoll handler */ @@ -72,7 +66,7 @@ class WorkerThread : public Thread { std::atomic keepalive_timeout_; // keepalive second - virtual void *ThreadMain() override; + virtual void* ThreadMain() override; void DoCronTask(); pstd::Mutex killer_mutex_; diff --git a/src/net/test/gmock/include/gmock/gmock-actions.h b/src/net/test/gmock/include/gmock/gmock-actions.h index b3f654af34..c003bfbb34 100644 --- a/src/net/test/gmock/include/gmock/gmock-actions.h +++ b/src/net/test/gmock/include/gmock/gmock-actions.h @@ -37,7 +37,7 @@ #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE -# include +# include #endif #include @@ -47,7 +47,7 @@ #include "gmock/internal/gmock-port.h" #if GTEST_HAS_STD_TYPE_TRAITS_ // Defined by gtest-port.h via gmock-port.h. -#include +# include #endif namespace testing { @@ -78,8 +78,7 @@ struct BuiltInDefaultValueGetter { template struct BuiltInDefaultValueGetter { static T Get() { - Assert(false, __FILE__, __LINE__, - "Default action undefined for the function return type."); + Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); return internal::Invalid(); // The above statement will never be reached, but is required in // order for this function to compile. @@ -98,24 +97,15 @@ class BuiltInDefaultValue { public: #if GTEST_HAS_STD_TYPE_TRAITS_ // This function returns true iff type T has a built-in default value. - static bool Exists() { - return ::std::is_default_constructible::value; - } + static bool Exists() { return ::std::is_default_constructible::value; } - static T Get() { - return BuiltInDefaultValueGetter< - T, ::std::is_default_constructible::value>::Get(); - } + static T Get() { return BuiltInDefaultValueGetter::value>::Get(); } #else // GTEST_HAS_STD_TYPE_TRAITS_ // This function returns true iff type T has a built-in default value. - static bool Exists() { - return false; - } + static bool Exists() { return false; } - static T Get() { - return BuiltInDefaultValueGetter::Get(); - } + static T Get() { return BuiltInDefaultValueGetter::Get(); } #endif // GTEST_HAS_STD_TYPE_TRAITS_ }; @@ -141,11 +131,11 @@ class BuiltInDefaultValue { // The following specializations define the default values for // specific types we care about. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ - template <> \ - class BuiltInDefaultValue { \ - public: \ - static bool Exists() { return true; } \ - static type Get() { return value; } \ + template <> \ + class BuiltInDefaultValue { \ + public: \ + static bool Exists() { return true; } \ + static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT @@ -226,17 +216,12 @@ class DefaultValue { // Returns true if T has a default return value set by the user or there // exists a built-in default value. - static bool Exists() { - return IsSet() || internal::BuiltInDefaultValue::Exists(); - } + static bool Exists() { return IsSet() || internal::BuiltInDefaultValue::Exists(); } // Returns the default value for type T if the user has set one; // otherwise returns the built-in default value. Requires that Exists() // is true, which ensures that the return value is well-defined. - static T Get() { - return producer_ == NULL ? - internal::BuiltInDefaultValue::Get() : producer_->Produce(); - } + static T Get() { return producer_ == NULL ? internal::BuiltInDefaultValue::Get() : producer_->Produce(); } private: class ValueProducer { @@ -257,8 +242,7 @@ class DefaultValue { class FactoryValueProducer : public ValueProducer { public: - explicit FactoryValueProducer(FactoryFunction factory) - : factory_(factory) {} + explicit FactoryValueProducer(FactoryFunction factory) : factory_(factory) {} virtual T Produce() { return factory_(); } private: @@ -280,26 +264,19 @@ class DefaultValue { } // Unsets the default value for type T&. - static void Clear() { - address_ = NULL; - } + static void Clear() { address_ = NULL; } // Returns true iff the user has set the default value for type T&. static bool IsSet() { return address_ != NULL; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. - static bool Exists() { - return IsSet() || internal::BuiltInDefaultValue::Exists(); - } + static bool Exists() { return IsSet() || internal::BuiltInDefaultValue::Exists(); } // Returns the default value for type T& if the user has set one; // otherwise returns the built-in default value if there is one; // otherwise aborts the process. - static T& Get() { - return address_ == NULL ? - internal::BuiltInDefaultValue::Get() : *address_; - } + static T& Get() { return address_ == NULL ? internal::BuiltInDefaultValue::Get() : *address_; } private: static T* address_; @@ -385,13 +362,12 @@ class Action { // cannot change state. (Think of the difference between a const // pointer and a pointer to const.) Result Perform(const ArgumentTuple& args) const { - internal::Assert( - !IsDoDefault(), __FILE__, __LINE__, - "You are using DoDefault() inside a composite action like " - "DoAll() or WithArgs(). This is not supported for technical " - "reasons. Please instead spell out the default action, or " - "assign the default action to an Action variable and use " - "the variable in various places."); + internal::Assert(!IsDoDefault(), __FILE__, __LINE__, + "You are using DoDefault() inside a composite action like " + "DoAll() or WithArgs(). This is not supported for technical " + "reasons. Please instead spell out the default action, or " + "assign the default action to an Action variable and use " + "the variable in various places."); return impl_->Perform(args); } @@ -442,9 +418,7 @@ class PolymorphicAction { explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} - virtual Result Perform(const ArgumentTuple& args) { - return impl_.template Perform(args); - } + virtual Result Perform(const ArgumentTuple& args) { return impl_.template Perform(args); } private: Impl impl_; @@ -488,9 +462,7 @@ class ActionAdaptor : public ActionInterface { explicit ActionAdaptor(const Action& from) : impl_(from.impl_) {} - virtual Result Perform(const ArgumentTuple& args) { - return impl_->Perform(args); - } + virtual Result Perform(const ArgumentTuple& args) { return impl_->Perform(args); } private: const internal::linked_ptr > impl_; @@ -551,9 +523,7 @@ class ReturnAction { // and put the typedef both here (for use in assert statement) and // in the Impl class. But both definitions must be the same. typedef typename Function::Result Result; - GTEST_COMPILE_ASSERT_( - !is_reference::value, - use_ReturnRef_instead_of_Return_to_return_a_reference); + GTEST_COMPILE_ASSERT_(!is_reference::value, use_ReturnRef_instead_of_Return_to_return_a_reference); return Action(new Impl(value_)); } @@ -573,14 +543,12 @@ class ReturnAction { // Result without considering explicit constructors, thus resolving the // ambiguity. value_ is then initialized using its copy constructor. explicit Impl(const linked_ptr& value) - : value_before_cast_(*value), - value_(ImplicitCast_(value_before_cast_)) {} + : value_before_cast_(*value), value_(ImplicitCast_(value_before_cast_)) {} virtual Result Perform(const ArgumentTuple&) { return value_; } private: - GTEST_COMPILE_ASSERT_(!is_reference::value, - Result_cannot_be_a_reference_type); + GTEST_COMPILE_ASSERT_(!is_reference::value, Result_cannot_be_a_reference_type); // We save the value before casting just in case it is being cast to a // wrapper type. R value_before_cast_; @@ -597,12 +565,10 @@ class ReturnAction { typedef typename Function::Result Result; typedef typename Function::ArgumentTuple ArgumentTuple; - explicit Impl(const linked_ptr& wrapper) - : performed_(false), wrapper_(wrapper) {} + explicit Impl(const linked_ptr& wrapper) : performed_(false), wrapper_(wrapper) {} virtual Result Perform(const ArgumentTuple&) { - GTEST_CHECK_(!performed_) - << "A ByMove() action should only be performed once."; + GTEST_CHECK_(!performed_) << "A ByMove() action should only be performed once."; performed_ = true; return internal::move(wrapper_->payload); } @@ -630,8 +596,7 @@ class ReturnNullAction { #if GTEST_LANG_CXX11 return nullptr; #else - GTEST_COMPILE_ASSERT_(internal::is_pointer::value, - ReturnNull_can_be_used_to_return_a_pointer_only); + GTEST_COMPILE_ASSERT_(internal::is_pointer::value, ReturnNull_can_be_used_to_return_a_pointer_only); return NULL; #endif // GTEST_LANG_CXX11 } @@ -664,8 +629,7 @@ class ReturnRefAction { // Asserts that the function return type is a reference. This // catches the user error of using ReturnRef(x) when Return(x) // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_(internal::is_reference::value, - use_Return_instead_of_ReturnRef_to_return_a_value); + GTEST_COMPILE_ASSERT_(internal::is_reference::value, use_Return_instead_of_ReturnRef_to_return_a_value); return Action(new Impl(ref_)); } @@ -679,9 +643,7 @@ class ReturnRefAction { explicit Impl(T& ref) : ref_(ref) {} // NOLINT - virtual Result Perform(const ArgumentTuple&) { - return ref_; - } + virtual Result Perform(const ArgumentTuple&) { return ref_; } private: T& ref_; @@ -712,9 +674,8 @@ class ReturnRefOfCopyAction { // Asserts that the function return type is a reference. This // catches the user error of using ReturnRefOfCopy(x) when Return(x) // should be used, and generates some helpful error message. - GTEST_COMPILE_ASSERT_( - internal::is_reference::value, - use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); + GTEST_COMPILE_ASSERT_(internal::is_reference::value, + use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); return Action(new Impl(value_)); } @@ -728,9 +689,7 @@ class ReturnRefOfCopyAction { explicit Impl(const T& value) : value_(value) {} // NOLINT - virtual Result Perform(const ArgumentTuple&) { - return value_; - } + virtual Result Perform(const ArgumentTuple&) { return value_; } private: T value_; @@ -749,7 +708,9 @@ class DoDefaultAction { // This template type conversion operator allows DoDefault() to be // used in any function. template - operator Action() const { return Action(NULL); } + operator Action() const { + return Action(NULL); + } }; // Implements the Assign action to set a given pointer referent to a @@ -778,9 +739,7 @@ class AssignAction { template class SetErrnoAndReturnAction { public: - SetErrnoAndReturnAction(int errno_value, T result) - : errno_(errno_value), - result_(result) {} + SetErrnoAndReturnAction(int errno_value, T result) : errno_(errno_value), result_(result) {} template Result Perform(const ArgumentTuple& /* args */) const { errno = errno_; @@ -826,9 +785,7 @@ class SetArgumentPointeeAction { // N-th function argument to 'proto'. Both ProtocolMessage and // proto2::Message have the CopyFrom() method, so the same // implementation works for both. - explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) { - proto_->CopyFrom(proto); - } + explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) { proto_->CopyFrom(proto); } template void Perform(const ArgumentTuple& args) const { @@ -852,13 +809,14 @@ class InvokeWithoutArgsAction { public: // The c'tor makes a copy of function_impl (either a function // pointer or a functor). - explicit InvokeWithoutArgsAction(FunctionImpl function_impl) - : function_impl_(function_impl) {} + explicit InvokeWithoutArgsAction(FunctionImpl function_impl) : function_impl_(function_impl) {} // Allows InvokeWithoutArgs(f) to be used as any action whose type is // compatible with f. template - Result Perform(const ArgumentTuple&) { return function_impl_(); } + Result Perform(const ArgumentTuple&) { + return function_impl_(); + } private: FunctionImpl function_impl_; @@ -870,8 +828,7 @@ class InvokeWithoutArgsAction { template class InvokeMethodWithoutArgsAction { public: - InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr) - : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {} + InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr) : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {} template Result Perform(const ArgumentTuple&) const { @@ -926,8 +883,7 @@ class IgnoreResultAction { private: // Type OriginalFunction is the same as F except that its return // type is IgnoredValue. - typedef typename internal::Function::MakeResultIgnoredValue - OriginalFunction; + typedef typename internal::Function::MakeResultIgnoredValue OriginalFunction; const Action action_; @@ -955,6 +911,7 @@ class ReferenceWrapper { // Allows a ReferenceWrapper object to be implicitly converted to // a T&. operator T&() const { return *pointer_; } + private: T* pointer_; }; @@ -971,8 +928,7 @@ void PrintTo(const ReferenceWrapper& ref, ::std::ostream* os) { template class DoBothAction { public: - DoBothAction(Action1 action1, Action2 action2) - : action1_(action1), action2_(action2) {} + DoBothAction(Action1 action1, Action2 action2) : action1_(action1), action2_(action2) {} // This template type conversion operator allows DoAll(a1, ..., a_n) // to be used in ANY function of compatible type. @@ -990,8 +946,7 @@ class DoBothAction { typedef typename Function::ArgumentTuple ArgumentTuple; typedef typename Function::MakeResultVoid VoidResult; - Impl(const Action& action1, const Action& action2) - : action1_(action1), action2_(action2) {} + Impl(const Action& action1, const Action& action2) : action1_(action1), action2_(action2) {} virtual Result Perform(const ArgumentTuple& args) { action1_.Perform(args); @@ -1051,8 +1006,7 @@ typedef internal::IgnoredValue Unused; // To's. template template -Action::Action(const Action& from) - : impl_(new internal::ActionAdaptor(from)) {} +Action::Action(const Action& from) : impl_(new internal::ActionAdaptor(from)) {} // Creates an action that returns 'value'. 'value' is passed by value // instead of const reference - otherwise Return("string literal") @@ -1096,19 +1050,14 @@ internal::ByMoveWrapper ByMove(R x) { } // Creates an action that does the default action for the give mock function. -inline internal::DoDefaultAction DoDefault() { - return internal::DoDefaultAction(); -} +inline internal::DoDefaultAction DoDefault() { return internal::DoDefaultAction(); } // Creates an action that sets the variable pointed by the N-th // (0-based) function argument to 'value'. template -PolymorphicAction< - internal::SetArgumentPointeeAction< - N, T, internal::IsAProtocolMessage::value> > -SetArgPointee(const T& x) { - return MakePolymorphicAction(internal::SetArgumentPointeeAction< - N, T, internal::IsAProtocolMessage::value>(x)); +PolymorphicAction::value> > SetArgPointee( + const T& x) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction::value>(x)); } #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) @@ -1116,30 +1065,21 @@ SetArgPointee(const T& x) { // GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish // this overload from the templated version and emit a compile error. template -PolymorphicAction< - internal::SetArgumentPointeeAction > -SetArgPointee(const char* p) { - return MakePolymorphicAction(internal::SetArgumentPointeeAction< - N, const char*, false>(p)); +PolymorphicAction > SetArgPointee(const char* p) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction(p)); } template -PolymorphicAction< - internal::SetArgumentPointeeAction > -SetArgPointee(const wchar_t* p) { - return MakePolymorphicAction(internal::SetArgumentPointeeAction< - N, const wchar_t*, false>(p)); +PolymorphicAction > SetArgPointee(const wchar_t* p) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction(p)); } #endif // The following version is DEPRECATED. template -PolymorphicAction< - internal::SetArgumentPointeeAction< - N, T, internal::IsAProtocolMessage::value> > -SetArgumentPointee(const T& x) { - return MakePolymorphicAction(internal::SetArgumentPointeeAction< - N, T, internal::IsAProtocolMessage::value>(x)); +PolymorphicAction::value> > SetArgumentPointee( + const T& x) { + return MakePolymorphicAction(internal::SetArgumentPointeeAction::value>(x)); } // Creates an action that sets a pointer referent to a given value. @@ -1152,10 +1092,8 @@ PolymorphicAction > Assign(T1* ptr, T2 val) { // Creates an action that sets errno and returns the appropriate error. template -PolymorphicAction > -SetErrnoAndReturn(int errval, T result) { - return MakePolymorphicAction( - internal::SetErrnoAndReturnAction(errval, result)); +PolymorphicAction > SetErrnoAndReturn(int errval, T result) { + return MakePolymorphicAction(internal::SetErrnoAndReturnAction(errval, result)); } #endif // !GTEST_OS_WINDOWS_MOBILE @@ -1164,20 +1102,16 @@ SetErrnoAndReturn(int errval, T result) { // Creates an action that invokes 'function_impl' with no argument. template -PolymorphicAction > -InvokeWithoutArgs(FunctionImpl function_impl) { - return MakePolymorphicAction( - internal::InvokeWithoutArgsAction(function_impl)); +PolymorphicAction > InvokeWithoutArgs(FunctionImpl function_impl) { + return MakePolymorphicAction(internal::InvokeWithoutArgsAction(function_impl)); } // Creates an action that invokes the given method on the given object // with no argument. template -PolymorphicAction > -InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) { - return MakePolymorphicAction( - internal::InvokeMethodWithoutArgsAction( - obj_ptr, method_ptr)); +PolymorphicAction > InvokeWithoutArgs(Class* obj_ptr, + MethodPtr method_ptr) { + return MakePolymorphicAction(internal::InvokeMethodWithoutArgsAction(obj_ptr, method_ptr)); } // Creates an action that performs an_action and throws away its diff --git a/src/net/test/gmock/include/gmock/gmock-cardinalities.h b/src/net/test/gmock/include/gmock/gmock-cardinalities.h index fc315f92ab..f6316ed832 100644 --- a/src/net/test/gmock/include/gmock/gmock-cardinalities.h +++ b/src/net/test/gmock/include/gmock/gmock-cardinalities.h @@ -95,28 +95,22 @@ class GTEST_API_ Cardinality { int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); } // Returns true iff call_count calls will satisfy this cardinality. - bool IsSatisfiedByCallCount(int call_count) const { - return impl_->IsSatisfiedByCallCount(call_count); - } + bool IsSatisfiedByCallCount(int call_count) const { return impl_->IsSatisfiedByCallCount(call_count); } // Returns true iff call_count calls will saturate this cardinality. - bool IsSaturatedByCallCount(int call_count) const { - return impl_->IsSaturatedByCallCount(call_count); - } + bool IsSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count); } // Returns true iff call_count calls will over-saturate this // cardinality, i.e. exceed the maximum number of allowed calls. bool IsOverSaturatedByCallCount(int call_count) const { - return impl_->IsSaturatedByCallCount(call_count) && - !impl_->IsSatisfiedByCallCount(call_count); + return impl_->IsSaturatedByCallCount(call_count) && !impl_->IsSatisfiedByCallCount(call_count); } // Describes self to an ostream void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } // Describes the given actual call count to an ostream. - static void DescribeActualCallCountTo(int actual_call_count, - ::std::ostream* os); + static void DescribeActualCallCountTo(int actual_call_count, ::std::ostream* os); private: internal::linked_ptr impl_; @@ -138,9 +132,7 @@ GTEST_API_ Cardinality Between(int min, int max); GTEST_API_ Cardinality Exactly(int n); // Creates a cardinality from its implementation. -inline Cardinality MakeCardinality(const CardinalityInterface* c) { - return Cardinality(c); -} +inline Cardinality MakeCardinality(const CardinalityInterface* c) { return Cardinality(c); } } // namespace testing diff --git a/src/net/test/gmock/include/gmock/gmock-generated-actions.h b/src/net/test/gmock/include/gmock/gmock-generated-actions.h index b5a889c0c3..bca6e6bc21 100644 --- a/src/net/test/gmock/include/gmock/gmock-generated-actions.h +++ b/src/net/test/gmock/include/gmock/gmock-generated-actions.h @@ -55,14 +55,12 @@ class InvokeHelper > { public: template static R Invoke(Function function, const ::testing::tuple<>&) { - return function(); + return function(); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple<>&) { - return (obj_ptr->*method_ptr)(); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<>&) { + return (obj_ptr->*method_ptr)(); } }; @@ -71,14 +69,12 @@ class InvokeHelper > { public: template static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args)); + return function(get<0>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args)); } }; @@ -87,14 +83,12 @@ class InvokeHelper > { public: template static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args)); + return function(get<0>(args), get<1>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args)); } }; @@ -103,15 +97,12 @@ class InvokeHelper > { public: template static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args)); + return function(get<0>(args), get<1>(args), get<2>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args)); } }; @@ -119,158 +110,117 @@ template class InvokeHelper > { public: template - static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args)); + static R Invoke(Function function, const ::testing::tuple& args) { + return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args)); } }; -template +template class InvokeHelper > { public: template - static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args)); + static R Invoke(Function function, const ::testing::tuple& args) { + return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args)); } }; -template +template class InvokeHelper > { public: template - static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args)); + static R Invoke(Function function, const ::testing::tuple& args) { + return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args)); } }; -template +template class InvokeHelper > { public: template - static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args)); + static R Invoke(Function function, const ::testing::tuple& args) { + return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, + const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args)); } }; -template +template class InvokeHelper > { public: template - static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args), - get<7>(args)); + static R Invoke(Function function, const ::testing::tuple& args) { + return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args), get<7>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, + const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args), get<7>(args)); } }; -template +template class InvokeHelper > { public: template - static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args), - get<7>(args), get<8>(args)); + static R Invoke(Function function, const ::testing::tuple& args) { + return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args), get<8>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args), get<7>(args), get<8>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, + const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args), get<7>(args), get<8>(args)); } }; -template -class InvokeHelper > { +template +class InvokeHelper > { public: template - static R Invoke(Function function, const ::testing::tuple& args) { - return function(get<0>(args), get<1>(args), get<2>(args), - get<3>(args), get<4>(args), get<5>(args), get<6>(args), - get<7>(args), get<8>(args), get<9>(args)); + static R Invoke(Function function, const ::testing::tuple& args) { + return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args), get<8>(args), get<9>(args)); } template - static R InvokeMethod(Class* obj_ptr, - MethodPtr method_ptr, - const ::testing::tuple& args) { - return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), - get<2>(args), get<3>(args), get<4>(args), get<5>(args), - get<6>(args), get<7>(args), get<8>(args), get<9>(args)); + static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, + const ::testing::tuple& args) { + return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), + get<6>(args), get<7>(args), get<8>(args), get<9>(args)); } }; // An INTERNAL macro for extracting the type of a tuple field. It's // subject to change without notice - DO NOT USE IN USER CODE! -#define GMOCK_FIELD_(Tuple, N) \ - typename ::testing::tuple_element::type +#define GMOCK_FIELD_(Tuple, N) typename ::testing::tuple_element::type // SelectArgs::type is the // type of an n-ary function whose i-th (1-based) argument type is the @@ -290,180 +240,144 @@ class InvokeHelper +template class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), - GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), - GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), - GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9), - GMOCK_FIELD_(ArgumentTuple, k10)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), + GMOCK_FIELD_(ArgumentTuple, k7), GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9), + GMOCK_FIELD_(ArgumentTuple, k10)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args), get(args), - get(args), get(args), get(args), get(args), - get(args), get(args), get(args)); + return SelectedArgs(get(args), get(args), get(args), get(args), get(args), get(args), + get(args), get(args), get(args), get(args)); } }; template -class SelectArgs { +class SelectArgs { public: typedef Result type(); typedef typename Function::ArgumentTuple SelectedArgs; - static SelectedArgs Select(const ArgumentTuple& /* args */) { - return SelectedArgs(); - } + static SelectedArgs Select(const ArgumentTuple& /* args */) { return SelectedArgs(); } }; template -class SelectArgs { +class SelectArgs { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1)); typedef typename Function::ArgumentTuple SelectedArgs; - static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args)); - } + static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get(args)); } }; template -class SelectArgs { +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2)); typedef typename Function::ArgumentTuple SelectedArgs; - static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args)); - } + static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get(args), get(args)); } }; template -class SelectArgs { +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), + GMOCK_FIELD_(ArgumentTuple, k3)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get(args), get(args), get(args)); } }; -template -class SelectArgs { +template +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), - GMOCK_FIELD_(ArgumentTuple, k4)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args), get(args), - get(args)); + return SelectedArgs(get(args), get(args), get(args), get(args)); } }; -template -class SelectArgs { +template +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), - GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args), get(args), - get(args), get(args)); + return SelectedArgs(get(args), get(args), get(args), get(args), get(args)); } }; -template -class SelectArgs { +template +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), - GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), - GMOCK_FIELD_(ArgumentTuple, k6)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), + GMOCK_FIELD_(ArgumentTuple, k6)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args), get(args), - get(args), get(args), get(args)); + return SelectedArgs(get(args), get(args), get(args), get(args), get(args), get(args)); } }; -template -class SelectArgs { +template +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), - GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), - GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), + GMOCK_FIELD_(ArgumentTuple, k7)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args), get(args), - get(args), get(args), get(args), get(args)); + return SelectedArgs(get(args), get(args), get(args), get(args), get(args), get(args), + get(args)); } }; -template -class SelectArgs { +template +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), - GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), - GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), - GMOCK_FIELD_(ArgumentTuple, k8)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), + GMOCK_FIELD_(ArgumentTuple, k7), GMOCK_FIELD_(ArgumentTuple, k8)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args), get(args), - get(args), get(args), get(args), get(args), - get(args)); + return SelectedArgs(get(args), get(args), get(args), get(args), get(args), get(args), + get(args), get(args)); } }; -template -class SelectArgs { +template +class SelectArgs { public: - typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), - GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), - GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), - GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), - GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9)); + typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), + GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), + GMOCK_FIELD_(ArgumentTuple, k7), GMOCK_FIELD_(ArgumentTuple, k8), + GMOCK_FIELD_(ArgumentTuple, k9)); typedef typename Function::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { - return SelectedArgs(get(args), get(args), get(args), - get(args), get(args), get(args), get(args), - get(args), get(args)); + return SelectedArgs(get(args), get(args), get(args), get(args), get(args), get(args), + get(args), get(args), get(args)); } }; #undef GMOCK_FIELD_ // Implements the WithArgs action. -template +template class WithArgsAction { public: explicit WithArgsAction(const InnerAction& action) : action_(action) {} template - operator Action() const { return MakeAction(new Impl(action_)); } + operator Action() const { + return MakeAction(new Impl(action_)); + } private: template @@ -475,13 +389,11 @@ class WithArgsAction { explicit Impl(const InnerAction& action) : action_(action) {} virtual Result Perform(const ArgumentTuple& args) { - return action_.Perform(SelectArgs::Select(args)); + return action_.Perform(SelectArgs::Select(args)); } private: - typedef typename SelectArgs::type InnerFunctionType; + typedef typename SelectArgs::type InnerFunctionType; Action action_; }; @@ -512,102 +424,81 @@ template class ActionHelper { public: static Result Perform(Impl* impl, const ::testing::tuple<>& args) { - return impl->template gmock_PerformImpl<>(args, ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + return impl->template gmock_PerformImpl<>(args, ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg()); } template static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, get<0>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + return impl->template gmock_PerformImpl(args, get<0>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg()); } template static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, get<0>(args), - get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + return impl->template gmock_PerformImpl(args, get<0>(args), get<1>(args), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg()); } template static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, get<0>(args), - get<1>(args), get<2>(args), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + return impl->template gmock_PerformImpl(args, get<0>(args), get<1>(args), get<2>(args), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg()); } template - static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, get<0>(args), - get<1>(args), get<2>(args), get<3>(args), ExcessiveArg(), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + static Result Perform(Impl* impl, const ::testing::tuple& args) { + return impl->template gmock_PerformImpl( + args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template - static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, - get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), - ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + static Result Perform(Impl* impl, const ::testing::tuple& args) { + return impl->template gmock_PerformImpl( + args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), ExcessiveArg(), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } - template - static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, - get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), - get<5>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + template + static Result Perform(Impl* impl, const ::testing::tuple& args) { + return impl->template gmock_PerformImpl( + args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), ExcessiveArg(), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } - template - static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, - get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), - get<5>(args), get<6>(args), ExcessiveArg(), ExcessiveArg(), - ExcessiveArg()); + template + static Result Perform(Impl* impl, const ::testing::tuple& args) { + return impl->template gmock_PerformImpl( + args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), + ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } - template - static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), - get<4>(args), get<5>(args), get<6>(args), get<7>(args), ExcessiveArg(), - ExcessiveArg()); + template + static Result Perform(Impl* impl, const ::testing::tuple& args) { + return impl->template gmock_PerformImpl( + args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args), ExcessiveArg(), ExcessiveArg()); } - template - static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), - get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), - ExcessiveArg()); + template + static Result Perform(Impl* impl, const ::testing::tuple& args) { + return impl->template gmock_PerformImpl( + args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args), get<8>(args), ExcessiveArg()); } - template - static Result Perform(Impl* impl, const ::testing::tuple& args) { - return impl->template gmock_PerformImpl(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), - get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), - get<9>(args)); + template + static Result Perform(Impl* impl, const ::testing::tuple& args) { + return impl->template gmock_PerformImpl( + args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), + get<7>(args), get<8>(args), get<9>(args)); } }; @@ -621,161 +512,156 @@ class ActionHelper { // different argument lists. C++ doesn't support default arguments for // function templates, so we have to overload it. template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { +inline internal::WithArgsAction WithArgs(const InnerAction& action) { return internal::WithArgsAction(action); } template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { +inline internal::WithArgsAction WithArgs(const InnerAction& action) { return internal::WithArgsAction(action); } template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { +inline internal::WithArgsAction WithArgs(const InnerAction& action) { return internal::WithArgsAction(action); } template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { +inline internal::WithArgsAction WithArgs(const InnerAction& action) { return internal::WithArgsAction(action); } template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { +inline internal::WithArgsAction WithArgs(const InnerAction& action) { return internal::WithArgsAction(action); } template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { +inline internal::WithArgsAction WithArgs(const InnerAction& action) { return internal::WithArgsAction(action); } -template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { - return internal::WithArgsAction(action); +template +inline internal::WithArgsAction WithArgs(const InnerAction& action) { + return internal::WithArgsAction(action); } -template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { - return internal::WithArgsAction(action); +template +inline internal::WithArgsAction WithArgs(const InnerAction& action) { + return internal::WithArgsAction(action); } -template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { - return internal::WithArgsAction(action); +template +inline internal::WithArgsAction WithArgs(const InnerAction& action) { + return internal::WithArgsAction(action); } -template -inline internal::WithArgsAction -WithArgs(const InnerAction& action) { - return internal::WithArgsAction(action); +template +inline internal::WithArgsAction WithArgs( + const InnerAction& action) { + return internal::WithArgsAction(action); } // Creates an action that does actions a1, a2, ..., sequentially in // each invocation. template -inline internal::DoBothAction -DoAll(Action1 a1, Action2 a2) { +inline internal::DoBothAction DoAll(Action1 a1, Action2 a2) { return internal::DoBothAction(a1, a2); } template -inline internal::DoBothAction > -DoAll(Action1 a1, Action2 a2, Action3 a3) { +inline internal::DoBothAction > DoAll(Action1 a1, Action2 a2, + Action3 a3) { return DoAll(a1, DoAll(a2, a3)); } -template -inline internal::DoBothAction > > +template +inline internal::DoBothAction > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4) { return DoAll(a1, DoAll(a2, a3, a4)); } -template -inline internal::DoBothAction > > > +template +inline internal::DoBothAction< + Action1, + internal::DoBothAction > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5) { return DoAll(a1, DoAll(a2, a3, a4, a5)); } -template -inline internal::DoBothAction > > > > +template +inline internal::DoBothAction< + Action1, + internal::DoBothAction< + Action2, + internal::DoBothAction > > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6)); } -template -inline internal::DoBothAction > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7) { +template +inline internal::DoBothAction< + Action1, + internal::DoBothAction< + Action2, + internal::DoBothAction< + Action3, internal::DoBothAction< + Action4, internal::DoBothAction > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7)); } -template -inline internal::DoBothAction > > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7, Action8 a8) { +template +inline internal::DoBothAction< + Action1, + internal::DoBothAction< + Action2, + internal::DoBothAction< + Action3, internal::DoBothAction< + Action4, internal::DoBothAction< + Action5, internal::DoBothAction< + Action6, internal::DoBothAction > > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7, Action8 a8) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8)); } -template -inline internal::DoBothAction > > > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7, Action8 a8, Action9 a9) { +template +inline internal::DoBothAction< + Action1, + internal::DoBothAction< + Action2, + internal::DoBothAction< + Action3, + internal::DoBothAction< + Action4, internal::DoBothAction< + Action5, internal::DoBothAction< + Action6, internal::DoBothAction< + Action7, internal::DoBothAction > > > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7, Action8 a8, Action9 a9) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9)); } -template -inline internal::DoBothAction > > > > > > > > -DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, - Action7 a7, Action8 a8, Action9 a9, Action10 a10) { +template +inline internal::DoBothAction< + Action1, + internal::DoBothAction< + Action2, + internal::DoBothAction< + Action3, + internal::DoBothAction< + Action4, + internal::DoBothAction< + Action5, + internal::DoBothAction< + Action6, internal::DoBothAction< + Action7, internal::DoBothAction< + Action8, internal::DoBothAction > > > > > > > > +DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7, Action8 a8, Action9 a9, + Action10 a10) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9, a10)); } @@ -878,18 +764,13 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, // on http://code.google.com/p/googlemock/wiki/CookBook. // An internal macro needed for implementing ACTION*(). -#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ - const args_type& args GTEST_ATTRIBUTE_UNUSED_, \ - arg0_type arg0 GTEST_ATTRIBUTE_UNUSED_, \ - arg1_type arg1 GTEST_ATTRIBUTE_UNUSED_, \ - arg2_type arg2 GTEST_ATTRIBUTE_UNUSED_, \ - arg3_type arg3 GTEST_ATTRIBUTE_UNUSED_, \ - arg4_type arg4 GTEST_ATTRIBUTE_UNUSED_, \ - arg5_type arg5 GTEST_ATTRIBUTE_UNUSED_, \ - arg6_type arg6 GTEST_ATTRIBUTE_UNUSED_, \ - arg7_type arg7 GTEST_ATTRIBUTE_UNUSED_, \ - arg8_type arg8 GTEST_ATTRIBUTE_UNUSED_, \ - arg9_type arg9 GTEST_ATTRIBUTE_UNUSED_ +#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \ + const args_type &args GTEST_ATTRIBUTE_UNUSED_, arg0_type arg0 GTEST_ATTRIBUTE_UNUSED_, \ + arg1_type arg1 GTEST_ATTRIBUTE_UNUSED_, arg2_type arg2 GTEST_ATTRIBUTE_UNUSED_, \ + arg3_type arg3 GTEST_ATTRIBUTE_UNUSED_, arg4_type arg4 GTEST_ATTRIBUTE_UNUSED_, \ + arg5_type arg5 GTEST_ATTRIBUTE_UNUSED_, arg6_type arg6 GTEST_ATTRIBUTE_UNUSED_, \ + arg7_type arg7 GTEST_ATTRIBUTE_UNUSED_, arg8_type arg8 GTEST_ATTRIBUTE_UNUSED_, \ + arg9_type arg9 GTEST_ATTRIBUTE_UNUSED_ // Sometimes you want to give an action explicit template parameters // that cannot be inferred from its value parameters. ACTION() and @@ -974,179 +855,201 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, // Declares the template parameters. #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 -#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) kind0 name0, kind1 name1 -#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) kind0 name0, kind1 name1, kind2 name2 -#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3 -#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ - kind2 name2, kind3 name3, kind4 name4 -#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 -#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ - kind5 name5, kind6 name6 -#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ - kind4 name4, kind5 name5, kind6 name6, kind7 name7 -#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ - kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ - kind8 name8 -#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ - kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ - kind6 name6, kind7 name7, kind8 name8, kind9 name9 +#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) kind0 name0, kind1 name1 +#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2) \ + kind0 name0, kind1 name1, kind2 name2 +#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3 +#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4 +#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 +#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, kind6 name6 +#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6, kind7, name7) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7 +#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, kind8 name8 +#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6, kind7, name7, kind8, name8, \ + kind9, name9) \ + kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, kind8 name8, \ + kind9 name9 // Lists the template parameters. #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 -#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1) name0, name1 -#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2) name0, name1, name2 -#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3) name0, name1, name2, name3 -#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ - name4 -#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ - name2, name3, name4, name5 -#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6) name0, name1, name2, name3, name4, name5, name6 -#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 -#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ - kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ - kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ - name6, name7, name8 -#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ - name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ - name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ - name3, name4, name5, name6, name7, name8, name9 +#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) name0, name1 +#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2) name0, name1, name2 +#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3) \ + name0, name1, name2, name3 +#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4) \ + name0, name1, name2, name3, name4 +#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5) \ + name0, name1, name2, name3, name4, name5 +#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6) \ + name0, name1, name2, name3, name4, name5, name6 +#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6, kind7, name7) \ + name0, name1, name2, name3, name4, name5, name6, name7 +#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6, kind7, name7, kind8, name8) \ + name0, name1, name2, name3, name4, name5, name6, name7, name8 +#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, \ + name4, kind5, name5, kind6, name6, kind7, name7, kind8, name8, \ + kind9, name9) \ + name0, name1, name2, name3, name4, name5, name6, name7, name8, name9 // Declares the types of value parameters. #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ - typename p0##_type, typename p1##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ - typename p0##_type, typename p1##_type, typename p2##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \ - typename p3##_type, typename p4##_type, typename p5##_type, \ - typename p6##_type, typename p7##_type, typename p8##_type -#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \ - typename p2##_type, typename p3##_type, typename p4##_type, \ - typename p5##_type, typename p6##_type, typename p7##_type, \ - typename p8##_type, typename p9##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , typename p0##_type, typename p1##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \ + , typename p0##_type, typename p1##_type, typename p2##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + , typename p0##_type, typename p1##_type, typename p2##_type, typename p3##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + , typename p0##_type, typename p1##_type, typename p2##_type, typename p3##_type, typename p4##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + , typename p0##_type, typename p1##_type, typename p2##_type, typename p3##_type, typename p4##_type, \ + typename p5##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + , typename p0##_type, typename p1##_type, typename p2##_type, typename p3##_type, typename p4##_type, \ + typename p5##_type, typename p6##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + , typename p0##_type, typename p1##_type, typename p2##_type, typename p3##_type, typename p4##_type, \ + typename p5##_type, typename p6##_type, typename p7##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8) \ + , typename p0##_type, typename p1##_type, typename p2##_type, typename p3##_type, typename p4##_type, \ + typename p5##_type, typename p6##_type, typename p7##_type, typename p8##_type +#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ + , typename p0##_type, typename p1##_type, typename p2##_type, typename p3##_type, typename p4##_type, \ + typename p5##_type, typename p6##_type, typename p7##_type, typename p8##_type, typename p9##_type // Initializes the value parameters. -#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ - () -#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ - (p0##_type gmock_p0) : p0(gmock_p0) -#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ - (p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) -#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ - (p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) -#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3) -#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) -#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) -#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) -#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7) -#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ +#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() () +#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) (p0##_type gmock_p0) : p0(gmock_p0) +#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \ + (p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) +#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) +#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) +#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) +#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) +#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) +#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) +#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ p8(gmock_p8) -#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9)\ - (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8), p9(gmock_p9) +#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ + (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, p9##_type gmock_p9) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8), \ + p9(gmock_p9) // Declares the fields for storing the value parameters. #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; -#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ - p1##_type p1; -#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ - p1##_type p1; p2##_type p2; -#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ - p1##_type p1; p2##_type p2; p3##_type p3; -#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; -#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; -#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; -#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ - p5##_type p5; p6##_type p6; p7##_type p7; -#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; -#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ - p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ - p9##_type p9; +#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \ + p0##_type p0; \ + p1##_type p1; +#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; +#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; +#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; +#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; +#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; +#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; +#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; +#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + p9##_type p9; // Lists the value parameters. #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() @@ -1154,72 +1057,53 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 -#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \ - p2, p3, p4 -#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ - p1, p2, p3, p4, p5 -#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0, p1, p2, p3, p4, p5, p6 -#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0, p1, p2, p3, p4, p5, p6, p7 -#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 -#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 +#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, p2, p3, p4 +#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, p1, p2, p3, p4, p5 +#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) p0, p1, p2, p3, p4, p5, p6 +#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) p0, p1, p2, p3, p4, p5, p6, p7 +#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 +#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ + p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 // Lists the value parameter types. #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ - p1##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ - p1##_type, p2##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ - p0##_type, p1##_type, p2##_type, p3##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ - p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ - p6##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type -#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ - p5##_type, p6##_type, p7##_type, p8##_type, p9##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, p1##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, p1##_type, p2##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , p0##_type, p1##_type, p2##_type, p3##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type, p7##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type, p7##_type, p8##_type +#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ + , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type // Declares the value parameters. #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 -#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ - p1##_type p1 -#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ - p1##_type p1, p2##_type p2 -#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3 -#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ - p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 -#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ - p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5 -#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ - p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6 -#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ - p5##_type p5, p6##_type p6, p7##_type p7 -#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 -#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9 +#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, p1##_type p1 +#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, p1##_type p1, p2##_type p2 +#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3 +#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 +#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5 +#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6 +#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7 +#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8 +#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8, p9##_type p9 // The suffix of the class template implementing the action template. #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() @@ -1230,865 +1114,760 @@ DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 -#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7) P8 -#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8) P9 -#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ - p7, p8, p9) P10 +#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) P8 +#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8) P9 +#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) P10 // The name of the class template implementing the action template. -#define GMOCK_ACTION_CLASS_(name, value_params)\ - GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) - -#define ACTION_TEMPLATE(name, template_params, value_params)\ - template \ - class GMOCK_ACTION_CLASS_(name, value_params) {\ - public:\ - explicit GMOCK_ACTION_CLASS_(name, value_params)\ - GMOCK_INTERNAL_INIT_##value_params {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(\ - new gmock_Impl(GMOCK_INTERNAL_LIST_##value_params));\ - }\ - GMOCK_INTERNAL_DEFN_##value_params\ - private:\ - GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\ - };\ - template \ - inline GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\ - GMOCK_INTERNAL_DECL_##value_params) {\ - return GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>(\ - GMOCK_INTERNAL_LIST_##value_params);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - GMOCK_ACTION_CLASS_(name, value_params)<\ - GMOCK_INTERNAL_LIST_##template_params\ - GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl::\ - gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION(name)\ - class name##Action {\ - public:\ - name##Action() {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl() {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl());\ - }\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##Action);\ - };\ - inline name##Action name() {\ - return name##Action();\ - }\ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##Action::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P(name, p0)\ - template \ - class name##ActionP {\ - public:\ - explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0));\ - }\ - p0##_type p0;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP);\ - };\ - template \ - inline name##ActionP name(p0##_type p0) {\ - return name##ActionP(p0);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP::gmock_Impl::gmock_PerformImpl(\ +#define GMOCK_ACTION_CLASS_(name, value_params) GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) + +#define ACTION_TEMPLATE(name, template_params, value_params) \ + template \ + class GMOCK_ACTION_CLASS_(name, value_params) { \ + public: \ + explicit GMOCK_ACTION_CLASS_(name, value_params) GMOCK_INTERNAL_INIT_##value_params {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + GMOCK_INTERNAL_DEFN_##value_params private : GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(GMOCK_INTERNAL_LIST_##value_params)); \ + } \ + GMOCK_INTERNAL_DEFN_##value_params private : GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params)); \ + }; \ + template \ + inline GMOCK_ACTION_CLASS_( \ + name, value_params) \ + name(GMOCK_INTERNAL_DECL_##value_params) { \ + return GMOCK_ACTION_CLASS_( \ + name, value_params)( \ + GMOCK_INTERNAL_LIST_##value_params); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result GMOCK_ACTION_CLASS_( \ + name, value_params):: \ + gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION(name) \ + class name##Action { \ + public: \ + name##Action() {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl() {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl()); \ + } \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##Action); \ + }; \ + inline name##Action name() { return name##Action(); } \ + template \ + template \ + typename ::testing::internal::Function::Result name##Action::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P(name, p0) \ + template \ + class name##ActionP { \ + public: \ + explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0)); \ + } \ + p0##_type p0; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP); \ + }; \ + template \ + inline name##ActionP name(p0##_type p0) { \ + return name##ActionP(p0); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result name##ActionP::gmock_Impl::gmock_PerformImpl( \ + GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P2(name, p0, p1) \ + template \ + class name##ActionP2 { \ + public: \ + name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP2); \ + }; \ + template \ + inline name##ActionP2 name(p0##_type p0, p1##_type p1) { \ + return name##ActionP2(p0, p1); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP2::gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) \ + const + +#define ACTION_P3(name, p0, p1, p2) \ + template \ + class name##ActionP3 { \ + public: \ + name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP3); \ + }; \ + template \ + inline name##ActionP3 name(p0##_type p0, p1##_type p1, p2##_type p2) { \ + return name##ActionP3(p0, p1, p2); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP3::gmock_Impl::gmock_PerformImpl( \ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const -#define ACTION_P2(name, p0, p1)\ - template \ - class name##ActionP2 {\ - public:\ - name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ - p1(gmock_p1) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ - p1(gmock_p1) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP2);\ - };\ - template \ - inline name##ActionP2 name(p0##_type p0, \ - p1##_type p1) {\ - return name##ActionP2(p0, p1);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP2::gmock_Impl::gmock_PerformImpl(\ +#define ACTION_P4(name, p0, p1, p2, p3) \ + template \ + class name##ActionP4 { \ + public: \ + name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2, p3)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP4); \ + }; \ + template \ + inline name##ActionP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ + p3##_type p3) { \ + return name##ActionP4(p0, p1, p2, p3); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP4::gmock_Impl::gmock_PerformImpl( \ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const -#define ACTION_P3(name, p0, p1, p2)\ - template \ - class name##ActionP3 {\ - public:\ - name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP3);\ - };\ - template \ - inline name##ActionP3 name(p0##_type p0, \ - p1##_type p1, p2##_type p2) {\ - return name##ActionP3(p0, p1, p2);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP3::gmock_Impl::gmock_PerformImpl(\ +#define ACTION_P5(name, p0, p1, p2, p3, p4) \ + template \ + class name##ActionP5 { \ + public: \ + name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP5); \ + }; \ + template \ + inline name##ActionP5 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4) { \ + return name##ActionP5(p0, p1, p2, p3, p4); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP5::gmock_Impl::gmock_PerformImpl( \ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const -#define ACTION_P4(name, p0, p1, p2, p3)\ - template \ - class name##ActionP4 {\ - public:\ - name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP4);\ - };\ - template \ - inline name##ActionP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3) {\ - return name##ActionP4(p0, p1, \ - p2, p3);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP4::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P5(name, p0, p1, p2, p3, p4)\ - template \ - class name##ActionP5 {\ - public:\ - name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), \ - p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP5);\ - };\ - template \ - inline name##ActionP5 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4) {\ - return name##ActionP5(p0, p1, p2, p3, p4);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP5::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\ - template \ - class name##ActionP6 {\ - public:\ - name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP6);\ - };\ - template \ - inline name##ActionP6 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3, p4##_type p4, p5##_type p5) {\ - return name##ActionP6(p0, p1, p2, p3, p4, p5);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP6::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\ - template \ - class name##ActionP7 {\ - public:\ - name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ - p6(gmock_p6) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP7);\ - };\ - template \ - inline name##ActionP7 name(p0##_type p0, p1##_type p1, \ - p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6) {\ - return name##ActionP7(p0, p1, p2, p3, p4, p5, p6);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP7::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\ - template \ - class name##ActionP8 {\ - public:\ - name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), \ - p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), \ - p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP8);\ - };\ - template \ - inline name##ActionP8 name(p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6, p7##_type p7) {\ - return name##ActionP8(p0, p1, p2, p3, p4, p5, \ - p6, p7);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP8::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\ - template \ - class name##ActionP9 {\ - public:\ - name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP9);\ - };\ - template \ - inline name##ActionP9 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ - p8##_type p8) {\ - return name##ActionP9(p0, p1, p2, \ - p3, p4, p5, p6, p7, p8);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP9::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const - -#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\ - template \ - class name##ActionP10 {\ - public:\ - name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ - template \ - class gmock_Impl : public ::testing::ActionInterface {\ - public:\ - typedef F function_type;\ - typedef typename ::testing::internal::Function::Result return_type;\ - typedef typename ::testing::internal::Function::ArgumentTuple\ - args_type;\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ - virtual return_type Perform(const args_type& args) {\ - return ::testing::internal::ActionHelper::\ - Perform(this, args);\ - }\ - template \ - return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ - arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ - arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ - arg9_type arg9) const;\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template operator ::testing::Action() const {\ - return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, \ - p6, p7, p8, p9));\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##ActionP10);\ - };\ - template \ - inline name##ActionP10 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9) {\ - return name##ActionP10(p0, \ - p1, p2, p3, p4, p5, p6, p7, p8, p9);\ - }\ - template \ - template \ - template \ - typename ::testing::internal::Function::Result\ - name##ActionP10::gmock_Impl::gmock_PerformImpl(\ - GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const +#define ACTION_P6(name, p0, p1, p2, p3, p4, p5) \ + template \ + class name##ActionP6 { \ + public: \ + name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP6); \ + }; \ + template \ + inline name##ActionP6 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5) { \ + return name##ActionP6(p0, p1, p2, p3, p4, p5); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP6::gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6) \ + template \ + class name##ActionP7 { \ + public: \ + name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP7); \ + }; \ + template \ + inline name##ActionP7 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6) { \ + return name##ActionP7(p0, p1, p2, p3, \ + p4, p5, p6); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP7::gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7) \ + template \ + class name##ActionP8 { \ + public: \ + name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP8); \ + }; \ + template \ + inline name##ActionP8 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, \ + p7##_type p7) { \ + return name##ActionP8( \ + p0, p1, p2, p3, p4, p5, p6, p7); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP8::gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8) \ + template \ + class name##ActionP9 { \ + public: \ + name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP9); \ + }; \ + template \ + inline name##ActionP9 \ + name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8) { \ + return name##ActionP9(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result \ + name##ActionP9::gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const + +#define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) \ + template \ + class name##ActionP10 { \ + public: \ + name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4, p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8, p9##_type gmock_p9) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8), \ + p9(gmock_p9) {} \ + template \ + class gmock_Impl : public ::testing::ActionInterface { \ + public: \ + typedef F function_type; \ + typedef typename ::testing::internal::Function::Result return_type; \ + typedef typename ::testing::internal::Function::ArgumentTuple args_type; \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, p9##_type gmock_p9) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8), \ + p9(gmock_p9) {} \ + virtual return_type Perform(const args_type& args) { \ + return ::testing::internal::ActionHelper::Perform(this, args); \ + } \ + template \ + return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, arg1_type arg1, arg2_type arg2, \ + arg3_type arg3, arg4_type arg4, arg5_type arg5, arg6_type arg6, arg7_type arg7, \ + arg8_type arg8, arg9_type arg9) const; \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + p9##_type p9; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Action() const { \ + return ::testing::Action(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ + } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + p9##_type p9; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##ActionP10); \ + }; \ + template \ + inline name##ActionP10 \ + name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8, p9##_type p9) { \ + return name##ActionP10(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + } \ + template \ + template \ + template \ + typename ::testing::internal::Function::Result name##ActionP10< \ + p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ + p9##_type>::gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const namespace testing { - // The ACTION*() macros trigger warning C4100 (unreferenced formal // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in // the macro definition, as the warnings are generated when the macro // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +# pragma warning(push) +# pragma warning(disable : 4100) #endif // Various overloads for InvokeArgument(). @@ -2149,147 +1928,101 @@ template R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { return f(a1, a2, a3); } -template +template R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { return f(a1, a2, a3, a4); } -template +template R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { return f(a1, a2, a3, a4, a5); } -template +template R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { return f(a1, a2, a3, a4, a5, a6); } -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7) { +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { return f(a1, a2, a3, a4, a5, a6, a7); } -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8) { +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { return f(a1, a2, a3, a4, a5, a6, a7, a8); } -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9) { +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); } -template -R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, - A7 a7, A8 a8, A9 a9, A10 a10) { +template +R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, A10 a10) { return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); } } // namespace invoke_argument } // namespace internal -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args)); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args)); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(p0)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(p0)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_2_VALUE_PARAMS(p0, p1)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_2_VALUE_PARAMS(p0, p1)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_3_VALUE_PARAMS(p0, p1, p2)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_3_VALUE_PARAMS(p0, p1, p2)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2, p3); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2, p3); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2, p3, p4); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2, p3, + p4); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2, p3, p4, p5); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2, p3, + p4, p5); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2, p3, p4, p5, p6); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2, p3, + p4, p5, p6); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2, p3, p4, p5, p6, p7); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2, p3, + p4, p5, p6, p7); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2, p3, + p4, p5, p6, p7, p8); } -ACTION_TEMPLATE(InvokeArgument, - HAS_1_TEMPLATE_PARAMS(int, k), +ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { using internal::invoke_argument::InvokeArgumentAdl; - return InvokeArgumentAdl( - internal::invoke_argument::AdlTag(), - ::testing::get(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); + return InvokeArgumentAdl(internal::invoke_argument::AdlTag(), ::testing::get(args), p0, p1, p2, p3, + p4, p5, p6, p7, p8, p9); } // Various overloads for ReturnNew(). @@ -2297,74 +2030,47 @@ ACTION_TEMPLATE(InvokeArgument, // The ReturnNew(a1, a2, ..., a_k) action returns a pointer to a new // instance of type T, constructed on the heap with constructor arguments // a1, a2, ..., and a_k. The caller assumes ownership of the returned value. -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_0_VALUE_PARAMS()) { - return new T(); -} +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_0_VALUE_PARAMS()) { return new T(); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_1_VALUE_PARAMS(p0)) { - return new T(p0); -} +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_1_VALUE_PARAMS(p0)) { return new T(p0); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_2_VALUE_PARAMS(p0, p1)) { - return new T(p0, p1); -} +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_2_VALUE_PARAMS(p0, p1)) { return new T(p0, p1); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_3_VALUE_PARAMS(p0, p1, p2)) { +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_3_VALUE_PARAMS(p0, p1, p2)) { return new T(p0, p1, p2); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { return new T(p0, p1, p2, p3); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { return new T(p0, p1, p2, p3, p4); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { return new T(p0, p1, p2, p3, p4, p5); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { return new T(p0, p1, p2, p3, p4, p5, p6); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { return new T(p0, p1, p2, p3, p4, p5, p6, p7); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), - AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -ACTION_TEMPLATE(ReturnNew, - HAS_1_TEMPLATE_PARAMS(typename, T), +ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } #ifdef _MSC_VER -# pragma warning(pop) +# pragma warning(pop) #endif } // namespace testing diff --git a/src/net/test/gmock/include/gmock/gmock-generated-function-mockers.h b/src/net/test/gmock/include/gmock/gmock-generated-function-mockers.h index 4fa5ca9484..1e982c36d3 100644 --- a/src/net/test/gmock/include/gmock/gmock-generated-function-mockers.h +++ b/src/net/test/gmock/include/gmock/gmock-generated-function-mockers.h @@ -44,7 +44,7 @@ #include "gmock/internal/gmock-internal-utils.h" #if GTEST_HAS_STD_FUNCTION_ -# include +# include #endif namespace testing { @@ -62,15 +62,12 @@ template class FunctionMocker; template -class FunctionMocker : public - internal::FunctionMockerBase { +class FunctionMocker : public internal::FunctionMockerBase { public: typedef R F(); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With() { - return this->current_spec(); - } + MockSpec& With() { return this->current_spec(); } R Invoke() { // Even though gcc and MSVC don't enforce it, 'this->' is required @@ -82,8 +79,7 @@ class FunctionMocker : public }; template -class FunctionMocker : public - internal::FunctionMockerBase { +class FunctionMocker : public internal::FunctionMockerBase { public: typedef R F(A1); typedef typename internal::Function::ArgumentTuple ArgumentTuple; @@ -103,8 +99,7 @@ class FunctionMocker : public }; template -class FunctionMocker : public - internal::FunctionMockerBase { +class FunctionMocker : public internal::FunctionMockerBase { public: typedef R F(A1, A2); typedef typename internal::Function::ArgumentTuple ArgumentTuple; @@ -124,14 +119,12 @@ class FunctionMocker : public }; template -class FunctionMocker : public - internal::FunctionMockerBase { +class FunctionMocker : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3) { + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3)); return this->current_spec(); } @@ -146,14 +139,12 @@ class FunctionMocker : public }; template -class FunctionMocker : public - internal::FunctionMockerBase { +class FunctionMocker : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3, A4); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3, const Matcher& m4) { + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3, const Matcher& m4) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4)); return this->current_spec(); } @@ -167,16 +158,14 @@ class FunctionMocker : public } }; -template -class FunctionMocker : public - internal::FunctionMockerBase { +template +class FunctionMocker : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3, A4, A5); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3, const Matcher& m4, const Matcher& m5) { + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3, const Matcher& m4, + const Matcher& m5) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5)); return this->current_spec(); } @@ -190,19 +179,15 @@ class FunctionMocker : public } }; -template -class FunctionMocker : public - internal::FunctionMockerBase { +template +class FunctionMocker : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3, A4, A5, A6); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3, const Matcher& m4, const Matcher& m5, - const Matcher& m6) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6)); + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3, const Matcher& m4, + const Matcher& m5, const Matcher& m6) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6)); return this->current_spec(); } @@ -215,19 +200,16 @@ class FunctionMocker : public } }; -template -class FunctionMocker : public - internal::FunctionMockerBase { +template +class FunctionMocker + : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3, A4, A5, A6, A7); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3, const Matcher& m4, const Matcher& m5, - const Matcher& m6, const Matcher& m7) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7)); + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3, const Matcher& m4, + const Matcher& m5, const Matcher& m6, const Matcher& m7) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7)); return this->current_spec(); } @@ -240,19 +222,17 @@ class FunctionMocker : public } }; -template -class FunctionMocker : public - internal::FunctionMockerBase { +template +class FunctionMocker + : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3, A4, A5, A6, A7, A8); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3, const Matcher& m4, const Matcher& m5, - const Matcher& m6, const Matcher& m7, const Matcher& m8) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7, m8)); + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3, const Matcher& m4, + const Matcher& m5, const Matcher& m6, const Matcher& m7, const Matcher& m8) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8)); return this->current_spec(); } @@ -265,20 +245,18 @@ class FunctionMocker : public } }; -template -class FunctionMocker : public - internal::FunctionMockerBase { +template +class FunctionMocker + : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3, const Matcher& m4, const Matcher& m5, - const Matcher& m6, const Matcher& m7, const Matcher& m8, - const Matcher& m9) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7, m8, m9)); + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3, const Matcher& m4, + const Matcher& m5, const Matcher& m6, const Matcher& m7, const Matcher& m8, + const Matcher& m9) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8, m9)); return this->current_spec(); } @@ -291,32 +269,27 @@ class FunctionMocker : public } }; -template -class FunctionMocker : public - internal::FunctionMockerBase { +template +class FunctionMocker + : public internal::FunctionMockerBase { public: typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); typedef typename internal::Function::ArgumentTuple ArgumentTuple; - MockSpec& With(const Matcher& m1, const Matcher& m2, - const Matcher& m3, const Matcher& m4, const Matcher& m5, - const Matcher& m6, const Matcher& m7, const Matcher& m8, - const Matcher& m9, const Matcher& m10) { - this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, - m6, m7, m8, m9, m10)); + MockSpec& With(const Matcher& m1, const Matcher& m2, const Matcher& m3, const Matcher& m4, + const Matcher& m5, const Matcher& m6, const Matcher& m7, const Matcher& m8, + const Matcher& m9, const Matcher& m10) { + this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8, m9, m10)); return this->current_spec(); } - R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, - A10 a10) { + R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, A10 a10) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). - return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9, - a10)); + return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } }; @@ -334,343 +307,250 @@ using internal::FunctionMocker; // commas (the same reason that we use variadic macros in other places // in this file). // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_RESULT_(tn, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::Result +#define GMOCK_RESULT_(tn, ...) tn ::testing::internal::Function<__VA_ARGS__>::Result // The type of argument N of the given function type. // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_ARG_(tn, N, ...) \ - tn ::testing::internal::Function<__VA_ARGS__>::Argument##N +#define GMOCK_ARG_(tn, N, ...) tn ::testing::internal::Function<__VA_ARGS__>::Argument##N // The matcher type for argument N of the given function type. // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MATCHER_(tn, N, ...) \ - const ::testing::Matcher& +#define GMOCK_MATCHER_(tn, N, ...) const ::testing::Matcher& // The variable for mocking the given method. // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_MOCKER_(arity, constness, Method) \ - GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) +#define GMOCK_MOCKER_(arity, constness, Method) GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - ) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 0), \ - this_method_does_not_take_0_arguments); \ - GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(0, constness, Method).Invoke(); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method() constness { \ - GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(0, constness, Method).With(); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \ - Method) +#define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method() constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 0), \ + this_method_does_not_take_0_arguments); \ + GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(0, constness, Method).Invoke(); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method() constness { \ + GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(0, constness, Method).With(); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 1), \ - this_method_does_not_take_1_argument); \ - GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(1, constness, Method).Invoke(gmock_a1); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ - GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \ - Method) +#define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 1), \ + this_method_does_not_take_1_argument); \ + GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(1, constness, Method).Invoke(gmock_a1); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ + GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 2), \ - this_method_does_not_take_2_arguments); \ - GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(2, constness, Method).Invoke(gmock_a1, gmock_a2); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ - GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \ - Method) +#define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 2), \ + this_method_does_not_take_2_arguments); \ + GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(2, constness, Method).Invoke(gmock_a1, gmock_a2); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ + GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 3), \ - this_method_does_not_take_3_arguments); \ - GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(3, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ - GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \ - Method) +#define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 3), \ + this_method_does_not_take_3_arguments); \ + GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(3, constness, Method).Invoke(gmock_a1, gmock_a2, gmock_a3); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ + GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ + GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, gmock_a3); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 4), \ - this_method_does_not_take_4_arguments); \ - GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(4, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ - GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \ - Method) +#define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 4), \ + this_method_does_not_take_4_arguments); \ + GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(4, constness, Method).Invoke(gmock_a1, gmock_a2, gmock_a3, gmock_a4); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method( \ + GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ + GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, gmock_a3, gmock_a4); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 5), \ - this_method_does_not_take_5_arguments); \ - GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(5, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ - GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \ - Method) +#define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 5), \ + this_method_does_not_take_5_arguments); \ + GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(5, constness, Method).Invoke(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method( \ + GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ + GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 6), \ - this_method_does_not_take_6_arguments); \ - GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(6, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ - GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \ - Method) +#define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 6), \ + this_method_does_not_take_6_arguments); \ + GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(6, constness, Method).Invoke(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method( \ + GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ + GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 7), \ - this_method_does_not_take_7_arguments); \ - GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(7, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ - GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \ - Method) +#define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 7), \ + this_method_does_not_take_7_arguments); \ + GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(7, constness, Method) \ + .Invoke(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method( \ + GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ + GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(7, constness, Method) \ + .With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 8), \ - this_method_does_not_take_8_arguments); \ - GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(8, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ - GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \ - Method) +#define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 8), \ + this_method_does_not_take_8_arguments); \ + GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(8, constness, Method) \ + .Invoke(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method( \ + GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ + GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(8, constness, Method) \ + .With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 9), \ - this_method_does_not_take_9_arguments); \ - GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(9, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ - gmock_a9); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ - GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ - gmock_a9); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \ - Method) +#define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 9), \ + this_method_does_not_take_9_arguments); \ + GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(9, constness, Method) \ + .Invoke(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method( \ + GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ + GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(9, constness, Method) \ + .With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! -#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \ - GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ - GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \ - GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ - GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ - tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ - == 10), \ - this_method_does_not_take_10_arguments); \ - GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ - return GMOCK_MOCKER_(10, constness, Method).Invoke(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ - gmock_a10); \ - } \ - ::testing::MockSpec<__VA_ARGS__>& \ - gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ - GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ - GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ - GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ - GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ - GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ - GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ - GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ - GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \ - GMOCK_MATCHER_(tn, 10, \ - __VA_ARGS__) gmock_a10) constness { \ - GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \ - return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \ - gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ - gmock_a10); \ - } \ - mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \ - Method) +#define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \ + GMOCK_RESULT_(tn, __VA_ARGS__) \ + ct Method(GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ + GTEST_COMPILE_ASSERT_( \ + (::testing::tuple_size::ArgumentTuple>::value == 10), \ + this_method_does_not_take_10_arguments); \ + GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ + return GMOCK_MOCKER_(10, constness, Method) \ + .Invoke(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, gmock_a10); \ + } \ + ::testing::MockSpec<__VA_ARGS__>& gmock_##Method( \ + GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ + GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ + GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ + GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ + GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, GMOCK_MATCHER_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ + GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \ + return GMOCK_MOCKER_(10, constness, Method) \ + .With(gmock_a1, gmock_a2, gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, gmock_a10); \ + } \ + mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, Method) #define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__) #define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__) @@ -708,120 +588,65 @@ using internal::FunctionMocker; #define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__) -#define MOCK_CONST_METHOD0_T(m, ...) \ - GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_T(m, ...) \ - GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_T(m, ...) \ - GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_T(m, ...) \ - GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_T(m, ...) \ - GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_T(m, ...) \ - GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_T(m, ...) \ - GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_T(m, ...) \ - GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_T(m, ...) \ - GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_T(m, ...) \ - GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_T(m, ...) \ - GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__) - -#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(, , ct, m, __VA_ARGS__) -#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(, , ct, m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__) - -#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__) -#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__) - -#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__) -#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ - GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__) + +#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD0_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD1_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD2_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD3_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD4_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD5_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD6_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD7_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD8_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD9_(, , ct, m, __VA_ARGS__) +#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD10_(, , ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__) + +#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__) +#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__) + +#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__) +#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__) // A MockFunction class has one mock method whose type is F. It is // useful when you just want your test code to emit some messages and @@ -881,9 +706,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this]() -> R { - return this->Call(); - }; + return [this]() -> R { return this->Call(); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -900,9 +723,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0) -> R { - return this->Call(a0); - }; + return [this](A0 a0) -> R { return this->Call(a0); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -919,9 +740,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1) -> R { - return this->Call(a0, a1); - }; + return [this](A0 a0, A1 a1) -> R { return this->Call(a0, a1); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -938,9 +757,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1, A2 a2) -> R { - return this->Call(a0, a1, a2); - }; + return [this](A0 a0, A1 a1, A2 a2) -> R { return this->Call(a0, a1, a2); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -957,9 +774,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1, A2 a2, A3 a3) -> R { - return this->Call(a0, a1, a2, a3); - }; + return [this](A0 a0, A1 a1, A2 a2, A3 a3) -> R { return this->Call(a0, a1, a2, a3); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -967,8 +782,7 @@ class MockFunction { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; -template +template class MockFunction { public: MockFunction() {} @@ -977,9 +791,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) -> R { - return this->Call(a0, a1, a2, a3, a4); - }; + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) -> R { return this->Call(a0, a1, a2, a3, a4); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -987,8 +799,7 @@ class MockFunction { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; -template +template class MockFunction { public: MockFunction() {} @@ -997,9 +808,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) -> R { - return this->Call(a0, a1, a2, a3, a4, a5); - }; + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) -> R { return this->Call(a0, a1, a2, a3, a4, a5); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -1007,8 +816,7 @@ class MockFunction { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; -template +template class MockFunction { public: MockFunction() {} @@ -1017,9 +825,8 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) -> R { - return this->Call(a0, a1, a2, a3, a4, a5, a6); - }; + return + [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) -> R { return this->Call(a0, a1, a2, a3, a4, a5, a6); }; } #endif // GTEST_HAS_STD_FUNCTION_ @@ -1027,8 +834,8 @@ class MockFunction { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; -template +template class MockFunction { public: MockFunction() {} @@ -1047,8 +854,8 @@ class MockFunction { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; -template +template class MockFunction { public: MockFunction() {} @@ -1057,8 +864,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, - A8 a8) -> R { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) -> R { return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8); }; } @@ -1068,9 +874,8 @@ class MockFunction { GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; -template +template class MockFunction { public: MockFunction() {} @@ -1079,8 +884,7 @@ class MockFunction { #if GTEST_HAS_STD_FUNCTION_ std::function AsStdFunction() { - return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, - A8 a8, A9 a9) -> R { + return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) -> R { return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }; } diff --git a/src/net/test/gmock/include/gmock/gmock-generated-matchers.h b/src/net/test/gmock/include/gmock/gmock-generated-matchers.h index 57056fd91d..48732d64d7 100644 --- a/src/net/test/gmock/include/gmock/gmock-generated-matchers.h +++ b/src/net/test/gmock/include/gmock/gmock-generated-matchers.h @@ -48,8 +48,7 @@ namespace testing { namespace internal { // The type of the i-th (0-based) field of Tuple. -#define GMOCK_FIELD_TYPE_(Tuple, i) \ - typename ::testing::tuple_element::type +#define GMOCK_FIELD_TYPE_(Tuple, i) typename ::testing::tuple_element::type // TupleFields is for selecting fields from a // tuple of type Tuple. It has two members: @@ -62,25 +61,22 @@ namespace internal { // type is tuple, and // GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true). -template +template class TupleFields; // This generic version is used when there are 10 selectors. -template +template class TupleFields { public: - typedef ::testing::tuple type; + typedef ::testing::tuple + type; static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t), get(t), get(t), get(t), - get(t), get(t), get(t), get(t), get(t)); + return type(get(t), get(t), get(t), get(t), get(t), get(t), get(t), get(t), + get(t), get(t)); } }; @@ -90,57 +86,46 @@ template class TupleFields { public: typedef ::testing::tuple<> type; - static type GetSelectedFields(const Tuple& /* t */) { - return type(); - } + static type GetSelectedFields(const Tuple& /* t */) { return type(); } }; template class TupleFields { public: typedef ::testing::tuple type; - static type GetSelectedFields(const Tuple& t) { - return type(get(t)); - } + static type GetSelectedFields(const Tuple& t) { return type(get(t)); } }; template class TupleFields { public: - typedef ::testing::tuple type; - static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t)); - } + typedef ::testing::tuple type; + static type GetSelectedFields(const Tuple& t) { return type(get(t), get(t)); } }; template class TupleFields { public: - typedef ::testing::tuple type; - static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t), get(t)); - } + typedef ::testing::tuple + type; + static type GetSelectedFields(const Tuple& t) { return type(get(t), get(t), get(t)); } }; template class TupleFields { public: - typedef ::testing::tuple type; - static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t), get(t), get(t)); - } + typedef ::testing::tuple + type; + static type GetSelectedFields(const Tuple& t) { return type(get(t), get(t), get(t), get(t)); } }; template class TupleFields { public: - typedef ::testing::tuple type; + typedef ::testing::tuple + type; static type GetSelectedFields(const Tuple& t) { return type(get(t), get(t), get(t), get(t), get(t)); } @@ -149,89 +134,76 @@ class TupleFields { template class TupleFields { public: - typedef ::testing::tuple type; + typedef ::testing::tuple + type; static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t), get(t), get(t), get(t), - get(t)); + return type(get(t), get(t), get(t), get(t), get(t), get(t)); } }; template class TupleFields { public: - typedef ::testing::tuple type; + typedef ::testing::tuple + type; static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t), get(t), get(t), get(t), - get(t), get(t)); + return type(get(t), get(t), get(t), get(t), get(t), get(t), get(t)); } }; -template +template class TupleFields { public: - typedef ::testing::tuple type; + typedef ::testing::tuple + type; static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t), get(t), get(t), get(t), - get(t), get(t), get(t)); + return type(get(t), get(t), get(t), get(t), get(t), get(t), get(t), get(t)); } }; -template +template class TupleFields { public: - typedef ::testing::tuple type; + typedef ::testing::tuple + type; static type GetSelectedFields(const Tuple& t) { - return type(get(t), get(t), get(t), get(t), get(t), - get(t), get(t), get(t), get(t)); + return type(get(t), get(t), get(t), get(t), get(t), get(t), get(t), get(t), + get(t)); } }; #undef GMOCK_FIELD_TYPE_ // Implements the Args() matcher. -template +template class ArgsMatcherImpl : public MatcherInterface { public: // ArgsTuple may have top-level const or reference modifiers. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple; - typedef typename internal::TupleFields::type SelectedArgs; + typedef typename internal::TupleFields::type SelectedArgs; typedef Matcher MonomorphicInnerMatcher; template explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher) : inner_matcher_(SafeMatcherCast(inner_matcher)) {} - virtual bool MatchAndExplain(ArgsTuple args, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(ArgsTuple args, MatchResultListener* listener) const { const SelectedArgs& selected_args = GetSelectedArgs(args); - if (!listener->IsInterested()) - return inner_matcher_.Matches(selected_args); + if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args); PrintIndices(listener->stream()); *listener << "are " << PrintToString(selected_args); StringMatchResultListener inner_listener; - const bool match = inner_matcher_.MatchAndExplain(selected_args, - &inner_listener); + const bool match = inner_matcher_.MatchAndExplain(selected_args, &inner_listener); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } @@ -250,20 +222,17 @@ class ArgsMatcherImpl : public MatcherInterface { private: static SelectedArgs GetSelectedArgs(ArgsTuple args) { - return TupleFields::GetSelectedFields(args); + return TupleFields::GetSelectedFields(args); } // Prints the indices of the selected fields. static void PrintIndices(::std::ostream* os) { *os << "whose fields ("; - const int indices[10] = { k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 }; + const int indices[10] = {k0, k1, k2, k3, k4, k5, k6, k7, k8, k9}; for (int i = 0; i < 10; i++) { - if (indices[i] < 0) - break; + if (indices[i] < 0) break; - if (i >= 1) - *os << ", "; + if (i >= 1) *os << ", "; *os << "#" << indices[i]; } @@ -275,18 +244,15 @@ class ArgsMatcherImpl : public MatcherInterface { GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl); }; -template +template class ArgsMatcher { public: - explicit ArgsMatcher(const InnerMatcher& inner_matcher) - : inner_matcher_(inner_matcher) {} + explicit ArgsMatcher(const InnerMatcher& inner_matcher) : inner_matcher_(inner_matcher) {} template operator Matcher() const { - return MakeMatcher(new ArgsMatcherImpl(inner_matcher_)); + return MakeMatcher(new ArgsMatcherImpl(inner_matcher_)); } private: @@ -308,79 +274,52 @@ struct AllOfResult1 { template struct AllOfResult2 { - typedef BothOfMatcher< - typename AllOfResult1::type, - typename AllOfResult1::type - > type; + typedef BothOfMatcher::type, typename AllOfResult1::type> type; }; template struct AllOfResult3 { - typedef BothOfMatcher< - typename AllOfResult1::type, - typename AllOfResult2::type - > type; + typedef BothOfMatcher::type, typename AllOfResult2::type> type; }; template struct AllOfResult4 { - typedef BothOfMatcher< - typename AllOfResult2::type, - typename AllOfResult2::type - > type; + typedef BothOfMatcher::type, typename AllOfResult2::type> type; }; template struct AllOfResult5 { - typedef BothOfMatcher< - typename AllOfResult2::type, - typename AllOfResult3::type - > type; + typedef BothOfMatcher::type, typename AllOfResult3::type> type; }; -template +template struct AllOfResult6 { - typedef BothOfMatcher< - typename AllOfResult3::type, - typename AllOfResult3::type - > type; + typedef BothOfMatcher::type, typename AllOfResult3::type> type; }; -template +template struct AllOfResult7 { - typedef BothOfMatcher< - typename AllOfResult3::type, - typename AllOfResult4::type - > type; + typedef BothOfMatcher::type, typename AllOfResult4::type> type; }; -template +template struct AllOfResult8 { - typedef BothOfMatcher< - typename AllOfResult4::type, - typename AllOfResult4::type - > type; + typedef BothOfMatcher::type, typename AllOfResult4::type> type; }; -template +template struct AllOfResult9 { - typedef BothOfMatcher< - typename AllOfResult4::type, - typename AllOfResult5::type - > type; + typedef BothOfMatcher::type, typename AllOfResult5::type> + type; }; -template +template struct AllOfResult10 { - typedef BothOfMatcher< - typename AllOfResult5::type, - typename AllOfResult5::type - > type; + typedef BothOfMatcher::type, + typename AllOfResult5::type> + type; }; // A set of metafunctions for computing the result type of AnyOf. @@ -396,79 +335,53 @@ struct AnyOfResult1 { template struct AnyOfResult2 { - typedef EitherOfMatcher< - typename AnyOfResult1::type, - typename AnyOfResult1::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult1::type> type; }; template struct AnyOfResult3 { - typedef EitherOfMatcher< - typename AnyOfResult1::type, - typename AnyOfResult2::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult2::type> type; }; template struct AnyOfResult4 { - typedef EitherOfMatcher< - typename AnyOfResult2::type, - typename AnyOfResult2::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult2::type> type; }; template struct AnyOfResult5 { - typedef EitherOfMatcher< - typename AnyOfResult2::type, - typename AnyOfResult3::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult3::type> type; }; -template +template struct AnyOfResult6 { - typedef EitherOfMatcher< - typename AnyOfResult3::type, - typename AnyOfResult3::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult3::type> type; }; -template +template struct AnyOfResult7 { - typedef EitherOfMatcher< - typename AnyOfResult3::type, - typename AnyOfResult4::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult4::type> type; }; -template +template struct AnyOfResult8 { - typedef EitherOfMatcher< - typename AnyOfResult4::type, - typename AnyOfResult4::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult4::type> + type; }; -template +template struct AnyOfResult9 { - typedef EitherOfMatcher< - typename AnyOfResult4::type, - typename AnyOfResult5::type - > type; + typedef EitherOfMatcher::type, typename AnyOfResult5::type> + type; }; -template +template struct AnyOfResult10 { - typedef EitherOfMatcher< - typename AnyOfResult5::type, - typename AnyOfResult5::type - > type; + typedef EitherOfMatcher::type, + typename AnyOfResult5::type> + type; }; } // namespace internal @@ -477,78 +390,58 @@ struct AnyOfResult10 { // fields of it matches a_matcher. C++ doesn't support default // arguments for function templates, so we have to overload it. template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { return internal::ArgsMatcher(matcher); } template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { return internal::ArgsMatcher(matcher); } template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { return internal::ArgsMatcher(matcher); } template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { return internal::ArgsMatcher(matcher); } template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { return internal::ArgsMatcher(matcher); } template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { return internal::ArgsMatcher(matcher); } template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { return internal::ArgsMatcher(matcher); } -template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { - return internal::ArgsMatcher(matcher); +template +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher(matcher); } -template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { - return internal::ArgsMatcher(matcher); +template +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher(matcher); } -template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { - return internal::ArgsMatcher(matcher); +template +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher(matcher); } -template -inline internal::ArgsMatcher -Args(const InnerMatcher& matcher) { - return internal::ArgsMatcher(matcher); +template +inline internal::ArgsMatcher Args(const InnerMatcher& matcher) { + return internal::ArgsMatcher(matcher); } // ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with @@ -565,604 +458,409 @@ Args(const InnerMatcher& matcher) { // must not be used with containers whose elements's order is // undefined (e.g. hash_map). -inline internal::ElementsAreMatcher< - ::testing::tuple<> > -ElementsAre() { +inline internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre() { typedef ::testing::tuple<> Args; return internal::ElementsAreMatcher(Args()); } template -inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type> > -ElementsAre(const T1& e1) { - typedef ::testing::tuple< - typename internal::DecayArray::type> Args; +inline internal::ElementsAreMatcher< ::testing::tuple::type> > ElementsAre( + const T1& e1) { + typedef ::testing::tuple::type> Args; return internal::ElementsAreMatcher(Args(e1)); } template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type> > + ::testing::tuple::type, typename internal::DecayArray::type> > ElementsAre(const T1& e1, const T2& e2) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + typedef ::testing::tuple::type, typename internal::DecayArray::type> Args; return internal::ElementsAreMatcher(Args(e1, e2)); } template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; return internal::ElementsAreMatcher(Args(e1, e2, e3)); } template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; return internal::ElementsAreMatcher(Args(e1, e2, e3, e4)); } template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5)); } -template +template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6)); } -template +template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7)); } -template +template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, - e8)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, + const T8& e8) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; + return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, e8)); } -template +template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, - e8, e9)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, + const T8& e8, const T9& e9) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; + return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9)); } -template +template inline internal::ElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, - const T10& e10) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, - e8, e9, e10)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > +ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, + const T8& e8, const T9& e9, const T10& e10) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; + return internal::ElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10)); } // UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension // that matches n elements in any order. We support up to n=10 arguments. -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple<> > -UnorderedElementsAre() { +inline internal::UnorderedElementsAreMatcher< ::testing::tuple<> > UnorderedElementsAre() { typedef ::testing::tuple<> Args; return internal::UnorderedElementsAreMatcher(Args()); } template -inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type> > +inline internal::UnorderedElementsAreMatcher< ::testing::tuple::type> > UnorderedElementsAre(const T1& e1) { - typedef ::testing::tuple< - typename internal::DecayArray::type> Args; + typedef ::testing::tuple::type> Args; return internal::UnorderedElementsAreMatcher(Args(e1)); } template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type> > + ::testing::tuple::type, typename internal::DecayArray::type> > UnorderedElementsAre(const T1& e1, const T2& e2) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + typedef ::testing::tuple::type, typename internal::DecayArray::type> Args; return internal::UnorderedElementsAreMatcher(Args(e1, e2)); } template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3)); } template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4)); } template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5)); } -template +template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, - e6)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; + return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6)); } -template +template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, - e6, e7)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; + return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7)); } -template +template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, - e6, e7, e8)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, + const T8& e8) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; + return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, e8)); } -template +template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, - e6, e7, e8, e9)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, + const T8& e8, const T9& e9) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type> + Args; + return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9)); } -template +template inline internal::UnorderedElementsAreMatcher< - ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> > -UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, - const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, - const T10& e10) { - typedef ::testing::tuple< - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type, - typename internal::DecayArray::type> Args; - return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, - e6, e7, e8, e9, e10)); + ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> > +UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, + const T8& e8, const T9& e9, const T10& e10) { + typedef ::testing::tuple::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type, + typename internal::DecayArray::type, typename internal::DecayArray::type> + Args; + return internal::UnorderedElementsAreMatcher(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10)); } // AllOf(m1, m2, ..., mk) matches any value that matches all of the given // sub-matchers. AllOf is called fully qualified to prevent ADL from firing. template -inline typename internal::AllOfResult2::type -AllOf(M1 m1, M2 m2) { - return typename internal::AllOfResult2::type( - m1, - m2); +inline typename internal::AllOfResult2::type AllOf(M1 m1, M2 m2) { + return typename internal::AllOfResult2::type(m1, m2); } template -inline typename internal::AllOfResult3::type -AllOf(M1 m1, M2 m2, M3 m3) { - return typename internal::AllOfResult3::type( - m1, - ::testing::AllOf(m2, m3)); +inline typename internal::AllOfResult3::type AllOf(M1 m1, M2 m2, M3 m3) { + return typename internal::AllOfResult3::type(m1, ::testing::AllOf(m2, m3)); } template -inline typename internal::AllOfResult4::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4) { - return typename internal::AllOfResult4::type( - ::testing::AllOf(m1, m2), - ::testing::AllOf(m3, m4)); +inline typename internal::AllOfResult4::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4) { + return typename internal::AllOfResult4::type(::testing::AllOf(m1, m2), ::testing::AllOf(m3, m4)); } template -inline typename internal::AllOfResult5::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { - return typename internal::AllOfResult5::type( - ::testing::AllOf(m1, m2), - ::testing::AllOf(m3, m4, m5)); +inline typename internal::AllOfResult5::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { + return + typename internal::AllOfResult5::type(::testing::AllOf(m1, m2), ::testing::AllOf(m3, m4, m5)); } -template -inline typename internal::AllOfResult6::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { - return typename internal::AllOfResult6::type( - ::testing::AllOf(m1, m2, m3), - ::testing::AllOf(m4, m5, m6)); +template +inline typename internal::AllOfResult6::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { + return typename internal::AllOfResult6::type(::testing::AllOf(m1, m2, m3), + ::testing::AllOf(m4, m5, m6)); } -template -inline typename internal::AllOfResult7::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { - return typename internal::AllOfResult7::type( - ::testing::AllOf(m1, m2, m3), - ::testing::AllOf(m4, m5, m6, m7)); +template +inline typename internal::AllOfResult7::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, + M7 m7) { + return typename internal::AllOfResult7::type(::testing::AllOf(m1, m2, m3), + ::testing::AllOf(m4, m5, m6, m7)); } -template -inline typename internal::AllOfResult8::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { - return typename internal::AllOfResult8::type( - ::testing::AllOf(m1, m2, m3, m4), - ::testing::AllOf(m5, m6, m7, m8)); +template +inline typename internal::AllOfResult8::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, + M6 m6, M7 m7, M8 m8) { + return typename internal::AllOfResult8::type(::testing::AllOf(m1, m2, m3, m4), + ::testing::AllOf(m5, m6, m7, m8)); } -template -inline typename internal::AllOfResult9::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { - return typename internal::AllOfResult9::type( - ::testing::AllOf(m1, m2, m3, m4), - ::testing::AllOf(m5, m6, m7, m8, m9)); +template +inline typename internal::AllOfResult9::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, + M5 m5, M6 m6, M7 m7, M8 m8, + M9 m9) { + return typename internal::AllOfResult9::type( + ::testing::AllOf(m1, m2, m3, m4), ::testing::AllOf(m5, m6, m7, m8, m9)); } -template -inline typename internal::AllOfResult10::type -AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { - return typename internal::AllOfResult10::type( - ::testing::AllOf(m1, m2, m3, m4, m5), - ::testing::AllOf(m6, m7, m8, m9, m10)); +template +inline typename internal::AllOfResult10::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, + M5 m5, M6 m6, M7 m7, M8 m8, + M9 m9, M10 m10) { + return typename internal::AllOfResult10::type( + ::testing::AllOf(m1, m2, m3, m4, m5), ::testing::AllOf(m6, m7, m8, m9, m10)); } // AnyOf(m1, m2, ..., mk) matches any value that matches any of the given // sub-matchers. AnyOf is called fully qualified to prevent ADL from firing. template -inline typename internal::AnyOfResult2::type -AnyOf(M1 m1, M2 m2) { - return typename internal::AnyOfResult2::type( - m1, - m2); +inline typename internal::AnyOfResult2::type AnyOf(M1 m1, M2 m2) { + return typename internal::AnyOfResult2::type(m1, m2); } template -inline typename internal::AnyOfResult3::type -AnyOf(M1 m1, M2 m2, M3 m3) { - return typename internal::AnyOfResult3::type( - m1, - ::testing::AnyOf(m2, m3)); +inline typename internal::AnyOfResult3::type AnyOf(M1 m1, M2 m2, M3 m3) { + return typename internal::AnyOfResult3::type(m1, ::testing::AnyOf(m2, m3)); } template -inline typename internal::AnyOfResult4::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4) { - return typename internal::AnyOfResult4::type( - ::testing::AnyOf(m1, m2), - ::testing::AnyOf(m3, m4)); +inline typename internal::AnyOfResult4::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4) { + return typename internal::AnyOfResult4::type(::testing::AnyOf(m1, m2), ::testing::AnyOf(m3, m4)); } template -inline typename internal::AnyOfResult5::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { - return typename internal::AnyOfResult5::type( - ::testing::AnyOf(m1, m2), - ::testing::AnyOf(m3, m4, m5)); +inline typename internal::AnyOfResult5::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { + return + typename internal::AnyOfResult5::type(::testing::AnyOf(m1, m2), ::testing::AnyOf(m3, m4, m5)); } -template -inline typename internal::AnyOfResult6::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { - return typename internal::AnyOfResult6::type( - ::testing::AnyOf(m1, m2, m3), - ::testing::AnyOf(m4, m5, m6)); +template +inline typename internal::AnyOfResult6::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { + return typename internal::AnyOfResult6::type(::testing::AnyOf(m1, m2, m3), + ::testing::AnyOf(m4, m5, m6)); } -template -inline typename internal::AnyOfResult7::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { - return typename internal::AnyOfResult7::type( - ::testing::AnyOf(m1, m2, m3), - ::testing::AnyOf(m4, m5, m6, m7)); +template +inline typename internal::AnyOfResult7::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, + M7 m7) { + return typename internal::AnyOfResult7::type(::testing::AnyOf(m1, m2, m3), + ::testing::AnyOf(m4, m5, m6, m7)); } -template -inline typename internal::AnyOfResult8::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { - return typename internal::AnyOfResult8::type( - ::testing::AnyOf(m1, m2, m3, m4), - ::testing::AnyOf(m5, m6, m7, m8)); +template +inline typename internal::AnyOfResult8::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, + M6 m6, M7 m7, M8 m8) { + return typename internal::AnyOfResult8::type(::testing::AnyOf(m1, m2, m3, m4), + ::testing::AnyOf(m5, m6, m7, m8)); } -template -inline typename internal::AnyOfResult9::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { - return typename internal::AnyOfResult9::type( - ::testing::AnyOf(m1, m2, m3, m4), - ::testing::AnyOf(m5, m6, m7, m8, m9)); +template +inline typename internal::AnyOfResult9::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, + M5 m5, M6 m6, M7 m7, M8 m8, + M9 m9) { + return typename internal::AnyOfResult9::type( + ::testing::AnyOf(m1, m2, m3, m4), ::testing::AnyOf(m5, m6, m7, m8, m9)); } -template -inline typename internal::AnyOfResult10::type -AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { - return typename internal::AnyOfResult10::type( - ::testing::AnyOf(m1, m2, m3, m4, m5), - ::testing::AnyOf(m6, m7, m8, m9, m10)); +template +inline typename internal::AnyOfResult10::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, + M5 m5, M6 m6, M7 m7, M8 m8, + M9 m9, M10 m10) { + return typename internal::AnyOfResult10::type( + ::testing::AnyOf(m1, m2, m3, m4, m5), ::testing::AnyOf(m6, m7, m8, m9, m10)); } } // namespace testing - // The MATCHER* family of macros can be used in a namespace scope to // define custom matchers easily. // @@ -1378,802 +1076,680 @@ AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { // To learn more about using these macros, please search for 'MATCHER' // on http://code.google.com/p/googlemock/wiki/CookBook. -#define MATCHER(name, description)\ - class name##Matcher {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl()\ - {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple<>()));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl());\ - }\ - name##Matcher() {\ - }\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##Matcher);\ - };\ - inline name##Matcher name() {\ - return name##Matcher();\ - }\ - template \ - bool name##Matcher::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P(name, p0, description)\ - template \ - class name##MatcherP {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - explicit gmock_Impl(p0##_type gmock_p0)\ - : p0(gmock_p0) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0));\ - }\ - explicit name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {\ - }\ - p0##_type p0;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP);\ - };\ - template \ - inline name##MatcherP name(p0##_type p0) {\ - return name##MatcherP(p0);\ - }\ - template \ - template \ - bool name##MatcherP::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P2(name, p0, p1, description)\ - template \ - class name##MatcherP2 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ - : p0(gmock_p0), p1(gmock_p1) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1));\ - }\ - name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ - p1(gmock_p1) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP2);\ - };\ - template \ - inline name##MatcherP2 name(p0##_type p0, \ - p1##_type p1) {\ - return name##MatcherP2(p0, p1);\ - }\ - template \ - template \ - bool name##MatcherP2::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P3(name, p0, p1, p2, description)\ - template \ - class name##MatcherP3 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, \ - p2)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2));\ - }\ - name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP3);\ - };\ - template \ - inline name##MatcherP3 name(p0##_type p0, \ - p1##_type p1, p2##_type p2) {\ - return name##MatcherP3(p0, p1, p2);\ - }\ - template \ - template \ - bool name##MatcherP3::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P4(name, p0, p1, p2, p3, description)\ - template \ - class name##MatcherP4 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, p2, p3)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3));\ - }\ - name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP4);\ - };\ - template \ - inline name##MatcherP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3) {\ - return name##MatcherP4(p0, \ - p1, p2, p3);\ - }\ - template \ - template \ - bool name##MatcherP4::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\ - template \ - class name##MatcherP5 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, p2, p3, p4)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4));\ - }\ - name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, \ - p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP5);\ - };\ - template \ - inline name##MatcherP5 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4) {\ - return name##MatcherP5(p0, p1, p2, p3, p4);\ - }\ - template \ - template \ - bool name##MatcherP5::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\ - template \ - class name##MatcherP6 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, p2, p3, p4, p5)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5));\ - }\ - name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP6);\ - };\ - template \ - inline name##MatcherP6 name(p0##_type p0, p1##_type p1, p2##_type p2, \ - p3##_type p3, p4##_type p4, p5##_type p5) {\ - return name##MatcherP6(p0, p1, p2, p3, p4, p5);\ - }\ - template \ - template \ - bool name##MatcherP6::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\ - template \ - class name##MatcherP7 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, p2, p3, p4, p5, \ - p6)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6));\ - }\ - name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ - p6(gmock_p6) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP7);\ - };\ - template \ - inline name##MatcherP7 name(p0##_type p0, p1##_type p1, \ - p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6) {\ - return name##MatcherP7(p0, p1, p2, p3, p4, p5, p6);\ - }\ - template \ - template \ - bool name##MatcherP7::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\ - template \ - class name##MatcherP8 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, p2, \ - p3, p4, p5, p6, p7)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7));\ - }\ - name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, \ - p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP8);\ - };\ - template \ - inline name##MatcherP8 name(p0##_type p0, \ - p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ - p6##_type p6, p7##_type p7) {\ - return name##MatcherP8(p0, p1, p2, p3, p4, p5, \ - p6, p7);\ - }\ - template \ - template \ - bool name##MatcherP8::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\ - template \ - class name##MatcherP9 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8));\ - }\ - name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ - p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP9);\ - };\ - template \ - inline name##MatcherP9 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ - p8##_type p8) {\ - return name##MatcherP9(p0, p1, p2, \ - p3, p4, p5, p6, p7, p8);\ - }\ - template \ - template \ - bool name##MatcherP9::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const - -#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\ - template \ - class name##MatcherP10 {\ - public:\ - template \ - class gmock_Impl : public ::testing::MatcherInterface {\ - public:\ - gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ - p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ - p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ - p9##_type gmock_p9)\ - : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ - p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ - p8(gmock_p8), p9(gmock_p9) {}\ - virtual bool MatchAndExplain(\ - arg_type arg, ::testing::MatchResultListener* result_listener) const;\ - virtual void DescribeTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(false);\ - }\ - virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ - *gmock_os << FormatDescription(true);\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - ::testing::internal::string FormatDescription(bool negation) const {\ - const ::testing::internal::string gmock_description = (description);\ - if (!gmock_description.empty())\ - return gmock_description;\ - return ::testing::internal::FormatMatcherDescription(\ - negation, #name, \ - ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ - ::testing::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\ - }\ - GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ - };\ - template \ - operator ::testing::Matcher() const {\ - return ::testing::Matcher(\ - new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\ - }\ - name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \ - p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ - p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ - p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ - p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ - p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {\ - }\ - p0##_type p0;\ - p1##_type p1;\ - p2##_type p2;\ - p3##_type p3;\ - p4##_type p4;\ - p5##_type p5;\ - p6##_type p6;\ - p7##_type p7;\ - p8##_type p8;\ - p9##_type p9;\ - private:\ - GTEST_DISALLOW_ASSIGN_(name##MatcherP10);\ - };\ - template \ - inline name##MatcherP10 name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ - p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ - p9##_type p9) {\ - return name##MatcherP10(p0, \ - p1, p2, p3, p4, p5, p6, p7, p8, p9);\ - }\ - template \ - template \ - bool name##MatcherP10::gmock_Impl::MatchAndExplain(\ - arg_type arg, \ - ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ - const +#define MATCHER(name, description) \ + class name##Matcher { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl() {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, ::testing::internal::UniversalTersePrintTupleFieldsToStrings(::testing::tuple<>())); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl()); \ + } \ + name##Matcher() {} \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##Matcher); \ + }; \ + inline name##Matcher name() { return name##Matcher(); } \ + template \ + bool name##Matcher::gmock_Impl::MatchAndExplain( \ + arg_type arg, ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P(name, p0, description) \ + template \ + class name##MatcherP { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings(::testing::tuple(p0))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0)); \ + } \ + explicit name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {} \ + p0##_type p0; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP); \ + }; \ + template \ + inline name##MatcherP name(p0##_type p0) { \ + return name##MatcherP(p0); \ + } \ + template \ + template \ + bool name##MatcherP::gmock_Impl::MatchAndExplain( \ + arg_type arg, ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P2(name, p0, p1, description) \ + template \ + class name##MatcherP2 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1)); \ + } \ + name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) {} \ + p0##_type p0; \ + p1##_type p1; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP2); \ + }; \ + template \ + inline name##MatcherP2 name(p0##_type p0, p1##_type p1) { \ + return name##MatcherP2(p0, p1); \ + } \ + template \ + template \ + bool name##MatcherP2::gmock_Impl::MatchAndExplain( \ + arg_type arg, ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P3(name, p0, p1, p2, description) \ + template \ + class name##MatcherP3 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1, p2))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2)); \ + } \ + name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP3); \ + }; \ + template \ + inline name##MatcherP3 name(p0##_type p0, p1##_type p1, p2##_type p2) { \ + return name##MatcherP3(p0, p1, p2); \ + } \ + template \ + template \ + bool name##MatcherP3::gmock_Impl::MatchAndExplain( \ + arg_type arg, ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P4(name, p0, p1, p2, p3, description) \ + template \ + class name##MatcherP4 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1, p2, p3))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2, p3)); \ + } \ + name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP4); \ + }; \ + template \ + inline name##MatcherP4 name(p0##_type p0, p1##_type p1, p2##_type p2, \ + p3##_type p3) { \ + return name##MatcherP4(p0, p1, p2, p3); \ + } \ + template \ + template \ + bool name##MatcherP4::gmock_Impl::MatchAndExplain( \ + arg_type arg, ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P5(name, p0, p1, p2, p3, p4, description) \ + template \ + class name##MatcherP5 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1, p2, p3, p4))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2, p3, p4)); \ + } \ + name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP5); \ + }; \ + template \ + inline name##MatcherP5 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4) { \ + return name##MatcherP5(p0, p1, p2, p3, p4); \ + } \ + template \ + template \ + bool name##MatcherP5::gmock_Impl::MatchAndExplain( \ + arg_type arg, ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \ + template \ + class name##MatcherP6 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1, p2, p3, p4, \ + p5))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2, p3, p4, p5)); \ + } \ + name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4, p5##_type gmock_p5) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP6); \ + }; \ + template \ + inline name##MatcherP6 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5) { \ + return name##MatcherP6(p0, p1, p2, p3, p4, p5); \ + } \ + template \ + template \ + bool name##MatcherP6::gmock_Impl< \ + arg_type>::MatchAndExplain(arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \ + template \ + class name##MatcherP7 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple( \ + p0, p1, p2, p3, p4, p5, p6))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6)); \ + } \ + name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4, p5##_type gmock_p5, p6##_type gmock_p6) \ + : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP7); \ + }; \ + template \ + inline name##MatcherP7 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6) { \ + return name##MatcherP7( \ + p0, p1, p2, p3, p4, p5, p6); \ + } \ + template \ + template \ + bool name##MatcherP7::gmock_Impl< \ + arg_type>::MatchAndExplain(arg_type arg, \ + ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \ + template \ + class name##MatcherP8 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1, p2, p3, p4, p5, p6, p7))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7)); \ + } \ + name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4, p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP8); \ + }; \ + template \ + inline name##MatcherP8 name( \ + p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, \ + p7##_type p7) { \ + return name##MatcherP8( \ + p0, p1, p2, p3, p4, p5, p6, p7); \ + } \ + template \ + template \ + bool name##MatcherP8:: \ + gmock_Impl::MatchAndExplain( \ + arg_type arg, ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) const + +#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \ + template \ + class name##MatcherP9 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8)); \ + } \ + name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4, p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP9); \ + }; \ + template \ + inline name##MatcherP9 \ + name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8) { \ + return name##MatcherP9(p0, p1, p2, p3, p4, p5, p6, p7, p8); \ + } \ + template \ + template \ + bool name##MatcherP9::gmock_Impl::MatchAndExplain(arg_type arg, \ + ::testing::MatchResultListener* \ + result_listener GTEST_ATTRIBUTE_UNUSED_) \ + const + +#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \ + template \ + class name##MatcherP10 { \ + public: \ + template \ + class gmock_Impl : public ::testing::MatcherInterface { \ + public: \ + gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ + p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, p9##_type gmock_p9) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8), \ + p9(gmock_p9) {} \ + virtual bool MatchAndExplain(arg_type arg, ::testing::MatchResultListener* result_listener) const; \ + virtual void DescribeTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(false); } \ + virtual void DescribeNegationTo(::std::ostream* gmock_os) const { *gmock_os << FormatDescription(true); } \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + p9##_type p9; \ + \ + private: \ + ::testing::internal::string FormatDescription(bool negation) const { \ + const ::testing::internal::string gmock_description = (description); \ + if (!gmock_description.empty()) return gmock_description; \ + return ::testing::internal::FormatMatcherDescription( \ + negation, #name, \ + ::testing::internal::UniversalTersePrintTupleFieldsToStrings( \ + ::testing::tuple(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))); \ + } \ + GTEST_DISALLOW_ASSIGN_(gmock_Impl); \ + }; \ + template \ + operator ::testing::Matcher() const { \ + return ::testing::Matcher(new gmock_Impl(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)); \ + } \ + name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, p3##_type gmock_p3, \ + p4##_type gmock_p4, p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ + p8##_type gmock_p8, p9##_type gmock_p9) \ + : p0(gmock_p0), \ + p1(gmock_p1), \ + p2(gmock_p2), \ + p3(gmock_p3), \ + p4(gmock_p4), \ + p5(gmock_p5), \ + p6(gmock_p6), \ + p7(gmock_p7), \ + p8(gmock_p8), \ + p9(gmock_p9) {} \ + p0##_type p0; \ + p1##_type p1; \ + p2##_type p2; \ + p3##_type p3; \ + p4##_type p4; \ + p5##_type p5; \ + p6##_type p6; \ + p7##_type p7; \ + p8##_type p8; \ + p9##_type p9; \ + \ + private: \ + GTEST_DISALLOW_ASSIGN_(name##MatcherP10); \ + }; \ + template \ + inline name##MatcherP10 \ + name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ + p8##_type p8, p9##_type p9) { \ + return name##MatcherP10(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); \ + } \ + template \ + template \ + bool name##MatcherP10::gmock_Impl::MatchAndExplain(arg_type arg, \ + ::testing::MatchResultListener* \ + result_listener \ + GTEST_ATTRIBUTE_UNUSED_) \ + const #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ diff --git a/src/net/test/gmock/include/gmock/gmock-generated-nice-strict.h b/src/net/test/gmock/include/gmock/gmock-generated-nice-strict.h index 4095f4d5bc..eb2193278f 100644 --- a/src/net/test/gmock/include/gmock/gmock-generated-nice-strict.h +++ b/src/net/test/gmock/include/gmock/gmock-generated-nice-strict.h @@ -81,92 +81,70 @@ class NiceMock : public MockClass { public: // We don't factor out the constructor body to a common method, as // we have to avoid a possible clash with members of MockClass. - NiceMock() { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); - } + NiceMock() { ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } // C++ doesn't (yet) allow inheritance of constructors, so we have // to define it for each arity. template explicit NiceMock(const A1& a1) : MockClass(a1) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } template NiceMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } template NiceMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } template - NiceMock(const A1& a1, const A2& a2, const A3& a3, - const A4& a4) : MockClass(a1, a2, a3, a4) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4) : MockClass(a1, a2, a3, a4) { + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5) : MockClass(a1, a2, a3, a4, a5) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) : MockClass(a1, a2, a3, a4, a5) { + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + template + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) + : MockClass(a1, a2, a3, a4, a5, a6) { + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, - a6, a7) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + template + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) + : MockClass(a1, a2, a3, a4, a5, a6, a7) { + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, - a2, a3, a4, a5, a6, a7, a8) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + template + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8) { + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, - const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + template + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8, const A9& a9) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } - template - NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, - const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - ::testing::Mock::AllowUninterestingCalls( - internal::ImplicitCast_(this)); + template + NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8, const A9& a9, const A10& a10) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { + ::testing::Mock::AllowUninterestingCalls(internal::ImplicitCast_(this)); } - virtual ~NiceMock() { - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } + virtual ~NiceMock() { ::testing::Mock::UnregisterCallReaction(internal::ImplicitCast_(this)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); @@ -177,92 +155,70 @@ class NaggyMock : public MockClass { public: // We don't factor out the constructor body to a common method, as // we have to avoid a possible clash with members of MockClass. - NaggyMock() { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); - } + NaggyMock() { ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } // C++ doesn't (yet) allow inheritance of constructors, so we have // to define it for each arity. template explicit NaggyMock(const A1& a1) : MockClass(a1) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } template NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } template NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, - const A4& a4) : MockClass(a1, a2, a3, a4) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4) : MockClass(a1, a2, a3, a4) { + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5) : MockClass(a1, a2, a3, a4, a5) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) : MockClass(a1, a2, a3, a4, a5) { + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + template + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) + : MockClass(a1, a2, a3, a4, a5, a6) { + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, - a6, a7) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + template + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) + : MockClass(a1, a2, a3, a4, a5, a6, a7) { + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, - a2, a3, a4, a5, a6, a7, a8) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + template + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8) { + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, - const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + template + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8, const A9& a9) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } - template - NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, - const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - ::testing::Mock::WarnUninterestingCalls( - internal::ImplicitCast_(this)); + template + NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8, const A9& a9, const A10& a10) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { + ::testing::Mock::WarnUninterestingCalls(internal::ImplicitCast_(this)); } - virtual ~NaggyMock() { - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } + virtual ~NaggyMock() { ::testing::Mock::UnregisterCallReaction(internal::ImplicitCast_(this)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); @@ -273,92 +229,70 @@ class StrictMock : public MockClass { public: // We don't factor out the constructor body to a common method, as // we have to avoid a possible clash with members of MockClass. - StrictMock() { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); - } + StrictMock() { ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } // C++ doesn't (yet) allow inheritance of constructors, so we have // to define it for each arity. template explicit StrictMock(const A1& a1) : MockClass(a1) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } template StrictMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } template StrictMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } template - StrictMock(const A1& a1, const A2& a2, const A3& a3, - const A4& a4) : MockClass(a1, a2, a3, a4) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4) : MockClass(a1, a2, a3, a4) { + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5) : MockClass(a1, a2, a3, a4, a5) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) : MockClass(a1, a2, a3, a4, a5) { + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + template + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) + : MockClass(a1, a2, a3, a4, a5, a6) { + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, - a6, a7) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + template + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) + : MockClass(a1, a2, a3, a4, a5, a6, a7) { + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, - a2, a3, a4, a5, a6, a7, a8) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + template + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8) { + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, - const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + template + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8, const A9& a9) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } - template - StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, - const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, - const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { - ::testing::Mock::FailUninterestingCalls( - internal::ImplicitCast_(this)); + template + StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, + const A8& a8, const A9& a9, const A10& a10) + : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { + ::testing::Mock::FailUninterestingCalls(internal::ImplicitCast_(this)); } - virtual ~StrictMock() { - ::testing::Mock::UnregisterCallReaction( - internal::ImplicitCast_(this)); - } + virtual ~StrictMock() { ::testing::Mock::UnregisterCallReaction(internal::ImplicitCast_(this)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); diff --git a/src/net/test/gmock/include/gmock/gmock-matchers.h b/src/net/test/gmock/include/gmock/gmock-matchers.h index 33b37a7a5d..267eddb2a1 100644 --- a/src/net/test/gmock/include/gmock/gmock-matchers.h +++ b/src/net/test/gmock/include/gmock/gmock-matchers.h @@ -53,7 +53,7 @@ #include "gtest/gtest.h" #if GTEST_HAS_STD_INITIALIZER_LIST_ -# include // NOLINT -- must be after gtest.h +# include // NOLINT -- must be after gtest.h #endif namespace testing { @@ -89,8 +89,7 @@ class MatchResultListener { // is NULL. template MatchResultListener& operator<<(const T& x) { - if (stream_ != NULL) - *stream_ << x; + if (stream_ != NULL) *stream_ << x; return *this; } @@ -109,8 +108,7 @@ class MatchResultListener { GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); }; -inline MatchResultListener::~MatchResultListener() { -} +inline MatchResultListener::~MatchResultListener() {} // An instance of a subclass of this knows how to describe itself as a // matcher. @@ -201,27 +199,39 @@ namespace internal { struct AnyEq { template - bool operator()(const A& a, const B& b) const { return a == b; } + bool operator()(const A& a, const B& b) const { + return a == b; + } }; struct AnyNe { template - bool operator()(const A& a, const B& b) const { return a != b; } + bool operator()(const A& a, const B& b) const { + return a != b; + } }; struct AnyLt { template - bool operator()(const A& a, const B& b) const { return a < b; } + bool operator()(const A& a, const B& b) const { + return a < b; + } }; struct AnyGt { template - bool operator()(const A& a, const B& b) const { return a > b; } + bool operator()(const A& a, const B& b) const { + return a > b; + } }; struct AnyLe { template - bool operator()(const A& a, const B& b) const { return a <= b; } + bool operator()(const A& a, const B& b) const { + return a <= b; + } }; struct AnyGe { template - bool operator()(const A& a, const B& b) const { return a >= b; } + bool operator()(const A& a, const B& b) const { + return a >= b; + } }; // A match result listener that ignores the explanation. @@ -238,8 +248,7 @@ class DummyMatchResultListener : public MatchResultListener { // that the former is concrete. class StreamMatchResultListener : public MatchResultListener { public: - explicit StreamMatchResultListener(::std::ostream* os) - : MatchResultListener(os) {} + explicit StreamMatchResultListener(::std::ostream* os) : MatchResultListener(os) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); @@ -253,9 +262,7 @@ class MatcherBase { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener'. - bool MatchAndExplain(T x, MatchResultListener* listener) const { - return impl_->MatchAndExplain(x, listener); - } + bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } // Returns true iff this matcher matches x. bool Matches(T x) const { @@ -267,9 +274,7 @@ class MatcherBase { void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } // Describes the negation of this matcher to an ostream. - void DescribeNegationTo(::std::ostream* os) const { - impl_->DescribeNegationTo(os); - } + void DescribeNegationTo(::std::ostream* os) const { impl_->DescribeNegationTo(os); } // Explains why x matches, or doesn't match, the matcher. void ExplainMatchResultTo(T x, ::std::ostream* os) const { @@ -280,16 +285,13 @@ class MatcherBase { // Returns the describer for this matcher object; retains ownership // of the describer, which is only guaranteed to be alive when // this matcher object is alive. - const MatcherDescriberInterface* GetDescriber() const { - return impl_.get(); - } + const MatcherDescriberInterface* GetDescriber() const { return impl_.get(); } protected: MatcherBase() {} // Constructs a matcher from its implementation. - explicit MatcherBase(const MatcherInterface* impl) - : impl_(impl) {} + explicit MatcherBase(const MatcherInterface* impl) : impl_(impl) {} virtual ~MatcherBase() {} @@ -324,8 +326,7 @@ class Matcher : public internal::MatcherBase { explicit Matcher() {} // NOLINT // Constructs a matcher from its implementation. - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} // Implicit constructor here allows people to write // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes @@ -336,8 +337,7 @@ class Matcher : public internal::MatcherBase { // instead of Eq(str) and "foo" instead of Eq("foo") when a string // matcher is expected. template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher : public internal::MatcherBase { public: Matcher() {} @@ -353,13 +353,11 @@ class GTEST_API_ Matcher }; template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher : public internal::MatcherBase { public: Matcher() {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. @@ -374,8 +372,7 @@ class GTEST_API_ Matcher // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece // matcher is expected. template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher : public internal::MatcherBase { public: Matcher() {} @@ -394,13 +391,11 @@ class GTEST_API_ Matcher }; template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { +class GTEST_API_ Matcher : public internal::MatcherBase { public: Matcher() {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} + explicit Matcher(const MatcherInterface* impl) : internal::MatcherBase(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. @@ -450,13 +445,9 @@ class PolymorphicMatcher { public: explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} - virtual void DescribeTo(::std::ostream* os) const { - impl_.DescribeTo(os); - } + virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } - virtual void DescribeNegationTo(::std::ostream* os) const { - impl_.DescribeNegationTo(os); - } + virtual void DescribeNegationTo(::std::ostream* os) const { impl_.DescribeNegationTo(os); } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_.MatchAndExplain(x, listener); @@ -528,10 +519,8 @@ class MatcherCastImpl { // polymorphic_matcher_or_value to Matcher because it won't trigger // a user-defined conversion from M to T if one exists (assuming M is // a value). - return CastImpl( - polymorphic_matcher_or_value, - BooleanConstant< - internal::ImplicitlyConvertible >::value>()); + return CastImpl(polymorphic_matcher_or_value, + BooleanConstant >::value>()); } private: @@ -542,8 +531,7 @@ class MatcherCastImpl { return Matcher(ImplicitCast_(value)); } - static Matcher CastImpl(const M& polymorphic_matcher_or_value, - BooleanConstant) { + static Matcher CastImpl(const M& polymorphic_matcher_or_value, BooleanConstant) { // M is implicitly convertible to Matcher, which means that either // M is a polymorhpic matcher or Matcher has an implicit constructor // from M. In both cases using the implicit conversion will produce a @@ -562,28 +550,21 @@ class MatcherCastImpl { template class MatcherCastImpl > { public: - static Matcher Cast(const Matcher& source_matcher) { - return Matcher(new Impl(source_matcher)); - } + static Matcher Cast(const Matcher& source_matcher) { return Matcher(new Impl(source_matcher)); } private: class Impl : public MatcherInterface { public: - explicit Impl(const Matcher& source_matcher) - : source_matcher_(source_matcher) {} + explicit Impl(const Matcher& source_matcher) : source_matcher_(source_matcher) {} // We delegate the matching logic to the source matcher. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return source_matcher_.MatchAndExplain(static_cast(x), listener); } - virtual void DescribeTo(::std::ostream* os) const { - source_matcher_.DescribeTo(os); - } + virtual void DescribeTo(::std::ostream* os) const { source_matcher_.DescribeTo(os); } - virtual void DescribeNegationTo(::std::ostream* os) const { - source_matcher_.DescribeNegationTo(os); - } + virtual void DescribeNegationTo(::std::ostream* os) const { source_matcher_.DescribeNegationTo(os); } private: const Matcher source_matcher_; @@ -640,23 +621,19 @@ class SafeMatcherCastImpl { template static inline Matcher Cast(const Matcher& matcher) { // Enforce that T can be implicitly converted to U. - GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible::value), - T_must_be_implicitly_convertible_to_U); + GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible::value), T_must_be_implicitly_convertible_to_U); // Enforce that we are not converting a non-reference type T to a reference // type U. - GTEST_COMPILE_ASSERT_( - internal::is_reference::value || !internal::is_reference::value, - cannot_convert_non_referentce_arg_to_reference); + GTEST_COMPILE_ASSERT_(internal::is_reference::value || !internal::is_reference::value, + cannot_convert_non_referentce_arg_to_reference); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; - GTEST_COMPILE_ASSERT_( - kTIsOther || kUIsOther || - (internal::LosslessArithmeticConvertible::value), - conversion_of_arithmetic_types_must_be_lossless); + GTEST_COMPILE_ASSERT_(kTIsOther || kUIsOther || (internal::LosslessArithmeticConvertible::value), + conversion_of_arithmetic_types_must_be_lossless); return MatcherCast(matcher); } }; @@ -675,8 +652,7 @@ Matcher A(); namespace internal { // If the explanation is not empty, prints it to the ostream. -inline void PrintIfNotEmpty(const internal::string& explanation, - ::std::ostream* os) { +inline void PrintIfNotEmpty(const internal::string& explanation, ::std::ostream* os) { if (explanation != "" && os != NULL) { *os << ", " << explanation; } @@ -688,8 +664,7 @@ inline void PrintIfNotEmpty(const internal::string& explanation, inline bool IsReadableTypeName(const string& type_name) { // We consider a type name readable if it's short or doesn't contain // a template or function type. - return (type_name.length() <= 20 || - type_name.find_first_of("<(") == string::npos); + return (type_name.length() <= 20 || type_name.find_first_of("<(") == string::npos); } // Matches the value against the given matcher, prints the value and explains @@ -698,8 +673,7 @@ inline bool IsReadableTypeName(const string& type_name) { // Value cannot be passed by const reference, because some matchers take a // non-const argument. template -bool MatchPrintAndExplain(Value& value, const Matcher& matcher, - MatchResultListener* listener) { +bool MatchPrintAndExplain(Value& value, const Matcher& matcher, MatchResultListener* listener) { if (!listener->IsInterested()) { // If the listener is not interested, we do not need to construct the // inner explanation. @@ -712,8 +686,7 @@ bool MatchPrintAndExplain(Value& value, const Matcher& matcher, UniversalPrint(value, listener->stream()); #if GTEST_HAS_RTTI const string& type_name = GetTypeName(); - if (IsReadableTypeName(type_name)) - *listener->stream() << " (of type " << type_name << ")"; + if (IsReadableTypeName(type_name)) *listener->stream() << " (of type " << type_name << ")"; #endif PrintIfNotEmpty(inner_listener.str(), listener->stream()); @@ -729,10 +702,9 @@ class TuplePrefix { // iff the first N fields of matcher_tuple matches the first N // fields of value_tuple, respectively. template - static bool Matches(const MatcherTuple& matcher_tuple, - const ValueTuple& value_tuple) { - return TuplePrefix::Matches(matcher_tuple, value_tuple) - && get(matcher_tuple).Matches(get(value_tuple)); + static bool Matches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { + return TuplePrefix::Matches(matcher_tuple, value_tuple) && + get(matcher_tuple).Matches(get(value_tuple)); } // TuplePrefix::ExplainMatchFailuresTo(matchers, values, os) @@ -740,16 +712,13 @@ class TuplePrefix { // against the first N fields of values. If there is no failure, // nothing will be streamed to os. template - static void ExplainMatchFailuresTo(const MatcherTuple& matchers, - const ValueTuple& values, - ::std::ostream* os) { + static void ExplainMatchFailuresTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { // First, describes failures in the first N - 1 fields. TuplePrefix::ExplainMatchFailuresTo(matchers, values, os); // Then describes the failure (if any) in the (N - 1)-th (0-based) // field. - typename tuple_element::type matcher = - get(matchers); + typename tuple_element::type matcher = get(matchers); typedef typename tuple_element::type Value; Value value = get(values); StringMatchResultListener listener; @@ -776,14 +745,12 @@ template <> class TuplePrefix<0> { public: template - static bool Matches(const MatcherTuple& /* matcher_tuple */, - const ValueTuple& /* value_tuple */) { + static bool Matches(const MatcherTuple& /* matcher_tuple */, const ValueTuple& /* value_tuple */) { return true; } template - static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, - const ValueTuple& /* values */, + static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, const ValueTuple& /* values */, ::std::ostream* /* os */) {} }; @@ -793,25 +760,19 @@ class TuplePrefix<0> { // value_tuple have different number of fields or incompatible field // types. template -bool TupleMatches(const MatcherTuple& matcher_tuple, - const ValueTuple& value_tuple) { +bool TupleMatches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { // Makes sure that matcher_tuple and value_tuple have the same // number of fields. - GTEST_COMPILE_ASSERT_(tuple_size::value == - tuple_size::value, + GTEST_COMPILE_ASSERT_(tuple_size::value == tuple_size::value, matcher_and_value_have_different_numbers_of_fields); - return TuplePrefix::value>:: - Matches(matcher_tuple, value_tuple); + return TuplePrefix::value>::Matches(matcher_tuple, value_tuple); } // Describes failures in matching matchers against values. If there // is no failure, nothing will be streamed to os. template -void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, - const ValueTuple& values, - ::std::ostream* os) { - TuplePrefix::value>::ExplainMatchFailuresTo( - matchers, values, os); +void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { + TuplePrefix::value>::ExplainMatchFailuresTo(matchers, values, os); } // TransformTupleValues and its helper. @@ -833,16 +794,14 @@ class TransformTupleValuesHelper { private: template struct IterateOverTuple { - OutIter operator() (Func f, const Tup& t, OutIter out) const { + OutIter operator()(Func f, const Tup& t, OutIter out) const { *out++ = f(::testing::get(t)); return IterateOverTuple()(f, t, out); } }; template struct IterateOverTuple { - OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const { - return out; - } + OutIter operator()(Func /* f */, const Tup& /* t */, OutIter out) const { return out; } }; }; @@ -858,8 +817,7 @@ OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { template class AnyMatcherImpl : public MatcherInterface { public: - virtual bool MatchAndExplain( - T /* x */, MatchResultListener* /* listener */) const { return true; } + virtual bool MatchAndExplain(T /* x */, MatchResultListener* /* listener */) const { return true; } virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; } virtual void DescribeNegationTo(::std::ostream* os) const { // This is mostly for completeness' safe, as it's not very useful @@ -876,7 +834,9 @@ class AnyMatcherImpl : public MatcherInterface { class AnythingMatcher { public: template - operator Matcher() const { return A(); } + operator Matcher() const { + return A(); + } }; // Implements a matcher that compares a given value with a @@ -903,18 +863,16 @@ class ComparisonBase { class Impl : public MatcherInterface { public: explicit Impl(const Rhs& rhs) : rhs_(rhs) {} - virtual bool MatchAndExplain( - Lhs lhs, MatchResultListener* /* listener */) const { - return Op()(lhs, rhs_); - } + virtual bool MatchAndExplain(Lhs lhs, MatchResultListener* /* listener */) const { return Op()(lhs, rhs_); } virtual void DescribeTo(::std::ostream* os) const { *os << D::Desc() << " "; UniversalPrint(rhs_, os); } virtual void DescribeNegationTo(::std::ostream* os) const { - *os << D::NegatedDesc() << " "; + *os << D::NegatedDesc() << " "; UniversalPrint(rhs_, os); } + private: Rhs rhs_; GTEST_DISALLOW_ASSIGN_(Impl); @@ -926,48 +884,42 @@ class ComparisonBase { template class EqMatcher : public ComparisonBase, Rhs, AnyEq> { public: - explicit EqMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyEq>(rhs) { } + explicit EqMatcher(const Rhs& rhs) : ComparisonBase, Rhs, AnyEq>(rhs) {} static const char* Desc() { return "is equal to"; } static const char* NegatedDesc() { return "isn't equal to"; } }; template class NeMatcher : public ComparisonBase, Rhs, AnyNe> { public: - explicit NeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyNe>(rhs) { } + explicit NeMatcher(const Rhs& rhs) : ComparisonBase, Rhs, AnyNe>(rhs) {} static const char* Desc() { return "isn't equal to"; } static const char* NegatedDesc() { return "is equal to"; } }; template class LtMatcher : public ComparisonBase, Rhs, AnyLt> { public: - explicit LtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLt>(rhs) { } + explicit LtMatcher(const Rhs& rhs) : ComparisonBase, Rhs, AnyLt>(rhs) {} static const char* Desc() { return "is <"; } static const char* NegatedDesc() { return "isn't <"; } }; template class GtMatcher : public ComparisonBase, Rhs, AnyGt> { public: - explicit GtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGt>(rhs) { } + explicit GtMatcher(const Rhs& rhs) : ComparisonBase, Rhs, AnyGt>(rhs) {} static const char* Desc() { return "is >"; } static const char* NegatedDesc() { return "isn't >"; } }; template class LeMatcher : public ComparisonBase, Rhs, AnyLe> { public: - explicit LeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLe>(rhs) { } + explicit LeMatcher(const Rhs& rhs) : ComparisonBase, Rhs, AnyLe>(rhs) {} static const char* Desc() { return "is <="; } static const char* NegatedDesc() { return "isn't <="; } }; template class GeMatcher : public ComparisonBase, Rhs, AnyGe> { public: - explicit GeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGe>(rhs) { } + explicit GeMatcher(const Rhs& rhs) : ComparisonBase, Rhs, AnyGe>(rhs) {} static const char* Desc() { return "is >="; } static const char* NegatedDesc() { return "isn't >="; } }; @@ -977,19 +929,16 @@ class GeMatcher : public ComparisonBase, Rhs, AnyGe> { class IsNullMatcher { public: template - bool MatchAndExplain(const Pointer& p, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { #if GTEST_LANG_CXX11 return p == nullptr; -#else // GTEST_LANG_CXX11 +#else // GTEST_LANG_CXX11 return GetRawPointer(p) == NULL; #endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "isn't NULL"; - } + void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; } }; // Implements the polymorphic NotNull() matcher, which matches any raw or smart @@ -997,19 +946,16 @@ class IsNullMatcher { class NotNullMatcher { public: template - bool MatchAndExplain(const Pointer& p, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { #if GTEST_LANG_CXX11 return p != nullptr; -#else // GTEST_LANG_CXX11 +#else // GTEST_LANG_CXX11 return GetRawPointer(p) != NULL; #endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "is NULL"; - } + void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } }; // Ref(variable) matches any argument that is a reference to @@ -1059,8 +1005,7 @@ class RefMatcher { // MatchAndExplain() takes a Super& (as opposed to const Super&) // in order to match the interface MatcherInterface. - virtual bool MatchAndExplain( - Super& x, MatchResultListener* listener) const { + virtual bool MatchAndExplain(Super& x, MatchResultListener* listener) const { *listener << "which is located @" << static_cast(&x); return &x == &object_; } @@ -1091,16 +1036,14 @@ inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { return String::CaseInsensitiveCStringEquals(lhs, rhs); } -inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, - const wchar_t* rhs) { +inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { return String::CaseInsensitiveWideCStringEquals(lhs, rhs); } // String comparison for narrow or wide strings that can have embedded NUL // characters. template -bool CaseInsensitiveStringEquals(const StringType& s1, - const StringType& s2) { +bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) { // Are the heads equal? if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { return false; @@ -1125,8 +1068,7 @@ bool CaseInsensitiveStringEquals(const StringType& s1, template class StrEqualityMatcher { public: - StrEqualityMatcher(const StringType& str, bool expect_eq, - bool case_sensitive) + StrEqualityMatcher(const StringType& str, bool expect_eq, bool case_sensitive) : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} // Accepts pointer types, particularly: @@ -1147,21 +1089,15 @@ class StrEqualityMatcher { // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); - const bool eq = case_sensitive_ ? s2 == string_ : - CaseInsensitiveStringEquals(s2, string_); + const bool eq = case_sensitive_ ? s2 == string_ : CaseInsensitiveStringEquals(s2, string_); return expect_eq_ == eq; } - void DescribeTo(::std::ostream* os) const { - DescribeToHelper(expect_eq_, os); - } + void DescribeTo(::std::ostream* os) const { DescribeToHelper(expect_eq_, os); } - void DescribeNegationTo(::std::ostream* os) const { - DescribeToHelper(!expect_eq_, os); - } + void DescribeNegationTo(::std::ostream* os) const { DescribeToHelper(!expect_eq_, os); } private: void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { @@ -1186,8 +1122,7 @@ class StrEqualityMatcher { template class HasSubstrMatcher { public: - explicit HasSubstrMatcher(const StringType& substring) - : substring_(substring) {} + explicit HasSubstrMatcher(const StringType& substring) : substring_(substring) {} // Accepts pointer types, particularly: // const char* @@ -1204,8 +1139,7 @@ class HasSubstrMatcher { // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.find(substring_) != StringType::npos; } @@ -1233,8 +1167,7 @@ class HasSubstrMatcher { template class StartsWithMatcher { public: - explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { - } + explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {} // Accepts pointer types, particularly: // const char* @@ -1251,11 +1184,9 @@ class StartsWithMatcher { // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); - return s2.length() >= prefix_.length() && - s2.substr(0, prefix_.length()) == prefix_; + return s2.length() >= prefix_.length() && s2.substr(0, prefix_.length()) == prefix_; } void DescribeTo(::std::ostream* os) const { @@ -1297,11 +1228,9 @@ class EndsWithMatcher { // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); - return s2.length() >= suffix_.length() && - s2.substr(s2.length() - suffix_.length()) == suffix_; + return s2.length() >= suffix_.length() && s2.substr(s2.length() - suffix_.length()) == suffix_; } void DescribeTo(::std::ostream* os) const { @@ -1325,8 +1254,7 @@ class EndsWithMatcher { // T can be converted to a string. class MatchesRegexMatcher { public: - MatchesRegexMatcher(const RE* regex, bool full_match) - : regex_(regex), full_match_(full_match) {} + MatchesRegexMatcher(const RE* regex, bool full_match) : regex_(regex), full_match_(full_match) {} // Accepts pointer types, particularly: // const char* @@ -1343,22 +1271,18 @@ class MatchesRegexMatcher { // This is a template, not just a plain function with const internal::string&, // because StringPiece has some interfering non-explicit constructors. template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { + bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const internal::string& s2(s); - return full_match_ ? RE::FullMatch(s2, *regex_) : - RE::PartialMatch(s2, *regex_); + return full_match_ ? RE::FullMatch(s2, *regex_) : RE::PartialMatch(s2, *regex_); } void DescribeTo(::std::ostream* os) const { - *os << (full_match_ ? "matches" : "contains") - << " regular expression "; + *os << (full_match_ ? "matches" : "contains") << " regular expression "; UniversalPrinter::Print(regex_->pattern(), os); } void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't " << (full_match_ ? "match" : "contain") - << " regular expression "; + *os << "doesn't " << (full_match_ ? "match" : "contain") << " regular expression "; UniversalPrinter::Print(regex_->pattern(), os); } @@ -1397,17 +1321,11 @@ class PairMatchBase { template class Impl : public MatcherInterface { public: - virtual bool MatchAndExplain( - Tuple args, - MatchResultListener* /* listener */) const { + virtual bool MatchAndExplain(Tuple args, MatchResultListener* /* listener */) const { return Op()(::testing::get<0>(args), ::testing::get<1>(args)); } - virtual void DescribeTo(::std::ostream* os) const { - *os << "are " << GetDesc; - } - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "aren't " << GetDesc; - } + virtual void DescribeTo(::std::ostream* os) const { *os << "are " << GetDesc; } + virtual void DescribeNegationTo(::std::ostream* os) const { *os << "aren't " << GetDesc; } }; }; @@ -1443,20 +1361,15 @@ class Ge2Matcher : public PairMatchBase { template class NotMatcherImpl : public MatcherInterface { public: - explicit NotMatcherImpl(const Matcher& matcher) - : matcher_(matcher) {} + explicit NotMatcherImpl(const Matcher& matcher) : matcher_(matcher) {} virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return !matcher_.MatchAndExplain(x, listener); } - virtual void DescribeTo(::std::ostream* os) const { - matcher_.DescribeNegationTo(os); - } + virtual void DescribeTo(::std::ostream* os) const { matcher_.DescribeNegationTo(os); } - virtual void DescribeNegationTo(::std::ostream* os) const { - matcher_.DescribeTo(os); - } + virtual void DescribeNegationTo(::std::ostream* os) const { matcher_.DescribeTo(os); } private: const Matcher matcher_; @@ -1574,10 +1487,9 @@ struct MatcherList { // constructor taking two Matchers as input. template class CombiningMatcher> static Matcher CreateMatcher(const ListType& matchers) { - return Matcher(new CombiningMatcher( - SafeMatcherCast(matchers.first), - MatcherListTail::template CreateMatcher( - matchers.second))); + return Matcher( + new CombiningMatcher(SafeMatcherCast(matchers.first), + MatcherListTail::template CreateMatcher(matchers.second))); } }; @@ -1587,16 +1499,13 @@ template struct MatcherList<2, Matcher1, Matcher2> { typedef ::std::pair ListType; - static ListType BuildList(const Matcher1& matcher1, - const Matcher2& matcher2) { + static ListType BuildList(const Matcher1& matcher1, const Matcher2& matcher2) { return ::std::pair(matcher1, matcher2); } template class CombiningMatcher> static Matcher CreateMatcher(const ListType& matchers) { - return Matcher(new CombiningMatcher( - SafeMatcherCast(matchers.first), - SafeMatcherCast(matchers.second))); + return Matcher(new CombiningMatcher(SafeMatcherCast(matchers.first), SafeMatcherCast(matchers.second))); } }; @@ -1615,8 +1524,7 @@ class VariadicMatcher { // all of the provided matchers (Matcher1, Matcher2, ...) can match. template operator Matcher() const { - return MatcherListType::template CreateMatcher( - matchers_); + return MatcherListType::template CreateMatcher(matchers_); } private: @@ -1637,16 +1545,14 @@ using AllOfMatcher = VariadicMatcher; template class BothOfMatcher { public: - BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} + BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // BothOfMatcher object to match any type that // both Matcher1 and Matcher2 can match. template operator Matcher() const { - return Matcher(new BothOfMatcherImpl(SafeMatcherCast(matcher1_), - SafeMatcherCast(matcher2_))); + return Matcher(new BothOfMatcherImpl(SafeMatcherCast(matcher1_), SafeMatcherCast(matcher2_))); } private: @@ -1732,16 +1638,14 @@ using AnyOfMatcher = VariadicMatcher; template class EitherOfMatcher { public: - EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2) - : matcher1_(matcher1), matcher2_(matcher2) {} + EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // EitherOfMatcher object to match any type that // both Matcher1 and Matcher2 can match. template operator Matcher() const { - return Matcher(new EitherOfMatcherImpl( - SafeMatcherCast(matcher1_), SafeMatcherCast(matcher2_))); + return Matcher(new EitherOfMatcherImpl(SafeMatcherCast(matcher1_), SafeMatcherCast(matcher2_))); } private: @@ -1771,18 +1675,13 @@ class TrulyMatcher { // We cannot write 'return !!predicate_(x);' as that doesn't work // when predicate_(x) returns a class convertible to bool but // having no operator!(). - if (predicate_(x)) - return true; + if (predicate_(x)) return true; return false; } - void DescribeTo(::std::ostream* os) const { - *os << "satisfies the given predicate"; - } + void DescribeTo(::std::ostream* os) const { *os << "satisfies the given predicate"; } - void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't satisfy the given predicate"; - } + void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't satisfy the given predicate"; } private: Predicate predicate_; @@ -1853,8 +1752,7 @@ class PredicateFormatterFromMatcher { // potentially unsafe downcasting of the matcher argument. const Matcher matcher = SafeMatcherCast(matcher_); StringMatchResultListener listener; - if (MatchPrintAndExplain(x, matcher, &listener)) - return AssertionSuccess(); + if (MatchPrintAndExplain(x, matcher, &listener)) return AssertionSuccess(); ::std::stringstream ss; ss << "Value of: " << value_text << "\n" @@ -1875,8 +1773,7 @@ class PredicateFormatterFromMatcher { // used for implementing ASSERT_THAT() and EXPECT_THAT(). // Implementation detail: 'matcher' is received by-value to force decaying. template -inline PredicateFormatterFromMatcher -MakePredicateFormatterFromMatcher(M matcher) { +inline PredicateFormatterFromMatcher MakePredicateFormatterFromMatcher(M matcher) { return PredicateFormatterFromMatcher(internal::move(matcher)); } @@ -1893,20 +1790,15 @@ class FloatingEqMatcher { // equality comparisons between NANs will always return false. We specify a // negative max_abs_error_ term to indicate that ULP-based approximation will // be used for comparison. - FloatingEqMatcher(FloatType expected, bool nan_eq_nan) : - expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) { - } + FloatingEqMatcher(FloatType expected, bool nan_eq_nan) + : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {} // Constructor that supports a user-specified max_abs_error that will be used // for comparison instead of ULP-based approximation. The max absolute // should be non-negative. - FloatingEqMatcher(FloatType expected, bool nan_eq_nan, - FloatType max_abs_error) - : expected_(expected), - nan_eq_nan_(nan_eq_nan), - max_abs_error_(max_abs_error) { - GTEST_CHECK_(max_abs_error >= 0) - << ", where max_abs_error is" << max_abs_error; + FloatingEqMatcher(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) + : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) { + GTEST_CHECK_(max_abs_error >= 0) << ", where max_abs_error is" << max_abs_error; } // Implements floating point equality matcher as a Matcher. @@ -1914,12 +1806,9 @@ class FloatingEqMatcher { class Impl : public MatcherInterface { public: Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) - : expected_(expected), - nan_eq_nan_(nan_eq_nan), - max_abs_error_(max_abs_error) {} + : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {} - virtual bool MatchAndExplain(T value, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(T value, MatchResultListener* listener) const { const FloatingPoint actual(value), expected(expected_); // Compares NaNs first, if nan_eq_nan_ is true. @@ -1957,8 +1846,7 @@ class FloatingEqMatcher { // os->precision() returns the previously set precision, which we // store to restore the ostream to its original configuration // after outputting. - const ::std::streamsize old_precision = os->precision( - ::std::numeric_limits::digits10 + 2); + const ::std::streamsize old_precision = os->precision(::std::numeric_limits::digits10 + 2); if (FloatingPoint(expected_).is_nan()) { if (nan_eq_nan_) { *os << "is NaN"; @@ -1976,8 +1864,7 @@ class FloatingEqMatcher { virtual void DescribeNegationTo(::std::ostream* os) const { // As before, get original precision. - const ::std::streamsize old_precision = os->precision( - ::std::numeric_limits::digits10 + 2); + const ::std::streamsize old_precision = os->precision(::std::numeric_limits::digits10 + 2); if (FloatingPoint(expected_).is_nan()) { if (nan_eq_nan_) { *os << "isn't NaN"; @@ -1995,9 +1882,7 @@ class FloatingEqMatcher { } private: - bool HasMaxAbsError() const { - return max_abs_error_ >= 0; - } + bool HasMaxAbsError() const { return max_abs_error_ >= 0; } const FloatType expected_; const bool nan_eq_nan_; @@ -2014,18 +1899,15 @@ class FloatingEqMatcher { // by non-const reference, we may see them in code not conforming to // the style. Therefore Google Mock needs to support them.) operator Matcher() const { - return MakeMatcher( - new Impl(expected_, nan_eq_nan_, max_abs_error_)); + return MakeMatcher(new Impl(expected_, nan_eq_nan_, max_abs_error_)); } operator Matcher() const { - return MakeMatcher( - new Impl(expected_, nan_eq_nan_, max_abs_error_)); + return MakeMatcher(new Impl(expected_, nan_eq_nan_, max_abs_error_)); } operator Matcher() const { - return MakeMatcher( - new Impl(expected_, nan_eq_nan_, max_abs_error_)); + return MakeMatcher(new Impl(expected_, nan_eq_nan_, max_abs_error_)); } private: @@ -2065,8 +1947,7 @@ class PointeeMatcher { typedef typename PointeeOf::type Pointee; - explicit Impl(const InnerMatcher& matcher) - : matcher_(MatcherCast(matcher)) {} + explicit Impl(const InnerMatcher& matcher) : matcher_(MatcherCast(matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "points to a value that "; @@ -2078,10 +1959,8 @@ class PointeeMatcher { matcher_.DescribeTo(os); } - virtual bool MatchAndExplain(Pointer pointer, - MatchResultListener* listener) const { - if (GetRawPointer(pointer) == NULL) - return false; + virtual bool MatchAndExplain(Pointer pointer, MatchResultListener* listener) const { + if (GetRawPointer(pointer) == NULL) return false; *listener << "which points to "; return MatchPrintAndExplain(*pointer, matcher_, listener); @@ -2107,8 +1986,7 @@ class PointeeMatcher { template class WhenDynamicCastToMatcherBase { public: - explicit WhenDynamicCastToMatcherBase(const Matcher& matcher) - : matcher_(matcher) {} + explicit WhenDynamicCastToMatcherBase(const Matcher& matcher) : matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { GetCastTypeDescription(os); @@ -2126,15 +2004,13 @@ class WhenDynamicCastToMatcherBase { static string GetToName() { #if GTEST_HAS_RTTI return GetTypeName(); -#else // GTEST_HAS_RTTI +#else // GTEST_HAS_RTTI return "the target type"; #endif // GTEST_HAS_RTTI } private: - static void GetCastTypeDescription(::std::ostream* os) { - *os << "when dynamic_cast to " << GetToName() << ", "; - } + static void GetCastTypeDescription(::std::ostream* os) { *os << "when dynamic_cast to " << GetToName() << ", "; } GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase); }; @@ -2144,8 +2020,7 @@ class WhenDynamicCastToMatcherBase { template class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase { public: - explicit WhenDynamicCastToMatcher(const Matcher& matcher) - : WhenDynamicCastToMatcherBase(matcher) {} + explicit WhenDynamicCastToMatcher(const Matcher& matcher) : WhenDynamicCastToMatcherBase(matcher) {} template bool MatchAndExplain(From from, MatchResultListener* listener) const { @@ -2160,8 +2035,7 @@ class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase { template class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase { public: - explicit WhenDynamicCastToMatcher(const Matcher& matcher) - : WhenDynamicCastToMatcherBase(matcher) {} + explicit WhenDynamicCastToMatcher(const Matcher& matcher) : WhenDynamicCastToMatcherBase(matcher) {} template bool MatchAndExplain(From& from, MatchResultListener* listener) const { @@ -2180,9 +2054,7 @@ class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase { template class FieldMatcher { public: - FieldMatcher(FieldType Class::*field, - const Matcher& matcher) - : field_(field), matcher_(matcher) {} + FieldMatcher(FieldType Class::*field, const Matcher& matcher) : field_(field), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { *os << "is an object whose given field "; @@ -2196,26 +2068,21 @@ class FieldMatcher { template bool MatchAndExplain(const T& value, MatchResultListener* listener) const { - return MatchAndExplainImpl( - typename ::testing::internal:: - is_pointer::type(), - value, listener); + return MatchAndExplainImpl(typename ::testing::internal::is_pointer::type(), value, + listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Field() matcher is used to match a pointer. - bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, - MatchResultListener* listener) const { + bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given field is "; return MatchPrintAndExplain(obj.*field_, matcher_, listener); } - bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, - MatchResultListener* listener) const { - if (p == NULL) - return false; + bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { + if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a field, it must be a class/struct/union type and @@ -2241,8 +2108,7 @@ class PropertyMatcher { // PropertyType being a reference or not. typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; - PropertyMatcher(PropertyType (Class::*property)() const, - const Matcher& matcher) + PropertyMatcher(PropertyType (Class::*property)() const, const Matcher& matcher) : property_(property), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { @@ -2256,23 +2122,20 @@ class PropertyMatcher { } template - bool MatchAndExplain(const T&value, MatchResultListener* listener) const { - return MatchAndExplainImpl( - typename ::testing::internal:: - is_pointer::type(), - value, listener); + bool MatchAndExplain(const T& value, MatchResultListener* listener) const { + return MatchAndExplainImpl(typename ::testing::internal::is_pointer::type(), value, + listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Property() matcher is used to match a pointer. - bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, - MatchResultListener* listener) const { + bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given property is "; // Cannot pass the return value (for example, int) to MatchPrintAndExplain, // which takes a non-const reference as argument. -#if defined(_PREFAST_ ) && _MSC_VER == 1800 +#if defined(_PREFAST_) && _MSC_VER == 1800 // Workaround bug in VC++ 2013's /analyze parser. // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move posix::Abort(); // To make sure it is never run. @@ -2283,10 +2146,8 @@ class PropertyMatcher { #endif } - bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, - MatchResultListener* listener) const { - if (p == NULL) - return false; + bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { + if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a property method, it must be a class/struct/union @@ -2312,21 +2173,22 @@ struct CallableTraits { static void CheckIsValid(Functor /* functor */) {} template - static ResultType Invoke(Functor f, T arg) { return f(arg); } + static ResultType Invoke(Functor f, T arg) { + return f(arg); + } }; // Specialization for function pointers. template -struct CallableTraits { +struct CallableTraits { typedef ResType ResultType; - typedef ResType(*StorageType)(ArgType); + typedef ResType (*StorageType)(ArgType); - static void CheckIsValid(ResType(*f)(ArgType)) { - GTEST_CHECK_(f != NULL) - << "NULL function pointer is passed into ResultOf()."; + static void CheckIsValid(ResType (*f)(ArgType)) { + GTEST_CHECK_(f != NULL) << "NULL function pointer is passed into ResultOf()."; } template - static ResType Invoke(ResType(*f)(ArgType), T arg) { + static ResType Invoke(ResType (*f)(ArgType), T arg) { return (*f)(arg); } }; @@ -2338,8 +2200,7 @@ class ResultOfMatcher { public: typedef typename CallableTraits::ResultType ResultType; - ResultOfMatcher(Callable callable, const Matcher& matcher) - : callable_(callable), matcher_(matcher) { + ResultOfMatcher(Callable callable, const Matcher& matcher) : callable_(callable), matcher_(matcher) { CallableTraits::CheckIsValid(callable_); } @@ -2354,8 +2215,7 @@ class ResultOfMatcher { template class Impl : public MatcherInterface { public: - Impl(CallableStorageType callable, const Matcher& matcher) - : callable_(callable), matcher_(matcher) {} + Impl(CallableStorageType callable, const Matcher& matcher) : callable_(callable), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; @@ -2371,8 +2231,7 @@ class ResultOfMatcher { *listener << "which is mapped by the given callable to "; // Cannot pass the return value (for example, int) to // MatchPrintAndExplain, which takes a non-const reference as argument. - ResultType result = - CallableTraits::template Invoke(callable_, obj); + ResultType result = CallableTraits::template Invoke(callable_, obj); return MatchPrintAndExplain(result, matcher_, listener); } @@ -2398,9 +2257,7 @@ class ResultOfMatcher { template class SizeIsMatcher { public: - explicit SizeIsMatcher(const SizeMatcher& size_matcher) - : size_matcher_(size_matcher) { - } + explicit SizeIsMatcher(const SizeMatcher& size_matcher) : size_matcher_(size_matcher) {} template operator Matcher() const { @@ -2410,11 +2267,9 @@ class SizeIsMatcher { template class Impl : public MatcherInterface { public: - typedef internal::StlContainerView< - GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; + typedef internal::StlContainerView ContainerView; typedef typename ContainerView::type::size_type SizeType; - explicit Impl(const SizeMatcher& size_matcher) - : size_matcher_(MatcherCast(size_matcher)) {} + explicit Impl(const SizeMatcher& size_matcher) : size_matcher_(MatcherCast(size_matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "size "; @@ -2425,13 +2280,11 @@ class SizeIsMatcher { size_matcher_.DescribeNegationTo(os); } - virtual bool MatchAndExplain(Container container, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { SizeType size = container.size(); StringMatchResultListener size_listener; const bool result = size_matcher_.MatchAndExplain(size, &size_listener); - *listener - << "whose size " << size << (result ? " matches" : " doesn't match"); + *listener << "whose size " << size << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(size_listener.str(), listener->stream()); return result; } @@ -2451,8 +2304,7 @@ class SizeIsMatcher { template class BeginEndDistanceIsMatcher { public: - explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) - : distance_matcher_(distance_matcher) {} + explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) : distance_matcher_(distance_matcher) {} template operator Matcher() const { @@ -2462,11 +2314,8 @@ class BeginEndDistanceIsMatcher { template class Impl : public MatcherInterface { public: - typedef internal::StlContainerView< - GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; - typedef typename std::iterator_traits< - typename ContainerView::type::const_iterator>::difference_type - DistanceType; + typedef internal::StlContainerView ContainerView; + typedef typename std::iterator_traits::difference_type DistanceType; explicit Impl(const DistanceMatcher& distance_matcher) : distance_matcher_(MatcherCast(distance_matcher)) {} @@ -2479,8 +2328,7 @@ class BeginEndDistanceIsMatcher { distance_matcher_.DescribeNegationTo(os); } - virtual bool MatchAndExplain(Container container, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { #if GTEST_HAS_STD_BEGIN_AND_END_ using std::begin; using std::end; @@ -2489,10 +2337,8 @@ class BeginEndDistanceIsMatcher { DistanceType distance = std::distance(container.begin(), container.end()); #endif StringMatchResultListener distance_listener; - const bool result = - distance_matcher_.MatchAndExplain(distance, &distance_listener); - *listener << "whose distance between begin() and end() " << distance - << (result ? " matches" : " doesn't match"); + const bool result = distance_matcher_.MatchAndExplain(distance, &distance_listener); + *listener << "whose distance between begin() and end() " << distance << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(distance_listener.str(), listener->stream()); return result; } @@ -2526,12 +2372,10 @@ class ContainerEqMatcher { // We make a copy of expected in case the elements in it are modified // after this matcher is created. - explicit ContainerEqMatcher(const Container& expected) - : expected_(View::Copy(expected)) { + explicit ContainerEqMatcher(const Container& expected) : expected_(View::Copy(expected)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. - (void)testing::StaticAssertTypeEq(); + (void)testing::StaticAssertTypeEq(); } void DescribeTo(::std::ostream* os) const { @@ -2544,26 +2388,21 @@ class ContainerEqMatcher { } template - bool MatchAndExplain(const LhsContainer& lhs, - MatchResultListener* listener) const { + bool MatchAndExplain(const LhsContainer& lhs, MatchResultListener* listener) const { // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug // that causes LhsContainer to be a const type sometimes. - typedef internal::StlContainerView - LhsView; + typedef internal::StlContainerView LhsView; typedef typename LhsView::type LhsStlContainer; StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); - if (lhs_stl_container == expected_) - return true; + if (lhs_stl_container == expected_) return true; ::std::ostream* const os = listener->stream(); if (os != NULL) { // Something is different. Check for extra values first. bool printed_header = false; - for (typename LhsStlContainer::const_iterator it = - lhs_stl_container.begin(); - it != lhs_stl_container.end(); ++it) { - if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == - expected_.end()) { + for (typename LhsStlContainer::const_iterator it = lhs_stl_container.begin(); it != lhs_stl_container.end(); + ++it) { + if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == expected_.end()) { if (printed_header) { *os << ", "; } else { @@ -2576,16 +2415,13 @@ class ContainerEqMatcher { // Now check for missing values. bool printed_header2 = false; - for (typename StlContainer::const_iterator it = expected_.begin(); - it != expected_.end(); ++it) { - if (internal::ArrayAwareFind( - lhs_stl_container.begin(), lhs_stl_container.end(), *it) == + for (typename StlContainer::const_iterator it = expected_.begin(); it != expected_.end(); ++it) { + if (internal::ArrayAwareFind(lhs_stl_container.begin(), lhs_stl_container.end(), *it) == lhs_stl_container.end()) { if (printed_header2) { *os << ", "; } else { - *os << (printed_header ? ",\nand" : "which") - << " doesn't have these expected elements: "; + *os << (printed_header ? ",\nand" : "which") << " doesn't have these expected elements: "; printed_header2 = true; } UniversalPrint(*it, os); @@ -2605,15 +2441,16 @@ class ContainerEqMatcher { // A comparator functor that uses the < operator to compare two values. struct LessComparator { template - bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; } + bool operator()(const T& lhs, const U& rhs) const { + return lhs < rhs; + } }; // Implements WhenSortedBy(comparator, container_matcher). template class WhenSortedByMatcher { public: - WhenSortedByMatcher(const Comparator& comparator, - const ContainerMatcher& matcher) + WhenSortedByMatcher(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} template @@ -2624,17 +2461,14 @@ class WhenSortedByMatcher { template class Impl : public MatcherInterface { public: - typedef internal::StlContainerView< - GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; + typedef internal::StlContainerView LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; // Transforms std::pair into std::pair // so that we can match associative containers. - typedef typename RemoveConstFromKey< - typename LhsStlContainer::value_type>::type LhsValue; + typedef typename RemoveConstFromKey::type LhsValue; - Impl(const Comparator& comparator, const ContainerMatcher& matcher) - : comparator_(comparator), matcher_(matcher) {} + Impl(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "(when sorted) "; @@ -2646,13 +2480,10 @@ class WhenSortedByMatcher { matcher_.DescribeNegationTo(os); } - virtual bool MatchAndExplain(LhsContainer lhs, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); - ::std::vector sorted_container(lhs_stl_container.begin(), - lhs_stl_container.end()); - ::std::sort( - sorted_container.begin(), sorted_container.end(), comparator_); + ::std::vector sorted_container(lhs_stl_container.begin(), lhs_stl_container.end()); + ::std::sort(sorted_container.begin(), sorted_container.end(), comparator_); if (!listener->IsInterested()) { // If the listener is not interested, we do not need to @@ -2665,8 +2496,7 @@ class WhenSortedByMatcher { *listener << " when sorted"; StringMatchResultListener inner_listener; - const bool match = matcher_.MatchAndExplain(sorted_container, - &inner_listener); + const bool match = matcher_.MatchAndExplain(sorted_container, &inner_listener); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } @@ -2702,8 +2532,7 @@ class PointwiseMatcher { : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. - (void)testing::StaticAssertTypeEq(); + (void)testing::StaticAssertTypeEq(); } template @@ -2714,8 +2543,7 @@ class PointwiseMatcher { template class Impl : public MatcherInterface { public: - typedef internal::StlContainerView< - GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; + typedef internal::StlContainerView LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; typedef typename LhsStlContainer::value_type LhsValue; @@ -2727,27 +2555,23 @@ class PointwiseMatcher { Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. - : mono_tuple_matcher_(SafeMatcherCast(tuple_matcher)), - rhs_(rhs) {} + : mono_tuple_matcher_(SafeMatcherCast(tuple_matcher)), rhs_(rhs) {} virtual void DescribeTo(::std::ostream* os) const { - *os << "contains " << rhs_.size() - << " values, where each value and its corresponding value in "; + *os << "contains " << rhs_.size() << " values, where each value and its corresponding value in "; UniversalPrinter::Print(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't contain exactly " << rhs_.size() - << " values, or contains a value x at some index i" + *os << "doesn't contain exactly " << rhs_.size() << " values, or contains a value x at some index i" << " where x and the i-th value of "; UniversalPrint(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeNegationTo(os); } - virtual bool MatchAndExplain(LhsContainer lhs, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); const size_t actual_size = lhs_stl_container.size(); if (actual_size != rhs_.size()) { @@ -2762,8 +2586,7 @@ class PointwiseMatcher { if (listener->IsInterested()) { StringMatchResultListener inner_listener; - if (!mono_tuple_matcher_.MatchAndExplain( - value_pair, &inner_listener)) { + if (!mono_tuple_matcher_.MatchAndExplain(value_pair, &inner_listener)) { *listener << "where the value pair ("; UniversalPrint(*left, listener->stream()); *listener << ", "; @@ -2773,8 +2596,7 @@ class PointwiseMatcher { return false; } } else { - if (!mono_tuple_matcher_.Matches(value_pair)) - return false; + if (!mono_tuple_matcher_.Matches(value_pair)) return false; } } @@ -2807,25 +2629,20 @@ class QuantifierMatcherImpl : public MatcherInterface { template explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) - : inner_matcher_( - testing::SafeMatcherCast(inner_matcher)) {} + : inner_matcher_(testing::SafeMatcherCast(inner_matcher)) {} // Checks whether: // * All elements in the container match, if all_elements_should_match. // * Any element in the container matches, if !all_elements_should_match. - bool MatchAndExplainImpl(bool all_elements_should_match, - Container container, - MatchResultListener* listener) const { + bool MatchAndExplainImpl(bool all_elements_should_match, Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); size_t i = 0; - for (typename StlContainer::const_iterator it = stl_container.begin(); - it != stl_container.end(); ++it, ++i) { + for (typename StlContainer::const_iterator it = stl_container.begin(); it != stl_container.end(); ++it, ++i) { StringMatchResultListener inner_listener; const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); if (matches != all_elements_should_match) { - *listener << "whose element #" << i - << (matches ? " matches" : " doesn't match"); + *listener << "whose element #" << i << (matches ? " matches" : " doesn't match"); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return !all_elements_should_match; } @@ -2845,8 +2662,7 @@ template class ContainsMatcherImpl : public QuantifierMatcherImpl { public: template - explicit ContainsMatcherImpl(InnerMatcher inner_matcher) - : QuantifierMatcherImpl(inner_matcher) {} + explicit ContainsMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { @@ -2859,8 +2675,7 @@ class ContainsMatcherImpl : public QuantifierMatcherImpl { this->inner_matcher_.DescribeTo(os); } - virtual bool MatchAndExplain(Container container, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(false, container, listener); } @@ -2874,8 +2689,7 @@ template class EachMatcherImpl : public QuantifierMatcherImpl { public: template - explicit EachMatcherImpl(InnerMatcher inner_matcher) - : QuantifierMatcherImpl(inner_matcher) {} + explicit EachMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { @@ -2888,8 +2702,7 @@ class EachMatcherImpl : public QuantifierMatcherImpl { this->inner_matcher_.DescribeNegationTo(os); } - virtual bool MatchAndExplain(Container container, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(true, container, listener); } @@ -2943,16 +2756,12 @@ class KeyMatcherImpl : public MatcherInterface { template explicit KeyMatcherImpl(InnerMatcher inner_matcher) - : inner_matcher_( - testing::SafeMatcherCast(inner_matcher)) { - } + : inner_matcher_(testing::SafeMatcherCast(inner_matcher)) {} // Returns true iff 'key_value.first' (the key) matches the inner matcher. - virtual bool MatchAndExplain(PairType key_value, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(PairType key_value, MatchResultListener* listener) const { StringMatchResultListener inner_listener; - const bool match = inner_matcher_.MatchAndExplain(key_value.first, - &inner_listener); + const bool match = inner_matcher_.MatchAndExplain(key_value.first, &inner_listener); const internal::string explanation = inner_listener.str(); if (explanation != "") { *listener << "whose first field is a value " << explanation; @@ -3006,11 +2815,8 @@ class PairMatcherImpl : public MatcherInterface { template PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher) - : first_matcher_( - testing::SafeMatcherCast(first_matcher)), - second_matcher_( - testing::SafeMatcherCast(second_matcher)) { - } + : first_matcher_(testing::SafeMatcherCast(first_matcher)), + second_matcher_(testing::SafeMatcherCast(second_matcher)) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { @@ -3030,36 +2836,30 @@ class PairMatcherImpl : public MatcherInterface { // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second' // matches second_matcher. - virtual bool MatchAndExplain(PairType a_pair, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(PairType a_pair, MatchResultListener* listener) const { if (!listener->IsInterested()) { // If the listener is not interested, we don't need to construct the // explanation. - return first_matcher_.Matches(a_pair.first) && - second_matcher_.Matches(a_pair.second); + return first_matcher_.Matches(a_pair.first) && second_matcher_.Matches(a_pair.second); } StringMatchResultListener first_inner_listener; - if (!first_matcher_.MatchAndExplain(a_pair.first, - &first_inner_listener)) { + if (!first_matcher_.MatchAndExplain(a_pair.first, &first_inner_listener)) { *listener << "whose first field does not match"; PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); return false; } StringMatchResultListener second_inner_listener; - if (!second_matcher_.MatchAndExplain(a_pair.second, - &second_inner_listener)) { + if (!second_matcher_.MatchAndExplain(a_pair.second, &second_inner_listener)) { *listener << "whose second field does not match"; PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); return false; } - ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(), - listener); + ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(), listener); return true; } private: - void ExplainSuccess(const internal::string& first_explanation, - const internal::string& second_explanation, + void ExplainSuccess(const internal::string& first_explanation, const internal::string& second_explanation, MatchResultListener* listener) const { *listener << "whose both fields match"; if (first_explanation != "") { @@ -3090,10 +2890,8 @@ class PairMatcher { : first_matcher_(first_matcher), second_matcher_(second_matcher) {} template - operator Matcher () const { - return MakeMatcher( - new PairMatcherImpl( - first_matcher_, second_matcher_)); + operator Matcher() const { + return MakeMatcher(new PairMatcherImpl(first_matcher_, second_matcher_)); } private: @@ -3158,8 +2956,7 @@ class ElementsAreMatcherImpl : public MatcherInterface { } } - virtual bool MatchAndExplain(Container container, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { // To work with stream-like "containers", we must only walk // through the elements in one pass. @@ -3239,9 +3036,7 @@ class ElementsAreMatcherImpl : public MatcherInterface { } private: - static Message Elements(size_t count) { - return Message() << count << (count == 1 ? " element" : " elements"); - } + static Message Elements(size_t count) { return Message() << count << (count == 1 ? " element" : " elements"); } size_t count() const { return matchers_.size(); } @@ -3257,19 +3052,12 @@ class ElementsAreMatcherImpl : public MatcherInterface { class GTEST_API_ MatchMatrix { public: MatchMatrix(size_t num_elements, size_t num_matchers) - : num_elements_(num_elements), - num_matchers_(num_matchers), - matched_(num_elements_* num_matchers_, 0) { - } + : num_elements_(num_elements), num_matchers_(num_matchers), matched_(num_elements_ * num_matchers_, 0) {} size_t LhsSize() const { return num_elements_; } size_t RhsSize() const { return num_matchers_; } - bool HasEdge(size_t ilhs, size_t irhs) const { - return matched_[SpaceIndex(ilhs, irhs)] == 1; - } - void SetEdge(size_t ilhs, size_t irhs, bool b) { - matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; - } + bool HasEdge(size_t ilhs, size_t irhs) const { return matched_[SpaceIndex(ilhs, irhs)] == 1; } + void SetEdge(size_t ilhs, size_t irhs, bool b) { matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; } // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number, // adds 1 to that number; returns false if incrementing the graph left it @@ -3281,9 +3069,7 @@ class GTEST_API_ MatchMatrix { string DebugString() const; private: - size_t SpaceIndex(size_t ilhs, size_t irhs) const { - return ilhs * num_matchers_ + irhs; - } + size_t SpaceIndex(size_t ilhs, size_t irhs) const { return ilhs * num_matchers_ + irhs; } size_t num_elements_; size_t num_matchers_; @@ -3299,11 +3085,9 @@ typedef ::std::vector ElementMatcherPairs; // Returns a maximum bipartite matching for the specified graph 'g'. // The matching is represented as a vector of {element, matcher} pairs. -GTEST_API_ ElementMatcherPairs -FindMaxBipartiteMatching(const MatchMatrix& g); +GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g); -GTEST_API_ bool FindPairing(const MatchMatrix& matrix, - MatchResultListener* listener); +GTEST_API_ bool FindPairing(const MatchMatrix& matrix, MatchResultListener* listener); // Untyped base class for implementing UnorderedElementsAre. By // putting logic that's not specific to the element type here, we @@ -3321,18 +3105,12 @@ class GTEST_API_ UnorderedElementsAreMatcherImplBase { // Describes the negation of this UnorderedElementsAre matcher. void DescribeNegationToImpl(::std::ostream* os) const; - bool VerifyAllElementsAndMatchersAreMatched( - const ::std::vector& element_printouts, - const MatchMatrix& matrix, - MatchResultListener* listener) const; + bool VerifyAllElementsAndMatchersAreMatched(const ::std::vector& element_printouts, const MatchMatrix& matrix, + MatchResultListener* listener) const; - MatcherDescriberVec& matcher_describers() { - return matcher_describers_; - } + MatcherDescriberVec& matcher_describers() { return matcher_describers_; } - static Message Elements(size_t n) { - return Message() << n << " element" << (n == 1 ? "" : "s"); - } + static Message Elements(size_t n) { return Message() << n << " element" << (n == 1 ? "" : "s"); } private: MatcherDescriberVec matcher_describers_; @@ -3342,9 +3120,7 @@ class GTEST_API_ UnorderedElementsAreMatcherImplBase { // Implements unordered ElementsAre and unordered ElementsAreArray. template -class UnorderedElementsAreMatcherImpl - : public MatcherInterface, - public UnorderedElementsAreMatcherImplBase { +class UnorderedElementsAreMatcherImpl : public MatcherInterface, public UnorderedElementsAreMatcherImplBase { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView View; @@ -3364,23 +3140,17 @@ class UnorderedElementsAreMatcherImpl } // Describes what this matcher does. - virtual void DescribeTo(::std::ostream* os) const { - return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); - } + virtual void DescribeTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os); } - virtual bool MatchAndExplain(Container container, - MatchResultListener* listener) const { + virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); ::std::vector element_printouts; - MatchMatrix matrix = AnalyzeElements(stl_container.begin(), - stl_container.end(), - &element_printouts, - listener); + MatchMatrix matrix = AnalyzeElements(stl_container.begin(), stl_container.end(), &element_printouts, listener); const size_t actual_count = matrix.LhsSize(); if (actual_count == 0 && matchers_.empty()) { @@ -3397,17 +3167,14 @@ class UnorderedElementsAreMatcherImpl return false; } - return VerifyAllElementsAndMatchersAreMatched(element_printouts, - matrix, listener) && - FindPairing(matrix, listener); + return VerifyAllElementsAndMatchersAreMatched(element_printouts, matrix, listener) && FindPairing(matrix, listener); } private: typedef ::std::vector > MatcherVec; template - MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, - ::std::vector* element_printouts, + MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, ::std::vector* element_printouts, MatchResultListener* listener) const { element_printouts->clear(); ::std::vector did_match; @@ -3450,8 +3217,7 @@ struct CastAndAppendTransform { template class UnorderedElementsAreMatcher { public: - explicit UnorderedElementsAreMatcher(const MatcherTuple& args) - : matchers_(args) {} + explicit UnorderedElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} template operator Matcher() const { @@ -3461,10 +3227,8 @@ class UnorderedElementsAreMatcher { typedef ::std::vector > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size::value); - TransformTupleValues(CastAndAppendTransform(), matchers_, - ::std::back_inserter(matchers)); - return MakeMatcher(new UnorderedElementsAreMatcherImpl( - matchers.begin(), matchers.end())); + TransformTupleValues(CastAndAppendTransform(), matchers_, ::std::back_inserter(matchers)); + return MakeMatcher(new UnorderedElementsAreMatcherImpl(matchers.begin(), matchers.end())); } private: @@ -3486,10 +3250,8 @@ class ElementsAreMatcher { typedef ::std::vector > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size::value); - TransformTupleValues(CastAndAppendTransform(), matchers_, - ::std::back_inserter(matchers)); - return MakeMatcher(new ElementsAreMatcherImpl( - matchers.begin(), matchers.end())); + TransformTupleValues(CastAndAppendTransform(), matchers_, ::std::back_inserter(matchers)); + return MakeMatcher(new ElementsAreMatcherImpl(matchers.begin(), matchers.end())); } private: @@ -3504,14 +3266,11 @@ class UnorderedElementsAreArrayMatcher { UnorderedElementsAreArrayMatcher() {} template - UnorderedElementsAreArrayMatcher(Iter first, Iter last) - : matchers_(first, last) {} + UnorderedElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} template operator Matcher() const { - return MakeMatcher( - new UnorderedElementsAreMatcherImpl(matchers_.begin(), - matchers_.end())); + return MakeMatcher(new UnorderedElementsAreMatcherImpl(matchers_.begin(), matchers_.end())); } private: @@ -3529,8 +3288,7 @@ class ElementsAreArrayMatcher { template operator Matcher() const { - return MakeMatcher(new ElementsAreMatcherImpl( - matchers_.begin(), matchers_.end())); + return MakeMatcher(new ElementsAreMatcherImpl(matchers_.begin(), matchers_.end())); } private: @@ -3551,8 +3309,7 @@ class ElementsAreArrayMatcher { template class BoundSecondMatcher { public: - BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) - : tuple2_matcher_(tm), second_value_(second) {} + BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) : tuple2_matcher_(tm), second_value_(second) {} template operator Matcher() const { @@ -3578,8 +3335,7 @@ class BoundSecondMatcher { typedef ::testing::tuple ArgTuple; Impl(const Tuple2Matcher& tm, const Second& second) - : mono_tuple2_matcher_(SafeMatcherCast(tm)), - second_value_(second) {} + : mono_tuple2_matcher_(SafeMatcherCast(tm)), second_value_(second) {} virtual void DescribeTo(::std::ostream* os) const { *os << "and "; @@ -3589,8 +3345,7 @@ class BoundSecondMatcher { } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { - return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_), - listener); + return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_), listener); } private: @@ -3609,8 +3364,7 @@ class BoundSecondMatcher { // value x iff tm matches tuple (x, second). Useful for implementing // UnorderedPointwise() in terms of UnorderedElementsAreArray(). template -BoundSecondMatcher MatcherBindSecond( - const Tuple2Matcher& tm, const Second& second) { +BoundSecondMatcher MatcherBindSecond(const Tuple2Matcher& tm, const Second& second) { return BoundSecondMatcher(tm, second); } @@ -3619,9 +3373,7 @@ BoundSecondMatcher MatcherBindSecond( // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. -GTEST_API_ string FormatMatcherDescription(bool negation, - const char* matcher_name, - const Strings& param_values); +GTEST_API_ string FormatMatcherDescription(bool negation, const char* matcher_name, const Strings& param_values); } // namespace internal @@ -3641,35 +3393,30 @@ GTEST_API_ string FormatMatcherDescription(bool negation, // All forms of ElementsAreArray() make a copy of the input matcher sequence. template -inline internal::ElementsAreArrayMatcher< - typename ::std::iterator_traits::value_type> -ElementsAreArray(Iter first, Iter last) { +inline internal::ElementsAreArrayMatcher::value_type> ElementsAreArray( + Iter first, Iter last) { typedef typename ::std::iterator_traits::value_type T; return internal::ElementsAreArrayMatcher(first, last); } template -inline internal::ElementsAreArrayMatcher ElementsAreArray( - const T* pointer, size_t count) { +inline internal::ElementsAreArrayMatcher ElementsAreArray(const T* pointer, size_t count) { return ElementsAreArray(pointer, pointer + count); } template -inline internal::ElementsAreArrayMatcher ElementsAreArray( - const T (&array)[N]) { +inline internal::ElementsAreArrayMatcher ElementsAreArray(const T (&array)[N]) { return ElementsAreArray(array, N); } template -inline internal::ElementsAreArrayMatcher -ElementsAreArray(const Container& container) { +inline internal::ElementsAreArrayMatcher ElementsAreArray(const Container& container) { return ElementsAreArray(container.begin(), container.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template -inline internal::ElementsAreArrayMatcher -ElementsAreArray(::std::initializer_list xs) { +inline internal::ElementsAreArrayMatcher ElementsAreArray(::std::initializer_list xs) { return ElementsAreArray(xs.begin(), xs.end()); } #endif @@ -3683,36 +3430,31 @@ ElementsAreArray(::std::initializer_list xs) { // The UnorderedElementsAreArray() functions are like // ElementsAreArray(...), but allow matching the elements in any order. template -inline internal::UnorderedElementsAreArrayMatcher< - typename ::std::iterator_traits::value_type> +inline internal::UnorderedElementsAreArrayMatcher::value_type> UnorderedElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits::value_type T; return internal::UnorderedElementsAreArrayMatcher(first, last); } template -inline internal::UnorderedElementsAreArrayMatcher -UnorderedElementsAreArray(const T* pointer, size_t count) { +inline internal::UnorderedElementsAreArrayMatcher UnorderedElementsAreArray(const T* pointer, size_t count) { return UnorderedElementsAreArray(pointer, pointer + count); } template -inline internal::UnorderedElementsAreArrayMatcher -UnorderedElementsAreArray(const T (&array)[N]) { +inline internal::UnorderedElementsAreArrayMatcher UnorderedElementsAreArray(const T (&array)[N]) { return UnorderedElementsAreArray(array, N); } template -inline internal::UnorderedElementsAreArrayMatcher< - typename Container::value_type> -UnorderedElementsAreArray(const Container& container) { +inline internal::UnorderedElementsAreArrayMatcher UnorderedElementsAreArray( + const Container& container) { return UnorderedElementsAreArray(container.begin(), container.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template -inline internal::UnorderedElementsAreArrayMatcher -UnorderedElementsAreArray(::std::initializer_list xs) { +inline internal::UnorderedElementsAreArrayMatcher UnorderedElementsAreArray(::std::initializer_list xs) { return UnorderedElementsAreArray(xs.begin(), xs.end()); } #endif @@ -3729,22 +3471,30 @@ UnorderedElementsAreArray(::std::initializer_list xs) { const internal::AnythingMatcher _ = {}; // Creates a matcher that matches any value of the given type T. template -inline Matcher A() { return MakeMatcher(new internal::AnyMatcherImpl()); } +inline Matcher A() { + return MakeMatcher(new internal::AnyMatcherImpl()); +} // Creates a matcher that matches any value of the given type T. template -inline Matcher An() { return A(); } +inline Matcher An() { + return A(); +} // Creates a polymorphic matcher that matches anything equal to x. // Note: if the parameter of Eq() were declared as const T&, Eq("foo") // wouldn't compile. template -inline internal::EqMatcher Eq(T x) { return internal::EqMatcher(x); } +inline internal::EqMatcher Eq(T x) { + return internal::EqMatcher(x); +} // Constructs a Matcher from a 'value' of type T. The constructed // matcher matches any value that's equal to 'value'. template -Matcher::Matcher(T value) { *this = Eq(value); } +Matcher::Matcher(T value) { + *this = Eq(value); +} // Creates a monomorphic matcher that matches anything with type Lhs // and equal to rhs. A user may need to use this instead of Eq(...) @@ -3759,7 +3509,9 @@ Matcher::Matcher(T value) { *this = Eq(value); } // can always write Matcher(Lt(5)) to be explicit about the type, // for example. template -inline Matcher TypedEq(const Rhs& rhs) { return Eq(rhs); } +inline Matcher TypedEq(const Rhs& rhs) { + return Eq(rhs); +} // Creates a polymorphic matcher that matches anything >= x. template @@ -3792,14 +3544,14 @@ inline internal::NeMatcher Ne(Rhs x) { } // Creates a polymorphic matcher that matches any NULL pointer. -inline PolymorphicMatcher IsNull() { +inline PolymorphicMatcher IsNull() { return MakePolymorphicMatcher(internal::IsNullMatcher()); } // Creates a polymorphic matcher that matches any non-NULL pointer. // This is convenient as Not(NULL) doesn't compile (the compiler // thinks that that expression is comparing a pointer with an integer). -inline PolymorphicMatcher NotNull() { +inline PolymorphicMatcher NotNull() { return MakePolymorphicMatcher(internal::NotNullMatcher()); } @@ -3825,24 +3577,20 @@ inline internal::FloatingEqMatcher NanSensitiveDoubleEq(double rhs) { // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. -inline internal::FloatingEqMatcher DoubleNear( - double rhs, double max_abs_error) { +inline internal::FloatingEqMatcher DoubleNear(double rhs, double max_abs_error) { return internal::FloatingEqMatcher(rhs, false, max_abs_error); } // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. -inline internal::FloatingEqMatcher NanSensitiveDoubleNear( - double rhs, double max_abs_error) { +inline internal::FloatingEqMatcher NanSensitiveDoubleNear(double rhs, double max_abs_error) { return internal::FloatingEqMatcher(rhs, true, max_abs_error); } // Creates a matcher that matches any float argument approximately // equal to rhs, where two NANs are considered unequal. -inline internal::FloatingEqMatcher FloatEq(float rhs) { - return internal::FloatingEqMatcher(rhs, false); -} +inline internal::FloatingEqMatcher FloatEq(float rhs) { return internal::FloatingEqMatcher(rhs, false); } // Creates a matcher that matches any float argument approximately // equal to rhs, including NaN values when rhs is NaN. @@ -3853,24 +3601,21 @@ inline internal::FloatingEqMatcher NanSensitiveFloatEq(float rhs) { // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. -inline internal::FloatingEqMatcher FloatNear( - float rhs, float max_abs_error) { +inline internal::FloatingEqMatcher FloatNear(float rhs, float max_abs_error) { return internal::FloatingEqMatcher(rhs, false, max_abs_error); } // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. -inline internal::FloatingEqMatcher NanSensitiveFloatNear( - float rhs, float max_abs_error) { +inline internal::FloatingEqMatcher NanSensitiveFloatNear(float rhs, float max_abs_error) { return internal::FloatingEqMatcher(rhs, true, max_abs_error); } // Creates a matcher that matches a pointer (raw or smart) that points // to a value that matches inner_matcher. template -inline internal::PointeeMatcher Pointee( - const InnerMatcher& inner_matcher) { +inline internal::PointeeMatcher Pointee(const InnerMatcher& inner_matcher) { return internal::PointeeMatcher(inner_matcher); } @@ -3881,10 +3626,8 @@ inline internal::PointeeMatcher Pointee( // If To is a reference and the cast fails, this matcher returns false // immediately. template -inline PolymorphicMatcher > -WhenDynamicCastTo(const Matcher& inner_matcher) { - return MakePolymorphicMatcher( - internal::WhenDynamicCastToMatcher(inner_matcher)); +inline PolymorphicMatcher > WhenDynamicCastTo(const Matcher& inner_matcher) { + return MakePolymorphicMatcher(internal::WhenDynamicCastToMatcher(inner_matcher)); } // Creates a matcher that matches an object whose given field matches @@ -3892,12 +3635,10 @@ WhenDynamicCastTo(const Matcher& inner_matcher) { // Field(&Foo::number, Ge(5)) // matches a Foo object x iff x.number >= 5. template -inline PolymorphicMatcher< - internal::FieldMatcher > Field( - FieldType Class::*field, const FieldMatcher& matcher) { +inline PolymorphicMatcher > Field(FieldType Class::*field, + const FieldMatcher& matcher) { return MakePolymorphicMatcher( - internal::FieldMatcher( - field, MatcherCast(matcher))); + internal::FieldMatcher(field, MatcherCast(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Field(&Foo::bar, m) @@ -3909,13 +3650,11 @@ inline PolymorphicMatcher< // Property(&Foo::str, StartsWith("hi")) // matches a Foo object x iff x.str() starts with "hi". template -inline PolymorphicMatcher< - internal::PropertyMatcher > Property( - PropertyType (Class::*property)() const, const PropertyMatcher& matcher) { - return MakePolymorphicMatcher( - internal::PropertyMatcher( - property, - MatcherCast(matcher))); +inline PolymorphicMatcher > Property(PropertyType (Class::*property)() + const, + const PropertyMatcher& matcher) { + return MakePolymorphicMatcher(internal::PropertyMatcher( + property, MatcherCast(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Property(&Foo::bar, m) @@ -3936,12 +3675,9 @@ inline PolymorphicMatcher< // * If it is a function object, it has to define type result_type. // We recommend deriving your functor classes from std::unary_function. template -internal::ResultOfMatcher ResultOf( - Callable callable, const ResultOfMatcher& matcher) { +internal::ResultOfMatcher ResultOf(Callable callable, const ResultOfMatcher& matcher) { return internal::ResultOfMatcher( - callable, - MatcherCast::ResultType>( - matcher)); + callable, MatcherCast::ResultType>(matcher)); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // ResultOf(Function, m) @@ -3951,74 +3687,56 @@ internal::ResultOfMatcher ResultOf( // String matchers. // Matches a string equal to str. -inline PolymorphicMatcher > - StrEq(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, true)); +inline PolymorphicMatcher > StrEq(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, true, true)); } // Matches a string not equal to str. -inline PolymorphicMatcher > - StrNe(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, true)); +inline PolymorphicMatcher > StrNe(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, false, true)); } // Matches a string equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseEq(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, false)); +inline PolymorphicMatcher > StrCaseEq(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, true, false)); } // Matches a string not equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseNe(const internal::string& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, false)); +inline PolymorphicMatcher > StrCaseNe(const internal::string& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, false, false)); } // Creates a matcher that matches any string, std::string, or C string // that contains the given substring. -inline PolymorphicMatcher > - HasSubstr(const internal::string& substring) { - return MakePolymorphicMatcher(internal::HasSubstrMatcher( - substring)); +inline PolymorphicMatcher > HasSubstr(const internal::string& substring) { + return MakePolymorphicMatcher(internal::HasSubstrMatcher(substring)); } // Matches a string that starts with 'prefix' (case-sensitive). -inline PolymorphicMatcher > - StartsWith(const internal::string& prefix) { - return MakePolymorphicMatcher(internal::StartsWithMatcher( - prefix)); +inline PolymorphicMatcher > StartsWith(const internal::string& prefix) { + return MakePolymorphicMatcher(internal::StartsWithMatcher(prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). -inline PolymorphicMatcher > - EndsWith(const internal::string& suffix) { - return MakePolymorphicMatcher(internal::EndsWithMatcher( - suffix)); +inline PolymorphicMatcher > EndsWith(const internal::string& suffix) { + return MakePolymorphicMatcher(internal::EndsWithMatcher(suffix)); } // Matches a string that fully matches regular expression 'regex'. // The matcher takes ownership of 'regex'. -inline PolymorphicMatcher MatchesRegex( - const internal::RE* regex) { +inline PolymorphicMatcher MatchesRegex(const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); } -inline PolymorphicMatcher MatchesRegex( - const internal::string& regex) { +inline PolymorphicMatcher MatchesRegex(const internal::string& regex) { return MatchesRegex(new internal::RE(regex)); } // Matches a string that contains regular expression 'regex'. // The matcher takes ownership of 'regex'. -inline PolymorphicMatcher ContainsRegex( - const internal::RE* regex) { +inline PolymorphicMatcher ContainsRegex(const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); } -inline PolymorphicMatcher ContainsRegex( - const internal::string& regex) { +inline PolymorphicMatcher ContainsRegex(const internal::string& regex) { return ContainsRegex(new internal::RE(regex)); } @@ -4026,53 +3744,40 @@ inline PolymorphicMatcher ContainsRegex( // Wide string matchers. // Matches a string equal to str. -inline PolymorphicMatcher > - StrEq(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, true)); +inline PolymorphicMatcher > StrEq(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, true, true)); } // Matches a string not equal to str. -inline PolymorphicMatcher > - StrNe(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, true)); +inline PolymorphicMatcher > StrNe(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, false, true)); } // Matches a string equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseEq(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, true, false)); +inline PolymorphicMatcher > StrCaseEq(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, true, false)); } // Matches a string not equal to str, ignoring case. -inline PolymorphicMatcher > - StrCaseNe(const internal::wstring& str) { - return MakePolymorphicMatcher(internal::StrEqualityMatcher( - str, false, false)); +inline PolymorphicMatcher > StrCaseNe(const internal::wstring& str) { + return MakePolymorphicMatcher(internal::StrEqualityMatcher(str, false, false)); } // Creates a matcher that matches any wstring, std::wstring, or C wide string // that contains the given substring. -inline PolymorphicMatcher > - HasSubstr(const internal::wstring& substring) { - return MakePolymorphicMatcher(internal::HasSubstrMatcher( - substring)); +inline PolymorphicMatcher > HasSubstr( + const internal::wstring& substring) { + return MakePolymorphicMatcher(internal::HasSubstrMatcher(substring)); } // Matches a string that starts with 'prefix' (case-sensitive). -inline PolymorphicMatcher > - StartsWith(const internal::wstring& prefix) { - return MakePolymorphicMatcher(internal::StartsWithMatcher( - prefix)); +inline PolymorphicMatcher > StartsWith(const internal::wstring& prefix) { + return MakePolymorphicMatcher(internal::StartsWithMatcher(prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). -inline PolymorphicMatcher > - EndsWith(const internal::wstring& suffix) { - return MakePolymorphicMatcher(internal::EndsWithMatcher( - suffix)); +inline PolymorphicMatcher > EndsWith(const internal::wstring& suffix) { + return MakePolymorphicMatcher(internal::EndsWithMatcher(suffix)); } #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING @@ -4112,8 +3817,7 @@ inline internal::NotMatcher Not(InnerMatcher m) { // predicate. The predicate can be any unary function or functor // whose return type can be implicitly converted to bool. template -inline PolymorphicMatcher > -Truly(Predicate pred) { +inline PolymorphicMatcher > Truly(Predicate pred) { return MakePolymorphicMatcher(internal::TrulyMatcher(pred)); } @@ -4124,8 +3828,7 @@ Truly(Predicate pred) { // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements. // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2. template -inline internal::SizeIsMatcher -SizeIs(const SizeMatcher& size_matcher) { +inline internal::SizeIsMatcher SizeIs(const SizeMatcher& size_matcher) { return internal::SizeIsMatcher(size_matcher); } @@ -4135,8 +3838,8 @@ SizeIs(const SizeMatcher& size_matcher) { // do not implement size(). The container must provide const_iterator (with // valid iterator_traits), begin() and end(). template -inline internal::BeginEndDistanceIsMatcher -BeginEndDistanceIs(const DistanceMatcher& distance_matcher) { +inline internal::BeginEndDistanceIsMatcher BeginEndDistanceIs( + const DistanceMatcher& distance_matcher) { return internal::BeginEndDistanceIsMatcher(distance_matcher); } @@ -4146,33 +3849,29 @@ BeginEndDistanceIs(const DistanceMatcher& distance_matcher) { // values and order differences are not explained.) template inline PolymorphicMatcher > - ContainerEq(const Container& rhs) { + GTEST_REMOVE_CONST_(Container)> > +ContainerEq(const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes. typedef GTEST_REMOVE_CONST_(Container) RawContainer; - return MakePolymorphicMatcher( - internal::ContainerEqMatcher(rhs)); + return MakePolymorphicMatcher(internal::ContainerEqMatcher(rhs)); } // Returns a matcher that matches a container that, when sorted using // the given comparator, matches container_matcher. template -inline internal::WhenSortedByMatcher -WhenSortedBy(const Comparator& comparator, - const ContainerMatcher& container_matcher) { - return internal::WhenSortedByMatcher( - comparator, container_matcher); +inline internal::WhenSortedByMatcher WhenSortedBy( + const Comparator& comparator, const ContainerMatcher& container_matcher) { + return internal::WhenSortedByMatcher(comparator, container_matcher); } // Returns a matcher that matches a container that, when sorted using // the < operator, matches container_matcher. template -inline internal::WhenSortedByMatcher -WhenSorted(const ContainerMatcher& container_matcher) { - return - internal::WhenSortedByMatcher( - internal::LessComparator(), container_matcher); +inline internal::WhenSortedByMatcher WhenSorted( + const ContainerMatcher& container_matcher) { + return internal::WhenSortedByMatcher(internal::LessComparator(), + container_matcher); } // Matches an STL-style container or a native array that contains the @@ -4182,23 +3881,21 @@ WhenSorted(const ContainerMatcher& container_matcher) { // T1&, const T2&> >, where T1 and T2 are the types of elements in the // LHS container and the RHS container respectively. template -inline internal::PointwiseMatcher -Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { +inline internal::PointwiseMatcher Pointwise( + const TupleMatcher& tuple_matcher, const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes (e.g. when // rhs is a const int[]).. typedef GTEST_REMOVE_CONST_(Container) RawContainer; - return internal::PointwiseMatcher( - tuple_matcher, rhs); + return internal::PointwiseMatcher(tuple_matcher, rhs); } #if GTEST_HAS_STD_INITIALIZER_LIST_ // Supports the Pointwise(m, {a, b, c}) syntax. template -inline internal::PointwiseMatcher > Pointwise( - const TupleMatcher& tuple_matcher, std::initializer_list rhs) { +inline internal::PointwiseMatcher > Pointwise(const TupleMatcher& tuple_matcher, + std::initializer_list rhs) { return Pointwise(tuple_matcher, std::vector(rhs)); } @@ -4216,12 +3913,9 @@ inline internal::PointwiseMatcher > Pointwise( // This is like Pointwise(pair_matcher, rhs), except that the element // order doesn't matter. template -inline internal::UnorderedElementsAreArrayMatcher< - typename internal::BoundSecondMatcher< - Tuple2Matcher, typename internal::StlContainerView::type::value_type> > -UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, - const RhsContainer& rhs_container) { +inline internal::UnorderedElementsAreArrayMatcher::type::value_type> > +UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, const RhsContainer& rhs_container) { // This following line is for working around a bug in MSVC 8.0, // which causes RhsContainer to be a const type sometimes (e.g. when // rhs_container is a const int[]). @@ -4232,15 +3926,12 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, typedef typename internal::StlContainerView RhsView; typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type Second; - const RhsStlContainer& rhs_stl_container = - RhsView::ConstReference(rhs_container); + const RhsStlContainer& rhs_stl_container = RhsView::ConstReference(rhs_container); // Create a matcher for each element in rhs_container. ::std::vector > matchers; - for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin(); - it != rhs_stl_container.end(); ++it) { - matchers.push_back( - internal::MatcherBindSecond(tuple2_matcher, *it)); + for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin(); it != rhs_stl_container.end(); ++it) { + matchers.push_back(internal::MatcherBindSecond(tuple2_matcher, *it)); } // Delegate the work to UnorderedElementsAreArray(). @@ -4251,10 +3942,8 @@ UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, // Supports the UnorderedPointwise(m, {a, b, c}) syntax. template -inline internal::UnorderedElementsAreArrayMatcher< - typename internal::BoundSecondMatcher > -UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, - std::initializer_list rhs) { +inline internal::UnorderedElementsAreArrayMatcher > +UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, std::initializer_list rhs) { return UnorderedPointwise(tuple2_matcher, std::vector(rhs)); } @@ -4329,10 +4018,9 @@ inline internal::KeyMatcher Key(M inner_matcher) { // to match a std::map that contains exactly one element whose key // is >= 5 and whose value equals "foo". template -inline internal::PairMatcher -Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) { - return internal::PairMatcher( - first_matcher, second_matcher); +inline internal::PairMatcher Pair(FirstMatcher first_matcher, + SecondMatcher second_matcher) { + return internal::PairMatcher(first_matcher, second_matcher); } // Returns a predicate that is satisfied by anything that matches the @@ -4351,8 +4039,7 @@ inline bool Value(const T& value, M matcher) { // Matches the value against the given matcher and explains the match // result to listener. template -inline bool ExplainMatchResult( - M matcher, const T& value, MatchResultListener* listener) { +inline bool ExplainMatchResult(M matcher, const T& value, MatchResultListener* listener) { return SafeMatcherCast(matcher).MatchAndExplain(value, listener); } @@ -4379,16 +4066,18 @@ inline internal::AnyOfMatcher AnyOf(const Args&... matchers) { // // EXPECT_CALL(foo, Bar(_, _)).With(Eq()); template -inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } +inline InnerMatcher AllArgs(const InnerMatcher& matcher) { + return matcher; +} // These macros allow using matchers to check values in Google Test // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) // succeed iff the value matches the matcher. If the assertion fails, // the value and the description of the matcher will be printed. -#define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\ - ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) -#define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ - ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) +#define ASSERT_THAT(value, matcher) \ + ASSERT_PRED_FORMAT1(::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) +#define EXPECT_THAT(value, matcher) \ + EXPECT_PRED_FORMAT1(::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) } // namespace testing diff --git a/src/net/test/gmock/include/gmock/gmock-more-actions.h b/src/net/test/gmock/include/gmock/gmock-more-actions.h index 3d387b6b7d..3d149e0e00 100644 --- a/src/net/test/gmock/include/gmock/gmock-more-actions.h +++ b/src/net/test/gmock/include/gmock/gmock-more-actions.h @@ -53,8 +53,7 @@ class InvokeAction { public: // The c'tor makes a copy of function_impl (either a function // pointer or a functor). - explicit InvokeAction(FunctionImpl function_impl) - : function_impl_(function_impl) {} + explicit InvokeAction(FunctionImpl function_impl) : function_impl_(function_impl) {} template Result Perform(const ArgumentTuple& args) { @@ -71,13 +70,11 @@ class InvokeAction { template class InvokeMethodAction { public: - InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr) - : method_ptr_(method_ptr), obj_ptr_(obj_ptr) {} + InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr) : method_ptr_(method_ptr), obj_ptr_(obj_ptr) {} template Result Perform(const ArgumentTuple& args) const { - return InvokeHelper::InvokeMethod( - obj_ptr_, method_ptr_, args); + return InvokeHelper::InvokeMethod(obj_ptr_, method_ptr_, args); } private: @@ -94,10 +91,8 @@ class InvokeMethodAction { // necessary because Visual Studio deprecates ::std::copy, issuing warning 4996. // However Visual Studio 2010 and later do not honor #pragmas which disable that // warning. -template -inline OutputIterator CopyElements(InputIterator first, - InputIterator last, - OutputIterator output) { +template +inline OutputIterator CopyElements(InputIterator first, InputIterator last, OutputIterator output) { for (; first != last; ++first, ++output) { *output = *first; } @@ -111,19 +106,15 @@ inline OutputIterator CopyElements(InputIterator first, // Creates an action that invokes 'function_impl' with the mock // function's arguments. template -PolymorphicAction > Invoke( - FunctionImpl function_impl) { - return MakePolymorphicAction( - internal::InvokeAction(function_impl)); +PolymorphicAction > Invoke(FunctionImpl function_impl) { + return MakePolymorphicAction(internal::InvokeAction(function_impl)); } // Creates an action that invokes the given method on the given object // with the mock function's arguments. template -PolymorphicAction > Invoke( - Class* obj_ptr, MethodPtr method_ptr) { - return MakePolymorphicAction( - internal::InvokeMethodAction(obj_ptr, method_ptr)); +PolymorphicAction > Invoke(Class* obj_ptr, MethodPtr method_ptr) { + return MakePolymorphicAction(internal::InvokeMethodAction(obj_ptr, method_ptr)); } // WithoutArgs(inner_action) can be used in a mock function with a @@ -131,8 +122,7 @@ PolymorphicAction > Invoke( // argument. In other words, it adapts an action accepting no // argument to one that accepts (and ignores) arguments. template -inline internal::WithArgsAction -WithoutArgs(const InnerAction& action) { +inline internal::WithArgsAction WithoutArgs(const InnerAction& action) { return internal::WithArgsAction(action); } @@ -142,8 +132,7 @@ WithoutArgs(const InnerAction& action) { // multiple arguments. For convenience, we also provide // WithArgs(an_action) (defined below) as a synonym. template -inline internal::WithArgsAction -WithArg(const InnerAction& action) { +inline internal::WithArgsAction WithArg(const InnerAction& action) { return internal::WithArgsAction(action); } @@ -153,44 +142,33 @@ WithArg(const InnerAction& action) { // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4100) +# pragma warning(push) +# pragma warning(disable : 4100) #endif // Action ReturnArg() returns the k-th argument of the mock function. -ACTION_TEMPLATE(ReturnArg, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { - return ::testing::get(args); -} +ACTION_TEMPLATE(ReturnArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { return ::testing::get(args); } // Action SaveArg(pointer) saves the k-th (0-based) argument of the // mock function to *pointer. -ACTION_TEMPLATE(SaveArg, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(pointer)) { +ACTION_TEMPLATE(SaveArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(pointer)) { *pointer = ::testing::get(args); } // Action SaveArgPointee(pointer) saves the value pointed to // by the k-th (0-based) argument of the mock function to *pointer. -ACTION_TEMPLATE(SaveArgPointee, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(pointer)) { +ACTION_TEMPLATE(SaveArgPointee, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(pointer)) { *pointer = *::testing::get(args); } // Action SetArgReferee(value) assigns 'value' to the variable // referenced by the k-th (0-based) argument of the mock function. -ACTION_TEMPLATE(SetArgReferee, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_1_VALUE_PARAMS(value)) { +ACTION_TEMPLATE(SetArgReferee, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(value)) { typedef typename ::testing::tuple_element::type argk_type; // Ensures that argument #k is a reference. If you get a compiler // error on the next line, you are using SetArgReferee(value) in // a mock function whose k-th (0-based) argument is not a reference. - GTEST_COMPILE_ASSERT_(internal::is_reference::value, - SetArgReferee_must_be_used_with_a_reference_argument); + GTEST_COMPILE_ASSERT_(internal::is_reference::value, SetArgReferee_must_be_used_with_a_reference_argument); ::testing::get(args) = value; } @@ -199,9 +177,7 @@ ACTION_TEMPLATE(SetArgReferee, // (0-based) argument, which can be either a pointer or an // iterator. The action does not take ownership of the elements in the // source range. -ACTION_TEMPLATE(SetArrayArgument, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_2_VALUE_PARAMS(first, last)) { +ACTION_TEMPLATE(SetArrayArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_2_VALUE_PARAMS(first, last)) { // Visual Studio deprecates ::std::copy, so we use our own copy in that case. #ifdef _MSC_VER internal::CopyElements(first, last, ::testing::get(args)); @@ -212,11 +188,7 @@ ACTION_TEMPLATE(SetArrayArgument, // Action DeleteArg() deletes the k-th (0-based) argument of the mock // function. -ACTION_TEMPLATE(DeleteArg, - HAS_1_TEMPLATE_PARAMS(int, k), - AND_0_VALUE_PARAMS()) { - delete ::testing::get(args); -} +ACTION_TEMPLATE(DeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { delete ::testing::get(args); } // This action returns the value pointed to by 'pointer'. ACTION_P(ReturnPointee, pointer) { return *pointer; } @@ -226,19 +198,19 @@ ACTION_P(ReturnPointee, pointer) { return *pointer; } #if GTEST_HAS_EXCEPTIONS // Suppresses the 'unreachable code' warning that VC generates in opt modes. -# ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4702) // Temporarily disables warning 4702. -# endif +# ifdef _MSC_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable : 4702) // Temporarily disables warning 4702. +# endif ACTION_P(Throw, exception) { throw exception; } -# ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -# endif +# ifdef _MSC_VER +# pragma warning(pop) // Restores the warning state. +# endif #endif // GTEST_HAS_EXCEPTIONS #ifdef _MSC_VER -# pragma warning(pop) +# pragma warning(pop) #endif } // namespace testing diff --git a/src/net/test/gmock/include/gmock/gmock-spec-builders.h b/src/net/test/gmock/include/gmock/gmock-spec-builders.h index fed7de66bc..bc2b4b6399 100644 --- a/src/net/test/gmock/include/gmock/gmock-spec-builders.h +++ b/src/net/test/gmock/include/gmock/gmock-spec-builders.h @@ -67,7 +67,7 @@ #include #if GTEST_HAS_EXCEPTIONS -# include // NOLINT +# include // NOLINT #endif #include "gmock/gmock-actions.h" @@ -90,19 +90,22 @@ class ExpectationSet; namespace internal { // Implements a mock function. -template class FunctionMocker; +template +class FunctionMocker; // Base class for expectations. class ExpectationBase; // Implements an expectation. -template class TypedExpectation; +template +class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; // Base class for function mockers. -template class FunctionMockerBase; +template +class FunctionMockerBase; // Protects the mock object registry (in class Mock), all function // mockers, and all expectations. @@ -131,12 +134,10 @@ class GTEST_API_ UntypedFunctionMockerBase { // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. - bool VerifyAndClearExpectationsLocked() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + bool VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Clears the ON_CALL()s set on this mock function. - virtual void ClearDefaultActionsLocked() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0; + virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0; // In all of the following Untyped* functions, it's the caller's // responsibility to guarantee the correctness of the arguments' @@ -147,24 +148,20 @@ class GTEST_API_ UntypedFunctionMockerBase { // the error message to describe the call in the case the default // action fails. // L = * - virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( - const void* untyped_args, - const string& call_description) const = 0; + virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(const void* untyped_args, + const string& call_description) const = 0; // Performs the given action with the given arguments and returns // the action's result. // L = * - virtual UntypedActionResultHolderBase* UntypedPerformAction( - const void* untyped_action, - const void* untyped_args) const = 0; + virtual UntypedActionResultHolderBase* UntypedPerformAction(const void* untyped_action, + const void* untyped_args) const = 0; // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. - virtual void UntypedDescribeUninterestingCall( - const void* untyped_args, - ::std::ostream* os) const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + virtual void UntypedDescribeUninterestingCall(const void* untyped_args, ::std::ostream* os) const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Returns the expectation that matches the given function arguments // (or NULL is there's no match); when a match is found, @@ -172,54 +169,45 @@ class GTEST_API_ UntypedFunctionMockerBase { // performed (or NULL if the action is "do default"), and // is_excessive is modified to indicate whether the call exceeds the // expected number. - virtual const ExpectationBase* UntypedFindMatchingExpectation( - const void* untyped_args, - const void** untyped_action, bool* is_excessive, - ::std::ostream* what, ::std::ostream* why) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; + virtual const ExpectationBase* UntypedFindMatchingExpectation(const void* untyped_args, const void** untyped_action, + bool* is_excessive, ::std::ostream* what, + ::std::ostream* why) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Prints the given function arguments to the ostream. - virtual void UntypedPrintArgs(const void* untyped_args, - ::std::ostream* os) const = 0; + virtual void UntypedPrintArgs(const void* untyped_args, ::std::ostream* os) const = 0; // Sets the mock object this mock method belongs to, and registers // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. // TODO(wan@google.com): rename to SetAndRegisterOwner(). - void RegisterOwner(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Sets the mock object this mock method belongs to, and sets the // name of the mock function. Will be called upon each invocation // of this mock function. - void SetOwnerAndName(const void* mock_obj, const char* name) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + void SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the mock object this mock method belongs to. Must be // called after RegisterOwner() or SetOwnerAndName() has been // called. - const void* MockObject() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. - const char* Name() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple // threads concurrently. The caller is responsible for deleting the // result. - UntypedActionResultHolderBase* UntypedInvokeWith( - const void* untyped_args) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex); + UntypedActionResultHolderBase* UntypedInvokeWith(const void* untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector UntypedOnCallSpecs; - typedef std::vector > - UntypedExpectations; + typedef std::vector > UntypedExpectations; // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. @@ -245,8 +233,7 @@ class GTEST_API_ UntypedFunctionMockerBase { class UntypedOnCallSpecBase { public: // The arguments are the location of the ON_CALL() statement. - UntypedOnCallSpecBase(const char* a_file, int a_line) - : file_(a_file), line_(a_line), last_clause_(kNone) {} + UntypedOnCallSpecBase(const char* a_file, int a_line) : file_(a_file), line_(a_line), last_clause_(kNone) {} // Where in the source file was the default action spec defined? const char* file() const { return file_; } @@ -289,16 +276,14 @@ class OnCallSpec : public UntypedOnCallSpecBase { // Constructs an OnCallSpec object from the information inside // the parenthesis of an ON_CALL() statement. - OnCallSpec(const char* a_file, int a_line, - const ArgumentMatcherTuple& matchers) + OnCallSpec(const char* a_file, int a_line, const ArgumentMatcherTuple& matchers) : UntypedOnCallSpecBase(a_file, a_line), matchers_(matchers), // By default, extra_matcher_ should match anything. However, // we cannot initialize it with _ as that triggers a compiler // bug in Symbian's C++ compiler (cannot decide between two // overloaded constructors of Matcher). - extra_matcher_(A()) { - } + extra_matcher_(A()) {} // Implements the .With() clause. OnCallSpec& With(const Matcher& m) { @@ -319,8 +304,7 @@ class OnCallSpec : public UntypedOnCallSpecBase { "exactly once in an ON_CALL()."); last_clause_ = kWillByDefault; - ExpectSpecProperty(!action.IsDoDefault(), - "DoDefault() cannot be used in ON_CALL()."); + ExpectSpecProperty(!action.IsDoDefault(), "DoDefault() cannot be used in ON_CALL()."); action_ = action; return *this; } @@ -374,20 +358,17 @@ class GTEST_API_ Mock { // Tells Google Mock to ignore mock_obj when checking for leaked // mock objects. - static void AllowLeak(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies and clears all expectations on the given mock object. // If the expectations aren't satisfied, generates one or more // Google Test non-fatal failures and returns false. - static bool VerifyAndClearExpectations(void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static bool VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies all expectations on the given mock object and clears its // default actions and expectations. Returns true iff the // verification was successful. - static bool VerifyAndClear(void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static bool VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); private: friend class internal::UntypedFunctionMockerBase; @@ -408,52 +389,42 @@ class GTEST_API_ Mock { // Tells Google Mock to allow uninteresting calls on the given mock // object. - static void AllowUninterestingCalls(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void AllowUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to warn the user about uninteresting calls on // the given mock object. - static void WarnUninterestingCalls(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void WarnUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to fail uninteresting calls on the given mock // object. - static void FailUninterestingCalls(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void FailUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock the given mock object is being destroyed and // its entry in the call-reaction table should be removed. - static void UnregisterCallReaction(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void UnregisterCallReaction(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. - static internal::CallReaction GetReactionOnUninterestingCalls( - const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static internal::CallReaction GetReactionOnUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies that all expectations on the given mock object have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. - static bool VerifyAndClearExpectationsLocked(void* mock_obj) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); + static bool VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Clears all ON_CALL()s set on the given mock object. - static void ClearDefaultActionsLocked(void* mock_obj) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); + static void ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Registers a mock object and a mock method it owns. - static void Register( - const void* mock_obj, - internal::UntypedFunctionMockerBase* mocker) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. - static void RegisterUseByOnCallOrExpectCall( - const void* mock_obj, const char* file, int line) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); + static void RegisterUseByOnCallOrExpectCall(const void* mock_obj, const char* file, int line) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Unregisters a mock method; removes the owning mock object from // the registry when the last mock method associated with it has @@ -506,9 +477,7 @@ class GTEST_API_ Expectation { // intended, so we don't need to define our own. // Returns true iff rhs references the same expectation as this object does. - bool operator==(const Expectation& rhs) const { - return expectation_base_ == rhs.expectation_base_; - } + bool operator==(const Expectation& rhs) const { return expectation_base_ == rhs.expectation_base_; } bool operator!=(const Expectation& rhs) const { return !(*this == rhs); } @@ -534,14 +503,10 @@ class GTEST_API_ Expectation { typedef ::std::set Set; - Expectation( - const internal::linked_ptr& expectation_base); + Expectation(const internal::linked_ptr& expectation_base); // Returns the expectation this object references. - const internal::linked_ptr& - expectation_base() const { - return expectation_base_; - } + const internal::linked_ptr& expectation_base() const { return expectation_base_; } // A linked_ptr that co-owns the expectation this handle references. internal::linked_ptr expectation_base_; @@ -590,9 +555,7 @@ class ExpectationSet { // Returns true iff rhs contains the same set of Expectation objects // as this does. - bool operator==(const ExpectationSet& rhs) const { - return expectations_ == rhs.expectations_; - } + bool operator==(const ExpectationSet& rhs) const { return expectations_ == rhs.expectations_; } bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); } @@ -612,7 +575,6 @@ class ExpectationSet { Expectation::Set expectations_; }; - // Sequence objects are used by a user to specify the relative order // in which the expectations should match. They are copyable (we rely // on the compiler-defined copy constructor and assignment operator). @@ -661,6 +623,7 @@ class GTEST_API_ InSequence { public: InSequence(); ~InSequence(); + private: bool sequence_created_; @@ -702,14 +665,11 @@ class GTEST_API_ ExpectationBase { const Cardinality& cardinality() const { return cardinality_; } // Describes the source file location of this expectation. - void DescribeLocationTo(::std::ostream* os) const { - *os << FormatFileLocation(file(), line()) << " "; - } + void DescribeLocationTo(::std::ostream* os) const { *os << FormatFileLocation(file(), line()) << " "; } // Describes how many times a function call matching this // expectation has occurred. - void DescribeCallCountTo(::std::ostream* os) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + void DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // If this mock method has an extra matcher (i.e. .With(matcher)), // describes it to the ostream. @@ -756,71 +716,59 @@ class GTEST_API_ ExpectationBase { bool cardinality_specified() const { return cardinality_specified_; } // Sets the cardinality of this expectation spec. - void set_cardinality(const Cardinality& a_cardinality) { - cardinality_ = a_cardinality; - } + void set_cardinality(const Cardinality& a_cardinality) { cardinality_ = a_cardinality; } // The following group of methods should only be called after the // EXPECT_CALL() statement, and only when g_gmock_mutex is held by // the current thread. // Retires all pre-requisites of this expectation. - void RetireAllPreRequisites() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns true iff this expectation is retired. - bool is_retired() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return retired_; } // Retires this expectation. - void Retire() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); retired_ = true; } // Returns true iff this expectation is satisfied. - bool IsSatisfied() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } // Returns true iff this expectation is saturated. - bool IsSaturated() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } // Returns true iff this expectation is over-saturated. - bool IsOverSaturated() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } // Returns true iff all pre-requisites of this expectation are satisfied. - bool AllPrerequisitesAreSatisfied() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Adds unsatisfied pre-requisites of this expectation to 'result'. - void FindUnsatisfiedPrerequisites(ExpectationSet* result) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); + void FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns the number this expectation has been invoked. - int call_count() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return call_count_; } // Increments the number this expectation has been invoked. - void IncrementCallCount() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); call_count_++; } @@ -829,8 +777,7 @@ class GTEST_API_ ExpectationBase { // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. - void CheckActionCountIfNotDone() const - GTEST_LOCK_EXCLUDED_(mutex_); + void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_); friend class ::testing::Sequence; friend class ::testing::internal::ExpectationTester; @@ -848,7 +795,7 @@ class GTEST_API_ ExpectationBase { const string source_text_; // The EXPECT_CALL(...) source text. // True iff the cardinality is specified explicitly. bool cardinality_specified_; - Cardinality cardinality_; // The cardinality of the expectation. + Cardinality cardinality_; // The cardinality of the expectation. // The immediate pre-requisites (i.e. expectations that must be // satisfied before this expectation can be matched) of this // expectation. We use linked_ptr in the set because we want an @@ -867,7 +814,7 @@ class GTEST_API_ ExpectationBase { bool retires_on_saturation_; Clause last_clause_; mutable bool action_count_checked_; // Under mutex_. - mutable Mutex mutex_; // Protects action_count_checked_. + mutable Mutex mutex_; // Protects action_count_checked_. GTEST_DISALLOW_ASSIGN_(ExpectationBase); }; // class ExpectationBase @@ -880,8 +827,7 @@ class TypedExpectation : public ExpectationBase { typedef typename Function::ArgumentMatcherTuple ArgumentMatcherTuple; typedef typename Function::Result Result; - TypedExpectation(FunctionMockerBase* owner, - const char* a_file, int a_line, const string& a_source_text, + TypedExpectation(FunctionMockerBase* owner, const char* a_file, int a_line, const string& a_source_text, const ArgumentMatcherTuple& m) : ExpectationBase(a_file, a_line, a_source_text), owner_(owner), @@ -897,8 +843,7 @@ class TypedExpectation : public ExpectationBase { // Check the validity of the action count if it hasn't been done // yet (for example, if the expectation was never used). CheckActionCountIfNotDone(); - for (UntypedActions::const_iterator it = untyped_actions_.begin(); - it != untyped_actions_.end(); ++it) { + for (UntypedActions::const_iterator it = untyped_actions_.begin(); it != untyped_actions_.end(); ++it) { delete static_cast*>(*it); } } @@ -928,9 +873,7 @@ class TypedExpectation : public ExpectationBase { } // Implements the .Times() clause. - TypedExpectation& Times(int n) { - return Times(Exactly(n)); - } + TypedExpectation& Times(int n) { return Times(Exactly(n)); } // Implements the .InSequence() clause. TypedExpectation& InSequence(const Sequence& s) { @@ -943,19 +886,14 @@ class TypedExpectation : public ExpectationBase { s.AddExpectation(GetHandle()); return *this; } - TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) { - return InSequence(s1).InSequence(s2); - } - TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, - const Sequence& s3) { + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) { return InSequence(s1).InSequence(s2); } + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3) { return InSequence(s1, s2).InSequence(s3); } - TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, - const Sequence& s3, const Sequence& s4) { + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3, const Sequence& s4) { return InSequence(s1, s2, s3).InSequence(s4); } - TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, - const Sequence& s3, const Sequence& s4, + TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3, const Sequence& s4, const Sequence& s5) { return InSequence(s1, s2, s3, s4).InSequence(s5); } @@ -973,20 +911,16 @@ class TypedExpectation : public ExpectationBase { } return *this; } - TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) { - return After(s1).After(s2); - } - TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, - const ExpectationSet& s3) { + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) { return After(s1).After(s2); } + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3) { return After(s1, s2).After(s3); } - TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, - const ExpectationSet& s3, const ExpectationSet& s4) { + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3, + const ExpectationSet& s4) { return After(s1, s2, s3).After(s4); } - TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, - const ExpectationSet& s3, const ExpectationSet& s4, - const ExpectationSet& s5) { + TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3, + const ExpectationSet& s4, const ExpectationSet& s5) { return After(s1, s2, s3, s4).After(s5); } @@ -1045,14 +979,10 @@ class TypedExpectation : public ExpectationBase { // Returns the matchers for the arguments as specified inside the // EXPECT_CALL() macro. - const ArgumentMatcherTuple& matchers() const { - return matchers_; - } + const ArgumentMatcherTuple& matchers() const { return matchers_; } // Returns the matcher specified by the .With() clause. - const Matcher& extra_matcher() const { - return extra_matcher_; - } + const Matcher& extra_matcher() const { return extra_matcher_; } // Returns the action specified by the .WillRepeatedly() clause. const Action& repeated_action() const { return repeated_action_; } @@ -1073,24 +1003,20 @@ class TypedExpectation : public ExpectationBase { // Returns an Expectation object that references and co-owns this // expectation. - virtual Expectation GetHandle() { - return owner_->GetHandleOf(this); - } + virtual Expectation GetHandle() { return owner_->GetHandleOf(this); } // The following methods will be called only after the EXPECT_CALL() // statement finishes and when the current thread holds // g_gmock_mutex. // Returns true iff this expectation matches the given arguments. - bool Matches(const ArgumentTuple& args) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool Matches(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } // Returns true iff this expectation should handle the given arguments. - bool ShouldHandleArguments(const ArgumentTuple& args) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + bool ShouldHandleArguments(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // In case the action count wasn't checked when the expectation @@ -1103,10 +1029,8 @@ class TypedExpectation : public ExpectationBase { // Describes the result of matching the arguments against this // expectation to the given ostream. - void ExplainMatchResultTo( - const ArgumentTuple& args, - ::std::ostream* os) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (is_retired()) { @@ -1132,8 +1056,7 @@ class TypedExpectation : public ExpectationBase { ExpectationSet unsatisfied_prereqs; FindUnsatisfiedPrerequisites(&unsatisfied_prereqs); int i = 0; - for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin(); - it != unsatisfied_prereqs.end(); ++it) { + for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin(); it != unsatisfied_prereqs.end(); ++it) { it->expectation_base()->DescribeLocationTo(os); *os << "pre-requisite #" << i++ << "\n"; } @@ -1148,10 +1071,8 @@ class TypedExpectation : public ExpectationBase { } // Returns the action that should be taken for the current invocation. - const Action& GetCurrentAction( - const FunctionMockerBase* mocker, - const ArgumentTuple& args) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + const Action& GetCurrentAction(const FunctionMockerBase* mocker, const ArgumentTuple& args) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const int count = call_count(); Assert(count >= 1, __FILE__, __LINE__, @@ -1159,23 +1080,19 @@ class TypedExpectation : public ExpectationBase { "called - this should never happen."); const int action_count = static_cast(untyped_actions_.size()); - if (action_count > 0 && !repeated_action_specified_ && - count > action_count) { + if (action_count > 0 && !repeated_action_specified_ && count > action_count) { // If there is at least one WillOnce() and no WillRepeatedly(), // we warn the user when the WillOnce() clauses ran out. ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Actions ran out in " << source_text() << "...\n" - << "Called " << count << " times, but only " - << action_count << " WillOnce()" + << "Called " << count << " times, but only " << action_count << " WillOnce()" << (action_count == 1 ? " is" : "s are") << " specified - "; mocker->DescribeDefaultActionTo(args, &ss); Log(kWarning, ss.str(), 1); } - return count <= action_count ? - *static_cast*>(untyped_actions_[count - 1]) : - repeated_action(); + return count <= action_count ? *static_cast*>(untyped_actions_[count - 1]) : repeated_action(); } // Given the arguments of a mock function call, if the call will @@ -1185,12 +1102,9 @@ class TypedExpectation : public ExpectationBase { // Mock does it to 'why'. This method is not const as it calls // IncrementCallCount(). A return value of NULL means the default // action. - const Action* GetActionForArguments( - const FunctionMockerBase* mocker, - const ArgumentTuple& args, - ::std::ostream* what, - ::std::ostream* why) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + const Action* GetActionForArguments(const FunctionMockerBase* mocker, const ArgumentTuple& args, + ::std::ostream* what, ::std::ostream* why) + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (IsSaturated()) { // We have an excessive call. @@ -1213,7 +1127,7 @@ class TypedExpectation : public ExpectationBase { } // Must be done after IncrementCount()! - *what << "Mock function call matches " << source_text() <<"...\n"; + *what << "Mock function call matches " << source_text() << "...\n"; return &(GetCurrentAction(mocker, args)); } @@ -1238,48 +1152,39 @@ class TypedExpectation : public ExpectationBase { // ::testing::internal and import it into ::testing. // Logs a message including file and line number information. -GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, - const char* file, int line, +GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const string& message); template class MockSpec { public: typedef typename internal::Function::ArgumentTuple ArgumentTuple; - typedef typename internal::Function::ArgumentMatcherTuple - ArgumentMatcherTuple; + typedef typename internal::Function::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. - explicit MockSpec(internal::FunctionMockerBase* function_mocker) - : function_mocker_(function_mocker) {} + explicit MockSpec(internal::FunctionMockerBase* function_mocker) : function_mocker_(function_mocker) {} // Adds a new default action spec to the function mocker and returns // the newly created spec. - internal::OnCallSpec& InternalDefaultActionSetAt( - const char* file, int line, const char* obj, const char* call) { - LogWithLocation(internal::kInfo, file, line, - string("ON_CALL(") + obj + ", " + call + ") invoked"); + internal::OnCallSpec& InternalDefaultActionSetAt(const char* file, int line, const char* obj, const char* call) { + LogWithLocation(internal::kInfo, file, line, string("ON_CALL(") + obj + ", " + call + ") invoked"); return function_mocker_->AddNewOnCallSpec(file, line, matchers_); } // Adds a new expectation spec to the function mocker and returns // the newly created spec. - internal::TypedExpectation& InternalExpectedAt( - const char* file, int line, const char* obj, const char* call) { + internal::TypedExpectation& InternalExpectedAt(const char* file, int line, const char* obj, const char* call) { const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); - return function_mocker_->AddNewExpectation( - file, line, source_text, matchers_); + return function_mocker_->AddNewExpectation(file, line, source_text, matchers_); } private: template friend class internal::FunctionMocker; - void SetMatchers(const ArgumentMatcherTuple& matchers) { - matchers_ = matchers; - } + void SetMatchers(const ArgumentMatcherTuple& matchers) { matchers_ = matchers; } // The function mocker that owns this spec. internal::FunctionMockerBase* const function_mocker_; @@ -1302,9 +1207,7 @@ template class ReferenceOrValueWrapper { public: // Constructs a wrapper from the given value/reference. - explicit ReferenceOrValueWrapper(T value) - : value_(::testing::internal::move(value)) { - } + explicit ReferenceOrValueWrapper(T value) : value_(::testing::internal::move(value)) {} // Unwraps and returns the underlying value/reference, exactly as // originally passed. The behavior of calling this more than once on @@ -1315,9 +1218,7 @@ class ReferenceOrValueWrapper { // Always returns a const reference (more precisely, // const RemoveReference&). The behavior of calling this after // calling Unwrap on the same object is unspecified. - const T& Peek() const { - return value_; - } + const T& Peek() const { return value_; } private: T value_; @@ -1331,8 +1232,7 @@ class ReferenceOrValueWrapper { // Workaround for debatable pass-by-reference lint warning (c-library-team // policy precludes NOLINT in this context) typedef T& reference; - explicit ReferenceOrValueWrapper(reference ref) - : value_ptr_(&ref) {} + explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {} T& Unwrap() { return *value_ptr_; } const T& Peek() const { return *value_ptr_; } @@ -1346,9 +1246,9 @@ class ReferenceOrValueWrapper { // the constructor only. #ifdef _MSC_VER -# pragma warning(push) // Saves the current warning state. -# pragma warning(disable:4355) // Temporarily disables warning 4355. -#endif // _MSV_VER +# pragma warning(push) // Saves the current warning state. +# pragma warning(disable : 4355) // Temporarily disables warning 4355. +#endif // _MSV_VER // C++ treats the void type specially. For example, you cannot define // a void-typed variable or pass a void value to a function. @@ -1372,9 +1272,7 @@ template class ActionResultHolder : public UntypedActionResultHolderBase { public: // Returns the held value. Must not be called more than once. - T Unwrap() { - return result_.Unwrap(); - } + T Unwrap() { return result_.Unwrap(); } // Prints the held value as an action's result to os. virtual void PrintAsActionResult(::std::ostream* os) const { @@ -1386,29 +1284,23 @@ class ActionResultHolder : public UntypedActionResultHolderBase { // Performs the given mock function's default action and returns the // result in a new-ed ActionResultHolder. template - static ActionResultHolder* PerformDefaultAction( - const FunctionMockerBase* func_mocker, - const typename Function::ArgumentTuple& args, - const string& call_description) { - return new ActionResultHolder(Wrapper( - func_mocker->PerformDefaultAction(args, call_description))); + static ActionResultHolder* PerformDefaultAction(const FunctionMockerBase* func_mocker, + const typename Function::ArgumentTuple& args, + const string& call_description) { + return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(args, call_description))); } // Performs the given action and returns the result in a new-ed // ActionResultHolder. template - static ActionResultHolder* - PerformAction(const Action& action, - const typename Function::ArgumentTuple& args) { + static ActionResultHolder* PerformAction(const Action& action, const typename Function::ArgumentTuple& args) { return new ActionResultHolder(Wrapper(action.Perform(args))); } private: typedef ReferenceOrValueWrapper Wrapper; - explicit ActionResultHolder(Wrapper result) - : result_(::testing::internal::move(result)) { - } + explicit ActionResultHolder(Wrapper result) : result_(::testing::internal::move(result)) {} Wrapper result_; @@ -1419,17 +1311,16 @@ class ActionResultHolder : public UntypedActionResultHolderBase { template <> class ActionResultHolder : public UntypedActionResultHolderBase { public: - void Unwrap() { } + void Unwrap() {} virtual void PrintAsActionResult(::std::ostream* /* os */) const {} // Performs the given mock function's default action and returns ownership // of an empty ActionResultHolder*. template - static ActionResultHolder* PerformDefaultAction( - const FunctionMockerBase* func_mocker, - const typename Function::ArgumentTuple& args, - const string& call_description) { + static ActionResultHolder* PerformDefaultAction(const FunctionMockerBase* func_mocker, + const typename Function::ArgumentTuple& args, + const string& call_description) { func_mocker->PerformDefaultAction(args, call_description); return new ActionResultHolder; } @@ -1437,9 +1328,7 @@ class ActionResultHolder : public UntypedActionResultHolderBase { // Performs the given action and returns ownership of an empty // ActionResultHolder*. template - static ActionResultHolder* PerformAction( - const Action& action, - const typename Function::ArgumentTuple& args) { + static ActionResultHolder* PerformAction(const Action& action, const typename Function::ArgumentTuple& args) { action.Perform(args); return new ActionResultHolder; } @@ -1464,8 +1353,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // The destructor verifies that all expectations on this mock // function have been satisfied. If not, it will report Google Test // non-fatal failures for the violations. - virtual ~FunctionMockerBase() - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + virtual ~FunctionMockerBase() GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { MutexLock l(&g_gmock_mutex); VerifyAndClearExpectationsLocked(); Mock::UnregisterLocked(this); @@ -1475,14 +1363,11 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // Returns the ON_CALL spec that matches this mock function with the // given arguments; returns NULL if no matching ON_CALL is found. // L = * - const OnCallSpec* FindOnCallSpec( - const ArgumentTuple& args) const { - for (UntypedOnCallSpecs::const_reverse_iterator it - = untyped_on_call_specs_.rbegin(); + const OnCallSpec* FindOnCallSpec(const ArgumentTuple& args) const { + for (UntypedOnCallSpecs::const_reverse_iterator it = untyped_on_call_specs_.rbegin(); it != untyped_on_call_specs_.rend(); ++it) { const OnCallSpec* spec = static_cast*>(*it); - if (spec->Matches(args)) - return spec; + if (spec->Matches(args)) return spec; } return NULL; @@ -1495,16 +1380,14 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // mutable state of this object, and thus can be called concurrently // without locking. // L = * - Result PerformDefaultAction(const ArgumentTuple& args, - const string& call_description) const { - const OnCallSpec* const spec = - this->FindOnCallSpec(args); + Result PerformDefaultAction(const ArgumentTuple& args, const string& call_description) const { + const OnCallSpec* const spec = this->FindOnCallSpec(args); if (spec != NULL) { return spec->GetAction().Perform(args); } const string message = call_description + - "\n The mock function has no default action " - "set, and its return type has no default value set."; + "\n The mock function has no default action " + "set, and its return type has no default value set."; #if GTEST_HAS_EXCEPTIONS if (!DefaultValue::Exists()) { throw std::runtime_error(message); @@ -1523,8 +1406,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( const void* untyped_args, // must point to an ArgumentTuple const string& call_description) const { - const ArgumentTuple& args = - *static_cast(untyped_args); + const ArgumentTuple& args = *static_cast(untyped_args); return ResultHolder::PerformDefaultAction(this, args, call_description); } @@ -1532,20 +1414,18 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // the action's result. The caller is responsible for deleting the // result. // L = * - virtual UntypedActionResultHolderBase* UntypedPerformAction( - const void* untyped_action, const void* untyped_args) const { + virtual UntypedActionResultHolderBase* UntypedPerformAction(const void* untyped_action, + const void* untyped_args) const { // Make a copy of the action before performing it, in case the // action deletes the mock object (and thus deletes itself). const Action action = *static_cast*>(untyped_action); - const ArgumentTuple& args = - *static_cast(untyped_args); + const ArgumentTuple& args = *static_cast(untyped_args); return ResultHolder::PerformAction(action, args); } // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): // clears the ON_CALL()s set on this mock function. - virtual void ClearDefaultActionsLocked() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // Deleting our default actions may trigger other mock objects to be @@ -1559,9 +1439,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { untyped_on_call_specs_.swap(specs_to_delete); g_gmock_mutex.Unlock(); - for (UntypedOnCallSpecs::const_iterator it = - specs_to_delete.begin(); - it != specs_to_delete.end(); ++it) { + for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin(); it != specs_to_delete.end(); ++it) { delete static_cast*>(*it); } @@ -1579,18 +1457,14 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple // threads concurrently. - Result InvokeWith(const ArgumentTuple& args) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { - scoped_ptr holder( - DownCast_(this->UntypedInvokeWith(&args))); + Result InvokeWith(const ArgumentTuple& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + scoped_ptr holder(DownCast_(this->UntypedInvokeWith(&args))); return holder->Unwrap(); } // Adds and returns a default action spec for this mock function. - OnCallSpec& AddNewOnCallSpec( - const char* file, int line, - const ArgumentMatcherTuple& m) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + OnCallSpec& AddNewOnCallSpec(const char* file, int line, const ArgumentMatcherTuple& m) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); OnCallSpec* const on_call_spec = new OnCallSpec(file, line, m); untyped_on_call_specs_.push_back(on_call_spec); @@ -1598,15 +1472,10 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { } // Adds and returns an expectation spec for this mock function. - TypedExpectation& AddNewExpectation( - const char* file, - int line, - const string& source_text, - const ArgumentMatcherTuple& m) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + TypedExpectation& AddNewExpectation(const char* file, int line, const string& source_text, + const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); - TypedExpectation* const expectation = - new TypedExpectation(this, file, line, source_text, m); + TypedExpectation* const expectation = new TypedExpectation(this, file, line, source_text, m); const linked_ptr untyped_expectation(expectation); untyped_expectations_.push_back(untyped_expectation); @@ -1624,36 +1493,30 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { MockSpec& current_spec() { return current_spec_; } private: - template friend class TypedExpectation; + template + friend class TypedExpectation; // Some utilities needed for implementing UntypedInvokeWith(). // Describes what default action will be performed for the given // arguments. // L = * - void DescribeDefaultActionTo(const ArgumentTuple& args, - ::std::ostream* os) const { + void DescribeDefaultActionTo(const ArgumentTuple& args, ::std::ostream* os) const { const OnCallSpec* const spec = FindOnCallSpec(args); if (spec == NULL) { - *os << (internal::type_equals::value ? - "returning directly.\n" : - "returning default value.\n"); + *os << (internal::type_equals::value ? "returning directly.\n" : "returning default value.\n"); } else { - *os << "taking default action specified at:\n" - << FormatFileLocation(spec->file(), spec->line()) << "\n"; + *os << "taking default action specified at:\n" << FormatFileLocation(spec->file(), spec->line()) << "\n"; } } // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. - virtual void UntypedDescribeUninterestingCall( - const void* untyped_args, - ::std::ostream* os) const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { - const ArgumentTuple& args = - *static_cast(untyped_args); + virtual void UntypedDescribeUninterestingCall(const void* untyped_args, ::std::ostream* os) const + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + const ArgumentTuple& args = *static_cast(untyped_args); *os << "Uninteresting mock function call - "; DescribeDefaultActionTo(args, os); *os << " Function call: " << Name(); @@ -1676,13 +1539,11 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // section. The reason is that we have no control on what the // action does (it can invoke an arbitrary user function or even a // mock function) and excessive locking could cause a dead lock. - virtual const ExpectationBase* UntypedFindMatchingExpectation( - const void* untyped_args, - const void** untyped_action, bool* is_excessive, - ::std::ostream* what, ::std::ostream* why) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { - const ArgumentTuple& args = - *static_cast(untyped_args); + virtual const ExpectationBase* UntypedFindMatchingExpectation(const void* untyped_args, const void** untyped_action, + bool* is_excessive, ::std::ostream* what, + ::std::ostream* why) + GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { + const ArgumentTuple& args = *static_cast(untyped_args); MutexLock l(&g_gmock_mutex); TypedExpectation* exp = this->FindMatchingExpectationLocked(args); if (exp == NULL) { // A match wasn't found. @@ -1695,31 +1556,25 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // its saturation status. *is_excessive = exp->IsSaturated(); const Action* action = exp->GetActionForArguments(this, args, what, why); - if (action != NULL && action->IsDoDefault()) - action = NULL; // Normalize "do default" to NULL. + if (action != NULL && action->IsDoDefault()) action = NULL; // Normalize "do default" to NULL. *untyped_action = action; return exp; } // Prints the given function arguments to the ostream. - virtual void UntypedPrintArgs(const void* untyped_args, - ::std::ostream* os) const { - const ArgumentTuple& args = - *static_cast(untyped_args); + virtual void UntypedPrintArgs(const void* untyped_args, ::std::ostream* os) const { + const ArgumentTuple& args = *static_cast(untyped_args); UniversalPrint(args, os); } // Returns the expectation that matches the arguments, or NULL if no // expectation matches them. - TypedExpectation* FindMatchingExpectationLocked( - const ArgumentTuple& args) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + TypedExpectation* FindMatchingExpectationLocked(const ArgumentTuple& args) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - for (typename UntypedExpectations::const_reverse_iterator it = - untyped_expectations_.rbegin(); + for (typename UntypedExpectations::const_reverse_iterator it = untyped_expectations_.rbegin(); it != untyped_expectations_.rend(); ++it) { - TypedExpectation* const exp = - static_cast*>(it->get()); + TypedExpectation* const exp = static_cast*>(it->get()); if (exp->ShouldHandleArguments(args)) { return exp; } @@ -1728,11 +1583,8 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { } // Returns a message that the arguments don't match any expectation. - void FormatUnexpectedCallMessageLocked( - const ArgumentTuple& args, - ::std::ostream* os, - ::std::ostream* why) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args, ::std::ostream* os, ::std::ostream* why) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); *os << "\nUnexpected mock function call - "; DescribeDefaultActionTo(args, os); @@ -1741,19 +1593,14 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { // Prints a list of expectations that have been tried against the // current mock function call. - void PrintTriedExpectationsLocked( - const ArgumentTuple& args, - ::std::ostream* why) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { + void PrintTriedExpectationsLocked(const ArgumentTuple& args, ::std::ostream* why) const + GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const int count = static_cast(untyped_expectations_.size()); *why << "Google Mock tried the following " << count << " " - << (count == 1 ? "expectation, but it didn't match" : - "expectations, but none matched") - << ":\n"; + << (count == 1 ? "expectation, but it didn't match" : "expectations, but none matched") << ":\n"; for (int i = 0; i < count; i++) { - TypedExpectation* const expectation = - static_cast*>(untyped_expectations_[i].get()); + TypedExpectation* const expectation = static_cast*>(untyped_expectations_[i].get()); *why << "\n"; expectation->DescribeLocationTo(why); if (count > 1) { @@ -1785,8 +1632,8 @@ class FunctionMockerBase : public UntypedFunctionMockerBase { }; // class FunctionMockerBase #ifdef _MSC_VER -# pragma warning(pop) // Restores the warning state. -#endif // _MSV_VER +# pragma warning(pop) // Restores the warning state. +#endif // _MSV_VER // Implements methods of FunctionMockerBase. @@ -1823,7 +1670,9 @@ using internal::MockSpec; // // Expects a call to const MockFoo::Bar(). // EXPECT_CALL(Const(foo), Bar()); template -inline const T& Const(const T& x) { return x; } +inline const T& Const(const T& x) { + return x; +} // Constructs an Expectation object that references and co-owns exp. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT @@ -1835,13 +1684,10 @@ inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT // of the method used in call is a result of macro expansion. // See CompilesWithMethodNameExpandedFromMacro tests in // internal/gmock-spec-builders_test.cc for more details. -#define GMOCK_ON_CALL_IMPL_(obj, call) \ - ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \ - #obj, #call) +#define GMOCK_ON_CALL_IMPL_(obj, call) ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, #obj, #call) #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call) -#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \ - ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call) +#define GMOCK_EXPECT_CALL_IMPL_(obj, call) ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call) #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call) #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ diff --git a/src/net/test/gmock/include/gmock/gmock.h b/src/net/test/gmock/include/gmock/gmock.h index 6735c71bf8..eb22dc4216 100644 --- a/src/net/test/gmock/include/gmock/gmock.h +++ b/src/net/test/gmock/include/gmock/gmock.h @@ -59,8 +59,8 @@ #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-generated-actions.h" #include "gmock/gmock-generated-function-mockers.h" -#include "gmock/gmock-generated-nice-strict.h" #include "gmock/gmock-generated-matchers.h" +#include "gmock/gmock-generated-nice-strict.h" #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-matchers.h" diff --git a/src/net/test/gmock/include/gmock/internal/gmock-generated-internal-utils.h b/src/net/test/gmock/include/gmock/internal/gmock-generated-internal-utils.h index 7811e43f87..2d1c96a9ea 100644 --- a/src/net/test/gmock/include/gmock/internal/gmock-generated-internal-utils.h +++ b/src/net/test/gmock/include/gmock/internal/gmock-generated-internal-utils.h @@ -70,7 +70,7 @@ struct MatcherTuple; template <> struct MatcherTuple< ::testing::tuple<> > { - typedef ::testing::tuple< > type; + typedef ::testing::tuple<> type; }; template @@ -90,51 +90,46 @@ struct MatcherTuple< ::testing::tuple > { template struct MatcherTuple< ::testing::tuple > { - typedef ::testing::tuple, Matcher, Matcher, - Matcher > type; + typedef ::testing::tuple, Matcher, Matcher, Matcher > type; }; template struct MatcherTuple< ::testing::tuple > { - typedef ::testing::tuple, Matcher, Matcher, Matcher, - Matcher > type; + typedef ::testing::tuple, Matcher, Matcher, Matcher, Matcher > type; }; -template +template struct MatcherTuple< ::testing::tuple > { - typedef ::testing::tuple, Matcher, Matcher, Matcher, - Matcher, Matcher > type; + typedef ::testing::tuple, Matcher, Matcher, Matcher, Matcher, Matcher > type; }; -template +template struct MatcherTuple< ::testing::tuple > { - typedef ::testing::tuple, Matcher, Matcher, Matcher, - Matcher, Matcher, Matcher > type; + typedef ::testing::tuple, Matcher, Matcher, Matcher, Matcher, Matcher, Matcher > + type; }; -template +template struct MatcherTuple< ::testing::tuple > { - typedef ::testing::tuple, Matcher, Matcher, Matcher, - Matcher, Matcher, Matcher, Matcher > type; + typedef ::testing::tuple, Matcher, Matcher, Matcher, Matcher, Matcher, Matcher, + Matcher > + type; }; -template +template struct MatcherTuple< ::testing::tuple > { - typedef ::testing::tuple, Matcher, Matcher, Matcher, - Matcher, Matcher, Matcher, Matcher, Matcher > type; + typedef ::testing::tuple, Matcher, Matcher, Matcher, Matcher, Matcher, Matcher, + Matcher, Matcher > + type; }; -template -struct MatcherTuple< ::testing::tuple > { - typedef ::testing::tuple, Matcher, Matcher, Matcher, - Matcher, Matcher, Matcher, Matcher, Matcher, - Matcher > type; +template +struct MatcherTuple< ::testing::tuple > { + typedef ::testing::tuple, Matcher, Matcher, Matcher, Matcher, Matcher, Matcher, + Matcher, Matcher, Matcher > + type; }; // Template struct Function, where F must be a function type, contains @@ -163,8 +158,7 @@ struct Function { }; template -struct Function - : Function { +struct Function : Function { typedef A1 Argument1; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -173,8 +167,7 @@ struct Function }; template -struct Function - : Function { +struct Function : Function { typedef A2 Argument2; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -183,8 +176,7 @@ struct Function }; template -struct Function - : Function { +struct Function : Function { typedef A3 Argument3; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -193,8 +185,7 @@ struct Function }; template -struct Function - : Function { +struct Function : Function { typedef A4 Argument4; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -202,10 +193,8 @@ struct Function typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4); }; -template -struct Function - : Function { +template +struct Function : Function { typedef A5 Argument5; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -213,10 +202,8 @@ struct Function typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5); }; -template -struct Function - : Function { +template +struct Function : Function { typedef A6 Argument6; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -224,10 +211,8 @@ struct Function typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6); }; -template -struct Function - : Function { +template +struct Function : Function { typedef A7 Argument7; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -235,10 +220,9 @@ struct Function typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7); }; -template -struct Function - : Function { +template +struct Function : Function { typedef A8 Argument8; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; @@ -246,30 +230,24 @@ struct Function typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8); }; -template -struct Function - : Function { +template +struct Function : Function { typedef A9 Argument9; typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9); - typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, - A9); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, A9); }; -template -struct Function - : Function { +template +struct Function : Function { typedef A10 Argument10; - typedef ::testing::tuple ArgumentTuple; + typedef ::testing::tuple ArgumentTuple; typedef typename MatcherTuple::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); - typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, - A9, A10); + typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); }; } // namespace internal diff --git a/src/net/test/gmock/include/gmock/internal/gmock-internal-utils.h b/src/net/test/gmock/include/gmock/internal/gmock-internal-utils.h index e2ddb05c91..b3ceab24ca 100644 --- a/src/net/test/gmock/include/gmock/internal/gmock-internal-utils.h +++ b/src/net/test/gmock/include/gmock/internal/gmock-internal-utils.h @@ -67,7 +67,9 @@ struct PointeeOf { }; // This specialization is for the raw pointer case. template -struct PointeeOf { typedef T type; }; // NOLINT +struct PointeeOf { + typedef T type; +}; // NOLINT // GetRawPointer(p) returns the raw pointer underlying p when p is a // smart pointer, or returns p itself when p is already a raw pointer. @@ -78,13 +80,14 @@ inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) { } // This overloaded version is for the raw pointer case. template -inline Element* GetRawPointer(Element* p) { return p; } +inline Element* GetRawPointer(Element* p) { + return p; +} // This comparator allows linked_ptr to be stored in sets. template struct LinkedPtrLessThan { - bool operator()(const ::testing::internal::linked_ptr& lhs, - const ::testing::internal::linked_ptr& rhs) const { + bool operator()(const ::testing::internal::linked_ptr& lhs, const ::testing::internal::linked_ptr& rhs) const { return lhs.get() < rhs.get(); } }; @@ -97,11 +100,10 @@ struct LinkedPtrLessThan { // same as unsigned short when the compiler option /Zc:wchar_t- is // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t // is a native type. -#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \ - (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)) +#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)) // wchar_t is a typedef. #else -# define GMOCK_WCHAR_T_IS_NATIVE_ 1 +# define GMOCK_WCHAR_T_IS_NATIVE_ 1 #endif // signed wchar_t and unsigned wchar_t are NOT in the C++ standard. @@ -115,7 +117,7 @@ struct LinkedPtrLessThan { // wchar_t == signed wchar_t != unsigned wchar_t == unsigned int #ifdef __GNUC__ // signed/unsigned wchar_t are valid types. -# define GMOCK_HAS_SIGNED_WCHAR_T_ 1 +# define GMOCK_HAS_SIGNED_WCHAR_T_ 1 #endif // In what follows, we use the term "kind" to indicate whether a type @@ -123,18 +125,20 @@ struct LinkedPtrLessThan { // or none of them. This categorization is useful for determining // when a matcher argument type can be safely converted to another // type in the implementation of SafeMatcherCast. -enum TypeKind { - kBool, kInteger, kFloatingPoint, kOther -}; +enum TypeKind { kBool, kInteger, kFloatingPoint, kOther }; // KindOf::value is the kind of type T. -template struct KindOf { +template +struct KindOf { enum { value = kOther }; // The default kind. }; // This macro declares that the kind of 'type' is 'kind'. #define GMOCK_DECLARE_KIND_(type, kind) \ - template <> struct KindOf { enum { value = kind }; } + template <> \ + struct KindOf { \ + enum { value = kind }; \ + } GMOCK_DECLARE_KIND_(bool, kBool); @@ -142,11 +146,11 @@ GMOCK_DECLARE_KIND_(bool, kBool); GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(unsigned char, kInteger); -GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); -GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT +GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT #if GMOCK_WCHAR_T_IS_NATIVE_ @@ -165,9 +169,7 @@ GMOCK_DECLARE_KIND_(long double, kFloatingPoint); #undef GMOCK_DECLARE_KIND_ // Evaluates to the kind of 'type'. -#define GMOCK_KIND_OF_(type) \ - static_cast< ::testing::internal::TypeKind>( \ - ::testing::internal::KindOf::value) +#define GMOCK_KIND_OF_(type) static_cast< ::testing::internal::TypeKind>(::testing::internal::KindOf::value) // Evaluates to true iff integer type T is signed. #define GMOCK_IS_SIGNED_(T) (static_cast(-1) < 0) @@ -186,60 +188,50 @@ struct LosslessArithmeticConvertibleImpl : public false_type {}; // Converting bool to bool is lossless. template <> -struct LosslessArithmeticConvertibleImpl - : public true_type {}; // NOLINT +struct LosslessArithmeticConvertibleImpl : public true_type {}; // NOLINT // Converting bool to any integer type is lossless. template -struct LosslessArithmeticConvertibleImpl - : public true_type {}; // NOLINT +struct LosslessArithmeticConvertibleImpl : public true_type {}; // NOLINT // Converting bool to any floating-point type is lossless. template -struct LosslessArithmeticConvertibleImpl - : public true_type {}; // NOLINT +struct LosslessArithmeticConvertibleImpl : public true_type {}; // NOLINT // Converting an integer to bool is lossy. template -struct LosslessArithmeticConvertibleImpl - : public false_type {}; // NOLINT +struct LosslessArithmeticConvertibleImpl : public false_type {}; // NOLINT // Converting an integer to another non-bool integer is lossless iff // the target type's range encloses the source type's range. template struct LosslessArithmeticConvertibleImpl : public bool_constant< - // When converting from a smaller size to a larger size, we are - // fine as long as we are not converting from signed to unsigned. - ((sizeof(From) < sizeof(To)) && - (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) || - // When converting between the same size, the signedness must match. - ((sizeof(From) == sizeof(To)) && - (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT + // When converting from a smaller size to a larger size, we are + // fine as long as we are not converting from signed to unsigned. + ((sizeof(From) < sizeof(To)) && (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) || + // When converting between the same size, the signedness must match. + ((sizeof(From) == sizeof(To)) && (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT #undef GMOCK_IS_SIGNED_ // Converting an integer to a floating-point type may be lossy, since // the format of a floating-point number is implementation-defined. template -struct LosslessArithmeticConvertibleImpl - : public false_type {}; // NOLINT +struct LosslessArithmeticConvertibleImpl : public false_type {}; // NOLINT // Converting a floating-point to bool is lossy. template -struct LosslessArithmeticConvertibleImpl - : public false_type {}; // NOLINT +struct LosslessArithmeticConvertibleImpl : public false_type {}; // NOLINT // Converting a floating-point to an integer is lossy. template -struct LosslessArithmeticConvertibleImpl - : public false_type {}; // NOLINT +struct LosslessArithmeticConvertibleImpl : public false_type {}; // NOLINT // Converting a floating-point to another floating-point is lossless // iff the target type is at least as big as the source type. template -struct LosslessArithmeticConvertibleImpl< - kFloatingPoint, From, kFloatingPoint, To> +struct LosslessArithmeticConvertibleImpl : public bool_constant {}; // NOLINT // LosslessArithmeticConvertible::value is true iff arithmetic @@ -251,23 +243,19 @@ struct LosslessArithmeticConvertibleImpl< // implementation-defined when the above pre-condition is violated. template struct LosslessArithmeticConvertible - : public LosslessArithmeticConvertibleImpl< - GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT + : public LosslessArithmeticConvertibleImpl {}; // NOLINT // This interface knows how to report a Google Mock failure (either // non-fatal or fatal). class FailureReporterInterface { public: // The type of a failure (either non-fatal or fatal). - enum FailureType { - kNonfatal, kFatal - }; + enum FailureType { kNonfatal, kFatal }; virtual ~FailureReporterInterface() {} // Reports a failure that occurred at the given source file location. - virtual void ReportFailure(FailureType type, const char* file, int line, - const string& message) = 0; + virtual void ReportFailure(FailureType type, const char* file, int line, const string& message) = 0; }; // Returns the failure reporter used by Google Mock. @@ -278,35 +266,24 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter(); // as Google Mock might be used to mock the log sink itself. We // inline this function to prevent it from showing up in the stack // trace. -inline void Assert(bool condition, const char* file, int line, - const string& msg) { +inline void Assert(bool condition, const char* file, int line, const string& msg) { if (!condition) { - GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, - file, line, msg); + GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, line, msg); } } -inline void Assert(bool condition, const char* file, int line) { - Assert(condition, file, line, "Assertion failed."); -} +inline void Assert(bool condition, const char* file, int line) { Assert(condition, file, line, "Assertion failed."); } // Verifies that condition is true; generates a non-fatal failure if // condition is false. -inline void Expect(bool condition, const char* file, int line, - const string& msg) { +inline void Expect(bool condition, const char* file, int line, const string& msg) { if (!condition) { - GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, - file, line, msg); + GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, file, line, msg); } } -inline void Expect(bool condition, const char* file, int line) { - Expect(condition, file, line, "Expectation failed."); -} +inline void Expect(bool condition, const char* file, int line) { Expect(condition, file, line, "Expectation failed."); } // Severity level of a log. -enum LogSeverity { - kInfo = 0, - kWarning = 1 -}; +enum LogSeverity { kInfo = 0, kWarning = 1 }; // Valid values for the --gmock_verbose flag. @@ -328,44 +305,57 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity); // stack_frames_to_skip is treated as 0, since we don't know which // function calls will be inlined by the compiler and need to be // conservative. -GTEST_API_ void Log(LogSeverity severity, - const string& message, - int stack_frames_to_skip); +GTEST_API_ void Log(LogSeverity severity, const string& message, int stack_frames_to_skip); // TODO(wan@google.com): group all type utilities together. // Type traits. // is_reference::value is non-zero iff T is a reference type. -template struct is_reference : public false_type {}; -template struct is_reference : public true_type {}; +template +struct is_reference : public false_type {}; +template +struct is_reference : public true_type {}; // type_equals::value is non-zero iff T1 and T2 are the same type. -template struct type_equals : public false_type {}; -template struct type_equals : public true_type {}; +template +struct type_equals : public false_type {}; +template +struct type_equals : public true_type {}; // remove_reference::type removes the reference from type T, if any. -template struct remove_reference { typedef T type; }; // NOLINT -template struct remove_reference { typedef T type; }; // NOLINT +template +struct remove_reference { + typedef T type; +}; // NOLINT +template +struct remove_reference { + typedef T type; +}; // NOLINT // DecayArray::type turns an array type U[N] to const U* and preserves // other types. Useful for saving a copy of a function argument. -template struct DecayArray { typedef T type; }; // NOLINT -template struct DecayArray { +template +struct DecayArray { + typedef T type; +}; // NOLINT +template +struct DecayArray { typedef const T* type; }; // Sometimes people use arrays whose size is not available at the use site // (e.g. extern const char kNamePrefix[]). This specialization covers that // case. -template struct DecayArray { +template +struct DecayArray { typedef const T* type; }; // Disable MSVC warnings for infinite recursion, since in this case the // the recursion is unreachable. #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4717) +# pragma warning(push) +# pragma warning(disable : 4717) #endif // Invalid() is usable as an expression of type T, but will terminate @@ -383,7 +373,7 @@ inline T Invalid() { } #ifdef _MSC_VER -# pragma warning(pop) +# pragma warning(pop) #endif // Given a raw type (i.e. having no top-level reference or const @@ -410,8 +400,7 @@ class StlContainerView { static const_reference ConstReference(const RawContainer& container) { // Ensures that RawContainer is not a const type. - testing::StaticAssertTypeEq(); + testing::StaticAssertTypeEq(); return container; } static type Copy(const RawContainer& container) { return container; } @@ -447,8 +436,7 @@ class StlContainerView { // ConstReference(const char * (&)[4])') // (and though the N parameter type is mismatched in the above explicit // conversion of it doesn't help - only the conversion of the array). - return type(const_cast(&array[0]), N, - RelationToSourceReference()); + return type(const_cast(&array[0]), N, RelationToSourceReference()); #else return type(array, N, RelationToSourceReference()); #endif // GTEST_OS_SYMBIAN @@ -467,13 +455,11 @@ class StlContainerView { template class StlContainerView< ::testing::tuple > { public: - typedef GTEST_REMOVE_CONST_( - typename internal::PointeeOf::type) RawElement; + typedef GTEST_REMOVE_CONST_(typename internal::PointeeOf::type) RawElement; typedef internal::NativeArray type; typedef const type const_reference; - static const_reference ConstReference( - const ::testing::tuple& array) { + static const_reference ConstReference(const ::testing::tuple& array) { return type(get<0>(array), get<1>(array), RelationToSourceReference()); } static type Copy(const ::testing::tuple& array) { @@ -483,7 +469,8 @@ class StlContainerView< ::testing::tuple > { // The following specialization prevents the user from instantiating // StlContainer with a reference type. -template class StlContainerView; +template +class StlContainerView; // A type transform to remove constness from the first part of a pair. // Pairs like that are used as the value_type of associative containers, @@ -508,4 +495,3 @@ struct BooleanConstant {}; } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ - diff --git a/src/net/test/gmock/include/gmock/internal/gmock-port.h b/src/net/test/gmock/include/gmock/internal/gmock-port.h index 63f4a6802e..309c43c3b9 100644 --- a/src/net/test/gmock/include/gmock/internal/gmock-port.h +++ b/src/net/test/gmock/include/gmock/internal/gmock-port.h @@ -50,9 +50,9 @@ // portability utilities to Google Test's gtest-port.h instead of // here, as Google Mock depends on Google Test. Only add a utility // here if it's truly specific to Google Mock. +#include "gmock/internal/custom/gmock-port.h" #include "gtest/internal/gtest-linked_ptr.h" #include "gtest/internal/gtest-port.h" -#include "gmock/internal/custom/gmock-port.h" // To avoid conditional compilation everywhere, we make it // gmock-port.h's responsibility to #include the header implementing @@ -62,7 +62,7 @@ // For MS Visual C++, check the compiler version. At least VS 2003 is // required to compile Google Mock. #if defined(_MSC_VER) && _MSC_VER < 1310 -# error "At least Visual C++ 2003 (7.1) is required to compile Google Mock." +# error "At least Visual C++ 2003 (7.1) is required to compile Google Mock." #endif // Macro for referencing flags. This is public as we want the user to @@ -72,19 +72,15 @@ #if !defined(GMOCK_DECLARE_bool_) // Macros for declaring flags. -#define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) -#define GMOCK_DECLARE_int32_(name) \ - extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) -#define GMOCK_DECLARE_string_(name) \ - extern GTEST_API_ ::std::string GMOCK_FLAG(name) +# define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) +# define GMOCK_DECLARE_int32_(name) extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) +# define GMOCK_DECLARE_string_(name) extern GTEST_API_ ::std::string GMOCK_FLAG(name) // Macros for defining flags. -#define GMOCK_DEFINE_bool_(name, default_val, doc) \ - GTEST_API_ bool GMOCK_FLAG(name) = (default_val) -#define GMOCK_DEFINE_int32_(name, default_val, doc) \ +# define GMOCK_DEFINE_bool_(name, default_val, doc) GTEST_API_ bool GMOCK_FLAG(name) = (default_val) +# define GMOCK_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val) -#define GMOCK_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) +# define GMOCK_DEFINE_string_(name, default_val, doc) GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) #endif // !defined(GMOCK_DECLARE_bool_) diff --git a/src/net/test/gmock/src/gmock-cardinalities.cc b/src/net/test/gmock/src/gmock-cardinalities.cc index 50ec7286ee..2ad4a56cfd 100644 --- a/src/net/test/gmock/src/gmock-cardinalities.cc +++ b/src/net/test/gmock/src/gmock-cardinalities.cc @@ -49,9 +49,7 @@ namespace { // Implements the Between(m, n) cardinality. class BetweenCardinalityImpl : public CardinalityInterface { public: - BetweenCardinalityImpl(int min, int max) - : min_(min >= 0 ? min : 0), - max_(max >= min_ ? max : min_) { + BetweenCardinalityImpl(int min, int max) : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) { std::stringstream ss; if (min < 0) { ss << "The invocation lower bound must be >= 0, " @@ -62,9 +60,7 @@ class BetweenCardinalityImpl : public CardinalityInterface { << "but is actually " << max << "."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } else if (min > max) { - ss << "The invocation upper bound (" << max - << ") must be >= the invocation lower bound (" << min - << ")."; + ss << "The invocation upper bound (" << max << ") must be >= the invocation lower bound (" << min << ")."; internal::Expect(false, __FILE__, __LINE__, ss.str()); } } @@ -74,13 +70,9 @@ class BetweenCardinalityImpl : public CardinalityInterface { virtual int ConservativeLowerBound() const { return min_; } virtual int ConservativeUpperBound() const { return max_; } - virtual bool IsSatisfiedByCallCount(int call_count) const { - return min_ <= call_count && call_count <= max_; - } + virtual bool IsSatisfiedByCallCount(int call_count) const { return min_ <= call_count && call_count <= max_; } - virtual bool IsSaturatedByCallCount(int call_count) const { - return call_count >= max_; - } + virtual bool IsSaturatedByCallCount(int call_count) const { return call_count >= max_; } virtual void DescribeTo(::std::ostream* os) const; @@ -127,8 +119,7 @@ void BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const { } // Unnamed namespace // Describes the given call count to an ostream. -void Cardinality::DescribeActualCallCountTo(int actual_call_count, - ::std::ostream* os) { +void Cardinality::DescribeActualCallCountTo(int actual_call_count, ::std::ostream* os) { if (actual_call_count > 0) { *os << "called " << FormatTimes(actual_call_count); } else { @@ -146,9 +137,7 @@ GTEST_API_ Cardinality AtMost(int n) { return Between(0, n); } GTEST_API_ Cardinality AnyNumber() { return AtLeast(0); } // Creates a cardinality that allows between min and max calls. -GTEST_API_ Cardinality Between(int min, int max) { - return Cardinality(new BetweenCardinalityImpl(min, max)); -} +GTEST_API_ Cardinality Between(int min, int max) { return Cardinality(new BetweenCardinalityImpl(min, max)); } // Creates a cardinality that allows exactly n calls. GTEST_API_ Cardinality Exactly(int n) { return Between(n, n); } diff --git a/src/net/test/gmock/src/gmock-internal-utils.cc b/src/net/test/gmock/src/gmock-internal-utils.cc index fb5308018a..190f3c9ca4 100644 --- a/src/net/test/gmock/src/gmock-internal-utils.cc +++ b/src/net/test/gmock/src/gmock-internal-utils.cc @@ -57,13 +57,11 @@ GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) { for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { // We don't care about the current locale as the input is // guaranteed to be a valid C++ identifier name. - const bool starts_new_word = IsUpper(*p) || - (!IsAlpha(prev_char) && IsLower(*p)) || - (!IsDigit(prev_char) && IsDigit(*p)); + const bool starts_new_word = + IsUpper(*p) || (!IsAlpha(prev_char) && IsLower(*p)) || (!IsDigit(prev_char) && IsDigit(*p)); if (IsAlNum(*p)) { - if (starts_new_word && result != "") - result += ' '; + if (starts_new_word && result != "") result += ' '; result += ToLower(*p); } } @@ -75,13 +73,8 @@ GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) { // use Google Mock with a testing framework other than Google Test. class GoogleTestFailureReporter : public FailureReporterInterface { public: - virtual void ReportFailure(FailureType type, const char* file, int line, - const string& message) { - AssertHelper(type == kFatal ? - TestPartResult::kFatalFailure : - TestPartResult::kNonFatalFailure, - file, - line, + virtual void ReportFailure(FailureType type, const char* file, int line, const string& message) { + AssertHelper(type == kFatal ? TestPartResult::kFatalFailure : TestPartResult::kNonFatalFailure, file, line, message.c_str()) = Message(); if (type == kFatal) { posix::Abort(); @@ -97,8 +90,7 @@ GTEST_API_ FailureReporterInterface* GetFailureReporter() { // thread-safe. We may need to add additional synchronization to // protect failure_reporter if we port Google Mock to other // compilers. - static FailureReporterInterface* const failure_reporter = - new GoogleTestFailureReporter(); + static FailureReporterInterface* const failure_reporter = new GoogleTestFailureReporter(); return failure_reporter; } @@ -128,11 +120,8 @@ GTEST_API_ bool LogIsVisible(LogSeverity severity) { // stack_frames_to_skip is treated as 0, since we don't know which // function calls will be inlined by the compiler and need to be // conservative. -GTEST_API_ void Log(LogSeverity severity, - const string& message, - int stack_frames_to_skip) { - if (!LogIsVisible(severity)) - return; +GTEST_API_ void Log(LogSeverity severity, const string& message, int stack_frames_to_skip) { + if (!LogIsVisible(severity)) return; // Ensures that logs from different threads don't interleave. MutexLock l(&g_log_mutex); @@ -164,8 +153,8 @@ GTEST_API_ void Log(LogSeverity severity, std::cout << "\n"; } std::cout << "Stack trace:\n" - << ::testing::internal::GetCurrentOsStackTraceExceptTop( - ::testing::UnitTest::GetInstance(), actual_to_skip); + << ::testing::internal::GetCurrentOsStackTraceExceptTop(::testing::UnitTest::GetInstance(), + actual_to_skip); } std::cout << ::std::flush; } diff --git a/src/net/test/gmock/src/gmock-matchers.cc b/src/net/test/gmock/src/gmock-matchers.cc index e7424510fc..d9a0f26934 100644 --- a/src/net/test/gmock/src/gmock-matchers.cc +++ b/src/net/test/gmock/src/gmock-matchers.cc @@ -45,57 +45,39 @@ namespace testing { // Constructs a matcher that matches a const string& whose value is // equal to s. -Matcher::Matcher(const internal::string& s) { - *this = Eq(s); -} +Matcher::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a const string& whose value is // equal to s. -Matcher::Matcher(const char* s) { - *this = Eq(internal::string(s)); -} +Matcher::Matcher(const char* s) { *this = Eq(internal::string(s)); } // Constructs a matcher that matches a string whose value is equal to s. Matcher::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a string whose value is equal to s. -Matcher::Matcher(const char* s) { - *this = Eq(internal::string(s)); -} +Matcher::Matcher(const char* s) { *this = Eq(internal::string(s)); } #if GTEST_HAS_STRING_PIECE_ // Constructs a matcher that matches a const StringPiece& whose value is // equal to s. -Matcher::Matcher(const internal::string& s) { - *this = Eq(s); -} +Matcher::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a const StringPiece& whose value is // equal to s. -Matcher::Matcher(const char* s) { - *this = Eq(internal::string(s)); -} +Matcher::Matcher(const char* s) { *this = Eq(internal::string(s)); } // Constructs a matcher that matches a const StringPiece& whose value is // equal to s. -Matcher::Matcher(StringPiece s) { - *this = Eq(s.ToString()); -} +Matcher::Matcher(StringPiece s) { *this = Eq(s.ToString()); } // Constructs a matcher that matches a StringPiece whose value is equal to s. -Matcher::Matcher(const internal::string& s) { - *this = Eq(s); -} +Matcher::Matcher(const internal::string& s) { *this = Eq(s); } // Constructs a matcher that matches a StringPiece whose value is equal to s. -Matcher::Matcher(const char* s) { - *this = Eq(internal::string(s)); -} +Matcher::Matcher(const char* s) { *this = Eq(internal::string(s)); } // Constructs a matcher that matches a StringPiece whose value is equal to s. -Matcher::Matcher(StringPiece s) { - *this = Eq(s.ToString()); -} +Matcher::Matcher(StringPiece s) { *this = Eq(s.ToString()); } #endif // GTEST_HAS_STRING_PIECE_ namespace internal { @@ -124,12 +106,9 @@ GTEST_API_ string JoinAsTuple(const Strings& fields) { // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. -GTEST_API_ string FormatMatcherDescription(bool negation, - const char* matcher_name, - const Strings& param_values) { +GTEST_API_ string FormatMatcherDescription(bool negation, const char* matcher_name, const Strings& param_values) { string result = ConvertIdentifierNameToWords(matcher_name); - if (param_values.size() >= 1) - result += " " + JoinAsTuple(param_values); + if (param_values.size() >= 1) result += " " + JoinAsTuple(param_values); return negation ? "not (" + result + ")" : result; } @@ -198,10 +177,7 @@ GTEST_API_ string FormatMatcherDescription(bool negation, class MaxBipartiteMatchState { public: explicit MaxBipartiteMatchState(const MatchMatrix& graph) - : graph_(&graph), - left_(graph_->LhsSize(), kUnused), - right_(graph_->RhsSize(), kUnused) { - } + : graph_(&graph), left_(graph_->LhsSize(), kUnused), right_(graph_->RhsSize(), kUnused) {} // Returns the edges of a maximal match, each in the form {left, right}. ElementMatcherPairs Compute() { @@ -222,8 +198,7 @@ class MaxBipartiteMatchState { for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) { // Reset the path-marking vector and try to find a path from // source to sink starting at the left_[ilhs] node. - GTEST_CHECK_(left_[ilhs] == kUnused) - << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs]; + GTEST_CHECK_(left_[ilhs] == kUnused) << "ilhs: " << ilhs << ", left_[ilhs]: " << left_[ilhs]; // 'seen' initialized to 'graph_->RhsSize()' copies of 0. seen.assign(graph_->RhsSize(), 0); TryAugment(ilhs, &seen); @@ -258,10 +233,8 @@ class MaxBipartiteMatchState { // bool TryAugment(size_t ilhs, ::std::vector* seen) { for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) { - if ((*seen)[irhs]) - continue; - if (!graph_->HasEdge(ilhs, irhs)) - continue; + if ((*seen)[irhs]) continue; + if (!graph_->HasEdge(ilhs, irhs)) continue; // There's an available edge from ilhs to irhs. (*seen)[irhs] = 1; // Next a search is performed to determine whether @@ -304,17 +277,15 @@ class MaxBipartiteMatchState { const size_t MaxBipartiteMatchState::kUnused; -GTEST_API_ ElementMatcherPairs -FindMaxBipartiteMatching(const MatchMatrix& g) { +GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) { return MaxBipartiteMatchState(g).Compute(); } -static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, - ::std::ostream* stream) { +static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, ::std::ostream* stream) { typedef ElementMatcherPairs::const_iterator Iter; ::std::ostream& os = *stream; os << "{"; - const char *sep = ""; + const char* sep = ""; for (Iter it = pairs.begin(); it != pairs.end(); ++it) { os << sep << "\n (" << "element #" << it->first << ", " @@ -325,8 +296,7 @@ static void LogElementMatcherPairVec(const ElementMatcherPairs& pairs, } // Tries to find a pairing, and explains the result. -GTEST_API_ bool FindPairing(const MatchMatrix& matrix, - MatchResultListener* listener) { +GTEST_API_ bool FindPairing(const MatchMatrix& matrix, MatchResultListener* listener) { ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix); size_t max_flow = matches.size(); @@ -336,8 +306,7 @@ GTEST_API_ bool FindPairing(const MatchMatrix& matrix, if (listener->IsInterested()) { *listener << "where no permutation of the elements can " "satisfy all matchers, and the closest match is " - << max_flow << " of " << matrix.RhsSize() - << " matchers with the pairings:\n"; + << max_flow << " of " << matrix.RhsSize() << " matchers with the pairings:\n"; LogElementMatcherPairVec(matches, listener->stream()); } return false; @@ -345,10 +314,9 @@ GTEST_API_ bool FindPairing(const MatchMatrix& matrix, if (matches.size() > 1) { if (listener->IsInterested()) { - const char *sep = "where:\n"; + const char* sep = "where:\n"; for (size_t mi = 0; mi < matches.size(); ++mi) { - *listener << sep << " - element #" << matches[mi].first - << " is matched by matcher #" << matches[mi].second; + *listener << sep << " - element #" << matches[mi].first << " is matched by matcher #" << matches[mi].second; sep = ",\n"; } } @@ -381,7 +349,7 @@ void MatchMatrix::Randomize() { string MatchMatrix::DebugString() const { ::std::stringstream ss; - const char *sep = ""; + const char* sep = ""; for (size_t i = 0; i < LhsSize(); ++i) { ss << sep; for (size_t j = 0; j < RhsSize(); ++j) { @@ -392,8 +360,7 @@ string MatchMatrix::DebugString() const { return ss.str(); } -void UnorderedElementsAreMatcherImplBase::DescribeToImpl( - ::std::ostream* os) const { +void UnorderedElementsAreMatcherImplBase::DescribeToImpl(::std::ostream* os) const { if (matcher_describers_.empty()) { *os << "is empty"; return; @@ -413,15 +380,13 @@ void UnorderedElementsAreMatcherImplBase::DescribeToImpl( } } -void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( - ::std::ostream* os) const { +void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(::std::ostream* os) const { if (matcher_describers_.empty()) { *os << "isn't empty"; return; } if (matcher_describers_.size() == 1) { - *os << "doesn't have " << Elements(1) - << ", or has " << Elements(1) << " that "; + *os << "doesn't have " << Elements(1) << ", or has " << Elements(1) << " that "; matcher_describers_[0]->DescribeNegationTo(os); return; } @@ -440,11 +405,8 @@ void UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl( // and better error reporting. // Returns false, writing an explanation to 'listener', if and only // if the success criteria are not met. -bool UnorderedElementsAreMatcherImplBase:: -VerifyAllElementsAndMatchersAreMatched( - const ::std::vector& element_printouts, - const MatchMatrix& matrix, - MatchResultListener* listener) const { +bool UnorderedElementsAreMatcherImplBase::VerifyAllElementsAndMatchersAreMatched( + const ::std::vector& element_printouts, const MatchMatrix& matrix, MatchResultListener* listener) const { bool result = true; ::std::vector element_matched(matrix.LhsSize(), 0); ::std::vector matcher_matched(matrix.RhsSize(), 0); @@ -458,11 +420,9 @@ VerifyAllElementsAndMatchersAreMatched( } { - const char* sep = - "where the following matchers don't match any elements:\n"; + const char* sep = "where the following matchers don't match any elements:\n"; for (size_t mi = 0; mi < matcher_matched.size(); ++mi) { - if (matcher_matched[mi]) - continue; + if (matcher_matched[mi]) continue; result = false; if (listener->IsInterested()) { *listener << sep << "matcher #" << mi << ": "; @@ -473,19 +433,16 @@ VerifyAllElementsAndMatchersAreMatched( } { - const char* sep = - "where the following elements don't match any matchers:\n"; + const char* sep = "where the following elements don't match any matchers:\n"; const char* outer_sep = ""; if (!result) { outer_sep = "\nand "; } for (size_t ei = 0; ei < element_matched.size(); ++ei) { - if (element_matched[ei]) - continue; + if (element_matched[ei]) continue; result = false; if (listener->IsInterested()) { - *listener << outer_sep << sep << "element #" << ei << ": " - << element_printouts[ei]; + *listener << outer_sep << sep << "element #" << ei << ": " << element_printouts[ei]; sep = ",\n"; outer_sep = ""; } diff --git a/src/net/test/gmock/src/gmock-spec-builders.cc b/src/net/test/gmock/src/gmock-spec-builders.cc index 9551342070..54a420c65e 100644 --- a/src/net/test/gmock/src/gmock-spec-builders.cc +++ b/src/net/test/gmock/src/gmock-spec-builders.cc @@ -45,7 +45,7 @@ #include "gtest/gtest.h" #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC -# include // NOLINT +# include // NOLINT #endif namespace testing { @@ -56,8 +56,7 @@ namespace internal { GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex); // Logs a message including file and line number information. -GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, - const char* file, int line, +GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const string& message) { ::std::ostringstream s; s << file << ":" << line << ": " << message << ::std::endl; @@ -65,9 +64,7 @@ GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, } // Constructs an ExpectationBase object. -ExpectationBase::ExpectationBase(const char* a_file, - int a_line, - const string& a_source_text) +ExpectationBase::ExpectationBase(const char* a_file, int a_line, const string& a_source_text) : file_(a_file), line_(a_line), source_text_(a_source_text), @@ -92,16 +89,15 @@ void ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) { } // Retires all pre-requisites of this expectation. -void ExpectationBase::RetireAllPreRequisites() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { +void ExpectationBase::RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { if (is_retired()) { // We can take this short-cut as we never retire an expectation // until we have retired all its pre-requisites. return; } - for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); - it != immediate_prerequisites_.end(); ++it) { + for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); + ++it) { ExpectationBase* const prerequisite = it->expectation_base().get(); if (!prerequisite->is_retired()) { prerequisite->RetireAllPreRequisites(); @@ -112,13 +108,11 @@ void ExpectationBase::RetireAllPreRequisites() // Returns true iff all pre-requisites of this expectation have been // satisfied. -bool ExpectationBase::AllPrerequisitesAreSatisfied() const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { +bool ExpectationBase::AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); - it != immediate_prerequisites_.end(); ++it) { - if (!(it->expectation_base()->IsSatisfied()) || - !(it->expectation_base()->AllPrerequisitesAreSatisfied())) + for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); + ++it) { + if (!(it->expectation_base()->IsSatisfied()) || !(it->expectation_base()->AllPrerequisitesAreSatisfied())) return false; } return true; @@ -128,8 +122,8 @@ bool ExpectationBase::AllPrerequisitesAreSatisfied() const void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); - for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); - it != immediate_prerequisites_.end(); ++it) { + for (ExpectationSet::const_iterator it = immediate_prerequisites_.begin(); it != immediate_prerequisites_.end(); + ++it) { if (it->expectation_base()->IsSatisfied()) { // If *it is satisfied and has a call count of 0, some of its // pre-requisites may not be satisfied yet. @@ -147,8 +141,7 @@ void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const // Describes how many times a function call matching this // expectation has occurred. -void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { +void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // Describes how many times the function is expected to be called. @@ -159,19 +152,19 @@ void ExpectationBase::DescribeCallCountTo(::std::ostream* os) const // Describes the state of the expectation (e.g. is it satisfied? // is it active?). - *os << " - " << (IsOverSaturated() ? "over-saturated" : - IsSaturated() ? "saturated" : - IsSatisfied() ? "satisfied" : "unsatisfied") - << " and " - << (is_retired() ? "retired" : "active"); + *os << " - " + << (IsOverSaturated() ? "over-saturated" + : IsSaturated() ? "saturated" + : IsSatisfied() ? "satisfied" + : "unsatisfied") + << " and " << (is_retired() ? "retired" : "active"); } // Checks the action count (i.e. the number of WillOnce() and // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. -void ExpectationBase::CheckActionCountIfNotDone() const - GTEST_LOCK_EXCLUDED_(mutex_) { +void ExpectationBase::CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_) { bool should_check = false; { MutexLock l(&mutex_); @@ -194,11 +187,9 @@ void ExpectationBase::CheckActionCountIfNotDone() const const int lower_bound = cardinality().ConservativeLowerBound(); bool too_many; // True if there are too many actions, or false // if there are too few. - if (action_count > upper_bound || - (action_count == upper_bound && repeated_action_specified_)) { + if (action_count > upper_bound || (action_count == upper_bound && repeated_action_specified_)) { too_many = true; - } else if (0 < action_count && action_count < lower_bound && - !repeated_action_specified_) { + } else if (0 < action_count && action_count < lower_bound && !repeated_action_specified_) { too_many = false; } else { return; @@ -206,13 +197,10 @@ void ExpectationBase::CheckActionCountIfNotDone() const ::std::stringstream ss; DescribeLocationTo(&ss); - ss << "Too " << (too_many ? "many" : "few") - << " actions specified in " << source_text() << "...\n" + ss << "Too " << (too_many ? "many" : "few") << " actions specified in " << source_text() << "...\n" << "Expected to be "; cardinality().DescribeTo(&ss); - ss << ", but has " << (too_many ? "" : "only ") - << action_count << " WillOnce()" - << (action_count == 1 ? "" : "s"); + ss << ", but has " << (too_many ? "" : "only ") << action_count << " WillOnce()" << (action_count == 1 ? "" : "s"); if (repeated_action_specified_) { ss << " and a WillRepeatedly()"; } @@ -246,8 +234,7 @@ GTEST_API_ ThreadLocal g_gmock_implicit_sequence; // manner specified by 'reaction'. void ReportUninterestingCall(CallReaction reaction, const string& msg) { // Include a stack trace only if --gmock_verbose=info is specified. - const int stack_frames_to_skip = - GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1; + const int stack_frames_to_skip = GMOCK_FLAG(verbose) == kInfoVerbosity ? 3 : -1; switch (reaction) { case kAllow: Log(kInfo, msg, stack_frames_to_skip); @@ -255,11 +242,11 @@ void ReportUninterestingCall(CallReaction reaction, const string& msg) { case kWarn: Log(kWarning, msg + - "\nNOTE: You can safely ignore the above warning unless this " - "call should not happen. Do not suppress it by blindly adding " - "an EXPECT_CALL() if you don't mean to enforce the call. " - "See /~https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" - "knowing-when-to-expect for details.\n", + "\nNOTE: You can safely ignore the above warning unless this " + "call should not happen. Do not suppress it by blindly adding " + "an EXPECT_CALL() if you don't mean to enforce the call. " + "See /~https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#" + "knowing-when-to-expect for details.\n", stack_frames_to_skip); break; default: // FAIL @@ -267,8 +254,7 @@ void ReportUninterestingCall(CallReaction reaction, const string& msg) { } } -UntypedFunctionMockerBase::UntypedFunctionMockerBase() - : mock_obj_(NULL), name_("") {} +UntypedFunctionMockerBase::UntypedFunctionMockerBase() : mock_obj_(NULL), name_("") {} UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} @@ -276,8 +262,7 @@ UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {} // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. -void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { +void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { { MutexLock l(&g_gmock_mutex); mock_obj_ = mock_obj; @@ -288,8 +273,7 @@ void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj) // Sets the mock object this mock method belongs to, and sets the name // of the mock function. Will be called upon each invocation of this // mock function. -void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, - const char* name) +void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { // We protect name_ under g_gmock_mutex in case this mock function // is called from two threads concurrently. @@ -300,8 +284,7 @@ void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj, // Returns the name of the function being mocked. Must be called // after RegisterOwner() or SetOwnerAndName() has been called. -const void* UntypedFunctionMockerBase::MockObject() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { +const void* UntypedFunctionMockerBase::MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const void* mock_obj; { // We protect mock_obj_ under g_gmock_mutex in case this mock @@ -317,8 +300,7 @@ const void* UntypedFunctionMockerBase::MockObject() const // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. -const char* UntypedFunctionMockerBase::Name() const - GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { +const char* UntypedFunctionMockerBase::Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const char* name; { // We protect name_ under g_gmock_mutex in case this mock @@ -335,8 +317,7 @@ const char* UntypedFunctionMockerBase::Name() const // Calculates the result of invoking this mock function with the given // arguments, prints it, and returns it. The caller is responsible // for deleting the result. -UntypedActionResultHolderBase* -UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) +UntypedActionResultHolderBase* UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { if (untyped_expectations_.size() == 0) { // No expectation is set on this mock method - we have an @@ -346,8 +327,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) // made on this mock object BEFORE performing the action, // because the action may DELETE the mock object and make the // following expression meaningless. - const CallReaction reaction = - Mock::GetReactionOnUninterestingCalls(MockObject()); + const CallReaction reaction = Mock::GetReactionOnUninterestingCalls(MockObject()); // True iff we need to print this call's arguments and return // value. This definition must be kept in sync with @@ -356,12 +336,13 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) // If the user allows this uninteresting call, we print it // only when he wants informational messages. reaction == kAllow ? LogIsVisible(kInfo) : - // If the user wants this to be a warning, we print it only - // when he wants to see warnings. - reaction == kWarn ? LogIsVisible(kWarning) : - // Otherwise, the user wants this to be an error, and we - // should always print detailed information in the error. - true; + // If the user wants this to be a warning, we print it only + // when he wants to see warnings. + reaction == kWarn ? LogIsVisible(kWarning) + : + // Otherwise, the user wants this to be an error, and we + // should always print detailed information in the error. + true; if (!need_to_report_uninteresting_call) { // Perform the action without printing the call information. @@ -373,12 +354,10 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) this->UntypedDescribeUninterestingCall(untyped_args, &ss); // Calculates the function result. - UntypedActionResultHolderBase* const result = - this->UntypedPerformDefaultAction(untyped_args, ss.str()); + UntypedActionResultHolderBase* const result = this->UntypedPerformDefaultAction(untyped_args, ss.str()); // Prints the function result. - if (result != NULL) - result->PrintAsActionResult(&ss); + if (result != NULL) result->PrintAsActionResult(&ss); ReportUninterestingCall(reaction, ss.str()); return result; @@ -393,22 +372,17 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) // The UntypedFindMatchingExpectation() function acquires and // releases g_gmock_mutex. const ExpectationBase* const untyped_expectation = - this->UntypedFindMatchingExpectation( - untyped_args, &untyped_action, &is_excessive, - &ss, &why); + this->UntypedFindMatchingExpectation(untyped_args, &untyped_action, &is_excessive, &ss, &why); const bool found = untyped_expectation != NULL; // True iff we need to print the call's arguments and return value. // This definition must be kept in sync with the uses of Expect() // and Log() in this function. - const bool need_to_report_call = - !found || is_excessive || LogIsVisible(kInfo); + const bool need_to_report_call = !found || is_excessive || LogIsVisible(kInfo); if (!need_to_report_call) { // Perform the action without printing the call information. - return - untyped_action == NULL ? - this->UntypedPerformDefaultAction(untyped_args, "") : - this->UntypedPerformAction(untyped_action, untyped_args); + return untyped_action == NULL ? this->UntypedPerformDefaultAction(untyped_args, "") + : this->UntypedPerformAction(untyped_action, untyped_args); } ss << " Function call: " << Name(); @@ -420,12 +394,10 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) untyped_expectation->DescribeLocationTo(&loc); } - UntypedActionResultHolderBase* const result = - untyped_action == NULL ? - this->UntypedPerformDefaultAction(untyped_args, ss.str()) : - this->UntypedPerformAction(untyped_action, untyped_args); - if (result != NULL) - result->PrintAsActionResult(&ss); + UntypedActionResultHolderBase* const result = untyped_action == NULL + ? this->UntypedPerformDefaultAction(untyped_args, ss.str()) + : this->UntypedPerformAction(untyped_action, untyped_args); + if (result != NULL) result->PrintAsActionResult(&ss); ss << "\n" << why.str(); if (!found) { @@ -433,8 +405,7 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) Expect(false, NULL, -1, ss.str()); } else if (is_excessive) { // We had an upper-bound violation and the failure message is in ss. - Expect(false, untyped_expectation->file(), - untyped_expectation->line(), ss.str()); + Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } else { // We had an expected call and the matching expectation is // described in ss. @@ -447,9 +418,8 @@ UntypedFunctionMockerBase::UntypedInvokeWith(const void* const untyped_args) // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { - for (UntypedExpectations::const_iterator it = - untyped_expectations_.begin(); - it != untyped_expectations_.end(); ++it) { + for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); + ++it) { if (it->get() == exp) { return Expectation(*it); } @@ -464,13 +434,11 @@ Expectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) { // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. -bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() - GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { +bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); bool expectations_met = true; - for (UntypedExpectations::const_iterator it = - untyped_expectations_.begin(); - it != untyped_expectations_.end(); ++it) { + for (UntypedExpectations::const_iterator it = untyped_expectations_.begin(); it != untyped_expectations_.end(); + ++it) { ExpectationBase* const untyped_expectation = it->get(); if (untyped_expectation->IsOverSaturated()) { // There was an upper-bound violation. Since the error was @@ -480,15 +448,13 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked() } else if (!untyped_expectation->IsSatisfied()) { expectations_met = false; ::std::stringstream ss; - ss << "Actual function call count doesn't match " - << untyped_expectation->source_text() << "...\n"; + ss << "Actual function call count doesn't match " << untyped_expectation->source_text() << "...\n"; // No need to show the source file location of the expectation // in the description, as the Expect() call that follows already // takes care of it. untyped_expectation->MaybeDescribeExtraMatcherTo(&ss); untyped_expectation->DescribeCallCountTo(&ss); - Expect(false, untyped_expectation->file(), - untyped_expectation->line(), ss.str()); + Expect(false, untyped_expectation->file(), untyped_expectation->line(), ss.str()); } } @@ -521,8 +487,7 @@ typedef std::set FunctionMockers; // detecting leaked mock objects and explicitly verifying a mock's // expectations. struct MockObjectState { - MockObjectState() - : first_used_file(NULL), first_used_line(-1), leakable(false) {} + MockObjectState() : first_used_file(NULL), first_used_line(-1), leakable(false) {} // Where in the source file an ON_CALL or EXPECT_CALL is first // invoked on this mock object. @@ -530,7 +495,7 @@ struct MockObjectState { int first_used_line; ::std::string first_used_test_case; ::std::string first_used_test; - bool leakable; // true iff it's OK to leak the object. + bool leakable; // true iff it's OK to leak the object. FunctionMockers function_mockers; // All registered methods of the object. }; @@ -551,12 +516,10 @@ class MockObjectRegistry { // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is // a macro. - if (!GMOCK_FLAG(catch_leaked_mocks)) - return; + if (!GMOCK_FLAG(catch_leaked_mocks)) return; int leaked_count = 0; - for (StateMap::const_iterator it = states_.begin(); it != states_.end(); - ++it) { + for (StateMap::const_iterator it = states_.begin(); it != states_.end(); ++it) { if (it->second.leakable) // The user said it's fine to leak this object. continue; @@ -564,21 +527,17 @@ class MockObjectRegistry { // This can help the user identify the leaked object. std::cout << "\n"; const MockObjectState& state = it->second; - std::cout << internal::FormatFileLocation(state.first_used_file, - state.first_used_line); + std::cout << internal::FormatFileLocation(state.first_used_file, state.first_used_line); std::cout << " ERROR: this mock object"; if (state.first_used_test != "") { - std::cout << " (used in test " << state.first_used_test_case << "." - << state.first_used_test << ")"; + std::cout << " (used in test " << state.first_used_test_case << "." << state.first_used_test << ")"; } - std::cout << " should be deleted but never is. Its address is @" - << it->first << "."; + std::cout << " should be deleted but never is. Its address is @" << it->first << "."; leaked_count++; } if (leaked_count > 0) { - std::cout << "\nERROR: " << leaked_count - << " leaked mock " << (leaked_count == 1 ? "object" : "objects") - << " found at program exit.\n"; + std::cout << "\nERROR: " << leaked_count << " leaked mock " << (leaked_count == 1 ? "object" : "objects") + << " found at program exit.\n"; std::cout.flush(); ::std::cerr.flush(); // RUN_ALL_TESTS() has already returned when this destructor is @@ -604,8 +563,7 @@ std::map g_uninteresting_call_reaction; // Sets the reaction Google Mock should have when an uninteresting // method of the given mock object is called. -void SetReactionOnUninterestingCalls(const void* mock_obj, - internal::CallReaction reaction) +void SetReactionOnUninterestingCalls(const void* mock_obj, internal::CallReaction reaction) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_uninteresting_call_reaction[mock_obj] = reaction; @@ -615,47 +573,41 @@ void SetReactionOnUninterestingCalls(const void* mock_obj, // Tells Google Mock to allow uninteresting calls on the given mock // object. -void Mock::AllowUninterestingCalls(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +void Mock::AllowUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kAllow); } // Tells Google Mock to warn the user about uninteresting calls on the // given mock object. -void Mock::WarnUninterestingCalls(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +void Mock::WarnUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kWarn); } // Tells Google Mock to fail uninteresting calls on the given mock // object. -void Mock::FailUninterestingCalls(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +void Mock::FailUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { SetReactionOnUninterestingCalls(mock_obj, internal::kFail); } // Tells Google Mock the given mock object is being destroyed and its // entry in the call-reaction table should be removed. -void Mock::UnregisterCallReaction(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +void Mock::UnregisterCallReaction(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_uninteresting_call_reaction.erase(mock_obj); } // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. -internal::CallReaction Mock::GetReactionOnUninterestingCalls( - const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +internal::CallReaction Mock::GetReactionOnUninterestingCalls(const void* mock_obj) + GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); - return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? - internal::kDefault : g_uninteresting_call_reaction[mock_obj]; + return (g_uninteresting_call_reaction.count(mock_obj) == 0) ? internal::kDefault + : g_uninteresting_call_reaction[mock_obj]; } // Tells Google Mock to ignore mock_obj when checking for leaked mock // objects. -void Mock::AllowLeak(const void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +void Mock::AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].leakable = true; } @@ -663,8 +615,7 @@ void Mock::AllowLeak(const void* mock_obj) // Verifies and clears all expectations on the given mock object. If // the expectations aren't satisfied, generates one or more Google // Test non-fatal failures and returns false. -bool Mock::VerifyAndClearExpectations(void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +bool Mock::VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); return VerifyAndClearExpectationsLocked(mock_obj); } @@ -672,8 +623,7 @@ bool Mock::VerifyAndClearExpectations(void* mock_obj) // Verifies all expectations on the given mock object and clears its // default actions and expectations. Returns true iff the // verification was successful. -bool Mock::VerifyAndClear(void* mock_obj) - GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { +bool Mock::VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); ClearDefaultActionsLocked(mock_obj); return VerifyAndClearExpectationsLocked(mock_obj); @@ -682,8 +632,7 @@ bool Mock::VerifyAndClear(void* mock_obj) // Verifies and clears all expectations on the given mock object. If // the expectations aren't satisfied, generates one or more Google // Test non-fatal failures and returns false. -bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { +bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { // No EXPECT_CALL() was set on the given mock object. @@ -693,10 +642,8 @@ bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) // Verifies and clears the expectations on each mock method in the // given mock object. bool expectations_met = true; - FunctionMockers& mockers = - g_mock_object_registry.states()[mock_obj].function_mockers; - for (FunctionMockers::const_iterator it = mockers.begin(); - it != mockers.end(); ++it) { + FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; + for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { if (!(*it)->VerifyAndClearExpectationsLocked()) { expectations_met = false; } @@ -708,8 +655,7 @@ bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj) } // Registers a mock object and a mock method it owns. -void Mock::Register(const void* mock_obj, - internal::UntypedFunctionMockerBase* mocker) +void Mock::Register(const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker); @@ -718,16 +664,14 @@ void Mock::Register(const void* mock_obj, // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. -void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, - const char* file, int line) +void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) { internal::MutexLock l(&internal::g_gmock_mutex); MockObjectState& state = g_mock_object_registry.states()[mock_obj]; if (state.first_used_file == NULL) { state.first_used_file = file; state.first_used_line = line; - const TestInfo* const test_info = - UnitTest::GetInstance()->current_test_info(); + const TestInfo* const test_info = UnitTest::GetInstance()->current_test_info(); if (test_info != NULL) { // TODO(wan@google.com): record the test case name when the // ON_CALL or EXPECT_CALL is invoked from SetUpTestCase() or @@ -745,8 +689,7 @@ void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj, void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); - for (MockObjectRegistry::StateMap::iterator it = - g_mock_object_registry.states().begin(); + for (MockObjectRegistry::StateMap::iterator it = g_mock_object_registry.states().begin(); it != g_mock_object_registry.states().end(); ++it) { FunctionMockers& mockers = it->second.function_mockers; if (mockers.erase(mocker) > 0) { @@ -760,8 +703,7 @@ void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) } // Clears all ON_CALL()s set on the given mock object. -void Mock::ClearDefaultActionsLocked(void* mock_obj) - GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { +void Mock::ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) { internal::g_gmock_mutex.AssertHeld(); if (g_mock_object_registry.states().count(mock_obj) == 0) { @@ -771,10 +713,8 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj) // Clears the default actions for each mock method in the given mock // object. - FunctionMockers& mockers = - g_mock_object_registry.states()[mock_obj].function_mockers; - for (FunctionMockers::const_iterator it = mockers.begin(); - it != mockers.end(); ++it) { + FunctionMockers& mockers = g_mock_object_registry.states()[mock_obj].function_mockers; + for (FunctionMockers::const_iterator it = mockers.begin(); it != mockers.end(); ++it) { (*it)->ClearDefaultActionsLocked(); } @@ -784,8 +724,7 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj) Expectation::Expectation() {} -Expectation::Expectation( - const internal::linked_ptr& an_expectation_base) +Expectation::Expectation(const internal::linked_ptr& an_expectation_base) : expectation_base_(an_expectation_base) {} Expectation::~Expectation() {} @@ -794,8 +733,7 @@ Expectation::~Expectation() {} void Sequence::AddExpectation(const Expectation& expectation) const { if (*last_expectation_ != expectation) { if (last_expectation_->expectation_base() != NULL) { - expectation.expectation_base()->immediate_prerequisites_ - += *last_expectation_; + expectation.expectation_base()->immediate_prerequisites_ += *last_expectation_; } *last_expectation_ = expectation; } diff --git a/src/net/test/gmock/src/gmock.cc b/src/net/test/gmock/src/gmock.cc index eac3d842ba..d4d7acfeb8 100644 --- a/src/net/test/gmock/src/gmock.cc +++ b/src/net/test/gmock/src/gmock.cc @@ -55,9 +55,7 @@ namespace internal { // "=value" part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. -static const char* ParseGoogleMockFlagValue(const char* str, - const char* flag, - bool def_optional) { +static const char* ParseGoogleMockFlagValue(const char* str, const char* flag, bool def_optional) { // str and flag must not be NULL. if (str == NULL || flag == NULL) return NULL; @@ -88,8 +86,7 @@ static const char* ParseGoogleMockFlagValue(const char* str, // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. -static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, - bool* value) { +static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, bool* value) { // Gets the value of the flag as a string. const char* const value_str = ParseGoogleMockFlagValue(str, flag, true); @@ -107,8 +104,7 @@ static bool ParseGoogleMockBoolFlag(const char* str, const char* flag, // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. template -static bool ParseGoogleMockStringFlag(const char* str, const char* flag, - String* value) { +static bool ParseGoogleMockStringFlag(const char* str, const char* flag, String* value) { // Gets the value of the flag as a string. const char* const value_str = ParseGoogleMockFlagValue(str, flag, false); @@ -136,8 +132,7 @@ void InitGoogleMockImpl(int* argc, CharType** argv) { const char* const arg = arg_string.c_str(); // Do we see a Google Mock flag? - if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks", - &GMOCK_FLAG(catch_leaked_mocks)) || + if (ParseGoogleMockBoolFlag(arg, "catch_leaked_mocks", &GMOCK_FLAG(catch_leaked_mocks)) || ParseGoogleMockStringFlag(arg, "verbose", &GMOCK_FLAG(verbose))) { // Yes. Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being @@ -170,14 +165,10 @@ void InitGoogleMockImpl(int* argc, CharType** argv) { // Since Google Test is needed for Google Mock to work, this function // also initializes Google Test and parses its flags, if that hasn't // been done. -GTEST_API_ void InitGoogleMock(int* argc, char** argv) { - internal::InitGoogleMockImpl(argc, argv); -} +GTEST_API_ void InitGoogleMock(int* argc, char** argv) { internal::InitGoogleMockImpl(argc, argv); } // This overloaded version can be used in Windows programs compiled in // UNICODE mode. -GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { - internal::InitGoogleMockImpl(argc, argv); -} +GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) { internal::InitGoogleMockImpl(argc, argv); } } // namespace testing diff --git a/src/net/test/gmock/src/gmock_main.cc b/src/net/test/gmock/src/gmock_main.cc index bd5be03be2..a5eebcc882 100644 --- a/src/net/test/gmock/src/gmock_main.cc +++ b/src/net/test/gmock/src/gmock_main.cc @@ -39,7 +39,7 @@ // Windows. See the following link to track the current status of this bug: // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT #if GTEST_OS_WINDOWS_MOBILE -# include // NOLINT +# include // NOLINT GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else diff --git a/src/net/test/gtest/include/gtest/gtest-death-test.h b/src/net/test/gtest/include/gtest/gtest-death-test.h index 957a69c6a9..a76da9299f 100644 --- a/src/net/test/gtest/include/gtest/gtest-death-test.h +++ b/src/net/test/gtest/include/gtest/gtest-death-test.h @@ -165,24 +165,21 @@ GTEST_API_ bool InDeathTestChild(); // Asserts that a given statement causes the program to exit, with an // integer exit status that satisfies predicate, and emitting error output // that matches regex. -# define ASSERT_EXIT(statement, predicate, regex) \ - GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) +# define ASSERT_EXIT(statement, predicate, regex) GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) // Like ASSERT_EXIT, but continues on to successive tests in the // test case, if any: -# define EXPECT_EXIT(statement, predicate, regex) \ +# define EXPECT_EXIT(statement, predicate, regex) \ GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) // Asserts that a given statement causes the program to exit, either by // explicitly exiting with a nonzero exit code or being killed by a // signal, and emitting error output that matches regex. -# define ASSERT_DEATH(statement, regex) \ - ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) +# define ASSERT_DEATH(statement, regex) ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) // Like ASSERT_DEATH, but continues on to successive tests in the // test case, if any: -# define EXPECT_DEATH(statement, regex) \ - EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) +# define EXPECT_DEATH(statement, regex) EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: @@ -191,6 +188,7 @@ class GTEST_API_ ExitedWithCode { public: explicit ExitedWithCode(int exit_code); bool operator()(int exit_status) const; + private: // No implementation - assignment is unsupported. void operator=(const ExitedWithCode& other); @@ -198,17 +196,18 @@ class GTEST_API_ ExitedWithCode { const int exit_code_; }; -# if !GTEST_OS_WINDOWS +# if !GTEST_OS_WINDOWS // Tests that an exit code describes an exit due to termination by a // given signal. class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); bool operator()(int exit_status) const; + private: const int signum_; }; -# endif // !GTEST_OS_WINDOWS +# endif // !GTEST_OS_WINDOWS // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. // The death testing framework causes this to have interesting semantics, @@ -253,24 +252,20 @@ class GTEST_API_ KilledBySignal { // EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); // }, "death"); // -# ifdef NDEBUG +# ifdef NDEBUG -# define EXPECT_DEBUG_DEATH(statement, regex) \ - GTEST_EXECUTE_STATEMENT_(statement, regex) +# define EXPECT_DEBUG_DEATH(statement, regex) GTEST_EXECUTE_STATEMENT_(statement, regex) -# define ASSERT_DEBUG_DEATH(statement, regex) \ - GTEST_EXECUTE_STATEMENT_(statement, regex) +# define ASSERT_DEBUG_DEATH(statement, regex) GTEST_EXECUTE_STATEMENT_(statement, regex) -# else +# else -# define EXPECT_DEBUG_DEATH(statement, regex) \ - EXPECT_DEATH(statement, regex) +# define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex) -# define ASSERT_DEBUG_DEATH(statement, regex) \ - ASSERT_DEATH(statement, regex) +# define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex) -# endif // NDEBUG for EXPECT_DEBUG_DEATH -#endif // GTEST_HAS_DEATH_TEST +# endif // NDEBUG for EXPECT_DEBUG_DEATH +#endif // GTEST_HAS_DEATH_TEST // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if @@ -278,15 +273,11 @@ class GTEST_API_ KilledBySignal { // useful when you are combining death test assertions with normal test // assertions in one test. #if GTEST_HAS_DEATH_TEST -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - EXPECT_DEATH(statement, regex) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - ASSERT_DEATH(statement, regex) +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) EXPECT_DEATH(statement, regex) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) ASSERT_DEATH(statement, regex) #else -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) +# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) +# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) #endif } // namespace testing diff --git a/src/net/test/gtest/include/gtest/gtest-message.h b/src/net/test/gtest/include/gtest/gtest-message.h index fe879bca79..dd58a1cf6a 100644 --- a/src/net/test/gtest/include/gtest/gtest-message.h +++ b/src/net/test/gtest/include/gtest/gtest-message.h @@ -98,21 +98,19 @@ class GTEST_API_ Message { } // Constructs a Message from a C-string. - explicit Message(const char* str) : ss_(new ::std::stringstream) { - *ss_ << str; - } + explicit Message(const char* str) : ss_(new ::std::stringstream) { *ss_ << str; } #if GTEST_OS_SYMBIAN // Streams a value (either a pointer or not) to this object. template - inline Message& operator <<(const T& value) { + inline Message& operator<<(const T& value) { StreamHelper(typename internal::is_pointer::type(), value); return *this; } #else // Streams a non-pointer value to this object. template - inline Message& operator <<(const T& val) { + inline Message& operator<<(const T& val) { // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. // @@ -127,7 +125,7 @@ class GTEST_API_ Message { // from the global namespace. With this using declaration, // overloads of << defined in the global namespace and those // visible via Koenig lookup are both exposed in this function. - using ::operator <<; + using ::operator<<; *ss_ << val; return *this; } @@ -146,7 +144,7 @@ class GTEST_API_ Message { // ensure consistent result across compilers, we always treat NULL // as "(null)". template - inline Message& operator <<(T* const& pointer) { // NOLINT + inline Message& operator<<(T* const& pointer) { // NOLINT if (pointer == NULL) { *ss_ << "(null)"; } else { @@ -162,31 +160,29 @@ class GTEST_API_ Message { // templatized version above. Without this definition, streaming // endl or other basic IO manipulators to Message will confuse the // compiler. - Message& operator <<(BasicNarrowIoManip val) { + Message& operator<<(BasicNarrowIoManip val) { *ss_ << val; return *this; } // Instead of 1/0, we want to see true/false for bool values. - Message& operator <<(bool b) { - return *this << (b ? "true" : "false"); - } + Message& operator<<(bool b) { return *this << (b ? "true" : "false"); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. - Message& operator <<(const wchar_t* wide_c_str); - Message& operator <<(wchar_t* wide_c_str); + Message& operator<<(const wchar_t* wide_c_str); + Message& operator<<(wchar_t* wide_c_str); #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. - Message& operator <<(const ::std::wstring& wstr); + Message& operator<<(const ::std::wstring& wstr); #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. - Message& operator <<(const ::wstring& wstr); + Message& operator<<(const ::wstring& wstr); #endif // GTEST_HAS_GLOBAL_WSTRING // Gets the text streamed to this object so far as an std::string. @@ -196,7 +192,6 @@ class GTEST_API_ Message { std::string GetString() const; private: - #if GTEST_OS_SYMBIAN // These are needed as the Nokia Symbian Compiler cannot decide between // const T& and const T* in a function template. The Nokia compiler _can_ @@ -211,11 +206,10 @@ class GTEST_API_ Message { } } template - inline void StreamHelper(internal::false_type /*is_pointer*/, - const T& value) { + inline void StreamHelper(internal::false_type /*is_pointer*/, const T& value) { // See the comments in Message& operator <<(const T&) above for why // we need this using statement. - using ::operator <<; + using ::operator<<; *ss_ << value; } #endif // GTEST_OS_SYMBIAN @@ -229,9 +223,7 @@ class GTEST_API_ Message { }; // Streams a Message to an ostream. -inline std::ostream& operator <<(std::ostream& os, const Message& sb) { - return os << sb.GetString(); -} +inline std::ostream& operator<<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } namespace internal { diff --git a/src/net/test/gtest/include/gtest/gtest-param-test.h b/src/net/test/gtest/include/gtest/gtest-param-test.h index 038f9ba79e..2524e79f86 100644 --- a/src/net/test/gtest/include/gtest/gtest-param-test.h +++ b/src/net/test/gtest/include/gtest/gtest-param-test.h @@ -41,7 +41,6 @@ #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ - // Value-parameterized tests allow you to test your code with different // parameters without writing multiple copies of the same test. // @@ -182,15 +181,15 @@ TEST_P(DerivedTest, DoesBlah) { #include "gtest/internal/gtest-port.h" #if !GTEST_OS_SYMBIAN -# include +# include #endif // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-internal.h" -#include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-param-util-generated.h" +#include "gtest/internal/gtest-param-util.h" #if GTEST_HAS_PARAM_TEST @@ -240,8 +239,7 @@ namespace testing { // template internal::ParamGenerator Range(T start, T end, IncrementT step) { - return internal::ParamGenerator( - new internal::RangeGenerator(start, end, step)); + return internal::ParamGenerator(new internal::RangeGenerator(start, end, step)); } template @@ -305,13 +303,10 @@ internal::ParamGenerator Range(T start, T end) { // ValuesIn(l.begin(), l.end())); // template -internal::ParamGenerator< - typename ::testing::internal::IteratorTraits::value_type> -ValuesIn(ForwardIterator begin, ForwardIterator end) { - typedef typename ::testing::internal::IteratorTraits - ::value_type ParamType; - return internal::ParamGenerator( - new internal::ValuesInIteratorRangeGenerator(begin, end)); +internal::ParamGenerator::value_type> ValuesIn( + ForwardIterator begin, ForwardIterator end) { + typedef typename ::testing::internal::IteratorTraits::value_type ParamType; + return internal::ParamGenerator(new internal::ValuesInIteratorRangeGenerator(begin, end)); } template @@ -320,8 +315,7 @@ internal::ParamGenerator ValuesIn(const T (&array)[N]) { } template -internal::ParamGenerator ValuesIn( - const Container& container) { +internal::ParamGenerator ValuesIn(const Container& container) { return ValuesIn(container.begin(), container.end()); } @@ -365,835 +359,647 @@ internal::ValueArray4 Values(T1 v1, T2 v2, T3 v3, T4 v4) { } template -internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5) { +internal::ValueArray5 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return internal::ValueArray5(v1, v2, v3, v4, v5); } -template -internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6) { +template +internal::ValueArray6 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { return internal::ValueArray6(v1, v2, v3, v4, v5, v6); } -template -internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7) { - return internal::ValueArray7(v1, v2, v3, v4, v5, - v6, v7); -} - -template -internal::ValueArray8 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { - return internal::ValueArray8(v1, v2, v3, v4, - v5, v6, v7, v8); -} - -template -internal::ValueArray9 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { - return internal::ValueArray9(v1, v2, v3, - v4, v5, v6, v7, v8, v9); -} - -template -internal::ValueArray10 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { - return internal::ValueArray10(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10); -} - -template -internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11) { - return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); -} - -template -internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12) { - return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); -} - -template -internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13) { - return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); -} - -template -internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { - return internal::ValueArray14(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14); -} - -template -internal::ValueArray15 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { - return internal::ValueArray15(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15); -} - -template -internal::ValueArray16 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, +template +internal::ValueArray7 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) { + return internal::ValueArray7(v1, v2, v3, v4, v5, v6, v7); +} + +template +internal::ValueArray8 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { + return internal::ValueArray8(v1, v2, v3, v4, v5, v6, v7, v8); +} + +template +internal::ValueArray9 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9) { + return internal::ValueArray9(v1, v2, v3, v4, v5, v6, v7, v8, v9); +} + +template +internal::ValueArray10 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, + T8 v8, T9 v9, T10 v10) { + return internal::ValueArray10(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); +} + +template +internal::ValueArray11 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, + T7 v7, T8 v8, T9 v9, T10 v10, T11 v11) { + return internal::ValueArray11(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, + v11); +} + +template +internal::ValueArray12 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, + T11 v11, T12 v12) { + return internal::ValueArray12(v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12); +} + +template +internal::ValueArray13 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, + T6 v6, T7 v7, T8 v8, T9 v9, + T10 v10, T11 v11, T12 v12, + T13 v13) { + return internal::ValueArray13(v1, v2, v3, v4, v5, v6, v7, v8, + v9, v10, v11, v12, v13); +} + +template +internal::ValueArray14 Values(T1 v1, T2 v2, T3 v3, T4 v4, + T5 v5, T6 v6, T7 v7, T8 v8, + T9 v9, T10 v10, T11 v11, + T12 v12, T13 v13, T14 v14) { + return internal::ValueArray14( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14); +} + +template +internal::ValueArray15 Values( + T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15) { + return internal::ValueArray15( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); +} + +template +internal::ValueArray16 Values( + T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) { - return internal::ValueArray16(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16); -} - -template -internal::ValueArray17 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + return internal::ValueArray16( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); +} + +template +internal::ValueArray17 Values( + T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17) { - return internal::ValueArray17(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17); -} - -template -internal::ValueArray18 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + return internal::ValueArray17( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17); +} + +template +internal::ValueArray18 Values( + T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18) { - return internal::ValueArray18(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18); -} - -template -internal::ValueArray19 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { - return internal::ValueArray19(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); -} - -template -internal::ValueArray20 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { - return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); -} - -template -internal::ValueArray21 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { - return internal::ValueArray21(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); -} - -template -internal::ValueArray22 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22) { - return internal::ValueArray22(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22); -} - -template -internal::ValueArray23 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23) { - return internal::ValueArray23(v1, v2, v3, - v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23); -} - -template -internal::ValueArray24 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24) { - return internal::ValueArray24(v1, v2, - v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, - v19, v20, v21, v22, v23, v24); -} - -template -internal::ValueArray25 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, - T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, - T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { - return internal::ValueArray25(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, - v18, v19, v20, v21, v22, v23, v24, v25); -} - -template -internal::ValueArray26 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26) { - return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, - v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); -} - -template -internal::ValueArray27 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27) { - return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, - v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); -} - -template -internal::ValueArray28 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28) { - return internal::ValueArray28(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, - v28); -} - -template -internal::ValueArray29 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29) { - return internal::ValueArray29(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, - v27, v28, v29); -} - -template -internal::ValueArray30 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { - return internal::ValueArray30(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, - v26, v27, v28, v29, v30); -} - -template -internal::ValueArray31 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { - return internal::ValueArray31(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + return internal::ValueArray18( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18); +} + +template +internal::ValueArray19 Values( + T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, + T16 v16, T17 v17, T18 v18, T19 v19) { + return internal::ValueArray19( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); +} + +template +internal::ValueArray20 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { + return internal::ValueArray20(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20); +} + +template +internal::ValueArray21 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { + return internal::ValueArray21(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21); +} + +template +internal::ValueArray22 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) { + return internal::ValueArray22(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, + v17, v18, v19, v20, v21, v22); +} + +template +internal::ValueArray23 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) { + return internal::ValueArray23(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23); +} + +template +internal::ValueArray24 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) { + return internal::ValueArray24(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, + v15, v16, v17, v18, v19, v20, v21, v22, v23, v24); +} + +template +internal::ValueArray25 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { + return internal::ValueArray25(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, + v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25); +} + +template +internal::ValueArray26 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26) { + return internal::ValueArray26(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, + v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, + v23, v24, v25, v26); +} + +template +internal::ValueArray27 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27) { + return internal::ValueArray27(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, + v12, v13, v14, v15, v16, v17, v18, v19, v20, + v21, v22, v23, v24, v25, v26, v27); +} + +template +internal::ValueArray28 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28) { + return internal::ValueArray28( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28); +} + +template +internal::ValueArray29 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29) { + return internal::ValueArray29( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29); +} + +template +internal::ValueArray30 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30) { + return internal::ValueArray30( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30); +} + +template +internal::ValueArray31 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { + return internal::ValueArray31( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); } -template -internal::ValueArray32 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32) { - return internal::ValueArray32(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32); -} - -template -internal::ValueArray33 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33) { - return internal::ValueArray33(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); -} - -template -internal::ValueArray34 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, - T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, - T31 v31, T32 v32, T33 v33, T34 v34) { - return internal::ValueArray34(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, - v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); -} - -template -internal::ValueArray35 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { - return internal::ValueArray35(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, - v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); -} - -template -internal::ValueArray36 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { - return internal::ValueArray36(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36); -} - -template -internal::ValueArray37 Values(T1 v1, T2 v2, T3 v3, - T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37) { - return internal::ValueArray37(v1, v2, v3, - v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36, v37); -} - -template -internal::ValueArray38 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37, T38 v38) { - return internal::ValueArray38(v1, v2, - v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, - v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, - v33, v34, v35, v36, v37, v38); -} - -template -internal::ValueArray39 Values(T1 v1, T2 v2, - T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, - T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, - T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, - T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, - T37 v37, T38 v38, T39 v39) { - return internal::ValueArray39(v1, - v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, - v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, - v32, v33, v34, v35, v36, v37, v38, v39); -} - -template -internal::ValueArray40 Values(T1 v1, - T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, - T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, - T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, - T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, - T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { - return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, - v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, - v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); -} - -template -internal::ValueArray41 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { - return internal::ValueArray41(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, - v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, - v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); -} - -template -internal::ValueArray42 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42) { - return internal::ValueArray42(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, - v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, - v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, - v42); -} - -template -internal::ValueArray43 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43) { - return internal::ValueArray43(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, - v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, - v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, - v41, v42, v43); -} - -template -internal::ValueArray44 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44) { - return internal::ValueArray44(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, - v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, - v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, - v40, v41, v42, v43, v44); -} - -template -internal::ValueArray45 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, - T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, - T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { - return internal::ValueArray45(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, - v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, - v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, - v39, v40, v41, v42, v43, v44, v45); -} - -template -internal::ValueArray46 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { - return internal::ValueArray46(v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, - v38, v39, v40, v41, v42, v43, v44, v45, v46); -} - -template -internal::ValueArray47 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { - return internal::ValueArray47(v1, v2, v3, v4, v5, v6, v7, v8, - v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, - v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, - v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); -} - -template -internal::ValueArray48 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, - T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, - T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, - T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, - T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, - T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, - T48 v48) { - return internal::ValueArray48(v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, - v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, - v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); -} - -template -internal::ValueArray49 Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, - T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, - T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, - T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, - T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, - T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, - T47 v47, T48 v48, T49 v49) { - return internal::ValueArray49(v1, v2, v3, v4, v5, v6, - v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, - v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, - v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); -} - -template -internal::ValueArray50 Values(T1 v1, T2 v2, T3 v3, T4 v4, - T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, - T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, - T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, - T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, - T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, - T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { - return internal::ValueArray50(v1, v2, v3, v4, - v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, - v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, +template +internal::ValueArray32 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) { + return internal::ValueArray32( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32); +} + +template +internal::ValueArray33 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33) { + return internal::ValueArray33( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33); +} + +template +internal::ValueArray34 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34) { + return internal::ValueArray34( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); +} + +template +internal::ValueArray35 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { + return internal::ValueArray35( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); +} + +template +internal::ValueArray36 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { + return internal::ValueArray36( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36); +} + +template +internal::ValueArray37 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37) { + return internal::ValueArray37(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, + v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, + v35, v36, v37); +} + +template +internal::ValueArray38 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) { + return internal::ValueArray38(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, + v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, + v33, v34, v35, v36, v37, v38); +} + +template +internal::ValueArray39 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39) { + return internal::ValueArray39(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, + v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, + v31, v32, v33, v34, v35, v36, v37, v38, v39); +} + +template +internal::ValueArray40 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40) { + return internal::ValueArray40(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, + v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, + v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); +} + +template +internal::ValueArray41 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41) { + return internal::ValueArray41( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); +} + +template +internal::ValueArray42 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42) { + return internal::ValueArray42( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42); +} + +template +internal::ValueArray43 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43) { + return internal::ValueArray43( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43); +} + +template +internal::ValueArray44 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44) { + return internal::ValueArray44( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44); +} + +template +internal::ValueArray45 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { + return internal::ValueArray45( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45); +} + +template +internal::ValueArray46 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { + return internal::ValueArray46( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46); +} + +template +internal::ValueArray47 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { + return internal::ValueArray47( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, + v47); +} + +template +internal::ValueArray48 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) { + return internal::ValueArray48( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, + v48); +} + +template +internal::ValueArray49 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49) { + return internal::ValueArray49( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, + v48, v49); +} + +template +internal::ValueArray50 +Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, + T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, + T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, + T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { + return internal::ValueArray50( + v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, + v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50); } @@ -1217,11 +1023,9 @@ internal::ValueArray50 Bool() { - return Values(false, true); -} +inline internal::ParamGenerator Bool() { return Values(false, true); } -# if GTEST_HAS_COMBINE +# if GTEST_HAS_COMBINE // Combine() allows the user to combine two or more sequences to produce // values of a Cartesian product of those sequences' elements. // @@ -1271,140 +1075,106 @@ inline internal::ParamGenerator Bool() { // Combine(Bool(), Bool())); // template -internal::CartesianProductHolder2 Combine( - const Generator1& g1, const Generator2& g2) { - return internal::CartesianProductHolder2( - g1, g2); +internal::CartesianProductHolder2 Combine(const Generator1& g1, const Generator2& g2) { + return internal::CartesianProductHolder2(g1, g2); } template -internal::CartesianProductHolder3 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3) { - return internal::CartesianProductHolder3( - g1, g2, g3); -} - -template -internal::CartesianProductHolder4 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4) { - return internal::CartesianProductHolder4( - g1, g2, g3, g4); -} - -template -internal::CartesianProductHolder5 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5) { - return internal::CartesianProductHolder5( - g1, g2, g3, g4, g5); -} - -template -internal::CartesianProductHolder6 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6) { - return internal::CartesianProductHolder6( +internal::CartesianProductHolder3 Combine(const Generator1& g1, + const Generator2& g2, + const Generator3& g3) { + return internal::CartesianProductHolder3(g1, g2, g3); +} + +template +internal::CartesianProductHolder4 Combine(const Generator1& g1, + const Generator2& g2, + const Generator3& g3, + const Generator4& g4) { + return internal::CartesianProductHolder4(g1, g2, g3, g4); +} + +template +internal::CartesianProductHolder5 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5) { + return internal::CartesianProductHolder5(g1, g2, g3, g4, + g5); +} + +template +internal::CartesianProductHolder6 Combine( + const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6) { + return internal::CartesianProductHolder6( g1, g2, g3, g4, g5, g6); } -template -internal::CartesianProductHolder7 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7) { - return internal::CartesianProductHolder7( - g1, g2, g3, g4, g5, g6, g7); -} - -template -internal::CartesianProductHolder8 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8) { - return internal::CartesianProductHolder8( - g1, g2, g3, g4, g5, g6, g7, g8); -} - -template -internal::CartesianProductHolder9 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8, const Generator9& g9) { - return internal::CartesianProductHolder9( - g1, g2, g3, g4, g5, g6, g7, g8, g9); -} - -template -internal::CartesianProductHolder10 Combine( - const Generator1& g1, const Generator2& g2, const Generator3& g3, - const Generator4& g4, const Generator5& g5, const Generator6& g6, - const Generator7& g7, const Generator8& g8, const Generator9& g9, +template +internal::CartesianProductHolder7 +Combine(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7) { + return internal::CartesianProductHolder7(g1, g2, g3, g4, g5, g6, g7); +} + +template +internal::CartesianProductHolder8 +Combine(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8) { + return internal::CartesianProductHolder8(g1, g2, g3, g4, g5, g6, g7, g8); +} + +template +internal::CartesianProductHolder9 +Combine(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9) { + return internal::CartesianProductHolder9(g1, g2, g3, g4, g5, g6, g7, g8, g9); +} + +template +internal::CartesianProductHolder10 +Combine(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, + const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9, const Generator10& g10) { - return internal::CartesianProductHolder10( - g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); -} -# endif // GTEST_HAS_COMBINE - - - -# define TEST_P(test_case_name, test_name) \ - class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - : public test_case_name { \ - public: \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ - virtual void TestBody(); \ - private: \ - static int AddToRegistry() { \ - ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, \ - ::testing::internal::CodeLocation(\ - __FILE__, __LINE__))->AddTestPattern(\ - #test_case_name, \ - #test_name, \ - new ::testing::internal::TestMetaFactory< \ - GTEST_TEST_CLASS_NAME_(\ - test_case_name, test_name)>()); \ - return 0; \ - } \ - static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ - }; \ - int GTEST_TEST_CLASS_NAME_(test_case_name, \ - test_name)::gtest_registering_dummy_ = \ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ - void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() + return internal::CartesianProductHolder10(g1, g2, g3, g4, g5, g6, g7, + g8, g9, g10); +} +# endif // GTEST_HAS_COMBINE + +# define TEST_P(test_case_name, test_name) \ + class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public test_case_name { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + virtual void TestBody(); \ + \ + private: \ + static int AddToRegistry() { \ + ::testing::UnitTest::GetInstance() \ + ->parameterized_test_registry() \ + .GetTestCasePatternHolder(#test_case_name, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ + ->AddTestPattern( \ + #test_case_name, #test_name, \ + new ::testing::internal::TestMetaFactory()); \ + return 0; \ + } \ + static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + }; \ + int GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::gtest_registering_dummy_ = \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ + void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() // The optional last argument to INSTANTIATE_TEST_CASE_P allows the user // to specify a function or functor that generates custom test name suffixes @@ -1418,24 +1188,21 @@ internal::CartesianProductHolder10 \ - gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ - ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ - const ::testing::TestParamInfo& info) { \ - return ::testing::internal::GetParamNameGen \ - (__VA_ARGS__)(info); \ - } \ - int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ - GetTestCasePatternHolder(\ - #test_case_name, \ - ::testing::internal::CodeLocation(\ - __FILE__, __LINE__))->AddTestCaseInstantiation(\ - #prefix, \ - >est_##prefix##test_case_name##_EvalGenerator_, \ - >est_##prefix##test_case_name##_EvalGenerateName_, \ - __FILE__, __LINE__) +# define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \ + ::testing::internal::ParamGenerator gtest_##prefix##test_case_name##_EvalGenerator_() { \ + return generator; \ + } \ + ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ + const ::testing::TestParamInfo& info) { \ + return ::testing::internal::GetParamNameGen(__VA_ARGS__)(info); \ + } \ + int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::UnitTest::GetInstance() \ + ->parameterized_test_registry() \ + .GetTestCasePatternHolder(#test_case_name, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ + ->AddTestCaseInstantiation(#prefix, >est_##prefix##test_case_name##_EvalGenerator_, \ + >est_##prefix##test_case_name##_EvalGenerateName_, __FILE__, __LINE__) } // namespace testing diff --git a/src/net/test/gtest/include/gtest/gtest-printers.h b/src/net/test/gtest/include/gtest/gtest-printers.h index 8a33164cb3..5c26313612 100644 --- a/src/net/test/gtest/include/gtest/gtest-printers.h +++ b/src/net/test/gtest/include/gtest/gtest-printers.h @@ -100,11 +100,11 @@ #include #include #include -#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-port.h" #if GTEST_HAS_STD_TUPLE_ -# include +# include #endif namespace testing { @@ -115,9 +115,7 @@ namespace internal2 { // Prints the given number of bytes in the given object to the given // ostream. -GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, - size_t count, - ::std::ostream* os); +GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ::std::ostream* os); // For selecting which printer to use when a given type has neither << // nor PrintTo(). @@ -137,8 +135,7 @@ class TypeWithoutFormatter { public: // This default version is called when kTypeKind is kOtherType. static void PrintValue(const T& value, ::std::ostream* os) { - PrintBytesInObjectTo(reinterpret_cast(&value), - sizeof(value), os); + PrintBytesInObjectTo(reinterpret_cast(&value), sizeof(value), os); } }; @@ -153,8 +150,7 @@ class TypeWithoutFormatter { static void PrintValue(const T& value, ::std::ostream* os) { const ::testing::internal::string short_str = value.ShortDebugString(); const ::testing::internal::string pretty_str = - short_str.length() <= kProtobufOneLinerMaxLength ? - short_str : ("\n" + value.DebugString()); + short_str.length() <= kProtobufOneLinerMaxLength ? short_str : ("\n" + value.DebugString()); *os << ("<" + pretty_str + ">"); } }; @@ -200,12 +196,11 @@ class TypeWithoutFormatter { // operator<<(std::basic_stream, const Foo&) is more // specific. template -::std::basic_ostream& operator<<( - ::std::basic_ostream& os, const T& x) { - TypeWithoutFormatter::value ? kProtobuf : - internal::ImplicitlyConvertible::value ? - kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); +::std::basic_ostream& operator<<(::std::basic_ostream& os, const T& x) { + TypeWithoutFormatter::value ? kProtobuf + : internal::ImplicitlyConvertible::value + ? kConvertibleToInteger + : kOtherType)>::PrintValue(x, &os); return os; } @@ -272,9 +267,7 @@ namespace internal { template class FormatForComparison { public: - static ::std::string Format(const ToPrint& value) { - return ::testing::PrintToString(value); - } + static ::std::string Format(const ToPrint& value) { return ::testing::PrintToString(value); } }; // Array. @@ -289,13 +282,11 @@ class FormatForComparison { // By default, print C string as pointers to be safe, as we don't know // whether they actually point to a NUL-terminated string. -#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ - template \ - class FormatForComparison { \ - public: \ - static ::std::string Format(CharType* value) { \ - return ::testing::PrintToString(static_cast(value)); \ - } \ +#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ + template \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { return ::testing::PrintToString(static_cast(value)); } \ } GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); @@ -308,13 +299,11 @@ GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); // If a C string is compared with an STL string object, we know it's meant // to point to a NUL-terminated string, and thus can print it as a string. -#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ - template <> \ - class FormatForComparison { \ - public: \ - static ::std::string Format(CharType* value) { \ - return ::testing::PrintToString(value); \ - } \ +#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ + template <> \ + class FormatForComparison { \ + public: \ + static ::std::string Format(CharType* value) { return ::testing::PrintToString(value); } \ } GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); @@ -346,8 +335,7 @@ GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template -std::string FormatForComparisonFailureMessage( - const T1& value, const T2& /* other_operand */) { +std::string FormatForComparisonFailureMessage(const T1& value, const T2& /* other_operand */) { return FormatForComparison::Format(value); } @@ -367,14 +355,12 @@ void UniversalPrint(const T& value, ::std::ostream* os); // Used to print an STL-style container when the user doesn't define // a PrintTo() for it. template -void DefaultPrintTo(IsContainer /* dummy */, - false_type /* is not a pointer */, - const C& container, ::std::ostream* os) { +void DefaultPrintTo(IsContainer /* dummy */, false_type /* is not a pointer */, const C& container, + ::std::ostream* os) { const size_t kMaxCount = 32; // The maximum number of elements to print. *os << '{'; size_t count = 0; - for (typename C::const_iterator it = container.begin(); - it != container.end(); ++it, ++count) { + for (typename C::const_iterator it = container.begin(); it != container.end(); ++it, ++count) { if (count > 0) { *os << ','; if (count == kMaxCount) { // Enough has been printed. @@ -401,9 +387,7 @@ void DefaultPrintTo(IsContainer /* dummy */, // implementation-defined. Therefore they will be printed as raw // bytes.) template -void DefaultPrintTo(IsNotContainer /* dummy */, - true_type /* is a pointer */, - T* p, ::std::ostream* os) { +void DefaultPrintTo(IsNotContainer /* dummy */, true_type /* is a pointer */, T* p, ::std::ostream* os) { if (p == NULL) { *os << "NULL"; } else { @@ -424,8 +408,7 @@ void DefaultPrintTo(IsNotContainer /* dummy */, // even using reinterpret_cast, as earlier versions of gcc // (e.g. 3.4.5) cannot compile the cast when p is a function // pointer. Casting to UInt64 first solves the problem. - *os << reinterpret_cast( - reinterpret_cast(p)); + *os << reinterpret_cast(reinterpret_cast(p)); } } } @@ -433,9 +416,7 @@ void DefaultPrintTo(IsNotContainer /* dummy */, // Used to print a non-container, non-pointer value when the user // doesn't define PrintTo() for it. template -void DefaultPrintTo(IsNotContainer /* dummy */, - false_type /* is not a pointer */, - const T& value, ::std::ostream* os) { +void DefaultPrintTo(IsNotContainer /* dummy */, false_type /* is not a pointer */, const T& value, ::std::ostream* os) { ::testing_internal::DefaultPrintNonContainerTo(value, os); } @@ -492,9 +473,7 @@ inline void PrintTo(char c, ::std::ostream* os) { } // Overloads for other simple built-in types. -inline void PrintTo(bool x, ::std::ostream* os) { - *os << (x ? "true" : "false"); -} +inline void PrintTo(bool x, ::std::ostream* os) { *os << (x ? "true" : "false"); } // Overload for wchar_t type. // Prints a wchar_t as a symbol if it is printable or as its internal @@ -507,24 +486,14 @@ GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); // Overloads for C strings. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); -inline void PrintTo(char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} +inline void PrintTo(char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } // signed/unsigned char is often used for representing binary data, so // we print pointers to it as void* to be safe. -inline void PrintTo(const signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(const unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} +inline void PrintTo(const signed char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } +inline void PrintTo(signed char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } +inline void PrintTo(const unsigned char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } +inline void PrintTo(unsigned char* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } // MSVC can be configured to define wchar_t as a typedef of unsigned // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native @@ -534,9 +503,7 @@ inline void PrintTo(unsigned char* s, ::std::ostream* os) { #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) // Overloads for wide C strings GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); -inline void PrintTo(wchar_t* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} +inline void PrintTo(wchar_t* s, ::std::ostream* os) { PrintTo(ImplicitCast_(s), os); } #endif // Overload for C arrays. Multi-dimensional arrays are printed @@ -555,30 +522,22 @@ void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { // Overloads for ::string and ::std::string. #if GTEST_HAS_GLOBAL_STRING -GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); -inline void PrintTo(const ::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} +GTEST_API_ void PrintStringTo(const ::string& s, ::std::ostream* os); +inline void PrintTo(const ::string& s, ::std::ostream* os) { PrintStringTo(s, os); } #endif // GTEST_HAS_GLOBAL_STRING -GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); -inline void PrintTo(const ::std::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} +GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os); +inline void PrintTo(const ::std::string& s, ::std::ostream* os) { PrintStringTo(s, os); } // Overloads for ::wstring and ::std::wstring. #if GTEST_HAS_GLOBAL_WSTRING -GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} +GTEST_API_ void PrintWideStringTo(const ::wstring& s, ::std::ostream* os); +inline void PrintTo(const ::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING -GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} +GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os); +inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ @@ -597,9 +556,7 @@ void PrintTupleTo(const T& t, ::std::ostream* os); // regardless of whether tr1::tuple is implemented using the // non-standard variadic template feature or not. -inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { - PrintTupleTo(t, os); -} +inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { @@ -622,44 +579,34 @@ void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { } template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } -template -void PrintTo(const ::std::tr1::tuple& t, - ::std::ostream* os) { +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } -template -void PrintTo( - const ::std::tr1::tuple& t, - ::std::ostream* os) { +template +void PrintTo(const ::std::tr1::tuple& t, ::std::ostream* os) { PrintTupleTo(t, os); } #endif // GTEST_HAS_TR1_TUPLE @@ -735,12 +682,10 @@ void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { } } // This overload prints a (const) char array compactly. -GTEST_API_ void UniversalPrintArray( - const char* begin, size_t len, ::std::ostream* os); +GTEST_API_ void UniversalPrintArray(const char* begin, size_t len, ::std::ostream* os); // This overload prints a (const) wchar_t array compactly. -GTEST_API_ void UniversalPrintArray( - const wchar_t* begin, size_t len, ::std::ostream* os); +GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len, ::std::ostream* os); // Implements printing an array type T[N]. template @@ -748,9 +693,7 @@ class UniversalPrinter { public: // Prints the given array, omitting some elements when there are too // many. - static void Print(const T (&a)[N], ::std::ostream* os) { - UniversalPrintArray(a, N, os); - } + static void Print(const T (&a)[N], ::std::ostream* os) { UniversalPrintArray(a, N, os); } }; // Implements printing a reference type T&. @@ -780,23 +723,17 @@ class UniversalPrinter { template class UniversalTersePrinter { public: - static void Print(const T& value, ::std::ostream* os) { - UniversalPrint(value, os); - } + static void Print(const T& value, ::std::ostream* os) { UniversalPrint(value, os); } }; template class UniversalTersePrinter { public: - static void Print(const T& value, ::std::ostream* os) { - UniversalPrint(value, os); - } + static void Print(const T& value, ::std::ostream* os) { UniversalPrint(value, os); } }; template class UniversalTersePrinter { public: - static void Print(const T (&value)[N], ::std::ostream* os) { - UniversalPrinter::Print(value, os); - } + static void Print(const T (&value)[N], ::std::ostream* os) { UniversalPrinter::Print(value, os); } }; template <> class UniversalTersePrinter { @@ -812,9 +749,7 @@ class UniversalTersePrinter { template <> class UniversalTersePrinter { public: - static void Print(char* str, ::std::ostream* os) { - UniversalTersePrinter::Print(str, os); - } + static void Print(char* str, ::std::ostream* os) { UniversalTersePrinter::Print(str, os); } }; #if GTEST_HAS_STD_WSTRING @@ -834,9 +769,7 @@ class UniversalTersePrinter { template <> class UniversalTersePrinter { public: - static void Print(wchar_t* str, ::std::ostream* os) { - UniversalTersePrinter::Print(str, os); - } + static void Print(wchar_t* str, ::std::ostream* os) { UniversalTersePrinter::Print(str, os); } }; template @@ -878,9 +811,7 @@ struct TuplePolicy { struct tuple_element : ::std::tr1::tuple_element {}; template - static typename AddReference< - const typename ::std::tr1::tuple_element::type>::type get( - const Tuple& tuple) { + static typename AddReference::type>::type get(const Tuple& tuple) { return ::std::tr1::get(tuple); } }; @@ -898,8 +829,7 @@ struct TuplePolicy< ::std::tuple > { struct tuple_element : ::std::tuple_element {}; template - static const typename ::std::tuple_element::type& get( - const Tuple& tuple) { + static const typename ::std::tuple_element::type& get(const Tuple& tuple) { return ::std::get(tuple); } }; @@ -924,12 +854,11 @@ struct TuplePrefixPrinter { TuplePrefixPrinter::PrintPrefixTo(t, os); GTEST_INTENTIONAL_CONST_COND_PUSH_() if (N > 1) { - GTEST_INTENTIONAL_CONST_COND_POP_() + GTEST_INTENTIONAL_CONST_COND_POP_() *os << ", "; } - UniversalPrinter< - typename TuplePolicy::template tuple_element::type> - ::Print(TuplePolicy::template get(t), os); + UniversalPrinter::template tuple_element::type>::Print( + TuplePolicy::template get(t), os); } // Tersely prints the first N fields of a tuple to a string vector, @@ -968,8 +897,7 @@ void PrintTupleTo(const Tuple& t, ::std::ostream* os) { template Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { Strings result; - TuplePrefixPrinter::tuple_size>:: - TersePrintPrefixToStrings(value, &result); + TuplePrefixPrinter::tuple_size>::TersePrintPrefixToStrings(value, &result); return result; } #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ diff --git a/src/net/test/gtest/include/gtest/gtest-spi.h b/src/net/test/gtest/include/gtest/gtest-spi.h index f63fa9a1b2..1aeab5976b 100644 --- a/src/net/test/gtest/include/gtest/gtest-spi.h +++ b/src/net/test/gtest/include/gtest/gtest-spi.h @@ -48,8 +48,7 @@ namespace testing { // generated in the same thread that created this object or it can intercept // all generated failures. The scope of this mock object can be controlled with // the second argument to the two arguments constructor. -class GTEST_API_ ScopedFakeTestPartResultReporter - : public TestPartResultReporterInterface { +class GTEST_API_ ScopedFakeTestPartResultReporter : public TestPartResultReporterInterface { public: // The two possible mocking modes of this object. enum InterceptMode { @@ -64,8 +63,7 @@ class GTEST_API_ ScopedFakeTestPartResultReporter explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); // Same as above, but you can choose the interception scope of this object. - ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, - TestPartResultArray* result); + ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, TestPartResultArray* result); // The d'tor restores the previous test part result reporter. virtual ~ScopedFakeTestPartResultReporter(); @@ -76,6 +74,7 @@ class GTEST_API_ ScopedFakeTestPartResultReporter // This method is from the TestPartResultReporterInterface // interface. virtual void ReportTestPartResult(const TestPartResult& result); + private: void Init(); @@ -96,10 +95,9 @@ namespace internal { class GTEST_API_ SingleFailureChecker { public: // The constructor remembers the arguments. - SingleFailureChecker(const TestPartResultArray* results, - TestPartResult::Type type, - const string& substr); + SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const string& substr); ~SingleFailureChecker(); + private: const TestPartResultArray* const results_; const TestPartResult::Type type_; @@ -135,38 +133,36 @@ class GTEST_API_ SingleFailureChecker { // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. -#define EXPECT_FATAL_FAILURE(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ +#define EXPECT_FATAL_FAILURE(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper { \ + public: \ + static void Execute() { statement; } \ + }; \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker(>est_failures, ::testing::TestPartResult::kFatalFailure, \ + (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, >est_failures); \ + GTestExpectFatalFailureHelper::Execute(); \ + } \ } while (::testing::internal::AlwaysFalse()) -#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ALL_THREADS, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ +#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do { \ + class GTestExpectFatalFailureHelper { \ + public: \ + static void Execute() { statement; } \ + }; \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker(>est_failures, ::testing::TestPartResult::kFatalFailure, \ + (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, >est_failures); \ + GTestExpectFatalFailureHelper::Execute(); \ + } \ } while (::testing::internal::AlwaysFalse()) // A macro for testing Google Test assertions or code that's expected to @@ -201,32 +197,32 @@ class GTEST_API_ SingleFailureChecker { // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. -#define EXPECT_NONFATAL_FAILURE(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ +#define EXPECT_NONFATAL_FAILURE(statement, substr) \ + do { \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker(>est_failures, \ + ::testing::TestPartResult::kNonFatalFailure, (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD, >est_failures); \ + if (::testing::internal::AlwaysTrue()) { \ + statement; \ + } \ + } \ } while (::testing::internal::AlwaysFalse()) -#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ - >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ +#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ + do { \ + ::testing::TestPartResultArray gtest_failures; \ + ::testing::internal::SingleFailureChecker gtest_checker(>est_failures, \ + ::testing::TestPartResult::kNonFatalFailure, (substr)); \ + { \ + ::testing::ScopedFakeTestPartResultReporter gtest_reporter( \ + ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, >est_failures); \ + if (::testing::internal::AlwaysTrue()) { \ + statement; \ + } \ + } \ } while (::testing::internal::AlwaysFalse()) #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ diff --git a/src/net/test/gtest/include/gtest/gtest-test-part.h b/src/net/test/gtest/include/gtest/gtest-test-part.h index 77eb844839..44d20e0faf 100644 --- a/src/net/test/gtest/include/gtest/gtest-test-part.h +++ b/src/net/test/gtest/include/gtest/gtest-test-part.h @@ -57,25 +57,19 @@ class GTEST_API_ TestPartResult { // C'tor. TestPartResult does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestPartResult object. - TestPartResult(Type a_type, - const char* a_file_name, - int a_line_number, - const char* a_message) + TestPartResult(Type a_type, const char* a_file_name, int a_line_number, const char* a_message) : type_(a_type), file_name_(a_file_name == NULL ? "" : a_file_name), line_number_(a_line_number), summary_(ExtractSummary(a_message)), - message_(a_message) { - } + message_(a_message) {} // Gets the outcome of the test part. Type type() const { return type_; } // Gets the name of the source file where the test part took place, or // NULL if it's unknown. - const char* file_name() const { - return file_name_.empty() ? NULL : file_name_.c_str(); - } + const char* file_name() const { return file_name_.empty() ? NULL : file_name_.c_str(); } // Gets the line in the source file where the test part took place, // or -1 if it's unknown. @@ -158,13 +152,13 @@ namespace internal { // reported, it only delegates the reporting to the former result reporter. // The original result reporter is restored in the destructor. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -class GTEST_API_ HasNewFatalFailureHelper - : public TestPartResultReporterInterface { +class GTEST_API_ HasNewFatalFailureHelper : public TestPartResultReporterInterface { public: HasNewFatalFailureHelper(); virtual ~HasNewFatalFailureHelper(); virtual void ReportTestPartResult(const TestPartResult& result); bool has_new_fatal_failure() const { return has_new_fatal_failure_; } + private: bool has_new_fatal_failure_; TestPartResultReporterInterface* original_reporter_; diff --git a/src/net/test/gtest/include/gtest/gtest-typed-test.h b/src/net/test/gtest/include/gtest/gtest-typed-test.h index 5f69d5678e..8225e5fce1 100644 --- a/src/net/test/gtest/include/gtest/gtest-typed-test.h +++ b/src/net/test/gtest/include/gtest/gtest-typed-test.h @@ -157,34 +157,29 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); // // Expands to the name of the typedef for the type parameters of the // given test case. -# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ +# define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types) -# define TYPED_TEST_CASE(CaseName, Types) \ - typedef ::testing::internal::TypeList< Types >::type \ - GTEST_TYPE_PARAMS_(CaseName) - -# define TYPED_TEST(CaseName, TestName) \ - template \ - class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ - : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTest< \ - CaseName, \ - ::testing::internal::TemplateSel< \ - GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ - GTEST_TYPE_PARAMS_(CaseName)>::Register(\ - "", ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - #CaseName, #TestName, 0); \ - template \ - void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() +# define TYPED_TEST_CASE(CaseName, Types) \ + typedef ::testing::internal::TypeList::type GTEST_TYPE_PARAMS_(CaseName) + +# define TYPED_TEST(CaseName, TestName) \ + template \ + class GTEST_TEST_CLASS_NAME_(CaseName, TestName) : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ + ::testing::internal::TypeParameterizedTest< \ + CaseName, ::testing::internal::TemplateSel, \ + GTEST_TYPE_PARAMS_(CaseName)>::Register("", ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + #CaseName, #TestName, 0); \ + template \ + void GTEST_TEST_CLASS_NAME_(CaseName, TestName)::TestBody() #endif // GTEST_HAS_TYPED_TEST @@ -197,66 +192,58 @@ INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); // Expands to the namespace name that the type-parameterized tests for // the given type-parameterized test case are defined in. The exact // name of the namespace is subject to change without notice. -# define GTEST_CASE_NAMESPACE_(TestCaseName) \ - gtest_case_##TestCaseName##_ +# define GTEST_CASE_NAMESPACE_(TestCaseName) gtest_case_##TestCaseName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the variable used to remember the names of // the defined tests in the given test case. -# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ - gtest_typed_test_case_p_state_##TestCaseName##_ +# define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) gtest_typed_test_case_p_state_##TestCaseName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. // // Expands to the name of the variable used to remember the names of // the registered tests in the given test case. -# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ - gtest_registered_test_names_##TestCaseName##_ +# define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) gtest_registered_test_names_##TestCaseName##_ // The variables defined in the type-parameterized test macros are // static as typically these macros are used in a .h file that can be // #included in multiple translation units linked together. -# define TYPED_TEST_CASE_P(CaseName) \ - static ::testing::internal::TypedTestCasePState \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) - -# define TYPED_TEST_P(CaseName, TestName) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - template \ - class TestName : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ - __FILE__, __LINE__, #CaseName, #TestName); \ - } \ - template \ - void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() - -# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ - namespace GTEST_CASE_NAMESPACE_(CaseName) { \ - typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ - } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ - GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ - __FILE__, __LINE__, #__VA_ARGS__) +# define TYPED_TEST_CASE_P(CaseName) \ + static ::testing::internal::TypedTestCasePState GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) + +# define TYPED_TEST_P(CaseName, TestName) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + template \ + class TestName : public CaseName { \ + private: \ + typedef CaseName TestFixture; \ + typedef gtest_TypeParam_ TypeParam; \ + virtual void TestBody(); \ + }; \ + static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(__FILE__, __LINE__, #CaseName, #TestName); \ + } \ + template \ + void GTEST_CASE_NAMESPACE_(CaseName)::TestName::TestBody() + +# define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ + namespace GTEST_CASE_NAMESPACE_(CaseName) { \ + typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ + } \ + static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ + GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(__FILE__, __LINE__, #__VA_ARGS__) // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types) -# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ - bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestCase::type>::Register(\ - #Prefix, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_CASE_P_STATE_(CaseName), \ - #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) +# define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ + bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTestCase< \ + CaseName, GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \ + ::testing::internal::TypeList::type>::Register(#Prefix, \ + ::testing::internal::CodeLocation(__FILE__, __LINE__), \ + >EST_TYPED_TEST_CASE_P_STATE_(CaseName), #CaseName, \ + GTEST_REGISTERED_TEST_NAMES_(CaseName)) #endif // GTEST_HAS_TYPED_TEST_P diff --git a/src/net/test/gtest/include/gtest/gtest.h b/src/net/test/gtest/include/gtest/gtest.h index f846c5bd66..ee768dcb49 100644 --- a/src/net/test/gtest/include/gtest/gtest.h +++ b/src/net/test/gtest/include/gtest/gtest.h @@ -55,15 +55,15 @@ #include #include -#include "gtest/internal/gtest-internal.h" -#include "gtest/internal/gtest-string.h" #include "gtest/gtest-death-test.h" #include "gtest/gtest-message.h" #include "gtest/gtest-param-test.h" #include "gtest/gtest-printers.h" -#include "gtest/gtest_prod.h" #include "gtest/gtest-test-part.h" #include "gtest/gtest-typed-test.h" +#include "gtest/gtest_prod.h" +#include "gtest/internal/gtest-internal.h" +#include "gtest/internal/gtest-string.h" // Depending on the platform, different string classes are available. // On Linux, in addition to ::std::string, Google also makes use of @@ -161,8 +161,7 @@ class TestEventRepeater; class UnitTestRecordPropertyTestHelper; class WindowsDeathTest; class UnitTestImpl* GetUnitTestImpl(); -void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const std::string& message); +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message); } // namespace internal @@ -270,10 +269,9 @@ class GTEST_API_ AssertionResult { // we want AssertionResult's copy constructor to be used. template explicit AssertionResult( - const T& success, - typename internal::EnableIf< - !internal::ImplicitlyConvertible::value>::type* - /*enabler*/ = NULL) + const T& success, typename internal::EnableIf::value>::type* + /*enabler*/ + = NULL) : success_(success) {} GTEST_DISABLE_MSC_WARNINGS_POP_() @@ -294,23 +292,21 @@ class GTEST_API_ AssertionResult { // use it when they fail (i.e., the predicate's outcome doesn't match the // assertion's expectation). When nothing has been streamed into the // object, returns an empty string. - const char* message() const { - return message_.get() != NULL ? message_->c_str() : ""; - } + const char* message() const { return message_.get() != NULL ? message_->c_str() : ""; } // TODO(vladl@google.com): Remove this after making sure no clients use it. // Deprecated; please use message() instead. const char* failure_message() const { return message(); } // Streams a custom failure message into this object. - template AssertionResult& operator<<(const T& value) { + template + AssertionResult& operator<<(const T& value) { AppendMessage(Message() << value); return *this; } // Allows streaming basic output manipulators such as endl or flush into // this object. - AssertionResult& operator<<( - ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { + AssertionResult& operator<<(::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { AppendMessage(Message() << basic_manipulator); return *this; } @@ -318,8 +314,7 @@ class GTEST_API_ AssertionResult { private: // Appends the contents of message to message_. void AppendMessage(const Message& a_message) { - if (message_.get() == NULL) - message_.reset(new ::std::string); + if (message_.get() == NULL) message_.reset(new ::std::string); message_->append(a_message.GetString().c_str()); } @@ -452,7 +447,7 @@ class GTEST_API_ Test { // internal method to avoid clashing with names used in user TESTs. void DeleteSelf_() { delete this; } - const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_; + const internal::scoped_ptr gtest_flag_saver_; // Often a user misspells SetUp() as Setup() and spends a long time // wondering why it is never called by Google Test. The declaration of @@ -488,24 +483,16 @@ class TestProperty { // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. - TestProperty(const std::string& a_key, const std::string& a_value) : - key_(a_key), value_(a_value) { - } + TestProperty(const std::string& a_key, const std::string& a_value) : key_(a_key), value_(a_value) {} // Gets the user supplied key. - const char* key() const { - return key_.c_str(); - } + const char* key() const { return key_.c_str(); } // Gets the user supplied value. - const char* value() const { - return value_.c_str(); - } + const char* value() const { return value_.c_str(); } // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const std::string& new_value) { - value_ = new_value; - } + void SetValue(const std::string& new_value) { value_ = new_value; } private: // The key supplied by the user. @@ -571,14 +558,10 @@ class GTEST_API_ TestResult { friend class internal::WindowsDeathTest; // Gets the vector of TestPartResults. - const std::vector& test_part_results() const { - return test_part_results_; - } + const std::vector& test_part_results() const { return test_part_results_; } // Gets the vector of TestProperties. - const std::vector& test_properties() const { - return test_properties_; - } + const std::vector& test_properties() const { return test_properties_; } // Sets the elapsed time. void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } @@ -589,14 +572,12 @@ class GTEST_API_ TestResult { // value will be updated, rather than storing multiple values for the same // key. xml_element specifies the element for which the property is being // recorded and is used for validation. - void RecordProperty(const std::string& xml_element, - const TestProperty& test_property); + void RecordProperty(const std::string& xml_element, const TestProperty& test_property); // Adds a failure if the key is a reserved attribute of Google Test // testcase tags. Returns true if the property is valid. // TODO(russr): Validate attribute names are legal and human readable. - static bool ValidateTestProperty(const std::string& xml_element, - const TestProperty& test_property); + static bool ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property); // Adds a test part result to the list. void AddTestPartResult(const TestPartResult& test_part_result); @@ -656,16 +637,14 @@ class GTEST_API_ TestInfo { // Returns the name of the parameter type, or NULL if this is not a typed // or a type-parameterized test. const char* type_param() const { - if (type_param_.get() != NULL) - return type_param_->c_str(); + if (type_param_.get() != NULL) return type_param_->c_str(); return NULL; } // Returns the text representation of the value parameter, or NULL if this // is not a value-parameterized test. const char* value_param() const { - if (value_param_.get() != NULL) - return value_param_->c_str(); + if (value_param_.get() != NULL) return value_param_->c_str(); return NULL; } @@ -713,43 +692,31 @@ class GTEST_API_ TestInfo { friend class internal::UnitTestImpl; friend class internal::StreamingListenerTest; friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_case_name, - const char* name, - const char* type_param, - const char* value_param, - internal::CodeLocation code_location, - internal::TypeId fixture_class_id, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, - internal::TestFactoryBase* factory); + const char* test_case_name, const char* name, const char* type_param, const char* value_param, + internal::CodeLocation code_location, internal::TypeId fixture_class_id, Test::SetUpTestCaseFunc set_up_tc, + Test::TearDownTestCaseFunc tear_down_tc, internal::TestFactoryBase* factory); // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. - TestInfo(const std::string& test_case_name, - const std::string& name, + TestInfo(const std::string& test_case_name, const std::string& name, const char* a_type_param, // NULL if not a type-parameterized test const char* a_value_param, // NULL if not a value-parameterized test - internal::CodeLocation a_code_location, - internal::TypeId fixture_class_id, + internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory); // Increments the number of death tests encountered in this test so // far. - int increment_death_test_count() { - return result_.increment_death_test_count(); - } + int increment_death_test_count() { return result_.increment_death_test_count(); } // Creates the test object, runs it, records its result, and then // deletes it. void Run(); - static void ClearTestResult(TestInfo* test_info) { - test_info->result_.Clear(); - } + static void ClearTestResult(TestInfo* test_info) { test_info->result_.Clear(); } // These fields are immutable properties of the test. - const std::string test_case_name_; // Test case name - const std::string name_; // Test name + const std::string test_case_name_; // Test case name + const std::string name_; // Test name // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. const internal::scoped_ptr type_param_; @@ -758,10 +725,10 @@ class GTEST_API_ TestInfo { const internal::scoped_ptr value_param_; internal::CodeLocation location_; const internal::TypeId fixture_class_id_; // ID of the test fixture class - bool should_run_; // True iff this test should run - bool is_disabled_; // True iff this test is disabled - bool matches_filter_; // True if this test matches the - // user-specified filter. + bool should_run_; // True iff this test should run + bool is_disabled_; // True iff this test is disabled + bool matches_filter_; // True if this test matches the + // user-specified filter. internal::TestFactoryBase* const factory_; // The factory that creates // the test object @@ -789,8 +756,7 @@ class GTEST_API_ TestCase { // this is not a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case - TestCase(const char* name, const char* a_type_param, - Test::SetUpTestCaseFunc set_up_tc, + TestCase(const char* name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Destructor of TestCase. @@ -802,8 +768,7 @@ class GTEST_API_ TestCase { // Returns the name of the parameter type, or NULL if this is not a // type-parameterized test case. const char* type_param() const { - if (type_param_.get() != NULL) - return type_param_->c_str(); + if (type_param_.get() != NULL) return type_param_->c_str(); return NULL; } @@ -856,9 +821,7 @@ class GTEST_API_ TestCase { std::vector& test_info_list() { return test_info_list_; } // Gets the (immutable) vector of TestInfos in this TestCase. - const std::vector& test_info_list() const { - return test_info_list_; - } + const std::vector& test_info_list() const { return test_info_list_; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. @@ -869,15 +832,13 @@ class GTEST_API_ TestCase { // Adds a TestInfo to this test case. Will delete the TestInfo upon // destruction of the TestCase object. - void AddTestInfo(TestInfo * test_info); + void AddTestInfo(TestInfo* test_info); // Clears the results of all tests in this test case. void ClearResult(); // Clears the results of all tests in the given test case. - static void ClearTestCaseResult(TestCase* test_case) { - test_case->ClearResult(); - } + static void ClearTestCaseResult(TestCase* test_case) { test_case->ClearResult(); } // Runs every test in this TestCase. void Run(); @@ -891,14 +852,10 @@ class GTEST_API_ TestCase { void RunTearDownTestCase() { (*tear_down_tc_)(); } // Returns true iff test passed. - static bool TestPassed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Passed(); - } + static bool TestPassed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Passed(); } // Returns true iff test failed. - static bool TestFailed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Failed(); - } + static bool TestFailed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Failed(); } // Returns true iff the test is disabled and will be reported in the XML // report. @@ -907,19 +864,13 @@ class GTEST_API_ TestCase { } // Returns true iff test is disabled. - static bool TestDisabled(const TestInfo* test_info) { - return test_info->is_disabled_; - } + static bool TestDisabled(const TestInfo* test_info) { return test_info->is_disabled_; } // Returns true iff this test will appear in the XML report. - static bool TestReportable(const TestInfo* test_info) { - return test_info->is_reportable(); - } + static bool TestReportable(const TestInfo* test_info) { return test_info->is_reportable(); } // Returns true if the given test should run. - static bool ShouldRunTest(const TestInfo* test_info) { - return test_info->should_run(); - } + static bool ShouldRunTest(const TestInfo* test_info) { return test_info->should_run(); } // Shuffles the tests in this test case. void ShuffleTests(internal::Random* random); @@ -979,6 +930,7 @@ class Environment { // Override this to define how to tear down the environment. virtual void TearDown() {} + private: // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). @@ -998,8 +950,7 @@ class TestEventListener { // Fired before each iteration of tests starts. There may be more than // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration // index, starting from 0. - virtual void OnTestIterationStart(const UnitTest& unit_test, - int iteration) = 0; + virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration) = 0; // Fired before environment set-up for each iteration of tests starts. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; @@ -1029,8 +980,7 @@ class TestEventListener { virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; // Fired after each iteration of tests finishes. - virtual void OnTestIterationEnd(const UnitTest& unit_test, - int iteration) = 0; + virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0; // Fired after all test activities have ended. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; @@ -1044,8 +994,7 @@ class TestEventListener { class EmptyTestEventListener : public TestEventListener { public: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, - int /*iteration*/) {} + virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} @@ -1055,8 +1004,7 @@ class EmptyTestEventListener : public TestEventListener { virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} - virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, - int /*iteration*/) {} + virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} }; @@ -1081,9 +1029,7 @@ class GTEST_API_ TestEventListeners { // console output. Note that removing this object from the listener list // with Release transfers its ownership to the caller and makes this // function return NULL the next time. - TestEventListener* default_result_printer() const { - return default_result_printer_; - } + TestEventListener* default_result_printer() const { return default_result_printer_; } // Returns the standard listener responsible for the default XML output // controlled by the --gtest_output=xml flag. Can be removed from the @@ -1092,9 +1038,7 @@ class GTEST_API_ TestEventListeners { // removing this object from the listener list with Release transfers its // ownership to the caller and makes this function return NULL the next // time. - TestEventListener* default_xml_generator() const { - return default_xml_generator_; - } + TestEventListener* default_xml_generator() const { return default_xml_generator_; } private: friend class TestCase; @@ -1169,13 +1113,11 @@ class GTEST_API_ UnitTest { // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. - const TestCase* current_test_case() const - GTEST_LOCK_EXCLUDED_(mutex_); + const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. - const TestInfo* current_test_info() const - GTEST_LOCK_EXCLUDED_(mutex_); + const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the random seed used at the start of the current test run. int random_seed() const; @@ -1185,8 +1127,7 @@ class GTEST_API_ UnitTest { // value-parameterized tests and instantiate and register them. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry() - GTEST_LOCK_EXCLUDED_(mutex_); + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_); #endif // GTEST_HAS_PARAM_TEST // Gets the number of successful test cases. @@ -1265,12 +1206,8 @@ class GTEST_API_ UnitTest { // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) // eventually call this to report their results. The user code // should use the assertion macros instead of calling this directly. - void AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, - const std::string& message, - const std::string& os_stack_trace) - GTEST_LOCK_EXCLUDED_(mutex_); + void AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, + const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_); // Adds a TestProperty to the current TestResult object when invoked from // inside a test, to current TestCase's ad_hoc_test_result_ when invoked @@ -1296,9 +1233,7 @@ class GTEST_API_ UnitTest { friend class internal::UnitTestRecordPropertyTestHelper; friend Environment* AddGlobalTestEnvironment(Environment* env); friend internal::UnitTestImpl* internal::GetUnitTestImpl(); - friend void internal::ReportFailureInUnknownLocation( - TestPartResult::Type result_type, - const std::string& message); + friend void internal::ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message); // Creates an empty UnitTest. UnitTest(); @@ -1308,12 +1243,10 @@ class GTEST_API_ UnitTest { // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. - void PushGTestTrace(const internal::TraceInfo& trace) - GTEST_LOCK_EXCLUDED_(mutex_); + void PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_); // Pops a trace from the per-thread Google Test trace stack. - void PopGTestTrace() - GTEST_LOCK_EXCLUDED_(mutex_); + void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_); // Protects mutable state in *impl_. This is mutable as some const // methods need to lock it too. @@ -1347,9 +1280,7 @@ class GTEST_API_ UnitTest { // translation units and the environments have dependencies among them // (remember that the compiler doesn't guarantee the order in which // global variables from different translation units are initialized). -inline Environment* AddGlobalTestEnvironment(Environment* env) { - return UnitTest::GetInstance()->AddEnvironment(env); -} +inline Environment* AddGlobalTestEnvironment(Environment* env) { return UnitTest::GetInstance()->AddEnvironment(env); } // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the @@ -1372,27 +1303,20 @@ namespace internal { // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers // when calling EXPECT_* in a tight loop. template -AssertionResult CmpHelperEQFailure(const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, const T2& rhs) { - return EqFailure(lhs_expression, - rhs_expression, - FormatForComparisonFailureMessage(lhs, rhs), - FormatForComparisonFailureMessage(rhs, lhs), - false); +AssertionResult CmpHelperEQFailure(const char* lhs_expression, const char* rhs_expression, const T1& lhs, + const T2& rhs) { + return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), + FormatForComparisonFailureMessage(rhs, lhs), false); } // The helper function for {ASSERT|EXPECT}_EQ. template -AssertionResult CmpHelperEQ(const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, - const T2& rhs) { -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */) +AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { + GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */) if (lhs == rhs) { return AssertionSuccess(); } -GTEST_DISABLE_MSC_WARNINGS_POP_() + GTEST_DISABLE_MSC_WARNINGS_POP_() return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); } @@ -1400,9 +1324,7 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums // can be implicitly cast to BiggestInt. -GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, +GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs); // The helper class for {ASSERT|EXPECT}_EQ. The template argument @@ -1414,10 +1336,7 @@ class EqHelper { public: // This templatized version is for the general case. template - static AssertionResult Compare(const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, - const T2& rhs) { + static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } @@ -1427,9 +1346,7 @@ class EqHelper { // // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. - static AssertionResult Compare(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, + static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } @@ -1445,37 +1362,29 @@ class EqHelper { // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or // EXPECT_EQ(false, a_bool). template - static AssertionResult Compare( - const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, - const T2& rhs, - // The following line prevents this overload from being considered if T2 - // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) - // expands to Compare("", "", NULL, my_ptr), which requires a conversion - // to match the Secret* in the other overload, which would otherwise make - // this template match better. - typename EnableIf::value>::type* = 0) { + static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs, + // The following line prevents this overload from being considered if T2 + // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) + // expands to Compare("", "", NULL, my_ptr), which requires a conversion + // to match the Secret* in the other overload, which would otherwise make + // this template match better. + typename EnableIf::value>::type* = 0) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } // This version will be picked when the second argument to ASSERT_EQ() is a // pointer, e.g. ASSERT_EQ(NULL, a_pointer). template - static AssertionResult Compare( - const char* lhs_expression, - const char* rhs_expression, - // We used to have a second template parameter instead of Secret*. That - // template parameter would deduce to 'long', making this a better match - // than the first overload even without the first overload's EnableIf. - // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to - // non-pointer argument" (even a deduced integral argument), so the old - // implementation caused warnings in user code. - Secret* /* lhs (NULL) */, - T* rhs) { + static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, + // We used to have a second template parameter instead of Secret*. That + // template parameter would deduce to 'long', making this a better match + // than the first overload even without the first overload's EnableIf. + // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to + // non-pointer argument" (even a deduced integral argument), so the old + // implementation caused warnings in user code. + Secret* /* lhs (NULL) */, T* rhs) { // We already know that 'lhs' is a null pointer. - return CmpHelperEQ(lhs_expression, rhs_expression, - static_cast(NULL), rhs); + return CmpHelperEQ(lhs_expression, rhs_expression, static_cast(NULL), rhs); } }; @@ -1483,13 +1392,11 @@ class EqHelper { // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers // when calling EXPECT_OP in a tight loop. template -AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, - const T1& val1, const T2& val2, +AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, const T1& val1, const T2& val2, const char* op) { - return AssertionFailure() - << "Expected: (" << expr1 << ") " << op << " (" << expr2 - << "), actual: " << FormatForComparisonFailureMessage(val1, val2) - << " vs " << FormatForComparisonFailureMessage(val2, val1); + return AssertionFailure() << "Expected: (" << expr1 << ") " << op << " (" << expr2 + << "), actual: " << FormatForComparisonFailureMessage(val1, val2) << " vs " + << FormatForComparisonFailureMessage(val2, val1); } // A macro for implementing the helper functions needed to implement @@ -1503,18 +1410,16 @@ AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -template \ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - const T1& val1, const T2& val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ - }\ -}\ -GTEST_API_ AssertionResult CmpHelper##op_name(\ - const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) +#define GTEST_IMPL_CMP_HELPER_(op_name, op) \ + template \ + AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, const T1& val1, const T2& val2) { \ + if (val1 op val2) { \ + return AssertionSuccess(); \ + } else { \ + return CmpHelperOpFailure(expr1, expr2, val1, val2, #op); \ + } \ + } \ + GTEST_API_ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. @@ -1534,50 +1439,37 @@ GTEST_IMPL_CMP_HELPER_(GT, >); // The helper function for {ASSERT|EXPECT}_STREQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, - const char* s2_expression, - const char* s1, +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, - const char* s2_expression, - const char* s1, +GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRNE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASENE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, +GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); - // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, +GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2); // Helper function for *_STRNE on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, +GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2); } // namespace internal @@ -1590,32 +1482,24 @@ GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, // // The {needle,haystack}_expr arguments are the stringified // expressions that generated the two real arguments. -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, + const char* haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, + const wchar_t* haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, + const char* haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, + const wchar_t* haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::string& needle, + const ::std::string& haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, + const ::std::string& needle, const ::std::string& haystack); #if GTEST_HAS_STD_WSTRING -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, + const ::std::wstring& haystack); +GTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, + const ::std::wstring& needle, const ::std::wstring& haystack); #endif // GTEST_HAS_STD_WSTRING namespace internal { @@ -1628,9 +1512,7 @@ namespace internal { // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template -AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, - const char* rhs_expression, - RawType lhs_value, +AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, const char* rhs_expression, RawType lhs_value, RawType rhs_value) { const FloatingPoint lhs(lhs_value), rhs(rhs_value); @@ -1639,39 +1521,26 @@ AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, } ::std::stringstream lhs_ss; - lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << lhs_value; + lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) << lhs_value; ::std::stringstream rhs_ss; - rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << rhs_value; - - return EqFailure(lhs_expression, - rhs_expression, - StringStreamToString(&lhs_ss), - StringStreamToString(&rhs_ss), - false); + rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) << rhs_value; + + return EqFailure(lhs_expression, rhs_expression, StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), false); } // Helper function for implementing ASSERT_NEAR. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error); +GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, + double val1, double val2, double abs_error); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // A class that enables one to stream messages to assertion macros class GTEST_API_ AssertHelper { public: // Constructor. - AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message); + AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message); ~AssertHelper(); // Message assignment is a semantic trick to enable assertion @@ -1684,11 +1553,8 @@ class GTEST_API_ AssertHelper { // re-using stack space even for temporary variables, so every EXPECT_EQ // reserves stack space for another AssertHelper. struct AssertHelperData { - AssertHelperData(TestPartResult::Type t, - const char* srcfile, - int line_num, - const char* msg) - : type(t), file(srcfile), line(line_num), message(msg) { } + AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num, const char* msg) + : type(t), file(srcfile), line(line_num), message(msg) {} TestPartResult::Type const type; const char* const file; @@ -1753,24 +1619,22 @@ class WithParamInterface { // like writing 'WithParamInterface::GetParam()' for a test that // uses a fixture whose parameter type is int. const ParamType& GetParam() const { - GTEST_CHECK_(parameter_ != NULL) - << "GetParam() can only be called inside a value-parameterized test " - << "-- did you intend to write TEST_P instead of TEST_F?"; + GTEST_CHECK_(parameter_ != NULL) << "GetParam() can only be called inside a value-parameterized test " + << "-- did you intend to write TEST_P instead of TEST_F?"; return *parameter_; } private: // Sets parameter value. The caller is responsible for making sure the value // remains alive and unchanged throughout the current test. - static void SetParam(const ParamType* parameter) { - parameter_ = parameter; - } + static void SetParam(const ParamType* parameter) { parameter_ = parameter; } // Static value used for accessing parameter during a test lifetime. static const ParamType* parameter_; // TestClass must be a subclass of WithParamInterface and Test. - template friend class internal::ParameterizedTestFactory; + template + friend class internal::ParameterizedTestFactory; }; template @@ -1780,8 +1644,7 @@ const T* WithParamInterface::parameter_ = NULL; // WithParamInterface, and can just inherit from ::testing::TestWithParam. template -class TestWithParam : public Test, public WithParamInterface { -}; +class TestWithParam : public Test, public WithParamInterface {}; #endif // GTEST_HAS_PARAM_TEST @@ -1809,9 +1672,7 @@ class TestWithParam : public Test, public WithParamInterface { // Generates a nonfatal failure at the given source file location with // a generic message. -#define ADD_FAILURE_AT(file, line) \ - GTEST_MESSAGE_AT_(file, line, "Failed", \ - ::testing::TestPartResult::kNonFatalFailure) +#define ADD_FAILURE_AT(file, line) GTEST_MESSAGE_AT_(file, line, "Failed", ::testing::TestPartResult::kNonFatalFailure) // Generates a fatal failure with a generic message. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") @@ -1819,7 +1680,7 @@ class TestWithParam : public Test, public WithParamInterface { // Define this macro to 1 to omit the definition of FAIL(), which is a // generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_FAIL -# define FAIL() GTEST_FAIL() +# define FAIL() GTEST_FAIL() #endif // Generates a success with a generic message. @@ -1828,7 +1689,7 @@ class TestWithParam : public Test, public WithParamInterface { // Define this macro to 1 to omit the definition of SUCCEED(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_SUCCEED -# define SUCCEED() GTEST_SUCCEED() +# define SUCCEED() GTEST_SUCCEED() #endif // Macros for testing exceptions. @@ -1842,32 +1703,20 @@ class TestWithParam : public Test, public WithParamInterface { #define EXPECT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) -#define EXPECT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) -#define EXPECT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define EXPECT_NO_THROW(statement) GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) +#define EXPECT_ANY_THROW(statement) GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) #define ASSERT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) -#define ASSERT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) -#define ASSERT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) +#define ASSERT_NO_THROW(statement) GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) +#define ASSERT_ANY_THROW(statement) GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) // Boolean assertions. Condition can be either a Boolean expression or an // AssertionResult. For more information on how to use AssertionResult with // these macros see comments on that class. -#define EXPECT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ - GTEST_NONFATAL_FAILURE_) -#define EXPECT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_NONFATAL_FAILURE_) -#define ASSERT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ - GTEST_FATAL_FAILURE_) -#define ASSERT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_FATAL_FAILURE_) +#define EXPECT_TRUE(condition) GTEST_TEST_BOOLEAN_((condition), #condition, false, true, GTEST_NONFATAL_FAILURE_) +#define EXPECT_FALSE(condition) GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, GTEST_NONFATAL_FAILURE_) +#define ASSERT_TRUE(condition) GTEST_TEST_BOOLEAN_((condition), #condition, false, true, GTEST_FATAL_FAILURE_) +#define ASSERT_FALSE(condition) GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, GTEST_FATAL_FAILURE_) // Includes the auto-generated header that implements a family of // generic predicate assertion macros. @@ -1920,60 +1769,46 @@ class TestWithParam : public Test, public WithParamInterface { // ASSERT_GT(records.size(), 0) << "There is no record left."; #define EXPECT_EQ(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal:: \ - EqHelper::Compare, \ - val1, val2) -#define EXPECT_NE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) -#define EXPECT_LE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define EXPECT_LT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define EXPECT_GE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define EXPECT_GT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2) +#define EXPECT_NE(val1, val2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) +#define EXPECT_LE(val1, val2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define EXPECT_LT(val1, val2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define EXPECT_GE(val1, val2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define EXPECT_GT(val1, val2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) #define GTEST_ASSERT_EQ(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal:: \ - EqHelper::Compare, \ - val1, val2) -#define GTEST_ASSERT_NE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) -#define GTEST_ASSERT_LE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define GTEST_ASSERT_LT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define GTEST_ASSERT_GE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define GTEST_ASSERT_GT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) + ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2) +#define GTEST_ASSERT_NE(val1, val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) +#define GTEST_ASSERT_LE(val1, val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) +#define GTEST_ASSERT_LT(val1, val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) +#define GTEST_ASSERT_GE(val1, val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) +#define GTEST_ASSERT_GT(val1, val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of // ASSERT_XY(), which clashes with some users' own code. #if !GTEST_DONT_DEFINE_ASSERT_EQ -# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) +# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_NE -# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) +# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LE -# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) +# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LT -# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) +# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GE -# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) +# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GT -# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) +# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif // C-string Comparisons. All tests treat NULL and any non-NULL string @@ -1992,23 +1827,15 @@ class TestWithParam : public Test, public WithParamInterface { // // These macros evaluate their arguments exactly once. -#define EXPECT_STREQ(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) -#define EXPECT_STRNE(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define EXPECT_STRCASEEQ(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) -#define EXPECT_STRCASENE(s1, s2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) - -#define ASSERT_STREQ(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) -#define ASSERT_STRNE(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define ASSERT_STRCASEEQ(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) -#define ASSERT_STRCASENE(s1, s2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) +#define EXPECT_STREQ(s1, s2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) +#define EXPECT_STRNE(s1, s2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define EXPECT_STRCASEEQ(s1, s2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) +#define EXPECT_STRCASENE(s1, s2) EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) + +#define ASSERT_STREQ(s1, s2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) +#define ASSERT_STRNE(s1, s2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) +#define ASSERT_STRCASEEQ(s1, s2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) +#define ASSERT_STRCASENE(s1, s2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) // Macros for comparing floating-point numbers. // @@ -2024,29 +1851,23 @@ class TestWithParam : public Test, public WithParamInterface { // FloatingPoint template class in gtest-internal.h if you are // interested in the implementation details. -#define EXPECT_FLOAT_EQ(val1, val2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) +#define EXPECT_FLOAT_EQ(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, val1, val2) -#define EXPECT_DOUBLE_EQ(val1, val2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) +#define EXPECT_DOUBLE_EQ(val1, val2) \ + EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, val1, val2) -#define ASSERT_FLOAT_EQ(val1, val2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) +#define ASSERT_FLOAT_EQ(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, val1, val2) -#define ASSERT_DOUBLE_EQ(val1, val2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) +#define ASSERT_DOUBLE_EQ(val1, val2) \ + ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, val1, val2) -#define EXPECT_NEAR(val1, val2, abs_error)\ - EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) +#define EXPECT_NEAR(val1, val2, abs_error) \ + EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, abs_error) -#define ASSERT_NEAR(val1, val2, abs_error)\ - ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) +#define ASSERT_NEAR(val1, val2, abs_error) \ + ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, abs_error) // These predicate format functions work on floating-point values, and // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. @@ -2055,11 +1876,8 @@ class TestWithParam : public Test, public WithParamInterface { // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. -GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2); -GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2); - +GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2); +GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2); #if GTEST_OS_WINDOWS @@ -2072,17 +1890,13 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, // expected result and the actual result with both a human-readable // string representation of the error, if available, as well as the // hex result code. -# define EXPECT_HRESULT_SUCCEEDED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) +# define EXPECT_HRESULT_SUCCEEDED(expr) EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) -# define ASSERT_HRESULT_SUCCEEDED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) +# define ASSERT_HRESULT_SUCCEEDED(expr) ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) -# define EXPECT_HRESULT_FAILED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) +# define EXPECT_HRESULT_FAILED(expr) EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) -# define ASSERT_HRESULT_FAILED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) +# define ASSERT_HRESULT_FAILED(expr) ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) #endif // GTEST_OS_WINDOWS @@ -2096,10 +1910,8 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, // EXPECT_NO_FATAL_FAILURE(Process()); // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; // -#define ASSERT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) -#define EXPECT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) +#define ASSERT_NO_FATAL_FAILURE(statement) GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) +#define EXPECT_NO_FATAL_FAILURE(statement) GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) // Causes a trace (including the source file path, the current line // number, and the given message) to be included in every test failure @@ -2112,9 +1924,9 @@ GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s // to appear in the same block - as long as they are on different // lines. -#define SCOPED_TRACE(message) \ - ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ - __FILE__, __LINE__, ::testing::Message() << (message)) +#define SCOPED_TRACE(message) \ + ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(__FILE__, __LINE__, \ + ::testing::Message() << (message)) // Compile-time assertion for type equality. // StaticAssertTypeEq() compiles iff type1 and type2 are @@ -2177,14 +1989,13 @@ bool StaticAssertTypeEq() { // code. GetTestTypeId() is guaranteed to always return the same // value, as it always calls GetTypeId<>() from the Google Test // framework. -#define GTEST_TEST(test_case_name, test_name)\ - GTEST_TEST_(test_case_name, test_name, \ - ::testing::Test, ::testing::internal::GetTestTypeId()) +#define GTEST_TEST(test_case_name, test_name) \ + GTEST_TEST_(test_case_name, test_name, ::testing::Test, ::testing::internal::GetTestTypeId()) // Define this macro to 1 to omit the definition of TEST(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_TEST -# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) +# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) #endif // Defines a test that uses a test fixture. @@ -2213,9 +2024,8 @@ bool StaticAssertTypeEq() { // EXPECT_EQ(1, b_.size()); // } -#define TEST_F(test_fixture, test_name)\ - GTEST_TEST_(test_fixture, test_name, test_fixture, \ - ::testing::internal::GetTypeId()) +#define TEST_F(test_fixture, test_name) \ + GTEST_TEST_(test_fixture, test_name, test_fixture, ::testing::internal::GetTypeId()) } // namespace testing @@ -2229,8 +2039,6 @@ bool StaticAssertTypeEq() { // namespace and has an all-caps name. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; -inline int RUN_ALL_TESTS() { - return ::testing::UnitTest::GetInstance()->Run(); -} +inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); } #endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/src/net/test/gtest/include/gtest/gtest_pred_impl.h b/src/net/test/gtest/include/gtest/gtest_pred_impl.h index 30ae712f50..e8b7ccbb58 100644 --- a/src/net/test/gtest/include/gtest/gtest_pred_impl.h +++ b/src/net/test/gtest/include/gtest/gtest_pred_impl.h @@ -37,7 +37,7 @@ // Makes sure this header is not included before gtest.h. #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ -# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. +# error Do not include gtest_pred_impl.h directly. Include gtest.h instead. #endif // GTEST_INCLUDE_GTEST_GTEST_H_ // This header implements a family of generic predicate assertion @@ -72,287 +72,165 @@ // GTEST_ASSERT_ is the basic statement to which all of the assertions // in this file reduce. Don't use this in your code. -#define GTEST_ASSERT_(expression, on_failure) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ +#define GTEST_ASSERT_(expression, on_failure) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar = (expression)) \ - ; \ - else \ + ; \ + else \ on_failure(gtest_ar.failure_message()) - // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. -template -AssertionResult AssertPred1Helper(const char* pred_text, - const char* e1, - Pred pred, - const T1& v1) { +template +AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1; + return AssertionFailure() << pred_text << "(" << e1 << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << v1; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Don't use this in your code. -#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, v1), \ - on_failure) +#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) GTEST_ASSERT_(pred_format(#v1, v1), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. -#define GTEST_PRED1_(pred, v1, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ - #v1, \ - pred, \ - v1), on_failure) +#define GTEST_PRED1_(pred, v1, on_failure) GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure) // Unary predicate assertion macros. -#define EXPECT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) - - +#define EXPECT_PRED_FORMAT1(pred_format, v1) GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT1(pred_format, v1) GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. -template -AssertionResult AssertPred2Helper(const char* pred_text, - const char* e1, - const char* e2, - Pred pred, - const T1& v1, +template +AssertionResult AssertPred2Helper(const char* pred_text, const char* e1, const char* e2, Pred pred, const T1& v1, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2; + return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << v1 << "\n" + << e2 << " evaluates to " << v2; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Don't use this in your code. -#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ - on_failure) +#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. -#define GTEST_PRED2_(pred, v1, v2, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ - #v1, \ - #v2, \ - pred, \ - v1, \ - v2), on_failure) +#define GTEST_PRED2_(pred, v1, v2, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), on_failure) // Binary predicate assertion macros. -#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) - - +#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED2(pred, v1, v2) GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED2(pred, v1, v2) GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. -template -AssertionResult AssertPred3Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3) { +template +AssertionResult AssertPred3Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, Pred pred, + const T1& v1, const T2& v2, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3; + return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << v1 << "\n" + << e2 << " evaluates to " << v2 << "\n" + << e3 << " evaluates to " << v3; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Don't use this in your code. -#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ - on_failure) +#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. -#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - pred, \ - v1, \ - v2, \ - v3), on_failure) +#define GTEST_PRED3_(pred, v1, v2, v3, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), on_failure) // Ternary predicate assertion macros. #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ - GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) - - +#define EXPECT_PRED3(pred, v1, v2, v3) GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) +#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) +#define ASSERT_PRED3(pred, v1, v2, v3) GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. -template -AssertionResult AssertPred4Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4) { +template +AssertionResult AssertPred4Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, + Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4; + return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 + << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << v1 << "\n" + << e2 << " evaluates to " << v2 << "\n" + << e3 << " evaluates to " << v3 << "\n" + << e4 << " evaluates to " << v4; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Don't use this in your code. -#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ - on_failure) +#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. -#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4), on_failure) +#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, v1, v2, v3, v4), on_failure) // 4-ary predicate assertion macros. #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED4(pred, v1, v2, v3, v4) GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) - - +#define ASSERT_PRED4(pred, v1, v2, v3, v4) GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. -template -AssertionResult AssertPred5Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, +template +AssertionResult AssertPred5Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, + const char* e5, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); - return AssertionFailure() << pred_text << "(" - << e1 << ", " - << e2 << ", " - << e3 << ", " - << e4 << ", " - << e5 << ") evaluates to false, where" - << "\n" << e1 << " evaluates to " << v1 - << "\n" << e2 << " evaluates to " << v2 - << "\n" << e3 << " evaluates to " << v3 - << "\n" << e4 << " evaluates to " << v4 - << "\n" << e5 << " evaluates to " << v5; + return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ", " << e5 + << ") evaluates to false, where" + << "\n" + << e1 << " evaluates to " << v1 << "\n" + << e2 << " evaluates to " << v2 << "\n" + << e3 << " evaluates to " << v3 << "\n" + << e4 << " evaluates to " << v4 << "\n" + << e5 << " evaluates to " << v5; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Don't use this in your code. -#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ - on_failure) +#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure) \ + GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. -#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - #v5, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4, \ - v5), on_failure) +#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure) \ + GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, pred, v1, v2, v3, v4, v5), on_failure) // 5-ary predicate assertion macros. #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) +#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) - - +#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ diff --git a/src/net/test/gtest/include/gtest/gtest_prod.h b/src/net/test/gtest/include/gtest/gtest_prod.h index da80ddc6c7..e222745ffe 100644 --- a/src/net/test/gtest/include/gtest/gtest_prod.h +++ b/src/net/test/gtest/include/gtest/gtest_prod.h @@ -52,7 +52,6 @@ // // Can call MyClass::MyMethod() here. // } -#define FRIEND_TEST(test_case_name, test_name)\ -friend class test_case_name##_##test_name##_Test +#define FRIEND_TEST(test_case_name, test_name) friend class test_case_name##_##test_name##_Test #endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ diff --git a/src/net/test/gtest/include/gtest/internal/gtest-death-test-internal.h b/src/net/test/gtest/include/gtest/internal/gtest-death-test-internal.h index 2b3a78f5bf..8e3bfeac06 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-death-test-internal.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-death-test-internal.h @@ -76,16 +76,16 @@ class GTEST_API_ DeathTest { // argument is set. If the death test should be skipped, the pointer // is set to NULL; otherwise, it is set to the address of a new concrete // DeathTest object that controls the execution of the current test. - static bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test); + static bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); DeathTest(); - virtual ~DeathTest() { } + virtual ~DeathTest() {} // A helper class that aborts a death test when it's deleted. class ReturnSentinel { public: - explicit ReturnSentinel(DeathTest* test) : test_(test) { } + explicit ReturnSentinel(DeathTest* test) : test_(test) {} ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } + private: DeathTest* const test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); @@ -99,11 +99,7 @@ class GTEST_API_ DeathTest { enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; // An enumeration of the three reasons that a test might be aborted. - enum AbortReason { - TEST_ENCOUNTERED_RETURN_STATEMENT, - TEST_THREW_EXCEPTION, - TEST_DID_NOT_DIE - }; + enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_THREW_EXCEPTION, TEST_DID_NOT_DIE }; // Assumes one of the above roles. virtual TestRole AssumeRole() = 0; @@ -139,16 +135,14 @@ class GTEST_API_ DeathTest { // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: - virtual ~DeathTestFactory() { } - virtual bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test) = 0; + virtual ~DeathTestFactory() {} + virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) = 0; }; // A concrete DeathTestFactory implementation for normal use. class DefaultDeathTestFactory : public DeathTestFactory { public: - virtual bool Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test); + virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); }; // Returns true if exit_status describes a process that was terminated @@ -157,63 +151,57 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. -# if GTEST_HAS_EXCEPTIONS -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } catch (const ::std::exception& gtest_exception) { \ - fprintf(\ - stderr, \ - "\n%s: Caught std::exception-derived exception escaping the " \ - "death test statement. Exception message: %s\n", \ - ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ - gtest_exception.what()); \ - fflush(stderr); \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } catch (...) { \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } - -# else -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) - -# endif +# if GTEST_HAS_EXCEPTIONS +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (const ::std::exception& gtest_exception) { \ + fprintf(stderr, \ + "\n%s: Caught std::exception-derived exception escaping the " \ + "death test statement. Exception message: %s\n", \ + ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), gtest_exception.what()); \ + fflush(stderr); \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } catch (...) { \ + death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ + } + +# else +# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) + +# endif // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // ASSERT_EXIT*, and EXPECT_EXIT*. -# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - const ::testing::internal::RE& gtest_regex = (regex); \ - ::testing::internal::DeathTest* gtest_dt; \ - if (!::testing::internal::DeathTest::Create(#statement, >est_regex, \ - __FILE__, __LINE__, >est_dt)) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - if (gtest_dt != NULL) { \ - ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ - gtest_dt_ptr(gtest_dt); \ - switch (gtest_dt->AssumeRole()) { \ - case ::testing::internal::DeathTest::OVERSEE_TEST: \ - if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - break; \ - case ::testing::internal::DeathTest::EXECUTE_TEST: { \ - ::testing::internal::DeathTest::ReturnSentinel \ - gtest_sentinel(gtest_dt); \ - GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ - gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ - break; \ - } \ - default: \ - break; \ - } \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ - fail(::testing::internal::DeathTest::LastMessage()) +# define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + const ::testing::internal::RE& gtest_regex = (regex); \ + ::testing::internal::DeathTest* gtest_dt; \ + if (!::testing::internal::DeathTest::Create(#statement, >est_regex, __FILE__, __LINE__, >est_dt)) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + if (gtest_dt != NULL) { \ + ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \ + switch (gtest_dt->AssumeRole()) { \ + case ::testing::internal::DeathTest::OVERSEE_TEST: \ + if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ + } \ + break; \ + case ::testing::internal::DeathTest::EXECUTE_TEST: { \ + ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel(gtest_dt); \ + GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ + gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ + break; \ + } \ + default: \ + break; \ + } \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) : fail(::testing::internal::DeathTest::LastMessage()) // The symbol "fail" here expands to something into which a message // can be streamed. @@ -221,28 +209,23 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // NDEBUG mode. In this case we need the statements to be executed, the regex is // ignored, and the macro must accept a streamed message even though the message // is never printed. -# define GTEST_EXECUTE_STATEMENT_(statement, regex) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } else \ - ::testing::Message() +# define GTEST_EXECUTE_STATEMENT_(statement, regex) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } else \ + ::testing::Message() // A class representing the parsed contents of the // --gtest_internal_run_death_test flag, as it existed when // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: - InternalRunDeathTestFlag(const std::string& a_file, - int a_line, - int an_index, - int a_write_fd) - : file_(a_file), line_(a_line), index_(an_index), - write_fd_(a_write_fd) {} + InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index, int a_write_fd) + : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {} ~InternalRunDeathTestFlag() { - if (write_fd_ >= 0) - posix::Close(write_fd_); + if (write_fd_ >= 0) posix::Close(write_fd_); } const std::string& file() const { return file_; } @@ -298,17 +281,16 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_LOG_(WARNING) \ - << "Death tests are not supported on this platform.\n" \ - << "Statement '" #statement "' cannot be verified."; \ - } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - terminator; \ - } else \ +# define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + GTEST_LOG_(WARNING) << "Death tests are not supported on this platform.\n" \ + << "Statement '" #statement "' cannot be verified."; \ + } else if (::testing::internal::AlwaysFalse()) { \ + ::testing::internal::RE::PartialMatch(".*", (regex)); \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + terminator; \ + } else \ ::testing::Message() #endif // GTEST_HAS_DEATH_TEST diff --git a/src/net/test/gtest/include/gtest/internal/gtest-filepath.h b/src/net/test/gtest/include/gtest/internal/gtest-filepath.h index 7a13b4b0de..8ba1404a18 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-filepath.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-filepath.h @@ -58,21 +58,17 @@ namespace internal { class GTEST_API_ FilePath { public: - FilePath() : pathname_("") { } - FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } + FilePath() : pathname_("") {} + FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {} - explicit FilePath(const std::string& pathname) : pathname_(pathname) { - Normalize(); - } + explicit FilePath(const std::string& pathname) : pathname_(pathname) { Normalize(); } FilePath& operator=(const FilePath& rhs) { Set(rhs); return *this; } - void Set(const FilePath& rhs) { - pathname_ = rhs.pathname_; - } + void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } const std::string& string() const { return pathname_; } const char* c_str() const { return pathname_.c_str(); } @@ -84,16 +80,12 @@ class GTEST_API_ FilePath { // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. - static FilePath MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, - const char* extension); + static FilePath MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension); // Given directory = "dir", relative_path = "test.xml", // returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. - static FilePath ConcatPaths(const FilePath& directory, - const FilePath& relative_path); + static FilePath ConcatPaths(const FilePath& directory, const FilePath& relative_path); // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or @@ -103,9 +95,7 @@ class GTEST_API_ FilePath { // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. - static FilePath GenerateUniqueFileName(const FilePath& directory, - const FilePath& base_name, - const char* extension); + static FilePath GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension); // Returns true iff the path is "". bool IsEmpty() const { return pathname_.empty(); } diff --git a/src/net/test/gtest/include/gtest/internal/gtest-internal.h b/src/net/test/gtest/include/gtest/internal/gtest-internal.h index ebd1cf615d..537a2e8cf9 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-internal.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-internal.h @@ -40,14 +40,14 @@ #include "gtest/internal/gtest-port.h" #if GTEST_OS_LINUX -# include -# include -# include -# include +# include +# include +# include +# include #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS -# include +# include #endif #include @@ -61,8 +61,8 @@ #include #include "gtest/gtest-message.h" -#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-filepath.h" +#include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-type-util.h" // Due to C++ preprocessor weirdness, we need double indirection to @@ -74,31 +74,33 @@ // the current line number. For more details, see // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) -#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar +#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar class ProtocolMessage; -namespace proto2 { class Message; } +namespace proto2 { +class Message; +} namespace testing { // Forward declarations. -class AssertionResult; // Result of an assertion. -class Message; // Represents a failure message. -class Test; // Represents a test. -class TestInfo; // Information about a test. -class TestPartResult; // Result of a test part. -class UnitTest; // A collection of test cases. +class AssertionResult; // Result of an assertion. +class Message; // Represents a failure message. +class Test; // Represents a test. +class TestInfo; // Information about a test. +class TestPartResult; // Result of a test part. +class UnitTest; // A collection of test cases. template ::std::string PrintToString(const T& value); namespace internal { -struct TraceInfo; // Information about a trace point. -class ScopedTrace; // Implements scoped trace. -class TestInfoImpl; // Opaque implementation of TestInfo -class UnitTestImpl; // Opaque implementation of UnitTest +struct TraceInfo; // Information about a trace point. +class ScopedTrace; // Implements scoped trace. +class TestInfoImpl; // Opaque implementation of TestInfo +class UnitTestImpl; // Opaque implementation of UnitTest // The text used in failure messages to indicate the start of the // stack trace. @@ -127,15 +129,13 @@ char (&IsNullLiteralHelper(...))[2]; // NOLINT #ifdef GTEST_ELLIPSIS_NEEDS_POD_ // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). -# define GTEST_IS_NULL_LITERAL_(x) false +# define GTEST_IS_NULL_LITERAL_(x) false #else -# define GTEST_IS_NULL_LITERAL_(x) \ - (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) +# define GTEST_IS_NULL_LITERAL_(x) (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) #endif // GTEST_ELLIPSIS_NEEDS_POD_ // Appends the user-supplied message to the Google-Test-generated message. -GTEST_API_ std::string AppendUserMessage( - const std::string& gtest_msg, const Message& user_msg); +GTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg, const Message& user_msg); #if GTEST_HAS_EXCEPTIONS @@ -178,17 +178,15 @@ namespace edit_distance { // Simple implementation of the Wagner–Fischer algorithm. // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm enum EditType { kMatch, kAdd, kRemove, kReplace }; -GTEST_API_ std::vector CalculateOptimalEdits( - const std::vector& left, const std::vector& right); +GTEST_API_ std::vector CalculateOptimalEdits(const std::vector& left, + const std::vector& right); // Same as above, but the input is represented as strings. -GTEST_API_ std::vector CalculateOptimalEdits( - const std::vector& left, - const std::vector& right); +GTEST_API_ std::vector CalculateOptimalEdits(const std::vector& left, + const std::vector& right); // Create a diff of the input strings in Unified diff format. -GTEST_API_ std::string CreateUnifiedDiff(const std::vector& left, - const std::vector& right, +GTEST_API_ std::string CreateUnifiedDiff(const std::vector& left, const std::vector& right, size_t context = 2); } // namespace edit_distance @@ -197,9 +195,7 @@ GTEST_API_ std::string CreateUnifiedDiff(const std::vector& left, // format. // If not null, stores in 'total_line_count' the total number of lines found // in left + right. -GTEST_API_ std::string DiffStrings(const std::string& left, - const std::string& right, - size_t* total_line_count); +GTEST_API_ std::string DiffStrings(const std::string& left, const std::string& right, size_t* total_line_count); // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. @@ -216,18 +212,14 @@ GTEST_API_ std::string DiffStrings(const std::string& left, // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will // be inserted into the message. -GTEST_API_ AssertionResult EqFailure(const char* expected_expression, - const char* actual_expression, - const std::string& expected_value, - const std::string& actual_value, +GTEST_API_ AssertionResult EqFailure(const char* expected_expression, const char* actual_expression, + const std::string& expected_value, const std::string& actual_value, bool ignoring_case); // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -GTEST_API_ std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value); +GTEST_API_ std::string GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, + const char* expression_text, const char* actual_predicate_value, + const char* expected_predicate_value); // This template class represents an IEEE floating-point number // (either single-precision or double-precision, depending on the @@ -268,11 +260,10 @@ class FloatingPoint { // Constants. // # of bits in a number. - static const size_t kBitCount = 8*sizeof(RawType); + static const size_t kBitCount = 8 * sizeof(RawType); // # of fraction bits in a number. - static const size_t kFractionBitCount = - std::numeric_limits::digits - 1; + static const size_t kFractionBitCount = std::numeric_limits::digits - 1; // # of exponent bits in a number. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; @@ -281,8 +272,7 @@ class FloatingPoint { static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); // The mask for the fraction bits. - static const Bits kFractionBitMask = - ~static_cast(0) >> (kExponentBitCount + 1); + static const Bits kFractionBitMask = ~static_cast(0) >> (kExponentBitCount + 1); // The mask for the exponent bits. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); @@ -321,9 +311,7 @@ class FloatingPoint { } // Returns the floating-point number that represent positive infinity. - static RawType Infinity() { - return ReinterpretBits(kExponentBitMask); - } + static RawType Infinity() { return ReinterpretBits(kExponentBitMask); } // Returns the maximum representable finite floating-point number. static RawType Max(); @@ -331,7 +319,7 @@ class FloatingPoint { // Non-static methods // Returns the bits that represents this number. - const Bits &bits() const { return u_.bits_; } + const Bits& bits() const { return u_.bits_; } // Returns the exponent bits of this number. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } @@ -360,8 +348,7 @@ class FloatingPoint { // a NAN must return false. if (is_nan() || rhs.is_nan()) return false; - return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) - <= kMaxUlps; + return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <= kMaxUlps; } private: @@ -386,7 +373,7 @@ class FloatingPoint { // // Read http://en.wikipedia.org/wiki/Signed_number_representations // for more details on signed number representations. - static Bits SignAndMagnitudeToBiased(const Bits &sam) { + static Bits SignAndMagnitudeToBiased(const Bits& sam) { if (kSignBitMask & sam) { // sam represents a negative number. return ~sam + 1; @@ -398,8 +385,7 @@ class FloatingPoint { // Given two numbers in the sign-and-magnitude representation, // returns the distance between them as an unsigned number. - static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, - const Bits &sam2) { + static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1, const Bits& sam2) { const Bits biased1 = SignAndMagnitudeToBiased(sam1); const Bits biased2 = SignAndMagnitudeToBiased(sam2); return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); @@ -411,9 +397,13 @@ class FloatingPoint { // We cannot use std::numeric_limits::max() as it clashes with the max() // macro defined by . template <> -inline float FloatingPoint::Max() { return FLT_MAX; } +inline float FloatingPoint::Max() { + return FLT_MAX; +} template <> -inline double FloatingPoint::Max() { return DBL_MAX; } +inline double FloatingPoint::Max() { + return DBL_MAX; +} // Typedefs the instances of the FloatingPoint template class that we // care to use. @@ -526,16 +516,10 @@ struct CodeLocation { // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. -GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, - const char* name, - const char* type_param, - const char* value_param, - CodeLocation code_location, - TypeId fixture_class_id, - SetUpTestCaseFunc set_up_tc, - TearDownTestCaseFunc tear_down_tc, - TestFactoryBase* factory); +GTEST_API_ TestInfo* MakeAndRegisterTestInfo(const char* test_case_name, const char* name, const char* type_param, + const char* value_param, CodeLocation code_location, + TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, + TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory); // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged @@ -552,23 +536,20 @@ class GTEST_API_ TypedTestCasePState { // Adds the given test name to defined_test_names_ and return true // if the test case hasn't been registered; otherwise aborts the // program. - bool AddTestName(const char* file, int line, const char* case_name, - const char* test_name) { + bool AddTestName(const char* file, int line, const char* case_name, const char* test_name) { if (registered_) { - fprintf(stderr, "%s Test %s must be defined before " + fprintf(stderr, + "%s Test %s must be defined before " "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", FormatFileLocation(file, line).c_str(), test_name, case_name); fflush(stderr); posix::Abort(); } - registered_tests_.insert( - ::std::make_pair(test_name, CodeLocation(file, line))); + registered_tests_.insert(::std::make_pair(test_name, CodeLocation(file, line))); return true; } - bool TestExists(const std::string& test_name) const { - return registered_tests_.count(test_name) > 0; - } + bool TestExists(const std::string& test_name) const { return registered_tests_.count(test_name) > 0; } const CodeLocation& GetCodeLocation(const std::string& test_name) const { RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name); @@ -579,8 +560,7 @@ class GTEST_API_ TypedTestCasePState { // Verifies that registered_tests match the test names in // defined_test_names_; returns registered_tests if successful, or // aborts the program otherwise. - const char* VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests); + const char* VerifyRegisteredTestNames(const char* file, int line, const char* registered_tests); private: typedef ::std::map RegisteredTestsMap; @@ -596,7 +576,8 @@ inline const char* SkipComma(const char* str) { if (comma == NULL) { return NULL; } - while (IsSpace(*(++comma))) {} + while (IsSpace(*(++comma))) { + } return comma; } @@ -609,8 +590,7 @@ inline std::string GetPrefixUntilComma(const char* str) { // Splits a given string on a given delimiter, populating a given // vector with the fields. -void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest); +void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest); // TypeParameterizedTest::Register() // registers a list of type-parameterized tests with Google Test. The @@ -626,9 +606,7 @@ class TypeParameterizedTest { // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, // Types). Valid values for 'index' are [0, N - 1] where N is the // length of Types. - static bool Register(const char* prefix, - CodeLocation code_location, - const char* case_name, const char* test_names, + static bool Register(const char* prefix, CodeLocation code_location, const char* case_name, const char* test_names, int index) { typedef typename Types::Head Type; typedef Fixture FixtureClass; @@ -637,20 +615,15 @@ class TypeParameterizedTest { // First, registers the first type-parameterized test in the type // list. MakeAndRegisterTestInfo( - (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" - + StreamableToString(index)).c_str(), - StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), - GetTypeName().c_str(), + (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" + StreamableToString(index)).c_str(), + StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), GetTypeName().c_str(), NULL, // No value parameter. - code_location, - GetTypeId(), - TestClass::SetUpTestCase, - TestClass::TearDownTestCase, + code_location, GetTypeId(), TestClass::SetUpTestCase, TestClass::TearDownTestCase, new TestFactoryImpl); // Next, recurses (at compile time) with the tail of the type list. - return TypeParameterizedTest - ::Register(prefix, code_location, case_name, test_names, index + 1); + return TypeParameterizedTest::Register(prefix, code_location, case_name, + test_names, index + 1); } }; @@ -658,8 +631,7 @@ class TypeParameterizedTest { template class TypeParameterizedTest { public: - static bool Register(const char* /*prefix*/, CodeLocation, - const char* /*case_name*/, const char* /*test_names*/, + static bool Register(const char* /*prefix*/, CodeLocation, const char* /*case_name*/, const char* /*test_names*/, int /*index*/) { return true; } @@ -672,16 +644,12 @@ class TypeParameterizedTest { template class TypeParameterizedTestCase { public: - static bool Register(const char* prefix, CodeLocation code_location, - const TypedTestCasePState* state, + static bool Register(const char* prefix, CodeLocation code_location, const TypedTestCasePState* state, const char* case_name, const char* test_names) { - std::string test_name = StripTrailingSpaces( - GetPrefixUntilComma(test_names)); + std::string test_name = StripTrailingSpaces(GetPrefixUntilComma(test_names)); if (!state->TestExists(test_name)) { - fprintf(stderr, "Failed to get code location for test %s.%s at %s.", - case_name, test_name.c_str(), - FormatFileLocation(code_location.file.c_str(), - code_location.line).c_str()); + fprintf(stderr, "Failed to get code location for test %s.%s at %s.", case_name, test_name.c_str(), + FormatFileLocation(code_location.file.c_str(), code_location.line).c_str()); fflush(stderr); posix::Abort(); } @@ -690,13 +658,11 @@ class TypeParameterizedTestCase { typedef typename Tests::Head Head; // First, register the first test in 'Test' for each type in 'Types'. - TypeParameterizedTest::Register( - prefix, test_location, case_name, test_names, 0); + TypeParameterizedTest::Register(prefix, test_location, case_name, test_names, 0); // Next, recurses (at compile time) with the tail of the test list. - return TypeParameterizedTestCase - ::Register(prefix, code_location, state, - case_name, SkipComma(test_names)); + return TypeParameterizedTestCase::Register(prefix, code_location, state, + case_name, SkipComma(test_names)); } }; @@ -704,8 +670,7 @@ class TypeParameterizedTestCase { template class TypeParameterizedTestCase { public: - static bool Register(const char* /*prefix*/, CodeLocation, - const TypedTestCasePState* /*state*/, + static bool Register(const char* /*prefix*/, CodeLocation, const TypedTestCasePState* /*state*/, const char* /*case_name*/, const char* /*test_names*/) { return true; } @@ -723,8 +688,7 @@ class TypeParameterizedTestCase { // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( - UnitTest* unit_test, int skip_count); +GTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test, int skip_count); // Helpers for suppressing warnings on unreachable code or constant // condition. @@ -772,29 +736,35 @@ template struct CompileAssertTypesEqual; template -struct CompileAssertTypesEqual { -}; +struct CompileAssertTypesEqual {}; // Removes the reference from a type if it is a reference type, // otherwise leaves it unchanged. This is the same as // tr1::remove_reference, which is not widely available yet. template -struct RemoveReference { typedef T type; }; // NOLINT +struct RemoveReference { + typedef T type; +}; // NOLINT template -struct RemoveReference { typedef T type; }; // NOLINT +struct RemoveReference { + typedef T type; +}; // NOLINT // A handy wrapper around RemoveReference that works when the argument // T depends on template parameters. -#define GTEST_REMOVE_REFERENCE_(T) \ - typename ::testing::internal::RemoveReference::type +#define GTEST_REMOVE_REFERENCE_(T) typename ::testing::internal::RemoveReference::type // Removes const from a type if it is a const type, otherwise leaves // it unchanged. This is the same as tr1::remove_const, which is not // widely available yet. template -struct RemoveConst { typedef T type; }; // NOLINT +struct RemoveConst { + typedef T type; +}; // NOLINT template -struct RemoveConst { typedef T type; }; // NOLINT +struct RemoveConst { + typedef T type; +}; // NOLINT // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above // definition to fail to remove the const in 'const int[3]' and 'const @@ -816,25 +786,26 @@ struct RemoveConst { // A handy wrapper around RemoveConst that works when the argument // T depends on template parameters. -#define GTEST_REMOVE_CONST_(T) \ - typename ::testing::internal::RemoveConst::type +#define GTEST_REMOVE_CONST_(T) typename ::testing::internal::RemoveConst::type // Turns const U&, U&, const U, and U all into U. -#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ - GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) +#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) // Adds reference to a type if it is not a reference type, // otherwise leaves it unchanged. This is the same as // tr1::add_reference, which is not widely available yet. template -struct AddReference { typedef T& type; }; // NOLINT +struct AddReference { + typedef T& type; +}; // NOLINT template -struct AddReference { typedef T& type; }; // NOLINT +struct AddReference { + typedef T& type; +}; // NOLINT // A handy wrapper around AddReference that works when the argument T // depends on template parameters. -#define GTEST_ADD_REFERENCE_(T) \ - typename ::testing::internal::AddReference::type +#define GTEST_ADD_REFERENCE_(T) typename ::testing::internal::AddReference::type // Adds a reference to const on top of T as necessary. For example, // it transforms @@ -845,8 +816,7 @@ struct AddReference { typedef T& type; }; // NOLINT // const char& ==> const char& // // The argument T must depend on some template parameters. -#define GTEST_REFERENCE_TO_CONST_(T) \ - GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) +#define GTEST_REFERENCE_TO_CONST_(T) GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) // ImplicitlyConvertible::value is a compile-time bool // constant that's true iff type From can be implicitly converted to @@ -888,8 +858,7 @@ class ImplicitlyConvertible { // possible loss of data, so we need to temporarily disable the // warning. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244) - static const bool value = - sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; + static const bool value = sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // __BORLANDC__ }; @@ -900,11 +869,8 @@ const bool ImplicitlyConvertible::value; // true iff T is type ProtocolMessage, proto2::Message, or a subclass // of those. template -struct IsAProtocolMessage - : public bool_constant< - ImplicitlyConvertible::value || - ImplicitlyConvertible::value> { -}; +struct IsAProtocolMessage : public bool_constant::value || + ImplicitlyConvertible::value> {}; // When the compiler sees expression IsContainerTest(0), if C is an // STL-style container class, the first overload of IsContainerTest @@ -929,22 +895,27 @@ struct IsAProtocolMessage // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. typedef int IsContainer; template -IsContainer IsContainerTest(int /* dummy */, - typename C::iterator* /* it */ = NULL, +IsContainer IsContainerTest(int /* dummy */, typename C::iterator* /* it */ = NULL, typename C::const_iterator* /* const_it */ = NULL) { return 0; } typedef char IsNotContainer; template -IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } +IsNotContainer IsContainerTest(long /* dummy */) { + return '\0'; +} // EnableIf::type is void when 'Cond' is true, and // undefined when 'Cond' is false. To use SFINAE to make a function // overload only apply when a particular expression is true, add // "typename EnableIf::type* = 0" as the last parameter. -template struct EnableIf; -template<> struct EnableIf { typedef void type; }; // NOLINT +template +struct EnableIf; +template <> +struct EnableIf { + typedef void type; +}; // NOLINT // Utilities for native arrays. @@ -957,11 +928,13 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs); // This generic version is used when k is 0. template -inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } +inline bool ArrayEq(const T& lhs, const U& rhs) { + return lhs == rhs; +} // This overload is used when k >= 1. template -inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { +inline bool ArrayEq(const T (&lhs)[N], const U (&rhs)[N]) { return internal::ArrayEq(lhs, N, rhs); } @@ -971,8 +944,7 @@ inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { template bool ArrayEq(const T* lhs, size_t size, const U* rhs) { for (size_t i = 0; i != size; i++) { - if (!internal::ArrayEq(lhs[i], rhs[i])) - return false; + if (!internal::ArrayEq(lhs[i], rhs[i])) return false; } return true; } @@ -982,8 +954,7 @@ bool ArrayEq(const T* lhs, size_t size, const U* rhs) { template Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { for (Iter it = begin; it != end; ++it) { - if (internal::ArrayEq(*it, elem)) - return it; + if (internal::ArrayEq(*it, elem)) return it; } return end; } @@ -997,11 +968,13 @@ void CopyArray(const T* from, size_t size, U* to); // This generic version is used when k is 0. template -inline void CopyArray(const T& from, U* to) { *to = from; } +inline void CopyArray(const T& from, U* to) { + *to = from; +} // This overload is used when k >= 1. template -inline void CopyArray(const T(&from)[N], U(*to)[N]) { +inline void CopyArray(const T (&from)[N], U (*to)[N]) { internal::CopyArray(from, N, *to); } @@ -1039,23 +1012,16 @@ class NativeArray { typedef const Element* const_iterator; // Constructs from a native array. References the source. - NativeArray(const Element* array, size_t count, RelationToSourceReference) { - InitRef(array, count); - } + NativeArray(const Element* array, size_t count, RelationToSourceReference) { InitRef(array, count); } // Constructs from a native array. Copies the source. - NativeArray(const Element* array, size_t count, RelationToSourceCopy) { - InitCopy(array, count); - } + NativeArray(const Element* array, size_t count, RelationToSourceCopy) { InitCopy(array, count); } // Copy constructor. - NativeArray(const NativeArray& rhs) { - (this->*rhs.clone_)(rhs.array_, rhs.size_); - } + NativeArray(const NativeArray& rhs) { (this->*rhs.clone_)(rhs.array_, rhs.size_); } ~NativeArray() { - if (clone_ != &NativeArray::InitRef) - delete[] array_; + if (clone_ != &NativeArray::InitRef) delete[] array_; } // STL-style container methods. @@ -1063,14 +1029,13 @@ class NativeArray { const_iterator begin() const { return array_; } const_iterator end() const { return array_ + size_; } bool operator==(const NativeArray& rhs) const { - return size() == rhs.size() && - ArrayEq(begin(), size(), rhs.begin()); + return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin()); } private: enum { - kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper< - Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value, + kCheckTypeIsNotConstOrAReference = + StaticAssertTypeEqHelper::value, }; // Initializes this object with a copy of the input. @@ -1100,139 +1065,122 @@ class NativeArray { } // namespace testing #define GTEST_MESSAGE_AT_(file, line, message, result_type) \ - ::testing::internal::AssertHelper(result_type, file, line, message) \ - = ::testing::Message() + ::testing::internal::AssertHelper(result_type, file, line, message) = ::testing::Message() -#define GTEST_MESSAGE_(message, result_type) \ - GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) +#define GTEST_MESSAGE_(message, result_type) GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) -#define GTEST_FATAL_FAILURE_(message) \ - return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) +#define GTEST_FATAL_FAILURE_(message) return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) -#define GTEST_NONFATAL_FAILURE_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) +#define GTEST_NONFATAL_FAILURE_(message) GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) -#define GTEST_SUCCESS_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) +#define GTEST_SUCCESS_(message) GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) // Suppresses MSVC warnings 4072 (unreachable code) for the code following // statement if it returns or throws (or doesn't return or throw in some // situations). #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ - if (::testing::internal::AlwaysTrue()) { statement; } - -#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::ConstCharPtr gtest_msg = "") { \ - bool gtest_caught_expected = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (expected_exception const&) { \ - gtest_caught_expected = true; \ - } \ - catch (...) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws a different type."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - if (!gtest_caught_expected) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws nothing."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ - fail(gtest_msg.value) - -#define GTEST_TEST_NO_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ + if (::testing::internal::AlwaysTrue()) { \ + statement; \ + } + +#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::ConstCharPtr gtest_msg = "") { \ + bool gtest_caught_expected = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (expected_exception const&) { \ + gtest_caught_expected = true; \ + } catch (...) { \ + gtest_msg.value = "Expected: " #statement " throws an exception of type " #expected_exception \ + ".\n Actual: it throws a different type."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + if (!gtest_caught_expected) { \ + gtest_msg.value = "Expected: " #statement " throws an exception of type " #expected_exception \ + ".\n Actual: it throws nothing."; \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__) : fail(gtest_msg.value) + +#define GTEST_TEST_NO_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (...) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail("Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: it throws.") - -#define GTEST_TEST_ANY_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - bool gtest_caught_any = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - gtest_caught_any = true; \ - } \ - if (!gtest_caught_any) { \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__) \ + : fail("Expected: " #statement \ + " doesn't throw an exception.\n" \ + " Actual: it throws.") + +#define GTEST_TEST_ANY_THROW_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ + bool gtest_caught_any = false; \ + try { \ + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + } catch (...) { \ + gtest_caught_any = true; \ + } \ + if (!gtest_caught_any) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ - fail("Expected: " #statement " throws an exception.\n" \ - " Actual: it doesn't.") - + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__) \ + : fail("Expected: " #statement \ + " throws an exception.\n" \ + " Actual: it doesn't.") // Implements Boolean test assertions such as EXPECT_TRUE. expression can be // either a boolean expression or an AssertionResult. text is a textual // represenation of expression as it was passed into the EXPECT_TRUE. -#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar_ = \ - ::testing::AssertionResult(expression)) \ - ; \ - else \ - fail(::testing::internal::GetBoolAssertionFailureMessage(\ - gtest_ar_, text, #actual, #expected).c_str()) - -#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ +#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (const ::testing::AssertionResult gtest_ar_ = ::testing::AssertionResult(expression)) \ + ; \ + else \ + fail(::testing::internal::GetBoolAssertionFailureMessage(gtest_ar_, text, #actual, #expected).c_str()) + +#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + if (::testing::internal::AlwaysTrue()) { \ ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ - fail("Expected: " #statement " doesn't generate new fatal " \ - "failures in the current thread.\n" \ - " Actual: it does.") + GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ + if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ + goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ + } \ + } else \ + GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__) \ + : fail("Expected: " #statement \ + " doesn't generate new fatal " \ + "failures in the current thread.\n" \ + " Actual: it does.") // Expands to the name of the class that implements the given test. -#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ - test_case_name##_##test_name##_Test +#define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) test_case_name##_##test_name##_Test // Helper macro for defining tests. -#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ -class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ - public:\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ - private:\ - virtual void TestBody();\ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ - GTEST_DISALLOW_COPY_AND_ASSIGN_(\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ -};\ -\ -::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ - ::test_info_ =\ - ::testing::internal::MakeAndRegisterTestInfo(\ - #test_case_name, #test_name, NULL, NULL, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - (parent_id), \ - parent_class::SetUpTestCase, \ - parent_class::TearDownTestCase, \ - new ::testing::internal::TestFactoryImpl<\ - GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ -void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() +#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id) \ + class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class { \ + public: \ + GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ + \ + private: \ + virtual void TestBody(); \ + static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ + GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ + }; \ + \ + ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::test_info_ = \ + ::testing::internal::MakeAndRegisterTestInfo( \ + #test_case_name, #test_name, NULL, NULL, ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \ + parent_class::SetUpTestCase, parent_class::TearDownTestCase, \ + new ::testing::internal::TestFactoryImpl); \ + void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ - diff --git a/src/net/test/gtest/include/gtest/internal/gtest-linked_ptr.h b/src/net/test/gtest/include/gtest/internal/gtest-linked_ptr.h index 3602942217..9dfa49a3fc 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-linked_ptr.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-linked_ptr.h @@ -68,8 +68,8 @@ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ -#include #include +#include #include "gtest/internal/gtest-port.h" @@ -89,9 +89,7 @@ GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); class linked_ptr_internal { public: // Create a new circle that includes only this instance. - void join_new() { - next_ = this; - } + void join_new() { next_ = this; } // Many linked_ptr operations may change p.link_ for some linked_ptr // variable p in the same circle as this object. Therefore we need @@ -105,8 +103,7 @@ class linked_ptr_internal { // framework. // Join an existing circle. - void join(linked_ptr_internal const* ptr) - GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + void join(linked_ptr_internal const* ptr) GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { MutexLock lock(&g_linked_ptr_mutex); linked_ptr_internal const* p = ptr; @@ -122,8 +119,7 @@ class linked_ptr_internal { // Leave whatever circle we're part of. Returns true if we were the // last member of the circle. Once this is done, you can join() another. - bool depart() - GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { + bool depart() GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { MutexLock lock(&g_linked_ptr_mutex); if (next_ == this) return true; @@ -153,14 +149,18 @@ class linked_ptr { ~linked_ptr() { depart(); } // Copy an existing linked_ptr<>, adding ourselves to the list of references. - template linked_ptr(linked_ptr const& ptr) { copy(&ptr); } + template + linked_ptr(linked_ptr const& ptr) { + copy(&ptr); + } linked_ptr(linked_ptr const& ptr) { // NOLINT assert(&ptr != this); copy(&ptr); } // Assignment releases the old value and acquires the new. - template linked_ptr& operator=(linked_ptr const& ptr) { + template + linked_ptr& operator=(linked_ptr const& ptr) { depart(); copy(&ptr); return *this; @@ -210,7 +210,8 @@ class linked_ptr { link_.join_new(); } - template void copy(linked_ptr const* ptr) { + template + void copy(linked_ptr const* ptr) { value_ = ptr->get(); if (value_) link_.join(&ptr->link_); @@ -219,13 +220,13 @@ class linked_ptr { } }; -template inline -bool operator==(T* ptr, const linked_ptr& x) { +template +inline bool operator==(T* ptr, const linked_ptr& x) { return ptr == x.get(); } -template inline -bool operator!=(T* ptr, const linked_ptr& x) { +template +inline bool operator!=(T* ptr, const linked_ptr& x) { return ptr != x.get(); } diff --git a/src/net/test/gtest/include/gtest/internal/gtest-param-util-generated.h b/src/net/test/gtest/include/gtest/internal/gtest-param-util-generated.h index 4d1d81d20f..faeca70010 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-param-util-generated.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-param-util-generated.h @@ -59,16 +59,14 @@ namespace testing { // Forward declarations of ValuesIn(), which is implemented in // include/gtest/gtest-param-test.h. template -internal::ParamGenerator< - typename ::testing::internal::IteratorTraits::value_type> -ValuesIn(ForwardIterator begin, ForwardIterator end); +internal::ParamGenerator::value_type> ValuesIn( + ForwardIterator begin, ForwardIterator end); template internal::ParamGenerator ValuesIn(const T (&array)[N]); template -internal::ParamGenerator ValuesIn( - const Container& container); +internal::ParamGenerator ValuesIn(const Container& container); namespace internal { @@ -117,8 +115,7 @@ class ValueArray3 { template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_)}; return ValuesIn(array); } @@ -134,13 +131,11 @@ class ValueArray3 { template class ValueArray4 { public: - ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4) {} + ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), v4_(v4) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_)}; return ValuesIn(array); } @@ -157,13 +152,12 @@ class ValueArray4 { template class ValueArray5 { public: - ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5) {} + ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_)}; return ValuesIn(array); } @@ -178,18 +172,15 @@ class ValueArray5 { const T5 v5_; }; -template +template class ValueArray6 { public: - ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} + ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), + static_cast(v4_), static_cast(v5_), static_cast(v6_)}; return ValuesIn(array); } @@ -205,18 +196,16 @@ class ValueArray6 { const T6 v6_; }; -template +template class ValueArray7 { public: - ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} + ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) + : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_)}; return ValuesIn(array); } @@ -233,19 +222,16 @@ class ValueArray7 { const T7 v7_; }; -template +template class ValueArray8 { public: - ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, - T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8) {} + ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) + : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_)}; return ValuesIn(array); } @@ -263,20 +249,18 @@ class ValueArray8 { const T8 v8_; }; -template +template class ValueArray9 { public: - ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, - T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9) {} + ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) + : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), + static_cast(v4_), static_cast(v5_), static_cast(v6_), + static_cast(v7_), static_cast(v8_), static_cast(v9_)}; return ValuesIn(array); } @@ -295,20 +279,18 @@ class ValueArray9 { const T9 v9_; }; -template +template class ValueArray10 { public: - ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10) {} + ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) + : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_)}; return ValuesIn(array); } @@ -328,21 +310,18 @@ class ValueArray10 { const T10 v10_; }; -template +template class ValueArray11 { public: - ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} + ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11) + : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_)}; return ValuesIn(array); } @@ -363,22 +342,29 @@ class ValueArray11 { const T11 v11_; }; -template +template class ValueArray12 { public: - ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} + ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_)}; return ValuesIn(array); } @@ -400,23 +386,31 @@ class ValueArray12 { const T12 v12_; }; -template +template class ValueArray13 { public: - ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13) {} + ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_)}; return ValuesIn(array); } @@ -439,23 +433,33 @@ class ValueArray13 { const T13 v13_; }; -template +template class ValueArray14 { public: - ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} + ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_)}; return ValuesIn(array); } @@ -479,24 +483,34 @@ class ValueArray14 { const T14 v14_; }; -template +template class ValueArray15 { public: - ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} + ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_)}; return ValuesIn(array); } @@ -521,26 +535,35 @@ class ValueArray15 { const T15 v15_; }; -template +template class ValueArray16 { public: - ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16) {} + ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_)}; return ValuesIn(array); } @@ -566,26 +589,38 @@ class ValueArray16 { const T16 v16_; }; -template +template class ValueArray17 { public: - ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, - T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17) {} + ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_)}; return ValuesIn(array); } @@ -612,27 +647,39 @@ class ValueArray17 { const T17 v17_; }; -template +template class ValueArray18 { public: - ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} + ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_)}; return ValuesIn(array); } @@ -660,27 +707,40 @@ class ValueArray18 { const T18 v18_; }; -template +template class ValueArray19 { public: - ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} + ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_)}; return ValuesIn(array); } @@ -709,28 +769,41 @@ class ValueArray19 { const T19 v19_; }; -template +template class ValueArray20 { public: - ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20) {} + ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_)}; return ValuesIn(array); } @@ -760,30 +833,43 @@ class ValueArray20 { const T20 v20_; }; -template +template class ValueArray21 { public: - ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} + ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_)}; return ValuesIn(array); } @@ -814,30 +900,44 @@ class ValueArray21 { const T21 v21_; }; -template +template class ValueArray22 { public: - ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} + ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_)}; return ValuesIn(array); } @@ -869,31 +969,45 @@ class ValueArray22 { const T22 v22_; }; -template +template class ValueArray23 { public: - ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23) {} + ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_)}; return ValuesIn(array); } @@ -926,32 +1040,47 @@ class ValueArray23 { const T23 v23_; }; -template +template class ValueArray24 { public: - ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24) {} + ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_)}; return ValuesIn(array); } @@ -985,32 +1114,49 @@ class ValueArray24 { const T24 v24_; }; -template +template class ValueArray25 { public: - ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, - T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} + ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_)}; return ValuesIn(array); } @@ -1045,33 +1191,51 @@ class ValueArray25 { const T25 v25_; }; -template +template class ValueArray26 { public: - ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} + ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), + static_cast(v25_), static_cast(v26_)}; return ValuesIn(array); } @@ -1107,35 +1271,52 @@ class ValueArray26 { const T26 v26_; }; -template +template class ValueArray27 { public: - ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27) {} + ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), + static_cast(v25_), static_cast(v26_), static_cast(v27_)}; return ValuesIn(array); } @@ -1172,35 +1353,53 @@ class ValueArray27 { const T27 v27_; }; -template +template class ValueArray28 { public: - ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} + ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), + static_cast(v25_), static_cast(v26_), static_cast(v27_), static_cast(v28_)}; return ValuesIn(array); } @@ -1238,35 +1437,54 @@ class ValueArray28 { const T28 v28_; }; -template +template class ValueArray29 { public: - ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} + ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_)}; return ValuesIn(array); } @@ -1305,37 +1523,55 @@ class ValueArray29 { const T29 v29_; }; -template +template class ValueArray30 { public: - ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30) {} + ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_)}; return ValuesIn(array); } @@ -1375,38 +1611,58 @@ class ValueArray30 { const T30 v30_; }; -template +template class ValueArray31 { public: - ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31) {} + ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), + static_cast(v25_), static_cast(v26_), static_cast(v27_), static_cast(v28_), + static_cast(v29_), static_cast(v30_), static_cast(v31_)}; return ValuesIn(array); } @@ -1447,38 +1703,59 @@ class ValueArray31 { const T31 v31_; }; -template +template class ValueArray32 { public: - ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} + ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), + static_cast(v25_), static_cast(v26_), static_cast(v27_), static_cast(v28_), + static_cast(v29_), static_cast(v30_), static_cast(v31_), static_cast(v32_)}; return ValuesIn(array); } @@ -1520,40 +1797,60 @@ class ValueArray32 { const T32 v32_; }; -template +template class ValueArray33 { public: - ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, - T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33) {} + ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_)}; return ValuesIn(array); } @@ -1596,40 +1893,61 @@ class ValueArray33 { const T33 v33_; }; -template +template class ValueArray34 { public: - ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34) {} + ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_)}; return ValuesIn(array); } @@ -1673,40 +1991,62 @@ class ValueArray34 { const T34 v34_; }; -template +template class ValueArray35 { public: - ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), - v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} + ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_)}; return ValuesIn(array); } @@ -1751,42 +2091,65 @@ class ValueArray35 { const T35 v35_; }; -template +template class ValueArray36 { public: - ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), - v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} + ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_)}; + const T array[] = {static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), + static_cast(v5_), static_cast(v6_), static_cast(v7_), static_cast(v8_), + static_cast(v9_), static_cast(v10_), static_cast(v11_), static_cast(v12_), + static_cast(v13_), static_cast(v14_), static_cast(v15_), static_cast(v16_), + static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), + static_cast(v25_), static_cast(v26_), static_cast(v27_), static_cast(v28_), + static_cast(v29_), static_cast(v30_), static_cast(v31_), static_cast(v32_), + static_cast(v33_), static_cast(v34_), static_cast(v35_), static_cast(v36_)}; return ValuesIn(array); } @@ -1832,42 +2195,65 @@ class ValueArray36 { const T36 v36_; }; -template +template class ValueArray37 { public: - ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), - v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), - v36_(v36), v37_(v37) {} + ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), static_cast(v36_), static_cast(v37_)}; return ValuesIn(array); } @@ -1915,42 +2301,67 @@ class ValueArray37 { const T37 v37_; }; -template +template class ValueArray38 { public: - ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} + ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), static_cast(v36_), static_cast(v37_), static_cast(v38_)}; return ValuesIn(array); } @@ -1999,44 +2410,69 @@ class ValueArray38 { const T38 v38_; }; -template +template class ValueArray39 { public: - ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} + ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_)}; return ValuesIn(array); } @@ -2085,45 +2521,70 @@ class ValueArray39 { const T39 v39_; }; -template +template class ValueArray40 { public: - ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), - v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), - v40_(v40) {} + ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_)}; return ValuesIn(array); } @@ -2173,46 +2634,72 @@ class ValueArray40 { const T40 v40_; }; -template +template class ValueArray41 { public: - ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, - T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41) {} + ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_)}; return ValuesIn(array); } @@ -2263,47 +2750,73 @@ class ValueArray41 { const T41 v41_; }; -template +template class ValueArray42 { public: - ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} + ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_)}; return ValuesIn(array); } @@ -2355,47 +2868,74 @@ class ValueArray42 { const T42 v42_; }; -template +template class ValueArray43 { public: - ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), - v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), - v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), - v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), - v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), - v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), - v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} + ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_)}; return ValuesIn(array); } @@ -2448,48 +2988,75 @@ class ValueArray43 { const T43 v43_; }; -template +template class ValueArray44 { public: - ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), - v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), - v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), - v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), - v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), - v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), - v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), - v43_(v43), v44_(v44) {} + ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43), + v44_(v44) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_), static_cast(v44_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_), static_cast(v44_)}; return ValuesIn(array); } @@ -2543,49 +3110,77 @@ class ValueArray44 { const T44 v44_; }; -template +template class ValueArray45 { public: - ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), - v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), - v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), - v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), - v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), - v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), - v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), - v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} + ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43), + v44_(v44), + v45_(v45) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_), static_cast(v44_), - static_cast(v45_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_), static_cast(v44_), static_cast(v45_)}; return ValuesIn(array); } @@ -2640,50 +3235,79 @@ class ValueArray45 { const T45 v45_; }; -template +template class ValueArray46 { public: - ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), - v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), - v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} + ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43), + v44_(v44), + v45_(v45), + v46_(v46) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_), static_cast(v44_), - static_cast(v45_), static_cast(v46_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_), static_cast(v44_), static_cast(v45_), + static_cast(v46_)}; return ValuesIn(array); } @@ -2739,51 +3363,81 @@ class ValueArray46 { const T46 v46_; }; -template +template class ValueArray47 { public: - ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), - v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), - v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), - v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), - v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), - v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), - v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), - v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), - v47_(v47) {} + ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, + T47 v47) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43), + v44_(v44), + v45_(v45), + v46_(v46), + v47_(v47) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_), static_cast(v44_), - static_cast(v45_), static_cast(v46_), static_cast(v47_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_), static_cast(v44_), static_cast(v45_), + static_cast(v46_), static_cast(v47_)}; return ValuesIn(array); } @@ -2840,52 +3494,82 @@ class ValueArray47 { const T47 v47_; }; -template +template class ValueArray48 { public: - ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), - v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), - v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), - v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), - v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), - v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), - v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), - v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), - v46_(v46), v47_(v47), v48_(v48) {} + ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, + T47 v47, T48 v48) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43), + v44_(v44), + v45_(v45), + v46_(v46), + v47_(v47), + v48_(v48) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_), static_cast(v44_), - static_cast(v45_), static_cast(v46_), static_cast(v47_), - static_cast(v48_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_), static_cast(v44_), static_cast(v45_), + static_cast(v46_), static_cast(v47_), static_cast(v48_)}; return ValuesIn(array); } @@ -2943,52 +3627,83 @@ class ValueArray48 { const T48 v48_; }; -template +template class ValueArray49 { public: - ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, - T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), - v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} + ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, + T47 v47, T48 v48, T49 v49) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43), + v44_(v44), + v45_(v45), + v46_(v46), + v47_(v47), + v48_(v48), + v49_(v49) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_), static_cast(v44_), - static_cast(v45_), static_cast(v46_), static_cast(v47_), - static_cast(v48_), static_cast(v49_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_), static_cast(v44_), static_cast(v45_), + static_cast(v46_), static_cast(v47_), static_cast(v48_), static_cast(v49_)}; return ValuesIn(array); } @@ -3047,52 +3762,84 @@ class ValueArray49 { const T49 v49_; }; -template +template class ValueArray50 { public: - ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, - T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, - T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, - T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, - T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, - T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, - T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), - v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), - v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), - v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), - v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), - v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), - v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), - v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} + ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, + T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, + T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, + T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, + T47 v47, T48 v48, T49 v49, T50 v50) + : v1_(v1), + v2_(v2), + v3_(v3), + v4_(v4), + v5_(v5), + v6_(v6), + v7_(v7), + v8_(v8), + v9_(v9), + v10_(v10), + v11_(v11), + v12_(v12), + v13_(v13), + v14_(v14), + v15_(v15), + v16_(v16), + v17_(v17), + v18_(v18), + v19_(v19), + v20_(v20), + v21_(v21), + v22_(v22), + v23_(v23), + v24_(v24), + v25_(v25), + v26_(v26), + v27_(v27), + v28_(v28), + v29_(v29), + v30_(v30), + v31_(v31), + v32_(v32), + v33_(v33), + v34_(v34), + v35_(v35), + v36_(v36), + v37_(v37), + v38_(v38), + v39_(v39), + v40_(v40), + v41_(v41), + v42_(v42), + v43_(v43), + v44_(v44), + v45_(v45), + v46_(v46), + v47_(v47), + v48_(v48), + v49_(v49), + v50_(v50) {} template operator ParamGenerator() const { - const T array[] = {static_cast(v1_), static_cast(v2_), - static_cast(v3_), static_cast(v4_), static_cast(v5_), - static_cast(v6_), static_cast(v7_), static_cast(v8_), - static_cast(v9_), static_cast(v10_), static_cast(v11_), - static_cast(v12_), static_cast(v13_), static_cast(v14_), - static_cast(v15_), static_cast(v16_), static_cast(v17_), - static_cast(v18_), static_cast(v19_), static_cast(v20_), - static_cast(v21_), static_cast(v22_), static_cast(v23_), - static_cast(v24_), static_cast(v25_), static_cast(v26_), - static_cast(v27_), static_cast(v28_), static_cast(v29_), - static_cast(v30_), static_cast(v31_), static_cast(v32_), - static_cast(v33_), static_cast(v34_), static_cast(v35_), - static_cast(v36_), static_cast(v37_), static_cast(v38_), - static_cast(v39_), static_cast(v40_), static_cast(v41_), - static_cast(v42_), static_cast(v43_), static_cast(v44_), - static_cast(v45_), static_cast(v46_), static_cast(v47_), - static_cast(v48_), static_cast(v49_), static_cast(v50_)}; + const T array[] = { + static_cast(v1_), static_cast(v2_), static_cast(v3_), static_cast(v4_), static_cast(v5_), + static_cast(v6_), static_cast(v7_), static_cast(v8_), static_cast(v9_), static_cast(v10_), + static_cast(v11_), static_cast(v12_), static_cast(v13_), static_cast(v14_), static_cast(v15_), + static_cast(v16_), static_cast(v17_), static_cast(v18_), static_cast(v19_), static_cast(v20_), + static_cast(v21_), static_cast(v22_), static_cast(v23_), static_cast(v24_), static_cast(v25_), + static_cast(v26_), static_cast(v27_), static_cast(v28_), static_cast(v29_), static_cast(v30_), + static_cast(v31_), static_cast(v32_), static_cast(v33_), static_cast(v34_), static_cast(v35_), + static_cast(v36_), static_cast(v37_), static_cast(v38_), static_cast(v39_), static_cast(v40_), + static_cast(v41_), static_cast(v42_), static_cast(v43_), static_cast(v44_), static_cast(v45_), + static_cast(v46_), static_cast(v47_), static_cast(v48_), static_cast(v49_), static_cast(v50_)}; return ValuesIn(array); } @@ -3152,48 +3899,43 @@ class ValueArray50 { const T50 v50_; }; -# if GTEST_HAS_COMBINE +# if GTEST_HAS_COMBINE // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Generates values from the Cartesian product of values produced // by the argument generators. // template -class CartesianProductGenerator2 - : public ParamGeneratorInterface< ::testing::tuple > { +class CartesianProductGenerator2 : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator2(const ParamGenerator& g1, - const ParamGenerator& g2) - : g1_(g1), g2_(g2) {} + CartesianProductGenerator2(const ParamGenerator& g1, const ParamGenerator& g2) : g1_(g1), g2_(g2) {} virtual ~CartesianProductGenerator2() {} virtual ParamIteratorInterface* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); - } + virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -3205,49 +3947,40 @@ class CartesianProductGenerator2 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_) { ComputeCurrentValue(); } void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_); + if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_; + return current1_ == end1_ || current2_ == end2_; } // No implementation - assignment is unsupported. @@ -3272,21 +4005,17 @@ class CartesianProductGenerator2 const ParamGenerator g2_; }; // class CartesianProductGenerator2 - template -class CartesianProductGenerator3 - : public ParamGeneratorInterface< ::testing::tuple > { +class CartesianProductGenerator3 : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator3(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3) + CartesianProductGenerator3(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3) : g1_(g1), g2_(g2), g3_(g3) {} virtual ~CartesianProductGenerator3() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin()); } virtual ParamIteratorInterface* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); @@ -3295,24 +4024,25 @@ class CartesianProductGenerator3 private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -3328,54 +4058,44 @@ class CartesianProductGenerator3 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_) { ComputeCurrentValue(); } void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_); + if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_; } // No implementation - assignment is unsupported. @@ -3404,52 +4124,49 @@ class CartesianProductGenerator3 const ParamGenerator g3_; }; // class CartesianProductGenerator3 - template -class CartesianProductGenerator4 - : public ParamGeneratorInterface< ::testing::tuple > { +class CartesianProductGenerator4 : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator4(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4) + CartesianProductGenerator4(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4) : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} virtual ~CartesianProductGenerator4() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin()); } virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end()); + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3), + begin4_(g4.begin()), + end4_(g4.end()), + current4_(current4) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -3469,60 +4186,47 @@ class CartesianProductGenerator4 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && current4_ == typed_other->current4_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_) { ComputeCurrentValue(); } void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_); + if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_; } // No implementation - assignment is unsupported. @@ -3555,55 +4259,53 @@ class CartesianProductGenerator4 const ParamGenerator g4_; }; // class CartesianProductGenerator4 - template -class CartesianProductGenerator5 - : public ParamGeneratorInterface< ::testing::tuple > { +class CartesianProductGenerator5 : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator5(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5) + CartesianProductGenerator5(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} virtual ~CartesianProductGenerator5() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); } virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end()); + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3), + begin4_(g4.begin()), + end4_(g4.end()), + current4_(current4), + begin5_(g5.begin()), + end5_(g5.end()), + current5_(current5) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -3627,65 +4329,51 @@ class CartesianProductGenerator5 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && + current5_ == typed_other->current5_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_) { ComputeCurrentValue(); } void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_); + if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_; } // No implementation - assignment is unsupported. @@ -3722,61 +4410,59 @@ class CartesianProductGenerator5 const ParamGenerator g5_; }; // class CartesianProductGenerator5 - -template -class CartesianProductGenerator6 - : public ParamGeneratorInterface< ::testing::tuple > { +template +class CartesianProductGenerator6 : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator6(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6) + CartesianProductGenerator6(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} virtual ~CartesianProductGenerator6() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), + g6_, g6_.begin()); } virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, + g6_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3), + begin4_(g4.begin()), + end4_(g4.end()), + current4_(current4), + begin5_(g5.begin()), + end5_(g5.end()), + current5_(current5), + begin6_(g6.begin()), + end6_(g6.end()), + current6_(current6) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -3804,70 +4490,55 @@ class CartesianProductGenerator6 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && current6_ == typed_other->current6_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_) { ComputeCurrentValue(); } void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_); + if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || + current5_ == end5_ || current6_ == end6_; } // No implementation - assignment is unsupported. @@ -3908,65 +4579,64 @@ class CartesianProductGenerator6 const ParamGenerator g6_; }; // class CartesianProductGenerator6 - -template -class CartesianProductGenerator7 - : public ParamGeneratorInterface< ::testing::tuple > { +template +class CartesianProductGenerator7 : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator7(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7) + CartesianProductGenerator7(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, + const ParamGenerator& g7) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} virtual ~CartesianProductGenerator7() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), + g6_, g6_.begin(), g7_, g7_.begin()); } virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, + g6_.end(), g7_, g7_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3), + begin4_(g4.begin()), + end4_(g4.end()), + current4_(current4), + begin5_(g5.begin()), + end5_(g5.end()), + current5_(current5), + begin6_(g6.begin()), + end6_(g6.end()), + current6_(current6), + begin7_(g7.begin()), + end7_(g7.end()), + current7_(current7) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -3998,75 +4668,60 @@ class CartesianProductGenerator7 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && + current7_ == typed_other->current7_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_); + current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || + current5_ == end5_ || current6_ == end6_ || current7_ == end7_; } // No implementation - assignment is unsupported. @@ -4111,71 +4766,68 @@ class CartesianProductGenerator7 const ParamGenerator g7_; }; // class CartesianProductGenerator7 - -template -class CartesianProductGenerator8 - : public ParamGeneratorInterface< ::testing::tuple > { +template +class CartesianProductGenerator8 : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator8(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), - g8_(g8) {} + CartesianProductGenerator8(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, + const ParamGenerator& g7, const ParamGenerator& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8) {} virtual ~CartesianProductGenerator8() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), + g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin()); } virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end()); + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, + g6_.end(), g7_, g7_.end(), g8_, g8_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3), + begin4_(g4.begin()), + end4_(g4.end()), + current4_(current4), + begin5_(g5.begin()), + end5_(g5.end()), + current5_(current5), + begin6_(g6.begin()), + end6_(g6.end()), + current6_(current6), + begin7_(g7.begin()), + end7_(g7.end()), + current7_(current7), + begin8_(g8.begin()), + end8_(g8.end()), + current8_(current8) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -4211,80 +4863,64 @@ class CartesianProductGenerator8 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && current8_ == typed_other->current8_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_); + current_value_ = + ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, *current8_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || + current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_; } // No implementation - assignment is unsupported. @@ -4333,74 +4969,74 @@ class CartesianProductGenerator8 const ParamGenerator g8_; }; // class CartesianProductGenerator8 - -template +template class CartesianProductGenerator9 - : public ParamGeneratorInterface< ::testing::tuple > { + : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator9(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8, const ParamGenerator& g9) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9) {} + CartesianProductGenerator9(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, + const ParamGenerator& g7, const ParamGenerator& g8, const ParamGenerator& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9) {} virtual ~CartesianProductGenerator9() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), + g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); } virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end(), g9_, g9_.end()); + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, + g6_.end(), g7_, g7_.end(), g8_, g8_.end(), g9_, g9_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8, - const ParamGenerator& g9, - const typename ParamGenerator::iterator& current9) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8), - begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3), + begin4_(g4.begin()), + end4_(g4.end()), + current4_(current4), + begin5_(g5.begin()), + end5_(g5.end()), + current5_(current5), + begin6_(g6.begin()), + end6_(g6.end()), + current6_(current6), + begin7_(g7.begin()), + end7_(g7.end()), + current7_(current7), + begin8_(g8.begin()), + end8_(g8.end()), + current8_(current8), + begin9_(g9.begin()), + end9_(g9.end()), + current9_(current9) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -4440,86 +5076,68 @@ class CartesianProductGenerator9 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_ && - current9_ == typed_other->current9_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && current8_ == typed_other->current8_ && + current9_ == typed_other->current9_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_), - begin9_(other.begin9_), - end9_(other.end9_), - current9_(other.current9_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_, - *current9_); + current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, + *current8_, *current9_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_ || - current9_ == end9_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || + current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_ || current9_ == end9_; } // No implementation - assignment is unsupported. @@ -4572,78 +5190,79 @@ class CartesianProductGenerator9 const ParamGenerator g9_; }; // class CartesianProductGenerator9 - -template +template class CartesianProductGenerator10 - : public ParamGeneratorInterface< ::testing::tuple > { + : public ParamGeneratorInterface< ::testing::tuple > { public: typedef ::testing::tuple ParamType; - CartesianProductGenerator10(const ParamGenerator& g1, - const ParamGenerator& g2, const ParamGenerator& g3, - const ParamGenerator& g4, const ParamGenerator& g5, - const ParamGenerator& g6, const ParamGenerator& g7, - const ParamGenerator& g8, const ParamGenerator& g9, - const ParamGenerator& g10) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9), g10_(g10) {} + CartesianProductGenerator10(const ParamGenerator& g1, const ParamGenerator& g2, const ParamGenerator& g3, + const ParamGenerator& g4, const ParamGenerator& g5, const ParamGenerator& g6, + const ParamGenerator& g7, const ParamGenerator& g8, const ParamGenerator& g9, + const ParamGenerator& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9), g10_(g10) {} virtual ~CartesianProductGenerator10() {} virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, - g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, - g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); + return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), + g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); } virtual ParamIteratorInterface* End() const { - return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), - g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, - g8_.end(), g9_, g9_.end(), g10_, g10_.end()); + return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, + g6_.end(), g7_, g7_.end(), g8_, g8_.end(), g9_, g9_.end(), g10_, g10_.end()); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - const ParamGenerator& g1, - const typename ParamGenerator::iterator& current1, - const ParamGenerator& g2, - const typename ParamGenerator::iterator& current2, - const ParamGenerator& g3, - const typename ParamGenerator::iterator& current3, - const ParamGenerator& g4, - const typename ParamGenerator::iterator& current4, - const ParamGenerator& g5, - const typename ParamGenerator::iterator& current5, - const ParamGenerator& g6, - const typename ParamGenerator::iterator& current6, - const ParamGenerator& g7, - const typename ParamGenerator::iterator& current7, - const ParamGenerator& g8, - const typename ParamGenerator::iterator& current8, - const ParamGenerator& g9, - const typename ParamGenerator::iterator& current9, - const ParamGenerator& g10, - const typename ParamGenerator::iterator& current10) + Iterator(const ParamGeneratorInterface* base, const ParamGenerator& g1, + const typename ParamGenerator::iterator& current1, const ParamGenerator& g2, + const typename ParamGenerator::iterator& current2, const ParamGenerator& g3, + const typename ParamGenerator::iterator& current3, const ParamGenerator& g4, + const typename ParamGenerator::iterator& current4, const ParamGenerator& g5, + const typename ParamGenerator::iterator& current5, const ParamGenerator& g6, + const typename ParamGenerator::iterator& current6, const ParamGenerator& g7, + const typename ParamGenerator::iterator& current7, const ParamGenerator& g8, + const typename ParamGenerator::iterator& current8, const ParamGenerator& g9, + const typename ParamGenerator::iterator& current9, const ParamGenerator& g10, + const typename ParamGenerator::iterator& current10) : base_(base), - begin1_(g1.begin()), end1_(g1.end()), current1_(current1), - begin2_(g2.begin()), end2_(g2.end()), current2_(current2), - begin3_(g3.begin()), end3_(g3.end()), current3_(current3), - begin4_(g4.begin()), end4_(g4.end()), current4_(current4), - begin5_(g5.begin()), end5_(g5.end()), current5_(current5), - begin6_(g6.begin()), end6_(g6.end()), current6_(current6), - begin7_(g7.begin()), end7_(g7.end()), current7_(current7), - begin8_(g8.begin()), end8_(g8.end()), current8_(current8), - begin9_(g9.begin()), end9_(g9.end()), current9_(current9), - begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { + begin1_(g1.begin()), + end1_(g1.end()), + current1_(current1), + begin2_(g2.begin()), + end2_(g2.end()), + current2_(current2), + begin3_(g3.begin()), + end3_(g3.end()), + current3_(current3), + begin4_(g4.begin()), + end4_(g4.end()), + current4_(current4), + begin5_(g5.begin()), + end5_(g5.end()), + current5_(current5), + begin6_(g6.begin()), + end6_(g6.end()), + current6_(current6), + begin7_(g7.begin()), + end7_(g7.end()), + current7_(current7), + begin8_(g8.begin()), + end8_(g8.end()), + current8_(current8), + begin9_(g9.begin()), + end9_(g9.end()), + current9_(current9), + begin10_(g10.begin()), + end10_(g10.end()), + current10_(current10) { ComputeCurrentValue(); } virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { @@ -4687,91 +5306,72 @@ class CartesianProductGenerator10 } ComputeCurrentValue(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return ¤t_value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const Iterator* typed_other = - CheckedDowncastToActualType(&other); + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const Iterator* typed_other = CheckedDowncastToActualType(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || - ( - current1_ == typed_other->current1_ && - current2_ == typed_other->current2_ && - current3_ == typed_other->current3_ && - current4_ == typed_other->current4_ && - current5_ == typed_other->current5_ && - current6_ == typed_other->current6_ && - current7_ == typed_other->current7_ && - current8_ == typed_other->current8_ && - current9_ == typed_other->current9_ && - current10_ == typed_other->current10_); + (current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && + current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && + current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && + current7_ == typed_other->current7_ && current8_ == typed_other->current8_ && + current9_ == typed_other->current9_ && current10_ == typed_other->current10_); } private: Iterator(const Iterator& other) : base_(other.base_), - begin1_(other.begin1_), - end1_(other.end1_), - current1_(other.current1_), - begin2_(other.begin2_), - end2_(other.end2_), - current2_(other.current2_), - begin3_(other.begin3_), - end3_(other.end3_), - current3_(other.current3_), - begin4_(other.begin4_), - end4_(other.end4_), - current4_(other.current4_), - begin5_(other.begin5_), - end5_(other.end5_), - current5_(other.current5_), - begin6_(other.begin6_), - end6_(other.end6_), - current6_(other.current6_), - begin7_(other.begin7_), - end7_(other.end7_), - current7_(other.current7_), - begin8_(other.begin8_), - end8_(other.end8_), - current8_(other.current8_), - begin9_(other.begin9_), - end9_(other.end9_), - current9_(other.current9_), - begin10_(other.begin10_), - end10_(other.end10_), - current10_(other.current10_) { + begin1_(other.begin1_), + end1_(other.end1_), + current1_(other.current1_), + begin2_(other.begin2_), + end2_(other.end2_), + current2_(other.current2_), + begin3_(other.begin3_), + end3_(other.end3_), + current3_(other.current3_), + begin4_(other.begin4_), + end4_(other.end4_), + current4_(other.current4_), + begin5_(other.begin5_), + end5_(other.end5_), + current5_(other.current5_), + begin6_(other.begin6_), + end6_(other.end6_), + current6_(other.current6_), + begin7_(other.begin7_), + end7_(other.end7_), + current7_(other.current7_), + begin8_(other.begin8_), + end8_(other.end8_), + current8_(other.current8_), + begin9_(other.begin9_), + end9_(other.end9_), + current9_(other.current9_), + begin10_(other.begin10_), + end10_(other.end10_), + current10_(other.current10_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) - current_value_ = ParamType(*current1_, *current2_, *current3_, - *current4_, *current5_, *current6_, *current7_, *current8_, - *current9_, *current10_); + current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, + *current8_, *current9_, *current10_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. - return - current1_ == end1_ || - current2_ == end2_ || - current3_ == end3_ || - current4_ == end4_ || - current5_ == end5_ || - current6_ == end6_ || - current7_ == end7_ || - current8_ == end8_ || - current9_ == end9_ || - current10_ == end10_; + return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || + current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_ || + current9_ == end9_ || current10_ == end10_; } // No implementation - assignment is unsupported. @@ -4828,7 +5428,6 @@ class CartesianProductGenerator10 const ParamGenerator g10_; }; // class CartesianProductGenerator10 - // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Helper classes providing Combine() with polymorphic features. They allow @@ -4838,14 +5437,11 @@ class CartesianProductGenerator10 template class CartesianProductHolder2 { public: -CartesianProductHolder2(const Generator1& g1, const Generator2& g2) - : g1_(g1), g2_(g2) {} + CartesianProductHolder2(const Generator1& g1, const Generator2& g2) : g1_(g1), g2_(g2) {} template operator ParamGenerator< ::testing::tuple >() const { - return ParamGenerator< ::testing::tuple >( - new CartesianProductGenerator2( - static_cast >(g1_), - static_cast >(g2_))); + return ParamGenerator< ::testing::tuple >(new CartesianProductGenerator2( + static_cast >(g1_), static_cast >(g2_))); } private: @@ -4859,15 +5455,12 @@ CartesianProductHolder2(const Generator1& g1, const Generator2& g2) template class CartesianProductHolder3 { public: -CartesianProductHolder3(const Generator1& g1, const Generator2& g2, - const Generator3& g3) + CartesianProductHolder3(const Generator1& g1, const Generator2& g2, const Generator3& g3) : g1_(g1), g2_(g2), g3_(g3) {} template operator ParamGenerator< ::testing::tuple >() const { - return ParamGenerator< ::testing::tuple >( - new CartesianProductGenerator3( - static_cast >(g1_), - static_cast >(g2_), + return ParamGenerator< ::testing::tuple >(new CartesianProductGenerator3( + static_cast >(g1_), static_cast >(g2_), static_cast >(g3_))); } @@ -4880,21 +5473,16 @@ CartesianProductHolder3(const Generator1& g1, const Generator2& g2, const Generator3 g3_; }; // class CartesianProductHolder3 -template +template class CartesianProductHolder4 { public: -CartesianProductHolder4(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4) + CartesianProductHolder4(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4) : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} template operator ParamGenerator< ::testing::tuple >() const { - return ParamGenerator< ::testing::tuple >( - new CartesianProductGenerator4( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_))); + return ParamGenerator< ::testing::tuple >(new CartesianProductGenerator4( + static_cast >(g1_), static_cast >(g2_), + static_cast >(g3_), static_cast >(g4_))); } private: @@ -4907,21 +5495,17 @@ CartesianProductHolder4(const Generator1& g1, const Generator2& g2, const Generator4 g4_; }; // class CartesianProductHolder4 -template +template class CartesianProductHolder5 { public: -CartesianProductHolder5(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5) + CartesianProductHolder5(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, + const Generator5& g5) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} template operator ParamGenerator< ::testing::tuple >() const { - return ParamGenerator< ::testing::tuple >( - new CartesianProductGenerator5( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), + return ParamGenerator< ::testing::tuple >(new CartesianProductGenerator5( + static_cast >(g1_), static_cast >(g2_), + static_cast >(g3_), static_cast >(g4_), static_cast >(g5_))); } @@ -4936,25 +5520,19 @@ CartesianProductHolder5(const Generator1& g1, const Generator2& g2, const Generator5 g5_; }; // class CartesianProductHolder5 -template +template class CartesianProductHolder6 { public: -CartesianProductHolder6(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6) + CartesianProductHolder6(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, + const Generator5& g5, const Generator6& g6) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} - template + template operator ParamGenerator< ::testing::tuple >() const { return ParamGenerator< ::testing::tuple >( new CartesianProductGenerator6( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_))); + static_cast >(g1_), static_cast >(g2_), + static_cast >(g3_), static_cast >(g4_), + static_cast >(g5_), static_cast >(g6_))); } private: @@ -4969,27 +5547,21 @@ CartesianProductHolder6(const Generator1& g1, const Generator2& g2, const Generator6 g6_; }; // class CartesianProductHolder6 -template +template class CartesianProductHolder7 { public: -CartesianProductHolder7(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7) + CartesianProductHolder7(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, + const Generator5& g5, const Generator6& g6, const Generator7& g7) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} - template - operator ParamGenerator< ::testing::tuple >() const { + template + operator ParamGenerator< ::testing::tuple >() const { return ParamGenerator< ::testing::tuple >( new CartesianProductGenerator7( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_))); + static_cast >(g1_), static_cast >(g2_), + static_cast >(g3_), static_cast >(g4_), + static_cast >(g5_), static_cast >(g6_), + static_cast >(g7_))); } private: @@ -5005,30 +5577,21 @@ CartesianProductHolder7(const Generator1& g1, const Generator2& g2, const Generator7 g7_; }; // class CartesianProductHolder7 -template +template class CartesianProductHolder8 { public: -CartesianProductHolder8(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), - g8_(g8) {} - template - operator ParamGenerator< ::testing::tuple >() const { + CartesianProductHolder8(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, + const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8) {} + template + operator ParamGenerator< ::testing::tuple >() const { return ParamGenerator< ::testing::tuple >( new CartesianProductGenerator8( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_))); + static_cast >(g1_), static_cast >(g2_), + static_cast >(g3_), static_cast >(g4_), + static_cast >(g5_), static_cast >(g6_), + static_cast >(g7_), static_cast >(g8_))); } private: @@ -5045,33 +5608,24 @@ CartesianProductHolder8(const Generator1& g1, const Generator2& g2, const Generator8 g8_; }; // class CartesianProductHolder8 -template +template class CartesianProductHolder9 { public: -CartesianProductHolder9(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8, - const Generator9& g9) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9) {} - template - operator ParamGenerator< ::testing::tuple >() const { - return ParamGenerator< ::testing::tuple >( + CartesianProductHolder9(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, + const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( new CartesianProductGenerator9( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_), - static_cast >(g9_))); + static_cast >(g1_), static_cast >(g2_), + static_cast >(g3_), static_cast >(g4_), + static_cast >(g5_), static_cast >(g6_), + static_cast >(g7_), static_cast >(g8_), + static_cast >(g9_))); } private: @@ -5089,35 +5643,24 @@ CartesianProductHolder9(const Generator1& g1, const Generator2& g2, const Generator9 g9_; }; // class CartesianProductHolder9 -template +template class CartesianProductHolder10 { public: -CartesianProductHolder10(const Generator1& g1, const Generator2& g2, - const Generator3& g3, const Generator4& g4, const Generator5& g5, - const Generator6& g6, const Generator7& g7, const Generator8& g8, - const Generator9& g9, const Generator10& g10) - : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), - g9_(g9), g10_(g10) {} - template - operator ParamGenerator< ::testing::tuple >() const { - return ParamGenerator< ::testing::tuple >( - new CartesianProductGenerator10( - static_cast >(g1_), - static_cast >(g2_), - static_cast >(g3_), - static_cast >(g4_), - static_cast >(g5_), - static_cast >(g6_), - static_cast >(g7_), - static_cast >(g8_), - static_cast >(g9_), - static_cast >(g10_))); + CartesianProductHolder10(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, + const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, + const Generator9& g9, const Generator10& g10) + : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9), g10_(g10) {} + template + operator ParamGenerator< ::testing::tuple >() const { + return ParamGenerator< ::testing::tuple >( + new CartesianProductGenerator10( + static_cast >(g1_), static_cast >(g2_), + static_cast >(g3_), static_cast >(g4_), + static_cast >(g5_), static_cast >(g6_), + static_cast >(g7_), static_cast >(g8_), + static_cast >(g9_), static_cast >(g10_))); } private: @@ -5136,7 +5679,7 @@ CartesianProductHolder10(const Generator1& g1, const Generator2& g2, const Generator10 g10_; }; // class CartesianProductHolder10 -# endif // GTEST_HAS_COMBINE +# endif // GTEST_HAS_COMBINE } // namespace internal } // namespace testing diff --git a/src/net/test/gtest/include/gtest/internal/gtest-param-util.h b/src/net/test/gtest/include/gtest/internal/gtest-param-util.h index 82cab9b020..c48530ed01 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-param-util.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-param-util.h @@ -44,10 +44,10 @@ // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. +#include "gtest/gtest-printers.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-linked_ptr.h" #include "gtest/internal/gtest-port.h" -#include "gtest/gtest-printers.h" #if GTEST_HAS_PARAM_TEST @@ -57,9 +57,7 @@ namespace testing { // Consists of the parameter value and the integer parameter index. template struct TestParamInfo { - TestParamInfo(const ParamType& a_param, size_t an_index) : - param(a_param), - index(an_index) {} + TestParamInfo(const ParamType& a_param, size_t an_index) : param(a_param), index(an_index) {} ParamType param; size_t index; }; @@ -81,11 +79,12 @@ namespace internal { // fixture class for the same test case. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. -GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, - CodeLocation code_location); +GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, CodeLocation code_location); -template class ParamGeneratorInterface; -template class ParamGenerator; +template +class ParamGeneratorInterface; +template +class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface. @@ -129,8 +128,7 @@ class ParamIterator { // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { - if (this != &other) - impl_.reset(other.impl_->Clone()); + if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } @@ -150,9 +148,7 @@ class ParamIterator { bool operator==(const ParamIterator& other) const { return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); } - bool operator!=(const ParamIterator& other) const { - return !(*this == other); - } + bool operator!=(const ParamIterator& other) const { return !(*this == other); } private: friend class ParamGenerator; @@ -179,7 +175,7 @@ class ParamGeneratorInterface { // This class implements copy initialization semantics and the contained // ParamGeneratorInterface instance is shared among all copies // of the original object. This is possible because that instance is immutable. -template +template class ParamGenerator { public: typedef ParamIterator iterator; @@ -207,51 +203,41 @@ template class RangeGenerator : public ParamGeneratorInterface { public: RangeGenerator(T begin, T end, IncrementT step) - : begin_(begin), end_(end), - step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} + : begin_(begin), end_(end), step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} virtual ~RangeGenerator() {} - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, begin_, 0, step_); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, end_, end_index_, step_); - } + virtual ParamIteratorInterface* Begin() const { return new Iterator(this, begin_, 0, step_); } + virtual ParamIteratorInterface* End() const { return new Iterator(this, end_, end_index_, step_); } private: class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, T value, int index, - IncrementT step) + Iterator(const ParamGeneratorInterface* base, T value, int index, IncrementT step) : base_(base), value_(value), index_(index), step_(step) {} virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } virtual void Advance() { value_ = static_cast(value_ + step_); index_++; } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } virtual const T* Current() const { return &value_; } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const int other_index = - CheckedDowncastToActualType(&other)->index_; + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + const int other_index = CheckedDowncastToActualType(&other)->index_; return index_ == other_index; } private: Iterator(const Iterator& other) : ParamIteratorInterface(), - base_(other.base_), value_(other.value_), index_(other.index_), + base_(other.base_), + value_(other.value_), + index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. @@ -263,12 +249,9 @@ class RangeGenerator : public ParamGeneratorInterface { const IncrementT step_; }; // class RangeGenerator::Iterator - static int CalculateEndIndex(const T& begin, - const T& end, - const IncrementT& step) { + static int CalculateEndIndex(const T& begin, const T& end, const IncrementT& step) { int end_index = 0; - for (T i = begin; i < end; i = static_cast(i + step)) - end_index++; + for (T i = begin; i < end; i = static_cast(i + step)) end_index++; return end_index; } @@ -283,7 +266,6 @@ class RangeGenerator : public ParamGeneratorInterface { const int end_index_; }; // class RangeGenerator - // Generates values from a pair of STL-style iterators. Used in the // ValuesIn() function. The elements are copied from the source range // since the source can be located on the stack, and the generator @@ -292,37 +274,27 @@ template class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { public: template - ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) - : container_(begin, end) {} + ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} virtual ~ValuesInIteratorRangeGenerator() {} - virtual ParamIteratorInterface* Begin() const { - return new Iterator(this, container_.begin()); - } - virtual ParamIteratorInterface* End() const { - return new Iterator(this, container_.end()); - } + virtual ParamIteratorInterface* Begin() const { return new Iterator(this, container_.begin()); } + virtual ParamIteratorInterface* End() const { return new Iterator(this, container_.end()); } private: typedef typename ::std::vector ContainerType; class Iterator : public ParamIteratorInterface { public: - Iterator(const ParamGeneratorInterface* base, - typename ContainerType::const_iterator iterator) + Iterator(const ParamGeneratorInterface* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} virtual ~Iterator() {} - virtual const ParamGeneratorInterface* BaseGenerator() const { - return base_; - } + virtual const ParamGeneratorInterface* BaseGenerator() const { return base_; } virtual void Advance() { ++iterator_; value_.reset(); } - virtual ParamIteratorInterface* Clone() const { - return new Iterator(*this); - } + virtual ParamIteratorInterface* Clone() const { return new Iterator(*this); } // We need to use cached value referenced by iterator_ because *iterator_ // can return a temporary object (and of type other then T), so just // having "return &*iterator_;" doesn't work. @@ -331,27 +303,22 @@ class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { // detect that fact. The client code, on the other hand, is // responsible for not calling Current() on an out-of-range iterator. virtual const T* Current() const { - if (value_.get() == NULL) - value_.reset(new T(*iterator_)); + if (value_.get() == NULL) value_.reset(new T(*iterator_)); return value_.get(); } virtual bool Equals(const ParamIteratorInterface& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - return iterator_ == - CheckedDowncastToActualType(&other)->iterator_; + GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " + << "from different generators." << std::endl; + return iterator_ == CheckedDowncastToActualType(&other)->iterator_; } private: Iterator(const Iterator& other) - // The explicit constructor call suppresses a false warning - // emitted by gcc when supplied with the -Wextra option. - : ParamIteratorInterface(), - base_(other.base_), - iterator_(other.iterator_) {} + // The explicit constructor call suppresses a false warning + // emitted by gcc when supplied with the -Wextra option. + : ParamIteratorInterface(), base_(other.base_), iterator_(other.iterator_) {} const ParamGeneratorInterface* const base_; typename ContainerType::const_iterator iterator_; @@ -396,7 +363,7 @@ struct ParamNameGenFunc { }; template -typename ParamNameGenFunc::Type *GetParamNameGen() { +typename ParamNameGenFunc::Type* GetParamNameGen() { return DefaultParamName; } @@ -408,8 +375,7 @@ template class ParameterizedTestFactory : public TestFactoryBase { public: typedef typename TestClass::ParamType ParamType; - explicit ParameterizedTestFactory(ParamType parameter) : - parameter_(parameter) {} + explicit ParameterizedTestFactory(ParamType parameter) : parameter_(parameter) {} virtual Test* CreateTest() { TestClass::SetParam(¶meter_); return new TestClass(); @@ -442,8 +408,7 @@ class TestMetaFactoryBase { // it for each Test/Parameter value combination. Thus it needs meta factory // creator class. template -class TestMetaFactory - : public TestMetaFactoryBase { +class TestMetaFactory : public TestMetaFactoryBase { public: typedef typename TestCase::ParamType ParamType; @@ -506,8 +471,7 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { typedef ParamGenerator(GeneratorCreationFunc)(); typedef typename ParamNameGenFunc::Type ParamNameGeneratorFunc; - explicit ParameterizedTestCaseInfo( - const char* name, CodeLocation code_location) + explicit ParameterizedTestCaseInfo(const char* name, CodeLocation code_location) : test_case_name_(name), code_location_(code_location) {} // Test case base name for display purposes. @@ -520,22 +484,15 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test case base name and DoBar is test base name. - void AddTestPattern(const char* test_case_name, - const char* test_base_name, + void AddTestPattern(const char* test_case_name, const char* test_base_name, TestMetaFactoryBase* meta_factory) { - tests_.push_back(linked_ptr(new TestInfo(test_case_name, - test_base_name, - meta_factory))); + tests_.push_back(linked_ptr(new TestInfo(test_case_name, test_base_name, meta_factory))); } // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information // about a generator. - int AddTestCaseInstantiation(const string& instantiation_name, - GeneratorCreationFunc* func, - ParamNameGeneratorFunc* name_func, - const char* file, - int line) { - instantiations_.push_back( - InstantiationInfo(instantiation_name, func, name_func, file, line)); + int AddTestCaseInstantiation(const string& instantiation_name, GeneratorCreationFunc* func, + ParamNameGeneratorFunc* name_func, const char* file, int line) { + instantiations_.push_back(InstantiationInfo(instantiation_name, func, name_func, file, line)); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test case @@ -544,12 +501,10 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { // instance of a ParameterizedTestCaseInfoBase derived class. // UnitTest has a guard to prevent from calling this method more then once. virtual void RegisterTests() { - for (typename TestInfoContainer::iterator test_it = tests_.begin(); - test_it != tests_.end(); ++test_it) { + for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { linked_ptr test_info = *test_it; - for (typename InstantiationContainer::iterator gen_it = - instantiations_.begin(); gen_it != instantiations_.end(); - ++gen_it) { + for (typename InstantiationContainer::iterator gen_it = instantiations_.begin(); gen_it != instantiations_.end(); + ++gen_it) { const string& instantiation_name = gen_it->name; ParamGenerator generator((*gen_it->generator)()); ParamNameGeneratorFunc* name_func = gen_it->name_func; @@ -557,57 +512,45 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { int line = gen_it->line; string test_case_name; - if ( !instantiation_name.empty() ) - test_case_name = instantiation_name + "/"; + if (!instantiation_name.empty()) test_case_name = instantiation_name + "/"; test_case_name += test_info->test_case_base_name; size_t i = 0; std::set test_param_names; - for (typename ParamGenerator::iterator param_it = - generator.begin(); - param_it != generator.end(); ++param_it, ++i) { + for (typename ParamGenerator::iterator param_it = generator.begin(); param_it != generator.end(); + ++param_it, ++i) { Message test_name_stream; - std::string param_name = name_func( - TestParamInfo(*param_it, i)); + std::string param_name = name_func(TestParamInfo(*param_it, i)); - GTEST_CHECK_(IsValidParamName(param_name)) - << "Parameterized test name '" << param_name - << "' is invalid, in " << file - << " line " << line << std::endl; + GTEST_CHECK_(IsValidParamName(param_name)) << "Parameterized test name '" << param_name << "' is invalid, in " + << file << " line " << line << std::endl; - GTEST_CHECK_(test_param_names.count(param_name) == 0) - << "Duplicate parameterized test name '" << param_name - << "', in " << file << " line " << line << std::endl; + GTEST_CHECK_(test_param_names.count(param_name) == 0) << "Duplicate parameterized test name '" << param_name + << "', in " << file << " line " << line << std::endl; test_param_names.insert(param_name); test_name_stream << test_info->test_base_name << "/" << param_name; - MakeAndRegisterTestInfo( - test_case_name.c_str(), - test_name_stream.GetString().c_str(), - NULL, // No type parameter. - PrintToString(*param_it).c_str(), - code_location_, - GetTestCaseTypeId(), - TestCase::SetUpTestCase, - TestCase::TearDownTestCase, - test_info->test_meta_factory->CreateTestFactory(*param_it)); + MakeAndRegisterTestInfo(test_case_name.c_str(), test_name_stream.GetString().c_str(), + NULL, // No type parameter. + PrintToString(*param_it).c_str(), code_location_, GetTestCaseTypeId(), + TestCase::SetUpTestCase, TestCase::TearDownTestCase, + test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it - } // for gen_it - } // for test_it - } // RegisterTests + } // for gen_it + } // for test_it + } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { - TestInfo(const char* a_test_case_base_name, - const char* a_test_base_name, - TestMetaFactoryBase* a_test_meta_factory) : - test_case_base_name(a_test_case_base_name), - test_base_name(a_test_base_name), - test_meta_factory(a_test_meta_factory) {} + TestInfo(const char* a_test_case_base_name, const char* a_test_base_name, + TestMetaFactoryBase* a_test_meta_factory) + : test_case_base_name(a_test_case_base_name), + test_base_name(a_test_base_name), + test_meta_factory(a_test_meta_factory) {} const string test_case_base_name; const string test_base_name; @@ -618,34 +561,25 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { // struct InstantiationInfo { - InstantiationInfo(const std::string &name_in, - GeneratorCreationFunc* generator_in, - ParamNameGeneratorFunc* name_func_in, - const char* file_in, - int line_in) - : name(name_in), - generator(generator_in), - name_func(name_func_in), - file(file_in), - line(line_in) {} - - std::string name; - GeneratorCreationFunc* generator; - ParamNameGeneratorFunc* name_func; - const char* file; - int line; + InstantiationInfo(const std::string& name_in, GeneratorCreationFunc* generator_in, + ParamNameGeneratorFunc* name_func_in, const char* file_in, int line_in) + : name(name_in), generator(generator_in), name_func(name_func_in), file(file_in), line(line_in) {} + + std::string name; + GeneratorCreationFunc* generator; + ParamNameGeneratorFunc* name_func; + const char* file; + int line; }; typedef ::std::vector InstantiationContainer; static bool IsValidParamName(const std::string& name) { // Check for empty string - if (name.empty()) - return false; + if (name.empty()) return false; // Check for invalid characters for (std::string::size_type index = 0; index < name.size(); ++index) { - if (!isalnum(name[index]) && name[index] != '_') - return false; + if (!isalnum(name[index]) && name[index] != '_') return false; } return true; @@ -669,8 +603,7 @@ class ParameterizedTestCaseRegistry { public: ParameterizedTestCaseRegistry() {} ~ParameterizedTestCaseRegistry() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { delete *it; } } @@ -678,12 +611,10 @@ class ParameterizedTestCaseRegistry { // Looks up or creates and returns a structure containing information about // tests and instantiations of a particular test case. template - ParameterizedTestCaseInfo* GetTestCasePatternHolder( - const char* test_case_name, - CodeLocation code_location) { + ParameterizedTestCaseInfo* GetTestCasePatternHolder(const char* test_case_name, + CodeLocation code_location) { ParameterizedTestCaseInfo* typed_test_info = NULL; - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { if ((*it)->GetTestCaseName() == test_case_name) { if ((*it)->GetTestCaseTypeId() != GetTypeId()) { // Complain about incorrect usage of Google Test facilities @@ -695,22 +626,19 @@ class ParameterizedTestCaseRegistry { // At this point we are sure that the object we found is of the same // type we are looking for, so we downcast it to that type // without further checks. - typed_test_info = CheckedDowncastToActualType< - ParameterizedTestCaseInfo >(*it); + typed_test_info = CheckedDowncastToActualType >(*it); } break; } } if (typed_test_info == NULL) { - typed_test_info = new ParameterizedTestCaseInfo( - test_case_name, code_location); + typed_test_info = new ParameterizedTestCaseInfo(test_case_name, code_location); test_case_infos_.push_back(typed_test_info); } return typed_test_info; } void RegisterTests() { - for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); - it != test_case_infos_.end(); ++it) { + for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { (*it)->RegisterTests(); } } diff --git a/src/net/test/gtest/include/gtest/internal/gtest-port-arch.h b/src/net/test/gtest/include/gtest/internal/gtest-port-arch.h index 74ab949057..fc56230ca0 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-port-arch.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-port-arch.h @@ -37,57 +37,57 @@ // Determines the platform on which Google Test is compiled. #ifdef __CYGWIN__ -# define GTEST_OS_CYGWIN 1 +# define GTEST_OS_CYGWIN 1 #elif defined __SYMBIAN32__ -# define GTEST_OS_SYMBIAN 1 +# define GTEST_OS_SYMBIAN 1 #elif defined _WIN32 -# define GTEST_OS_WINDOWS 1 -# ifdef _WIN32_WCE -# define GTEST_OS_WINDOWS_MOBILE 1 -# elif defined(__MINGW__) || defined(__MINGW32__) -# define GTEST_OS_WINDOWS_MINGW 1 -# elif defined(WINAPI_FAMILY) -# include -# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) -# define GTEST_OS_WINDOWS_DESKTOP 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) -# define GTEST_OS_WINDOWS_PHONE 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) -# define GTEST_OS_WINDOWS_RT 1 +# define GTEST_OS_WINDOWS 1 +# ifdef _WIN32_WCE +# define GTEST_OS_WINDOWS_MOBILE 1 +# elif defined(__MINGW__) || defined(__MINGW32__) +# define GTEST_OS_WINDOWS_MINGW 1 +# elif defined(WINAPI_FAMILY) +# include +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# define GTEST_OS_WINDOWS_DESKTOP 1 +# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) +# define GTEST_OS_WINDOWS_PHONE 1 +# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) +# define GTEST_OS_WINDOWS_RT 1 +# else +// WINAPI_FAMILY defined but no known partition matched. +// Default to desktop. +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif # else - // WINAPI_FAMILY defined but no known partition matched. - // Default to desktop. -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif -# else -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif // _WIN32_WCE +# define GTEST_OS_WINDOWS_DESKTOP 1 +# endif // _WIN32_WCE #elif defined __APPLE__ -# define GTEST_OS_MAC 1 -# if TARGET_OS_IPHONE -# define GTEST_OS_IOS 1 -# endif +# define GTEST_OS_MAC 1 +# if TARGET_OS_IPHONE +# define GTEST_OS_IOS 1 +# endif #elif defined __FreeBSD__ -# define GTEST_OS_FREEBSD 1 +# define GTEST_OS_FREEBSD 1 #elif defined __linux__ -# define GTEST_OS_LINUX 1 -# if defined __ANDROID__ -# define GTEST_OS_LINUX_ANDROID 1 -# endif +# define GTEST_OS_LINUX 1 +# if defined __ANDROID__ +# define GTEST_OS_LINUX_ANDROID 1 +# endif #elif defined __MVS__ -# define GTEST_OS_ZOS 1 +# define GTEST_OS_ZOS 1 #elif defined(__sun) && defined(__SVR4) -# define GTEST_OS_SOLARIS 1 +# define GTEST_OS_SOLARIS 1 #elif defined(_AIX) -# define GTEST_OS_AIX 1 +# define GTEST_OS_AIX 1 #elif defined(__hpux) -# define GTEST_OS_HPUX 1 +# define GTEST_OS_HPUX 1 #elif defined __native_client__ -# define GTEST_OS_NACL 1 +# define GTEST_OS_NACL 1 #elif defined __OpenBSD__ -# define GTEST_OS_OPENBSD 1 +# define GTEST_OS_OPENBSD 1 #elif defined __QNX__ -# define GTEST_OS_QNX 1 +# define GTEST_OS_QNX 1 #endif // __CYGWIN__ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ diff --git a/src/net/test/gtest/include/gtest/internal/gtest-port.h b/src/net/test/gtest/include/gtest/internal/gtest-port.h index 0094ed5077..a8bc0e203a 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-port.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-port.h @@ -258,47 +258,46 @@ #include // for isspace, etc #include // for ptrdiff_t -#include #include +#include #include #ifndef _WIN32_WCE -# include -# include +# include +# include #endif // !_WIN32_WCE #if defined __APPLE__ -# include -# include +# include +# include #endif #include // NOLINT -#include // NOLINT -#include // NOLINT -#include // NOLINT +#include // NOLINT +#include // NOLINT +#include // NOLINT #include #include // NOLINT -#include "gtest/internal/gtest-port-arch.h" #include "gtest/internal/custom/gtest-port.h" +#include "gtest/internal/gtest-port-arch.h" #if !defined(GTEST_DEV_EMAIL_) -# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" -# define GTEST_FLAG_PREFIX_ "gtest_" -# define GTEST_FLAG_PREFIX_DASH_ "gtest-" -# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" -# define GTEST_NAME_ "Google Test" -# define GTEST_PROJECT_URL_ "/~https://github.com/google/googletest/" +# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" +# define GTEST_FLAG_PREFIX_ "gtest_" +# define GTEST_FLAG_PREFIX_DASH_ "gtest-" +# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" +# define GTEST_NAME_ "Google Test" +# define GTEST_PROJECT_URL_ "/~https://github.com/google/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) -# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" +# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. -# define GTEST_GCC_VER_ \ - (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) +# define GTEST_GCC_VER_ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. @@ -307,15 +306,12 @@ // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() #if _MSC_VER >= 1500 -# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ - __pragma(warning(push)) \ - __pragma(warning(disable: warnings)) -# define GTEST_DISABLE_MSC_WARNINGS_POP_() \ - __pragma(warning(pop)) +# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) __pragma(warning(push)) __pragma(warning(disable : warnings)) +# define GTEST_DISABLE_MSC_WARNINGS_POP_() __pragma(warning(pop)) #else // Older versions of MSVC don't have __pragma. -# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) -# define GTEST_DISABLE_MSC_WARNINGS_POP_() +# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) +# define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif #ifndef GTEST_LANG_CXX11 @@ -323,12 +319,12 @@ // -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a // value for __cplusplus, and recent versions of clang, gcc, and // probably other compilers set that too in C++11 mode. -# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L +# if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L // Compiling in at least C++11 mode. -# define GTEST_LANG_CXX11 1 -# else -# define GTEST_LANG_CXX11 0 -# endif +# define GTEST_LANG_CXX11 1 +# else +# define GTEST_LANG_CXX11 0 +# endif #endif // Distinct from C++11 language support, some environments don't provide @@ -340,61 +336,60 @@ // 20110325, but maintenance releases in the 4.4 and 4.5 series followed // this date, so check for those versions by their date stamps. // https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning -#if GTEST_LANG_CXX11 && \ - (!defined(__GLIBCXX__) || ( \ - __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ - /* Blacklist of patch releases of older branches: */ \ - __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ - __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ - __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ - __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ -# define GTEST_STDLIB_CXX11 1 +#if GTEST_LANG_CXX11 && \ + (!defined(__GLIBCXX__) || \ + (__GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ /* Blacklist of patch releases of older branches: */ \ + __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ + __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ + __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ + __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ +# define GTEST_STDLIB_CXX11 1 #endif // Only use C++11 library features if the library provides them. #if GTEST_STDLIB_CXX11 -# define GTEST_HAS_STD_BEGIN_AND_END_ 1 -# define GTEST_HAS_STD_FORWARD_LIST_ 1 -# define GTEST_HAS_STD_FUNCTION_ 1 -# define GTEST_HAS_STD_INITIALIZER_LIST_ 1 -# define GTEST_HAS_STD_MOVE_ 1 -# define GTEST_HAS_STD_SHARED_PTR_ 1 -# define GTEST_HAS_STD_TYPE_TRAITS_ 1 -# define GTEST_HAS_STD_UNIQUE_PTR_ 1 +# define GTEST_HAS_STD_BEGIN_AND_END_ 1 +# define GTEST_HAS_STD_FORWARD_LIST_ 1 +# define GTEST_HAS_STD_FUNCTION_ 1 +# define GTEST_HAS_STD_INITIALIZER_LIST_ 1 +# define GTEST_HAS_STD_MOVE_ 1 +# define GTEST_HAS_STD_SHARED_PTR_ 1 +# define GTEST_HAS_STD_TYPE_TRAITS_ 1 +# define GTEST_HAS_STD_UNIQUE_PTR_ 1 #endif // C++11 specifies that provides std::tuple. // Some platforms still might not have it, however. #if GTEST_LANG_CXX11 -# define GTEST_HAS_STD_TUPLE_ 1 -# if defined(__clang__) +# define GTEST_HAS_STD_TUPLE_ 1 +# if defined(__clang__) // Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include -# if defined(__has_include) && !__has_include() -# undef GTEST_HAS_STD_TUPLE_ -# endif -# elif defined(_MSC_VER) +# if defined(__has_include) && !__has_include() +# undef GTEST_HAS_STD_TUPLE_ +# endif +# elif defined(_MSC_VER) // Inspired by boost/config/stdlib/dinkumware.hpp -# if defined(_CPPLIB_VER) && _CPPLIB_VER < 520 -# undef GTEST_HAS_STD_TUPLE_ -# endif -# elif defined(__GLIBCXX__) +# if defined(_CPPLIB_VER) && _CPPLIB_VER < 520 +# undef GTEST_HAS_STD_TUPLE_ +# endif +# elif defined(__GLIBCXX__) // Inspired by boost/config/stdlib/libstdcpp3.hpp, // http://gcc.gnu.org/gcc-4.2/changes.html and // http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x -# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) -# undef GTEST_HAS_STD_TUPLE_ +# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) +# undef GTEST_HAS_STD_TUPLE_ +# endif # endif -# endif #endif // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. #if GTEST_OS_WINDOWS -# if !GTEST_OS_WINDOWS_MOBILE -# include -# include -# endif +# if !GTEST_OS_WINDOWS_MOBILE +# include +# include +# endif // In order to avoid having to include , use forward declaration // assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. // This assumption is verified by @@ -404,8 +399,8 @@ struct _RTL_CRITICAL_SECTION; // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. -# include -# include +# include +# include #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID @@ -415,12 +410,12 @@ struct _RTL_CRITICAL_SECTION; // Defines this to true iff Google Test can use POSIX regular expressions. #ifndef GTEST_HAS_POSIX_RE -# if GTEST_OS_LINUX_ANDROID +# if GTEST_OS_LINUX_ANDROID // On Android, is only available starting with Gingerbread. -# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) -# else -# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) -# endif +# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) +# else +# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) +# endif #endif #if GTEST_USES_PCRE @@ -432,36 +427,36 @@ struct _RTL_CRITICAL_SECTION; // won't compile otherwise. We can #include it here as we already // included , which is guaranteed to define size_t through // . -# include // NOLINT +# include // NOLINT -# define GTEST_USES_POSIX_RE 1 +# define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS // is not available on Windows. Use our own simple regex // implementation instead. -# define GTEST_USES_SIMPLE_RE 1 +# define GTEST_USES_SIMPLE_RE 1 #else // may not be available on this platform. Use our own // simple regex implementation instead. -# define GTEST_USES_SIMPLE_RE 1 +# define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_USES_PCRE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. -# if defined(_MSC_VER) || defined(__BORLANDC__) +# if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. -# ifndef _HAS_EXCEPTIONS -# define _HAS_EXCEPTIONS 1 -# endif // _HAS_EXCEPTIONS -# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS -# elif defined(__clang__) +# ifndef _HAS_EXCEPTIONS +# define _HAS_EXCEPTIONS 1 +# endif // _HAS_EXCEPTIONS +# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS +# elif defined(__clang__) // clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, // but iff cleanups are enabled after that. In Obj-C++ files, there can be // cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions @@ -469,43 +464,43 @@ struct _RTL_CRITICAL_SECTION; // exceptions starting at clang r206352, but which checked for cleanups prior to // that. To reliably check for C++ exception availability with clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). -# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) -# elif defined(__GNUC__) && __EXCEPTIONS +# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) +# elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__SUNPRO_CC) +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__IBMCPP__) && __EXCEPTIONS +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__HP_aCC) +# define GTEST_HAS_EXCEPTIONS 1 +# elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. -# define GTEST_HAS_EXCEPTIONS 1 -# else +# define GTEST_HAS_EXCEPTIONS 1 +# else // For other compilers, we assume exceptions are disabled to be // conservative. -# define GTEST_HAS_EXCEPTIONS 0 -# endif // defined(_MSC_VER) || defined(__BORLANDC__) -#endif // GTEST_HAS_EXCEPTIONS +# define GTEST_HAS_EXCEPTIONS 0 +# endif // defined(_MSC_VER) || defined(__BORLANDC__) +#endif // GTEST_HAS_EXCEPTIONS #if !defined(GTEST_HAS_STD_STRING) // Even though we don't use this macro any longer, we keep it in case // some clients still depend on it. -# define GTEST_HAS_STD_STRING 1 +# define GTEST_HAS_STD_STRING 1 #elif !GTEST_HAS_STD_STRING // The user told us that ::std::string isn't available. -# error "Google Test cannot be used where ::std::string isn't available." +# error "Google Test cannot be used where ::std::string isn't available." #endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING // The user didn't tell us whether ::string is available, so we need // to figure it out. -# define GTEST_HAS_GLOBAL_STRING 0 +# define GTEST_HAS_GLOBAL_STRING 0 #endif // GTEST_HAS_GLOBAL_STRING @@ -518,16 +513,14 @@ struct _RTL_CRITICAL_SECTION; // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). -# define GTEST_HAS_STD_WSTRING \ - (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) +# define GTEST_HAS_STD_WSTRING (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) #endif // GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_GLOBAL_WSTRING // The user didn't tell us whether ::wstring is available, so we need // to figure it out. -# define GTEST_HAS_GLOBAL_WSTRING \ - (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) +# define GTEST_HAS_GLOBAL_WSTRING (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) #endif // GTEST_HAS_GLOBAL_WSTRING // Determines whether RTTI is available. @@ -535,62 +528,61 @@ struct _RTL_CRITICAL_SECTION; // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. -# ifdef _MSC_VER +# ifdef _MSC_VER -# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif +# ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. -# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) -# ifdef __GXX_RTTI +# ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. -# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ - !defined(__EXCEPTIONS) -# define GTEST_HAS_RTTI 0 -# else -# define GTEST_HAS_RTTI 1 -# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS -# else -# define GTEST_HAS_RTTI 0 -# endif // __GXX_RTTI +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS) +# define GTEST_HAS_RTTI 0 +# else +# define GTEST_HAS_RTTI 1 +# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS +# else +# define GTEST_HAS_RTTI 0 +# endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. -# elif defined(__clang__) +# elif defined(__clang__) -# define GTEST_HAS_RTTI __has_feature(cxx_rtti) +# define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. -# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) +# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) -# ifdef __RTTI_ALL__ -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif +# ifdef __RTTI_ALL__ +# define GTEST_HAS_RTTI 1 +# else +# define GTEST_HAS_RTTI 0 +# endif -# else +# else // For all other compilers, we assume RTTI is enabled. -# define GTEST_HAS_RTTI 1 +# define GTEST_HAS_RTTI 1 -# endif // _MSC_VER +# endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include when RTTI // is enabled. #if GTEST_HAS_RTTI -# include +# include #endif // Determines whether Google Test can use the pthreads library. @@ -600,39 +592,39 @@ struct _RTL_CRITICAL_SECTION; // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. -# define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ - || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL) +# define GTEST_HAS_PTHREAD \ + (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is // true. -# include // NOLINT +# include // NOLINT // For timespec and nanosleep, used below. -# include // NOLINT +# include // NOLINT #endif // Determines if hash_map/hash_set are available. // Only used for testing against those containers. #if !defined(GTEST_HAS_HASH_MAP_) -# if _MSC_VER -# define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. -# define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. -# endif // _MSC_VER -#endif // !defined(GTEST_HAS_HASH_MAP_) +# if _MSC_VER +# define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. +# define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. +# endif // _MSC_VER +#endif // !defined(GTEST_HAS_HASH_MAP_) // Determines whether Google Test can use tr1/tuple. You can define // this macro to 0 to prevent Google Test from using tuple (any // feature depending on tuple with be disabled in this mode). #ifndef GTEST_HAS_TR1_TUPLE -# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) +# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) // STLport, provided with the Android NDK, has neither or . -# define GTEST_HAS_TR1_TUPLE 0 -# else +# define GTEST_HAS_TR1_TUPLE 0 +# else // The user didn't tell us not to do it, so we assume it's OK. -# define GTEST_HAS_TR1_TUPLE 1 -# endif +# define GTEST_HAS_TR1_TUPLE 1 +# endif #endif // GTEST_HAS_TR1_TUPLE // Determines whether Google Test's own tr1 tuple implementation @@ -650,23 +642,24 @@ struct _RTL_CRITICAL_SECTION; // user has. QNX's QCC compiler is a modified GCC but it doesn't // support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, // and it can be used with some compilers that define __GNUC__. -# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ - && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 -# define GTEST_ENV_HAS_TR1_TUPLE_ 1 -# endif +# if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) && !GTEST_OS_QNX && \ + !defined(_LIBCPP_VERSION)) || \ + _MSC_VER >= 1600 +# define GTEST_ENV_HAS_TR1_TUPLE_ 1 +# endif // C++11 specifies that provides std::tuple. Use that if gtest is used // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 // can build with clang but need to use gcc4.2's libstdc++). -# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) -# define GTEST_ENV_HAS_STD_TUPLE_ 1 -# endif +# if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) +# define GTEST_ENV_HAS_STD_TUPLE_ 1 +# endif -# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ -# define GTEST_USE_OWN_TR1_TUPLE 0 -# else -# define GTEST_USE_OWN_TR1_TUPLE 1 -# endif +# if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ +# define GTEST_USE_OWN_TR1_TUPLE 0 +# else +# define GTEST_USE_OWN_TR1_TUPLE 1 +# endif #endif // GTEST_USE_OWN_TR1_TUPLE @@ -674,21 +667,21 @@ struct _RTL_CRITICAL_SECTION; // gtest-port.h's responsibility to #include the header implementing // tuple. #if GTEST_HAS_STD_TUPLE_ -# include // IWYU pragma: export -# define GTEST_TUPLE_NAMESPACE_ ::std +# include // IWYU pragma: export +# define GTEST_TUPLE_NAMESPACE_ ::std #endif // GTEST_HAS_STD_TUPLE_ // We include tr1::tuple even if std::tuple is available to define printers for // them. #if GTEST_HAS_TR1_TUPLE -# ifndef GTEST_TUPLE_NAMESPACE_ -# define GTEST_TUPLE_NAMESPACE_ ::std::tr1 -# endif // GTEST_TUPLE_NAMESPACE_ - -# if GTEST_USE_OWN_TR1_TUPLE -# include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT -# elif GTEST_ENV_HAS_STD_TUPLE_ -# include +# ifndef GTEST_TUPLE_NAMESPACE_ +# define GTEST_TUPLE_NAMESPACE_ ::std::tr1 +# endif // GTEST_TUPLE_NAMESPACE_ + +# if GTEST_USE_OWN_TR1_TUPLE +# include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT +# elif GTEST_ENV_HAS_STD_TUPLE_ +# include // C++11 puts its tuple into the ::std namespace rather than // ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. // This causes undefined behavior, but supported compilers react in @@ -700,48 +693,48 @@ using ::std::make_tuple; using ::std::tuple; using ::std::tuple_element; using ::std::tuple_size; -} -} +} // namespace tr1 +} // namespace std -# elif GTEST_OS_SYMBIAN +# elif GTEST_OS_SYMBIAN // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to // use STLport's tuple implementation, which unfortunately doesn't // work as the copy of STLport distributed with Symbian is incomplete. // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to // use its own tuple implementation. -# ifdef BOOST_HAS_TR1_TUPLE -# undef BOOST_HAS_TR1_TUPLE -# endif // BOOST_HAS_TR1_TUPLE +# ifdef BOOST_HAS_TR1_TUPLE +# undef BOOST_HAS_TR1_TUPLE +# endif // BOOST_HAS_TR1_TUPLE // This prevents , which defines // BOOST_HAS_TR1_TUPLE, from being #included by Boost's . -# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED -# include // IWYU pragma: export // NOLINT +# define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED +# include // IWYU pragma: export // NOLINT -# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) +# elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) // GCC 4.0+ implements tr1/tuple in the header. This does // not conform to the TR1 spec, which requires the header to be . -# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 +# if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 // Until version 4.3.2, gcc has a bug that causes , // which is #included by , to not compile when RTTI is // disabled. _TR1_FUNCTIONAL is the header guard for // . Hence the following #define is a hack to prevent // from being included. -# define _TR1_FUNCTIONAL 1 -# include -# undef _TR1_FUNCTIONAL // Allows the user to #include - // if he chooses to. -# else -# include // NOLINT -# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 +# define _TR1_FUNCTIONAL 1 +# include +# undef _TR1_FUNCTIONAL // Allows the user to #include +// if he chooses to. +# else +# include // NOLINT +# endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 -# else +# else // If the compiler is not GCC 4.0+, we assume the user is using a // spec-conforming TR1 implementation. -# include // IWYU pragma: export // NOLINT -# endif // GTEST_USE_OWN_TR1_TUPLE +# include // IWYU pragma: export // NOLINT +# endif // GTEST_USE_OWN_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE @@ -752,20 +745,20 @@ using ::std::tuple_size; #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. -# if GTEST_OS_LINUX && !defined(__ia64__) -# if GTEST_OS_LINUX_ANDROID +# if GTEST_OS_LINUX && !defined(__ia64__) +# if GTEST_OS_LINUX_ANDROID // On Android, clone() is only available on ARM starting with Gingerbread. -# if defined(__arm__) && __ANDROID_API__ >= 9 -# define GTEST_HAS_CLONE 1 +# if defined(__arm__) && __ANDROID_API__ >= 9 +# define GTEST_HAS_CLONE 1 +# else +# define GTEST_HAS_CLONE 0 +# endif # else -# define GTEST_HAS_CLONE 0 +# define GTEST_HAS_CLONE 1 # endif # else -# define GTEST_HAS_CLONE 1 -# endif -# else -# define GTEST_HAS_CLONE 0 -# endif // GTEST_OS_LINUX && !defined(__ia64__) +# define GTEST_HAS_CLONE 0 +# endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE @@ -774,24 +767,21 @@ using ::std::tuple_size; #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ - GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT -# define GTEST_HAS_STREAM_REDIRECTION 0 -# else -# define GTEST_HAS_STREAM_REDIRECTION 1 -# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN -#endif // GTEST_HAS_STREAM_REDIRECTION +# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT +# define GTEST_HAS_STREAM_REDIRECTION 0 +# else +# define GTEST_HAS_STREAM_REDIRECTION 1 +# endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN +#endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // Google Test does not support death tests for VC 7.1 and earlier as // abort() in a VC 7.1 application compiled as GUI in debug config // pops up a dialog window that cannot be suppressed programmatically. -#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - (GTEST_OS_MAC && !GTEST_OS_IOS) || \ - (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ - GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ +#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || (GTEST_OS_MAC && !GTEST_OS_IOS) || \ + (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD) -# define GTEST_HAS_DEATH_TEST 1 +# define GTEST_HAS_DEATH_TEST 1 #endif // We don't support MSVC 7.1 with exceptions disabled now. Therefore @@ -803,10 +793,9 @@ using ::std::tuple_size; // Typed tests need and variadic macros, which GCC, VC++ 8.0, // Sun Pro CC, IBM Visual Age, and HP aCC support. -#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ - defined(__IBMCPP__) || defined(__HP_aCC) -# define GTEST_HAS_TYPED_TEST 1 -# define GTEST_HAS_TYPED_TEST_P 1 +#if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || defined(__IBMCPP__) || defined(__HP_aCC) +# define GTEST_HAS_TYPED_TEST 1 +# define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether to support Combine(). This only makes sense when @@ -814,16 +803,15 @@ using ::std::tuple_size; // work on Sun Studio since it doesn't understand templated conversion // operators. #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) -# define GTEST_HAS_COMBINE 1 +# define GTEST_HAS_COMBINE 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. -#define GTEST_WIDE_STRING_USES_UTF16_ \ - (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) +#define GTEST_WIDE_STRING_USES_UTF16_ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX -# define GTEST_CAN_STREAM_RESULTS_ 1 +# define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. @@ -837,9 +825,12 @@ using ::std::tuple_size; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT +# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ + switch (0) \ + case 0: \ + default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to @@ -854,25 +845,24 @@ using ::std::tuple_size; // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) +# define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) #elif defined(__clang__) -# if __has_attribute(unused) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -# endif +# if __has_attribute(unused) +# define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused)) +# endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ -# define GTEST_ATTRIBUTE_UNUSED_ +# define GTEST_ATTRIBUTE_UNUSED_ #endif // A macro to disallow operator= // This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_ASSIGN_(type)\ - void operator=(type const &) +#define GTEST_DISALLOW_ASSIGN_(type) void operator=(type const&) // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ - type(type const &);\ +#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \ + type(type const&); \ GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared @@ -881,9 +871,9 @@ using ::std::tuple_size; // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) -# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) +# define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result)) #else -# define GTEST_MUST_USE_RESULT_ +# define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time @@ -894,10 +884,8 @@ using ::std::tuple_size; // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } -# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) -# define GTEST_INTENTIONAL_CONST_COND_POP_() \ - GTEST_DISABLE_MSC_WARNINGS_POP_() +#define GTEST_INTENTIONAL_CONST_COND_PUSH_() GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) +#define GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally @@ -905,84 +893,80 @@ using ::std::tuple_size; #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. -# if defined(_MSC_VER) || defined(__BORLANDC__) +# if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. -# define GTEST_HAS_SEH 1 -# else +# define GTEST_HAS_SEH 1 +# else // Assume no SEH. -# define GTEST_HAS_SEH 0 -# endif +# define GTEST_HAS_SEH 0 +# endif -#define GTEST_IS_THREADSAFE \ - (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \ - || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \ - || GTEST_HAS_PTHREAD) +# define GTEST_IS_THREADSAFE \ + (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \ + GTEST_HAS_PTHREAD) #endif // GTEST_HAS_SEH #ifdef _MSC_VER -# if GTEST_LINKED_AS_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllimport) -# elif GTEST_CREATE_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllexport) -# endif +# if GTEST_LINKED_AS_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllimport) +# elif GTEST_CREATE_SHARED_LIBRARY +# define GTEST_API_ __declspec(dllexport) +# endif #elif __GNUC__ >= 4 || defined(__clang__) -# define GTEST_API_ __attribute__((visibility ("default"))) -#endif // _MSC_VER +# define GTEST_API_ __attribute__((visibility("default"))) +#endif // _MSC_VER #ifndef GTEST_API_ -# define GTEST_API_ +# define GTEST_API_ #endif #ifdef __GNUC__ // Ask the compiler to never inline a given function. -# define GTEST_NO_INLINE_ __attribute__((noinline)) +# define GTEST_NO_INLINE_ __attribute__((noinline)) #else -# define GTEST_NO_INLINE_ +# define GTEST_NO_INLINE_ #endif // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) -# define GTEST_HAS_CXXABI_H_ 1 +# define GTEST_HAS_CXXABI_H_ 1 #else -# define GTEST_HAS_CXXABI_H_ 0 +# define GTEST_HAS_CXXABI_H_ 0 #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) -# if __has_feature(memory_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ - __attribute__((no_sanitize_memory)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -# endif // __has_feature(memory_sanitizer) +# if __has_feature(memory_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +# endif // __has_feature(memory_sanitizer) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ +# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(address_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ - __attribute__((no_sanitize_address)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -# endif // __has_feature(address_sanitizer) +# if __has_feature(address_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ __attribute__((no_sanitize_address)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +# endif // __has_feature(address_sanitizer) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ +# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) -# if __has_feature(thread_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ - __attribute__((no_sanitize_thread)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -# endif // __has_feature(thread_sanitizer) +# if __has_feature(thread_sanitizer) +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread)) +# else +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +# endif // __has_feature(thread_sanitizer) #else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ +# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { @@ -996,8 +980,8 @@ class Message; using GTEST_TUPLE_NAMESPACE_::get; using GTEST_TUPLE_NAMESPACE_::make_tuple; using GTEST_TUPLE_NAMESPACE_::tuple; -using GTEST_TUPLE_NAMESPACE_::tuple_size; using GTEST_TUPLE_NAMESPACE_::tuple_element; +using GTEST_TUPLE_NAMESPACE_::tuple_size; #endif // defined(GTEST_TUPLE_NAMESPACE_) namespace internal { @@ -1023,15 +1007,14 @@ class Secret; // containing the name of the variable. #if GTEST_LANG_CXX11 -# define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) +# define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) #else // !GTEST_LANG_CXX11 template - struct CompileAssert { -}; +struct CompileAssert {}; -# define GTEST_COMPILE_ASSERT_(expr, msg) \ - typedef ::testing::internal::CompileAssert<(static_cast(expr))> \ - msg[static_cast(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ +# define GTEST_COMPILE_ASSERT_(expr, msg) \ + typedef ::testing::internal::CompileAssert<(static_cast(expr))> \ + msg[static_cast(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ #endif // !GTEST_LANG_CXX11 // Implementation details of GTEST_COMPILE_ASSERT_: @@ -1181,21 +1164,13 @@ class GTEST_API_ RE { // // TODO(wan@google.com): make FullMatch() and PartialMatch() work // when str contains NUL characters. - static bool FullMatch(const ::std::string& str, const RE& re) { - return FullMatch(str.c_str(), re); - } - static bool PartialMatch(const ::std::string& str, const RE& re) { - return PartialMatch(str.c_str(), re); - } + static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } + static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #if GTEST_HAS_GLOBAL_STRING - static bool FullMatch(const ::string& str, const RE& re) { - return FullMatch(str.c_str(), re); - } - static bool PartialMatch(const ::string& str, const RE& re) { - return PartialMatch(str.c_str(), re); - } + static bool FullMatch(const ::string& str, const RE& re) { return FullMatch(str.c_str(), re); } + static bool PartialMatch(const ::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #endif // GTEST_HAS_GLOBAL_STRING @@ -1232,8 +1207,7 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, - int line); +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line); // Defines logging utilities: // GTEST_LOG_(severity) - logs messages at the specified severity level. The @@ -1241,12 +1215,7 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. -enum GTestLogSeverity { - GTEST_INFO, - GTEST_WARNING, - GTEST_ERROR, - GTEST_FATAL -}; +enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of @@ -1268,9 +1237,8 @@ class GTEST_API_ GTestLog { #if !defined(GTEST_LOG_) -# define GTEST_LOG_(severity) \ - ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ - __FILE__, __LINE__).GetStream() +# define GTEST_LOG_(severity) \ + ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, __FILE__, __LINE__).GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(NULL); } @@ -1292,11 +1260,11 @@ inline void FlushInfoLog() { fflush(NULL); } // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. -# define GTEST_CHECK_(condition) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ +# define GTEST_CHECK_(condition) \ + GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ - ; \ - else \ + ; \ + else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) @@ -1306,13 +1274,11 @@ inline void FlushInfoLog() { fflush(NULL); } // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ - if (const int gtest_error = (posix_call)) \ - GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ - << gtest_error + if (const int gtest_error = (posix_call)) GTEST_LOG_(FATAL) << #posix_call << "failed with error " << gtest_error #if GTEST_HAS_STD_MOVE_ using std::move; -#else // GTEST_HAS_STD_MOVE_ +#else // GTEST_HAS_STD_MOVE_ template const T& move(const T& t) { return t; @@ -1339,8 +1305,10 @@ const T& move(const T& t) { // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. -template -inline To ImplicitCast_(To x) { return x; } +template +inline To ImplicitCast_(To x) { + return x; +} // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts @@ -1363,15 +1331,15 @@ inline To ImplicitCast_(To x) { return x; } // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. -template // use like this: DownCast_(foo); -inline To DownCast_(From* f) { // so we only accept pointers +template // use like this: DownCast_(foo); +inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { - GTEST_INTENTIONAL_CONST_COND_POP_() + GTEST_INTENTIONAL_CONST_COND_POP_() const To to = NULL; ::testing::internal::ImplicitCast_(to); } @@ -1433,32 +1401,30 @@ GTEST_API_ const ::std::vector& GetArgvs(); #if GTEST_HAS_DEATH_TEST const ::std::vector& GetInjectableArgvs(); -void SetInjectableArgvs(const ::std::vector* - new_argvs); - +void SetInjectableArgvs(const ::std::vector* new_argvs); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. #if GTEST_IS_THREADSAFE -# if GTEST_HAS_PTHREAD +# if GTEST_HAS_PTHREAD // Sleeps for (roughly) n milliseconds. This function is only for testing // Google Test's own constructs. Don't use it in user tests, either // directly or indirectly. inline void SleepMilliseconds(int n) { const timespec time = { - 0, // 0 seconds. - n * 1000L * 1000L, // And n ms. + 0, // 0 seconds. + n * 1000L * 1000L, // And n ms. }; nanosleep(&time, NULL); } -# endif // GTEST_HAS_PTHREAD +# endif // GTEST_HAS_PTHREAD -# if GTEST_HAS_NOTIFICATION_ +# if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. -# elif GTEST_HAS_PTHREAD +# elif GTEST_HAS_PTHREAD // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. @@ -1467,12 +1433,8 @@ inline void SleepMilliseconds(int n) { // use it in user tests, either directly or indirectly. class Notification { public: - Notification() : notified_(false) { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); - } - ~Notification() { - pthread_mutex_destroy(&mutex_); - } + Notification() : notified_(false) { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); } + ~Notification() { pthread_mutex_destroy(&mutex_); } // Notifies all threads created with this notification to start. Must // be called from the controller thread. @@ -1489,8 +1451,7 @@ class Notification { pthread_mutex_lock(&mutex_); const bool notified = notified_; pthread_mutex_unlock(&mutex_); - if (notified) - break; + if (notified) break; SleepMilliseconds(10); } } @@ -1502,7 +1463,7 @@ class Notification { GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; -# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT GTEST_API_ void SleepMilliseconds(int n); @@ -1551,12 +1512,12 @@ class GTEST_API_ Notification { GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; -# endif // GTEST_HAS_NOTIFICATION_ +# endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. -# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW +# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam @@ -1598,15 +1559,11 @@ class ThreadWithParam : public ThreadWithParamBase { typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) - : func_(func), - param_(param), - thread_can_start_(thread_can_start), - finished_(false) { + : func_(func), param_(param), thread_can_start_(thread_can_start), finished_(false) { ThreadWithParamBase* const base = this; // The thread can be created only after all fields except thread_ // have been initialized. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); + GTEST_CHECK_POSIX_SUCCESS_(pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); } ~ThreadWithParam() { Join(); } @@ -1618,30 +1575,29 @@ class ThreadWithParam : public ThreadWithParamBase { } virtual void Run() { - if (thread_can_start_ != NULL) - thread_can_start_->WaitForNotification(); + if (thread_can_start_ != NULL) thread_can_start_->WaitForNotification(); func_(param_); } private: UserThreadFunc* const func_; // User-supplied thread function. - const T param_; // User-supplied parameter to the thread function. + const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; - bool finished_; // true iff we know that the thread function has finished. + bool finished_; // true iff we know that the thread function has finished. pthread_t thread_; // The native thread object. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; -# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || - // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || + // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ -# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. -# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: @@ -1698,11 +1654,9 @@ class GTEST_API_ Mutex { GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::Mutex mutex +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) extern ::testing::internal::Mutex mutex -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some @@ -1711,8 +1665,7 @@ class GTEST_API_ Mutex { // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: - explicit GTestMutexLock(Mutex* mutex) - : mutex_(mutex) { mutex_->Lock(); } + explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } @@ -1756,12 +1709,10 @@ class GTEST_API_ ThreadLocalRegistry { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. - static ThreadLocalValueHolderBase* GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance); + static ThreadLocalValueHolderBase* GetValueOnCurrentThread(const ThreadLocalBase* thread_local_instance); // Invoked when a ThreadLocal instance is destroyed. - static void OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance); + static void OnThreadLocalDestroyed(const ThreadLocalBase* thread_local_instance); }; class GTEST_API_ ThreadWithParamBase { @@ -1775,7 +1726,7 @@ class GTEST_API_ ThreadWithParamBase { virtual void Run() = 0; }; - ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); + ThreadWithParamBase(Runnable* runnable, Notification* thread_can_start); virtual ~ThreadWithParamBase(); private: @@ -1789,21 +1740,15 @@ class ThreadWithParam : public ThreadWithParamBase { typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) - : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { - } + : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {} virtual ~ThreadWithParam() {} private: class RunnableImpl : public Runnable { public: - RunnableImpl(UserThreadFunc* func, T param) - : func_(func), - param_(param) { - } + RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) {} virtual ~RunnableImpl() {} - virtual void Run() { - func_(param_); - } + virtual void Run() { func_(param_); } private: UserThreadFunc* const func_; @@ -1846,8 +1791,7 @@ template class ThreadLocal : public ThreadLocalBase { public: ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} - explicit ThreadLocal(const T& value) - : default_factory_(new InstanceValueHolderFactory(value)) {} + explicit ThreadLocal(const T& value) : default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } @@ -1871,15 +1815,11 @@ class ThreadLocal : public ThreadLocalBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; - T* GetOrCreateValue() const { - return static_cast( - ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); + return static_cast(ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); } - virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { - return default_factory_->MakeNewHolder(); - } + virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { return default_factory_->MakeNewHolder(); } class ValueHolderFactory { public: @@ -1903,9 +1843,7 @@ class ThreadLocal : public ThreadLocalBase { class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} - virtual ValueHolder* MakeNewHolder() const { - return new ValueHolder(value_); - } + virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. @@ -1918,7 +1856,7 @@ class ThreadLocal : public ThreadLocalBase { GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; -# elif GTEST_HAS_PTHREAD +# elif GTEST_HAS_PTHREAD // MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { @@ -1965,12 +1903,11 @@ class MutexBase { }; // Forward-declares a static mutex. -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::MutexBase mutex +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, pthread_t() } +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ + ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, pthread_t()} // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. @@ -1980,9 +1917,7 @@ class Mutex : public MutexBase { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); has_owner_ = false; } - ~Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); - } + ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); @@ -1995,8 +1930,7 @@ class Mutex : public MutexBase { // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: - explicit GTestMutexLock(MutexBase* mutex) - : mutex_(mutex) { mutex_->Lock(); } + explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } @@ -2029,11 +1963,8 @@ extern "C" inline void DeleteThreadLocalValue(void* value_holder) { template class ThreadLocal { public: - ThreadLocal() - : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} - explicit ThreadLocal(const T& value) - : key_(CreateKey()), - default_factory_(new InstanceValueHolderFactory(value)) {} + ThreadLocal() : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} + explicit ThreadLocal(const T& value) : key_(CreateKey()), default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. @@ -2067,14 +1998,12 @@ class ThreadLocal { pthread_key_t key; // When a thread exits, DeleteThreadLocalValue() will be called on // the object managed for that thread. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_key_create(&key, &DeleteThreadLocalValue)); + GTEST_CHECK_POSIX_SUCCESS_(pthread_key_create(&key, &DeleteThreadLocalValue)); return key; } T* GetOrCreateValue() const { - ThreadLocalValueHolderBase* const holder = - static_cast(pthread_getspecific(key_)); + ThreadLocalValueHolderBase* const holder = static_cast(pthread_getspecific(key_)); if (holder != NULL) { return CheckedDowncastToActualType(holder)->pointer(); } @@ -2107,9 +2036,7 @@ class ThreadLocal { class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} - virtual ValueHolder* MakeNewHolder() const { - return new ValueHolder(value_); - } + virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. @@ -2124,7 +2051,7 @@ class ThreadLocal { GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; -# endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ +# endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #else // GTEST_IS_THREADSAFE @@ -2141,10 +2068,9 @@ class Mutex { void AssertHeld() const {} }; -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::Mutex mutex +# define GTEST_DECLARE_STATIC_MUTEX_(mutex) extern ::testing::internal::Mutex mutex -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex +# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some @@ -2167,6 +2093,7 @@ class ThreadLocal { const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } + private: T value_; }; @@ -2186,9 +2113,9 @@ GTEST_API_ size_t GetThreadCount(); #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). -# define GTEST_ELLIPSIS_NEEDS_POD_ 1 +# define GTEST_ELLIPSIS_NEEDS_POD_ 1 #else -# define GTEST_CAN_COMPARE_NULL 1 +# define GTEST_CAN_COMPARE_NULL 1 #endif // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between @@ -2196,7 +2123,7 @@ GTEST_API_ size_t GetThreadCount(); // _can_ decide between class template specializations for T and T*, // so a tr1::type_traits-like is_pointer works. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) -# define GTEST_NEEDS_IS_POINTER_ 1 +# define GTEST_NEEDS_IS_POINTER_ 1 #endif template @@ -2204,7 +2131,8 @@ struct bool_constant { typedef bool_constant type; static const bool value = bool_value; }; -template const bool bool_constant::value; +template +const bool bool_constant::value; typedef bool_constant false_type; typedef bool_constant true_type; @@ -2231,13 +2159,13 @@ struct IteratorTraits { }; #if GTEST_OS_WINDOWS -# define GTEST_PATH_SEP_ "\\" -# define GTEST_HAS_ALT_PATH_SEP_ 1 +# define GTEST_PATH_SEP_ "\\" +# define GTEST_HAS_ALT_PATH_SEP_ 1 // The biggest signed integer type the compiler supports. typedef __int64 BiggestInt; #else -# define GTEST_PATH_SEP_ "/" -# define GTEST_HAS_ALT_PATH_SEP_ 0 +# define GTEST_PATH_SEP_ "/" +# define GTEST_HAS_ALT_PATH_SEP_ 0 typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS @@ -2248,43 +2176,24 @@ typedef long long BiggestInt; // NOLINT // Therefore we need to cast a char to unsigned char before calling // isspace(), etc. -inline bool IsAlpha(char ch) { - return isalpha(static_cast(ch)) != 0; -} -inline bool IsAlNum(char ch) { - return isalnum(static_cast(ch)) != 0; -} -inline bool IsDigit(char ch) { - return isdigit(static_cast(ch)) != 0; -} -inline bool IsLower(char ch) { - return islower(static_cast(ch)) != 0; -} -inline bool IsSpace(char ch) { - return isspace(static_cast(ch)) != 0; -} -inline bool IsUpper(char ch) { - return isupper(static_cast(ch)) != 0; -} -inline bool IsXDigit(char ch) { - return isxdigit(static_cast(ch)) != 0; -} +inline bool IsAlpha(char ch) { return isalpha(static_cast(ch)) != 0; } +inline bool IsAlNum(char ch) { return isalnum(static_cast(ch)) != 0; } +inline bool IsDigit(char ch) { return isdigit(static_cast(ch)) != 0; } +inline bool IsLower(char ch) { return islower(static_cast(ch)) != 0; } +inline bool IsSpace(char ch) { return isspace(static_cast(ch)) != 0; } +inline bool IsUpper(char ch) { return isupper(static_cast(ch)) != 0; } +inline bool IsXDigit(char ch) { return isxdigit(static_cast(ch)) != 0; } inline bool IsXDigit(wchar_t ch) { const unsigned char low_byte = static_cast(ch); return ch == low_byte && isxdigit(low_byte) != 0; } -inline char ToLower(char ch) { - return static_cast(tolower(static_cast(ch))); -} -inline char ToUpper(char ch) { - return static_cast(toupper(static_cast(ch))); -} +inline char ToLower(char ch) { return static_cast(tolower(static_cast(ch))); } +inline char ToUpper(char ch) { return static_cast(toupper(static_cast(ch))); } inline std::string StripTrailingSpaces(std::string str) { std::string::iterator it = str.end(); - while (it != str.begin() && IsSpace(*--it)) - it = str.erase(it); + while (it != str.begin() && IsSpace(*--it)) it = str.erase(it); return str; } @@ -2302,36 +2211,30 @@ namespace posix { typedef struct _stat StatStruct; -# ifdef __BORLANDC__ +# ifdef __BORLANDC__ inline int IsATTY(int fd) { return isatty(fd); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return stricmp(s1, s2); -} +inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } -# else // !__BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE +# else // !__BORLANDC__ +# if GTEST_OS_WINDOWS_MOBILE inline int IsATTY(int /* fd */) { return 0; } -# else +# else inline int IsATTY(int fd) { return _isatty(fd); } -# endif // GTEST_OS_WINDOWS_MOBILE -inline int StrCaseCmp(const char* s1, const char* s2) { - return _stricmp(s1, s2); -} +# endif // GTEST_OS_WINDOWS_MOBILE +inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } -# endif // __BORLANDC__ +# endif // __BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE +# if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. -# else +# else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } -inline bool IsDir(const StatStruct& st) { - return (_S_IFDIR & st.st_mode) != 0; -} -# endif // GTEST_OS_WINDOWS_MOBILE +inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } +# endif // GTEST_OS_WINDOWS_MOBILE #else @@ -2340,9 +2243,7 @@ typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int IsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return strcasecmp(s1, s2); -} +inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } @@ -2353,9 +2254,7 @@ inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) -inline const char* StrNCpy(char* dest, const char* src, size_t n) { - return strncpy(dest, src, n); -} +inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); } // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not @@ -2364,23 +2263,15 @@ inline const char* StrNCpy(char* dest, const char* src, size_t n) { #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT inline int ChDir(const char* dir) { return chdir(dir); } #endif -inline FILE* FOpen(const char* path, const char* mode) { - return fopen(path, mode); -} +inline FILE* FOpen(const char* path, const char* mode) { return fopen(path, mode); } #if !GTEST_OS_WINDOWS_MOBILE -inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { - return freopen(path, mode, stream); -} +inline FILE* FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif inline int FClose(FILE* fp) { return fclose(fp); } #if !GTEST_OS_WINDOWS_MOBILE -inline int Read(int fd, void* buf, unsigned int count) { - return static_cast(read(fd, buf, count)); -} -inline int Write(int fd, const void* buf, unsigned int count) { - return static_cast(write(fd, buf, count)); -} +inline int Read(int fd, void* buf, unsigned int count) { return static_cast(read(fd, buf, count)); } +inline int Write(int fd, const void* buf, unsigned int count) { return static_cast(write(fd, buf, count)); } inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif @@ -2419,14 +2310,13 @@ inline void Abort() { abort(); } // snprintf is a variadic function. #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. -# define GTEST_SNPRINTF_(buffer, size, format, ...) \ - _snprintf_s(buffer, size, size, format, __VA_ARGS__) +# define GTEST_SNPRINTF_(buffer, size, format, ...) _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't // complain about _snprintf. -# define GTEST_SNPRINTF_ _snprintf +# define GTEST_SNPRINTF_ _snprintf #else -# define GTEST_SNPRINTF_ snprintf +# define GTEST_SNPRINTF_ snprintf #endif // The maximum number a BiggestInt can represent. This definition @@ -2436,8 +2326,7 @@ inline void Abort() { abort(); } // We cannot rely on numeric_limits in STL, as __int64 and long long // are not part of standard C++ and numeric_limits doesn't need to be // defined for them. -const BiggestInt kMaxBiggestInt = - ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); +const BiggestInt kMaxBiggestInt = ~(static_cast(1) << (8 * sizeof(BiggestInt) - 1)); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that @@ -2485,7 +2374,7 @@ class TypeWithSize<8> { typedef __int64 Int; typedef unsigned __int64 UInt; #else - typedef long long Int; // NOLINT + typedef long long Int; // NOLINT typedef unsigned long long UInt; // NOLINT #endif // GTEST_OS_WINDOWS }; @@ -2501,37 +2390,33 @@ typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Macro for referencing flags. #if !defined(GTEST_FLAG) -# define GTEST_FLAG(name) FLAGS_gtest_##name +# define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) -# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 +# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) #if !defined(GTEST_DECLARE_bool_) -# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver +# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. -# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) -# define GTEST_DECLARE_int32_(name) \ - GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) -#define GTEST_DECLARE_string_(name) \ - GTEST_API_ extern ::std::string GTEST_FLAG(name) +# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) +# define GTEST_DECLARE_int32_(name) GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) +# define GTEST_DECLARE_string_(name) GTEST_API_ extern ::std::string GTEST_FLAG(name) // Macros for defining flags. -#define GTEST_DEFINE_bool_(name, default_val, doc) \ - GTEST_API_ bool GTEST_FLAG(name) = (default_val) -#define GTEST_DEFINE_int32_(name, default_val, doc) \ +# define GTEST_DEFINE_bool_(name, default_val, doc) GTEST_API_ bool GTEST_FLAG(name) = (default_val) +# define GTEST_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) -#define GTEST_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) +# define GTEST_DEFINE_string_(name, default_val, doc) GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) #endif // !defined(GTEST_DECLARE_bool_) // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) -# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) -# define GTEST_LOCK_EXCLUDED_(locks) +# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) +# define GTEST_LOCK_EXCLUDED_(locks) #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result diff --git a/src/net/test/gtest/include/gtest/internal/gtest-string.h b/src/net/test/gtest/include/gtest/internal/gtest-string.h index 97f1a7fdd2..8eb5b395d3 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-string.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-string.h @@ -43,7 +43,7 @@ #ifdef __BORLANDC__ // string.h is not guaranteed to provide strcpy on C++ Builder. -# include +# include #endif #include @@ -121,8 +121,7 @@ class GTEST_API_ String { // Unlike strcasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL C string, // including the empty string. - static bool CaseInsensitiveCStringEquals(const char* lhs, - const char* rhs); + static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs); // Compares two wide C strings, ignoring case. Returns true iff they // have the same content. @@ -136,13 +135,11 @@ class GTEST_API_ String { // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. - static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, - const wchar_t* rhs); + static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); // Returns true iff the given string ends with the given suffix, ignoring // case. Any string is considered to end with an empty suffix. - static bool EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix); + static bool EndsWithCaseInsensitive(const std::string& str, const std::string& suffix); // Formats an int value as "%02d". static std::string FormatIntWidth2(int value); // "%02d" for width == 2 @@ -155,7 +152,7 @@ class GTEST_API_ String { private: String(); // Not meant to be instantiated. -}; // class String +}; // class String // Gets the content of the stringstream's buffer as an std::string. Each '\0' // character in the buffer is replaced with "\\0". diff --git a/src/net/test/gtest/include/gtest/internal/gtest-tuple.h b/src/net/test/gtest/include/gtest/internal/gtest-tuple.h index e9b405340a..8f9887f81d 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-tuple.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-tuple.h @@ -46,65 +46,55 @@ // private as public. // Sun Studio versions < 12 also have the above bug. #if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) -# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: #else -# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ - template friend class tuple; \ +# define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ + template \ + friend class tuple; \ + \ private: #endif // Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict // with our own definitions. Therefore using our own tuple does not work on // those compilers. -#if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */ -# error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \ +#if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */ +# error \ + "gtest's tuple doesn't compile on Visual Studio 2010 or later. \ GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers." #endif // GTEST_n_TUPLE_(T) is the type of an n-tuple. #define GTEST_0_TUPLE_(T) tuple<> -#define GTEST_1_TUPLE_(T) tuple -#define GTEST_2_TUPLE_(T) tuple -#define GTEST_3_TUPLE_(T) tuple -#define GTEST_4_TUPLE_(T) tuple -#define GTEST_5_TUPLE_(T) tuple -#define GTEST_6_TUPLE_(T) tuple -#define GTEST_7_TUPLE_(T) tuple -#define GTEST_8_TUPLE_(T) tuple -#define GTEST_9_TUPLE_(T) tuple -#define GTEST_10_TUPLE_(T) tuple +#define GTEST_1_TUPLE_(T) tuple +#define GTEST_2_TUPLE_(T) tuple +#define GTEST_3_TUPLE_(T) tuple +#define GTEST_4_TUPLE_(T) tuple +#define GTEST_5_TUPLE_(T) tuple +#define GTEST_6_TUPLE_(T) tuple +#define GTEST_7_TUPLE_(T) tuple +#define GTEST_8_TUPLE_(T) tuple +#define GTEST_9_TUPLE_(T) tuple +#define GTEST_10_TUPLE_(T) tuple // GTEST_n_TYPENAMES_(T) declares a list of n typenames. #define GTEST_0_TYPENAMES_(T) #define GTEST_1_TYPENAMES_(T) typename T##0 #define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 #define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 -#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3 -#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4 -#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5 -#define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6 -#define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 -#define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, \ - typename T##7, typename T##8 -#define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ - typename T##3, typename T##4, typename T##5, typename T##6, \ - typename T##7, typename T##8, typename T##9 +#define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, typename T##3 +#define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, typename T##3, typename T##4 +#define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, typename T##3, typename T##4, typename T##5 +#define GTEST_7_TYPENAMES_(T) \ + typename T##0, typename T##1, typename T##2, typename T##3, typename T##4, typename T##5, typename T##6 +#define GTEST_8_TYPENAMES_(T) \ + typename T##0, typename T##1, typename T##2, typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 +#define GTEST_9_TYPENAMES_(T) \ + typename T##0, typename T##1, typename T##2, typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8 +#define GTEST_10_TYPENAMES_(T) \ + typename T##0, typename T##1, typename T##2, typename T##3, typename T##4, typename T##5, typename T##6, \ + typename T##7, typename T##8, typename T##9 // In theory, defining stuff in the ::std namespace is undefined // behavior. We can do this as we are playing the role of a standard @@ -112,10 +102,8 @@ GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers." namespace std { namespace tr1 { -template +template class tuple; // Anything in namespace gtest_internal is Google Test's INTERNAL @@ -124,9 +112,13 @@ namespace gtest_internal { // ByRef::type is T if T is a reference; otherwise it's const T&. template -struct ByRef { typedef const T& type; }; // NOLINT +struct ByRef { + typedef const T& type; +}; // NOLINT template -struct ByRef { typedef T& type; }; // NOLINT +struct ByRef { + typedef T& type; +}; // NOLINT // A handy wrapper for ByRef. #define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef::type @@ -134,15 +126,20 @@ struct ByRef { typedef T& type; }; // NOLINT // AddRef::type is T if T is a reference; otherwise it's T&. This // is the same as tr1::add_reference::type. template -struct AddRef { typedef T& type; }; // NOLINT +struct AddRef { + typedef T& type; +}; // NOLINT template -struct AddRef { typedef T& type; }; // NOLINT +struct AddRef { + typedef T& type; +}; // NOLINT // A handy wrapper for AddRef. #define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef::type // A helper for implementing get(). -template class Get; +template +class Get; // A helper for implementing tuple_element. kIndexValid is true // iff k < the number of fields in tuple type T. @@ -150,52 +147,52 @@ template struct TupleElement; template -struct TupleElement { +struct TupleElement { typedef T0 type; }; template -struct TupleElement { +struct TupleElement { typedef T1 type; }; template -struct TupleElement { +struct TupleElement { typedef T2 type; }; template -struct TupleElement { +struct TupleElement { typedef T3 type; }; template -struct TupleElement { +struct TupleElement { typedef T4 type; }; template -struct TupleElement { +struct TupleElement { typedef T5 type; }; template -struct TupleElement { +struct TupleElement { typedef T6 type; }; template -struct TupleElement { +struct TupleElement { typedef T7 type; }; template -struct TupleElement { +struct TupleElement { typedef T8 type; }; template -struct TupleElement { +struct TupleElement { typedef T9 type; }; @@ -205,14 +202,15 @@ template <> class tuple<> { public: tuple() {} - tuple(const tuple& /* t */) {} + tuple(const tuple& /* t */) {} tuple& operator=(const tuple& /* t */) { return *this; } }; template class GTEST_1_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_() {} @@ -221,19 +219,19 @@ class GTEST_1_TUPLE_(T) { tuple(const tuple& t) : f0_(t.f0_) {} template - tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} + tuple(const GTEST_1_TUPLE_(U) & t) : f0_(t.f0_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_1_TUPLE_(U)& t) { + tuple& operator=(const GTEST_1_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_1_TUPLE_(U) & t) { f0_ = t.f0_; return *this; } @@ -244,24 +242,24 @@ class GTEST_1_TUPLE_(T) { template class GTEST_2_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), - f1_(f1) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), f1_(f1) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} template - tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} + tuple(const GTEST_2_TUPLE_(U) & t) : f0_(t.f0_), f1_(t.f1_) {} template tuple(const ::std::pair& p) : f0_(p.first), f1_(p.second) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_2_TUPLE_(U)& t) { + tuple& operator=(const GTEST_2_TUPLE_(U) & t) { return CopyFrom(t); } template @@ -274,7 +272,7 @@ class GTEST_2_TUPLE_(T) { GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_2_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; return *this; @@ -287,29 +285,29 @@ class GTEST_2_TUPLE_(T) { template class GTEST_3_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} template - tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} + tuple(const GTEST_3_TUPLE_(U) & t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_3_TUPLE_(U)& t) { + tuple& operator=(const GTEST_3_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_3_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -324,31 +322,30 @@ class GTEST_3_TUPLE_(T) { template class GTEST_4_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) + : f0_(f0), f1_(f1), f2_(f2), f3_(f3) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} template - tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_) {} + tuple(const GTEST_4_TUPLE_(U) & t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_4_TUPLE_(U)& t) { + tuple& operator=(const GTEST_4_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_4_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -365,32 +362,31 @@ class GTEST_4_TUPLE_(T) { template class GTEST_5_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, - GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4) + : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_) {} + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_) {} template - tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_) {} + tuple(const GTEST_5_TUPLE_(U) & t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_5_TUPLE_(U)& t) { + tuple& operator=(const GTEST_5_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_5_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -409,33 +405,31 @@ class GTEST_5_TUPLE_(T) { template class GTEST_6_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5) + : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5) {} - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_) {} + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} template - tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} + tuple(const GTEST_6_TUPLE_(U) & t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_6_TUPLE_(U)& t) { + tuple& operator=(const GTEST_6_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_6_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -456,33 +450,32 @@ class GTEST_6_TUPLE_(T) { template class GTEST_7_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) + : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} template - tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} + tuple(const GTEST_7_TUPLE_(U) & t) + : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_7_TUPLE_(U)& t) { + tuple& operator=(const GTEST_7_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_7_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -505,34 +498,33 @@ class GTEST_7_TUPLE_(T) { template class GTEST_8_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, - GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5), f6_(f6), f7_(f7) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7) + : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7) {} - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + tuple(const tuple& t) + : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} template - tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} + tuple(const GTEST_8_TUPLE_(U) & t) + : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_8_TUPLE_(U)& t) { + tuple& operator=(const GTEST_8_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_8_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -557,34 +549,34 @@ class GTEST_8_TUPLE_(T) { template class GTEST_9_TUPLE_(T) { public: - template friend class gtest_internal::Get; + template + friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, - GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), - f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8) + : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + tuple(const tuple& t) + : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} template - tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} + tuple(const GTEST_9_TUPLE_(U) & t) + : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_9_TUPLE_(U)& t) { + tuple& operator=(const GTEST_9_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_9_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -611,36 +603,52 @@ class GTEST_9_TUPLE_(T) { template class tuple { public: - template friend class gtest_internal::Get; - - tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), - f9_() {} - - explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, - GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, - GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, - GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), - f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} - - tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), - f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} + template + friend class gtest_internal::Get; + + tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), f9_() {} + + explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, + GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, + GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) + : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} + + tuple(const tuple& t) + : f0_(t.f0_), + f1_(t.f1_), + f2_(t.f2_), + f3_(t.f3_), + f4_(t.f4_), + f5_(t.f5_), + f6_(t.f6_), + f7_(t.f7_), + f8_(t.f8_), + f9_(t.f9_) {} template - tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), - f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), - f9_(t.f9_) {} + tuple(const GTEST_10_TUPLE_(U) & t) + : f0_(t.f0_), + f1_(t.f1_), + f2_(t.f2_), + f3_(t.f3_), + f4_(t.f4_), + f5_(t.f5_), + f6_(t.f6_), + f7_(t.f7_), + f8_(t.f8_), + f9_(t.f9_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template - tuple& operator=(const GTEST_10_TUPLE_(U)& t) { + tuple& operator=(const GTEST_10_TUPLE_(U) & t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template - tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { + tuple& CopyFrom(const GTEST_10_TUPLE_(U) & t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; @@ -690,115 +698,111 @@ inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { } template -inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3) { +inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3) { return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); } template -inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4) { +inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4) { return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); } template -inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5) { +inline GTEST_6_TUPLE_(T) + make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5) { return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); } template -inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6) { +inline GTEST_7_TUPLE_(T) + make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6) { return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); } template -inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { +inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, + const T6& f6, const T7& f7) { return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); } template -inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, - const T8& f8) { +inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, + const T6& f6, const T7& f7, const T8& f8) { return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); } template -inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, - const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, - const T8& f8, const T9& f9) { +inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, + const T6& f6, const T7& f7, const T8& f8, const T9& f9) { return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); } // 6.1.3.3 Tuple helper classes. -template struct tuple_size; +template +struct tuple_size; template -struct tuple_size { +struct tuple_size { static const int value = 0; }; template -struct tuple_size { +struct tuple_size { static const int value = 1; }; template -struct tuple_size { +struct tuple_size { static const int value = 2; }; template -struct tuple_size { +struct tuple_size { static const int value = 3; }; template -struct tuple_size { +struct tuple_size { static const int value = 4; }; template -struct tuple_size { +struct tuple_size { static const int value = 5; }; template -struct tuple_size { +struct tuple_size { static const int value = 6; }; template -struct tuple_size { +struct tuple_size { static const int value = 7; }; template -struct tuple_size { +struct tuple_size { static const int value = 8; }; template -struct tuple_size { +struct tuple_size { static const int value = 9; }; template -struct tuple_size { +struct tuple_size { static const int value = 10; }; template struct tuple_element { - typedef typename gtest_internal::TupleElement< - k < (tuple_size::value), k, Tuple>::type type; + typedef typename gtest_internal::TupleElement < k<(tuple_size::value), k, Tuple>::type type; }; -#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type +#define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element::type // 6.1.3.4 Element access. @@ -808,133 +812,153 @@ template <> class Get<0> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) - Field(Tuple& t) { return t.f0_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) Field(Tuple& t) { + return t.f0_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) - ConstField(const Tuple& t) { return t.f0_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) ConstField(const Tuple& t) { + return t.f0_; + } }; template <> class Get<1> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) - Field(Tuple& t) { return t.f1_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) Field(Tuple& t) { + return t.f1_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) - ConstField(const Tuple& t) { return t.f1_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) ConstField(const Tuple& t) { + return t.f1_; + } }; template <> class Get<2> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) - Field(Tuple& t) { return t.f2_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) Field(Tuple& t) { + return t.f2_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) - ConstField(const Tuple& t) { return t.f2_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) ConstField(const Tuple& t) { + return t.f2_; + } }; template <> class Get<3> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) - Field(Tuple& t) { return t.f3_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) Field(Tuple& t) { + return t.f3_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) - ConstField(const Tuple& t) { return t.f3_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) ConstField(const Tuple& t) { + return t.f3_; + } }; template <> class Get<4> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) - Field(Tuple& t) { return t.f4_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) Field(Tuple& t) { + return t.f4_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) - ConstField(const Tuple& t) { return t.f4_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) ConstField(const Tuple& t) { + return t.f4_; + } }; template <> class Get<5> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) - Field(Tuple& t) { return t.f5_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) Field(Tuple& t) { + return t.f5_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) - ConstField(const Tuple& t) { return t.f5_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) ConstField(const Tuple& t) { + return t.f5_; + } }; template <> class Get<6> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) - Field(Tuple& t) { return t.f6_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) Field(Tuple& t) { + return t.f6_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) - ConstField(const Tuple& t) { return t.f6_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) ConstField(const Tuple& t) { + return t.f6_; + } }; template <> class Get<7> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) - Field(Tuple& t) { return t.f7_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) Field(Tuple& t) { + return t.f7_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) - ConstField(const Tuple& t) { return t.f7_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) ConstField(const Tuple& t) { + return t.f7_; + } }; template <> class Get<8> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) - Field(Tuple& t) { return t.f8_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) Field(Tuple& t) { + return t.f8_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) - ConstField(const Tuple& t) { return t.f8_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) ConstField(const Tuple& t) { + return t.f8_; + } }; template <> class Get<9> { public: template - static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) - Field(Tuple& t) { return t.f9_; } // NOLINT + static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) Field(Tuple& t) { + return t.f9_; + } // NOLINT template - static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) - ConstField(const Tuple& t) { return t.f9_; } + static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) ConstField(const Tuple& t) { + return t.f9_; + } }; } // namespace gtest_internal template GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) -get(GTEST_10_TUPLE_(T)& t) { +get(GTEST_10_TUPLE_(T) & t) { return gtest_internal::Get::Field(t); } template -GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) -get(const GTEST_10_TUPLE_(T)& t) { +GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) +get(const GTEST_10_TUPLE_(T) & t) { return gtest_internal::Get::ConstField(t); } @@ -964,23 +988,22 @@ struct SameSizeTuplePrefixComparator { template static bool Eq(const Tuple1& t1, const Tuple2& t2) { return SameSizeTuplePrefixComparator::Eq(t1, t2) && - ::std::tr1::get(t1) == ::std::tr1::get(t2); + ::std::tr1::get(t1) == ::std::tr1::get(t2); } }; } // namespace gtest_internal template -inline bool operator==(const GTEST_10_TUPLE_(T)& t, - const GTEST_10_TUPLE_(U)& u) { - return gtest_internal::SameSizeTuplePrefixComparator< - tuple_size::value, - tuple_size::value>::Eq(t, u); +inline bool operator==(const GTEST_10_TUPLE_(T) & t, const GTEST_10_TUPLE_(U) & u) { + return gtest_internal::SameSizeTuplePrefixComparator::value, + tuple_size::value>::Eq(t, u); } template -inline bool operator!=(const GTEST_10_TUPLE_(T)& t, - const GTEST_10_TUPLE_(U)& u) { return !(t == u); } +inline bool operator!=(const GTEST_10_TUPLE_(T) & t, const GTEST_10_TUPLE_(U) & u) { + return !(t == u); +} // 6.1.4 Pairs. // Unimplemented. diff --git a/src/net/test/gtest/include/gtest/internal/gtest-type-util.h b/src/net/test/gtest/include/gtest/internal/gtest-type-util.h index e46f7cfcb4..ee3df651f1 100644 --- a/src/net/test/gtest/include/gtest/internal/gtest-type-util.h +++ b/src/net/test/gtest/include/gtest/internal/gtest-type-util.h @@ -48,11 +48,11 @@ // #ifdef __GNUC__ is too general here. It is possible to use gcc without using // libstdc++ (which is where cxxabi.h comes from). -# if GTEST_HAS_CXXABI_H_ +#if GTEST_HAS_CXXABI_H_ # include -# elif defined(__HP_aCC) +#elif defined(__HP_aCC) # include -# endif // GTEST_HASH_CXXABI_H_ +#endif // GTEST_HASH_CXXABI_H_ namespace testing { namespace internal { @@ -62,16 +62,16 @@ namespace internal { // the typed-test-only section below. template std::string GetTypeName() { -# if GTEST_HAS_RTTI +#if GTEST_HAS_RTTI const char* const name = typeid(T).name(); # if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) int status = 0; // gcc's implementation of typeid(T).name() mangles the type name, // so we have to demangle it. -# if GTEST_HAS_CXXABI_H_ +# if GTEST_HAS_CXXABI_H_ using abi::__cxa_demangle; -# endif // GTEST_HAS_CXXABI_H_ +# endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, 0, 0, &status); const std::string name_str(status == 0 ? readable_name : name); free(readable_name); @@ -80,11 +80,11 @@ std::string GetTypeName() { return name; # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC -# else +#else return ""; -# endif // GTEST_HAS_RTTI +#endif // GTEST_HAS_RTTI } #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P @@ -148,568 +148,480 @@ struct Types5 { typedef Types4 Tail; }; -template +template struct Types6 { typedef T1 Head; typedef Types5 Tail; }; -template +template struct Types7 { typedef T1 Head; typedef Types6 Tail; }; -template +template struct Types8 { typedef T1 Head; typedef Types7 Tail; }; -template +template struct Types9 { typedef T1 Head; typedef Types8 Tail; }; -template +template struct Types10 { typedef T1 Head; typedef Types9 Tail; }; -template +template struct Types11 { typedef T1 Head; typedef Types10 Tail; }; -template +template struct Types12 { typedef T1 Head; typedef Types11 Tail; }; -template +template struct Types13 { typedef T1 Head; typedef Types12 Tail; }; -template +template struct Types14 { typedef T1 Head; typedef Types13 Tail; }; -template +template struct Types15 { typedef T1 Head; - typedef Types14 Tail; + typedef Types14 Tail; }; -template +template struct Types16 { typedef T1 Head; - typedef Types15 Tail; + typedef Types15 Tail; }; -template +template struct Types17 { typedef T1 Head; - typedef Types16 Tail; + typedef Types16 Tail; }; -template +template struct Types18 { typedef T1 Head; - typedef Types17 Tail; + typedef Types17 Tail; }; -template +template struct Types19 { typedef T1 Head; - typedef Types18 Tail; + typedef Types18 Tail; }; -template +template struct Types20 { typedef T1 Head; - typedef Types19 Tail; + typedef Types19 Tail; }; -template +template struct Types21 { typedef T1 Head; - typedef Types20 Tail; + typedef Types20 Tail; }; -template +template struct Types22 { typedef T1 Head; - typedef Types21 Tail; + typedef Types21 Tail; }; -template +template struct Types23 { typedef T1 Head; - typedef Types22 Tail; + typedef Types22 + Tail; }; -template +template struct Types24 { typedef T1 Head; - typedef Types23 Tail; + typedef Types23 + Tail; }; -template +template struct Types25 { typedef T1 Head; - typedef Types24 Tail; + typedef Types24 + Tail; }; -template +template struct Types26 { typedef T1 Head; - typedef Types25 Tail; + typedef Types25 + Tail; }; -template +template struct Types27 { typedef T1 Head; - typedef Types26 Tail; + typedef Types26 + Tail; }; -template +template struct Types28 { typedef T1 Head; - typedef Types27 Tail; + typedef Types27 + Tail; }; -template +template struct Types29 { typedef T1 Head; - typedef Types28 Tail; + typedef Types28 + Tail; }; -template +template struct Types30 { typedef T1 Head; - typedef Types29 Tail; -}; - -template + typedef Types29 + Tail; +}; + +template struct Types31 { typedef T1 Head; - typedef Types30 Tail; -}; - -template + typedef Types30 + Tail; +}; + +template struct Types32 { typedef T1 Head; - typedef Types31 Tail; -}; - -template + typedef Types31 + Tail; +}; + +template struct Types33 { typedef T1 Head; - typedef Types32 Tail; -}; - -template + typedef Types32 + Tail; +}; + +template struct Types34 { typedef T1 Head; - typedef Types33 Tail; -}; - -template + typedef Types33 + Tail; +}; + +template struct Types35 { typedef T1 Head; - typedef Types34 Tail; -}; - -template + typedef Types34 + Tail; +}; + +template struct Types36 { typedef T1 Head; - typedef Types35 Tail; -}; - -template + typedef Types35 + Tail; +}; + +template struct Types37 { typedef T1 Head; - typedef Types36 Tail; -}; - -template + typedef Types36 + Tail; +}; + +template struct Types38 { typedef T1 Head; - typedef Types37 Tail; -}; - -template + typedef Types37 + Tail; +}; + +template struct Types39 { typedef T1 Head; - typedef Types38 Tail; -}; - -template + typedef Types38 + Tail; +}; + +template struct Types40 { typedef T1 Head; - typedef Types39 Tail; -}; - -template + typedef Types39 + Tail; +}; + +template struct Types41 { typedef T1 Head; - typedef Types40 Tail; -}; - -template + typedef Types40 + Tail; +}; + +template struct Types42 { typedef T1 Head; - typedef Types41 Tail; -}; - -template + typedef Types41 + Tail; +}; + +template struct Types43 { typedef T1 Head; - typedef Types42 Tail; -}; - -template + typedef Types42 + Tail; +}; + +template struct Types44 { typedef T1 Head; - typedef Types43 Tail; -}; - -template + typedef Types43 + Tail; +}; + +template struct Types45 { typedef T1 Head; - typedef Types44 Tail; -}; - -template + typedef Types44 + Tail; +}; + +template struct Types46 { typedef T1 Head; - typedef Types45 Tail; -}; - -template + typedef Types45 + Tail; +}; + +template struct Types47 { typedef T1 Head; - typedef Types46 Tail; -}; - -template + typedef Types46 + Tail; +}; + +template struct Types48 { typedef T1 Head; - typedef Types47 Tail; -}; - -template + typedef Types47 + Tail; +}; + +template struct Types49 { typedef T1 Head; - typedef Types48 Tail; -}; - -template + typedef Types48 + Tail; +}; + +template struct Types50 { typedef T1 Head; - typedef Types49 Tail; + typedef Types49 + Tail; }; - } // namespace internal // We don't want to require the users to write TypesN<...> directly, @@ -725,901 +637,678 @@ struct Types50 { // that to TypesN internally to make error messages // readable. The translation is done by the 'type' member of the // Types template. -template +template struct Types { - typedef internal::Types50 type; + typedef internal::Types50 + type; }; template <> -struct Types { +struct Types { typedef internal::Types0 type; }; template -struct Types { +struct Types< + T1, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, + internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, + internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, + internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, + internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, + internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, + internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types1 type; }; template -struct Types { +struct Types { typedef internal::Types2 type; }; template -struct Types { +struct Types { typedef internal::Types3 type; }; template -struct Types { +struct Types { typedef internal::Types4 type; }; template -struct Types { +struct Types { typedef internal::Types5 type; }; -template -struct Types { +template +struct Types { typedef internal::Types6 type; }; -template -struct Types { +template +struct Types { typedef internal::Types7 type; }; -template -struct Types { +template +struct Types { typedef internal::Types8 type; }; -template -struct Types { +template +struct Types { typedef internal::Types9 type; }; -template -struct Types { +template +struct Types { typedef internal::Types10 type; }; -template -struct Types { +template +struct Types { typedef internal::Types11 type; }; -template -struct Types { - typedef internal::Types12 type; -}; -template -struct Types { - typedef internal::Types13 type; -}; -template -struct Types { - typedef internal::Types14 type; -}; -template -struct Types { - typedef internal::Types15 type; -}; -template -struct Types { - typedef internal::Types16 type; -}; -template -struct Types { - typedef internal::Types17 type; -}; -template -struct Types { - typedef internal::Types18 type; -}; -template -struct Types { - typedef internal::Types19 type; -}; -template -struct Types { - typedef internal::Types20 type; -}; -template -struct Types { - typedef internal::Types21 type; -}; -template -struct Types { - typedef internal::Types22 type; -}; -template -struct Types { - typedef internal::Types23 type; -}; -template -struct Types { - typedef internal::Types24 type; -}; -template -struct Types { - typedef internal::Types25 type; -}; -template -struct Types { - typedef internal::Types26 type; -}; -template -struct Types { - typedef internal::Types27 type; -}; -template -struct Types { - typedef internal::Types28 type; -}; -template -struct Types { - typedef internal::Types29 type; -}; -template -struct Types { - typedef internal::Types30 type; -}; -template -struct Types { - typedef internal::Types31 type; -}; -template -struct Types { - typedef internal::Types32 type; -}; -template -struct Types { - typedef internal::Types33 type; -}; -template -struct Types { - typedef internal::Types34 type; -}; -template -struct Types { - typedef internal::Types35 type; -}; -template -struct Types { - typedef internal::Types36 type; -}; -template -struct Types { - typedef internal::Types37 type; -}; -template -struct Types { - typedef internal::Types38 type; -}; -template -struct Types { - typedef internal::Types39 type; -}; -template -struct Types { - typedef internal::Types40 type; -}; -template -struct Types { - typedef internal::Types41 type; -}; -template -struct Types { - typedef internal::Types42 type; -}; -template -struct Types { - typedef internal::Types43 type; -}; -template -struct Types { - typedef internal::Types44 type; -}; -template -struct Types { - typedef internal::Types45 type; -}; -template -struct Types { - typedef internal::Types46 type; -}; -template -struct Types { - typedef internal::Types47 type; -}; -template -struct Types { - typedef internal::Types48 type; -}; -template -struct Types { - typedef internal::Types49 type; +template +struct Types { + typedef internal::Types12 type; +}; +template +struct Types { + typedef internal::Types13 type; +}; +template +struct Types { + typedef internal::Types14 type; +}; +template +struct Types { + typedef internal::Types15 type; +}; +template +struct Types { + typedef internal::Types16 type; +}; +template +struct Types { + typedef internal::Types17 type; +}; +template +struct Types { + typedef internal::Types18 type; +}; +template +struct Types { + typedef internal::Types19 type; +}; +template +struct Types { + typedef internal::Types20 + type; +}; +template +struct Types { + typedef internal::Types21 + type; +}; +template +struct Types { + typedef internal::Types22 + type; +}; +template +struct Types { + typedef internal::Types23 + type; +}; +template +struct Types { + typedef internal::Types24 + type; +}; +template +struct Types { + typedef internal::Types25 + type; +}; +template +struct Types { + typedef internal::Types26 + type; +}; +template +struct Types { + typedef internal::Types27 + type; +}; +template +struct Types { + typedef internal::Types28 + type; +}; +template +struct Types { + typedef internal::Types29 + type; +}; +template +struct Types { + typedef internal::Types30 + type; +}; +template +struct Types { + typedef internal::Types31 + type; +}; +template +struct Types { + typedef internal::Types32 + type; +}; +template +struct Types { + typedef internal::Types33 + type; +}; +template +struct Types { + typedef internal::Types34 + type; +}; +template +struct Types { + typedef internal::Types35 + type; +}; +template +struct Types { + typedef internal::Types36 + type; +}; +template +struct Types { + typedef internal::Types37 + type; +}; +template +struct Types { + typedef internal::Types38 + type; +}; +template +struct Types { + typedef internal::Types39 + type; +}; +template +struct Types { + typedef internal::Types40 + type; +}; +template +struct Types { + typedef internal::Types41 + type; +}; +template +struct Types { + typedef internal::Types42 + type; +}; +template +struct Types { + typedef internal::Types43 + type; +}; +template +struct Types { + typedef internal::Types44 + type; +}; +template +struct Types { + typedef internal::Types45 + type; +}; +template +struct Types { + typedef internal::Types46 + type; +}; +template +struct Types { + typedef internal::Types47 + type; +}; +template +struct Types { + typedef internal::Types48 + type; +}; +template +struct Types { + typedef internal::Types49 + type; }; namespace internal { -# define GTEST_TEMPLATE_ template class +# define GTEST_TEMPLATE_ \ + template \ + class // The template "selector" struct TemplateSel is used to // represent Tmpl, which must be a class template with one type @@ -1637,8 +1326,7 @@ struct TemplateSel { }; }; -# define GTEST_BIND_(TmplSel, T) \ - TmplSel::template Bind::type +# define GTEST_BIND_(TmplSel, T) TmplSel::template Bind::type // A unique struct template used as the default value for the // arguments of class template Templates. This allows us to simulate @@ -1676,750 +1364,579 @@ struct Templates3 { typedef Templates2 Tail; }; -template +template struct Templates4 { typedef TemplateSel Head; typedef Templates3 Tail; }; -template +template struct Templates5 { typedef TemplateSel Head; typedef Templates4 Tail; }; -template +template struct Templates6 { typedef TemplateSel Head; typedef Templates5 Tail; }; -template +template struct Templates7 { typedef TemplateSel Head; typedef Templates6 Tail; }; -template +template struct Templates8 { typedef TemplateSel Head; typedef Templates7 Tail; }; -template +template struct Templates9 { typedef TemplateSel Head; typedef Templates8 Tail; }; -template +template struct Templates10 { typedef TemplateSel Head; typedef Templates9 Tail; }; -template +template struct Templates11 { typedef TemplateSel Head; typedef Templates10 Tail; }; -template +template struct Templates12 { typedef TemplateSel Head; typedef Templates11 Tail; }; -template +template struct Templates13 { typedef TemplateSel Head; typedef Templates12 Tail; }; -template +template struct Templates14 { typedef TemplateSel Head; - typedef Templates13 Tail; + typedef Templates13 Tail; }; -template +template struct Templates15 { typedef TemplateSel Head; - typedef Templates14 Tail; + typedef Templates14 Tail; }; -template +template struct Templates16 { typedef TemplateSel Head; - typedef Templates15 Tail; + typedef Templates15 Tail; }; -template +template struct Templates17 { typedef TemplateSel Head; - typedef Templates16 Tail; + typedef Templates16 Tail; }; -template +template struct Templates18 { typedef TemplateSel Head; - typedef Templates17 Tail; + typedef Templates17 Tail; }; -template +template struct Templates19 { typedef TemplateSel Head; - typedef Templates18 Tail; + typedef Templates18 Tail; }; -template +template struct Templates20 { typedef TemplateSel Head; - typedef Templates19 Tail; + typedef Templates19 Tail; }; -template +template struct Templates21 { typedef TemplateSel Head; - typedef Templates20 Tail; -}; - -template + typedef Templates20 Tail; +}; + +template struct Templates22 { typedef TemplateSel Head; - typedef Templates21 Tail; -}; - -template + typedef Templates21 + Tail; +}; + +template struct Templates23 { typedef TemplateSel Head; - typedef Templates22 Tail; -}; - -template + typedef Templates22 + Tail; +}; + +template struct Templates24 { typedef TemplateSel Head; - typedef Templates23 Tail; -}; - -template + typedef Templates23 + Tail; +}; + +template struct Templates25 { typedef TemplateSel Head; - typedef Templates24 Tail; -}; - -template + typedef Templates24 + Tail; +}; + +template struct Templates26 { typedef TemplateSel Head; - typedef Templates25 Tail; -}; - -template + typedef Templates25 + Tail; +}; + +template struct Templates27 { typedef TemplateSel Head; - typedef Templates26 Tail; -}; - -template + typedef Templates26 + Tail; +}; + +template struct Templates28 { typedef TemplateSel Head; - typedef Templates27 Tail; -}; - -template + typedef Templates27 + Tail; +}; + +template struct Templates29 { typedef TemplateSel Head; - typedef Templates28 Tail; -}; - -template + typedef Templates28 + Tail; +}; + +template struct Templates30 { typedef TemplateSel Head; - typedef Templates29 Tail; -}; - -template + typedef Templates29 + Tail; +}; + +template struct Templates31 { typedef TemplateSel Head; - typedef Templates30 Tail; -}; - -template + typedef Templates30 + Tail; +}; + +template struct Templates32 { typedef TemplateSel Head; - typedef Templates31 Tail; -}; - -template + typedef Templates31 + Tail; +}; + +template struct Templates33 { typedef TemplateSel Head; - typedef Templates32 Tail; -}; - -template + typedef Templates32 + Tail; +}; + +template struct Templates34 { typedef TemplateSel Head; - typedef Templates33 Tail; -}; - -template + typedef Templates33 + Tail; +}; + +template struct Templates35 { typedef TemplateSel Head; - typedef Templates34 Tail; -}; - -template + typedef Templates34 + Tail; +}; + +template struct Templates36 { typedef TemplateSel Head; - typedef Templates35 Tail; -}; - -template + typedef Templates35 + Tail; +}; + +template struct Templates37 { typedef TemplateSel Head; - typedef Templates36 Tail; -}; - -template + typedef Templates36 + Tail; +}; + +template struct Templates38 { typedef TemplateSel Head; - typedef Templates37 Tail; -}; - -template + typedef Templates37 + Tail; +}; + +template struct Templates39 { typedef TemplateSel Head; - typedef Templates38 Tail; -}; - -template + typedef Templates38 + Tail; +}; + +template struct Templates40 { typedef TemplateSel Head; - typedef Templates39 Tail; -}; - -template + typedef Templates39 + Tail; +}; + +template struct Templates41 { typedef TemplateSel Head; - typedef Templates40 Tail; -}; - -template + typedef Templates40 + Tail; +}; + +template struct Templates42 { typedef TemplateSel Head; - typedef Templates41 Tail; -}; - -template + typedef Templates41 + Tail; +}; + +template struct Templates43 { typedef TemplateSel Head; - typedef Templates42 Tail; -}; - -template + typedef Templates42 + Tail; +}; + +template struct Templates44 { typedef TemplateSel Head; - typedef Templates43 Tail; -}; - -template + typedef Templates43 + Tail; +}; + +template struct Templates45 { typedef TemplateSel Head; - typedef Templates44 Tail; -}; - -template + typedef Templates44 + Tail; +}; + +template struct Templates46 { typedef TemplateSel Head; - typedef Templates45 Tail; -}; - -template + typedef Templates45 + Tail; +}; + +template struct Templates47 { typedef TemplateSel Head; - typedef Templates46 Tail; -}; - -template + typedef Templates46 + Tail; +}; + +template struct Templates48 { typedef TemplateSel Head; - typedef Templates47 Tail; -}; - -template + typedef Templates47 + Tail; +}; + +template struct Templates49 { typedef TemplateSel Head; - typedef Templates48 Tail; -}; - -template + typedef Templates48 + Tail; +}; + +template struct Templates50 { typedef TemplateSel Head; - typedef Templates49 Tail; + typedef Templates49 + Tail; }; - // We don't want to require the users to write TemplatesN<...> directly, // as that would require them to count the length. Templates<...> is much // easier to write, but generates horrible messages when there is a @@ -2433,865 +1950,629 @@ struct Templates50 { // that to TemplatesN internally to make error messages // readable. The translation is done by the 'type' member of the // Templates template. -template struct Templates { - typedef Templates50 type; + typedef Templates50 + type; }; template <> -struct Templates { +struct Templates { typedef Templates0 type; }; template -struct Templates { +struct Templates { typedef Templates1 type; }; template -struct Templates { +struct Templates { typedef Templates2 type; }; template -struct Templates { +struct Templates { typedef Templates3 type; }; -template -struct Templates { +template +struct Templates { typedef Templates4 type; }; -template -struct Templates { +template +struct Templates { typedef Templates5 type; }; -template -struct Templates { +template +struct Templates { typedef Templates6 type; }; -template -struct Templates { +template +struct Templates { typedef Templates7 type; }; -template -struct Templates { +template +struct Templates { typedef Templates8 type; }; -template -struct Templates { +template +struct Templates { typedef Templates9 type; }; -template -struct Templates { +template +struct Templates { typedef Templates10 type; }; -template -struct Templates { +template +struct Templates { typedef Templates11 type; }; -template -struct Templates { +template +struct Templates { typedef Templates12 type; }; -template -struct Templates { - typedef Templates13 type; -}; -template -struct Templates { - typedef Templates14 type; -}; -template -struct Templates { - typedef Templates15 type; -}; -template -struct Templates { - typedef Templates16 type; -}; -template -struct Templates { - typedef Templates17 type; -}; -template -struct Templates { - typedef Templates18 type; -}; -template -struct Templates { - typedef Templates19 type; -}; -template -struct Templates { - typedef Templates20 type; -}; -template -struct Templates { - typedef Templates21 type; -}; -template -struct Templates { - typedef Templates22 type; -}; -template -struct Templates { - typedef Templates23 type; -}; -template -struct Templates { - typedef Templates24 type; -}; -template -struct Templates { - typedef Templates25 type; -}; -template -struct Templates { - typedef Templates26 type; -}; -template -struct Templates { - typedef Templates27 type; -}; -template -struct Templates { - typedef Templates28 type; -}; -template -struct Templates { - typedef Templates29 type; -}; -template -struct Templates { - typedef Templates30 type; -}; -template -struct Templates { - typedef Templates31 type; -}; -template -struct Templates { - typedef Templates32 type; -}; -template -struct Templates { - typedef Templates33 type; -}; -template -struct Templates { - typedef Templates34 type; -}; -template -struct Templates { - typedef Templates35 type; -}; -template -struct Templates { - typedef Templates36 type; -}; -template -struct Templates { - typedef Templates37 type; -}; -template -struct Templates { - typedef Templates38 type; -}; -template -struct Templates { - typedef Templates39 type; -}; -template -struct Templates { - typedef Templates40 type; -}; -template -struct Templates { - typedef Templates41 type; -}; -template -struct Templates { - typedef Templates42 type; -}; -template -struct Templates { - typedef Templates43 type; -}; -template -struct Templates { - typedef Templates44 type; -}; -template -struct Templates { - typedef Templates45 type; -}; -template -struct Templates { - typedef Templates46 type; -}; -template -struct Templates { - typedef Templates47 type; -}; -template -struct Templates { - typedef Templates48 type; -}; -template -struct Templates { - typedef Templates49 type; +template +struct Templates { + typedef Templates13 type; +}; +template +struct Templates { + typedef Templates14 type; +}; +template +struct Templates { + typedef Templates15 type; +}; +template +struct Templates { + typedef Templates16 type; +}; +template +struct Templates { + typedef Templates17 type; +}; +template +struct Templates { + typedef Templates18 type; +}; +template +struct Templates { + typedef Templates19 type; +}; +template +struct Templates { + typedef Templates20 type; +}; +template +struct Templates { + typedef Templates21 + type; +}; +template +struct Templates { + typedef Templates22 + type; +}; +template +struct Templates { + typedef Templates23 + type; +}; +template +struct Templates { + typedef Templates24 + type; +}; +template +struct Templates { + typedef Templates25 + type; +}; +template +struct Templates { + typedef Templates26 + type; +}; +template +struct Templates { + typedef Templates27 + type; +}; +template +struct Templates { + typedef Templates28 + type; +}; +template +struct Templates { + typedef Templates29 + type; +}; +template +struct Templates { + typedef Templates30 + type; +}; +template +struct Templates { + typedef Templates31 + type; +}; +template +struct Templates { + typedef Templates32 + type; +}; +template +struct Templates { + typedef Templates33 + type; +}; +template +struct Templates { + typedef Templates34 + type; +}; +template +struct Templates { + typedef Templates35 + type; +}; +template +struct Templates { + typedef Templates36 + type; +}; +template +struct Templates { + typedef Templates37 + type; +}; +template +struct Templates { + typedef Templates38 + type; +}; +template +struct Templates { + typedef Templates39 + type; +}; +template +struct Templates { + typedef Templates40 + type; +}; +template +struct Templates { + typedef Templates41 + type; +}; +template +struct Templates { + typedef Templates42 + type; +}; +template +struct Templates { + typedef Templates43 + type; +}; +template +struct Templates { + typedef Templates44 + type; +}; +template +struct Templates { + typedef Templates45 + type; +}; +template +struct Templates { + typedef Templates46 + type; +}; +template +struct Templates { + typedef Templates47 + type; +}; +template +struct Templates { + typedef Templates48 + type; +}; +template +struct Templates { + typedef Templates49 + type; }; // The TypeList template makes it possible to use either a single type @@ -3303,24 +2584,19 @@ struct TypeList { typedef Types1 type; }; -template -struct TypeList > { - typedef typename Types::type type; +template +struct TypeList > { + typedef typename Types::type type; }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P diff --git a/src/net/test/gtest/src/gtest-all.cc b/src/net/test/gtest/src/gtest-all.cc index 0a9cee5223..6b09ab36e2 100644 --- a/src/net/test/gtest/src/gtest-all.cc +++ b/src/net/test/gtest/src/gtest-all.cc @@ -39,10 +39,10 @@ #include "gtest/gtest.h" // The following lines pull in the real gtest *.cc files. -#include "src/gtest.cc" #include "src/gtest-death-test.cc" #include "src/gtest-filepath.cc" #include "src/gtest-port.cc" #include "src/gtest-printers.cc" #include "src/gtest-test-part.cc" #include "src/gtest-typed-test.cc" +#include "src/gtest.cc" diff --git a/src/net/test/gtest/src/gtest-death-test.cc b/src/net/test/gtest/src/gtest-death-test.cc index a01a369830..a107632e51 100644 --- a/src/net/test/gtest/src/gtest-death-test.cc +++ b/src/net/test/gtest/src/gtest-death-test.cc @@ -32,35 +32,35 @@ // This file implements death tests. #include "gtest/gtest-death-test.h" -#include "gtest/internal/gtest-port.h" #include "gtest/internal/custom/gtest.h" +#include "gtest/internal/gtest-port.h" #if GTEST_HAS_DEATH_TEST -# if GTEST_OS_MAC -# include -# endif // GTEST_OS_MAC +# if GTEST_OS_MAC +# include +# endif // GTEST_OS_MAC -# include -# include -# include +# include +# include +# include -# if GTEST_OS_LINUX -# include -# endif // GTEST_OS_LINUX +# if GTEST_OS_LINUX +# include +# endif // GTEST_OS_LINUX -# include +# include -# if GTEST_OS_WINDOWS -# include -# else -# include -# include -# endif // GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS +# include +# else +# include +# include +# endif // GTEST_OS_WINDOWS -# if GTEST_OS_QNX -# include -# endif // GTEST_OS_QNX +# if GTEST_OS_QNX +# include +# endif // GTEST_OS_QNX #endif // GTEST_HAS_DEATH_TEST @@ -83,36 +83,31 @@ namespace testing { // The default death test style. static const char kDefaultDeathTestStyle[] = "fast"; -GTEST_DEFINE_string_( - death_test_style, - internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), - "Indicates how to run a death test in a forked child process: " - "\"threadsafe\" (child process re-executes the test binary " - "from the beginning, running only the specific death test) or " - "\"fast\" (child process runs the death test immediately " - "after forking)."); - -GTEST_DEFINE_bool_( - death_test_use_fork, - internal::BoolFromGTestEnv("death_test_use_fork", false), - "Instructs to use fork()/_exit() instead of clone() in death tests. " - "Ignored and always uses fork() on POSIX systems where clone() is not " - "implemented. Useful when running under valgrind or similar tools if " - "those do not support clone(). Valgrind 3.3.1 will just fail if " - "it sees an unsupported combination of clone() flags. " - "It is not recommended to use this flag w/o valgrind though it will " - "work in 99% of the cases. Once valgrind is fixed, this flag will " - "most likely be removed."); +GTEST_DEFINE_string_(death_test_style, internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), + "Indicates how to run a death test in a forked child process: " + "\"threadsafe\" (child process re-executes the test binary " + "from the beginning, running only the specific death test) or " + "\"fast\" (child process runs the death test immediately " + "after forking)."); + +GTEST_DEFINE_bool_(death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false), + "Instructs to use fork()/_exit() instead of clone() in death tests. " + "Ignored and always uses fork() on POSIX systems where clone() is not " + "implemented. Useful when running under valgrind or similar tools if " + "those do not support clone(). Valgrind 3.3.1 will just fail if " + "it sees an unsupported combination of clone() flags. " + "It is not recommended to use this flag w/o valgrind though it will " + "work in 99% of the cases. Once valgrind is fixed, this flag will " + "most likely be removed."); namespace internal { -GTEST_DEFINE_string_( - internal_run_death_test, "", - "Indicates the file, line number, temporal index of " - "the single death test to run, and a file descriptor to " - "which a success code may be sent, all separated by " - "the '|' characters. This flag is specified if and only if the current " - "process is a sub-process launched for running a thread-safe " - "death test. FOR INTERNAL USE ONLY."); +GTEST_DEFINE_string_(internal_run_death_test, "", + "Indicates the file, line number, temporal index of " + "the single death test to run, and a file descriptor to " + "which a success code may be sent, all separated by " + "the '|' characters. This flag is specified if and only if the current " + "process is a sub-process launched for running a thread-safe " + "death test. FOR INTERNAL USE ONLY."); } // namespace internal #if GTEST_HAS_DEATH_TEST @@ -121,9 +116,9 @@ namespace internal { // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. -# if !GTEST_OS_WINDOWS +# if !GTEST_OS_WINDOWS static bool g_in_fast_death_test_child = false; -# endif +# endif // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as @@ -131,58 +126,56 @@ static bool g_in_fast_death_test_child = false; // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. bool InDeathTestChild() { -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS // On Windows, death tests are thread-safe regardless of the value of the // death_test_style flag. return !GTEST_FLAG(internal_run_death_test).empty(); -# else +# else if (GTEST_FLAG(death_test_style) == "threadsafe") return !GTEST_FLAG(internal_run_death_test).empty(); else return g_in_fast_death_test_child; -#endif +# endif } } // namespace internal // ExitedWithCode constructor. -ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { -} +ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {} // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS return exit_status == exit_code_; -# else +# else return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; -# endif // GTEST_OS_WINDOWS +# endif // GTEST_OS_WINDOWS } -# if !GTEST_OS_WINDOWS +# if !GTEST_OS_WINDOWS // KilledBySignal constructor. -KilledBySignal::KilledBySignal(int signum) : signum_(signum) { -} +KilledBySignal::KilledBySignal(int signum) : signum_(signum) {} // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { -# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) +# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) { bool result; if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { return result; } } -# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) +# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } -# endif // !GTEST_OS_WINDOWS +# endif // !GTEST_OS_WINDOWS namespace internal { @@ -193,34 +186,32 @@ namespace internal { static std::string ExitSummary(int exit_code) { Message m; -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS m << "Exited with exit status " << exit_code; -# else +# else if (WIFEXITED(exit_code)) { m << "Exited with exit status " << WEXITSTATUS(exit_code); } else if (WIFSIGNALED(exit_code)) { m << "Terminated by signal " << WTERMSIG(exit_code); } -# ifdef WCOREDUMP +# ifdef WCOREDUMP if (WCOREDUMP(exit_code)) { m << " (core dumped)"; } -# endif -# endif // GTEST_OS_WINDOWS +# endif +# endif // GTEST_OS_WINDOWS return m.GetString(); } // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. -bool ExitedUnsuccessfully(int exit_status) { - return !ExitedWithCode(0)(exit_status); -} +bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } -# if !GTEST_OS_WINDOWS +# if !GTEST_OS_WINDOWS // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the @@ -235,7 +226,7 @@ static std::string DeathTestThreadWarning(size_t thread_count) { msg << "detected " << thread_count << " threads."; return msg.GetString(); } -# endif // !GTEST_OS_WINDOWS +# endif // !GTEST_OS_WINDOWS // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; @@ -263,8 +254,7 @@ void DeathTestAbort(const std::string& message) { // On a POSIX system, this function may be called from a threadsafe-style // death test child process, which operates on a very small stack. Use // the heap for any additional non-minuscule memory requirements. - const InternalRunDeathTestFlag* const flag = - GetUnitTestImpl()->internal_run_death_test_flag(); + const InternalRunDeathTestFlag* const flag = GetUnitTestImpl()->internal_run_death_test_flag(); if (flag != NULL) { FILE* parent = posix::FDOpen(flag->write_fd(), "w"); fputc(kDeathTestInternalError, parent); @@ -280,15 +270,13 @@ void DeathTestAbort(const std::string& message) { // A replacement for CHECK that calls DeathTestAbort if the assertion // fails. -# define GTEST_DEATH_TEST_CHECK_(expression) \ - do { \ - if (!::testing::internal::IsTrue(expression)) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression); \ - } \ - } while (::testing::internal::AlwaysFalse()) +# define GTEST_DEATH_TEST_CHECK_(expression) \ + do { \ + if (!::testing::internal::IsTrue(expression)) { \ + DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + ", line " + \ + ::testing::internal::StreamableToString(__LINE__) + ": " + #expression); \ + } \ + } while (::testing::internal::AlwaysFalse()) // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for // evaluating any system call that fulfills two conditions: it must return @@ -297,24 +285,20 @@ void DeathTestAbort(const std::string& message) { // evaluates the expression as long as it evaluates to -1 and sets // errno to EINTR. If the expression evaluates to -1 but errno is // something other than EINTR, DeathTestAbort is called. -# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ - do { \ - int gtest_retval; \ - do { \ - gtest_retval = (expression); \ - } while (gtest_retval == -1 && errno == EINTR); \ - if (gtest_retval == -1) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression + " != -1"); \ - } \ - } while (::testing::internal::AlwaysFalse()) +# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ + do { \ + int gtest_retval; \ + do { \ + gtest_retval = (expression); \ + } while (gtest_retval == -1 && errno == EINTR); \ + if (gtest_retval == -1) { \ + DeathTestAbort(::std::string("CHECK failed: File ") + __FILE__ + ", line " + \ + ::testing::internal::StreamableToString(__LINE__) + ": " + #expression + " != -1"); \ + } \ + } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. -std::string GetLastErrnoDescription() { - return errno == 0 ? "" : posix::StrError(errno); -} +std::string GetLastErrnoDescription() { return errno == 0 ? "" : posix::StrError(errno); } // This is called from a death test parent process to read a failure // message from the death test child process and log it with the FATAL @@ -336,8 +320,8 @@ static void FailFromInternalError(int fd) { GTEST_LOG_(FATAL) << error.GetString(); } else { const int last_error = errno; - GTEST_LOG_(FATAL) << "Error while reading death test internal: " - << GetLastErrnoDescription() << " [" << last_error << "]"; + GTEST_LOG_(FATAL) << "Error while reading death test internal: " << GetLastErrnoDescription() << " [" << last_error + << "]"; } } @@ -346,26 +330,21 @@ static void FailFromInternalError(int fd) { DeathTest::DeathTest() { TestInfo* const info = GetUnitTestImpl()->current_test_info(); if (info == NULL) { - DeathTestAbort("Cannot run a death test outside of a TEST or " - "TEST_F construct"); + DeathTestAbort( + "Cannot run a death test outside of a TEST or " + "TEST_F construct"); } } // Creates and returns a death test by dispatching to the current // death test factory. -bool DeathTest::Create(const char* statement, const RE* regex, - const char* file, int line, DeathTest** test) { - return GetUnitTestImpl()->death_test_factory()->Create( - statement, regex, file, line, test); +bool DeathTest::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { + return GetUnitTestImpl()->death_test_factory()->Create(statement, regex, file, line, test); } -const char* DeathTest::LastMessage() { - return last_death_test_message_.c_str(); -} +const char* DeathTest::LastMessage() { return last_death_test_message_.c_str(); } -void DeathTest::set_last_death_test_message(const std::string& message) { - last_death_test_message_ = message; -} +void DeathTest::set_last_death_test_message(const std::string& message) { last_death_test_message_ = message; } std::string DeathTest::last_death_test_message_; @@ -463,12 +442,10 @@ void DeathTestImpl::ReadAndInterpretStatusByte() { break; default: GTEST_LOG_(FATAL) << "Death test child process reported " - << "unexpected status byte (" - << static_cast(flag) << ")"; + << "unexpected status byte (" << static_cast(flag) << ")"; } } else { - GTEST_LOG_(FATAL) << "Read from death test child process failed: " - << GetLastErrnoDescription(); + GTEST_LOG_(FATAL) << "Read from death test child process failed: " << GetLastErrnoDescription(); } GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); set_read_fd(-1); @@ -482,9 +459,9 @@ void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte // to the pipe, then exit. - const char status_ch = - reason == TEST_DID_NOT_DIE ? kDeathTestLived : - reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; + const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived + : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew + : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., @@ -503,7 +480,7 @@ void DeathTestImpl::Abort(AbortReason reason) { // much easier. static ::std::string FormatDeathTestOutput(const ::std::string& output) { ::std::string ret; - for (size_t at = 0; ; ) { + for (size_t at = 0;;) { const size_t line_end = output.find('\n', at); ret += "[ DEATH ] "; if (line_end == ::std::string::npos) { @@ -539,8 +516,7 @@ static ::std::string FormatDeathTestOutput(const ::std::string& output) { // first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { - if (!spawned()) - return false; + if (!spawned()) return false; const std::string error_message = GetCapturedStderr(); @@ -551,15 +527,18 @@ bool DeathTestImpl::Passed(bool status_ok) { switch (outcome()) { case LIVED: buffer << " Result: failed to die.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case THREW: buffer << " Result: threw an exception.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case RETURNED: buffer << " Result: illegal return in test statement.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); + << " Error msg:\n" + << FormatDeathTestOutput(error_message); break; case DIED: if (status_ok) { @@ -569,25 +548,26 @@ bool DeathTestImpl::Passed(bool status_ok) { } else { buffer << " Result: died but not with expected error.\n" << " Expected: " << regex()->pattern() << "\n" - << "Actual msg:\n" << FormatDeathTestOutput(error_message); + << "Actual msg:\n" + << FormatDeathTestOutput(error_message); } } else { buffer << " Result: died but not with expected exit code:\n" << " " << ExitSummary(status()) << "\n" - << "Actual msg:\n" << FormatDeathTestOutput(error_message); + << "Actual msg:\n" + << FormatDeathTestOutput(error_message); } break; case IN_PROGRESS: default: - GTEST_LOG_(FATAL) - << "DeathTest::Passed somehow called before conclusion of test"; + GTEST_LOG_(FATAL) << "DeathTest::Passed somehow called before conclusion of test"; } DeathTest::set_last_death_test_message(buffer.GetString()); return success; } -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the @@ -618,10 +598,7 @@ bool DeathTestImpl::Passed(bool status_ok) { // class WindowsDeathTest : public DeathTestImpl { public: - WindowsDeathTest(const char* a_statement, - const RE* a_regex, - const char* file, - int line) + WindowsDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} // All of these virtual functions are inherited from DeathTest. @@ -648,14 +625,12 @@ class WindowsDeathTest : public DeathTestImpl { // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int WindowsDeathTest::Wait() { - if (!spawned()) - return 0; + if (!spawned()) return 0; // Wait until the child either signals that it has acquired the write end // of the pipe or it dies. - const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; - switch (::WaitForMultipleObjects(2, - wait_handles, + const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()}; + switch (::WaitForMultipleObjects(2, wait_handles, FALSE, // Waits for any of the handles. INFINITE)) { case WAIT_OBJECT_0: @@ -676,12 +651,9 @@ int WindowsDeathTest::Wait() { // returns immediately if the child has already exited, regardless of // whether previous calls to WaitForMultipleObjects synchronized on this // handle or not. - GTEST_DEATH_TEST_CHECK_( - WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), - INFINITE)); + GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), INFINITE)); DWORD status_code; - GTEST_DEATH_TEST_CHECK_( - ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); + GTEST_DEATH_TEST_CHECK_(::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); child_handle_.Reset(); set_status(static_cast(status_code)); return status(); @@ -694,8 +666,7 @@ int WindowsDeathTest::Wait() { // current death test only. DeathTest::TestRole WindowsDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); + const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); @@ -708,45 +679,33 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { // WindowsDeathTest uses an anonymous pipe to communicate results of // a death test. - SECURITY_ATTRIBUTES handles_are_inheritable = { - sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE}; HANDLE read_handle, write_handle; - GTEST_DEATH_TEST_CHECK_( - ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, - 0) // Default buffer size. - != FALSE); - set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), - O_RDONLY)); + GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, + 0) // Default buffer size. + != FALSE); + set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), O_RDONLY)); write_handle_.Reset(write_handle); - event_handle_.Reset(::CreateEvent( - &handles_are_inheritable, - TRUE, // The event will automatically reset to non-signaled state. - FALSE, // The initial state is non-signalled. - NULL)); // The even is unnamed. + event_handle_.Reset(::CreateEvent(&handles_are_inheritable, + TRUE, // The event will automatically reset to non-signaled state. + FALSE, // The initial state is non-signalled. + NULL)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); const std::string filter_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + - info->test_case_name() + "." + info->name(); - const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + - "=" + file_ + "|" + StreamableToString(line_) + "|" + - StreamableToString(death_test_index) + "|" + - StreamableToString(static_cast(::GetCurrentProcessId())) + - // size_t has the same width as pointers on both 32-bit and 64-bit - // Windows platforms. - // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. - "|" + StreamableToString(reinterpret_cast(write_handle)) + - "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_case_name() + "." + info->name(); + const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + + StreamableToString(static_cast(::GetCurrentProcessId())) + + // size_t has the same width as pointers on both 32-bit and 64-bit + // Windows platforms. + // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. + "|" + StreamableToString(reinterpret_cast(write_handle)) + "|" + + StreamableToString(reinterpret_cast(event_handle_.Get())); char executable_path[_MAX_PATH + 1]; // NOLINT - GTEST_DEATH_TEST_CHECK_( - _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, - executable_path, - _MAX_PATH)); + GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(NULL, executable_path, _MAX_PATH)); - std::string command_line = - std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + - internal_flag + "\""; + std::string command_line = std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + internal_flag + "\""; DeathTest::set_last_death_test_message(""); @@ -763,23 +722,20 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() { startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION process_info; - GTEST_DEATH_TEST_CHECK_(::CreateProcessA( - executable_path, - const_cast(command_line.c_str()), - NULL, // Retuned process handle is not inheritable. - NULL, // Retuned thread handle is not inheritable. - TRUE, // Child inherits all inheritable handles (for write_handle_). - 0x0, // Default creation flags. - NULL, // Inherit the parent's environment. - UnitTest::GetInstance()->original_working_dir(), - &startup_info, - &process_info) != FALSE); + GTEST_DEATH_TEST_CHECK_(::CreateProcessA(executable_path, const_cast(command_line.c_str()), + NULL, // Retuned process handle is not inheritable. + NULL, // Retuned thread handle is not inheritable. + TRUE, // Child inherits all inheritable handles (for write_handle_). + 0x0, // Default creation flags. + NULL, // Inherit the parent's environment. + UnitTest::GetInstance()->original_working_dir(), &startup_info, + &process_info) != FALSE); child_handle_.Reset(process_info.hProcess); ::CloseHandle(process_info.hThread); set_spawned(true); return OVERSEE_TEST; } -# else // We are not on Windows. +# else // We are not on Windows. // ForkingDeathTest provides implementations for most of the abstract // methods of the DeathTest interface. Only the AssumeRole method is @@ -801,15 +757,13 @@ class ForkingDeathTest : public DeathTestImpl { // Constructs a ForkingDeathTest. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) - : DeathTestImpl(a_statement, a_regex), - child_pid_(-1) {} + : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {} // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int ForkingDeathTest::Wait() { - if (!spawned()) - return 0; + if (!spawned()) return 0; ReadAndInterpretStatusByte(); @@ -823,8 +777,7 @@ int ForkingDeathTest::Wait() { // in the child process. class NoExecDeathTest : public ForkingDeathTest { public: - NoExecDeathTest(const char* a_statement, const RE* a_regex) : - ForkingDeathTest(a_statement, a_regex) { } + NoExecDeathTest(const char* a_statement, const RE* a_regex) : ForkingDeathTest(a_statement, a_regex) {} virtual TestRole AssumeRole(); }; @@ -878,19 +831,17 @@ DeathTest::TestRole NoExecDeathTest::AssumeRole() { // only this specific death test to be run. class ExecDeathTest : public ForkingDeathTest { public: - ExecDeathTest(const char* a_statement, const RE* a_regex, - const char* file, int line) : - ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } + ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) + : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) {} virtual TestRole AssumeRole(); + private: - static ::std::vector - GetArgvsForDeathTestChildProcess() { + static ::std::vector GetArgvsForDeathTestChildProcess() { ::std::vector args = GetInjectableArgvs(); -# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) - ::std::vector extra_args = - GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); +# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) + ::std::vector extra_args = GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); args.insert(args.end(), extra_args.begin(), extra_args.end()); -# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) +# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) return args; } // The name of the file in which the death test is located. @@ -902,31 +853,22 @@ class ExecDeathTest : public ForkingDeathTest { // Utility class for accumulating command-line arguments. class Arguments { public: - Arguments() { - args_.push_back(NULL); - } + Arguments() { args_.push_back(NULL); } ~Arguments() { - for (std::vector::iterator i = args_.begin(); i != args_.end(); - ++i) { + for (std::vector::iterator i = args_.begin(); i != args_.end(); ++i) { free(*i); } } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } + void AddArgument(const char* argument) { args_.insert(args_.end() - 1, posix::StrDup(argument)); } template void AddArguments(const ::std::vector& arguments) { - for (typename ::std::vector::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { + for (typename ::std::vector::const_iterator i = arguments.begin(); i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } - char* const* Argv() { - return &args_[0]; - } + char* const* Argv() { return &args_[0]; } private: std::vector args_; @@ -939,21 +881,21 @@ struct ExecDeathTestArgs { int close_fd; // File descriptor to close; the read end of a pipe }; -# if GTEST_OS_MAC +# if GTEST_OS_MAC inline char** GetEnviron() { // When Google Test is built as a framework on MacOS X, the environ variable // is unavailable. Apple's documentation (man environ) recommends using // _NSGetEnviron() instead. return *_NSGetEnviron(); } -# else +# else // Some POSIX platforms expect you to declare environ. extern "C" makes // it reside in the global namespace. extern "C" char** environ; inline char** GetEnviron() { return environ; } -# endif // GTEST_OS_MAC +# endif // GTEST_OS_MAC -# if !GTEST_OS_QNX +# if !GTEST_OS_QNX // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. @@ -964,12 +906,10 @@ static int ExecDeathTestChildMain(void* child_arg) { // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. - const char* const original_dir = - UnitTest::GetInstance()->original_working_dir(); + const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } @@ -979,12 +919,11 @@ static int ExecDeathTestChildMain(void* child_arg) { // invoke the test program via a valid path that contains at least // one path separator. execve(args->argv[0], args->argv, GetEnviron()); - DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + - original_dir + " failed: " + - GetLastErrnoDescription()); + DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + original_dir + + " failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } -# endif // !GTEST_OS_QNX +# endif // !GTEST_OS_QNX // Two utility routines that together determine the direction the stack // grows. @@ -1018,10 +957,10 @@ bool StackGrowsDown() { // spawn(2) there instead. The function dies with an error message if // anything goes wrong. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { - ExecDeathTestArgs args = { argv, close_fd }; + ExecDeathTestArgs args = {argv, close_fd}; pid_t child_pid = -1; -# if GTEST_OS_QNX +# if GTEST_OS_QNX // Obtains the current directory and sets it to be closed in the child // process. const int cwd_fd = open(".", O_RDONLY); @@ -1030,20 +969,17 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. - const char* const original_dir = - UnitTest::GetInstance()->original_working_dir(); + const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); + DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } int fd_flags; // Set close_fd to be closed after spawn. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); - GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, - fd_flags | FD_CLOEXEC)); + GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC)); struct inheritance inherit = {0}; // spawn is a system call. child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); @@ -1051,8 +987,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); -# else // GTEST_OS_QNX -# if GTEST_OS_LINUX +# else // GTEST_OS_QNX +# if GTEST_OS_LINUX // When a SIGPROF signal is received while fork() or clone() are executing, // the process may hang. To avoid this, we ignore SIGPROF here and re-enable // it after the call to fork()/clone() is complete. @@ -1061,19 +997,17 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); sigemptyset(&ignore_sigprof_action.sa_mask); ignore_sigprof_action.sa_handler = SIG_IGN; - GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( - SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); -# endif // GTEST_OS_LINUX + GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); +# endif // GTEST_OS_LINUX -# if GTEST_HAS_CLONE +# if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG(death_test_use_fork); if (!use_fork) { static const bool stack_grows_down = StackGrowsDown(); const size_t stack_size = getpagesize(); // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. - void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, - MAP_ANON | MAP_PRIVATE, -1, 0); + void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); // Maximum stack alignment in bytes: For a downward-growing stack, this @@ -1083,29 +1017,26 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { // than 64. We assume stack and stack_size already have alignment of // kMaxStackAlignment. const size_t kMaxStackAlignment = 64; - void* const stack_top = - static_cast(stack) + - (stack_grows_down ? stack_size - kMaxStackAlignment : 0); + void* const stack_top = static_cast(stack) + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && - reinterpret_cast(stack_top) % kMaxStackAlignment == 0); + reinterpret_cast(stack_top) % kMaxStackAlignment == 0); child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } -# else +# else const bool use_fork = true; -# endif // GTEST_HAS_CLONE +# endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { - ExecDeathTestChildMain(&args); - _exit(0); + ExecDeathTestChildMain(&args); + _exit(0); } -# endif // GTEST_OS_QNX -# if GTEST_OS_LINUX - GTEST_DEATH_TEST_CHECK_SYSCALL_( - sigaction(SIGPROF, &saved_sigprof_action, NULL)); -# endif // GTEST_OS_LINUX +# endif // GTEST_OS_QNX +# if GTEST_OS_LINUX + GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(SIGPROF, &saved_sigprof_action, NULL)); +# endif // GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; @@ -1117,8 +1048,7 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { // death test to be re-run. DeathTest::TestRole ExecDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); + const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); @@ -1134,13 +1064,10 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); const std::string filter_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" - + info->test_case_name() + "." + info->name(); - const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" - + file_ + "|" + StreamableToString(line_) + "|" - + StreamableToString(death_test_index) + "|" - + StreamableToString(pipe_fd[1]); + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_case_name() + "." + info->name(); + const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + + StreamableToString(pipe_fd[1]); Arguments args; args.AddArguments(GetArgvsForDeathTestChildProcess()); args.AddArgument(filter_flag.c_str()); @@ -1161,46 +1088,40 @@ DeathTest::TestRole ExecDeathTest::AssumeRole() { return OVERSEE_TEST; } -# endif // !GTEST_OS_WINDOWS +# endif // !GTEST_OS_WINDOWS // Creates a concrete DeathTest-derived class that depends on the // --gtest_death_test_style flag, and sets the pointer pointed to // by the "test" argument to its address. If the test should be // skipped, sets that pointer to NULL. Returns true, unless the // flag is set to an invalid value. -bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, - const char* file, int line, +bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const int death_test_index = impl->current_test_info() - ->increment_death_test_count(); + const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); + const int death_test_index = impl->current_test_info()->increment_death_test_count(); if (flag != NULL) { if (death_test_index > flag->index()) { - DeathTest::set_last_death_test_message( - "Death test count (" + StreamableToString(death_test_index) - + ") somehow exceeded expected maximum (" - + StreamableToString(flag->index()) + ")"); + DeathTest::set_last_death_test_message("Death test count (" + StreamableToString(death_test_index) + + ") somehow exceeded expected maximum (" + + StreamableToString(flag->index()) + ")"); return false; } - if (!(flag->file() == file && flag->line() == line && - flag->index() == death_test_index)) { + if (!(flag->file() == file && flag->line() == line && flag->index() == death_test_index)) { *test = NULL; return true; } } -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS - if (GTEST_FLAG(death_test_style) == "threadsafe" || - GTEST_FLAG(death_test_style) == "fast") { + if (GTEST_FLAG(death_test_style) == "threadsafe" || GTEST_FLAG(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, regex, file, line); } -# else +# else if (GTEST_FLAG(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, regex, file, line); @@ -1208,75 +1129,61 @@ bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, *test = new NoExecDeathTest(statement, regex); } -# endif // GTEST_OS_WINDOWS +# endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. - DeathTest::set_last_death_test_message( - "Unknown death test style \"" + GTEST_FLAG(death_test_style) - + "\" encountered"); + DeathTest::set_last_death_test_message("Unknown death test style \"" + GTEST_FLAG(death_test_style) + + "\" encountered"); return false; } return true; } -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. -int GetStatusFileDescriptor(unsigned int parent_process_id, - size_t write_handle_as_size_t, +int GetStatusFileDescriptor(unsigned int parent_process_id, size_t write_handle_as_size_t, size_t event_handle_as_size_t) { AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, - FALSE, // Non-inheritable. - parent_process_id)); + FALSE, // Non-inheritable. + parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { - DeathTestAbort("Unable to open parent process " + - StreamableToString(parent_process_id)); + DeathTestAbort("Unable to open parent process " + StreamableToString(parent_process_id)); } // TODO(vladl@google.com): Replace the following check with a // compile-time assertion when available. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); - const HANDLE write_handle = - reinterpret_cast(write_handle_as_size_t); + const HANDLE write_handle = reinterpret_cast(write_handle_as_size_t); HANDLE dup_write_handle; // The newly initialized handle is accessible only in in the parent // process. To obtain one accessible within the child, we need to use // DuplicateHandle. - if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, - ::GetCurrentProcess(), &dup_write_handle, + if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, ::GetCurrentProcess(), &dup_write_handle, 0x0, // Requested privileges ignored since // DUPLICATE_SAME_ACCESS is used. FALSE, // Request non-inheritable handler. DUPLICATE_SAME_ACCESS)) { - DeathTestAbort("Unable to duplicate the pipe handle " + - StreamableToString(write_handle_as_size_t) + - " from the parent process " + - StreamableToString(parent_process_id)); + DeathTestAbort("Unable to duplicate the pipe handle " + StreamableToString(write_handle_as_size_t) + + " from the parent process " + StreamableToString(parent_process_id)); } const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t); HANDLE dup_event_handle; - if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, - ::GetCurrentProcess(), &dup_event_handle, - 0x0, - FALSE, - DUPLICATE_SAME_ACCESS)) { - DeathTestAbort("Unable to duplicate the event handle " + - StreamableToString(event_handle_as_size_t) + - " from the parent process " + - StreamableToString(parent_process_id)); + if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, ::GetCurrentProcess(), &dup_event_handle, 0x0, + FALSE, DUPLICATE_SAME_ACCESS)) { + DeathTestAbort("Unable to duplicate the event handle " + StreamableToString(event_handle_as_size_t) + + " from the parent process " + StreamableToString(parent_process_id)); } - const int write_fd = - ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); + const int write_fd = ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); if (write_fd == -1) { - DeathTestAbort("Unable to convert pipe handle " + - StreamableToString(write_handle_as_size_t) + + DeathTestAbort("Unable to convert pipe handle " + StreamableToString(write_handle_as_size_t) + " to a file descriptor"); } @@ -1286,7 +1193,7 @@ int GetStatusFileDescriptor(unsigned int parent_process_id, return write_fd; } -# endif // GTEST_OS_WINDOWS +# endif // GTEST_OS_WINDOWS // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if @@ -1302,35 +1209,26 @@ InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); int write_fd = -1; -# if GTEST_OS_WINDOWS +# if GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; size_t event_handle_as_size_t = 0; - if (fields.size() != 6 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &parent_process_id) - || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) - || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { - DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + - GTEST_FLAG(internal_run_death_test)); + if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || + !ParseNaturalNumber(fields[3], &parent_process_id) || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || + !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } - write_fd = GetStatusFileDescriptor(parent_process_id, - write_handle_as_size_t, - event_handle_as_size_t); -# else - - if (fields.size() != 4 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &write_fd)) { - DeathTestAbort("Bad --gtest_internal_run_death_test flag: " - + GTEST_FLAG(internal_run_death_test)); + write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); +# else + + if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || + !ParseNaturalNumber(fields[3], &write_fd)) { + DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } -# endif // GTEST_OS_WINDOWS +# endif // GTEST_OS_WINDOWS return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); } diff --git a/src/net/test/gtest/src/gtest-filepath.cc b/src/net/test/gtest/src/gtest-filepath.cc index 0292dc1195..667cfe9ebd 100644 --- a/src/net/test/gtest/src/gtest-filepath.cc +++ b/src/net/test/gtest/src/gtest-filepath.cc @@ -29,33 +29,33 @@ // // Authors: keith.ray@gmail.com (Keith Ray) -#include "gtest/gtest-message.h" #include "gtest/internal/gtest-filepath.h" +#include "gtest/gtest-message.h" #include "gtest/internal/gtest-port.h" #include #if GTEST_OS_WINDOWS_MOBILE -# include +# include #elif GTEST_OS_WINDOWS -# include -# include +# include +# include #elif GTEST_OS_SYMBIAN // Symbian OpenC has PATH_MAX in sys/syslimits.h -# include +# include #else -# include -# include // Some Linux distributions define PATH_MAX here. -#endif // GTEST_OS_WINDOWS_MOBILE +# include +# include // Some Linux distributions define PATH_MAX here. +#endif // GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS -# define GTEST_PATH_MAX_ _MAX_PATH +# define GTEST_PATH_MAX_ _MAX_PATH #elif defined(PATH_MAX) -# define GTEST_PATH_MAX_ PATH_MAX +# define GTEST_PATH_MAX_ PATH_MAX #elif defined(_XOPEN_PATH_MAX) -# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX +# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #else -# define GTEST_PATH_MAX_ _POSIX_PATH_MAX +# define GTEST_PATH_MAX_ _POSIX_PATH_MAX #endif // GTEST_OS_WINDOWS #include "gtest/internal/gtest-string.h" @@ -71,16 +71,16 @@ namespace internal { const char kPathSeparator = '\\'; const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparatorString[] = "/"; -# if GTEST_OS_WINDOWS_MOBILE +# if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least // provides a reasonable fallback. const char kCurrentDirectoryString[] = "\\"; // Windows CE doesn't define INVALID_FILE_ATTRIBUTES const DWORD kInvalidFileAttributes = 0xffffffff; -# else +# else const char kCurrentDirectoryString[] = ".\\"; -# endif // GTEST_OS_WINDOWS_MOBILE +# endif // GTEST_OS_WINDOWS_MOBILE #else const char kPathSeparator = '/'; const char kCurrentDirectoryString[] = "./"; @@ -102,19 +102,19 @@ FilePath FilePath::GetCurrentDir() { // something reasonable. return FilePath(kCurrentDirectoryString); #elif GTEST_OS_WINDOWS - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); #else - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; + char cwd[GTEST_PATH_MAX_ + 1] = {'\0'}; char* result = getcwd(cwd, sizeof(cwd)); -# if GTEST_OS_NACL +# if GTEST_OS_NACL // getcwd will likely fail in NaCl due to the sandbox, so return something // reasonable. The user may have provided a shim implementation for getcwd, // however, so fallback only when failure is detected. return FilePath(result == NULL ? kCurrentDirectoryString : cwd); -# endif // GTEST_OS_NACL +# endif // GTEST_OS_NACL return FilePath(result == NULL ? "" : cwd); -#endif // GTEST_OS_WINDOWS_MOBILE +#endif // GTEST_OS_WINDOWS_MOBILE } // Returns a copy of the FilePath with the case-insensitive extension removed. @@ -124,8 +124,7 @@ FilePath FilePath::GetCurrentDir() { FilePath FilePath::RemoveExtension(const char* extension) const { const std::string dot_extension = std::string(".") + extension; if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { - return FilePath(pathname_.substr( - 0, pathname_.length() - dot_extension.length())); + return FilePath(pathname_.substr(0, pathname_.length() - dot_extension.length())); } return *this; } @@ -138,8 +137,7 @@ const char* FilePath::FindLastPathSeparator() const { #if GTEST_HAS_ALT_PATH_SEP_ const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); // Comparing two pointers of which only one is NULL is undefined. - if (last_alt_sep != NULL && - (last_sep == NULL || last_alt_sep > last_sep)) { + if (last_alt_sep != NULL && (last_sep == NULL || last_alt_sep > last_sep)) { return last_alt_sep; } #endif @@ -180,26 +178,21 @@ FilePath FilePath::RemoveFileName() const { // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. -FilePath FilePath::MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, +FilePath FilePath::MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension) { std::string file; if (number == 0) { file = base_name.string() + "." + extension; } else { - file = base_name.string() + "_" + StreamableToString(number) - + "." + extension; + file = base_name.string() + "_" + StreamableToString(number) + "." + extension; } return ConcatPaths(directory, FilePath(file)); } // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. -FilePath FilePath::ConcatPaths(const FilePath& directory, - const FilePath& relative_path) { - if (directory.IsEmpty()) - return relative_path; +FilePath FilePath::ConcatPaths(const FilePath& directory, const FilePath& relative_path) { + if (directory.IsEmpty()) return relative_path; const FilePath dir(directory.RemoveTrailingPathSeparator()); return FilePath(dir.string() + kPathSeparator + relative_path.string()); } @@ -210,7 +203,7 @@ bool FilePath::FileOrDirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; + delete[] unicode; return attributes != kInvalidFileAttributes; #else posix::StatStruct file_stat; @@ -225,8 +218,7 @@ bool FilePath::DirectoryExists() const { #if GTEST_OS_WINDOWS // Don't strip off trailing separator if path is a root directory on // Windows (like "C:\\"). - const FilePath& path(IsRootDirectory() ? *this : - RemoveTrailingPathSeparator()); + const FilePath& path(IsRootDirectory() ? *this : RemoveTrailingPathSeparator()); #else const FilePath& path(*this); #endif @@ -234,15 +226,13 @@ bool FilePath::DirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; - if ((attributes != kInvalidFileAttributes) && - (attributes & FILE_ATTRIBUTE_DIRECTORY)) { + delete[] unicode; + if ((attributes != kInvalidFileAttributes) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) { result = true; } #else posix::StatStruct file_stat; - result = posix::Stat(path.c_str(), &file_stat) == 0 && - posix::IsDir(file_stat); + result = posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat); #endif // GTEST_OS_WINDOWS_MOBILE return result; @@ -265,11 +255,8 @@ bool FilePath::IsRootDirectory() const { bool FilePath::IsAbsolutePath() const { const char* const name = pathname_.c_str(); #if GTEST_OS_WINDOWS - return pathname_.length() >= 3 && - ((name[0] >= 'a' && name[0] <= 'z') || - (name[0] >= 'A' && name[0] <= 'Z')) && - name[1] == ':' && - IsPathSeparator(name[2]); + return pathname_.length() >= 3 && ((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z')) && + name[1] == ':' && IsPathSeparator(name[2]); #else return IsPathSeparator(name[0]); #endif @@ -283,9 +270,7 @@ bool FilePath::IsAbsolutePath() const { // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. -FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, - const FilePath& base_name, - const char* extension) { +FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension) { FilePath full_pathname; int number = 0; do { @@ -298,8 +283,7 @@ FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool FilePath::IsDirectory() const { - return !pathname_.empty() && - IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); + return !pathname_.empty() && IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); } // Create directories so that path exists. Returns true if successful or if @@ -327,7 +311,7 @@ bool FilePath::CreateFolder() const { FilePath removed_sep(this->RemoveTrailingPathSeparator()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); int result = CreateDirectory(unicode, NULL) ? 0 : -1; - delete [] unicode; + delete[] unicode; #elif GTEST_OS_WINDOWS int result = _mkdir(pathname_.c_str()); #else @@ -344,9 +328,7 @@ bool FilePath::CreateFolder() const { // name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { - return IsDirectory() - ? FilePath(pathname_.substr(0, pathname_.length() - 1)) - : *this; + return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1)) : *this; } // Removes any redundant separators that might be in the pathname. @@ -373,8 +355,7 @@ void FilePath::Normalize() { *dest_ptr = kPathSeparator; } #endif - while (IsPathSeparator(*src)) - src++; + while (IsPathSeparator(*src)) src++; } dest_ptr++; } diff --git a/src/net/test/gtest/src/gtest-internal-inl.h b/src/net/test/gtest/src/gtest-internal-inl.h index ed8a682a96..d9bad873b1 100644 --- a/src/net/test/gtest/src/gtest-internal-inl.h +++ b/src/net/test/gtest/src/gtest-internal-inl.h @@ -41,12 +41,12 @@ // part of Google Test's implementation; otherwise it's undefined. #if !GTEST_IMPLEMENTATION_ // If this file is included from the user's code, just say no. -# error "gtest-internal-inl.h is part of Google Test's internal implementation." -# error "It must not be included except by Google Test itself." +# error "gtest-internal-inl.h is part of Google Test's internal implementation." +# error "It must not be included except by Google Test itself." #endif // GTEST_IMPLEMENTATION_ #ifndef _WIN32_WCE -# include +# include #endif // !_WIN32_WCE #include #include // For strtoll/_strtoul64/malloc/free. @@ -59,16 +59,16 @@ #include "gtest/internal/gtest-port.h" #if GTEST_CAN_STREAM_RESULTS_ -# include // NOLINT -# include // NOLINT +# include // NOLINT +# include // NOLINT #endif #if GTEST_OS_WINDOWS -# include // NOLINT -#endif // GTEST_OS_WINDOWS +# include // NOLINT +#endif // GTEST_OS_WINDOWS -#include "gtest/gtest.h" // NOLINT #include "gtest/gtest-spi.h" +#include "gtest/gtest.h" // NOLINT namespace testing { @@ -128,21 +128,17 @@ GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. -GTEST_API_ bool ParseInt32Flag( - const char* str, const char* flag, Int32* value); +GTEST_API_ bool ParseInt32Flag(const char* str, const char* flag, Int32* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { - const unsigned int raw_seed = (random_seed_flag == 0) ? - static_cast(GetTimeInMillis()) : - static_cast(random_seed_flag); + const unsigned int raw_seed = (random_seed_flag == 0) ? static_cast(GetTimeInMillis()) + : static_cast(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. - const int normalized_seed = - static_cast((raw_seed - 1U) % - static_cast(kMaxRandomSeed)) + 1; + const int normalized_seed = static_cast((raw_seed - 1U) % static_cast(kMaxRandomSeed)) + 1; return normalized_seed; } @@ -151,8 +147,7 @@ inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { // considered to be 1. inline int GetNextRandomSeed(int seed) { GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) - << "Invalid random seed " << seed << " - must be in [1, " - << kMaxRandomSeed << "]."; + << "Invalid random seed " << seed << " - must be in [1, " << kMaxRandomSeed << "]."; const int next_seed = seed + 1; return (next_seed > kMaxRandomSeed) ? 1 : next_seed; } @@ -259,8 +254,7 @@ void WriteToShardStatusFileIfNeeded(); // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. -GTEST_API_ bool ShouldShard(const char* total_shards_str, - const char* shard_index_str, +GTEST_API_ bool ShouldShard(const char* total_shards_str, const char* shard_index_str, bool in_subprocess_for_death_test); // Parses the environment variable var as an Int32. If it is unset, @@ -272,8 +266,7 @@ GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. -GTEST_API_ bool ShouldRunTestOnShard( - int total_shards, int shard_index, int test_id); +GTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id); // STL container utilities. @@ -285,8 +278,7 @@ inline int CountIf(const Container& c, Predicate predicate) { // Solaris has a non-standard signature. int count = 0; for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { - if (predicate(*it)) - ++count; + if (predicate(*it)) ++count; } return count; } @@ -309,15 +301,12 @@ inline E GetElementOr(const std::vector& v, int i, E default_value) { // i.e. [begin, end) are shuffled, where 'end' == size() means to // shuffle to the end of the vector. template -void ShuffleRange(internal::Random* random, int begin, int end, - std::vector* v) { +void ShuffleRange(internal::Random* random, int begin, int end, std::vector* v) { const int size = static_cast(v->size()); GTEST_CHECK_(0 <= begin && begin <= size) - << "Invalid shuffle range start " << begin << ": must be in range [0, " - << size << "]."; + << "Invalid shuffle range start " << begin << ": must be in range [0, " << size << "]."; GTEST_CHECK_(begin <= end && end <= size) - << "Invalid shuffle range finish " << end << ": must be in range [" - << begin << ", " << size << "]."; + << "Invalid shuffle range finish " << end << ": must be in range [" << begin << ", " << size << "]."; // Fisher-Yates shuffle, from // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle @@ -352,9 +341,7 @@ class TestPropertyKeyIs { explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} // Returns true iff the test name of test property matches on key_. - bool operator()(const TestProperty& test_property) const { - return test_property.key() == key_; - } + bool operator()(const TestProperty& test_property) const { return test_property.key() == key_; } private: std::string key_; @@ -389,12 +376,11 @@ class GTEST_API_ UnitTestOptions { // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. - static bool PatternMatchesString(const char *pattern, const char *str); + static bool PatternMatchesString(const char* pattern, const char* str); // Returns true iff the user-specified filter matches the test case // name and the test name. - static bool FilterMatchesTest(const std::string &test_case_name, - const std::string &test_name); + static bool FilterMatchesTest(const std::string& test_case_name, const std::string& test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. @@ -462,8 +448,7 @@ struct TraceInfo { // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. -class DefaultGlobalTestPartResultReporter - : public TestPartResultReporterInterface { +class DefaultGlobalTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part @@ -478,8 +463,7 @@ class DefaultGlobalTestPartResultReporter // This is the default per thread test part result reporter used in // UnitTestImpl. This class should only be used by UnitTestImpl. -class DefaultPerThreadTestPartResultReporter - : public TestPartResultReporterInterface { +class DefaultPerThreadTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. The implementation just @@ -512,15 +496,13 @@ class GTEST_API_ UnitTestImpl { TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); // Sets the global test part result reporter. - void SetGlobalTestPartResultReporter( - TestPartResultReporterInterface* reporter); + void SetGlobalTestPartResultReporter(TestPartResultReporterInterface* reporter); // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); // Sets the test part result reporter for the current thread. - void SetTestPartResultReporterForCurrentThread( - TestPartResultReporterInterface* reporter); + void SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface* reporter); // Gets the number of successful test cases. int successful_test_case_count() const; @@ -568,9 +550,7 @@ class GTEST_API_ UnitTestImpl { // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). - bool Failed() const { - return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); - } + bool Failed() const { return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. @@ -630,9 +610,7 @@ class GTEST_API_ UnitTestImpl { // this is not a typed or a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case - TestCase* GetTestCase(const char* test_case_name, - const char* type_param, - Test::SetUpTestCaseFunc set_up_tc, + TestCase* GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Adds a TestInfo to the unit test. @@ -642,9 +620,7 @@ class GTEST_API_ UnitTestImpl { // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // test_info: the TestInfo object - void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc, - TestInfo* test_info) { + void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo* test_info) { // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // was first invoked. We cannot do this in RUN_ALL_TESTS(), as @@ -654,35 +630,25 @@ class GTEST_API_ UnitTestImpl { // before main() is reached. if (original_working_dir_.IsEmpty()) { original_working_dir_.Set(FilePath::GetCurrentDir()); - GTEST_CHECK_(!original_working_dir_.IsEmpty()) - << "Failed to get the current working directory."; + GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } - GetTestCase(test_info->test_case_name(), - test_info->type_param(), - set_up_tc, - tear_down_tc)->AddTestInfo(test_info); + GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc, tear_down_tc)->AddTestInfo(test_info); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. - internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { - return parameterized_test_registry_; - } + internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { return parameterized_test_registry_; } #endif // GTEST_HAS_PARAM_TEST // Sets the TestCase object for the test that's currently running. - void set_current_test_case(TestCase* a_current_test_case) { - current_test_case_ = a_current_test_case; - } + void set_current_test_case(TestCase* a_current_test_case) { current_test_case_ = a_current_test_case; } // Sets the TestInfo object for the test that's currently running. If // current_test_info is NULL, the assertion results will be stored in // ad_hoc_test_result_. - void set_current_test_info(TestInfo* a_current_test_info) { - current_test_info_ = a_current_test_info; - } + void set_current_test_info(TestInfo* a_current_test_info) { current_test_info_ = a_current_test_info; } // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter @@ -699,14 +665,10 @@ class GTEST_API_ UnitTestImpl { bool RunAllTests(); // Clears the results of all tests, except the ad hoc tests. - void ClearNonAdHocTestResult() { - ForEach(test_cases_, TestCase::ClearTestCaseResult); - } + void ClearNonAdHocTestResult() { ForEach(test_cases_, TestCase::ClearTestCaseResult); } // Clears the results of ad-hoc test assertions. - void ClearAdHocTestResult() { - ad_hoc_test_result_.Clear(); - } + void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test or a test case, or to the global property set. If the @@ -714,10 +676,7 @@ class GTEST_API_ UnitTestImpl { // updated. void RecordProperty(const TestProperty& test_property); - enum ReactionToSharding { - HONOR_SHARDING_PROTOCOL, - IGNORE_SHARDING_PROTOCOL - }; + enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the @@ -739,29 +698,19 @@ class GTEST_API_ UnitTestImpl { std::vector& environments() { return environments_; } // Getters for the per-thread Google Test trace stack. - std::vector& gtest_trace_stack() { - return *(gtest_trace_stack_.pointer()); - } - const std::vector& gtest_trace_stack() const { - return gtest_trace_stack_.get(); - } + std::vector& gtest_trace_stack() { return *(gtest_trace_stack_.pointer()); } + const std::vector& gtest_trace_stack() const { return gtest_trace_stack_.get(); } #if GTEST_HAS_DEATH_TEST - void InitDeathTestSubprocessControlInfo() { - internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); - } + void InitDeathTestSubprocessControlInfo() { internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); } // Returns a pointer to the parsed --gtest_internal_run_death_test // flag, or NULL if that flag was not specified. // This information is useful only in a death test child process. // Must not be called before a call to InitGoogleTest. - const InternalRunDeathTestFlag* internal_run_death_test_flag() const { - return internal_run_death_test_flag_.get(); - } + const InternalRunDeathTestFlag* internal_run_death_test_flag() const { return internal_run_death_test_flag_.get(); } // Returns a pointer to the current death test factory. - internal::DeathTestFactory* death_test_factory() { - return death_test_factory_.get(); - } + internal::DeathTestFactory* death_test_factory() { return death_test_factory_.get(); } void SuppressTestEventsIfInSubprocess(); @@ -818,8 +767,7 @@ class GTEST_API_ UnitTestImpl { // The default test part result reporters. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; - DefaultPerThreadTestPartResultReporter - default_per_thread_test_part_result_reporter_; + DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_; // Points to (but doesn't own) the global test part result reporter. TestPartResultReporterInterface* global_test_part_result_repoter_; @@ -828,8 +776,7 @@ class GTEST_API_ UnitTestImpl { internal::Mutex global_test_part_result_reporter_mutex_; // Points to (but doesn't own) the per-thread test part result reporter. - internal::ThreadLocal - per_thread_test_part_result_reporter_; + internal::ThreadLocal per_thread_test_part_result_reporter_; // The vector of environments that need to be set-up/torn-down // before/after the tests are run. @@ -924,9 +871,7 @@ class GTEST_API_ UnitTestImpl { // Convenience function for accessing the global UnitTest // implementation object. -inline UnitTestImpl* GetUnitTestImpl() { - return UnitTest::GetInstance()->impl(); -} +inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } #if GTEST_USES_SIMPLE_RE @@ -942,8 +887,7 @@ GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); -GTEST_API_ bool MatchRepetitionAndRegexAtHead( - bool escaped, char ch, char repeat, const char* regex, const char* str); +GTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch, char repeat, const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE @@ -977,18 +921,18 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // BiggestConvertible is the largest integer type that system-provided // string-to-number conversion routines can return. -# if GTEST_OS_WINDOWS && !defined(__GNUC__) +# if GTEST_OS_WINDOWS && !defined(__GNUC__) // MSVC and C++ Builder define __int64 instead of the standard long long. typedef unsigned __int64 BiggestConvertible; const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); -# else +# else typedef unsigned long long BiggestConvertible; // NOLINT const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); -# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) +# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) const bool parse_success = *end == '\0' && errno == 0; @@ -1013,18 +957,13 @@ bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // constructs. Do not use it in user tests, either directly or indirectly. class TestResultAccessor { public: - static void RecordProperty(TestResult* test_result, - const std::string& xml_element, - const TestProperty& property) { + static void RecordProperty(TestResult* test_result, const std::string& xml_element, const TestProperty& property) { test_result->RecordProperty(xml_element, property); } - static void ClearTestPartResults(TestResult* test_result) { - test_result->ClearTestPartResults(); - } + static void ClearTestPartResults(TestResult* test_result) { test_result->ClearTestPartResults(); } - static const std::vector& test_part_results( - const TestResult& test_result) { + static const std::vector& test_part_results(const TestResult& test_result) { return test_result.test_part_results(); } }; @@ -1046,34 +985,27 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener { virtual void CloseConnection() {} // Sends a string and a newline to the socket. - void SendLn(const string& message) { - Send(message + "\n"); - } + void SendLn(const string& message) { Send(message + "\n"); } }; // Concrete class for actually writing strings to a socket. class SocketWriter : public AbstractSocketWriter { public: - SocketWriter(const string& host, const string& port) - : sockfd_(-1), host_name_(host), port_num_(port) { + SocketWriter(const string& host, const string& port) : sockfd_(-1), host_name_(host), port_num_(port) { MakeConnection(); } virtual ~SocketWriter() { - if (sockfd_ != -1) - CloseConnection(); + if (sockfd_ != -1) CloseConnection(); } // Sends a string to the socket. virtual void Send(const string& message) { - GTEST_CHECK_(sockfd_ != -1) - << "Send() can be called only when there is a connection."; + GTEST_CHECK_(sockfd_ != -1) << "Send() can be called only when there is a connection."; const int len = static_cast(message.length()); if (write(sockfd_, message.c_str(), len) != len) { - GTEST_LOG_(WARNING) - << "stream_result_to: failed to stream to " - << host_name_ << ":" << port_num_; + GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_; } } @@ -1083,8 +1015,7 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener { // Closes the socket. void CloseConnection() { - GTEST_CHECK_(sockfd_ != -1) - << "CloseConnection() can be called only when there is a connection."; + GTEST_CHECK_(sockfd_ != -1) << "CloseConnection() can be called only when there is a connection."; close(sockfd_); sockfd_ = -1; @@ -1100,15 +1031,11 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener { // Escapes '=', '&', '%', and '\n' characters in str as "%xx". static string UrlEncode(const char* str); - StreamingListener(const string& host, const string& port) - : socket_writer_(new SocketWriter(host, port)) { Start(); } + StreamingListener(const string& host, const string& port) : socket_writer_(new SocketWriter(host, port)) { Start(); } - explicit StreamingListener(AbstractSocketWriter* socket_writer) - : socket_writer_(socket_writer) { Start(); } + explicit StreamingListener(AbstractSocketWriter* socket_writer) : socket_writer_(socket_writer) { Start(); } - void OnTestProgramStart(const UnitTest& /* unit_test */) { - SendLn("event=TestProgramStart"); - } + void OnTestProgramStart(const UnitTest& /* unit_test */) { SendLn("event=TestProgramStart"); } void OnTestProgramEnd(const UnitTest& unit_test) { // Note that Google Test current only report elapsed time for each @@ -1120,14 +1047,12 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener { } void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { - SendLn("event=TestIterationStart&iteration=" + - StreamableToString(iteration)); + SendLn("event=TestIterationStart&iteration=" + StreamableToString(iteration)); } void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { - SendLn("event=TestIterationEnd&passed=" + - FormatBool(unit_test.Passed()) + "&elapsed_time=" + - StreamableToString(unit_test.elapsed_time()) + "ms"); + SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) + + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) + "ms"); } void OnTestCaseStart(const TestCase& test_case) { @@ -1135,29 +1060,22 @@ class GTEST_API_ StreamingListener : public EmptyTestEventListener { } void OnTestCaseEnd(const TestCase& test_case) { - SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) - + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) - + "ms"); + SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + "ms"); } - void OnTestStart(const TestInfo& test_info) { - SendLn(std::string("event=TestStart&name=") + test_info.name()); - } + void OnTestStart(const TestInfo& test_info) { SendLn(std::string("event=TestStart&name=") + test_info.name()); } void OnTestEnd(const TestInfo& test_info) { - SendLn("event=TestEnd&passed=" + - FormatBool((test_info.result())->Passed()) + - "&elapsed_time=" + - StreamableToString((test_info.result())->elapsed_time()) + "ms"); + SendLn("event=TestEnd&passed=" + FormatBool((test_info.result())->Passed()) + + "&elapsed_time=" + StreamableToString((test_info.result())->elapsed_time()) + "ms"); } void OnTestPartResult(const TestPartResult& test_part_result) { const char* file_name = test_part_result.file_name(); - if (file_name == NULL) - file_name = ""; - SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + - "&line=" + StreamableToString(test_part_result.line_number()) + - "&message=" + UrlEncode(test_part_result.message())); + if (file_name == NULL) file_name = ""; + SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + "&line=" + + StreamableToString(test_part_result.line_number()) + "&message=" + UrlEncode(test_part_result.message())); } private: diff --git a/src/net/test/gtest/src/gtest-port.cc b/src/net/test/gtest/src/gtest-port.cc index e5bf3dd2be..a6c0c03e45 100644 --- a/src/net/test/gtest/src/gtest-port.cc +++ b/src/net/test/gtest/src/gtest-port.cc @@ -32,39 +32,39 @@ #include "gtest/internal/gtest-port.h" #include -#include #include +#include #include #include #if GTEST_OS_WINDOWS -# include -# include -# include -# include // Used in ThreadLocal. +# include +# include +# include +# include // Used in ThreadLocal. #else -# include +# include #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC -# include -# include -# include +# include +# include +# include #endif // GTEST_OS_MAC #if GTEST_OS_QNX -# include -# include -# include +# include +# include +# include #endif // GTEST_OS_QNX #if GTEST_OS_AIX -# include -# include +# include +# include #endif // GTEST_OS_AIX -#include "gtest/gtest-spi.h" #include "gtest/gtest-message.h" +#include "gtest/gtest-spi.h" #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" @@ -107,8 +107,7 @@ T ReadProcFileField(const string& filename, int field) { // Returns the number of active threads, or 0 when there is an error. size_t GetThreadCount() { - const string filename = - (Message() << "/proc/" << getpid() << "/stat").GetString(); + const string filename = (Message() << "/proc/" << getpid() << "/stat").GetString(); return ReadProcFileField(filename, 19); } @@ -122,9 +121,7 @@ size_t GetThreadCount() { if (status == KERN_SUCCESS) { // task_threads allocates resources in thread_list and we need to free them // to avoid leaks. - vm_deallocate(task, - reinterpret_cast(thread_list), - sizeof(thread_t) * thread_count); + vm_deallocate(task, reinterpret_cast(thread_list), sizeof(thread_t) * thread_count); return static_cast(thread_count); } else { return 0; @@ -141,8 +138,7 @@ size_t GetThreadCount() { return 0; } procfs_info process_info; - const int status = - devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); + const int status = devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); close(fd); if (status == EOK) { return static_cast(process_info.num_threads); @@ -176,27 +172,17 @@ size_t GetThreadCount() { #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS -void SleepMilliseconds(int n) { - ::Sleep(n); -} +void SleepMilliseconds(int n) { ::Sleep(n); } -AutoHandle::AutoHandle() - : handle_(INVALID_HANDLE_VALUE) {} +AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} -AutoHandle::AutoHandle(Handle handle) - : handle_(handle) {} +AutoHandle::AutoHandle(Handle handle) : handle_(handle) {} -AutoHandle::~AutoHandle() { - Reset(); -} +AutoHandle::~AutoHandle() { Reset(); } -AutoHandle::Handle AutoHandle::Get() const { - return handle_; -} +AutoHandle::Handle AutoHandle::Get() const { return handle_; } -void AutoHandle::Reset() { - Reset(INVALID_HANDLE_VALUE); -} +void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); } void AutoHandle::Reset(HANDLE handle) { // Resetting with the same handle we already own is invalid. @@ -206,9 +192,8 @@ void AutoHandle::Reset(HANDLE handle) { } handle_ = handle; } else { - GTEST_CHECK_(!IsCloseable()) - << "Resetting a valid handle to itself is likely a programmer error " - "and thus not allowed."; + GTEST_CHECK_(!IsCloseable()) << "Resetting a valid handle to itself is likely a programmer error " + "and thus not allowed."; } } @@ -219,27 +204,21 @@ bool AutoHandle::IsCloseable() const { } Notification::Notification() - : event_(::CreateEvent(NULL, // Default security attributes. - TRUE, // Do not reset automatically. - FALSE, // Initially unset. + : event_(::CreateEvent(NULL, // Default security attributes. + TRUE, // Do not reset automatically. + FALSE, // Initially unset. NULL)) { // Anonymous event. GTEST_CHECK_(event_.Get() != NULL); } -void Notification::Notify() { - GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); -} +void Notification::Notify() { GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); } void Notification::WaitForNotification() { - GTEST_CHECK_( - ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); + GTEST_CHECK_(::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); } Mutex::Mutex() - : owner_thread_id_(0), - type_(kDynamic), - critical_section_init_phase_(0), - critical_section_(new CRITICAL_SECTION) { + : owner_thread_id_(0), type_(kDynamic), critical_section_init_phase_(0), critical_section_(new CRITICAL_SECTION) { ::InitializeCriticalSection(critical_section_); } @@ -275,16 +254,14 @@ void Mutex::Unlock() { // with high probability. void Mutex::AssertHeld() { ThreadSafeLazyInit(); - GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) - << "The current thread is not holding the mutex @" << this; + GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) << "The current thread is not holding the mutex @" << this; } // Initializes owner_thread_id_ and critical_section_ in static mutexes. void Mutex::ThreadSafeLazyInit() { // Dynamic mutexes are initialized in the constructor. if (type_ == kStatic) { - switch ( - ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { + switch (::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { case 0: // If critical_section_init_phase_ was 0 before the exchange, we // are the first to test it and need to perform the initialization. @@ -293,16 +270,12 @@ void Mutex::ThreadSafeLazyInit() { ::InitializeCriticalSection(critical_section_); // Updates the critical_section_init_phase_ to 2 to signal // initialization complete. - GTEST_CHECK_(::InterlockedCompareExchange( - &critical_section_init_phase_, 2L, 1L) == - 1L); + GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_, 2L, 1L) == 1L); break; case 1: // Somebody else is already initializing the mutex; spin until they // are done. - while (::InterlockedCompareExchange(&critical_section_init_phase_, - 2L, - 2L) != 2L) { + while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L, 2L) != 2L) { // Possibly yields the rest of the thread's time slice to other // threads. ::Sleep(0); @@ -313,9 +286,8 @@ void Mutex::ThreadSafeLazyInit() { break; // The mutex is already initialized and ready for use. default: - GTEST_CHECK_(false) - << "Unexpected value of critical_section_init_phase_ " - << "while initializing a static mutex."; + GTEST_CHECK_(false) << "Unexpected value of critical_section_init_phase_ " + << "while initializing a static mutex."; } } } @@ -324,20 +296,17 @@ namespace { class ThreadWithParamSupport : public ThreadWithParamBase { public: - static HANDLE CreateThread(Runnable* runnable, - Notification* thread_can_start) { + static HANDLE CreateThread(Runnable* runnable, Notification* thread_can_start) { ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); DWORD thread_id; // TODO(yukawa): Consider to use _beginthreadex instead. - HANDLE thread_handle = ::CreateThread( - NULL, // Default security. - 0, // Default stack size. - &ThreadWithParamSupport::ThreadMain, - param, // Parameter to ThreadMainStatic - 0x0, // Default creation flags. - &thread_id); // Need a valid pointer for the call to work under Win98. - GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error " - << ::GetLastError() << "."; + HANDLE thread_handle = ::CreateThread(NULL, // Default security. + 0, // Default stack size. + &ThreadWithParamSupport::ThreadMain, + param, // Parameter to ThreadMainStatic + 0x0, // Default creation flags. + &thread_id); // Need a valid pointer for the call to work under Win98. + GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error " << ::GetLastError() << "."; if (thread_handle == NULL) { delete param; } @@ -347,9 +316,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase { private: struct ThreadMainParam { ThreadMainParam(Runnable* runnable, Notification* thread_can_start) - : runnable_(runnable), - thread_can_start_(thread_can_start) { - } + : runnable_(runnable), thread_can_start_(thread_can_start) {} scoped_ptr runnable_; // Does not own. Notification* thread_can_start_; @@ -358,8 +325,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase { static DWORD WINAPI ThreadMain(void* ptr) { // Transfers ownership. scoped_ptr param(static_cast(ptr)); - if (param->thread_can_start_ != NULL) - param->thread_can_start_->WaitForNotification(); + if (param->thread_can_start_ != NULL) param->thread_can_start_->WaitForNotification(); param->runnable_->Run(); return 0; } @@ -372,15 +338,10 @@ class ThreadWithParamSupport : public ThreadWithParamBase { } // namespace -ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, - Notification* thread_can_start) - : thread_(ThreadWithParamSupport::CreateThread(runnable, - thread_can_start)) { -} +ThreadWithParamBase::ThreadWithParamBase(Runnable* runnable, Notification* thread_can_start) + : thread_(ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {} -ThreadWithParamBase::~ThreadWithParamBase() { - Join(); -} +ThreadWithParamBase::~ThreadWithParamBase() { Join(); } void ThreadWithParamBase::Join() { GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) @@ -395,50 +356,38 @@ class ThreadLocalRegistryImpl { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. - static ThreadLocalValueHolderBase* GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance) { + static ThreadLocalValueHolderBase* GetValueOnCurrentThread(const ThreadLocalBase* thread_local_instance) { DWORD current_thread = ::GetCurrentThreadId(); MutexLock lock(&mutex_); - ThreadIdToThreadLocals* const thread_to_thread_locals = - GetThreadLocalsMapLocked(); - ThreadIdToThreadLocals::iterator thread_local_pos = - thread_to_thread_locals->find(current_thread); + ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); + ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(current_thread); if (thread_local_pos == thread_to_thread_locals->end()) { - thread_local_pos = thread_to_thread_locals->insert( - std::make_pair(current_thread, ThreadLocalValues())).first; + thread_local_pos = thread_to_thread_locals->insert(std::make_pair(current_thread, ThreadLocalValues())).first; StartWatcherThreadFor(current_thread); } ThreadLocalValues& thread_local_values = thread_local_pos->second; - ThreadLocalValues::iterator value_pos = - thread_local_values.find(thread_local_instance); + ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos == thread_local_values.end()) { value_pos = thread_local_values - .insert(std::make_pair( - thread_local_instance, - linked_ptr( - thread_local_instance->NewValueForCurrentThread()))) + .insert(std::make_pair(thread_local_instance, linked_ptr( + thread_local_instance->NewValueForCurrentThread()))) .first; } return value_pos->second.get(); } - static void OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance) { + static void OnThreadLocalDestroyed(const ThreadLocalBase* thread_local_instance) { std::vector > value_holders; // Clean up the ThreadLocalValues data structure while holding the lock, but // defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); - ThreadIdToThreadLocals* const thread_to_thread_locals = - GetThreadLocalsMapLocked(); - for (ThreadIdToThreadLocals::iterator it = - thread_to_thread_locals->begin(); - it != thread_to_thread_locals->end(); - ++it) { + ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); + for (ThreadIdToThreadLocals::iterator it = thread_to_thread_locals->begin(); it != thread_to_thread_locals->end(); + ++it) { ThreadLocalValues& thread_local_values = it->second; - ThreadLocalValues::iterator value_pos = - thread_local_values.find(thread_local_instance); + ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos != thread_local_values.end()) { value_holders.push_back(value_pos->second); thread_local_values.erase(value_pos); @@ -458,16 +407,12 @@ class ThreadLocalRegistryImpl { // lock, but defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); - ThreadIdToThreadLocals* const thread_to_thread_locals = - GetThreadLocalsMapLocked(); - ThreadIdToThreadLocals::iterator thread_local_pos = - thread_to_thread_locals->find(thread_id); + ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); + ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(thread_id); if (thread_local_pos != thread_to_thread_locals->end()) { ThreadLocalValues& thread_local_values = thread_local_pos->second; - for (ThreadLocalValues::iterator value_pos = - thread_local_values.begin(); - value_pos != thread_local_values.end(); - ++value_pos) { + for (ThreadLocalValues::iterator value_pos = thread_local_values.begin(); + value_pos != thread_local_values.end(); ++value_pos) { value_holders.push_back(value_pos->second); } thread_to_thread_locals->erase(thread_local_pos); @@ -479,8 +424,7 @@ class ThreadLocalRegistryImpl { private: // In a particular thread, maps a ThreadLocal object to its value. - typedef std::map > ThreadLocalValues; + typedef std::map > ThreadLocalValues; // Stores all ThreadIdToThreadLocals having values in a thread, indexed by // thread's ID. typedef std::map ThreadIdToThreadLocals; @@ -492,25 +436,20 @@ class ThreadLocalRegistryImpl { static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by // watcher_thread in WatcherThreadFunc. - HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, - FALSE, - thread_id); + HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != NULL); // We need to to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. DWORD watcher_thread_id; - HANDLE watcher_thread = ::CreateThread( - NULL, // Default security. - 0, // Default stack size - &ThreadLocalRegistryImpl::WatcherThreadFunc, - reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)), - CREATE_SUSPENDED, - &watcher_thread_id); + HANDLE watcher_thread = ::CreateThread(NULL, // Default security. + 0, // Default stack size + &ThreadLocalRegistryImpl::WatcherThreadFunc, + reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)), + CREATE_SUSPENDED, &watcher_thread_id); GTEST_CHECK_(watcher_thread != NULL); // Give the watcher thread the same priority as ours to avoid being // blocked by it. - ::SetThreadPriority(watcher_thread, - ::GetThreadPriority(::GetCurrentThread())); + ::SetThreadPriority(watcher_thread, ::GetThreadPriority(::GetCurrentThread())); ::ResumeThread(watcher_thread); ::CloseHandle(watcher_thread); } @@ -518,10 +457,8 @@ class ThreadLocalRegistryImpl { // Monitors exit from a given thread and notifies those // ThreadIdToThreadLocals about thread termination. static DWORD WINAPI WatcherThreadFunc(LPVOID param) { - const ThreadIdAndHandle* tah = - reinterpret_cast(param); - GTEST_CHECK_( - ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); + const ThreadIdAndHandle* tah = reinterpret_cast(param); + GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); OnThreadExit(tah->first); ::CloseHandle(tah->second); delete tah; @@ -544,14 +481,11 @@ class ThreadLocalRegistryImpl { Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); -ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance) { - return ThreadLocalRegistryImpl::GetValueOnCurrentThread( - thread_local_instance); +ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(const ThreadLocalBase* thread_local_instance) { + return ThreadLocalRegistryImpl::GetValueOnCurrentThread(thread_local_instance); } -void ThreadLocalRegistry::OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance) { +void ThreadLocalRegistry::OnThreadLocalDestroyed(const ThreadLocalBase* thread_local_instance) { ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); } @@ -613,9 +547,7 @@ void RE::Init(const char* regex) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; } - EXPECT_TRUE(is_valid_) - << "Regular expression \"" << regex - << "\" is not a valid POSIX Extended regular expression."; + EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex << "\" is not a valid POSIX Extended regular expression."; delete[] full_pattern; } @@ -624,45 +556,49 @@ void RE::Init(const char* regex) { // Returns true iff ch appears anywhere in str (excluding the // terminating '\0' character). -bool IsInSet(char ch, const char* str) { - return ch != '\0' && strchr(str, ch) != NULL; -} +bool IsInSet(char ch, const char* str) { return ch != '\0' && strchr(str, ch) != NULL; } // Returns true iff ch belongs to the given classification. Unlike // similar functions in , these aren't affected by the // current locale. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } -bool IsAsciiPunct(char ch) { - return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); -} +bool IsAsciiPunct(char ch) { return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); } bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWordChar(char ch) { - return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || - ('0' <= ch && ch <= '9') || ch == '_'; + return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true iff "\\c" is a supported escape sequence. -bool IsValidEscape(char c) { - return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); -} +bool IsValidEscape(char c) { return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } // Returns true iff the given atom (specified by escaped and pattern) // matches ch. The result is undefined if the atom is invalid. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { - case 'd': return IsAsciiDigit(ch); - case 'D': return !IsAsciiDigit(ch); - case 'f': return ch == '\f'; - case 'n': return ch == '\n'; - case 'r': return ch == '\r'; - case 's': return IsAsciiWhiteSpace(ch); - case 'S': return !IsAsciiWhiteSpace(ch); - case 't': return ch == '\t'; - case 'v': return ch == '\v'; - case 'w': return IsAsciiWordChar(ch); - case 'W': return !IsAsciiWordChar(ch); + case 'd': + return IsAsciiDigit(ch); + case 'D': + return !IsAsciiDigit(ch); + case 'f': + return ch == '\f'; + case 'n': + return ch == '\n'; + case 'r': + return ch == '\r'; + case 's': + return IsAsciiWhiteSpace(ch); + case 'S': + return !IsAsciiWhiteSpace(ch); + case 't': + return ch == '\t'; + case 'v': + return ch == '\v'; + case 'w': + return IsAsciiWordChar(ch); + case 'W': + return !IsAsciiWordChar(ch); } return IsAsciiPunct(pattern_char) && pattern_char == ch; } @@ -672,8 +608,8 @@ bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { // Helper function used by ValidateRegex() to format error messages. std::string FormatRegexSyntaxError(const char* regex, int index) { - return (Message() << "Syntax error at index " << index - << " in simple regular expression \"" << regex << "\": ").GetString(); + return (Message() << "Syntax error at index " << index << " in simple regular expression \"" << regex << "\": ") + .GetString(); } // Generates non-fatal failures and returns false if regex is invalid; @@ -695,14 +631,12 @@ bool ValidateRegex(const char* regex) { if (regex[i] == '\\') { // An escape sequence i++; if (regex[i] == '\0') { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) - << "'\\' cannot appear at the end."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "'\\' cannot appear at the end."; return false; } if (!IsValidEscape(regex[i])) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) - << "invalid escape sequence \"\\" << regex[i] << "\"."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "invalid escape sequence \"\\" << regex[i] << "\"."; is_valid = false; } prev_repeatable = true; @@ -710,20 +644,16 @@ bool ValidateRegex(const char* regex) { const char ch = regex[i]; if (ch == '^' && i > 0) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'^' can only appear at the beginning."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'^' can only appear at the beginning."; is_valid = false; } else if (ch == '$' && regex[i + 1] != '\0') { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'$' can only appear at the end."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'$' can only appear at the end."; is_valid = false; } else if (IsInSet(ch, "()[]{}|")) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' is unsupported."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' is unsupported."; is_valid = false; } else if (IsRepeat(ch) && !prev_repeatable) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' can only follow a repeatable token."; + ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' can only follow a repeatable token."; is_valid = false; } @@ -741,12 +671,9 @@ bool ValidateRegex(const char* regex) { // characters to be indexable by size_t, in which case the test will // probably time out anyway. We are fine with this limitation as // std::string has it too. -bool MatchRepetitionAndRegexAtHead( - bool escaped, char c, char repeat, const char* regex, - const char* str) { +bool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat, const char* regex, const char* str) { const size_t min_count = (repeat == '+') ? 1 : 0; - const size_t max_count = (repeat == '?') ? 1 : - static_cast(-1) - 1; + const size_t max_count = (repeat == '?') ? 1 : static_cast(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. @@ -759,8 +686,7 @@ bool MatchRepetitionAndRegexAtHead( // greedy match. return true; } - if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) - return false; + if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false; } return false; } @@ -774,25 +700,21 @@ bool MatchRegexAtHead(const char* regex, const char* str) { // "$" only matches the end of a string. Note that regex being // valid guarantees that there's nothing after "$" in it. - if (*regex == '$') - return *str == '\0'; + if (*regex == '$') return *str == '\0'; // Is the first thing in regex an escape sequence? const bool escaped = *regex == '\\'; - if (escaped) - ++regex; + if (escaped) ++regex; if (IsRepeat(regex[1])) { // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // here's an indirect recursion. It terminates as the regex gets // shorter in each recursion. - return MatchRepetitionAndRegexAtHead( - escaped, regex[0], regex[1], regex + 2, str); + return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2, str); } else { // regex isn't empty, isn't "$", and doesn't start with a // repetition. We match the first atom of regex with the first // character of str and recurse. - return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && - MatchRegexAtHead(regex + 1, str + 1); + return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && MatchRegexAtHead(regex + 1, str + 1); } } @@ -805,16 +727,13 @@ bool MatchRegexAtHead(const char* regex, const char* str) { // exponential with respect to the regex length + the string length, // but usually it's must faster (often close to linear). bool MatchRegexAnywhere(const char* regex, const char* str) { - if (regex == NULL || str == NULL) - return false; + if (regex == NULL || str == NULL) return false; - if (*regex == '^') - return MatchRegexAtHead(regex + 1, str); + if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { - if (MatchRegexAtHead(regex, str)) - return true; + if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } @@ -827,15 +746,11 @@ RE::~RE() { } // Returns true iff regular expression re matches the entire str. -bool RE::FullMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); -} +bool RE::FullMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); } // Returns true iff regular expression re matches a substring of str // (including str itself). -bool RE::PartialMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); -} +bool RE::PartialMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); } // Initializes an RE from its string representation. void RE::Init(const char* regex) { @@ -857,16 +772,14 @@ void RE::Init(const char* regex) { char* buffer = static_cast(malloc(len + 3)); full_pattern_ = buffer; - if (*regex != '^') - *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. + if (*regex != '^') *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. // We don't use snprintf or strncpy, as they trigger a warning when // compiled with VC++ 8.0. memcpy(buffer, regex, len); buffer += len; - if (len == 0 || regex[len - 1] != '$') - *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. + if (len == 0 || regex[len - 1] != '$') *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. *buffer = '\0'; } @@ -895,8 +808,7 @@ GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { // FormatFileLocation in order to contrast the two functions. // Note that FormatCompilerIndependentFileLocation() does NOT append colon // to the file location it produces, unlike FormatFileLocation(). -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( - const char* file, int line) { +GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line) { const std::string file_name(file == NULL ? kUnknownFile : file); if (line < 0) @@ -905,14 +817,12 @@ GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( return file_name + ":" + StreamableToString(line); } -GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) - : severity_(severity) { - const char* const marker = - severity == GTEST_INFO ? "[ INFO ]" : - severity == GTEST_WARNING ? "[WARNING]" : - severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; - GetStream() << ::std::endl << marker << " " - << FormatFileLocation(file, line).c_str() << ": "; +GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { + const char* const marker = severity == GTEST_INFO ? "[ INFO ]" + : severity == GTEST_WARNING ? "[WARNING]" + : severity == GTEST_ERROR ? "[ ERROR ]" + : "[ FATAL ]"; + GetStream() << ::std::endl << marker << " " << FormatFileLocation(file, line).c_str() << ": "; } // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. @@ -934,27 +844,24 @@ class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { -# if GTEST_OS_WINDOWS - char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT - char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT +# if GTEST_OS_WINDOWS + char temp_dir_path[MAX_PATH + 1] = {'\0'}; // NOLINT + char temp_file_path[MAX_PATH + 1] = {'\0'}; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); - const UINT success = ::GetTempFileNameA(temp_dir_path, - "gtest_redir", + const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); - GTEST_CHECK_(success != 0) - << "Unable to create a temporary file in " << temp_dir_path; + GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); - GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " - << temp_file_path; + GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; -# else +# else // There's no guarantee that a test has write access to the current // directory, so we create the temporary file in the /tmp directory // instead. We use /tmp on most systems, and /sdcard on Android. // That's because Android doesn't have /tmp. -# if GTEST_OS_LINUX_ANDROID +# if GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, @@ -970,20 +877,18 @@ class CapturedStream { // other OEM-customized locations. Never rely on these, and always // use /sdcard. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; -# else +# else char name_template[] = "/tmp/captured_stream.XXXXXX"; -# endif // GTEST_OS_LINUX_ANDROID +# endif // GTEST_OS_LINUX_ANDROID const int captured_fd = mkstemp(name_template); filename_ = name_template; -# endif // GTEST_OS_WINDOWS +# endif // GTEST_OS_WINDOWS fflush(NULL); dup2(captured_fd, fd_); close(captured_fd); } - ~CapturedStream() { - remove(filename_.c_str()); - } + ~CapturedStream() { remove(filename_.c_str()); } std::string GetCapturedString() { if (uncaptured_fd_ != -1) { @@ -1017,8 +922,7 @@ static CapturedStream* g_captured_stdout = NULL; // Starts capturing an output stream (stdout/stderr). void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { if (*stream != NULL) { - GTEST_LOG_(FATAL) << "Only one " << stream_name - << " capturer can exist at a time."; + GTEST_LOG_(FATAL) << "Only one " << stream_name << " capturer can exist at a time."; } *stream = new CapturedStream(fd); } @@ -1034,24 +938,16 @@ std::string GetCapturedStream(CapturedStream** captured_stream) { } // Starts capturing stdout. -void CaptureStdout() { - CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); -} +void CaptureStdout() { CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); } // Starts capturing stderr. -void CaptureStderr() { - CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); -} +void CaptureStderr() { CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); } // Stops capturing stdout and returns the captured string. -std::string GetCapturedStdout() { - return GetCapturedStream(&g_captured_stdout); -} +std::string GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } // Stops capturing stderr and returns the captured string. -std::string GetCapturedStderr() { - return GetCapturedStream(&g_captured_stderr); -} +std::string GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } #endif // GTEST_HAS_STREAM_REDIRECTION @@ -1090,7 +986,7 @@ std::string ReadEntireFile(FILE* file) { // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); + bytes_last_read = fread(buffer + bytes_read, 1, file_size - bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); @@ -1102,12 +998,10 @@ std::string ReadEntireFile(FILE* file) { #if GTEST_HAS_DEATH_TEST -static const ::std::vector* g_injected_test_argvs = - NULL; // Owned. +static const ::std::vector* g_injected_test_argvs = NULL; // Owned. void SetInjectableArgvs(const ::std::vector* argvs) { - if (g_injected_test_argvs != argvs) - delete g_injected_test_argvs; + if (g_injected_test_argvs != argvs) delete g_injected_test_argvs; g_injected_test_argvs = argvs; } @@ -1132,8 +1026,7 @@ void Abort() { // given flag. For example, FlagToEnvVar("foo") will return // "GTEST_FOO" in the open-source version. static std::string FlagToEnvVar(const char* flag) { - const std::string full_flag = - (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); + const std::string full_flag = (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); Message env_var; for (size_t i = 0; i != full_flag.length(); i++) { @@ -1155,8 +1048,7 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) { if (*end != '\0') { // No - an invalid character was encountered. Message msg; - msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" + msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value \"" << str << "\".\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); @@ -1170,10 +1062,9 @@ bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an Int32. - ) { + ) { Message msg; - msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" + msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value " << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); @@ -1194,8 +1085,7 @@ bool BoolFromGTestEnv(const char* flag, bool default_value) { #endif // defined(GTEST_GET_BOOL_FROM_ENV_) const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); - return string_value == NULL ? - default_value : strcmp(string_value, "0") != 0; + return string_value == NULL ? default_value : strcmp(string_value, "0") != 0; } // Reads and returns a 32-bit integer stored in the environment @@ -1213,10 +1103,8 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { } Int32 result = default_value; - if (!ParseInt32(Message() << "Environment variable " << env_var, - string_value, &result)) { - printf("The default value %s is used.\n", - (Message() << default_value).GetString().c_str()); + if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, &result)) { + printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); return default_value; } diff --git a/src/net/test/gtest/src/gtest-printers.cc b/src/net/test/gtest/src/gtest-printers.cc index a2df412f8a..db6e94247d 100644 --- a/src/net/test/gtest/src/gtest-printers.cc +++ b/src/net/test/gtest/src/gtest-printers.cc @@ -60,8 +60,7 @@ using ::std::ostream; GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, - size_t count, ostream* os) { +void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, size_t count, ostream* os) { char text[5] = ""; for (size_t i = 0; i != count; i++) { const size_t j = start + i; @@ -79,8 +78,7 @@ void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, } // Prints the bytes in the given value to the given ostream. -void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, - ostream* os) { +void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, ostream* os) { // Tells the user how big the object is. *os << count << "-byte object <"; @@ -96,7 +94,7 @@ void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); *os << " ... "; // Rounds up to 2-byte boundary. - const size_t resume_pos = (count - kChunkSize + 1)/2*2; + const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2; PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); } *os << ">"; @@ -111,8 +109,7 @@ namespace internal2 { // uses the << operator and thus is easier done outside of the // ::testing::internal namespace, which contains a << operator that // sometimes conflicts with the one in STL. -void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, - ostream* os) { +void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ostream* os) { PrintBytesInObjectToImpl(obj_bytes, count, os); } @@ -125,18 +122,12 @@ namespace internal { // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as a hexidecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). -enum CharFormat { - kAsIs, - kHexEscape, - kSpecialEscape -}; +enum CharFormat { kAsIs, kHexEscape, kSpecialEscape }; // Returns true if c is a printable ASCII character. We test the // value of c directly instead of calling isprint(), which is buggy on // Windows Mobile. -inline bool IsPrintableAscii(wchar_t c) { - return 0x20 <= c && c <= 0x7E; -} +inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; } // Prints a wide or narrow char c as a character literal without the // quotes, escaping it when necessary; returns how c was formatted. @@ -205,8 +196,7 @@ static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { - return PrintAsStringLiteralTo( - static_cast(static_cast(c)), os); + return PrintAsStringLiteralTo(static_cast(static_cast(c)), os); } // Prints a wide or narrow character c and its code. '\0' is printed @@ -223,8 +213,7 @@ void PrintCharAndCodeTo(Char c, ostream* os) { // To aid user debugging, we also print c's code in decimal, unless // it's 0 (in which case c was printed as '\\0', making the code // obvious). - if (c == 0) - return; + if (c == 0) return; *os << " (" << static_cast(c); // For more convenience, we print c's code again in hexidecimal, @@ -238,29 +227,20 @@ void PrintCharAndCodeTo(Char c, ostream* os) { *os << ")"; } -void PrintTo(unsigned char c, ::std::ostream* os) { - PrintCharAndCodeTo(c, os); -} -void PrintTo(signed char c, ::std::ostream* os) { - PrintCharAndCodeTo(c, os); -} +void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); } +void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); } // Prints a wchar_t as a symbol if it is printable or as its internal // code otherwise and also as its code. L'\0' is printed as "L'\\0'". -void PrintTo(wchar_t wc, ostream* os) { - PrintCharAndCodeTo(wc, os); -} +void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); } // Prints the given array of characters to the ostream. CharType must be either // char or wchar_t. // The array starts at begin, the length is len, it may include '\0' characters // and may not be NUL-terminated. template -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -static void PrintCharsAsStringTo( - const CharType* begin, size_t len, ostream* os) { +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void +PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) { const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; *os << kQuoteBegin; bool is_previous_hex = false; @@ -280,11 +260,8 @@ static void PrintCharsAsStringTo( // Prints a (const) char/wchar_t array of 'len' elements, starting at address // 'begin'. CharType must be either char or wchar_t. template -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -static void UniversalPrintCharArray( - const CharType* begin, size_t len, ostream* os) { +GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void +UniversalPrintCharArray(const CharType* begin, size_t len, ostream* os) { // The code // const char kFoo[] = "foo"; // generates an array of 4, not 3, elements, with the last one being '\0'. @@ -306,15 +283,11 @@ static void UniversalPrintCharArray( } // Prints a (const) char array of 'len' elements, starting at address 'begin'. -void UniversalPrintArray(const char* begin, size_t len, ostream* os) { - UniversalPrintCharArray(begin, len, os); -} +void UniversalPrintArray(const char* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints a (const) wchar_t array of 'len' elements, starting at address // 'begin'. -void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { - UniversalPrintCharArray(begin, len, os); -} +void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints the given C string to the ostream. void PrintTo(const char* s, ostream* os) { @@ -346,26 +319,18 @@ void PrintTo(const wchar_t* s, ostream* os) { // Prints a ::string object. #if GTEST_HAS_GLOBAL_STRING -void PrintStringTo(const ::string& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} +void PrintStringTo(const ::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_STRING -void PrintStringTo(const ::std::string& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} +void PrintStringTo(const ::std::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } // Prints a ::wstring object. #if GTEST_HAS_GLOBAL_WSTRING -void PrintWideStringTo(const ::wstring& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} +void PrintWideStringTo(const ::wstring& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING -void PrintWideStringTo(const ::std::wstring& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} +void PrintWideStringTo(const ::std::wstring& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_STD_WSTRING } // namespace internal diff --git a/src/net/test/gtest/src/gtest-test-part.cc b/src/net/test/gtest/src/gtest-test-part.cc index fb0e35425e..05207ab858 100644 --- a/src/net/test/gtest/src/gtest-test-part.cc +++ b/src/net/test/gtest/src/gtest-test-part.cc @@ -50,24 +50,21 @@ using internal::GetUnitTestImpl; // in it. std::string TestPartResult::ExtractSummary(const char* message) { const char* const stack_trace = strstr(message, internal::kStackTraceMarker); - return stack_trace == NULL ? message : - std::string(message, stack_trace); + return stack_trace == NULL ? message : std::string(message, stack_trace); } // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { - return os - << result.file_name() << ":" << result.line_number() << ": " - << (result.type() == TestPartResult::kSuccess ? "Success" : - result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : - "Non-fatal failure") << ":\n" - << result.message() << std::endl; + return os << result.file_name() << ":" << result.line_number() << ": " + << (result.type() == TestPartResult::kSuccess ? "Success" + : result.type() == TestPartResult::kFatalFailure ? "Fatal failure" + : "Non-fatal failure") + << ":\n" + << result.message() << std::endl; } // Appends a TestPartResult to the array. -void TestPartResultArray::Append(const TestPartResult& result) { - array_.push_back(result); -} +void TestPartResultArray::Append(const TestPartResult& result) { array_.push_back(result); } // Returns the TestPartResult at the given index (0-based). const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { @@ -80,28 +77,22 @@ const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { } // Returns the number of TestPartResult objects in the array. -int TestPartResultArray::size() const { - return static_cast(array_.size()); -} +int TestPartResultArray::size() const { return static_cast(array_.size()); } namespace internal { HasNewFatalFailureHelper::HasNewFatalFailureHelper() : has_new_fatal_failure_(false), - original_reporter_(GetUnitTestImpl()-> - GetTestPartResultReporterForCurrentThread()) { + original_reporter_(GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); } HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { - GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( - original_reporter_); + GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(original_reporter_); } -void HasNewFatalFailureHelper::ReportTestPartResult( - const TestPartResult& result) { - if (result.fatally_failed()) - has_new_fatal_failure_ = true; +void HasNewFatalFailureHelper::ReportTestPartResult(const TestPartResult& result) { + if (result.fatally_failed()) has_new_fatal_failure_ = true; original_reporter_->ReportTestPartResult(result); } diff --git a/src/net/test/gtest/src/gtest-typed-test.cc b/src/net/test/gtest/src/gtest-typed-test.cc index df1eef4754..9d8c9e43ed 100644 --- a/src/net/test/gtest/src/gtest-typed-test.cc +++ b/src/net/test/gtest/src/gtest-typed-test.cc @@ -40,8 +40,7 @@ namespace internal { // Skips to the first non-space char in str. Returns an empty string if str // contains only whitespace characters. static const char* SkipSpaces(const char* str) { - while (IsSpace(*str)) - str++; + while (IsSpace(*str)) str++; return str; } @@ -57,8 +56,7 @@ static std::vector SplitIntoTestNames(const char* src) { // Verifies that registered_tests match the test names in // registered_tests_; returns registered_tests if successful, or // aborts the program otherwise. -const char* TypedTestCasePState::VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests) { +const char* TypedTestCasePState::VerifyRegisteredTestNames(const char* file, int line, const char* registered_tests) { typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; @@ -67,8 +65,7 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames( Message errors; std::set tests; - for (std::vector::const_iterator name_it = name_vec.begin(); - name_it != name_vec.end(); ++name_it) { + for (std::vector::const_iterator name_it = name_vec.begin(); name_it != name_vec.end(); ++name_it) { const std::string& name = *name_it; if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; @@ -76,9 +73,7 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames( } bool found = false; - for (RegisteredTestIter it = registered_tests_.begin(); - it != registered_tests_.end(); - ++it) { + for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (name == it->first) { found = true; break; @@ -88,14 +83,11 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames( if (found) { tests.insert(name); } else { - errors << "No test named " << name - << " can be found in this test case.\n"; + errors << "No test named " << name << " can be found in this test case.\n"; } } - for (RegisteredTestIter it = registered_tests_.begin(); - it != registered_tests_.end(); - ++it) { + for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } @@ -103,8 +95,7 @@ const char* TypedTestCasePState::VerifyRegisteredTestNames( const std::string& errors_str = errors.GetString(); if (errors_str != "") { - fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), - errors_str.c_str()); + fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); posix::Abort(); } diff --git a/src/net/test/gtest/src/gtest.cc b/src/net/test/gtest/src/gtest.cc index d882ab2e36..cd00c50d4e 100644 --- a/src/net/test/gtest/src/gtest.cc +++ b/src/net/test/gtest/src/gtest.cc @@ -32,8 +32,8 @@ // The Google C++ Testing Framework (Google Test) #include "gtest/gtest.h" -#include "gtest/internal/custom/gtest.h" #include "gtest/gtest-spi.h" +#include "gtest/internal/custom/gtest.h" #include #include @@ -57,80 +57,80 @@ // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). -# define GTEST_HAS_GETTIMEOFDAY_ 1 +# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT -# include // NOLINT -# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT // Declares vsnprintf(). This header is not available on Windows. -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include #elif GTEST_OS_SYMBIAN -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT #elif GTEST_OS_ZOS -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT // On z/OS we additionally need strings.h for strcasecmp. -# include // NOLINT +# include // NOLINT #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. -# include // NOLINT -# undef min +# include // NOLINT +# undef min #elif GTEST_OS_WINDOWS // We are on Windows proper. -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT -# if GTEST_OS_WINDOWS_MINGW +# if GTEST_OS_WINDOWS_MINGW // MinGW has gettimeofday() but not _ftime64(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). // TODO(kenton@google.com): There are other ways to get the time on // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW // supports these. consider using them instead. -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT -# endif // GTEST_OS_WINDOWS_MINGW +# define GTEST_HAS_GETTIMEOFDAY_ 1 +# include // NOLINT +# endif // GTEST_OS_WINDOWS_MINGW // cpplint thinks that the header is already included, so we want to // silence it. -# include // NOLINT -# undef min +# include // NOLINT +# undef min #else // Assume other platforms have gettimeofday(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). -# define GTEST_HAS_GETTIMEOFDAY_ 1 +# define GTEST_HAS_GETTIMEOFDAY_ 1 // cpplint thinks that the header is already included, so we want to // silence it. -# include // NOLINT -# include // NOLINT +# include // NOLINT +# include // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS -# include +# include #endif #if GTEST_CAN_STREAM_RESULTS_ -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT +# include // NOLINT #endif // Indicates that this translation unit is part of Google Test's @@ -143,7 +143,7 @@ #undef GTEST_IMPLEMENTATION_ #if GTEST_OS_WINDOWS -# define vsnprintf _vsnprintf +# define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS namespace testing { @@ -199,108 +199,76 @@ static const char* GetDefaultFilter() { return kUniversalFilter; } -GTEST_DEFINE_bool_( - also_run_disabled_tests, - internal::BoolFromGTestEnv("also_run_disabled_tests", false), - "Run disabled tests too, in addition to the tests normally being run."); - -GTEST_DEFINE_bool_( - break_on_failure, - internal::BoolFromGTestEnv("break_on_failure", false), - "True iff a failed assertion should be a debugger break-point."); - -GTEST_DEFINE_bool_( - catch_exceptions, - internal::BoolFromGTestEnv("catch_exceptions", true), - "True iff " GTEST_NAME_ - " should catch exceptions and treat them as test failures."); - -GTEST_DEFINE_string_( - color, - internal::StringFromGTestEnv("color", "auto"), - "Whether to use colors in the output. Valid values: yes, no, " - "and auto. 'auto' means to use colors if the output is " - "being sent to a terminal and the TERM environment variable " - "is set to a terminal type that supports colors."); - -GTEST_DEFINE_string_( - filter, - internal::StringFromGTestEnv("filter", GetDefaultFilter()), - "A colon-separated list of glob (not regex) patterns " - "for filtering the tests to run, optionally followed by a " - "'-' and a : separated list of negative patterns (tests to " - "exclude). A test is run if it matches one of the positive " - "patterns and does not match any of the negative patterns."); - -GTEST_DEFINE_bool_(list_tests, false, - "List all tests without running them."); - -GTEST_DEFINE_string_( - output, - internal::StringFromGTestEnv("output", ""), - "A format (currently must be \"xml\"), optionally followed " - "by a colon and an output file name or directory. A directory " - "is indicated by a trailing pathname separator. " - "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " - "If a directory is specified, output files will be created " - "within that directory, with file-names based on the test " - "executable's name and, if necessary, made unique by adding " - "digits."); - -GTEST_DEFINE_bool_( - print_time, - internal::BoolFromGTestEnv("print_time", true), - "True iff " GTEST_NAME_ - " should display elapsed time in text output."); - -GTEST_DEFINE_int32_( - random_seed, - internal::Int32FromGTestEnv("random_seed", 0), - "Random number seed to use when shuffling test orders. Must be in range " - "[1, 99999], or 0 to use a seed based on the current time."); - -GTEST_DEFINE_int32_( - repeat, - internal::Int32FromGTestEnv("repeat", 1), - "How many times to repeat each test. Specify a negative number " - "for repeating forever. Useful for shaking out flaky tests."); - -GTEST_DEFINE_bool_( - show_internal_stack_frames, false, - "True iff " GTEST_NAME_ " should include internal stack frames when " - "printing test failure stack traces."); - -GTEST_DEFINE_bool_( - shuffle, - internal::BoolFromGTestEnv("shuffle", false), - "True iff " GTEST_NAME_ - " should randomize tests' order on every run."); - -GTEST_DEFINE_int32_( - stack_trace_depth, - internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), - "The maximum number of stack frames to print when an " - "assertion fails. The valid range is 0 through 100, inclusive."); - -GTEST_DEFINE_string_( - stream_result_to, - internal::StringFromGTestEnv("stream_result_to", ""), - "This flag specifies the host name and the port number on which to stream " - "test results. Example: \"localhost:555\". The flag is effective only on " - "Linux."); - -GTEST_DEFINE_bool_( - throw_on_failure, - internal::BoolFromGTestEnv("throw_on_failure", false), - "When this flag is specified, a failed assertion will throw an exception " - "if exceptions are enabled or exit the program with a non-zero code " - "otherwise."); +GTEST_DEFINE_bool_(also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false), + "Run disabled tests too, in addition to the tests normally being run."); + +GTEST_DEFINE_bool_(break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), + "True iff a failed assertion should be a debugger break-point."); + +GTEST_DEFINE_bool_(catch_exceptions, internal::BoolFromGTestEnv("catch_exceptions", true), + "True iff " GTEST_NAME_ " should catch exceptions and treat them as test failures."); + +GTEST_DEFINE_string_(color, internal::StringFromGTestEnv("color", "auto"), + "Whether to use colors in the output. Valid values: yes, no, " + "and auto. 'auto' means to use colors if the output is " + "being sent to a terminal and the TERM environment variable " + "is set to a terminal type that supports colors."); + +GTEST_DEFINE_string_(filter, internal::StringFromGTestEnv("filter", GetDefaultFilter()), + "A colon-separated list of glob (not regex) patterns " + "for filtering the tests to run, optionally followed by a " + "'-' and a : separated list of negative patterns (tests to " + "exclude). A test is run if it matches one of the positive " + "patterns and does not match any of the negative patterns."); + +GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); + +GTEST_DEFINE_string_(output, internal::StringFromGTestEnv("output", ""), + "A format (currently must be \"xml\"), optionally followed " + "by a colon and an output file name or directory. A directory " + "is indicated by a trailing pathname separator. " + "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " + "If a directory is specified, output files will be created " + "within that directory, with file-names based on the test " + "executable's name and, if necessary, made unique by adding " + "digits."); + +GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true), + "True iff " GTEST_NAME_ " should display elapsed time in text output."); + +GTEST_DEFINE_int32_(random_seed, internal::Int32FromGTestEnv("random_seed", 0), + "Random number seed to use when shuffling test orders. Must be in range " + "[1, 99999], or 0 to use a seed based on the current time."); + +GTEST_DEFINE_int32_(repeat, internal::Int32FromGTestEnv("repeat", 1), + "How many times to repeat each test. Specify a negative number " + "for repeating forever. Useful for shaking out flaky tests."); + +GTEST_DEFINE_bool_(show_internal_stack_frames, false, + "True iff " GTEST_NAME_ + " should include internal stack frames when " + "printing test failure stack traces."); + +GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false), + "True iff " GTEST_NAME_ " should randomize tests' order on every run."); + +GTEST_DEFINE_int32_(stack_trace_depth, internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), + "The maximum number of stack frames to print when an " + "assertion fails. The valid range is 0 through 100, inclusive."); + +GTEST_DEFINE_string_(stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""), + "This flag specifies the host name and the port number on which to stream " + "test results. Example: \"localhost:555\". The flag is effective only on " + "Linux."); + +GTEST_DEFINE_bool_(throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false), + "When this flag is specified, a failed assertion will throw an exception " + "if exceptions are enabled or exit the program with a non-zero code " + "otherwise."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ -GTEST_DEFINE_string_( - flagfile, - internal::StringFromGTestEnv("flagfile", ""), - "This flag specifies the flagfile to read command-line flags from."); +GTEST_DEFINE_string_(flagfile, internal::StringFromGTestEnv("flagfile", ""), + "This flag specifies the flagfile to read command-line flags from."); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ namespace internal { @@ -310,13 +278,11 @@ namespace internal { // than kMaxRange. UInt32 Random::Generate(UInt32 range) { // These constants are the same as are used in glibc's rand(3). - state_ = (1103515245U*state_ + 12345U) % kMaxRange; + state_ = (1103515245U * state_ + 12345U) % kMaxRange; - GTEST_CHECK_(range > 0) - << "Cannot generate a number in the range [0, 0)."; - GTEST_CHECK_(range <= kMaxRange) - << "Generation of a number in [0, " << range << ") was requested, " - << "but this can only generate numbers in [0, " << kMaxRange << ")."; + GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; + GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " + << "but this can only generate numbers in [0, " << kMaxRange << ")."; // Converting via modulus introduces a bit of downward bias, but // it's simple, and a linear congruential generator isn't too good @@ -332,8 +298,7 @@ static bool GTestIsInitialized() { return GetArgvs().size() > 0; } // Iterates over a vector of TestCases, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. -static int SumOverTestCaseList(const std::vector& case_list, - int (TestCase::*method)() const) { +static int SumOverTestCaseList(const std::vector& case_list, int (TestCase::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); @@ -342,42 +307,28 @@ static int SumOverTestCaseList(const std::vector& case_list, } // Returns true iff the test case passed. -static bool TestCasePassed(const TestCase* test_case) { - return test_case->should_run() && test_case->Passed(); -} +static bool TestCasePassed(const TestCase* test_case) { return test_case->should_run() && test_case->Passed(); } // Returns true iff the test case failed. -static bool TestCaseFailed(const TestCase* test_case) { - return test_case->should_run() && test_case->Failed(); -} +static bool TestCaseFailed(const TestCase* test_case) { return test_case->should_run() && test_case->Failed(); } // Returns true iff test_case contains at least one test that should // run. -static bool ShouldRunTestCase(const TestCase* test_case) { - return test_case->should_run(); -} +static bool ShouldRunTestCase(const TestCase* test_case) { return test_case->should_run(); } // AssertHelper constructor. -AssertHelper::AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message) - : data_(new AssertHelperData(type, file, line, message)) { -} +AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) + : data_(new AssertHelperData(type, file, line, message)) {} -AssertHelper::~AssertHelper() { - delete data_; -} +AssertHelper::~AssertHelper() { delete data_; } // Message assignment, for assertion streaming support. void AssertHelper::operator=(const Message& message) const { - UnitTest::GetInstance()-> - AddTestPartResult(data_->type, data_->file, data_->line, - AppendUserMessage(data_->message, message), - UnitTest::GetInstance()->impl() - ->CurrentOsStackTraceExceptTop(1) - // Skips the stack frame for this function itself. - ); // NOLINT + UnitTest::GetInstance()->AddTestPartResult(data_->type, data_->file, data_->line, + AppendUserMessage(data_->message, message), + UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1) + // Skips the stack frame for this function itself. + ); // NOLINT } // Mutex for linked pointers. @@ -389,7 +340,7 @@ ::std::vector g_argvs; const ::std::vector& GetArgvs() { #if defined(GTEST_CUSTOM_GET_ARGVS_) return GTEST_CUSTOM_GET_ARGVS_(); -#else // defined(GTEST_CUSTOM_GET_ARGVS_) +#else // defined(GTEST_CUSTOM_GET_ARGVS_) return g_argvs; #endif // defined(GTEST_CUSTOM_GET_ARGVS_) } @@ -416,24 +367,20 @@ std::string UnitTestOptions::GetOutputFormat() { if (gtest_output_flag == NULL) return std::string(""); const char* const colon = strchr(gtest_output_flag, ':'); - return (colon == NULL) ? - std::string(gtest_output_flag) : - std::string(gtest_output_flag, colon - gtest_output_flag); + return (colon == NULL) ? std::string(gtest_output_flag) : std::string(gtest_output_flag, colon - gtest_output_flag); } // Returns the name of the requested output file, or the default if none // was explicitly specified. std::string UnitTestOptions::GetAbsolutePathToOutputFile() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); - if (gtest_output_flag == NULL) - return ""; + if (gtest_output_flag == NULL) return ""; const char* const colon = strchr(gtest_output_flag, ':'); if (colon == NULL) - return internal::FilePath::ConcatPaths( - internal::FilePath( - UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(kDefaultOutputFile)).string(); + return internal::FilePath::ConcatPaths(internal::FilePath(UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(kDefaultOutputFile)) + .string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) @@ -441,16 +388,13 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { // path (as its meaning depends on the current drive), yet the // following logic for turning it into an absolute path is wrong. // Fix it. - output_name = internal::FilePath::ConcatPaths( - internal::FilePath(UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(colon + 1)); + output_name = internal::FilePath::ConcatPaths(internal::FilePath(UnitTest::GetInstance()->original_working_dir()), + internal::FilePath(colon + 1)); - if (!output_name.IsDirectory()) - return output_name.string(); + if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( - output_name, internal::GetCurrentExecutableName(), - GetOutputFormat().c_str())); + output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); return result.string(); } @@ -459,8 +403,7 @@ std::string UnitTestOptions::GetAbsolutePathToOutputFile() { // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. -bool UnitTestOptions::PatternMatchesString(const char *pattern, - const char *str) { +bool UnitTestOptions::PatternMatchesString(const char* pattern, const char* str) { switch (*pattern) { case '\0': case ':': // Either ':' or '\0' marks the end of the pattern. @@ -468,17 +411,14 @@ bool UnitTestOptions::PatternMatchesString(const char *pattern, case '?': // Matches any single character. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); case '*': // Matches any string (possibly empty) of characters. - return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || - PatternMatchesString(pattern + 1, str); + return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || PatternMatchesString(pattern + 1, str); default: // Non-special character. Matches itself. - return *pattern == *str && - PatternMatchesString(pattern + 1, str + 1); + return *pattern == *str && PatternMatchesString(pattern + 1, str + 1); } } -bool UnitTestOptions::MatchesFilter( - const std::string& name, const char* filter) { - const char *cur_pattern = filter; +bool UnitTestOptions::MatchesFilter(const std::string& name, const char* filter) { + const char* cur_pattern = filter; for (;;) { if (PatternMatchesString(cur_pattern, name.c_str())) { return true; @@ -499,8 +439,7 @@ bool UnitTestOptions::MatchesFilter( // Returns true iff the user-specified filter matches the test case // name and the test name. -bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, - const std::string &test_name) { +bool UnitTestOptions::FilterMatchesTest(const std::string& test_case_name, const std::string& test_name) { const std::string& full_name = test_case_name + "." + test_name.c_str(); // Split --gtest_filter at '-', if there is one, to separate into @@ -523,8 +462,7 @@ bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, // A filter is a colon-separated list of patterns. It matches a // test if any pattern in it matches the test. - return (MatchesFilter(full_name, positive.c_str()) && - !MatchesFilter(full_name, negative.c_str())); + return (MatchesFilter(full_name, positive.c_str()) && !MatchesFilter(full_name, negative.c_str())); } #if GTEST_HAS_SEH @@ -560,20 +498,17 @@ int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. Intercepts only failures from the current thread. -ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( - TestPartResultArray* result) - : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), - result_(result) { +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(TestPartResultArray* result) + : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) { Init(); } // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. -ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( - InterceptMode intercept_mode, TestPartResultArray* result) - : intercept_mode_(intercept_mode), - result_(result) { +ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, + TestPartResultArray* result) + : intercept_mode_(intercept_mode), result_(result) { Init(); } @@ -601,10 +536,7 @@ ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { // Increments the test part result count and remembers the result. // This method is from the TestPartResultReporterInterface interface. -void ScopedFakeTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { - result_->Append(result); -} +void ScopedFakeTestPartResultReporter::ReportTestPartResult(const TestPartResult& result) { result_->Append(result); } namespace internal { @@ -617,9 +549,7 @@ namespace internal { // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. -TypeId GetTestTypeId() { - return GetTypeId(); -} +TypeId GetTestTypeId() { return GetTypeId(); } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). @@ -628,15 +558,10 @@ extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); // This predicate-formatter checks that 'results' contains a test part // failure of the given type and that the failure message contains the // given substring. -AssertionResult HasOneFailure(const char* /* results_expr */, - const char* /* type_expr */, - const char* /* substr_expr */, - const TestPartResultArray& results, - TestPartResult::Type type, - const string& substr) { - const std::string expected(type == TestPartResult::kFatalFailure ? - "1 fatal failure" : - "1 non-fatal failure"); +AssertionResult HasOneFailure(const char* /* results_expr */, const char* /* type_expr */, + const char* /* substr_expr */, const TestPartResultArray& results, + TestPartResult::Type type, const string& substr) { + const std::string expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" @@ -655,8 +580,7 @@ AssertionResult HasOneFailure(const char* /* results_expr */, } if (strstr(r.message(), substr.c_str()) == NULL) { - return AssertionFailure() << "Expected: " << expected << " containing \"" - << substr << "\"\n" + return AssertionFailure() << "Expected: " << expected << " containing \"" << substr << "\"\n" << " Actual:\n" << r; } @@ -667,85 +591,65 @@ AssertionResult HasOneFailure(const char* /* results_expr */, // The constructor of SingleFailureChecker remembers where to look up // test part results, what type of failure we expect, and what // substring the failure message should contain. -SingleFailureChecker:: SingleFailureChecker( - const TestPartResultArray* results, - TestPartResult::Type type, - const string& substr) - : results_(results), - type_(type), - substr_(substr) {} +SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, + const string& substr) + : results_(results), type_(type), substr_(substr) {} // The destructor of SingleFailureChecker verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. -SingleFailureChecker::~SingleFailureChecker() { - EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); -} +SingleFailureChecker::~SingleFailureChecker() { EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); } -DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} +DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test) + : unit_test_(unit_test) {} -void DefaultGlobalTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { +void DefaultGlobalTestPartResultReporter::ReportTestPartResult(const TestPartResult& result) { unit_test_->current_test_result()->AddTestPartResult(result); unit_test_->listeners()->repeater()->OnTestPartResult(result); } -DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} +DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test) + : unit_test_(unit_test) {} -void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { +void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(const TestPartResult& result) { unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); } // Returns the global test part result reporter. -TestPartResultReporterInterface* -UnitTestImpl::GetGlobalTestPartResultReporter() { +TestPartResultReporterInterface* UnitTestImpl::GetGlobalTestPartResultReporter() { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); return global_test_part_result_repoter_; } // Sets the global test part result reporter. -void UnitTestImpl::SetGlobalTestPartResultReporter( - TestPartResultReporterInterface* reporter) { +void UnitTestImpl::SetGlobalTestPartResultReporter(TestPartResultReporterInterface* reporter) { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); global_test_part_result_repoter_ = reporter; } // Returns the test part result reporter for the current thread. -TestPartResultReporterInterface* -UnitTestImpl::GetTestPartResultReporterForCurrentThread() { +TestPartResultReporterInterface* UnitTestImpl::GetTestPartResultReporterForCurrentThread() { return per_thread_test_part_result_reporter_.get(); } // Sets the test part result reporter for the current thread. -void UnitTestImpl::SetTestPartResultReporterForCurrentThread( - TestPartResultReporterInterface* reporter) { +void UnitTestImpl::SetTestPartResultReporterForCurrentThread(TestPartResultReporterInterface* reporter) { per_thread_test_part_result_reporter_.set(reporter); } // Gets the number of successful test cases. -int UnitTestImpl::successful_test_case_count() const { - return CountIf(test_cases_, TestCasePassed); -} +int UnitTestImpl::successful_test_case_count() const { return CountIf(test_cases_, TestCasePassed); } // Gets the number of failed test cases. -int UnitTestImpl::failed_test_case_count() const { - return CountIf(test_cases_, TestCaseFailed); -} +int UnitTestImpl::failed_test_case_count() const { return CountIf(test_cases_, TestCaseFailed); } // Gets the number of all test cases. -int UnitTestImpl::total_test_case_count() const { - return static_cast(test_cases_.size()); -} +int UnitTestImpl::total_test_case_count() const { return static_cast(test_cases_.size()); } // Gets the number of all test cases that contain at least one test // that should run. -int UnitTestImpl::test_case_to_run_count() const { - return CountIf(test_cases_, ShouldRunTestCase); -} +int UnitTestImpl::test_case_to_run_count() const { return CountIf(test_cases_, ShouldRunTestCase); } // Gets the number of successful tests. int UnitTestImpl::successful_test_count() const { @@ -753,14 +657,11 @@ int UnitTestImpl::successful_test_count() const { } // Gets the number of failed tests. -int UnitTestImpl::failed_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); -} +int UnitTestImpl::failed_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTestImpl::reportable_disabled_test_count() const { - return SumOverTestCaseList(test_cases_, - &TestCase::reportable_disabled_test_count); + return SumOverTestCaseList(test_cases_, &TestCase::reportable_disabled_test_count); } // Gets the number of disabled tests. @@ -774,14 +675,10 @@ int UnitTestImpl::reportable_test_count() const { } // Gets the number of all tests. -int UnitTestImpl::total_test_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); -} +int UnitTestImpl::total_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); } // Gets the number of tests that should run. -int UnitTestImpl::test_to_run_count() const { - return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); -} +int UnitTestImpl::test_to_run_count() const { return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); } // Returns the current OS stack trace as an std::string. // @@ -794,12 +691,10 @@ int UnitTestImpl::test_to_run_count() const { // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { - return os_stack_trace_getter()->CurrentStackTrace( - static_cast(GTEST_FLAG(stack_trace_depth)), - skip_count + 1 - // Skips the user-specified number of frames plus this function - // itself. - ); // NOLINT + return os_stack_trace_getter()->CurrentStackTrace(static_cast(GTEST_FLAG(stack_trace_depth)), skip_count + 1 + // Skips the user-specified number of frames plus this function + // itself. + ); // NOLINT } // Returns the current time in milliseconds. @@ -807,8 +702,7 @@ TimeInMillis GetTimeInMillis() { #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) // Difference between 1970-01-01 and 1601-01-01 in milliseconds. // http://analogous.blogspot.com/2005/04/epoch.html - const TimeInMillis kJavaEpochToWinFileTimeDelta = - static_cast(116444736UL) * 100000UL; + const TimeInMillis kJavaEpochToWinFileTimeDelta = static_cast(116444736UL) * 100000UL; const DWORD kTenthMicrosInMilliSecond = 10000; SYSTEMTIME now_systime; @@ -820,8 +714,7 @@ TimeInMillis GetTimeInMillis() { if (SystemTimeToFileTime(&now_systime, &now_filetime)) { now_int64.LowPart = now_filetime.dwLowDateTime; now_int64.HighPart = now_filetime.dwHighDateTime; - now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - - kJavaEpochToWinFileTimeDelta; + now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - kJavaEpochToWinFileTimeDelta; return now_int64.QuadPart; } return 0; @@ -842,7 +735,7 @@ TimeInMillis GetTimeInMillis() { gettimeofday(&now, NULL); return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; #else -# error "Don't know how to get the current time on your system." +# error "Don't know how to get the current time on your system." #endif } @@ -858,12 +751,9 @@ TimeInMillis GetTimeInMillis() { LPCWSTR String::AnsiToUtf16(const char* ansi) { if (!ansi) return NULL; const int length = strlen(ansi); - const int unicode_length = - MultiByteToWideChar(CP_ACP, 0, ansi, length, - NULL, 0); + const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, NULL, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; - MultiByteToWideChar(CP_ACP, 0, ansi, length, - unicode, unicode_length); + MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } @@ -872,14 +762,11 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) { // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. -const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { +const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return NULL; - const int ansi_length = - WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, - NULL, 0, NULL, NULL); + const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, NULL, 0, NULL, NULL); char* ansi = new char[ansi_length + 1]; - WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, - ansi, ansi_length, NULL, NULL); + WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, NULL, NULL); ansi[ansi_length] = 0; return ansi; } @@ -891,10 +778,10 @@ const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. -bool String::CStringEquals(const char * lhs, const char * rhs) { - if ( lhs == NULL ) return rhs == NULL; +bool String::CStringEquals(const char* lhs, const char* rhs) { + if (lhs == NULL) return rhs == NULL; - if ( rhs == NULL ) return false; + if (rhs == NULL) return false; return strcmp(lhs, rhs) == 0; } @@ -903,13 +790,11 @@ bool String::CStringEquals(const char * lhs, const char * rhs) { // Converts an array of wide chars to a narrow string using the UTF-8 // encoding, and streams the result to the given Message object. -static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, - Message* msg) { - for (size_t i = 0; i != length; ) { // NOLINT +static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { + for (size_t i = 0; i != length;) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); - while (i != length && wstr[i] != L'\0') - i++; + while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; @@ -919,8 +804,7 @@ static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING -void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest) { +void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { ::std::vector< ::std::string> parsed; ::std::string::size_type pos = 0; while (::testing::internal::AlwaysTrue()) { @@ -951,17 +835,15 @@ Message::Message() : ss_(new ::std::stringstream) { // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. -Message& Message::operator <<(const wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); -} -Message& Message::operator <<(wchar_t* wide_c_str) { +Message& Message::operator<<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } +Message& Message::operator<<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. -Message& Message::operator <<(const ::std::wstring& wstr) { +Message& Message::operator<<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } @@ -970,7 +852,7 @@ Message& Message::operator <<(const ::std::wstring& wstr) { #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. -Message& Message::operator <<(const ::wstring& wstr) { +Message& Message::operator<<(const ::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } @@ -978,17 +860,13 @@ Message& Message::operator <<(const ::wstring& wstr) { // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". -std::string Message::GetString() const { - return internal::StringStreamToString(ss_.get()); -} +std::string Message::GetString() const { return internal::StringStreamToString(ss_.get()); } // AssertionResult constructors. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) : success_(other.success_), - message_(other.message_.get() != NULL ? - new ::std::string(*other.message_) : - static_cast< ::std::string*>(NULL)) { + message_(other.message_.get() != NULL ? new ::std::string(*other.message_) : static_cast< ::std::string*>(NULL)) { } // Swaps two AssertionResults. @@ -1001,36 +879,26 @@ void AssertionResult::swap(AssertionResult& other) { // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult AssertionResult::operator!() const { AssertionResult negation(!success_); - if (message_.get() != NULL) - negation << *message_; + if (message_.get() != NULL) negation << *message_; return negation; } // Makes a successful assertion result. -AssertionResult AssertionSuccess() { - return AssertionResult(true); -} +AssertionResult AssertionSuccess() { return AssertionResult(true); } // Makes a failed assertion result. -AssertionResult AssertionFailure() { - return AssertionResult(false); -} +AssertionResult AssertionFailure() { return AssertionResult(false); } // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << message. -AssertionResult AssertionFailure(const Message& message) { - return AssertionFailure() << message; -} +AssertionResult AssertionFailure(const Message& message) { return AssertionFailure() << message; } namespace internal { namespace edit_distance { -std::vector CalculateOptimalEdits(const std::vector& left, - const std::vector& right) { - std::vector > costs( - left.size() + 1, std::vector(right.size() + 1)); - std::vector > best_move( - left.size() + 1, std::vector(right.size() + 1)); +std::vector CalculateOptimalEdits(const std::vector& left, const std::vector& right) { + std::vector > costs(left.size() + 1, std::vector(right.size() + 1)); + std::vector > best_move(left.size() + 1, std::vector(right.size() + 1)); // Populate for empty right. for (size_t l_i = 0; l_i < costs.size(); ++l_i) { @@ -1101,9 +969,8 @@ class InternalStrings { } // namespace -std::vector CalculateOptimalEdits( - const std::vector& left, - const std::vector& right) { +std::vector CalculateOptimalEdits(const std::vector& left, + const std::vector& right) { std::vector left_ids, right_ids; { InternalStrings intern_table; @@ -1126,11 +993,7 @@ namespace { class Hunk { public: Hunk(size_t left_start, size_t right_start) - : left_start_(left_start), - right_start_(right_start), - adds_(), - removes_(), - common_() {} + : left_start_(left_start), right_start_(right_start), adds_(), removes_(), common_() {} void PushLine(char edit, const char* line) { switch (edit) { @@ -1153,9 +1016,7 @@ class Hunk { void PrintTo(std::ostream* os) { PrintHeader(os); FlushEdits(); - for (std::list >::const_iterator it = - hunk_.begin(); - it != hunk_.end(); ++it) { + for (std::list >::const_iterator it = hunk_.begin(); it != hunk_.end(); ++it) { *os << it->first << it->second << "\n"; } } @@ -1200,8 +1061,7 @@ class Hunk { // 'context' represents the desired unchanged prefix/suffix around the diff. // If two hunks are close enough that their contexts overlap, then they are // joined into one hunk. -std::string CreateUnifiedDiff(const std::vector& left, - const std::vector& right, +std::string CreateUnifiedDiff(const std::vector& left, const std::vector& right, size_t context) { const std::vector edits = CalculateOptimalEdits(left, right); @@ -1309,11 +1169,8 @@ std::vector SplitEscapedString(const std::string& str) { // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string "Ignoring case" will // be inserted into the message. -AssertionResult EqFailure(const char* lhs_expression, - const char* rhs_expression, - const std::string& lhs_value, - const std::string& rhs_value, - bool ignoring_case) { +AssertionResult EqFailure(const char* lhs_expression, const char* rhs_expression, const std::string& lhs_value, + const std::string& rhs_value, bool ignoring_case) { Message msg; msg << " Expected: " << lhs_expression; if (lhs_value != lhs_expression) { @@ -1329,13 +1186,10 @@ AssertionResult EqFailure(const char* lhs_expression, } if (!lhs_value.empty() && !rhs_value.empty()) { - const std::vector lhs_lines = - SplitEscapedString(lhs_value); - const std::vector rhs_lines = - SplitEscapedString(rhs_value); + const std::vector lhs_lines = SplitEscapedString(lhs_value); + const std::vector rhs_lines = SplitEscapedString(rhs_value); if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { - msg << "\nWith diff:\n" - << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); + msg << "\nWith diff:\n" << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); } } @@ -1343,48 +1197,34 @@ AssertionResult EqFailure(const char* lhs_expression, } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value) { +std::string GetBoolAssertionFailureMessage(const AssertionResult& assertion_result, const char* expression_text, + const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; - msg << "Value of: " << expression_text - << "\n Actual: " << actual_predicate_value; - if (actual_message[0] != '\0') - msg << " (" << actual_message << ")"; + msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; + if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } // Helper function for implementing ASSERT_NEAR. -AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error) { +AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, + double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); // TODO(wan): do not print the value of an expression if it's // already a literal. - return AssertionFailure() - << "The difference between " << expr1 << " and " << expr2 - << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" - << expr1 << " evaluates to " << val1 << ",\n" - << expr2 << " evaluates to " << val2 << ", and\n" - << abs_error_expr << " evaluates to " << abs_error << "."; + return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff + << ", which exceeds " << abs_error_expr << ", where\n" + << expr1 << " evaluates to " << val1 << ",\n" + << expr2 << " evaluates to " << val2 << ", and\n" + << abs_error_expr << " evaluates to " << abs_error << "."; } - // Helper template for implementing FloatLE() and DoubleLE(). template -AssertionResult FloatingPointLE(const char* expr1, - const char* expr2, - RawType val1, - RawType val2) { +AssertionResult FloatingPointLE(const char* expr1, const char* expr2, RawType val1, RawType val2) { // Returns success if val1 is less than val2, if (val1 < val2) { return AssertionSuccess(); @@ -1401,32 +1241,27 @@ AssertionResult FloatingPointLE(const char* expr1, // any predicate involving a NaN must return false. ::std::stringstream val1_ss; - val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << val1; + val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) << val1; ::std::stringstream val2_ss; - val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << val2; + val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) << val2; - return AssertionFailure() - << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" - << " Actual: " << StringStreamToString(&val1_ss) << " vs " - << StringStreamToString(&val2_ss); + return AssertionFailure() << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" + << " Actual: " << StringStreamToString(&val1_ss) << " vs " + << StringStreamToString(&val2_ss); } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2) { +AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2) { return internal::FloatingPointLE(expr1, expr2, val1, val2); } // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2) { +AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2) { return internal::FloatingPointLE(expr1, expr2, val1, val2); } @@ -1434,36 +1269,28 @@ namespace internal { // The helper function for {ASSERT|EXPECT}_EQ with int or enum // arguments. -AssertionResult CmpHelperEQ(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, - BiggestInt rhs) { +AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { if (lhs == rhs) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - FormatForComparisonFailureMessage(lhs, rhs), - FormatForComparisonFailureMessage(rhs, lhs), - false); + return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), + FormatForComparisonFailureMessage(rhs, lhs), false); } // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here // just to avoid copy-and-paste of similar code. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - BiggestInt val1, BiggestInt val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return AssertionFailure() \ - << "Expected: (" << expr1 << ") " #op " (" << expr2\ - << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ - << " vs " << FormatForComparisonFailureMessage(val2, val1);\ - }\ -} +#define GTEST_IMPL_CMP_HELPER_(op_name, op) \ + AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) { \ + if (val1 op val2) { \ + return AssertionSuccess(); \ + } else { \ + return AssertionFailure() << "Expected: (" << expr1 << ") " #op " (" << expr2 \ + << "), actual: " << FormatForComparisonFailureMessage(val1, val2) << " vs " \ + << FormatForComparisonFailureMessage(val2, val1); \ + } \ + } // Implements the helper function for {ASSERT|EXPECT}_NE with int or // enum arguments. @@ -1473,74 +1300,54 @@ GTEST_IMPL_CMP_HELPER_(NE, !=) GTEST_IMPL_CMP_HELPER_(LE, <=) // Implements the helper function for {ASSERT|EXPECT}_LT with int or // enum arguments. -GTEST_IMPL_CMP_HELPER_(LT, < ) +GTEST_IMPL_CMP_HELPER_(LT, <) // Implements the helper function for {ASSERT|EXPECT}_GE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GE, >=) // Implements the helper function for {ASSERT|EXPECT}_GT with int or // enum arguments. -GTEST_IMPL_CMP_HELPER_(GT, > ) +GTEST_IMPL_CMP_HELPER_(GT, >) #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. -AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, +AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. -AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, +AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - true); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), true); } // The helper function for {ASSERT|EXPECT}_STRNE. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2) { +AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: \"" << s1 + << "\" vs \"" << s2 << "\""; } } // The helper function for {ASSERT|EXPECT}_STRCASENE. -AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, +AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { - return AssertionFailure() - << "Expected: (" << s1_expression << ") != (" - << s2_expression << ") (ignoring case), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression + << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } @@ -1555,23 +1362,20 @@ namespace { // only. bool IsSubstringPred(const char* needle, const char* haystack) { - if (needle == NULL || haystack == NULL) - return needle == haystack; + if (needle == NULL || haystack == NULL) return needle == haystack; return strstr(haystack, needle) != NULL; } bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { - if (needle == NULL || haystack == NULL) - return needle == haystack; + if (needle == NULL || haystack == NULL) return needle == haystack; return wcsstr(haystack, needle) != NULL; } // StringType here can be either ::std::string or ::std::wstring. template -bool IsSubstringPred(const StringType& needle, - const StringType& haystack) { +bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } @@ -1580,21 +1384,17 @@ bool IsSubstringPred(const StringType& needle, // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template -AssertionResult IsSubstringImpl( - bool expected_to_be_substring, - const char* needle_expr, const char* haystack_expr, - const StringType& needle, const StringType& haystack) { - if (IsSubstringPred(needle, haystack) == expected_to_be_substring) - return AssertionSuccess(); +AssertionResult IsSubstringImpl(bool expected_to_be_substring, const char* needle_expr, const char* haystack_expr, + const StringType& needle, const StringType& haystack) { + if (IsSubstringPred(needle, haystack) == expected_to_be_substring) return AssertionSuccess(); const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; - return AssertionFailure() - << "Value of: " << needle_expr << "\n" - << " Actual: " << begin_string_quote << needle << "\"\n" - << "Expected: " << (expected_to_be_substring ? "" : "not ") - << "a substring of " << haystack_expr << "\n" - << "Which is: " << begin_string_quote << haystack << "\""; + return AssertionFailure() << "Value of: " << needle_expr << "\n" + << " Actual: " << begin_string_quote << needle << "\"\n" + << "Expected: " << (expected_to_be_substring ? "" : "not ") << "a substring of " + << haystack_expr << "\n" + << "Which is: " << begin_string_quote << haystack << "\""; } } // namespace @@ -1603,52 +1403,44 @@ AssertionResult IsSubstringImpl( // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, + const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, + const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const char* needle, + const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const wchar_t* needle, + const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::string& needle, + const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const ::std::string& needle, + const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { +AssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, + const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { +AssertionResult IsNotSubstring(const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, + const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif // GTEST_HAS_STD_WSTRING @@ -1660,43 +1452,39 @@ namespace internal { namespace { // Helper function for IsHRESULT{SuccessFailure} predicates -AssertionResult HRESULTFailureHelper(const char* expr, - const char* expected, +AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT -# if GTEST_OS_WINDOWS_MOBILE +# if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't support FormatMessage. const char error_text[] = ""; -# else +# else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. - const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS; + const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. - char error_text[kBufSize] = { '\0' }; + char error_text[kBufSize] = {'\0'}; DWORD message_length = ::FormatMessageA(kFlags, - 0, // no source, we're asking system - hr, // the error - 0, // no line width restrictions + 0, // no source, we're asking system + hr, // the error + 0, // no line width restrictions error_text, // output buffer - kBufSize, // buf size - NULL); // no arguments for inserts + kBufSize, // buf size + NULL); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing CR-LF) - for (; message_length && IsSpace(error_text[message_length - 1]); - --message_length) { + for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } -# endif // GTEST_OS_WINDOWS_MOBILE +# endif // GTEST_OS_WINDOWS_MOBILE const std::string error_hex("0x" + String::FormatHexInt(hr)); - return ::testing::AssertionFailure() - << "Expected: " << expr << " " << expected << ".\n" - << " Actual: " << error_hex << " " << error_text << "\n"; + return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" + << " Actual: " << error_hex << " " << error_text << "\n"; } } // namespace @@ -1730,16 +1518,16 @@ AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; +const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; +const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2 * 6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; +const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3 * 6)) - 1; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be @@ -1764,7 +1552,7 @@ std::string CodePointToUtf8(UInt32 code_point) { char str[5]; // Big enough for the largest valid code point. if (code_point <= kMaxCodePoint1) { str[1] = '\0'; - str[0] = static_cast(code_point); // 0xxxxxxx + str[0] = static_cast(code_point); // 0xxxxxxx } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx @@ -1774,7 +1562,7 @@ std::string CodePointToUtf8(UInt32 code_point) { str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast(0xE0 | code_point); // 1110xxxx - } else { // code_point <= kMaxCodePoint4 + } else { // code_point <= kMaxCodePoint4 str[4] = '\0'; str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx @@ -1792,19 +1580,16 @@ std::string CodePointToUtf8(UInt32 code_point) { // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { - return sizeof(wchar_t) == 2 && - (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; + return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; } // Creates a Unicode code point from UTF16 surrogate pair. -inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, - wchar_t second) { +inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second) { const UInt32 mask = (1 << 10) - 1; - return (sizeof(wchar_t) == 2) ? - (((first & mask) << 10) | (second & mask)) + 0x10000 : - // This function should not be called when the condition is - // false, but we provide a sensible default in case it is. - static_cast(first); + return (sizeof(wchar_t) == 2) ? (((first & mask) << 10) | (second & mask)) + 0x10000 : + // This function should not be called when the condition is + // false, but we provide a sensible default in case it is. + static_cast(first); } // Converts a wide string to a narrow string in UTF-8 encoding. @@ -1821,8 +1606,7 @@ inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. std::string WideStringToUtf8(const wchar_t* str, int num_chars) { - if (num_chars == -1) - num_chars = static_cast(wcslen(str)); + if (num_chars == -1) num_chars = static_cast(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { @@ -1831,8 +1615,7 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { - unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], - str[i + 1]); + unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast(str[i]); @@ -1845,8 +1628,8 @@ std::string WideStringToUtf8(const wchar_t* str, int num_chars) { // Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". -std::string String::ShowWideCString(const wchar_t * wide_c_str) { - if (wide_c_str == NULL) return "(null)"; +std::string String::ShowWideCString(const wchar_t* wide_c_str) { + if (wide_c_str == NULL) return "(null)"; return internal::WideStringToUtf8(wide_c_str, -1); } @@ -1857,7 +1640,7 @@ std::string String::ShowWideCString(const wchar_t * wide_c_str) { // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. -bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { +bool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; @@ -1866,34 +1649,24 @@ bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { } // Helper function for *_STREQ on wide strings. -AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const wchar_t* lhs, +AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); + return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // Helper function for *_STRNE on wide strings. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, +AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: " - << PrintToString(s1) - << " vs " << PrintToString(s2); + return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression + << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2); } // Compares two C strings, ignoring case. Returns true iff they have @@ -1902,28 +1675,25 @@ AssertionResult CmpHelperSTRNE(const char* s1_expression, // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. -bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { - if (lhs == NULL) - return rhs == NULL; - if (rhs == NULL) - return false; +bool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { + if (lhs == NULL) return rhs == NULL; + if (rhs == NULL) return false; return posix::StrCaseCmp(lhs, rhs) == 0; } - // Compares two wide C strings, ignoring case. Returns true iff they - // have the same content. - // - // Unlike wcscasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL wide C string, - // including the empty string. - // NB: The implementations on different platforms slightly differ. - // On windows, this method uses _wcsicmp which compares according to LC_CTYPE - // environment variable. On GNU platform this method uses wcscasecmp - // which compares according to LC_CTYPE category of the current locale. - // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the - // current locale. -bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, - const wchar_t* rhs) { +// Compares two wide C strings, ignoring case. Returns true iff they +// have the same content. +// +// Unlike wcscasecmp(), this function can handle NULL argument(s). +// A NULL C string is considered different to any non-NULL wide C string, +// including the empty string. +// NB: The implementations on different platforms slightly differ. +// On windows, this method uses _wcsicmp which compares according to LC_CTYPE +// environment variable. On GNU platform this method uses wcscasecmp +// which compares according to LC_CTYPE category of the current locale. +// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the +// current locale. +bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; @@ -1946,13 +1716,10 @@ bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, // Returns true iff str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. -bool String::EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix) { +bool String::EndsWithCaseInsensitive(const std::string& str, const std::string& suffix) { const size_t str_len = str.length(); const size_t suffix_len = suffix.length(); - return (str_len >= suffix_len) && - CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, - suffix.c_str()); + return (str_len >= suffix_len) && CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, suffix.c_str()); } // Formats an int value as "%02d". @@ -1972,8 +1739,7 @@ std::string String::FormatHexInt(int value) { // Formats a byte as "%02X". std::string String::FormatByte(unsigned char value) { std::stringstream ss; - ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase - << static_cast(value); + ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase << static_cast(value); return ss.str(); } @@ -1998,8 +1764,7 @@ std::string StringStreamToString(::std::stringstream* ss) { } // Appends the user-supplied message to the Google-Test-generated message. -std::string AppendUserMessage(const std::string& gtest_msg, - const Message& user_msg) { +std::string AppendUserMessage(const std::string& gtest_msg, const Message& user_msg) { // Appends the user message if it's non-empty. const std::string user_msg_string = user_msg.GetString(); if (user_msg_string.empty()) { @@ -2014,21 +1779,16 @@ std::string AppendUserMessage(const std::string& gtest_msg, // class TestResult // Creates an empty TestResult. -TestResult::TestResult() - : death_test_count_(0), - elapsed_time_(0) { -} +TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) {} // D'tor. -TestResult::~TestResult() { -} +TestResult::~TestResult() {} // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { - if (i < 0 || i >= total_part_count()) - internal::posix::Abort(); + if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(i); } @@ -2036,15 +1796,12 @@ const TestPartResult& TestResult::GetTestPartResult(int i) const { // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { - if (i < 0 || i >= test_property_count()) - internal::posix::Abort(); + if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(i); } // Clears the test part results. -void TestResult::ClearTestPartResults() { - test_part_results_.clear(); -} +void TestResult::ClearTestPartResults() { test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { @@ -2054,15 +1811,13 @@ void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { // Adds a test property to the list. If a property with the same key as the // supplied property is already represented, the value of this test_property // replaces the old value for that key. -void TestResult::RecordProperty(const std::string& xml_element, - const TestProperty& test_property) { +void TestResult::RecordProperty(const std::string& xml_element, const TestProperty& test_property) { if (!ValidateTestProperty(xml_element, test_property)) { return; } internal::MutexLock lock(&test_properites_mutex_); const std::vector::iterator property_with_matching_key = - std::find_if(test_properties_.begin(), test_properties_.end(), - internal::TestPropertyKeyIs(test_property.key())); + std::find_if(test_properties_.begin(), test_properties_.end(), internal::TestPropertyKeyIs(test_property.key())); if (property_with_matching_key == test_properties_.end()) { test_properties_.push_back(test_property); return; @@ -2072,45 +1827,23 @@ void TestResult::RecordProperty(const std::string& xml_element, // The list of reserved attributes used in the element of XML // output. -static const char* const kReservedTestSuitesAttributes[] = { - "disabled", - "errors", - "failures", - "name", - "random_seed", - "tests", - "time", - "timestamp" -}; +static const char* const kReservedTestSuitesAttributes[] = {"disabled", "errors", "failures", "name", + "random_seed", "tests", "time", "timestamp"}; // The list of reserved attributes used in the element of XML // output. -static const char* const kReservedTestSuiteAttributes[] = { - "disabled", - "errors", - "failures", - "name", - "tests", - "time" -}; +static const char* const kReservedTestSuiteAttributes[] = {"disabled", "errors", "failures", "name", "tests", "time"}; // The list of reserved attributes used in the element of XML output. -static const char* const kReservedTestCaseAttributes[] = { - "classname", - "name", - "status", - "time", - "type_param", - "value_param" -}; +static const char* const kReservedTestCaseAttributes[] = {"classname", "name", "status", + "time", "type_param", "value_param"}; template std::vector ArrayAsVector(const char* const (&array)[kSize]) { return std::vector(array, array + kSize); } -static std::vector GetReservedAttributesForElement( - const std::string& xml_element) { +static std::vector GetReservedAttributesForElement(const std::string& xml_element) { if (xml_element == "testsuites") { return ArrayAsVector(kReservedTestSuitesAttributes); } else if (xml_element == "testsuite") { @@ -2138,13 +1871,10 @@ static std::string FormatWordList(const std::vector& words) { return word_list.GetString(); } -bool ValidateTestPropertyName(const std::string& property_name, - const std::vector& reserved_names) { - if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != - reserved_names.end()) { - ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name - << " (" << FormatWordList(reserved_names) - << " are reserved by " << GTEST_NAME_ << ")"; +bool ValidateTestPropertyName(const std::string& property_name, const std::vector& reserved_names) { + if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != reserved_names.end()) { + ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name << " (" + << FormatWordList(reserved_names) << " are reserved by " << GTEST_NAME_ << ")"; return false; } return true; @@ -2152,10 +1882,8 @@ bool ValidateTestPropertyName(const std::string& property_name, // Adds a failure if the key is a reserved attribute of the element named // xml_element. Returns true if the property is valid. -bool TestResult::ValidateTestProperty(const std::string& xml_element, - const TestProperty& test_property) { - return ValidateTestPropertyName(test_property.key(), - GetReservedAttributesForElement(xml_element)); +bool TestResult::ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property) { + return ValidateTestPropertyName(test_property.key(), GetReservedAttributesForElement(xml_element)); } // Clears the object. @@ -2169,69 +1897,51 @@ void TestResult::Clear() { // Returns true iff the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { - if (GetTestPartResult(i).failed()) - return true; + if (GetTestPartResult(i).failed()) return true; } return false; } // Returns true iff the test part fatally failed. -static bool TestPartFatallyFailed(const TestPartResult& result) { - return result.fatally_failed(); -} +static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } // Returns true iff the test fatally failed. -bool TestResult::HasFatalFailure() const { - return CountIf(test_part_results_, TestPartFatallyFailed) > 0; -} +bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } // Returns true iff the test part non-fatally failed. -static bool TestPartNonfatallyFailed(const TestPartResult& result) { - return result.nonfatally_failed(); -} +static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } // Returns true iff the test has a non-fatal failure. -bool TestResult::HasNonfatalFailure() const { - return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; -} +bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. -int TestResult::total_part_count() const { - return static_cast(test_part_results_.size()); -} +int TestResult::total_part_count() const { return static_cast(test_part_results_.size()); } // Returns the number of the test properties. -int TestResult::test_property_count() const { - return static_cast(test_properties_.size()); -} +int TestResult::test_property_count() const { return static_cast(test_properties_.size()); } // class Test // Creates a Test object. // The c'tor saves the states of all flags. -Test::Test() - : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { -} +Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {} // The d'tor restores the states of all flags. The actual work is // done by the d'tor of the gtest_flag_saver_ field, and thus not // visible here. -Test::~Test() { -} +Test::~Test() {} // Sets up the test fixture. // // A sub-class may override this. -void Test::SetUp() { -} +void Test::SetUp() {} // Tears down the test fixture. // // A sub-class may override this. -void Test::TearDown() { -} +void Test::TearDown() {} // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, const std::string& value) { @@ -2247,16 +1957,14 @@ void Test::RecordProperty(const std::string& key, int value) { namespace internal { -void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const std::string& message) { +void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message) { // This function is a friend of UnitTest and as such has access to // AddTestPartResult. - UnitTest::GetInstance()->AddTestPartResult( - result_type, - NULL, // No info about the source file where the exception occurred. - -1, // We have no info on which line caused the exception. - message, - ""); // No stack trace, either. + UnitTest::GetInstance()->AddTestPartResult(result_type, + NULL, // No info about the source file where the exception occurred. + -1, // We have no info on which line caused the exception. + message, + ""); // No stack trace, either. } } // namespace internal @@ -2293,33 +2001,26 @@ bool Test::HasSameFixtureClass() { // Gets the name of the TEST and the name of the TEST_F. Note // that first_is_TEST and this_is_TEST cannot both be true, as // the fixture IDs are different for the two tests. - const char* const TEST_name = - first_is_TEST ? first_test_name : this_test_name; - const char* const TEST_F_name = - first_is_TEST ? this_test_name : first_test_name; - - ADD_FAILURE() - << "All tests in the same test case must use the same test fixture\n" - << "class, so mixing TEST_F and TEST in the same test case is\n" - << "illegal. In test case " << this_test_info->test_case_name() - << ",\n" - << "test " << TEST_F_name << " is defined using TEST_F but\n" - << "test " << TEST_name << " is defined using TEST. You probably\n" - << "want to change the TEST to TEST_F or move it to another test\n" - << "case."; + const char* const TEST_name = first_is_TEST ? first_test_name : this_test_name; + const char* const TEST_F_name = first_is_TEST ? this_test_name : first_test_name; + + ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" + << "class, so mixing TEST_F and TEST in the same test case is\n" + << "illegal. In test case " << this_test_info->test_case_name() << ",\n" + << "test " << TEST_F_name << " is defined using TEST_F but\n" + << "test " << TEST_name << " is defined using TEST. You probably\n" + << "want to change the TEST to TEST_F or move it to another test\n" + << "case."; } else { // Two fixture classes with the same name appear in two different // namespaces, which is not allowed. Tell the user how to fix this. - ADD_FAILURE() - << "All tests in the same test case must use the same test fixture\n" - << "class. However, in test case " - << this_test_info->test_case_name() << ",\n" - << "you defined test " << first_test_name - << " and test " << this_test_name << "\n" - << "using two different test fixture classes. This can happen if\n" - << "the two classes are from different namespaces or translation\n" - << "units and have the same name. You should probably rename one\n" - << "of the classes to put the tests into different test cases."; + ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " << this_test_info->test_case_name() << ",\n" + << "you defined test " << first_test_name << " and test " << this_test_name << "\n" + << "using two different test fixture classes. This can happen if\n" + << "the two classes are from different namespaces or translation\n" + << "units and have the same name. You should probably rename one\n" + << "of the classes to put the tests into different test cases."; } return false; } @@ -2333,11 +2034,10 @@ bool Test::HasSameFixtureClass() { // function returns its result via an output parameter pointer because VC++ // prohibits creation of objects with destructors on stack in functions // using __try (see error C2712). -static std::string* FormatSehExceptionMessage(DWORD exception_code, - const char* location) { +static std::string* FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; - message << "SEH exception with code 0x" << std::setbase(16) << - exception_code << std::setbase(10) << " thrown in " << location << "."; + message << "SEH exception with code 0x" << std::setbase(16) << exception_code << std::setbase(10) << " thrown in " + << location << "."; return new std::string(message.GetString()); } @@ -2349,8 +2049,7 @@ namespace internal { #if GTEST_HAS_EXCEPTIONS // Adds an "exception thrown" fatal failure to the current test. -static std::string FormatCxxExceptionMessage(const char* description, - const char* location) { +static std::string FormatCxxExceptionMessage(const char* description, const char* location) { Message message; if (description != NULL) { message << "C++ exception with description \"" << description << "\""; @@ -2362,11 +2061,9 @@ static std::string FormatCxxExceptionMessage(const char* description, return message.GetString(); } -static std::string PrintTestPartResultToString( - const TestPartResult& test_part_result); +static std::string PrintTestPartResultToString(const TestPartResult& test_part_result); -GoogleTestFailureException::GoogleTestFailureException( - const TestPartResult& failure) +GoogleTestFailureException::GoogleTestFailureException(const TestPartResult& failure) : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} #endif // GTEST_HAS_EXCEPTIONS @@ -2380,8 +2077,7 @@ GoogleTestFailureException::GoogleTestFailureException( // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template -Result HandleSehExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { +Result HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(), const char* location) { #if GTEST_HAS_SEH __try { return (object->*method)(); @@ -2390,10 +2086,8 @@ Result HandleSehExceptionsInMethodIfSupported( // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). - std::string* exception_message = FormatSehExceptionMessage( - GetExceptionCode(), location); - internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, - *exception_message); + std::string* exception_message = FormatSehExceptionMessage(GetExceptionCode(), location); + internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); delete exception_message; return static_cast(0); } @@ -2407,8 +2101,7 @@ Result HandleSehExceptionsInMethodIfSupported( // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template -Result HandleExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { +Result HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(), const char* location) { // NOTE: The user code can affect the way in which Google Test handles // exceptions by setting GTEST_FLAG(catch_exceptions), but only before // RUN_ALL_TESTS() starts. It is technically possible to check the flag @@ -2442,13 +2135,11 @@ Result HandleExceptionsInMethodIfSupported( // framework catch it. Therefore we just re-throw it. throw; } catch (const std::exception& e) { // NOLINT - internal::ReportFailureInUnknownLocation( - TestPartResult::kFatalFailure, - FormatCxxExceptionMessage(e.what(), location)); + internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(e.what(), location)); } catch (...) { // NOLINT - internal::ReportFailureInUnknownLocation( - TestPartResult::kFatalFailure, - FormatCxxExceptionMessage(NULL, location)); + internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, + FormatCxxExceptionMessage(NULL, location)); } return static_cast(0); #else @@ -2471,39 +2162,28 @@ void Test::Run() { // We will run the test only if SetUp() was successful. if (!HasFatalFailure()) { impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TestBody, "the test body"); + internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody, "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TearDown, "TearDown()"); + internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown, "TearDown()"); } // Returns true iff the current test has a fatal failure. -bool Test::HasFatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); -} +bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); } // Returns true iff the current test has a non-fatal failure. -bool Test::HasNonfatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()-> - HasNonfatalFailure(); -} +bool Test::HasNonfatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasNonfatalFailure(); } // class TestInfo // Constructs a TestInfo object. It assumes ownership of the test factory // object. -TestInfo::TestInfo(const std::string& a_test_case_name, - const std::string& a_name, - const char* a_type_param, - const char* a_value_param, - internal::CodeLocation a_code_location, - internal::TypeId fixture_class_id, +TestInfo::TestInfo(const std::string& a_test_case_name, const std::string& a_name, const char* a_type_param, + const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : test_case_name_(a_test_case_name), name_(a_name), @@ -2540,40 +2220,29 @@ namespace internal { // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. -TestInfo* MakeAndRegisterTestInfo( - const char* test_case_name, - const char* name, - const char* type_param, - const char* value_param, - CodeLocation code_location, - TypeId fixture_class_id, - SetUpTestCaseFunc set_up_tc, - TearDownTestCaseFunc tear_down_tc, - TestFactoryBase* factory) { +TestInfo* MakeAndRegisterTestInfo(const char* test_case_name, const char* name, const char* type_param, + const char* value_param, CodeLocation code_location, TypeId fixture_class_id, + SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, + TestFactoryBase* factory) { TestInfo* const test_info = - new TestInfo(test_case_name, name, type_param, value_param, - code_location, fixture_class_id, factory); + new TestInfo(test_case_name, name, type_param, value_param, code_location, fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } #if GTEST_HAS_PARAM_TEST -void ReportInvalidTestCaseType(const char* test_case_name, - CodeLocation code_location) { +void ReportInvalidTestCaseType(const char* test_case_name, CodeLocation code_location) { Message errors; - errors - << "Attempted redefinition of test case " << test_case_name << ".\n" - << "All tests in the same test case must use the same test fixture\n" - << "class. However, in test case " << test_case_name << ", you tried\n" - << "to define a test using a fixture class different from the one\n" - << "used earlier. This can happen if the two fixture classes are\n" - << "from different namespaces and have the same name. You should\n" - << "probably rename one of the classes to put the tests into different\n" - << "test cases."; - - fprintf(stderr, "%s %s", - FormatFileLocation(code_location.file.c_str(), - code_location.line).c_str(), + errors << "Attempted redefinition of test case " << test_case_name << ".\n" + << "All tests in the same test case must use the same test fixture\n" + << "class. However, in test case " << test_case_name << ", you tried\n" + << "to define a test using a fixture class different from the one\n" + << "used earlier. This can happen if the two fixture classes are\n" + << "from different namespaces and have the same name. You should\n" + << "probably rename one of the classes to put the tests into different\n" + << "test cases."; + + fprintf(stderr, "%s %s", FormatFileLocation(code_location.file.c_str(), code_location.line).c_str(), errors.GetString().c_str()); } #endif // GTEST_HAS_PARAM_TEST @@ -2595,13 +2264,10 @@ class TestNameIs { // Constructor. // // TestNameIs has NO default constructor. - explicit TestNameIs(const char* name) - : name_(name) {} + explicit TestNameIs(const char* name) : name_(name) {} // Returns true iff the test name of test_info matches name_. - bool operator()(const TestInfo * test_info) const { - return test_info && test_info->name() == name_; - } + bool operator()(const TestInfo* test_info) const { return test_info && test_info->name() == name_; } private: std::string name_; @@ -2644,9 +2310,8 @@ void TestInfo::Run() { impl->os_stack_trace_getter()->UponLeavingGTest(); // Creates the test object. - Test* const test = internal::HandleExceptionsInMethodIfSupported( - factory_, &internal::TestFactoryBase::CreateTest, - "the test fixture's constructor"); + Test* const test = internal::HandleExceptionsInMethodIfSupported(factory_, &internal::TestFactoryBase::CreateTest, + "the test fixture's constructor"); // Runs the test only if the test object was created and its // constructor didn't generate a fatal failure. @@ -2658,8 +2323,7 @@ void TestInfo::Run() { // Deletes the test object. impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - test, &Test::DeleteSelf_, "the test fixture's destructor"); + internal::HandleExceptionsInMethodIfSupported(test, &Test::DeleteSelf_, "the test fixture's destructor"); result_.set_elapsed_time(internal::GetTimeInMillis() - start); @@ -2674,39 +2338,25 @@ void TestInfo::Run() { // class TestCase // Gets the number of successful tests in this test case. -int TestCase::successful_test_count() const { - return CountIf(test_info_list_, TestPassed); -} +int TestCase::successful_test_count() const { return CountIf(test_info_list_, TestPassed); } // Gets the number of failed tests in this test case. -int TestCase::failed_test_count() const { - return CountIf(test_info_list_, TestFailed); -} +int TestCase::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } // Gets the number of disabled tests that will be reported in the XML report. -int TestCase::reportable_disabled_test_count() const { - return CountIf(test_info_list_, TestReportableDisabled); -} +int TestCase::reportable_disabled_test_count() const { return CountIf(test_info_list_, TestReportableDisabled); } // Gets the number of disabled tests in this test case. -int TestCase::disabled_test_count() const { - return CountIf(test_info_list_, TestDisabled); -} +int TestCase::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } // Gets the number of tests to be printed in the XML report. -int TestCase::reportable_test_count() const { - return CountIf(test_info_list_, TestReportable); -} +int TestCase::reportable_test_count() const { return CountIf(test_info_list_, TestReportable); } // Get the number of tests in this test case that should run. -int TestCase::test_to_run_count() const { - return CountIf(test_info_list_, ShouldRunTest); -} +int TestCase::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); } // Gets the number of all tests. -int TestCase::total_test_count() const { - return static_cast(test_info_list_.size()); -} +int TestCase::total_test_count() const { return static_cast(test_info_list_.size()); } // Creates a TestCase with the given name. // @@ -2717,16 +2367,14 @@ int TestCase::total_test_count() const { // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case -TestCase::TestCase(const char* a_name, const char* a_type_param, - Test::SetUpTestCaseFunc set_up_tc, +TestCase::TestCase(const char* a_name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) : name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), set_up_tc_(set_up_tc), tear_down_tc_(tear_down_tc), should_run_(false), - elapsed_time_(0) { -} + elapsed_time_(0) {} // Destructor of TestCase. TestCase::~TestCase() { @@ -2750,7 +2398,7 @@ TestInfo* TestCase::GetMutableTestInfo(int i) { // Adds a test to this test case. Will delete the test upon // destruction of the TestCase object. -void TestCase::AddTestInfo(TestInfo * test_info) { +void TestCase::AddTestInfo(TestInfo* test_info) { test_info_list_.push_back(test_info); test_indices_.push_back(static_cast(test_indices_.size())); } @@ -2766,8 +2414,7 @@ void TestCase::Run() { repeater->OnTestCaseStart(*this); impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); + internal::HandleExceptionsInMethodIfSupported(this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); const internal::TimeInMillis start = internal::GetTimeInMillis(); for (int i = 0; i < total_test_count(); i++) { @@ -2776,8 +2423,7 @@ void TestCase::Run() { elapsed_time_ = internal::GetTimeInMillis() - start; impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); + internal::HandleExceptionsInMethodIfSupported(this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); repeater->OnTestCaseEnd(*this); impl->set_current_test_case(NULL); @@ -2790,9 +2436,7 @@ void TestCase::ClearResult() { } // Shuffles the tests in this test case. -void TestCase::ShuffleTests(internal::Random* random) { - Shuffle(random, &test_indices_); -} +void TestCase::ShuffleTests(internal::Random* random) { Shuffle(random, &test_indices_); } // Restores the test order to before the first shuffle. void TestCase::UnshuffleTests() { @@ -2806,17 +2450,12 @@ void TestCase::UnshuffleTests() { // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". -static std::string FormatCountableNoun(int count, - const char * singular_form, - const char * plural_form) { - return internal::StreamableToString(count) + " " + - (count == 1 ? singular_form : plural_form); +static std::string FormatCountableNoun(int count, const char* singular_form, const char* plural_form) { + return internal::StreamableToString(count) + " " + (count == 1 ? singular_form : plural_form); } // Formats the count of tests. -static std::string FormatTestCount(int test_count) { - return FormatCountableNoun(test_count, "test", "tests"); -} +static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } // Formats the count of test cases. static std::string FormatTestCaseCount(int test_case_count) { @@ -2827,7 +2466,7 @@ static std::string FormatTestCaseCount(int test_case_count) { // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. -static const char * TestPartResultTypeToString(TestPartResult::Type type) { +static const char* TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSuccess: return "Success"; @@ -2847,19 +2486,15 @@ static const char * TestPartResultTypeToString(TestPartResult::Type type) { namespace internal { // Prints a TestPartResult to an std::string. -static std::string PrintTestPartResultToString( - const TestPartResult& test_part_result) { - return (Message() - << internal::FormatFileLocation(test_part_result.file_name(), - test_part_result.line_number()) - << " " << TestPartResultTypeToString(test_part_result.type()) - << test_part_result.message()).GetString(); +static std::string PrintTestPartResultToString(const TestPartResult& test_part_result) { + return (Message() << internal::FormatFileLocation(test_part_result.file_name(), test_part_result.line_number()) << " " + << TestPartResultTypeToString(test_part_result.type()) << test_part_result.message()) + .GetString(); } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { - const std::string& result = - PrintTestPartResultToString(test_part_result); + const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); // If the test program runs in Visual Studio or a debugger, the @@ -2877,23 +2512,21 @@ static void PrintTestPartResult(const TestPartResult& test_part_result) { // class PrettyUnitTestResultPrinter -enum GTestColor { - COLOR_DEFAULT, - COLOR_RED, - COLOR_GREEN, - COLOR_YELLOW -}; +enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Returns the character attribute for the given color. WORD GetColorAttribute(GTestColor color) { switch (color) { - case COLOR_RED: return FOREGROUND_RED; - case COLOR_GREEN: return FOREGROUND_GREEN; - case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; - default: return 0; + case COLOR_RED: + return FOREGROUND_RED; + case COLOR_GREEN: + return FOREGROUND_GREEN; + case COLOR_YELLOW: + return FOREGROUND_RED | FOREGROUND_GREEN; + default: + return 0; } } @@ -2903,10 +2536,14 @@ WORD GetColorAttribute(GTestColor color) { // an invalid input. const char* GetAnsiColorCode(GTestColor color) { switch (color) { - case COLOR_RED: return "1"; - case COLOR_GREEN: return "2"; - case COLOR_YELLOW: return "3"; - default: return NULL; + case COLOR_RED: + return "1"; + case COLOR_GREEN: + return "2"; + case COLOR_YELLOW: + return "3"; + default: + return NULL; }; } @@ -2925,25 +2562,19 @@ bool ShouldUseColor(bool stdout_is_tty) { // On non-Windows platforms, we rely on the TERM variable. const char* const term = posix::GetEnv("TERM"); const bool term_supports_color = - String::CStringEquals(term, "xterm") || - String::CStringEquals(term, "xterm-color") || - String::CStringEquals(term, "xterm-256color") || - String::CStringEquals(term, "screen") || - String::CStringEquals(term, "screen-256color") || - String::CStringEquals(term, "tmux") || - String::CStringEquals(term, "tmux-256color") || - String::CStringEquals(term, "rxvt-unicode") || - String::CStringEquals(term, "rxvt-unicode-256color") || - String::CStringEquals(term, "linux") || + String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || + String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") || + String::CStringEquals(term, "screen-256color") || String::CStringEquals(term, "tmux") || + String::CStringEquals(term, "tmux-256color") || String::CStringEquals(term, "rxvt-unicode") || + String::CStringEquals(term, "rxvt-unicode-256color") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; #endif // GTEST_OS_WINDOWS } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || - String::CaseInsensitiveCStringEquals(gtest_color, "true") || - String::CaseInsensitiveCStringEquals(gtest_color, "t") || - String::CStringEquals(gtest_color, "1"); + String::CaseInsensitiveCStringEquals(gtest_color, "true") || + String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. @@ -2957,12 +2588,11 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ - GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT +#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || \ + GTEST_OS_WINDOWS_RT const bool use_color = AlwaysFalse(); #else - static const bool in_color_mode = - ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); + static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); const bool use_color = in_color_mode && (color != COLOR_DEFAULT); #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS // The '!= 0' comparison is necessary to satisfy MSVC 7.1. @@ -2973,8 +2603,7 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { return; } -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. @@ -2986,8 +2615,7 @@ void ColoredPrintf(GTestColor color, const char* fmt, ...) { // SetConsoleTextAttribute call lest it affect the text that is already // printed but has not yet reached the console. fflush(stdout); - SetConsoleTextAttribute(stdout_handle, - GetColorAttribute(color) | FOREGROUND_INTENSITY); + SetConsoleTextAttribute(stdout_handle, GetColorAttribute(color) | FOREGROUND_INTENSITY); vprintf(fmt, args); fflush(stdout); @@ -3014,8 +2642,7 @@ void PrintFullTestCommentIfPresent(const TestInfo& test_info) { printf(", where "); if (type_param != NULL) { printf("%s = %s", kTypeParamLabel, type_param); - if (value_param != NULL) - printf(" and "); + if (value_param != NULL) printf(" and "); } if (value_param != NULL) { printf("%s = %s", kValueParamLabel, value_param); @@ -3029,9 +2656,7 @@ void PrintFullTestCommentIfPresent(const TestInfo& test_info) { class PrettyUnitTestResultPrinter : public TestEventListener { public: PrettyUnitTestResultPrinter() {} - static void PrintTestName(const char * test_case, const char * test) { - printf("%s.%s", test_case, test); - } + static void PrintTestName(const char* test_case, const char* test) { printf("%s.%s", test_case, test); } // The following methods override what's in the TestEventListener class. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} @@ -3052,52 +2677,42 @@ class PrettyUnitTestResultPrinter : public TestEventListener { static void PrintFailedTests(const UnitTest& unit_test); }; - // Fired before each iteration of tests starts. -void PrettyUnitTestResultPrinter::OnTestIterationStart( - const UnitTest& unit_test, int iteration) { - if (GTEST_FLAG(repeat) != 1) - printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); +// Fired before each iteration of tests starts. +void PrettyUnitTestResultPrinter::OnTestIterationStart(const UnitTest& unit_test, int iteration) { + if (GTEST_FLAG(repeat) != 1) printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); const char* const filter = GTEST_FLAG(filter).c_str(); // Prints the filter if it's not *. This reminds the user that some // tests may be skipped. if (!String::CStringEquals(filter, kUniversalFilter)) { - ColoredPrintf(COLOR_YELLOW, - "Note: %s filter = %s\n", GTEST_NAME_, filter); + ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter); } if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); - ColoredPrintf(COLOR_YELLOW, - "Note: This is test shard %d of %s.\n", - static_cast(shard_index) + 1, + ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n", static_cast(shard_index) + 1, internal::posix::GetEnv(kTestTotalShards)); } if (GTEST_FLAG(shuffle)) { - ColoredPrintf(COLOR_YELLOW, - "Note: Randomizing tests' orders with a seed of %d .\n", - unit_test.random_seed()); + ColoredPrintf(COLOR_YELLOW, "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); } - ColoredPrintf(COLOR_GREEN, "[==========] "); - printf("Running %s from %s.\n", - FormatTestCount(unit_test.test_to_run_count()).c_str(), + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); fflush(stdout); } -void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( - const UnitTest& /*unit_test*/) { - ColoredPrintf(COLOR_GREEN, "[----------] "); +void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment set-up.\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { - const std::string counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s", counts.c_str(), test_case.name()); if (test_case.type_param() == NULL) { @@ -3109,18 +2724,16 @@ void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { } void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { - ColoredPrintf(COLOR_GREEN, "[ RUN ] "); + ColoredPrintf(COLOR_GREEN, "[ RUN ] "); PrintTestName(test_info.test_case_name(), test_info.name()); printf("\n"); fflush(stdout); } // Called after an assertion failure. -void PrettyUnitTestResultPrinter::OnTestPartResult( - const TestPartResult& result) { +void PrettyUnitTestResultPrinter::OnTestPartResult(const TestPartResult& result) { // If the test part succeeded, we don't need to do anything. - if (result.type() == TestPartResult::kSuccess) - return; + if (result.type() == TestPartResult::kSuccess) return; // Print failure message from the assertion (e.g. expected this and got that). PrintTestPartResult(result); @@ -3134,12 +2747,10 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } PrintTestName(test_info.test_case_name(), test_info.name()); - if (test_info.result()->Failed()) - PrintFullTestCommentIfPresent(test_info); + if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG(print_time)) { - printf(" (%s ms)\n", internal::StreamableToString( - test_info.result()->elapsed_time()).c_str()); + printf(" (%s ms)\n", internal::StreamableToString(test_info.result()->elapsed_time()).c_str()); } else { printf("\n"); } @@ -3149,18 +2760,15 @@ void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { if (!GTEST_FLAG(print_time)) return; - const std::string counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); + const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s (%s ms total)\n\n", - counts.c_str(), test_case.name(), + printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(), internal::StreamableToString(test_case.elapsed_time()).c_str()); fflush(stdout); } -void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( - const UnitTest& /*unit_test*/) { - ColoredPrintf(COLOR_GREEN, "[----------] "); +void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) { + ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment tear-down\n"); fflush(stdout); } @@ -3190,28 +2798,24 @@ void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { } } -void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { - ColoredPrintf(COLOR_GREEN, "[==========] "); - printf("%s from %s ran.", - FormatTestCount(unit_test.test_to_run_count()).c_str(), +void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { + ColoredPrintf(COLOR_GREEN, "[==========] "); + printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); if (GTEST_FLAG(print_time)) { - printf(" (%s ms total)", - internal::StreamableToString(unit_test.elapsed_time()).c_str()); + printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } printf("\n"); - ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); + ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); int num_failures = unit_test.failed_test_count(); if (!unit_test.Passed()) { const int failed_test_count = unit_test.failed_test_count(); - ColoredPrintf(COLOR_RED, "[ FAILED ] "); + ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); PrintFailedTests(unit_test); - printf("\n%2d FAILED %s\n", num_failures, - num_failures == 1 ? "TEST" : "TESTS"); + printf("\n%2d FAILED %s\n", num_failures, num_failures == 1 ? "TEST" : "TESTS"); } int num_disabled = unit_test.reportable_disabled_test_count(); @@ -3219,10 +2823,7 @@ void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, if (!num_failures) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } - ColoredPrintf(COLOR_YELLOW, - " YOU HAVE %d DISABLED %s\n\n", - num_disabled, - num_disabled == 1 ? "TEST" : "TESTS"); + ColoredPrintf(COLOR_YELLOW, " YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); } // Ensure that Google Test output is printed before, e.g., heapchecker output. fflush(stdout); @@ -3237,7 +2838,7 @@ class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} virtual ~TestEventRepeater(); - void Append(TestEventListener *listener); + void Append(TestEventListener* listener); TestEventListener* Release(TestEventListener* listener); // Controls whether events will be forwarded to listeners_. Set to false @@ -3269,16 +2870,12 @@ class TestEventRepeater : public TestEventListener { GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); }; -TestEventRepeater::~TestEventRepeater() { - ForEach(listeners_, Delete); -} +TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete); } -void TestEventRepeater::Append(TestEventListener *listener) { - listeners_.push_back(listener); -} +void TestEventRepeater::Append(TestEventListener* listener) { listeners_.push_back(listener); } // TODO(vladl@google.com): Factor the search functionality into Vector::Find. -TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { +TestEventListener* TestEventRepeater::Release(TestEventListener* listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { listeners_.erase(listeners_.begin() + i); @@ -3291,24 +2888,24 @@ TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { // Since most methods are very similar, use macros to reduce boilerplate. // This defines a member that forwards the call to all listeners. -#define GTEST_REPEATER_METHOD_(Name, Type) \ -void TestEventRepeater::Name(const Type& parameter) { \ - if (forwarding_enabled_) { \ - for (size_t i = 0; i < listeners_.size(); i++) { \ - listeners_[i]->Name(parameter); \ - } \ - } \ -} +#define GTEST_REPEATER_METHOD_(Name, Type) \ + void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (size_t i = 0; i < listeners_.size(); i++) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ + } // This defines a member that forwards the call to all listeners in reverse // order. -#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ -void TestEventRepeater::Name(const Type& parameter) { \ - if (forwarding_enabled_) { \ - for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ - listeners_[i]->Name(parameter); \ - } \ - } \ -} +#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ + void TestEventRepeater::Name(const Type& parameter) { \ + if (forwarding_enabled_) { \ + for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { \ + listeners_[i]->Name(parameter); \ + } \ + } \ + } GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) @@ -3325,8 +2922,7 @@ GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) #undef GTEST_REPEATER_METHOD_ #undef GTEST_REVERSE_REPEATER_METHOD_ -void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, - int iteration) { +void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (size_t i = 0; i < listeners_.size(); i++) { listeners_[i]->OnTestIterationStart(unit_test, iteration); @@ -3334,8 +2930,7 @@ void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, } } -void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, - int iteration) { +void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (int i = static_cast(listeners_.size()) - 1; i >= 0; i--) { listeners_[i]->OnTestIterationEnd(unit_test, iteration); @@ -3355,14 +2950,10 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { private: // Is c a whitespace character that is normalized to a space character // when it appears in an XML attribute value? - static bool IsNormalizableWhitespace(char c) { - return c == 0x9 || c == 0xA || c == 0xD; - } + static bool IsNormalizableWhitespace(char c) { return c == 0x9 || c == 0xA || c == 0xD; } // May c appear in a well-formed XML document? - static bool IsValidXmlCharacter(char c) { - return IsNormalizableWhitespace(c) || c >= 0x20; - } + static bool IsValidXmlCharacter(char c) { return IsNormalizableWhitespace(c) || c >= 0x20; } // Returns an XML-escaped copy of the input string str. If // is_attribute is true, the text is meant to appear as an attribute @@ -3374,37 +2965,27 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { static std::string RemoveInvalidXmlCharacters(const std::string& str); // Convenience wrapper around EscapeXml when str is an attribute value. - static std::string EscapeXmlAttribute(const std::string& str) { - return EscapeXml(str, true); - } + static std::string EscapeXmlAttribute(const std::string& str) { return EscapeXml(str, true); } // Convenience wrapper around EscapeXml when str is not an attribute value. - static std::string EscapeXmlText(const char* str) { - return EscapeXml(str, false); - } + static std::string EscapeXmlText(const char* str) { return EscapeXml(str, false); } // Verifies that the given attribute belongs to the given element and // streams the attribute as XML. - static void OutputXmlAttribute(std::ostream* stream, - const std::string& element_name, - const std::string& name, + static void OutputXmlAttribute(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value); // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. static void OutputXmlCDataSection(::std::ostream* stream, const char* data); // Streams an XML representation of a TestInfo object. - static void OutputXmlTestInfo(::std::ostream* stream, - const char* test_case_name, - const TestInfo& test_info); + static void OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info); // Prints an XML representation of a TestCase object - static void PrintXmlTestCase(::std::ostream* stream, - const TestCase& test_case); + static void PrintXmlTestCase(::std::ostream* stream, const TestCase& test_case); // Prints an XML summary of unit_test to output stream out. - static void PrintXmlUnitTest(::std::ostream* stream, - const UnitTest& unit_test); + static void PrintXmlUnitTest(::std::ostream* stream, const UnitTest& unit_test); // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. @@ -3419,8 +3000,7 @@ class XmlUnitTestResultPrinter : public EmptyTestEventListener { }; // Creates a new XmlUnitTestResultPrinter. -XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) - : output_file_(output_file) { +XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.c_str() == NULL || output_file_.empty()) { fprintf(stderr, "XML output file may not be null\n"); fflush(stderr); @@ -3429,8 +3009,7 @@ XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) } // Called after the unit test ends. -void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { +void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { FILE* xmlout = NULL; FilePath output_file(output_file_); FilePath output_dir(output_file.RemoveFileName()); @@ -3449,9 +3028,7 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, // 3. To interpret the meaning of errno in a thread-safe way, // we need the strerror_r() function, which is not available on // Windows. - fprintf(stderr, - "Unable to open file \"%s\"\n", - output_file_.c_str()); + fprintf(stderr, "Unable to open file \"%s\"\n", output_file_.c_str()); fflush(stderr); exit(EXIT_FAILURE); } @@ -3473,8 +3050,7 @@ void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, // most invalid characters can be retained using character references. // TODO(wan): It might be nice to have a minimally invasive, human-readable // escaping scheme for invalid characters, rather than dropping them. -std::string XmlUnitTestResultPrinter::EscapeXml( - const std::string& str, bool is_attribute) { +std::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str, bool is_attribute) { Message m; for (size_t i = 0; i < str.size(); ++i) { @@ -3504,8 +3080,7 @@ std::string XmlUnitTestResultPrinter::EscapeXml( default: if (IsValidXmlCharacter(ch)) { if (is_attribute && IsNormalizableWhitespace(ch)) - m << "&#x" << String::FormatByte(static_cast(ch)) - << ";"; + m << "&#x" << String::FormatByte(static_cast(ch)) << ";"; else m << ch; } @@ -3519,13 +3094,11 @@ std::string XmlUnitTestResultPrinter::EscapeXml( // Returns the given string with all characters invalid in XML removed. // Currently invalid characters are dropped from the string. An // alternative is to replace them with certain characters such as . or ?. -std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( - const std::string& str) { +std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(const std::string& str) { std::string output; output.reserve(str.size()); for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) - if (IsValidXmlCharacter(*it)) - output.push_back(*it); + if (IsValidXmlCharacter(*it)) output.push_back(*it); return output; } @@ -3560,8 +3133,7 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) { // MINGW provides neither localtime_r nor localtime_s, but uses // Windows' localtime(), which has a thread-local tm buffer. struct tm* tm_ptr = localtime(&seconds); // NOLINT - if (tm_ptr == NULL) - return false; + if (tm_ptr == NULL) return false; *out = *tm_ptr; return true; #else @@ -3573,27 +3145,21 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) { // 8601 format, without the timezone information. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { struct tm time_struct; - if (!PortableLocaltime(static_cast(ms / 1000), &time_struct)) - return ""; + if (!PortableLocaltime(static_cast(ms / 1000), &time_struct)) return ""; // YYYY-MM-DDThh:mm:ss - return StreamableToString(time_struct.tm_year + 1900) + "-" + - String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + - String::FormatIntWidth2(time_struct.tm_mday) + "T" + - String::FormatIntWidth2(time_struct.tm_hour) + ":" + - String::FormatIntWidth2(time_struct.tm_min) + ":" + - String::FormatIntWidth2(time_struct.tm_sec); + return StreamableToString(time_struct.tm_year + 1900) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + + String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_hour) + ":" + + String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_sec); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. -void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, - const char* data) { +void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { const char* segment = data; *stream << ""); if (next_segment != NULL) { - stream->write( - segment, static_cast(next_segment - segment)); + stream->write(segment, static_cast(next_segment - segment)); *stream << "]]>]]>"); } else { @@ -3604,26 +3170,19 @@ void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, *stream << "]]>"; } -void XmlUnitTestResultPrinter::OutputXmlAttribute( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value) { - const std::vector& allowed_names = - GetReservedAttributesForElement(element_name); +void XmlUnitTestResultPrinter::OutputXmlAttribute(std::ostream* stream, const std::string& element_name, + const std::string& name, const std::string& value) { + const std::vector& allowed_names = GetReservedAttributesForElement(element_name); - GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != - allowed_names.end()) - << "Attribute " << name << " is not allowed for element <" << element_name - << ">."; + GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) + << "Attribute " << name << " is not allowed for element <" << element_name << ">."; *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; } // Prints an XML representation of a TestInfo object. // TODO(wan): There is also value in printing properties with the plain printer. -void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, - const char* test_case_name, +void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); const std::string kTestcase = "testcase"; @@ -3632,17 +3191,14 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, OutputXmlAttribute(stream, kTestcase, "name", test_info.name()); if (test_info.value_param() != NULL) { - OutputXmlAttribute(stream, kTestcase, "value_param", - test_info.value_param()); + OutputXmlAttribute(stream, kTestcase, "value_param", test_info.value_param()); } if (test_info.type_param() != NULL) { OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param()); } - OutputXmlAttribute(stream, kTestcase, "status", - test_info.should_run() ? "run" : "notrun"); - OutputXmlAttribute(stream, kTestcase, "time", - FormatTimeInMillisAsSeconds(result.elapsed_time())); + OutputXmlAttribute(stream, kTestcase, "status", test_info.should_run() ? "run" : "notrun"); + OutputXmlAttribute(stream, kTestcase, "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); OutputXmlAttribute(stream, kTestcase, "classname", test_case_name); *stream << TestPropertiesAsXmlAttributes(result); @@ -3653,12 +3209,9 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, if (++failures == 1) { *stream << ">\n"; } - const string location = internal::FormatCompilerIndependentFileLocation( - part.file_name(), part.line_number()); + const string location = internal::FormatCompilerIndependentFileLocation(part.file_name(), part.line_number()); const string summary = location + "\n" + part.summary(); - *stream << " "; + *stream << " "; const string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); *stream << "\n"; @@ -3672,23 +3225,16 @@ void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, } // Prints an XML representation of a TestCase object -void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, - const TestCase& test_case) { +void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, const TestCase& test_case) { const std::string kTestsuite = "testsuite"; *stream << " <" << kTestsuite; OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); - OutputXmlAttribute(stream, kTestsuite, "tests", - StreamableToString(test_case.reportable_test_count())); - OutputXmlAttribute(stream, kTestsuite, "failures", - StreamableToString(test_case.failed_test_count())); - OutputXmlAttribute( - stream, kTestsuite, "disabled", - StreamableToString(test_case.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuite, "tests", StreamableToString(test_case.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuite, "failures", StreamableToString(test_case.failed_test_count())); + OutputXmlAttribute(stream, kTestsuite, "disabled", StreamableToString(test_case.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuite, "errors", "0"); - OutputXmlAttribute(stream, kTestsuite, "time", - FormatTimeInMillisAsSeconds(test_case.elapsed_time())); - *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) - << ">\n"; + OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(test_case.elapsed_time())); + *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) << ">\n"; for (int i = 0; i < test_case.total_test_count(); ++i) { if (test_case.GetTestInfo(i)->is_reportable()) @@ -3698,30 +3244,21 @@ void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, } // Prints an XML summary of unit_test to output stream out. -void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, - const UnitTest& unit_test) { +void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, const UnitTest& unit_test) { const std::string kTestsuites = "testsuites"; *stream << "\n"; *stream << "<" << kTestsuites; - OutputXmlAttribute(stream, kTestsuites, "tests", - StreamableToString(unit_test.reportable_test_count())); - OutputXmlAttribute(stream, kTestsuites, "failures", - StreamableToString(unit_test.failed_test_count())); - OutputXmlAttribute( - stream, kTestsuites, "disabled", - StreamableToString(unit_test.reportable_disabled_test_count())); + OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(unit_test.reportable_test_count())); + OutputXmlAttribute(stream, kTestsuites, "failures", StreamableToString(unit_test.failed_test_count())); + OutputXmlAttribute(stream, kTestsuites, "disabled", StreamableToString(unit_test.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuites, "errors", "0"); - OutputXmlAttribute( - stream, kTestsuites, "timestamp", - FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); - OutputXmlAttribute(stream, kTestsuites, "time", - FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); + OutputXmlAttribute(stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); + OutputXmlAttribute(stream, kTestsuites, "time", FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); if (GTEST_FLAG(shuffle)) { - OutputXmlAttribute(stream, kTestsuites, "random_seed", - StreamableToString(unit_test.random_seed())); + OutputXmlAttribute(stream, kTestsuites, "random_seed", StreamableToString(unit_test.random_seed())); } *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); @@ -3730,21 +3267,19 @@ void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, *stream << ">\n"; for (int i = 0; i < unit_test.total_test_case_count(); ++i) { - if (unit_test.GetTestCase(i)->reportable_test_count() > 0) - PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); + if (unit_test.GetTestCase(i)->reportable_test_count() > 0) PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); } *stream << "\n"; } // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. -std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( - const TestResult& result) { +std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(const TestResult& result) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << " " << property.key() << "=" - << "\"" << EscapeXmlAttribute(property.value()) << "\""; + << "\"" << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } @@ -3778,29 +3313,24 @@ string StreamingListener::UrlEncode(const char* str) { } void StreamingListener::SocketWriter::MakeConnection() { - GTEST_CHECK_(sockfd_ == -1) - << "MakeConnection() can't be called when there is already a connection."; + GTEST_CHECK_(sockfd_ == -1) << "MakeConnection() can't be called when there is already a connection."; addrinfo hints; memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. + hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_socktype = SOCK_STREAM; addrinfo* servinfo = NULL; // Use the getaddrinfo() to get a linked list of IP addresses for // the given host name. - const int error_num = getaddrinfo( - host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); + const int error_num = getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); if (error_num != 0) { - GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " - << gai_strerror(error_num); + GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " << gai_strerror(error_num); } // Loop through all the results and connect to the first we can. - for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; - cur_addr = cur_addr->ai_next) { - sockfd_ = socket( - cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); + for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; cur_addr = cur_addr->ai_next) { + sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); if (sockfd_ != -1) { // Connect the client socket to the server socket. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { @@ -3813,8 +3343,7 @@ void StreamingListener::SocketWriter::MakeConnection() { freeaddrinfo(servinfo); // all done with this structure if (sockfd_ == -1) { - GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " - << host_name_ << ":" << port_num_; + GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " << host_name_ << ":" << port_num_; } } @@ -3825,8 +3354,7 @@ void StreamingListener::SocketWriter::MakeConnection() { // Pushes the given source file location and message onto a per-thread // trace stack maintained by Google Test. -ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) - GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { +ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { TraceInfo trace; trace.file = file; trace.line = line; @@ -3836,21 +3364,13 @@ ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) } // Pops the info pushed by the c'tor. -ScopedTrace::~ScopedTrace() - GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { - UnitTest::GetInstance()->PopGTestTrace(); -} - +ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { UnitTest::GetInstance()->PopGTestTrace(); } // class OsStackTraceGetter -const char* const OsStackTraceGetterInterface::kElidedFramesMarker = - "... " GTEST_NAME_ " internal frames ..."; +const char* const OsStackTraceGetterInterface::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; -string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, - int /*skip_count*/) { - return ""; -} +string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, int /*skip_count*/) { return ""; } void OsStackTraceGetter::UponLeavingGTest() {} @@ -3888,10 +3408,7 @@ class ScopedPrematureExitFile { // class TestEventListeners TestEventListeners::TestEventListeners() - : repeater_(new internal::TestEventRepeater()), - default_result_printer_(NULL), - default_xml_generator_(NULL) { -} + : repeater_(new internal::TestEventRepeater()), default_result_printer_(NULL), default_xml_generator_(NULL) {} TestEventListeners::~TestEventListeners() { delete repeater_; } @@ -3899,9 +3416,7 @@ TestEventListeners::~TestEventListeners() { delete repeater_; } // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the user. -void TestEventListeners::Append(TestEventListener* listener) { - repeater_->Append(listener); -} +void TestEventListeners::Append(TestEventListener* listener) { repeater_->Append(listener); } // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns @@ -3929,8 +3444,7 @@ void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { // list. delete Release(default_result_printer_); default_result_printer_ = listener; - if (listener != NULL) - Append(listener); + if (listener != NULL) Append(listener); } } @@ -3945,20 +3459,15 @@ void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { // list. delete Release(default_xml_generator_); default_xml_generator_ = listener; - if (listener != NULL) - Append(listener); + if (listener != NULL) Append(listener); } } // Controls whether events will be forwarded by the repeater to the // listeners in the list. -bool TestEventListeners::EventForwardingEnabled() const { - return repeater_->forwarding_enabled(); -} +bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } -void TestEventListeners::SuppressEventForwarding() { - repeater_->set_forwarding_enabled(false); -} +void TestEventListeners::SuppressEventForwarding() { repeater_->set_forwarding_enabled(false); } // class UnitTest @@ -3991,48 +3500,32 @@ UnitTest* UnitTest::GetInstance() { } // Gets the number of successful test cases. -int UnitTest::successful_test_case_count() const { - return impl()->successful_test_case_count(); -} +int UnitTest::successful_test_case_count() const { return impl()->successful_test_case_count(); } // Gets the number of failed test cases. -int UnitTest::failed_test_case_count() const { - return impl()->failed_test_case_count(); -} +int UnitTest::failed_test_case_count() const { return impl()->failed_test_case_count(); } // Gets the number of all test cases. -int UnitTest::total_test_case_count() const { - return impl()->total_test_case_count(); -} +int UnitTest::total_test_case_count() const { return impl()->total_test_case_count(); } // Gets the number of all test cases that contain at least one test // that should run. -int UnitTest::test_case_to_run_count() const { - return impl()->test_case_to_run_count(); -} +int UnitTest::test_case_to_run_count() const { return impl()->test_case_to_run_count(); } // Gets the number of successful tests. -int UnitTest::successful_test_count() const { - return impl()->successful_test_count(); -} +int UnitTest::successful_test_count() const { return impl()->successful_test_count(); } // Gets the number of failed tests. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } // Gets the number of disabled tests that will be reported in the XML report. -int UnitTest::reportable_disabled_test_count() const { - return impl()->reportable_disabled_test_count(); -} +int UnitTest::reportable_disabled_test_count() const { return impl()->reportable_disabled_test_count(); } // Gets the number of disabled tests. -int UnitTest::disabled_test_count() const { - return impl()->disabled_test_count(); -} +int UnitTest::disabled_test_count() const { return impl()->disabled_test_count(); } // Gets the number of tests to be printed in the XML report. -int UnitTest::reportable_test_count() const { - return impl()->reportable_test_count(); -} +int UnitTest::reportable_test_count() const { return impl()->reportable_test_count(); } // Gets the number of all tests. int UnitTest::total_test_count() const { return impl()->total_test_count(); } @@ -4042,14 +3535,10 @@ int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } // Gets the time of the test program start, in ms from the start of the // UNIX epoch. -internal::TimeInMillis UnitTest::start_timestamp() const { - return impl()->start_timestamp(); -} +internal::TimeInMillis UnitTest::start_timestamp() const { return impl()->start_timestamp(); } // Gets the elapsed time, in milliseconds. -internal::TimeInMillis UnitTest::elapsed_time() const { - return impl()->elapsed_time(); -} +internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } // Returns true iff the unit test passed (i.e. all test cases passed). bool UnitTest::Passed() const { return impl()->Passed(); } @@ -4060,27 +3549,19 @@ bool UnitTest::Failed() const { return impl()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. -const TestCase* UnitTest::GetTestCase(int i) const { - return impl()->GetTestCase(i); -} +const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } // Returns the TestResult containing information on test failures and // properties logged outside of individual test cases. -const TestResult& UnitTest::ad_hoc_test_result() const { - return *impl()->ad_hoc_test_result(); -} +const TestResult& UnitTest::ad_hoc_test_result() const { return *impl()->ad_hoc_test_result(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. -TestCase* UnitTest::GetMutableTestCase(int i) { - return impl()->GetMutableTestCase(i); -} +TestCase* UnitTest::GetMutableTestCase(int i) { return impl()->GetMutableTestCase(i); } // Returns the list of event listeners that can be used to track events // inside Google Test. -TestEventListeners& UnitTest::listeners() { - return *impl()->listeners(); -} +TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in the @@ -4105,12 +3586,9 @@ Environment* UnitTest::AddEnvironment(Environment* env) { // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. -void UnitTest::AddTestPartResult( - TestPartResult::Type result_type, - const char* file_name, - int line_number, - const std::string& message, - const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { +void UnitTest::AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, + const std::string& message, const std::string& os_stack_trace) + GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; @@ -4118,11 +3596,9 @@ void UnitTest::AddTestPartResult( if (impl_->gtest_trace_stack().size() > 0) { msg << "\n" << GTEST_NAME_ << " trace:"; - for (int i = static_cast(impl_->gtest_trace_stack().size()); - i > 0; --i) { + for (int i = static_cast(impl_->gtest_trace_stack().size()); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; - msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) - << " " << trace.message; + msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) << " " << trace.message; } } @@ -4130,11 +3606,8 @@ void UnitTest::AddTestPartResult( msg << internal::kStackTraceMarker << os_stack_trace; } - const TestPartResult result = - TestPartResult(result_type, file_name, line_number, - msg.GetString().c_str()); - impl_->GetTestPartResultReporterForCurrentThread()-> - ReportTestPartResult(result); + const TestPartResult result = TestPartResult(result_type, file_name, line_number, msg.GetString().c_str()); + impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(result); if (result_type != TestPartResult::kSuccess) { // gtest_break_on_failure takes precedence over @@ -4172,8 +3645,7 @@ void UnitTest::AddTestPartResult( // from SetUpTestCase or TearDownTestCase, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. -void UnitTest::RecordProperty(const std::string& key, - const std::string& value) { +void UnitTest::RecordProperty(const std::string& key, const std::string& value) { impl_->RecordProperty(TestProperty(key, value)); } @@ -4183,8 +3655,7 @@ void UnitTest::RecordProperty(const std::string& key, // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { - const bool in_death_test_child_process = - internal::GTEST_FLAG(internal_run_death_test).length() > 0; + const bool in_death_test_child_process = internal::GTEST_FLAG(internal_run_death_test).length() > 0; // Google Test implements this protocol for catching that a test // program exits before returning control to Google Test: @@ -4208,8 +3679,7 @@ int UnitTest::Run() { // that understands the premature-exit-file protocol to report the // test as having failed. const internal::ScopedPrematureExitFile premature_exit_file( - in_death_test_child_process ? - NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); + in_death_test_child_process ? NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. @@ -4221,20 +3691,19 @@ int UnitTest::Run() { // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { -# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT +# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // SetErrorMode doesn't exist on CE. - SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | - SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); -# endif // !GTEST_OS_WINDOWS_MOBILE + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); +# endif // !GTEST_OS_WINDOWS_MOBILE -# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE +# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); -# endif +# endif -# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE +# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement @@ -4247,37 +3716,32 @@ int UnitTest::Run() { // TODO(vladl@google.com): find a way to suppress the abort dialog() in the // debug mode when compiled with VC 7.1 or lower. if (!GTEST_FLAG(break_on_failure)) - _set_abort_behavior( - 0x0, // Clear the following flags: - _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. -# endif + _set_abort_behavior(0x0, // Clear the following flags: + _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. +# endif } #endif // GTEST_HAS_SEH - return internal::HandleExceptionsInMethodIfSupported( - impl(), - &internal::UnitTestImpl::RunAllTests, - "auxiliary test code (environments or event listeners)") ? 0 : 1; + return internal::HandleExceptionsInMethodIfSupported(impl(), &internal::UnitTestImpl::RunAllTests, + "auxiliary test code (environments or event listeners)") + ? 0 + : 1; } // Returns the working directory when the first TEST() or TEST_F() was // executed. -const char* UnitTest::original_working_dir() const { - return impl_->original_working_dir_.c_str(); -} +const char* UnitTest::original_working_dir() const { return impl_->original_working_dir_.c_str(); } // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. -const TestCase* UnitTest::current_test_case() const - GTEST_LOCK_EXCLUDED_(mutex_) { +const TestCase* UnitTest::current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_case(); } // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. -const TestInfo* UnitTest::current_test_info() const - GTEST_LOCK_EXCLUDED_(mutex_) { +const TestInfo* UnitTest::current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_info(); } @@ -4288,34 +3752,26 @@ int UnitTest::random_seed() const { return impl_->random_seed(); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. -internal::ParameterizedTestCaseRegistry& - UnitTest::parameterized_test_registry() - GTEST_LOCK_EXCLUDED_(mutex_) { +internal::ParameterizedTestCaseRegistry& UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { return impl_->parameterized_test_registry(); } #endif // GTEST_HAS_PARAM_TEST // Creates an empty UnitTest. -UnitTest::UnitTest() { - impl_ = new internal::UnitTestImpl(this); -} +UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); } // Destructor of UnitTest. -UnitTest::~UnitTest() { - delete impl_; -} +UnitTest::~UnitTest() { delete impl_; } // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. -void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) - GTEST_LOCK_EXCLUDED_(mutex_) { +void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().push_back(trace); } // Pops a trace from the per-thread Google Test trace stack. -void UnitTest::PopGTestTrace() - GTEST_LOCK_EXCLUDED_(mutex_) { +void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } @@ -4325,13 +3781,10 @@ namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : parent_(parent), GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) - default_global_test_part_result_reporter_(this), + default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), - GTEST_DISABLE_MSC_WARNINGS_POP_() - global_test_part_result_repoter_( - &default_global_test_part_result_reporter_), - per_thread_test_part_result_reporter_( - &default_per_thread_test_part_result_reporter_), + GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(&default_global_test_part_result_reporter_), + per_thread_test_part_result_reporter_(&default_per_thread_test_part_result_reporter_), #if GTEST_HAS_PARAM_TEST parameterized_test_registry_(), parameterized_tests_registered_(false), @@ -4343,7 +3796,7 @@ UnitTestImpl::UnitTestImpl(UnitTest* parent) os_stack_trace_getter_(NULL), post_flag_parse_init_performed_(false), random_seed_(0), // Will be overridden by the flag before first use. - random_(0), // Will be reseeded before first use. + random_(0), // Will be reseeded before first use. start_timestamp_(0), elapsed_time_(0), #if GTEST_HAS_DEATH_TEST @@ -4390,8 +3843,7 @@ void UnitTestImpl::RecordProperty(const TestProperty& test_property) { // Disables event forwarding if the control is currently in a death test // subprocess. Must not be called before InitGoogleTest. void UnitTestImpl::SuppressTestEventsIfInSubprocess() { - if (internal_run_death_test_flag_.get() != NULL) - listeners()->SuppressEventForwarding(); + if (internal_run_death_test_flag_.get() != NULL) listeners()->SuppressEventForwarding(); } #endif // GTEST_HAS_DEATH_TEST @@ -4400,11 +3852,10 @@ void UnitTestImpl::SuppressTestEventsIfInSubprocess() { void UnitTestImpl::ConfigureXmlOutput() { const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml") { - listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); + listeners()->SetDefaultXmlGenerator( + new XmlUnitTestResultPrinter(UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (output_format != "") { - printf("WARNING: unrecognized output format \"%s\" ignored.\n", - output_format.c_str()); + printf("WARNING: unrecognized output format \"%s\" ignored.\n", output_format.c_str()); fflush(stdout); } } @@ -4417,11 +3868,9 @@ void UnitTestImpl::ConfigureStreamingOutput() { if (!target.empty()) { const size_t pos = target.find(':'); if (pos != std::string::npos) { - listeners()->Append(new StreamingListener(target.substr(0, pos), - target.substr(pos+1))); + listeners()->Append(new StreamingListener(target.substr(0, pos), target.substr(pos + 1))); } else { - printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", - target.c_str()); + printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", target.c_str()); fflush(stdout); } } @@ -4475,8 +3924,7 @@ void UnitTestImpl::PostFlagParsingInit() { class TestCaseNameIs { public: // Constructor. - explicit TestCaseNameIs(const std::string& name) - : name_(name) {} + explicit TestCaseNameIs(const std::string& name) : name_(name) {} // Returns true iff the name of test_case matches name_. bool operator()(const TestCase* test_case) const { @@ -4499,32 +3947,25 @@ class TestCaseNameIs { // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case -TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, - const char* type_param, - Test::SetUpTestCaseFunc set_up_tc, - Test::TearDownTestCaseFunc tear_down_tc) { +TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, const char* type_param, + Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) { // Can we find a TestCase with the given name? const std::vector::const_iterator test_case = - std::find_if(test_cases_.begin(), test_cases_.end(), - TestCaseNameIs(test_case_name)); + std::find_if(test_cases_.begin(), test_cases_.end(), TestCaseNameIs(test_case_name)); - if (test_case != test_cases_.end()) - return *test_case; + if (test_case != test_cases_.end()) return *test_case; // No. Let's create one. - TestCase* const new_test_case = - new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); + TestCase* const new_test_case = new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); // Is this a death test case? - if (internal::UnitTestOptions::MatchesFilter(test_case_name, - kDeathTestCaseFilter)) { + if (internal::UnitTestOptions::MatchesFilter(test_case_name, kDeathTestCaseFilter)) { // Yes. Inserts the test case after the last death test case // defined so far. This only works when the test cases haven't // been shuffled. Otherwise we may end up running a death test // after a non-death test. ++last_death_test_case_; - test_cases_.insert(test_cases_.begin() + last_death_test_case_, - new_test_case); + test_cases_.insert(test_cases_.begin() + last_death_test_case_, new_test_case); } else { // No. Appends to the end of the list. test_cases_.push_back(new_test_case); @@ -4558,8 +3999,7 @@ bool UnitTestImpl::RunAllTests() { } // Do not run any test if the --help flag was specified. - if (g_help_flag) - return true; + if (g_help_flag) return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. @@ -4576,21 +4016,18 @@ bool UnitTestImpl::RunAllTests() { #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); -# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) +# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); } -# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) -#endif // GTEST_HAS_DEATH_TEST +# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) +#endif // GTEST_HAS_DEATH_TEST - const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, - in_subprocess_for_death_test); + const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, in_subprocess_for_death_test); // Compares the full test names with the filter to decide which // tests to run. - const bool has_tests_to_run = FilterTests(should_shard - ? HONOR_SHARDING_PROTOCOL - : IGNORE_SHARDING_PROTOCOL) > 0; + const bool has_tests_to_run = FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL : IGNORE_SHARDING_PROTOCOL) > 0; // Lists the tests and exits if the --gtest_list_tests flag was specified. if (GTEST_FLAG(list_tests)) { @@ -4599,8 +4036,7 @@ bool UnitTestImpl::RunAllTests() { return true; } - random_seed_ = GTEST_FLAG(shuffle) ? - GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; + random_seed_ = GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; // True iff at least one test has failed. bool failed = false; @@ -4644,16 +4080,14 @@ bool UnitTestImpl::RunAllTests() { // Runs the tests only if there was no fatal failure during global // set-up. if (!Test::HasFatalFailure()) { - for (int test_index = 0; test_index < total_test_case_count(); - test_index++) { + for (int test_index = 0; test_index < total_test_case_count(); test_index++) { GetMutableTestCase(test_index)->Run(); } } // Tears down all environments in reverse order afterwards. repeater->OnEnvironmentsTearDownStart(*parent_); - std::for_each(environments_.rbegin(), environments_.rend(), - TearDownEnvironment); + std::for_each(environments_.rbegin(), environments_.rend(), TearDownEnvironment); repeater->OnEnvironmentsTearDownEnd(*parent_); } @@ -4712,9 +4146,7 @@ void WriteToShardStatusFileIfNeeded() { // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. -bool ShouldShard(const char* total_shards_env, - const char* shard_index_env, - bool in_subprocess_for_death_test) { +bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; } @@ -4725,27 +4157,21 @@ bool ShouldShard(const char* total_shards_env, if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestShardIndex << " = " << shard_index - << ", but have left " << kTestTotalShards << " unset.\n"; + const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex << " = " + << shard_index << ", but have left " << kTestTotalShards << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestTotalShards << " = " << total_shards - << ", but have left " << kTestShardIndex << " unset.\n"; + const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards << " = " + << total_shards << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { - const Message msg = Message() - << "Invalid environment variables: we require 0 <= " - << kTestShardIndex << " < " << kTestTotalShards - << ", but you have " << kTestShardIndex << "=" << shard_index - << ", " << kTestTotalShards << "=" << total_shards << ".\n"; + const Message msg = Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < " + << kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index + << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); @@ -4764,8 +4190,7 @@ Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { } Int32 result; - if (!ParseInt32(Message() << "The value of environment variable " << var, - str_val, &result)) { + if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); } return result; @@ -4787,10 +4212,8 @@ bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. // Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { - const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestTotalShards, -1) : -1; - const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestShardIndex, -1) : -1; + const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestTotalShards, -1) : -1; + const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestShardIndex, -1) : -1; // num_runnable_tests are the number of tests that will // run across all shards (i.e., match filter and are not disabled). @@ -4800,7 +4223,7 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { int num_selected_tests = 0; for (size_t i = 0; i < test_cases_.size(); i++) { TestCase* const test_case = test_cases_[i]; - const std::string &test_case_name = test_case->name(); + const std::string& test_case_name = test_case->name(); test_case->set_should_run(false); for (size_t j = 0; j < test_case->test_info_list().size(); j++) { @@ -4808,26 +4231,17 @@ int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const std::string test_name(test_info->name()); // A test is disabled if test case name or test name matches // kDisableTestFilter. - const bool is_disabled = - internal::UnitTestOptions::MatchesFilter(test_case_name, - kDisableTestFilter) || - internal::UnitTestOptions::MatchesFilter(test_name, - kDisableTestFilter); + const bool is_disabled = internal::UnitTestOptions::MatchesFilter(test_case_name, kDisableTestFilter) || + internal::UnitTestOptions::MatchesFilter(test_name, kDisableTestFilter); test_info->is_disabled_ = is_disabled; - const bool matches_filter = - internal::UnitTestOptions::FilterMatchesTest(test_case_name, - test_name); + const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(test_case_name, test_name); test_info->matches_filter_ = matches_filter; - const bool is_runnable = - (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && - matches_filter; + const bool is_runnable = (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && matches_filter; - const bool is_selected = is_runnable && - (shard_tests == IGNORE_SHARDING_PROTOCOL || - ShouldRunTestOnShard(total_shards, shard_index, - num_runnable_tests)); + const bool is_selected = is_runnable && (shard_tests == IGNORE_SHARDING_PROTOCOL || + ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests)); num_runnable_tests += is_runnable; num_selected_tests += is_selected; @@ -4871,8 +4285,7 @@ void UnitTestImpl::ListTestsMatchingFilter() { bool printed_test_case_name = false; for (size_t j = 0; j < test_case->test_info_list().size(); j++) { - const TestInfo* const test_info = - test_case->test_info_list()[j]; + const TestInfo* const test_info = test_case->test_info_list()[j]; if (test_info->matches_filter_) { if (!printed_test_case_name) { printed_test_case_name = true; @@ -4904,8 +4317,7 @@ void UnitTestImpl::ListTestsMatchingFilter() { // Does nothing if the input and the current OS stack trace getter are // the same; otherwise, deletes the old getter and makes the input the // current getter. -void UnitTestImpl::set_os_stack_trace_getter( - OsStackTraceGetterInterface* getter) { +void UnitTestImpl::set_os_stack_trace_getter(OsStackTraceGetterInterface* getter) { if (os_stack_trace_getter_ != getter) { delete os_stack_trace_getter_; os_stack_trace_getter_ = getter; @@ -4930,8 +4342,7 @@ OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* UnitTestImpl::current_test_result() { - return current_test_info_ ? - &(current_test_info_->result_) : &ad_hoc_test_result_; + return current_test_info_ ? &(current_test_info_->result_) : &ad_hoc_test_result_; } // Shuffles all test cases, and the tests within each test case, @@ -4941,8 +4352,7 @@ void UnitTestImpl::ShuffleTests() { ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); // Shuffles the non-death test cases. - ShuffleRange(random(), last_death_test_case_ + 1, - static_cast(test_cases_.size()), &test_case_indices_); + ShuffleRange(random(), last_death_test_case_ + 1, static_cast(test_cases_.size()), &test_case_indices_); // Shuffles the tests inside each test case. for (size_t i = 0; i < test_cases_.size(); i++) { @@ -4970,8 +4380,7 @@ void UnitTestImpl::UnshuffleTests() { // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, - int skip_count) { +std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { // We pass skip_count + 1 to skip this wrapper function in addition // to what the user really wants to skip. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); @@ -4981,7 +4390,7 @@ std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; -} +} // namespace bool IsTrue(bool condition) { return condition; } @@ -4989,8 +4398,7 @@ bool AlwaysTrue() { #if GTEST_HAS_EXCEPTIONS // This condition is always false so AlwaysTrue() never actually throws, // but it makes the compiler think that it may throw. - if (IsTrue(false)) - throw ClassUniqueToAlwaysTrue(); + if (IsTrue(false)) throw ClassUniqueToAlwaysTrue(); #endif // GTEST_HAS_EXCEPTIONS return true; } @@ -5012,9 +4420,7 @@ bool SkipPrefix(const char* prefix, const char** pstr) { // part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. -const char* ParseFlagValue(const char* str, - const char* flag, - bool def_optional) { +const char* ParseFlagValue(const char* str, const char* flag, bool def_optional) { // str and flag must not be NULL. if (str == NULL || flag == NULL) return NULL; @@ -5075,8 +4481,7 @@ bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { if (value_str == NULL) return false; // Sets *value to the value of the flag. - return ParseInt32(Message() << "The value of flag --" << flag, - value_str, value); + return ParseInt32(Message() << "The value of flag --" << flag, value_str, value); } // Parses a string for a string flag, in the form of @@ -5103,12 +4508,9 @@ bool ParseStringFlag(const char* str, const char* flag, std::string* value) { // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // internal flags and do not trigger the help message. static bool HasGoogleTestFlagPrefix(const char* str) { - return (SkipPrefix("--", &str) || - SkipPrefix("-", &str) || - SkipPrefix("/", &str)) && + return (SkipPrefix("--", &str) || SkipPrefix("-", &str) || SkipPrefix("/", &str)) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && - (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || - SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); + (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); } // Prints a string containing code-encoded text. The following escape @@ -5157,105 +4559,112 @@ static void PrintColorEncoded(const char* str) { } static const char kColorEncodedHelpMessage[] = -"This program contains tests written using " GTEST_NAME_ ". You can use the\n" -"following command line flags to control its behavior:\n" -"\n" -"Test Selection:\n" -" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" -" List the names of all tests instead of running them. The name of\n" -" TEST(Foo, Bar) is \"Foo.Bar\".\n" -" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" + "This program contains tests written using " GTEST_NAME_ + ". You can use the\n" + "following command line flags to control its behavior:\n" + "\n" + "Test Selection:\n" + " @G--" GTEST_FLAG_PREFIX_ + "list_tests@D\n" + " List the names of all tests instead of running them. The name of\n" + " TEST(Foo, Bar) is \"Foo.Bar\".\n" + " @G--" GTEST_FLAG_PREFIX_ + "filter=@YPOSTIVE_PATTERNS" "[@G-@YNEGATIVE_PATTERNS]@D\n" -" Run only the tests whose name matches one of the positive patterns but\n" -" none of the negative patterns. '?' matches any single character; '*'\n" -" matches any substring; ':' separates two patterns.\n" -" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" -" Run all disabled tests too.\n" -"\n" -"Test Execution:\n" -" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" -" Run the tests repeatedly; use a negative count to repeat forever.\n" -" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" -" Randomize tests' orders on every iteration.\n" -" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" -" Random number seed to use for shuffling test orders (between 1 and\n" -" 99999, or 0 to use a seed based on the current time).\n" -"\n" -"Test Output:\n" -" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" -" Enable/disable colored output. The default is @Gauto@D.\n" -" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" -" Don't print the elapsed time of each test.\n" -" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" - GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" -" Generate an XML report in the given directory or with the given file\n" -" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" + " Run only the tests whose name matches one of the positive patterns but\n" + " none of the negative patterns. '?' matches any single character; '*'\n" + " matches any substring; ':' separates two patterns.\n" + " @G--" GTEST_FLAG_PREFIX_ + "also_run_disabled_tests@D\n" + " Run all disabled tests too.\n" + "\n" + "Test Execution:\n" + " @G--" GTEST_FLAG_PREFIX_ + "repeat=@Y[COUNT]@D\n" + " Run the tests repeatedly; use a negative count to repeat forever.\n" + " @G--" GTEST_FLAG_PREFIX_ + "shuffle@D\n" + " Randomize tests' orders on every iteration.\n" + " @G--" GTEST_FLAG_PREFIX_ + "random_seed=@Y[NUMBER]@D\n" + " Random number seed to use for shuffling test orders (between 1 and\n" + " 99999, or 0 to use a seed based on the current time).\n" + "\n" + "Test Output:\n" + " @G--" GTEST_FLAG_PREFIX_ + "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" + " Enable/disable colored output. The default is @Gauto@D.\n" + " -@G-" GTEST_FLAG_PREFIX_ + "print_time=0@D\n" + " Don't print the elapsed time of each test.\n" + " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_ + "@Y|@G:@YFILE_PATH]@D\n" + " Generate an XML report in the given directory or with the given file\n" + " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" #if GTEST_CAN_STREAM_RESULTS_ -" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" -" Stream test results to the given server.\n" + " @G--" GTEST_FLAG_PREFIX_ + "stream_result_to=@YHOST@G:@YPORT@D\n" + " Stream test results to the given server.\n" #endif // GTEST_CAN_STREAM_RESULTS_ -"\n" -"Assertion Behavior:\n" + "\n" + "Assertion Behavior:\n" #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS -" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" -" Set the default death test style.\n" + " @G--" GTEST_FLAG_PREFIX_ + "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" + " Set the default death test style.\n" #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS -" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" -" Turn assertion failures into debugger break-points.\n" -" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" -" Turn assertion failures into C++ exceptions.\n" -" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" -" Do not report exceptions as test failures. Instead, allow them\n" -" to crash the program or throw a pop-up (on Windows).\n" -"\n" -"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " + " @G--" GTEST_FLAG_PREFIX_ + "break_on_failure@D\n" + " Turn assertion failures into debugger break-points.\n" + " @G--" GTEST_FLAG_PREFIX_ + "throw_on_failure@D\n" + " Turn assertion failures into C++ exceptions.\n" + " @G--" GTEST_FLAG_PREFIX_ + "catch_exceptions=0@D\n" + " Do not report exceptions as test failures. Instead, allow them\n" + " to crash the program or throw a pop-up (on Windows).\n" + "\n" + "Except for @G--" GTEST_FLAG_PREFIX_ + "list_tests@D, you can alternatively set " "the corresponding\n" -"environment variable of a flag (all letters in upper-case). For example, to\n" -"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ + "environment variable of a flag (all letters in upper-case). For example, to\n" + "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ "color=no@D or set\n" -"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" -"\n" -"For more information, please read the " GTEST_NAME_ " documentation at\n" -"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" -"(not one in your own code or tests), please report it to\n" -"@G<" GTEST_DEV_EMAIL_ ">@D.\n"; + "the @G" GTEST_FLAG_PREFIX_UPPER_ + "COLOR@D environment variable to @Gno@D.\n" + "\n" + "For more information, please read the " GTEST_NAME_ + " documentation at\n" + "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ + "\n" + "(not one in your own code or tests), please report it to\n" + "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; bool ParseGoogleTestFlag(const char* const arg) { - return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, - >EST_FLAG(also_run_disabled_tests)) || - ParseBoolFlag(arg, kBreakOnFailureFlag, - >EST_FLAG(break_on_failure)) || - ParseBoolFlag(arg, kCatchExceptionsFlag, - >EST_FLAG(catch_exceptions)) || - ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || - ParseStringFlag(arg, kDeathTestStyleFlag, - >EST_FLAG(death_test_style)) || - ParseBoolFlag(arg, kDeathTestUseFork, - >EST_FLAG(death_test_use_fork)) || - ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || - ParseStringFlag(arg, kInternalRunDeathTestFlag, - >EST_FLAG(internal_run_death_test)) || - ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || - ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || - ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || - ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || - ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || - ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || - ParseInt32Flag(arg, kStackTraceDepthFlag, - >EST_FLAG(stack_trace_depth)) || - ParseStringFlag(arg, kStreamResultToFlag, - >EST_FLAG(stream_result_to)) || - ParseBoolFlag(arg, kThrowOnFailureFlag, - >EST_FLAG(throw_on_failure)); + return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, >EST_FLAG(also_run_disabled_tests)) || + ParseBoolFlag(arg, kBreakOnFailureFlag, >EST_FLAG(break_on_failure)) || + ParseBoolFlag(arg, kCatchExceptionsFlag, >EST_FLAG(catch_exceptions)) || + ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || + ParseStringFlag(arg, kDeathTestStyleFlag, >EST_FLAG(death_test_style)) || + ParseBoolFlag(arg, kDeathTestUseFork, >EST_FLAG(death_test_use_fork)) || + ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || + ParseStringFlag(arg, kInternalRunDeathTestFlag, >EST_FLAG(internal_run_death_test)) || + ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || + ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || + ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || + ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || + ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || + ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || + ParseInt32Flag(arg, kStackTraceDepthFlag, >EST_FLAG(stack_trace_depth)) || + ParseStringFlag(arg, kStreamResultToFlag, >EST_FLAG(stream_result_to)) || + ParseBoolFlag(arg, kThrowOnFailureFlag, >EST_FLAG(throw_on_failure)); } #if GTEST_USE_OWN_FLAGFILE_FLAG_ void LoadFlagsFromFile(const std::string& path) { FILE* flagfile = posix::FOpen(path.c_str(), "r"); if (!flagfile) { - fprintf(stderr, - "Unable to open file \"%s\"\n", - GTEST_FLAG(flagfile).c_str()); + fprintf(stderr, "Unable to open file \"%s\"\n", GTEST_FLAG(flagfile).c_str()); fflush(stderr); exit(EXIT_FAILURE); } @@ -5264,10 +4673,8 @@ void LoadFlagsFromFile(const std::string& path) { std::vector lines; SplitString(contents, '\n', &lines); for (size_t i = 0; i < lines.size(); ++i) { - if (lines[i].empty()) - continue; - if (!ParseGoogleTestFlag(lines[i].c_str())) - g_help_flag = true; + if (lines[i].empty()) continue; + if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true; } } #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ @@ -5293,8 +4700,7 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { LoadFlagsFromFile(GTEST_FLAG(flagfile)); remove_flag = true; #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ - } else if (arg_string == "--help" || arg_string == "-h" || - arg_string == "-?" || arg_string == "/?" || + } else if (arg_string == "--help" || arg_string == "-h" || arg_string == "-?" || arg_string == "/?" || HasGoogleTestFlagPrefix(arg)) { // Both help flag and unrecognized Google Test flags (excluding // internal ones) trigger help display. @@ -5329,12 +4735,8 @@ void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { // Parses the command line for Google Test flags, without initializing // other parts of Google Test. -void ParseGoogleTestFlagsOnly(int* argc, char** argv) { - ParseGoogleTestFlagsOnlyImpl(argc, argv); -} -void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { - ParseGoogleTestFlagsOnlyImpl(argc, argv); -} +void ParseGoogleTestFlagsOnly(int* argc, char** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } +void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } // The internal implementation of InitGoogleTest(). // @@ -5370,7 +4772,7 @@ void InitGoogleTestImpl(int* argc, CharType** argv) { void InitGoogleTest(int* argc, char** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } @@ -5380,7 +4782,7 @@ void InitGoogleTest(int* argc, char** argv) { void InitGoogleTest(int* argc, wchar_t** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) +#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } diff --git a/src/net/test/gtest/src/gtest_main.cc b/src/net/test/gtest/src/gtest_main.cc index f302822552..f82e42ffc6 100644 --- a/src/net/test/gtest/src/gtest_main.cc +++ b/src/net/test/gtest/src/gtest_main.cc @@ -31,7 +31,7 @@ #include "gtest/gtest.h" -GTEST_API_ int main(int argc, char **argv) { +GTEST_API_ int main(int argc, char** argv) { printf("Running main() from gtest_main.cc\n"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/src/pika.cc b/src/pika.cc index e227ff1372..6eeefa5cda 100644 --- a/src/pika.cc +++ b/src/pika.cc @@ -3,22 +3,22 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include #include +#include #include -#include "pstd/include/env.h" -#include "include/pika_rm.h" -#include "include/pika_server.h" +#include "include/build_version.h" +#include "include/pika_cmd_table_manager.h" #include "include/pika_command.h" #include "include/pika_conf.h" #include "include/pika_define.h" +#include "include/pika_rm.h" +#include "include/pika_server.h" #include "include/pika_version.h" -#include "include/pika_cmd_table_manager.h" -#include "include/build_version.h" +#include "pstd/include/env.h" #ifdef TCMALLOC_EXTENSION -#include +# include #endif PikaConf* g_pika_conf; @@ -28,13 +28,12 @@ PikaReplicaManager* g_pika_rm; PikaCmdTableManager* g_pika_cmd_table_manager; static void version() { - char version[32]; - snprintf(version, sizeof(version), "%d.%d.%d", PIKA_MAJOR, - PIKA_MINOR, PIKA_PATCH); - std::cout << "-----------Pika server----------" << std::endl; - std::cout << "pika_version: " << version << std::endl; - std::cout << pika_build_git_sha << std::endl; - std::cout << "pika_build_compile_date: " << pika_build_compile_date << std::endl; + char version[32]; + snprintf(version, sizeof(version), "%d.%d.%d", PIKA_MAJOR, PIKA_MINOR, PIKA_PATCH); + std::cout << "-----------Pika server----------" << std::endl; + std::cout << "pika_version: " << version << std::endl; + std::cout << pika_build_git_sha << std::endl; + std::cout << "pika_build_compile_date: " << pika_build_compile_date << std::endl; } static void PikaConfInit(const std::string& path) { @@ -51,7 +50,7 @@ static void PikaConfInit(const std::string& path) { static void PikaGlogInit() { if (!pstd::FileExists(g_pika_conf->log_path())) { - pstd::CreatePath(g_pika_conf->log_path()); + pstd::CreatePath(g_pika_conf->log_path()); } if (!g_pika_conf->daemonize()) { @@ -66,7 +65,7 @@ static void PikaGlogInit() { static void daemonize() { if (fork() != 0) exit(0); /* parent exits */ - setsid(); /* create a new session */ + setsid(); /* create a new session */ } static void close_std() { @@ -91,9 +90,9 @@ static void create_pid_file(void) { path = kPikaPidFile; } - FILE *fp = fopen(path.c_str(), "w"); + FILE* fp = fopen(path.c_str(), "w"); if (fp) { - fprintf(fp,"%d\n",(int)getpid()); + fprintf(fp, "%d\n", (int)getpid()); fclose(fp); } } @@ -111,22 +110,19 @@ static void PikaSignalSetup() { signal(SIGTERM, &IntSigHandle); } -static void usage() -{ - char version[32]; - snprintf(version, sizeof(version), "%d.%d.%d", PIKA_MAJOR, - PIKA_MINOR, PIKA_PATCH); - fprintf(stderr, - "Pika module %s\n" - "usage: pika [-hv] [-c conf/file]\n" - "\t-h -- show this help\n" - "\t-c conf/file -- config file \n" - " example: ./output/bin/pika -c ./conf/pika.conf\n", - version - ); +static void usage() { + char version[32]; + snprintf(version, sizeof(version), "%d.%d.%d", PIKA_MAJOR, PIKA_MINOR, PIKA_PATCH); + fprintf(stderr, + "Pika module %s\n" + "usage: pika [-hv] [-c conf/file]\n" + "\t-h -- show this help\n" + "\t-c conf/file -- config file \n" + " example: ./output/bin/pika -c ./conf/pika.conf\n", + version); } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { if (argc != 2 && argc != 3) { usage(); exit(-1); @@ -154,7 +150,7 @@ int main(int argc, char *argv[]) { } if (path_opt == false) { - fprintf (stderr, "Please specify the conf file path\n" ); + fprintf(stderr, "Please specify the conf file path\n"); usage(); exit(-1); } @@ -172,9 +168,12 @@ int main(int argc, char *argv[]) { limit.rlim_cur = maxfiles; limit.rlim_max = maxfiles; if (setrlimit(RLIMIT_NOFILE, &limit) != -1) { - LOG(WARNING) << "your 'limit -n ' of " << old_limit << " is not enough for Redis to start. pika have successfully reconfig it to " << limit.rlim_cur; + LOG(WARNING) << "your 'limit -n ' of " << old_limit + << " is not enough for Redis to start. pika have successfully reconfig it to " << limit.rlim_cur; } else { - LOG(FATAL) << "your 'limit -n ' of " << old_limit << " is not enough for Redis to start. pika can not reconfig it(" << strerror(errno) << "), do it by yourself"; + LOG(FATAL) << "your 'limit -n ' of " << old_limit + << " is not enough for Redis to start. pika can not reconfig it(" << strerror(errno) + << "), do it by yourself"; } } @@ -184,7 +183,6 @@ int main(int argc, char *argv[]) { create_pid_file(); } - PikaGlogInit(); PikaSignalSetup(); @@ -199,7 +197,7 @@ int main(int argc, char *argv[]) { g_pika_rm->Start(); g_pika_server->Start(); - + if (g_pika_conf->daemonize()) { unlink(g_pika_conf->pidfile().c_str()); } @@ -208,12 +206,11 @@ int main(int argc, char *argv[]) { // may references to dead PikaServer g_pika_rm->Stop(); - delete g_pika_server; delete g_pika_rm; delete g_pika_cmd_table_manager; ::google::ShutdownGoogleLogging(); delete g_pika_conf; - + return 0; } diff --git a/src/pika_admin.cc b/src/pika_admin.cc index d63405ae06..9b7a210505 100644 --- a/src/pika_admin.cc +++ b/src/pika_admin.cc @@ -18,7 +18,7 @@ #include "pstd/include/rsync.h" #ifdef TCMALLOC_EXTENSION -#include +# include #endif extern PikaServer* g_pika_server; @@ -27,8 +27,7 @@ extern PikaReplicaManager* g_pika_rm; static std::string ConstructPinginPubSubResp(const PikaCmdArgsType& argv) { if (argv.size() > 2) { - return "-ERR wrong number of arguments for " + kCmdNamePing + - " command\r\n"; + return "-ERR wrong number of arguments for " + kCmdNamePing + " command\r\n"; } std::stringstream resp; @@ -50,8 +49,7 @@ enum AuthResult { INVALID_CONN, }; -static AuthResult AuthenticateUser(const std::string& pwd, - const std::shared_ptr& conn, +static AuthResult AuthenticateUser(const std::string& pwd, const std::shared_ptr& conn, std::string& msg_role) { std::string root_password(g_pika_conf->requirepass()); std::string user_password(g_pika_conf->userpass()); @@ -73,8 +71,7 @@ static AuthResult AuthenticateUser(const std::string& pwd, LOG(WARNING) << " weak ptr is empty"; return AuthResult::INVALID_CONN; } - std::shared_ptr cli_conn = - std::dynamic_pointer_cast(conn); + std::shared_ptr cli_conn = std::dynamic_pointer_cast(conn); cli_conn->auth_stat().ChecknUpdate(msg_role); return AuthResult::OK; @@ -96,8 +93,7 @@ void SlaveofCmd::DoInitial() { return; } - if (argv_.size() == 3 && !strcasecmp(argv_[1].data(), "no") && - !strcasecmp(argv_[2].data(), "one")) { + if (argv_.size() == 3 && !strcasecmp(argv_[1].data(), "no") && !strcasecmp(argv_[2].data(), "one")) { is_noone_ = true; return; } @@ -110,15 +106,12 @@ void SlaveofCmd::DoInitial() { master_ip_ = argv_[1]; std::string str_master_port = argv_[2]; - if (!pstd::string2int(str_master_port.data(), str_master_port.size(), - &master_port_) || - master_port_ <= 0) { + if (!pstd::string2int(str_master_port.data(), str_master_port.size(), &master_port_) || master_port_ <= 0) { res_.SetRes(CmdRes::kInvalidInt); return; } - if ((master_ip_ == "127.0.0.1" || master_ip_ == g_pika_server->host()) && - master_port_ == g_pika_server->port()) { + if ((master_ip_ == "127.0.0.1" || master_ip_ == g_pika_server->host()) && master_port_ == g_pika_server->port()) { res_.SetRes(CmdRes::kErrOther, "you fucked up"); return; } @@ -155,8 +148,7 @@ void SlaveofCmd::Do(std::shared_ptr partition) { g_pika_conf->SetSlaveof(master_ip_ + ":" + std::to_string(master_port_)); g_pika_server->SetFirstMetaSync(true); } else { - res_.SetRes(CmdRes::kErrOther, - "Server is not in correct state for slaveof"); + res_.SetRes(CmdRes::kErrOther, "Server is not in correct state for slaveof"); } } @@ -175,8 +167,7 @@ void DbSlaveofCmd::DoInitial() { res_.SetRes(CmdRes::kErrOther, "DbSlaveof only support on classic mode"); return; } - if (g_pika_server->role() ^ PIKA_ROLE_SLAVE || - !g_pika_server->MetaSyncDone()) { + if (g_pika_server->role() ^ PIKA_ROLE_SLAVE || !g_pika_server->MetaSyncDone()) { res_.SetRes(CmdRes::kErrOther, "Not currently a slave"); return; } @@ -198,19 +189,16 @@ void DbSlaveofCmd::DoInitial() { } if (argv_.size() == 4) { - if (!strcasecmp(argv_[2].data(), "no") && - !strcasecmp(argv_[3].data(), "one")) { + if (!strcasecmp(argv_[2].data(), "no") && !strcasecmp(argv_[3].data(), "one")) { is_noone_ = true; return; } - if (!pstd::string2int(argv_[2].data(), argv_[2].size(), &filenum_) || - filenum_ < 0) { + if (!pstd::string2int(argv_[2].data(), argv_[2].size(), &filenum_) || filenum_ < 0) { res_.SetRes(CmdRes::kInvalidInt); return; } - if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &offset_) || - offset_ < 0) { + if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &offset_) || offset_ < 0) { res_.SetRes(CmdRes::kInvalidInt); return; } @@ -231,20 +219,16 @@ void DbSlaveofCmd::Do(std::shared_ptr partition) { // In classic mode a table has only one partition s = g_pika_rm->SendRemoveSlaveNodeRequest(db_name_, 0); } else { - if (slave_partition->State() == ReplState::kNoConnect || - slave_partition->State() == ReplState::kError || + if (slave_partition->State() == ReplState::kNoConnect || slave_partition->State() == ReplState::kError || slave_partition->State() == ReplState::kDBNoConnect) { if (have_offset_) { std::shared_ptr db_partition = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(db_name_, 0)); db_partition->Logger()->SetProducerStatus(filenum_, offset_); } - ReplState state = - force_sync_ ? ReplState::kTryDBSync : ReplState::kTryConnect; + ReplState state = force_sync_ ? ReplState::kTryDBSync : ReplState::kTryConnect; s = g_pika_rm->ActivateSyncSlavePartition( - RmNode(g_pika_server->master_ip(), g_pika_server->master_port(), - db_name_, 0), - state); + RmNode(g_pika_server->master_ip(), g_pika_server->master_port(), db_name_, 0), state); } } @@ -288,8 +272,7 @@ void AuthCmd::Do(std::shared_ptr partition) { LOG(WARNING) << name_ << " weak ptr is empty"; return; } - std::shared_ptr cli_conn = - std::dynamic_pointer_cast(conn); + std::shared_ptr cli_conn = std::dynamic_pointer_cast(conn); cli_conn->auth_stat().ChecknUpdate(res().raw_message()); } @@ -325,8 +308,7 @@ void CompactCmd::DoInitial() { } if (g_pika_server->IsKeyScaning()) { - res_.SetRes(CmdRes::kErrOther, - "The info keyspace operation is executing, Try again later"); + res_.SetRes(CmdRes::kErrOther, "The info keyspace operation is executing, Try again later"); return; } @@ -351,23 +333,17 @@ void CompactCmd::DoInitial() { void CompactCmd::Do(std::shared_ptr partition) { if (!strcasecmp(struct_type_.data(), "all")) { - g_pika_server->DoSameThingSpecificTable(TaskType::kCompactAll, - compact_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kCompactAll, compact_tables_); } else if (!strcasecmp(struct_type_.data(), "string")) { - g_pika_server->DoSameThingSpecificTable(TaskType::kCompactStrings, - compact_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kCompactStrings, compact_tables_); } else if (!strcasecmp(struct_type_.data(), "hash")) { - g_pika_server->DoSameThingSpecificTable(TaskType::kCompactHashes, - compact_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kCompactHashes, compact_tables_); } else if (!strcasecmp(struct_type_.data(), "set")) { - g_pika_server->DoSameThingSpecificTable(TaskType::kCompactSets, - compact_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kCompactSets, compact_tables_); } else if (!strcasecmp(struct_type_.data(), "zset")) { - g_pika_server->DoSameThingSpecificTable(TaskType::kCompactZSets, - compact_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kCompactZSets, compact_tables_); } else if (!strcasecmp(struct_type_.data(), "list")) { - g_pika_server->DoSameThingSpecificTable(TaskType::kCompactList, - compact_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kCompactList, compact_tables_); } else { res_.SetRes(CmdRes::kInvalidDbType, struct_type_); return; @@ -382,8 +358,7 @@ void PurgelogstoCmd::DoInitial() { return; } std::string filename = argv_[1]; - if (filename.size() <= kBinlogPrefixLen || - kBinlogPrefix != filename.substr(0, kBinlogPrefixLen)) { + if (filename.size() <= kBinlogPrefixLen || kBinlogPrefix != filename.substr(0, kBinlogPrefixLen)) { res_.SetRes(CmdRes::kInvalidParameter); return; } @@ -427,8 +402,7 @@ void PingCmd::Do(std::shared_ptr partition) { LOG(WARNING) << name_ << " weak ptr is empty"; return; } - std::shared_ptr cli_conn = - std::dynamic_pointer_cast(conn); + std::shared_ptr cli_conn = std::dynamic_pointer_cast(conn); if (cli_conn->IsPubSub()) { return res_.SetRes(CmdRes::kNone, ConstructPinginPubSubResp(argv_)); @@ -448,8 +422,7 @@ void SelectCmd::DoInitial() { } if (g_pika_conf->classic_mode()) { if (index < 0 || index >= g_pika_conf->databases()) { - res_.SetRes(CmdRes::kInvalidIndex, - kCmdNameSelect + " DB index is out of range"); + res_.SetRes(CmdRes::kInvalidIndex, kCmdNameSelect + " DB index is out of range"); return; } } @@ -461,8 +434,7 @@ void SelectCmd::DoInitial() { } void SelectCmd::Do(std::shared_ptr partition) { - std::shared_ptr conn = - std::dynamic_pointer_cast(GetConn()); + std::shared_ptr conn = std::dynamic_pointer_cast(GetConn()); if (!conn) { res_.SetRes(CmdRes::kErrOther, kCmdNameSelect); LOG(WARNING) << name_ << " weak ptr is empty"; @@ -487,8 +459,7 @@ void FlushallCmd::Do(std::shared_ptr partition) { } // flushall convert flushdb writes to every partition binlog -std::string FlushallCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, - uint64_t logic_id, uint32_t filenum, +std::string FlushallCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); @@ -498,8 +469,7 @@ std::string FlushallCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, std::string flushdb_cmd("flushdb"); RedisAppendLen(content, flushdb_cmd.size(), "$"); RedisAppendContent(content, flushdb_cmd); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, - term_id, logic_id, filenum, offset, + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, content, {}); } @@ -565,20 +535,16 @@ void ClientCmd::DoInitial() { if (!strcasecmp(argv_[1].data(), "list") && argv_.size() == 2) { // nothing } else if (!strcasecmp(argv_[1].data(), "list") && argv_.size() == 5) { - if (!strcasecmp(argv_[2].data(), "order") && - !strcasecmp(argv_[3].data(), "by")) { + if (!strcasecmp(argv_[2].data(), "order") && !strcasecmp(argv_[3].data(), "by")) { info_ = argv_[4]; } else { - res_.SetRes(CmdRes::kErrOther, - "Syntax error, try CLIENT (LIST [order by [addr|idle])"); + res_.SetRes(CmdRes::kErrOther, "Syntax error, try CLIENT (LIST [order by [addr|idle])"); return; } } else if (!strcasecmp(argv_[1].data(), "kill") && argv_.size() == 3) { info_ = argv_[2]; } else { - res_.SetRes( - CmdRes::kErrOther, - "Syntax error, try CLIENT (LIST [order by [addr|idle]| KILL ip:port)"); + res_.SetRes(CmdRes::kErrOther, "Syntax error, try CLIENT (LIST [order by [addr|idle]| KILL ip:port)"); return; } operation_ = argv_[1]; @@ -618,17 +584,13 @@ void ClientCmd::Do(std::shared_ptr partition) { std::sort(clients.begin(), clients.end(), IdleCompare); } while (iter != clients.end()) { - snprintf(buf, sizeof(buf), "addr=%s fd=%d idle=%ld\n", - iter->ip_port.c_str(), iter->fd, - iter->last_interaction == 0 - ? 0 - : now.tv_sec - iter->last_interaction); + snprintf(buf, sizeof(buf), "addr=%s fd=%d idle=%ld\n", iter->ip_port.c_str(), iter->fd, + iter->last_interaction == 0 ? 0 : now.tv_sec - iter->last_interaction); reply.append(buf); iter++; } res_.AppendString(reply); - } else if (!strcasecmp(operation_.data(), "kill") && - !strcasecmp(info_.data(), "all")) { + } else if (!strcasecmp(operation_.data(), "kill") && !strcasecmp(info_.data(), "all")) { g_pika_server->ClientKillAll(); res_.SetRes(CmdRes::kOk); } else if (g_pika_server->ClientKill(info_) == 1) { @@ -654,8 +616,7 @@ void ShutdownCmd::DoInitial() { conn->ip_port().find(g_pika_server->host()) == std::string::npos) { LOG(WARNING) << "\'shutdown\' should be localhost" << " command from " << conn->ip_port(); - res_.SetRes(CmdRes::kErrOther, - kCmdNameShutdown + " should be localhost"); + res_.SetRes(CmdRes::kErrOther, kCmdNameShutdown + " should be localhost"); } } else { LOG(WARNING) << name_ << " weak ptr is empty"; @@ -720,8 +681,7 @@ void InfoCmd::DoInitial() { // info keyspace off db0,db1 if (argv_[2] == "1") { if (g_pika_server->IsCompacting()) { - res_.SetRes(CmdRes::kErrOther, - "The compact operation is executing, Try again later"); + res_.SetRes(CmdRes::kErrOther, "The compact operation is executing, Try again later"); } else { rescan_ = true; } @@ -840,28 +800,19 @@ void InfoCmd::InfoServer(std::string& info) { time_t current_time_s = time(NULL); std::stringstream tmp_stream; char version[32]; - snprintf(version, sizeof(version), "%d.%d.%d", PIKA_MAJOR, PIKA_MINOR, - PIKA_PATCH); + snprintf(version, sizeof(version), "%d.%d.%d", PIKA_MAJOR, PIKA_MINOR, PIKA_PATCH); tmp_stream << "# Server\r\n"; tmp_stream << "pika_version:" << version << "\r\n"; tmp_stream << pika_build_git_sha << "\r\n"; - tmp_stream << "pika_build_compile_date: " << pika_build_compile_date - << "\r\n"; - tmp_stream << "os:" << host_info.sysname << " " << host_info.release << " " - << host_info.machine << "\r\n"; - tmp_stream << "arch_bits:" - << (reinterpret_cast(&host_info.machine) + - strlen(host_info.machine) - 2) - << "\r\n"; + tmp_stream << "pika_build_compile_date: " << pika_build_compile_date << "\r\n"; + tmp_stream << "os:" << host_info.sysname << " " << host_info.release << " " << host_info.machine << "\r\n"; + tmp_stream << "arch_bits:" << (reinterpret_cast(&host_info.machine) + strlen(host_info.machine) - 2) << "\r\n"; tmp_stream << "process_id:" << getpid() << "\r\n"; tmp_stream << "tcp_port:" << g_pika_conf->port() << "\r\n"; tmp_stream << "thread_num:" << g_pika_conf->thread_num() << "\r\n"; tmp_stream << "sync_thread_num:" << g_pika_conf->sync_thread_num() << "\r\n"; - tmp_stream << "uptime_in_seconds:" - << (current_time_s - g_pika_server->start_time_s()) << "\r\n"; - tmp_stream << "uptime_in_days:" - << (current_time_s / (24 * 3600) - - g_pika_server->start_time_s() / (24 * 3600) + 1) + tmp_stream << "uptime_in_seconds:" << (current_time_s - g_pika_server->start_time_s()) << "\r\n"; + tmp_stream << "uptime_in_days:" << (current_time_s / (24 * 3600) - g_pika_server->start_time_s() / (24 * 3600) + 1) << "\r\n"; tmp_stream << "config_file:" << g_pika_conf->conf_path() << "\r\n"; tmp_stream << "server_id:" << g_pika_conf->server_id() << "\r\n"; @@ -880,21 +831,14 @@ void InfoCmd::InfoClients(std::string& info) { void InfoCmd::InfoStats(std::string& info) { std::stringstream tmp_stream; tmp_stream << "# Stats\r\n"; - tmp_stream << "total_connections_received:" - << g_pika_server->accumulative_connections() << "\r\n"; - tmp_stream << "instantaneous_ops_per_sec:" - << g_pika_server->ServerCurrentQps() << "\r\n"; - tmp_stream << "total_commands_processed:" << g_pika_server->ServerQueryNum() - << "\r\n"; - tmp_stream << "is_bgsaving:" << (g_pika_server->IsBgSaving() ? "Yes" : "No") - << "\r\n"; - tmp_stream << "is_scaning_keyspace:" - << (g_pika_server->IsKeyScaning() ? "Yes" : "No") << "\r\n"; - tmp_stream << "is_compact:" << (g_pika_server->IsCompacting() ? "Yes" : "No") - << "\r\n"; + tmp_stream << "total_connections_received:" << g_pika_server->accumulative_connections() << "\r\n"; + tmp_stream << "instantaneous_ops_per_sec:" << g_pika_server->ServerCurrentQps() << "\r\n"; + tmp_stream << "total_commands_processed:" << g_pika_server->ServerQueryNum() << "\r\n"; + tmp_stream << "is_bgsaving:" << (g_pika_server->IsBgSaving() ? "Yes" : "No") << "\r\n"; + tmp_stream << "is_scaning_keyspace:" << (g_pika_server->IsKeyScaning() ? "Yes" : "No") << "\r\n"; + tmp_stream << "is_compact:" << (g_pika_server->IsCompacting() ? "Yes" : "No") << "\r\n"; tmp_stream << "compact_cron:" << g_pika_conf->compact_cron() << "\r\n"; - tmp_stream << "compact_interval:" << g_pika_conf->compact_interval() - << "\r\n"; + tmp_stream << "compact_interval:" << g_pika_conf->compact_interval() << "\r\n"; info.append(tmp_stream.str()); } @@ -903,8 +847,7 @@ void InfoCmd::InfoExecCount(std::string& info) { std::stringstream tmp_stream; tmp_stream << "# Command_Exec_Count\r\n"; - std::unordered_map command_exec_count_table = - g_pika_server->ServerExecCountTable(); + std::unordered_map command_exec_count_table = g_pika_server->ServerExecCountTable(); for (const auto& item : command_exec_count_table) { if (item.second == 0) { continue; @@ -920,34 +863,21 @@ void InfoCmd::InfoCPU(std::string& info) { getrusage(RUSAGE_CHILDREN, &c_ru); std::stringstream tmp_stream; tmp_stream << "# CPU\r\n"; - tmp_stream << "used_cpu_sys:" << std::setiosflags(std::ios::fixed) - << std::setprecision(2) - << (float)self_ru.ru_stime.tv_sec + - (float)self_ru.ru_stime.tv_usec / 1000000 - << "\r\n"; - tmp_stream << "used_cpu_user:" << std::setiosflags(std::ios::fixed) - << std::setprecision(2) - << (float)self_ru.ru_utime.tv_sec + - (float)self_ru.ru_utime.tv_usec / 1000000 - << "\r\n"; - tmp_stream << "used_cpu_sys_children:" << std::setiosflags(std::ios::fixed) - << std::setprecision(2) - << (float)c_ru.ru_stime.tv_sec + - (float)c_ru.ru_stime.tv_usec / 1000000 - << "\r\n"; - tmp_stream << "used_cpu_user_children:" << std::setiosflags(std::ios::fixed) - << std::setprecision(2) - << (float)c_ru.ru_utime.tv_sec + - (float)c_ru.ru_utime.tv_usec / 1000000 - << "\r\n"; + tmp_stream << "used_cpu_sys:" << std::setiosflags(std::ios::fixed) << std::setprecision(2) + << (float)self_ru.ru_stime.tv_sec + (float)self_ru.ru_stime.tv_usec / 1000000 << "\r\n"; + tmp_stream << "used_cpu_user:" << std::setiosflags(std::ios::fixed) << std::setprecision(2) + << (float)self_ru.ru_utime.tv_sec + (float)self_ru.ru_utime.tv_usec / 1000000 << "\r\n"; + tmp_stream << "used_cpu_sys_children:" << std::setiosflags(std::ios::fixed) << std::setprecision(2) + << (float)c_ru.ru_stime.tv_sec + (float)c_ru.ru_stime.tv_usec / 1000000 << "\r\n"; + tmp_stream << "used_cpu_user_children:" << std::setiosflags(std::ios::fixed) << std::setprecision(2) + << (float)c_ru.ru_utime.tv_sec + (float)c_ru.ru_utime.tv_usec / 1000000 << "\r\n"; info.append(tmp_stream.str()); } void InfoCmd::InfoShardingReplication(std::string& info) { int role = 0; std::string slave_list_string; - uint32_t slave_num = - g_pika_server->GetShardingSlaveListString(slave_list_string); + uint32_t slave_num = g_pika_server->GetShardingSlaveListString(slave_list_string); if (slave_num) { role |= PIKA_ROLE_MASTER; } @@ -985,8 +915,7 @@ void InfoCmd::InfoShardingReplication(std::string& info) { tmp_stream << "master_port:" << master_port << "\r\n"; tmp_stream << "master_link_status:up" << "\r\n"; - tmp_stream << "slave_priority:" << g_pika_conf->slave_priority() - << "\r\n"; + tmp_stream << "slave_priority:" << g_pika_conf->slave_priority() << "\r\n"; break; case PIKA_ROLE_MASTER | PIKA_ROLE_SLAVE: tmp_stream << "master_host:" << master_ip << "\r\n"; @@ -995,8 +924,7 @@ void InfoCmd::InfoShardingReplication(std::string& info) { << "\r\n"; case PIKA_ROLE_SINGLE: case PIKA_ROLE_MASTER: - tmp_stream << "connected_slaves:" << slave_num << "\r\n" - << slave_list_string; + tmp_stream << "connected_slaves:" << slave_num << "\r\n" << slave_list_string; } info.append(tmp_stream.str()); } @@ -1017,13 +945,10 @@ void InfoCmd::InfoReplication(std::string& info) { for (const auto& table_item : g_pika_server->tables_) { pstd::RWLock partition_rwl(&table_item.second->partitions_rw_, false); for (const auto& partition_item : table_item.second->partitions_) { - std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_item.second->GetTableName(), - partition_item.second->GetPartitionId())); + std::shared_ptr slave_partition = g_pika_rm->GetSyncSlavePartitionByName( + PartitionInfo(table_item.second->GetTableName(), partition_item.second->GetPartitionId())); if (!slave_partition) { - out_of_sync << "(" << partition_item.second->GetPartitionName() - << ": InternalError)"; + out_of_sync << "(" << partition_item.second->GetPartitionName() << ": InternalError)"; continue; } if (slave_partition->State() != ReplState::kConnected) { @@ -1073,16 +998,10 @@ void InfoCmd::InfoReplication(std::string& info) { tmp_stream << "master_host:" << g_pika_server->master_ip() << "\r\n"; tmp_stream << "master_port:" << g_pika_server->master_port() << "\r\n"; tmp_stream << "master_link_status:" - << (((g_pika_server->repl_state() == - PIKA_REPL_META_SYNC_DONE) && - all_partition_sync) - ? "up" - : "down") - << "\r\n"; - tmp_stream << "slave_priority:" << g_pika_conf->slave_priority() - << "\r\n"; - tmp_stream << "slave_read_only:" << g_pika_conf->slave_read_only() + << (((g_pika_server->repl_state() == PIKA_REPL_META_SYNC_DONE) && all_partition_sync) ? "up" : "down") << "\r\n"; + tmp_stream << "slave_priority:" << g_pika_conf->slave_priority() << "\r\n"; + tmp_stream << "slave_read_only:" << g_pika_conf->slave_read_only() << "\r\n"; if (!all_partition_sync) { tmp_stream << "db_repl_state:" << out_of_sync.str() << "\r\n"; } @@ -1091,21 +1010,15 @@ void InfoCmd::InfoReplication(std::string& info) { tmp_stream << "master_host:" << g_pika_server->master_ip() << "\r\n"; tmp_stream << "master_port:" << g_pika_server->master_port() << "\r\n"; tmp_stream << "master_link_status:" - << (((g_pika_server->repl_state() == - PIKA_REPL_META_SYNC_DONE) && - all_partition_sync) - ? "up" - : "down") - << "\r\n"; - tmp_stream << "slave_read_only:" << g_pika_conf->slave_read_only() + << (((g_pika_server->repl_state() == PIKA_REPL_META_SYNC_DONE) && all_partition_sync) ? "up" : "down") << "\r\n"; + tmp_stream << "slave_read_only:" << g_pika_conf->slave_read_only() << "\r\n"; if (!all_partition_sync) { tmp_stream << "db_repl_state:" << out_of_sync.str() << "\r\n"; } case PIKA_ROLE_SINGLE: case PIKA_ROLE_MASTER: - tmp_stream << "connected_slaves:" - << g_pika_server->GetSlaveListString(slaves_list_str) << "\r\n" + tmp_stream << "connected_slaves:" << g_pika_server->GetSlaveListString(slaves_list_str) << "\r\n" << slaves_list_str; } @@ -1119,22 +1032,18 @@ void InfoCmd::InfoReplication(std::string& info) { for (const auto& p_item : t_item.second->partitions_) { std::string table_name = p_item.second->GetTableName(); uint32_t partition_id = p_item.second->GetPartitionId(); - master_partition = g_pika_rm->GetSyncMasterPartitionByName( - PartitionInfo(table_name, partition_id)); + master_partition = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!master_partition) { - LOG(WARNING) << "Sync Master Partition: " << table_name << ":" - << partition_id << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id << ", NotFound"; continue; } master_partition->Logger()->GetProducerStatus(&filenum, &offset); tmp_stream << table_name << " binlog_offset=" << filenum << " " << offset; s = master_partition->GetSafetyPurgeBinlog(&safety_purge); - tmp_stream << ",safety_purge=" << (s.ok() ? safety_purge : "error") - << "\r\n"; + tmp_stream << ",safety_purge=" << (s.ok() ? safety_purge : "error") << "\r\n"; if (g_pika_conf->consensus_level()) { LogOffset last_log = master_partition->ConsensusLastIndex(); - tmp_stream << table_name - << " consensus last_log=" << last_log.ToString() << "\r\n"; + tmp_stream << table_name << " consensus last_log=" << last_log.ToString() << "\r\n"; } } } @@ -1144,8 +1053,7 @@ void InfoCmd::InfoReplication(std::string& info) { void InfoCmd::InfoKeyspace(std::string& info) { if (off_) { - g_pika_server->DoSameThingSpecificTable(TaskType::kStopKeyScan, - keyspace_scan_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kStopKeyScan, keyspace_scan_tables_); info.append("OK\r\n"); return; } @@ -1158,9 +1066,7 @@ void InfoCmd::InfoKeyspace(std::string& info) { tmp_stream << "# Keyspace\r\n"; pstd::RWLock rwl(&g_pika_server->tables_rw_, false); for (const auto& table_item : g_pika_server->tables_) { - if (keyspace_scan_tables_.empty() || - keyspace_scan_tables_.find(table_item.first) != - keyspace_scan_tables_.end()) { + if (keyspace_scan_tables_.empty() || keyspace_scan_tables_.find(table_item.first) != keyspace_scan_tables_.end()) { table_name = table_item.second->GetTableName(); key_scan_info = table_item.second->GetKeyScanInfo(); key_infos = key_scan_info.key_infos; @@ -1181,29 +1087,22 @@ void InfoCmd::InfoKeyspace(std::string& info) { << "\r\n"; } - tmp_stream << table_name << " Strings_keys=" << key_infos[0].keys - << ", expires=" << key_infos[0].expires + tmp_stream << table_name << " Strings_keys=" << key_infos[0].keys << ", expires=" << key_infos[0].expires << ", invalid_keys=" << key_infos[0].invaild_keys << "\r\n"; - tmp_stream << table_name << " Hashes_keys=" << key_infos[1].keys - << ", expires=" << key_infos[1].expires + tmp_stream << table_name << " Hashes_keys=" << key_infos[1].keys << ", expires=" << key_infos[1].expires << ", invalid_keys=" << key_infos[1].invaild_keys << "\r\n"; - tmp_stream << table_name << " Lists_keys=" << key_infos[2].keys - << ", expires=" << key_infos[2].expires + tmp_stream << table_name << " Lists_keys=" << key_infos[2].keys << ", expires=" << key_infos[2].expires << ", invalid_keys=" << key_infos[2].invaild_keys << "\r\n"; - tmp_stream << table_name << " Zsets_keys=" << key_infos[3].keys - << ", expires=" << key_infos[3].expires + tmp_stream << table_name << " Zsets_keys=" << key_infos[3].keys << ", expires=" << key_infos[3].expires << ", invalid_keys=" << key_infos[3].invaild_keys << "\r\n"; - tmp_stream << table_name << " Sets_keys=" << key_infos[4].keys - << ", expires=" << key_infos[4].expires - << ", invalid_keys=" << key_infos[4].invaild_keys - << "\r\n\r\n"; + tmp_stream << table_name << " Sets_keys=" << key_infos[4].keys << ", expires=" << key_infos[4].expires + << ", invalid_keys=" << key_infos[4].invaild_keys << "\r\n\r\n"; } } info.append(tmp_stream.str()); if (rescan_) { - g_pika_server->DoSameThingSpecificTable(TaskType::kStartKeyScan, - keyspace_scan_tables_); + g_pika_server->DoSameThingSpecificTable(TaskType::kStartKeyScan, keyspace_scan_tables_); } return; } @@ -1234,39 +1133,28 @@ void InfoCmd::InfoData(std::string& info) { type_result.clear(); memtable_usage = table_reader_usage = 0; patition_item.second->DbRWLockReader(); - patition_item.second->db()->GetUsage( - storage::PROPERTY_TYPE_ROCKSDB_MEMTABLE, &memtable_usage); - patition_item.second->db()->GetUsage( - storage::PROPERTY_TYPE_ROCKSDB_TABLE_READER, &table_reader_usage); - patition_item.second->db()->GetUsage( - storage::PROPERTY_TYPE_ROCKSDB_BACKGROUND_ERRORS, &type_result); + patition_item.second->db()->GetUsage(storage::PROPERTY_TYPE_ROCKSDB_MEMTABLE, &memtable_usage); + patition_item.second->db()->GetUsage(storage::PROPERTY_TYPE_ROCKSDB_TABLE_READER, &table_reader_usage); + patition_item.second->db()->GetUsage(storage::PROPERTY_TYPE_ROCKSDB_BACKGROUND_ERRORS, &type_result); patition_item.second->DbRWUnLock(); total_memtable_usage += memtable_usage; total_table_reader_usage += table_reader_usage; for (const auto& item : type_result) { if (item.second != 0) { db_fatal_msg_stream << (total_background_errors != 0 ? "," : ""); - db_fatal_msg_stream << patition_item.second->GetPartitionName() << "/" - << item.first; + db_fatal_msg_stream << patition_item.second->GetPartitionName() << "/" << item.first; total_background_errors += item.second; } } } } - tmp_stream << "used_memory:" - << (total_memtable_usage + total_table_reader_usage) << "\r\n"; - tmp_stream << "used_memory_human:" - << ((total_memtable_usage + total_table_reader_usage) >> 20) - << "M\r\n"; + tmp_stream << "used_memory:" << (total_memtable_usage + total_table_reader_usage) << "\r\n"; + tmp_stream << "used_memory_human:" << ((total_memtable_usage + total_table_reader_usage) >> 20) << "M\r\n"; tmp_stream << "db_memtable_usage:" << total_memtable_usage << "\r\n"; tmp_stream << "db_tablereader_usage:" << total_table_reader_usage << "\r\n"; - tmp_stream << "db_fatal:" << (total_background_errors != 0 ? "1" : "0") - << "\r\n"; - tmp_stream << "db_fatal_msg:" - << (total_background_errors != 0 ? db_fatal_msg_stream.str() - : "NULL") - << "\r\n"; + tmp_stream << "db_fatal:" << (total_background_errors != 0 ? "1" : "0") << "\r\n"; + tmp_stream << "db_fatal_msg:" << (total_background_errors != 0 ? db_fatal_msg_stream.str() : "NULL") << "\r\n"; info.append(tmp_stream.str()); return; @@ -1295,36 +1183,29 @@ void ConfigCmd::DoInitial() { size_t argc = argv_.size(); if (!strcasecmp(argv_[1].data(), "get")) { if (argc != 3) { - res_.SetRes(CmdRes::kErrOther, - "Wrong number of arguments for CONFIG get"); + res_.SetRes(CmdRes::kErrOther, "Wrong number of arguments for CONFIG get"); return; } } else if (!strcasecmp(argv_[1].data(), "set")) { if (argc == 3 && argv_[2] != "*") { - res_.SetRes(CmdRes::kErrOther, - "Wrong number of arguments for CONFIG set"); + res_.SetRes(CmdRes::kErrOther, "Wrong number of arguments for CONFIG set"); return; } else if (argc != 4 && argc != 3) { - res_.SetRes(CmdRes::kErrOther, - "Wrong number of arguments for CONFIG set"); + res_.SetRes(CmdRes::kErrOther, "Wrong number of arguments for CONFIG set"); return; } } else if (!strcasecmp(argv_[1].data(), "rewrite")) { if (argc != 2) { - res_.SetRes(CmdRes::kErrOther, - "Wrong number of arguments for CONFIG rewrite"); + res_.SetRes(CmdRes::kErrOther, "Wrong number of arguments for CONFIG rewrite"); return; } } else if (!strcasecmp(argv_[1].data(), "resetstat")) { if (argc != 2) { - res_.SetRes(CmdRes::kErrOther, - "Wrong number of arguments for CONFIG resetstat"); + res_.SetRes(CmdRes::kErrOther, "Wrong number of arguments for CONFIG resetstat"); return; } } else { - res_.SetRes( - CmdRes::kErrOther, - "CONFIG subcommand must be one of GET, SET, RESETSTAT, REWRITE"); + res_.SetRes(CmdRes::kErrOther, "CONFIG subcommand must be one of GET, SET, RESETSTAT, REWRITE"); return; } config_args_v_.assign(argv_.begin() + 1, argv_.end()); @@ -1470,19 +1351,16 @@ void ConfigCmd::ConfigGet(std::string& ret) { if (pstd::stringmatch(pattern.data(), "instance-mode", 1)) { elements += 2; EncodeString(&config_body, "instance-mode"); - EncodeString(&config_body, - (g_pika_conf->classic_mode() ? "classic" : "sharding")); + EncodeString(&config_body, (g_pika_conf->classic_mode() ? "classic" : "sharding")); } - if (g_pika_conf->classic_mode() && - pstd::stringmatch(pattern.data(), "databases", 1)) { + if (g_pika_conf->classic_mode() && pstd::stringmatch(pattern.data(), "databases", 1)) { elements += 2; EncodeString(&config_body, "databases"); EncodeInt32(&config_body, g_pika_conf->databases()); } - if (!g_pika_conf->classic_mode() && - pstd::stringmatch(pattern.data(), "default-slot-num", 1)) { + if (!g_pika_conf->classic_mode() && pstd::stringmatch(pattern.data(), "default-slot-num", 1)) { elements += 2; EncodeString(&config_body, "default-slot-num"); EncodeInt32(&config_body, g_pika_conf->default_slot_num()); @@ -1587,24 +1465,19 @@ void ConfigCmd::ConfigGet(std::string& ret) { if (pstd::stringmatch(pattern.data(), "cache-index-and-filter-blocks", 1)) { elements += 2; EncodeString(&config_body, "cache-index-and-filter-blocks"); - EncodeString(&config_body, - g_pika_conf->cache_index_and_filter_blocks() ? "yes" : "no"); + EncodeString(&config_body, g_pika_conf->cache_index_and_filter_blocks() ? "yes" : "no"); } if (pstd::stringmatch(pattern.data(), "optimize-filters-for-hits", 1)) { elements += 2; EncodeString(&config_body, "optimize-filters-for-hits"); - EncodeString(&config_body, - g_pika_conf->optimize_filters_for_hits() ? "yes" : "no"); + EncodeString(&config_body, g_pika_conf->optimize_filters_for_hits() ? "yes" : "no"); } - if (pstd::stringmatch(pattern.data(), "level-compaction-dynamic-level-bytes", - 1)) { + if (pstd::stringmatch(pattern.data(), "level-compaction-dynamic-level-bytes", 1)) { elements += 2; EncodeString(&config_body, "level-compaction-dynamic-level-bytes"); - EncodeString( - &config_body, - g_pika_conf->level_compaction_dynamic_level_bytes() ? "yes" : "no"); + EncodeString(&config_body, g_pika_conf->level_compaction_dynamic_level_bytes() ? "yes" : "no"); } if (pstd::stringmatch(pattern.data(), "expire-logs-days", 1)) { @@ -1628,8 +1501,7 @@ void ConfigCmd::ConfigGet(std::string& ret) { if (pstd::stringmatch(pattern.data(), "slowlog-write-errorlog", 1)) { elements += 2; EncodeString(&config_body, "slowlog-write-errorlog"); - EncodeString(&config_body, - g_pika_conf->slowlog_write_errorlog() ? "yes" : "no"); + EncodeString(&config_body, g_pika_conf->slowlog_write_errorlog() ? "yes" : "no"); } if (pstd::stringmatch(pattern.data(), "slowlog-log-slower-than", 1)) { @@ -1814,8 +1686,7 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "maxclients") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival <= 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'maxclients'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'maxclients'\r\n"; return; } g_pika_conf->SetMaxConnection(ival); @@ -1823,40 +1694,35 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "dump-expire") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'dump-expire'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'dump-expire'\r\n"; return; } g_pika_conf->SetExpireDumpDays(ival); ret = "+OK\r\n"; } else if (set_item == "slave-priority") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'slave-priority'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'slave-priority'\r\n"; return; } g_pika_conf->SetSlavePriority(ival); ret = "+OK\r\n"; } else if (set_item == "expire-logs-days") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival <= 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'expire-logs-days'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'expire-logs-days'\r\n"; return; } g_pika_conf->SetExpireLogsDays(ival); ret = "+OK\r\n"; } else if (set_item == "expire-logs-nums") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival <= 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'expire-logs-nums'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'expire-logs-nums'\r\n"; return; } g_pika_conf->SetExpireLogsNums(ival); ret = "+OK\r\n"; } else if (set_item == "root-connection-num") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival <= 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'root-connection-num'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'root-connection-num'\r\n"; return; } g_pika_conf->SetRootConnectionNum(ival); @@ -1868,24 +1734,21 @@ void ConfigCmd::ConfigSet(std::string& ret) { } else if (value == "no") { is_write_errorlog = false; } else { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'slowlog-write-errorlog'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'slowlog-write-errorlog'\r\n"; return; } g_pika_conf->SetSlowlogWriteErrorlog(is_write_errorlog); ret = "+OK\r\n"; } else if (set_item == "slowlog-log-slower-than") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival < 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'slowlog-log-slower-than'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'slowlog-log-slower-than'\r\n"; return; } g_pika_conf->SetSlowlogSlowerThan(ival); ret = "+OK\r\n"; } else if (set_item == "slowlog-max-len") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival < 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'slowlog-max-len'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'slowlog-max-len'\r\n"; return; } g_pika_conf->SetSlowlogMaxLen(ival); @@ -1893,8 +1756,7 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "max-cache-statistic-keys") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival < 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'max-cache-statistic-keys'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'max-cache-statistic-keys'\r\n"; return; } g_pika_conf->SetMaxCacheStatisticKeys(ival); @@ -1902,8 +1764,7 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "small-compaction-threshold") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival < 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'small-compaction-threshold'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'small-compaction-threshold'\r\n"; return; } g_pika_conf->SetSmallCompactionThreshold(ival); @@ -1911,8 +1772,7 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "max-client-response-size") { if (!pstd::string2int(value.data(), value.size(), &ival) || ival < 0) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'max-client-response-size'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'max-client-response-size'\r\n"; return; } g_pika_conf->SetMaxClientResponseSize(ival); @@ -1931,8 +1791,7 @@ void ConfigCmd::ConfigSet(std::string& ret) { } } else if (set_item == "db-sync-speed") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'db-sync-speed(MB)'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'db-sync-speed(MB)'\r\n"; return; } if (ival < 0 || ival > 1024) { @@ -1958,17 +1817,16 @@ void ConfigCmd::ConfigSet(std::string& ret) { std::string::size_type len = compact_cron.length(); std::string::size_type colon = compact_cron.find("-"); std::string::size_type underline = compact_cron.find("/"); - if (colon == std::string::npos || underline == std::string::npos || - colon >= underline || colon + 1 >= len || colon + 1 == underline || - underline + 1 >= len) { + if (colon == std::string::npos || underline == std::string::npos || colon >= underline || colon + 1 >= len || + colon + 1 == underline || underline + 1 >= len) { invalid = true; } else { int week = std::atoi(week_str.c_str()); int start = std::atoi(compact_cron.substr(0, colon).c_str()); int end = std::atoi(compact_cron.substr(colon + 1, underline).c_str()); int usage = std::atoi(compact_cron.substr(underline + 1).c_str()); - if ((have_week && (week < 1 || week > 7)) || start < 0 || start > 23 || - end < 0 || end > 23 || usage < 0 || usage > 100) { + if ((have_week && (week < 1 || week > 7)) || start < 0 || start > 23 || end < 0 || end > 23 || usage < 0 || + usage > 100) { invalid = true; } } @@ -2004,27 +1862,22 @@ void ConfigCmd::ConfigSet(std::string& ret) { } } else if (set_item == "sync-window-size") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'sync-window-size'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'sync-window-size'\r\n"; return; } if (ival <= 0 || ival > kBinlogReadWinMaxSize) { - ret = "-ERR Argument exceed range \'" + value + - "\' for CONFIG SET 'sync-window-size'\r\n"; + ret = "-ERR Argument exceed range \'" + value + "\' for CONFIG SET 'sync-window-size'\r\n"; return; } g_pika_conf->SetSyncWindowSize(ival); ret = "+OK\r\n"; } else if (set_item == "max-cache-files") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'max-cache-files'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'max-cache-files'\r\n"; return; } - std::unordered_map options_map{ - {"max_open_files", value}}; - storage::Status s = g_pika_server->RewriteStorageOptions( - storage::OptionType::kDB, options_map); + std::unordered_map options_map{{"max_open_files", value}}; + storage::Status s = g_pika_server->RewriteStorageOptions(storage::OptionType::kDB, options_map); if (!s.ok()) { ret = "-ERR Set max-cache-files wrong: " + s.ToString() + "\r\n"; return; @@ -2033,31 +1886,24 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "max-background-compactions") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'max-background-compactions'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'max-background-compactions'\r\n"; return; } - std::unordered_map options_map{ - {"max_background_compactions", value}}; - storage::Status s = g_pika_server->RewriteStorageOptions( - storage::OptionType::kDB, options_map); + std::unordered_map options_map{{"max_background_compactions", value}}; + storage::Status s = g_pika_server->RewriteStorageOptions(storage::OptionType::kDB, options_map); if (!s.ok()) { - ret = - "-ERR Set max-background-compactions wrong: " + s.ToString() + "\r\n"; + ret = "-ERR Set max-background-compactions wrong: " + s.ToString() + "\r\n"; return; } g_pika_conf->SetMaxBackgroudCompactions(ival); ret = "+OK\r\n"; } else if (set_item == "write-buffer-size") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'write-buffer-size'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'write-buffer-size'\r\n"; return; } - std::unordered_map options_map{ - {"write_buffer_size", value}}; - storage::Status s = g_pika_server->RewriteStorageOptions( - storage::OptionType::kColumnFamily, options_map); + std::unordered_map options_map{{"write_buffer_size", value}}; + storage::Status s = g_pika_server->RewriteStorageOptions(storage::OptionType::kColumnFamily, options_map); if (!s.ok()) { ret = "-ERR Set write-buffer-size wrong: " + s.ToString() + "\r\n"; return; @@ -2066,14 +1912,11 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "max-write-buffer-num") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'max-write-buffer-number'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'max-write-buffer-number'\r\n"; return; } - std::unordered_map options_map{ - {"max_write_buffer_number", value}}; - storage::Status s = g_pika_server->RewriteStorageOptions( - storage::OptionType::kColumnFamily, options_map); + std::unordered_map options_map{{"max_write_buffer_number", value}}; + storage::Status s = g_pika_server->RewriteStorageOptions(storage::OptionType::kColumnFamily, options_map); if (!s.ok()) { ret = "-ERR Set max-write-buffer-number wrong: " + s.ToString() + "\r\n"; return; @@ -2082,14 +1925,11 @@ void ConfigCmd::ConfigSet(std::string& ret) { ret = "+OK\r\n"; } else if (set_item == "arena-block-size") { if (!pstd::string2int(value.data(), value.size(), &ival)) { - ret = "-ERR Invalid argument \'" + value + - "\' for CONFIG SET 'arena-block-size'\r\n"; + ret = "-ERR Invalid argument \'" + value + "\' for CONFIG SET 'arena-block-size'\r\n"; return; } - std::unordered_map options_map{ - {"arena_block_size", value}}; - storage::Status s = g_pika_server->RewriteStorageOptions( - storage::OptionType::kColumnFamily, options_map); + std::unordered_map options_map{{"arena_block_size", value}}; + storage::Status s = g_pika_server->RewriteStorageOptions(storage::OptionType::kColumnFamily, options_map); if (!s.ok()) { ret = "-ERR Set arena-block-size wrong: " + s.ToString() + "\r\n"; return; @@ -2101,7 +1941,7 @@ void ConfigCmd::ConfigSet(std::string& ret) { } } -void ConfigCmd::ConfigRewrite(std::string &ret) { +void ConfigCmd::ConfigRewrite(std::string& ret) { if (g_pika_conf->ConfigRewrite()) { ret = "+OK\r\n"; } else { @@ -2129,12 +1969,9 @@ void MonitorCmd::Do(std::shared_ptr partition) { return; } std::shared_ptr conn = - std::dynamic_pointer_cast(conn_repl) - ->server_thread() - ->MoveConnOut(conn_repl->fd()); + std::dynamic_pointer_cast(conn_repl)->server_thread()->MoveConnOut(conn_repl->fd()); assert(conn.get() == conn_repl.get()); - g_pika_server->AddMonitorClient( - std::dynamic_pointer_cast(conn)); + g_pika_server->AddMonitorClient(std::dynamic_pointer_cast(conn)); g_pika_server->AddMonitorMessage("OK"); return; // Monitor thread will return "OK" } @@ -2157,8 +1994,7 @@ void DbsizeCmd::Do(std::shared_ptr partition) { res_.SetRes(CmdRes::kErrOther, "keyspace error"); return; } - int64_t dbsize = key_infos[0].keys + key_infos[1].keys + key_infos[2].keys + - key_infos[3].keys + key_infos[4].keys; + int64_t dbsize = key_infos[0].keys + key_infos[1].keys + key_infos[2].keys + key_infos[3].keys + key_infos[4].keys; res_.AppendInteger(dbsize); } } @@ -2217,8 +2053,7 @@ void DelbackupCmd::Do(std::shared_ptr partition) { continue; } - std::string str_date = dump_dir[i].substr( - db_sync_prefix.size(), (dump_dir[i].size() - db_sync_prefix.size())); + std::string str_date = dump_dir[i].substr(db_sync_prefix.size(), (dump_dir[i].size() - db_sync_prefix.size())); char* end = NULL; std::strtol(str_date.c_str(), &end, 10); if (*end != 0) { @@ -2231,8 +2066,7 @@ void DelbackupCmd::Do(std::shared_ptr partition) { pstd::DeleteDirIfExist(dump_dir_name); len--; } else { - LOG(INFO) << "Syncing, can not delete " << dump_dir_name << " dump file" - << std::endl; + LOG(INFO) << "Syncing, can not delete " << dump_dir_name << " dump file" << std::endl; } } res_.SetRes(CmdRes::kOk); @@ -2298,18 +2132,14 @@ void SlowlogCmd::DoInitial() { condition_ = SlowlogCmd::kRESET; } else if (argv_.size() == 2 && !strcasecmp(argv_[1].data(), "len")) { condition_ = SlowlogCmd::kLEN; - } else if ((argv_.size() == 2 || argv_.size() == 3) && - !strcasecmp(argv_[1].data(), "get")) { + } else if ((argv_.size() == 2 || argv_.size() == 3) && !strcasecmp(argv_[1].data(), "get")) { condition_ = SlowlogCmd::kGET; - if (argv_.size() == 3 && - !pstd::string2int(argv_[2].data(), argv_[2].size(), &number_)) { + if (argv_.size() == 3 && !pstd::string2int(argv_[2].data(), argv_[2].size(), &number_)) { res_.SetRes(CmdRes::kInvalidInt); return; } } else { - res_.SetRes( - CmdRes::kErrOther, - "Unknown SLOWLOG subcommand or wrong # of args. Try GET, RESET, LEN."); + res_.SetRes(CmdRes::kErrOther, "Unknown SLOWLOG subcommand or wrong # of args. Try GET, RESET, LEN."); return; } } @@ -2345,17 +2175,13 @@ void PaddingCmd::DoInitial() { } } -void PaddingCmd::Do(std::shared_ptr partition) { - res_.SetRes(CmdRes::kOk); -} +void PaddingCmd::Do(std::shared_ptr partition) { res_.SetRes(CmdRes::kOk); } -std::string PaddingCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, - uint64_t logic_id, uint32_t filenum, +std::string PaddingCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, uint64_t offset) { return PikaBinlogTransverter::ConstructPaddingBinlog( - BinlogType::TypeFirst, argv_[1].size() + BINLOG_ITEM_HEADER_SIZE + - PADDING_BINLOG_PROTOCOL_SIZE + - SPACE_STROE_PARAMETER_LENGTH); + BinlogType::TypeFirst, + argv_[1].size() + BINLOG_ITEM_HEADER_SIZE + PADDING_BINLOG_PROTOCOL_SIZE + SPACE_STROE_PARAMETER_LENGTH); } #ifdef TCMALLOC_EXTENSION @@ -2408,10 +2234,8 @@ void TcmallocCmd::Do(std::shared_ptr partition) { MallocExtension::instance()->GetFreeListSizes(&fli); res_.AppendArrayLen(fli.size()); for (auto& i : fli) { - res_.AppendString("type: " + std::string(i.type) + - ", min: " + std::to_string(i.min_object_size) + - ", max: " + std::to_string(i.max_object_size) + - ", total: " + std::to_string(i.total_bytes_free)); + res_.AppendString("type: " + std::string(i.type) + ", min: " + std::to_string(i.min_object_size) + ", max: " + + std::to_string(i.max_object_size) + ", total: " + std::to_string(i.total_bytes_free)); } break; case 3: @@ -2482,10 +2306,8 @@ void HelloCmd::Do(std::shared_ptr partition) { size_t next_arg = 1; long ver = 0; if (argv_.size() >= 2) { - if (!pstd::string2int(argv_[next_arg].data(), argv_[next_arg].size(), - &ver)) { - res_.SetRes(CmdRes::kErrOther, - "Protocol version is not an integer or out of range"); + if (!pstd::string2int(argv_[next_arg].data(), argv_[next_arg].size(), &ver)) { + res_.SetRes(CmdRes::kErrOther, "Protocol version is not an integer or out of range"); return; } next_arg++; @@ -2517,8 +2339,7 @@ void HelloCmd::Do(std::shared_ptr partition) { res_.SetRes(CmdRes::kInvalidPwd); return; case AuthResult::NO_REQUIRE_PASS: - res_.SetRes(CmdRes::kErrOther, - "Client sent AUTH, but no password is set"); + res_.SetRes(CmdRes::kErrOther, "Client sent AUTH, but no password is set"); return; case AuthResult::OK: break; @@ -2556,8 +2377,7 @@ void HelloCmd::Do(std::shared_ptr partition) { fvs.push_back({"role", "master&&slave"}); break; default: - LOG(INFO) << "unknown role" << host_role - << " client ip:port " << conn->ip_port(); + LOG(INFO) << "unknown role" << host_role << " client ip:port " << conn->ip_port(); return; } diff --git a/src/pika_auxiliary_thread.cc b/src/pika_auxiliary_thread.cc index 4446fbf00c..6c4214c695 100644 --- a/src/pika_auxiliary_thread.cc +++ b/src/pika_auxiliary_thread.cc @@ -5,9 +5,9 @@ #include "include/pika_auxiliary_thread.h" -#include "include/pika_server.h" #include "include/pika_define.h" #include "include/pika_rm.h" +#include "include/pika_server.h" extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; @@ -49,9 +49,8 @@ void* PikaAuxiliaryThread::ThreadMain() { cv_.TimedWait(100); mu_.Unlock(); } else { - //LOG_EVERY_N(INFO, 1000) << "Consume binlog number " << res; + // LOG_EVERY_N(INFO, 1000) << "Consume binlog number " << res; } } return NULL; } - diff --git a/src/pika_binlog.cc b/src/pika_binlog.cc index 7df1036f26..97e9129f51 100644 --- a/src/pika_binlog.cc +++ b/src/pika_binlog.cc @@ -22,8 +22,7 @@ std::string NewFileName(const std::string name, const uint32_t current) { /* * Version */ -Version::Version(pstd::RWFile *save) - : pro_num_(0), pro_offset_(0), logic_id_(0), save_(save) { +Version::Version(pstd::RWFile* save) : pro_num_(0), pro_offset_(0), logic_id_(0), save_(save) { assert(save_ != NULL); pthread_rwlock_init(&rwlock_, NULL); @@ -35,7 +34,7 @@ Version::~Version() { } Status Version::StableSave() { - char *p = save_->GetData(); + char* p = save_->GetData(); memcpy(p, &pro_num_, sizeof(uint32_t)); p += 4; memcpy(p, &pro_offset_, sizeof(uint64_t)); @@ -62,12 +61,17 @@ Status Version::Init() { /* * Binlog */ -Binlog::Binlog(const std::string &binlog_path, const int file_size) - : opened_(false), version_(NULL), queue_(NULL), versionfile_(NULL), - pro_num_(0), pool_(NULL), exit_all_consume_(false), - binlog_path_(binlog_path), file_size_(file_size), +Binlog::Binlog(const std::string& binlog_path, const int file_size) + : opened_(false), + version_(NULL), + queue_(NULL), + versionfile_(NULL), + pro_num_(0), + pool_(NULL), + exit_all_consume_(false), + binlog_path_(binlog_path), + file_size_(file_size), binlog_io_error_(false) { - // To intergrate with old version, we don't set mmap file size to 100M; // pstd::SetMmapBoundSize(file_size); // pstd::kMmapBoundSize = 1024 * 1024 * 100; @@ -115,8 +119,7 @@ Binlog::Binlog(const std::string &binlog_path, const int file_size) DLOG(INFO) << "Binlog: open profile " << profile; s = pstd::AppendWritableFile(profile, &queue_, version_->pro_offset_); if (!s.ok()) { - LOG(FATAL) << "Binlog: Open file " << profile << " error " - << s.ToString(); + LOG(FATAL) << "Binlog: Open file " << profile << " error " << s.ToString(); } uint64_t filesize = queue_->Filesize(); @@ -151,8 +154,7 @@ void Binlog::InitLogFile() { opened_.store(true); } -Status Binlog::GetProducerStatus(uint32_t *filenum, uint64_t *pro_offset, - uint32_t *term, uint64_t *logic_id) { +Status Binlog::GetProducerStatus(uint32_t* filenum, uint64_t* pro_offset, uint32_t* term, uint64_t* logic_id) { if (!opened_.load()) { return Status::Busy("Binlog is not open yet"); } @@ -172,7 +174,7 @@ Status Binlog::GetProducerStatus(uint32_t *filenum, uint64_t *pro_offset, } // Note: mutex lock should be held -Status Binlog::Put(const std::string &item) { +Status Binlog::Put(const std::string& item) { if (!opened_.load()) { return Status::Busy("Binlog is not open yet"); } @@ -184,13 +186,13 @@ Status Binlog::Put(const std::string &item) { } // Note: mutex lock should be held -Status Binlog::Put(const char *item, int len) { +Status Binlog::Put(const char* item, int len) { Status s; /* Check to roll log file */ uint64_t filesize = queue_->Filesize(); if (filesize > file_size_) { - pstd::WritableFile * queue = nullptr; + pstd::WritableFile* queue = nullptr; std::string profile = NewFileName(filename_, pro_num_ + 1); s = pstd::NewWritableFile(profile, &queue); if (!s.ok()) { @@ -222,8 +224,7 @@ Status Binlog::Put(const char *item, int len) { return s; } -Status Binlog::EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, - int *temp_pro_offset) { +Status Binlog::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset) { Status s; assert(n <= 0xffffff); assert(block_offset_ + kHeaderSize + n <= kBlockSize); @@ -256,9 +257,9 @@ Status Binlog::EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, return s; } -Status Binlog::Produce(const Slice &item, int *temp_pro_offset) { +Status Binlog::Produce(const Slice& item, int* temp_pro_offset) { Status s; - const char *ptr = item.data(); + const char* ptr = item.data(); size_t left = item.size(); bool begin = true; @@ -341,14 +342,12 @@ Status Binlog::AppendPadding(pstd::WritableFile* file, uint64_t* len) { } *len -= left; if (left != 0) { - LOG(WARNING) << "AppendPadding left bytes: " << left - << " is less then kHeaderSize"; + LOG(WARNING) << "AppendPadding left bytes: " << left << " is less then kHeaderSize"; } return s; } -Status Binlog::SetProducerStatus(uint32_t pro_num, uint64_t pro_offset, - uint32_t term, uint64_t index) { +Status Binlog::SetProducerStatus(uint32_t pro_num, uint64_t pro_offset, uint32_t term, uint64_t index) { if (!opened_.load()) { return Status::Busy("Binlog is not open yet"); } diff --git a/src/pika_binlog_reader.cc b/src/pika_binlog_reader.cc index cdad11054b..0adbf5ee59 100644 --- a/src/pika_binlog_reader.cc +++ b/src/pika_binlog_reader.cc @@ -7,8 +7,7 @@ #include -PikaBinlogReader::PikaBinlogReader(uint32_t cur_filenum, - uint64_t cur_offset) +PikaBinlogReader::PikaBinlogReader(uint32_t cur_filenum, uint64_t cur_offset) : cur_filenum_(cur_filenum), cur_offset_(cur_offset), logger_(nullptr), @@ -30,7 +29,6 @@ PikaBinlogReader::PikaBinlogReader() pthread_rwlock_init(&rwlock_, NULL); } - PikaBinlogReader::~PikaBinlogReader() { delete[] backing_store_; delete queue_; @@ -117,8 +115,7 @@ bool PikaBinlogReader::GetNext(uint64_t* size) { const unsigned int type = header[7]; const uint32_t length = a | (b << 8) | (c << 16); - if (length > (kBlockSize - kHeaderSize)) - return true; + if (length > (kBlockSize - kHeaderSize)) return true; if (type == kFullType) { s = queue_->Read(length, &buffer_, backing_store_); @@ -147,7 +144,7 @@ bool PikaBinlogReader::GetNext(uint64_t* size) { return is_error; } -unsigned int PikaBinlogReader::ReadPhysicalRecord(pstd::Slice *result, uint32_t* filenum, uint64_t* offset) { +unsigned int PikaBinlogReader::ReadPhysicalRecord(pstd::Slice* result, uint32_t* filenum, uint64_t* offset) { pstd::Status s; if (kBlockSize - last_record_offset_ <= kHeaderSize) { queue_->Skip(kBlockSize - last_record_offset_); @@ -170,8 +167,7 @@ unsigned int PikaBinlogReader::ReadPhysicalRecord(pstd::Slice *result, uint32_t* const unsigned int type = header[7]; const uint32_t length = a | (b << 8) | (c << 16); - if (length > (kBlockSize - kHeaderSize)) - return kBadRecord; + if (length > (kBlockSize - kHeaderSize)) return kBadRecord; if (type == kZeroType || length == 0) { buffer_.clear(); @@ -218,7 +214,8 @@ Status PikaBinlogReader::Consume(std::string* scratch, uint32_t* filenum, uint64 case kEof: return Status::EndFile("Eof"); case kBadRecord: - LOG(WARNING) << "Read BadRecord record, will decode failed, this record may dbsync padded record, not processed here"; + LOG(WARNING) + << "Read BadRecord record, will decode failed, this record may dbsync padded record, not processed here"; return Status::IOError("Data Corruption"); case kOldRecord: return Status::EndFile("Eof"); @@ -277,5 +274,3 @@ Status PikaBinlogReader::Get(std::string* scratch, uint32_t* filenum, uint64_t* return Status::OK(); } - - diff --git a/src/pika_binlog_transverter.cc b/src/pika_binlog_transverter.cc index 6194a94490..e6bc5b4129 100644 --- a/src/pika_binlog_transverter.cc +++ b/src/pika_binlog_transverter.cc @@ -5,65 +5,43 @@ #include "include/pika_binlog_transverter.h" -#include #include #include +#include #include "pstd/include/pstd_coding.h" #include "include/pika_command.h" -uint32_t BinlogItem::exec_time() const { - return exec_time_; -} +uint32_t BinlogItem::exec_time() const { return exec_time_; } -uint32_t BinlogItem::term_id() const { - return term_id_; -} +uint32_t BinlogItem::term_id() const { return term_id_; } -uint64_t BinlogItem::logic_id() const { - return logic_id_; -} +uint64_t BinlogItem::logic_id() const { return logic_id_; } -uint32_t BinlogItem::filenum() const { - return filenum_; -} +uint32_t BinlogItem::filenum() const { return filenum_; } -uint64_t BinlogItem::offset() const { - return offset_; -} +uint64_t BinlogItem::offset() const { return offset_; } -std::string BinlogItem::content() const { - return content_; -} +std::string BinlogItem::content() const { return content_; } -void BinlogItem::set_exec_time(uint32_t exec_time) { - exec_time_ = exec_time; -} +void BinlogItem::set_exec_time(uint32_t exec_time) { exec_time_ = exec_time; } -void BinlogItem::set_term_id(uint32_t term_id) { - term_id_ = term_id; -} +void BinlogItem::set_term_id(uint32_t term_id) { term_id_ = term_id; } -void BinlogItem::set_logic_id(uint64_t logic_id) { - logic_id_ = logic_id; -} +void BinlogItem::set_logic_id(uint64_t logic_id) { logic_id_ = logic_id; } -void BinlogItem::set_filenum(uint32_t filenum) { - filenum_ = filenum; -} +void BinlogItem::set_filenum(uint32_t filenum) { filenum_ = filenum; } -void BinlogItem::set_offset(uint64_t offset) { - offset_ = offset; -} +void BinlogItem::set_offset(uint64_t offset) { offset_ = offset; } std::string BinlogItem::ToString() const { std::string str; - str.append("exec_time: " + std::to_string(exec_time_)); + str.append("exec_time: " + std::to_string(exec_time_)); str.append(",term_id: " + std::to_string(term_id_)); - str.append(",logic_id: " + std::to_string(logic_id_)); - str.append(",filenum: " + std::to_string(filenum_)); - str.append(",offset: " + std::to_string(offset_)); + str.append(",logic_id: " + std::to_string(logic_id_)); + str.append(",filenum: " + std::to_string(filenum_)); + str.append(",offset: " + std::to_string(offset_)); str.append("\ncontent: "); for (size_t idx = 0; idx < content_.size(); ++idx) { if (content_[idx] == '\n') { @@ -78,14 +56,9 @@ std::string BinlogItem::ToString() const { return str; } -std::string PikaBinlogTransverter::BinlogEncode(BinlogType type, - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset, - const std::string& content, - const std::vector& extends) { +std::string PikaBinlogTransverter::BinlogEncode(BinlogType type, uint32_t exec_time, uint32_t term_id, + uint64_t logic_id, uint32_t filenum, uint64_t offset, + const std::string& content, const std::vector& extends) { std::string binlog; pstd::PutFixed16(&binlog, type); pstd::PutFixed32(&binlog, exec_time); @@ -99,9 +72,7 @@ std::string PikaBinlogTransverter::BinlogEncode(BinlogType type, return binlog; } -bool PikaBinlogTransverter::BinlogDecode(BinlogType type, - const std::string& binlog, - BinlogItem* binlog_item) { +bool PikaBinlogTransverter::BinlogDecode(BinlogType type, const std::string& binlog, BinlogItem* binlog_item) { uint16_t binlog_type = 0; uint32_t content_length = 0; std::string binlog_str = binlog; @@ -119,16 +90,18 @@ bool PikaBinlogTransverter::BinlogDecode(BinlogType type, if (binlog_str.size() == content_length) { binlog_item->content_.assign(binlog_str.data(), content_length); } else { - LOG(ERROR) << "Binlog Item get content error, expect length:" << content_length << " left length:" << binlog_str.size(); + LOG(ERROR) << "Binlog Item get content error, expect length:" << content_length + << " left length:" << binlog_str.size(); return false; } return true; } /* - * *************************************************Type First Binlog Item Format************************************************** - * | | | | | | | | | - * | 2 Bytes | 4 Bytes | 4 Bytes | 8 Bytes | 4 Bytes | 8 Bytes | 4 Bytes | content length Bytes | + * *************************************************Type First Binlog Item + * Format************************************************** | | | | + * | | | | | | 2 Bytes | 4 Bytes | 4 Bytes | 8 + * Bytes | 4 Bytes | 8 Bytes | 4 Bytes | content length Bytes | * |---------------------------------------------- 34 Bytes -----------------------------------------------| * * content: *2\r\n$7\r\npadding\r\n$00001\r\n***\r\n @@ -136,11 +109,9 @@ bool PikaBinlogTransverter::BinlogDecode(BinlogType type, * * We allocate five bytes to store the length of the parameter */ -std::string PikaBinlogTransverter::ConstructPaddingBinlog(BinlogType type, - uint32_t size) { +std::string PikaBinlogTransverter::ConstructPaddingBinlog(BinlogType type, uint32_t size) { assert(size <= kBlockSize - kHeaderSize); - assert(BINLOG_ITEM_HEADER_SIZE + PADDING_BINLOG_PROTOCOL_SIZE - + SPACE_STROE_PARAMETER_LENGTH <= size); + assert(BINLOG_ITEM_HEADER_SIZE + PADDING_BINLOG_PROTOCOL_SIZE + SPACE_STROE_PARAMETER_LENGTH <= size); std::string binlog; pstd::PutFixed16(&binlog, type); @@ -150,8 +121,7 @@ std::string PikaBinlogTransverter::ConstructPaddingBinlog(BinlogType type, pstd::PutFixed32(&binlog, 0); pstd::PutFixed64(&binlog, 0); int32_t content_len = size - BINLOG_ITEM_HEADER_SIZE; - int32_t parameter_len = content_len - PADDING_BINLOG_PROTOCOL_SIZE - - SPACE_STROE_PARAMETER_LENGTH; + int32_t parameter_len = content_len - PADDING_BINLOG_PROTOCOL_SIZE - SPACE_STROE_PARAMETER_LENGTH; if (parameter_len < 0) { return std::string(); } @@ -181,9 +151,8 @@ std::string PikaBinlogTransverter::ConstructPaddingBinlog(BinlogType type, return binlog; } -bool PikaBinlogTransverter::BinlogItemWithoutContentDecode(BinlogType type, - const std::string& binlog, - BinlogItem* binlog_item) { +bool PikaBinlogTransverter::BinlogItemWithoutContentDecode(BinlogType type, const std::string& binlog, + BinlogItem* binlog_item) { uint16_t binlog_type = 0; std::string binlog_str = binlog; pstd::GetFixed16(&binlog_str, &binlog_type); diff --git a/src/pika_bit.cc b/src/pika_bit.cc index 7d5ecad988..891d00a35b 100644 --- a/src/pika_bit.cc +++ b/src/pika_bit.cc @@ -28,7 +28,7 @@ void BitSetCmd::DoInitial() { return; } // value no bigger than 2^18 - if ( (bit_offset_ >> kMaxBitOpInputBit) > 0) { + if ((bit_offset_ >> kMaxBitOpInputBit) > 0) { res_.SetRes(CmdRes::kInvalidBitOffsetInt); return; } @@ -43,7 +43,7 @@ void BitSetCmd::Do(std::shared_ptr partition) { std::string value; int32_t bit_val = 0; rocksdb::Status s = partition->db()->SetBit(key_, bit_offset_, on_, &bit_val); - if (s.ok()){ + if (s.ok()) { res_.AppendInteger((int)bit_val); } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); @@ -140,14 +140,14 @@ void BitPosCmd::DoInitial() { if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &start_offset_)) { res_.SetRes(CmdRes::kInvalidInt); return; - } + } } else if (argv_.size() == 5) { pos_all_ = false; endoffset_set_ = true; if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &start_offset_)) { res_.SetRes(CmdRes::kInvalidInt); return; - } + } if (!pstd::string2int(argv_[4].data(), argv_[4].size(), &end_offset_)) { res_.SetRes(CmdRes::kInvalidInt); return; @@ -193,19 +193,19 @@ void BitOpCmd::DoInitial() { return; } if (op_ == storage::kBitOpNot && argv_.size() != 4) { - res_.SetRes(CmdRes::kWrongBitOpNotNum, kCmdNameBitOp); - return; + res_.SetRes(CmdRes::kWrongBitOpNotNum, kCmdNameBitOp); + return; } else if (op_ != storage::kBitOpNot && argv_.size() < 4) { - res_.SetRes(CmdRes::kWrongNum, kCmdNameBitOp); - return; + res_.SetRes(CmdRes::kWrongNum, kCmdNameBitOp); + return; } else if (argv_.size() >= kMaxBitOpInputKey) { - res_.SetRes(CmdRes::kWrongNum, kCmdNameBitOp); - return; + res_.SetRes(CmdRes::kWrongNum, kCmdNameBitOp); + return; } dest_key_ = argv_[2].data(); - for(unsigned int i = 3; i <= argv_.size() - 1; i++) { - src_keys_.push_back(argv_[i].data()); + for (unsigned int i = 3; i <= argv_.size() - 1; i++) { + src_keys_.push_back(argv_[i].data()); } return; } diff --git a/src/pika_client_conn.cc b/src/pika_client_conn.cc index e49037b620..b3273bfc2b 100644 --- a/src/pika_client_conn.cc +++ b/src/pika_client_conn.cc @@ -5,44 +5,38 @@ #include "include/pika_client_conn.h" -#include #include +#include #include -#include "include/pika_conf.h" -#include "include/pika_server.h" -#include "include/pika_cmd_table_manager.h" #include "include/pika_admin.h" +#include "include/pika_cmd_table_manager.h" +#include "include/pika_conf.h" #include "include/pika_rm.h" +#include "include/pika_server.h" extern PikaConf* g_pika_conf; extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; extern PikaCmdTableManager* g_pika_cmd_table_manager; -PikaClientConn::PikaClientConn(int fd, std::string ip_port, - net::Thread* thread, - net::NetMultiplexer* mpx, - const net::HandleType& handle_type, - int max_conn_rbuf_size) - : RedisConn(fd, ip_port, thread, mpx, handle_type, max_conn_rbuf_size), - server_thread_(reinterpret_cast(thread)), - current_table_(g_pika_conf->default_table()), - is_pubsub_(false) { +PikaClientConn::PikaClientConn(int fd, std::string ip_port, net::Thread* thread, net::NetMultiplexer* mpx, + const net::HandleType& handle_type, int max_conn_rbuf_size) + : RedisConn(fd, ip_port, thread, mpx, handle_type, max_conn_rbuf_size), + server_thread_(reinterpret_cast(thread)), + current_table_(g_pika_conf->default_table()), + is_pubsub_(false) { auth_stat_.Init(); } -std::shared_ptr PikaClientConn::DoCmd( - const PikaCmdArgsType& argv, - const std::string& opt, - std::shared_ptr resp_ptr) { +std::shared_ptr PikaClientConn::DoCmd(const PikaCmdArgsType& argv, const std::string& opt, + std::shared_ptr resp_ptr) { // Get command info std::shared_ptr c_ptr = g_pika_cmd_table_manager->GetCmd(opt); if (!c_ptr) { std::shared_ptr tmp_ptr = std::make_shared(DummyCmd()); - tmp_ptr->res().SetRes(CmdRes::kErrOther, - "unknown command \"" + opt + "\""); + tmp_ptr->res().SetRes(CmdRes::kErrOther, "unknown command \"" + opt + "\""); return tmp_ptr; } c_ptr->SetConn(std::dynamic_pointer_cast(shared_from_this())); @@ -76,13 +70,10 @@ std::shared_ptr PikaClientConn::DoCmd( // PubSub connection // (P)SubscribeCmd will set is_pubsub_ if (this->IsPubSub()) { - if (opt != kCmdNameSubscribe && - opt != kCmdNameUnSubscribe && - opt != kCmdNamePing && - opt != kCmdNamePSubscribe && + if (opt != kCmdNameSubscribe && opt != kCmdNameUnSubscribe && opt != kCmdNamePing && opt != kCmdNamePSubscribe && opt != kCmdNamePUnSubscribe) { c_ptr->res().SetRes(CmdRes::kErrOther, - "only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context"); + "only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context"); return c_ptr; } } @@ -91,8 +82,7 @@ std::shared_ptr PikaClientConn::DoCmd( c_ptr->SetStage(Cmd::kBinlogStage); } if (!g_pika_server->IsCommandSupport(opt)) { - c_ptr->res().SetRes(CmdRes::kErrOther, - "This command is not supported in current configuration"); + c_ptr->res().SetRes(CmdRes::kErrOther, "This command is not supported in current configuration"); return c_ptr; } @@ -150,7 +140,7 @@ void PikaClientConn::ProcessSlowlog(const PikaCmdArgsType& argv, uint64_t start_ std::string slow_log; uint32_t cmd_size = 0; for (unsigned int i = 0; i < argv.size(); i++) { - cmd_size += 1 + argv[i].size(); // blank space and argument length + cmd_size += 1 + argv[i].size(); // blank space and argument length if (!trim) { slow_log.append(" "); slow_log.append(pstd::ToRead(argv[i])); @@ -161,27 +151,26 @@ void PikaClientConn::ProcessSlowlog(const PikaCmdArgsType& argv, uint64_t start_ } } } - LOG(ERROR) << "ip_port: " << ip_port() << ", table: " << current_table_ - << ", command:" << slow_log << ", command_size: " << cmd_size - 1 - << ", arguments: " << argv.size() << ", start_time(s): " << start_time - << ", duration(us): " << duration << ", do_duration_(us): " << do_duration; + LOG(ERROR) << "ip_port: " << ip_port() << ", table: " << current_table_ << ", command:" << slow_log + << ", command_size: " << cmd_size - 1 << ", arguments: " << argv.size() + << ", start_time(s): " << start_time << ", duration(us): " << duration + << ", do_duration_(us): " << do_duration; } } } void PikaClientConn::ProcessMonitor(const PikaCmdArgsType& argv) { std::string monitor_message; - std::string table_name = g_pika_conf->classic_mode() - ? current_table_.substr(2) : current_table_; - monitor_message = std::to_string(1.0*pstd::NowMicros()/1000000) + - " [" + table_name + " " + this->ip_port() + "]"; + std::string table_name = g_pika_conf->classic_mode() ? current_table_.substr(2) : current_table_; + monitor_message = std::to_string(1.0 * pstd::NowMicros() / 1000000) + " [" + table_name + " " + this->ip_port() + "]"; for (PikaCmdArgsType::const_iterator iter = argv.begin(); iter != argv.end(); iter++) { monitor_message += " " + pstd::ToRead(*iter); } g_pika_server->AddMonitorMessage(monitor_message); } -void PikaClientConn::ProcessRedisCmds(const std::vector& argvs, bool async, std::string* response) { +void PikaClientConn::ProcessRedisCmds(const std::vector& argvs, bool async, + std::string* response) { if (async) { BgTaskArg* arg = new BgTaskArg(); arg->redis_cmds = argvs; @@ -229,11 +218,11 @@ void PikaClientConn::DoExecTask(void* arg) { cmd_ptr->SetStage(Cmd::kExecuteStage); cmd_ptr->Execute(); if (g_pika_conf->slowlog_slower_than() >= 0) { - conn_ptr->ProcessSlowlog(cmd_ptr->argv(), start_us, cmd_ptr->GetDoDuration()); + conn_ptr->ProcessSlowlog(cmd_ptr->argv(), start_us, cmd_ptr->GetDoDuration()); } std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (partition == nullptr) { LOG(WARNING) << "Sync Master Partition not exist " << table_name << partition_id; return; @@ -276,13 +265,12 @@ void PikaClientConn::TryWriteResp() { } } - void PikaClientConn::ExecRedisCmd(const PikaCmdArgsType& argv, std::shared_ptr resp_ptr) { // get opt std::string opt = argv[0]; pstd::StringToLower(opt); if (opt == kClusterPrefix) { - if (argv.size() >= 2 ) { + if (argv.size() >= 2) { opt += argv[1]; pstd::StringToLower(opt); } @@ -299,10 +287,8 @@ void PikaClientConn::ExecRedisCmd(const PikaCmdArgsType& argv, std::shared_ptruserpass() == "" ? - kLimitAuthed : kNoAuthed; - if (stat_ == kLimitAuthed - && g_pika_conf->requirepass() == "") { + stat_ = g_pika_conf->userpass() == "" ? kLimitAuthed : kNoAuthed; + if (stat_ == kLimitAuthed && g_pika_conf->requirepass() == "") { stat_ = kAdminAuthed; } } @@ -320,9 +306,8 @@ bool PikaClientConn::AuthStat::IsAuthed(const std::shared_ptr cmd_ptr) { case kAdminAuthed: break; case kLimitAuthed: - if (cmd_ptr->is_admin_require() - || find(blacklist.begin(), blacklist.end(), opt) != blacklist.end()) { - return false; + if (cmd_ptr->is_admin_require() || find(blacklist.begin(), blacklist.end(), opt) != blacklist.end()) { + return false; } break; default: @@ -346,11 +331,6 @@ bool PikaClientConn::AuthStat::ChecknUpdate(const std::string& message) { } // compare addr in ClientInfo -bool AddrCompare(const ClientInfo& lhs, const ClientInfo& rhs) { - return rhs.ip_port < lhs.ip_port; -} - -bool IdleCompare(const ClientInfo& lhs, const ClientInfo& rhs) { - return lhs.last_interaction < rhs.last_interaction; -} +bool AddrCompare(const ClientInfo& lhs, const ClientInfo& rhs) { return rhs.ip_port < lhs.ip_port; } +bool IdleCompare(const ClientInfo& lhs, const ClientInfo& rhs) { return lhs.last_interaction < rhs.last_interaction; } diff --git a/src/pika_client_processor.cc b/src/pika_client_processor.cc index 33e44e925e..14b7979f89 100644 --- a/src/pika_client_processor.cc +++ b/src/pika_client_processor.cc @@ -7,10 +7,8 @@ #include -PikaClientProcessor::PikaClientProcessor( - size_t worker_num, size_t max_queue_size, const std::string& name_prefix) { - pool_ = new net::ThreadPool( - worker_num, max_queue_size, name_prefix + "Pool"); +PikaClientProcessor::PikaClientProcessor(size_t worker_num, size_t max_queue_size, const std::string& name_prefix) { + pool_ = new net::ThreadPool(worker_num, max_queue_size, name_prefix + "Pool"); for (size_t i = 0; i < worker_num; ++i) { net::BGThread* bg_thread = new net::BGThread(max_queue_size); bg_threads_.push_back(bg_thread); @@ -47,12 +45,9 @@ void PikaClientProcessor::Stop() { } } -void PikaClientProcessor::SchedulePool(net::TaskFunc func, void* arg) { - pool_->Schedule(func, arg); -} +void PikaClientProcessor::SchedulePool(net::TaskFunc func, void* arg) { pool_->Schedule(func, arg); } -void PikaClientProcessor::ScheduleBgThreads( - net::TaskFunc func, void* arg, const std::string& hash_str) { +void PikaClientProcessor::ScheduleBgThreads(net::TaskFunc func, void* arg, const std::string& hash_str) { std::size_t index = std::hash{}(hash_str) % bg_threads_.size(); bg_threads_[index]->Schedule(func, arg); } @@ -64,4 +59,3 @@ size_t PikaClientProcessor::ThreadPoolCurQueueSize() { } return cur_size; } - diff --git a/src/pika_cluster.cc b/src/pika_cluster.cc index 2481e70c50..5bff473d3f 100644 --- a/src/pika_cluster.cc +++ b/src/pika_cluster.cc @@ -3,11 +3,11 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include "include/pika_rm.h" -#include "include/pika_table.h" -#include "include/pika_server.h" #include "include/pika_cluster.h" #include "include/pika_cmd_table_manager.h" +#include "include/pika_rm.h" +#include "include/pika_server.h" +#include "include/pika_table.h" extern PikaReplicaManager* g_pika_rm; extern PikaServer* g_pika_server; @@ -151,8 +151,8 @@ bool PkClusterInfoCmd::ParseInfoTableSubCmd() { return true; } -void PkClusterInfoCmd::ClusterInfoSlotRange(const std::string& table_name, - const std::set slots, std::string* info) { +void PkClusterInfoCmd::ClusterInfoSlotRange(const std::string& table_name, const std::set slots, + std::string* info) { std::stringstream tmp_stream; for (const auto& partition_id : slots) { std::string p_info; @@ -183,11 +183,9 @@ void PkClusterInfoCmd::ClusterInfoSlotAll(std::string* info) { info->append(tmp_stream.str()); } -Status PkClusterInfoCmd::GetSlotInfo(const std::string table_name, - uint32_t partition_id, - std::string* info) { +Status PkClusterInfoCmd::GetSlotInfo(const std::string table_name, uint32_t partition_id, std::string* info) { std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!partition) { return Status::NotFound("not found"); } @@ -198,16 +196,14 @@ Status PkClusterInfoCmd::GetSlotInfo(const std::string table_name, uint32_t filenum = 0; uint64_t offset = 0; partition->Logger()->GetProducerStatus(&filenum, &offset); - tmp_stream << partition->PartitionName() << " binlog_offset=" - << filenum << " " << offset; + tmp_stream << partition->PartitionName() << " binlog_offset=" << filenum << " " << offset; // safety purge section std::string safety_purge; std::shared_ptr master_partition = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!master_partition) { - LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id << ", NotFound"; s = Status::NotFound("SyncMasterPartition NotFound"); } else { master_partition->GetSafetyPurgeBinlog(&safety_purge); @@ -230,17 +226,15 @@ Status PkClusterInfoCmd::GetSlotInfo(const std::string table_name, return Status::OK(); } -Status ParseSlotGroup(const std::string& slot_group, - std::set* slots) { +Status ParseSlotGroup(const std::string& slot_group, std::set* slots) { std::set tmp_slots; int64_t slot_idx, start_idx, end_idx; std::string::size_type pos; std::vector elems; pstd::StringSplit(slot_group, COMMA, elems); - for (const auto& elem : elems) { + for (const auto& elem : elems) { if ((pos = elem.find("-")) == std::string::npos) { - if (!pstd::string2int(elem.data(), elem.size(), &slot_idx) - || slot_idx < 0) { + if (!pstd::string2int(elem.data(), elem.size(), &slot_idx) || slot_idx < 0) { return Status::Corruption("syntax error"); } else { tmp_slots.insert(static_cast(slot_idx)); @@ -251,9 +245,9 @@ Status ParseSlotGroup(const std::string& slot_group, } else { std::string start_pos = elem.substr(0, pos); std::string end_pos = elem.substr(pos + 1, elem.size() - pos); - if (!pstd::string2int(start_pos.data(), start_pos.size(), &start_idx) - || !pstd::string2int(end_pos.data(), end_pos.size(), &end_idx) - || start_idx < 0 || end_idx < 0 || start_idx > end_idx) { + if (!pstd::string2int(start_pos.data(), start_pos.size(), &start_idx) || + !pstd::string2int(end_pos.data(), end_pos.size(), &end_idx) || start_idx < 0 || end_idx < 0 || + start_idx > end_idx) { return Status::Corruption("syntax error"); } for (int64_t idx = start_idx; idx <= end_idx; ++idx) { @@ -319,10 +313,8 @@ void PkClusterAddSlotsCmd::Do(std::shared_ptr partition) { } SlotState expected = INFREE; - if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, - &expected, INBUSY)) { - res_.SetRes(CmdRes::kErrOther, - "Slot in syncing or a change operation is under way, retry later"); + if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, &expected, INBUSY)) { + res_.SetRes(CmdRes::kErrOther, "Slot in syncing or a change operation is under way, retry later"); return; } @@ -408,10 +400,8 @@ void PkClusterDelSlotsCmd::Do(std::shared_ptr partition) { } SlotState expected = INFREE; - if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, - &expected, INBUSY)) { - res_.SetRes(CmdRes::kErrOther, - "Slot in syncing or a change operation is under way, retry later"); + if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, &expected, INBUSY)) { + res_.SetRes(CmdRes::kErrOther, "Slot in syncing or a change operation is under way, retry later"); return; } @@ -493,19 +483,16 @@ void PkClusterSlotsSlaveofCmd::DoInitial() { return; } - if (!strcasecmp(argv_[2].data(), "no") - && !strcasecmp(argv_[3].data(), "one")) { + if (!strcasecmp(argv_[2].data(), "no") && !strcasecmp(argv_[3].data(), "one")) { is_noone_ = true; } else { ip_ = argv_[2]; - if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &port_) - || port_ <= 0) { + if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &port_) || port_ <= 0) { res_.SetRes(CmdRes::kInvalidInt); return; } - if ((ip_ == "127.0.0.1" || ip_ == g_pika_server->host()) - && port_ == g_pika_server->port()) { + if ((ip_ == "127.0.0.1" || ip_ == g_pika_server->host()) && port_ == g_pika_server->port()) { res_.SetRes(CmdRes::kErrOther, "You fucked up"); return; } @@ -541,8 +528,7 @@ void PkClusterSlotsSlaveofCmd::DoInitial() { } break; case 7: - if ((!strcasecmp(argv_[5].data(), "force")) - && (pstd::string2int(argv_[6].data(), argv_[6].size(), &table_id))) { + if ((!strcasecmp(argv_[5].data(), "force")) && (pstd::string2int(argv_[6].data(), argv_[6].size(), &table_id))) { force_sync_ = true; table_name_ = "db"; table_name_ += std::to_string(table_id); @@ -574,16 +560,15 @@ void PkClusterSlotsSlaveofCmd::Do(std::shared_ptr partition) { std::vector to_del_slots; for (const auto& slot : slots_) { std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_name_, slot)); + g_pika_rm->GetSyncSlavePartitionByName(PartitionInfo(table_name_, slot)); if (!slave_partition) { res_.SetRes(CmdRes::kErrOther, "Slot " + std::to_string(slot) + " not found!"); return; } if (is_noone_) { // check okay - } else if (slave_partition->State() == ReplState::kConnected - && slave_partition->MasterIp() == ip_ && slave_partition->MasterPort() == port_) { + } else if (slave_partition->State() == ReplState::kConnected && slave_partition->MasterIp() == ip_ && + slave_partition->MasterPort() == port_) { to_del_slots.push_back(slot); } } @@ -593,12 +578,10 @@ void PkClusterSlotsSlaveofCmd::Do(std::shared_ptr partition) { } Status s = Status::OK(); - ReplState state = force_sync_ - ? ReplState::kTryDBSync : ReplState::kTryConnect; + ReplState state = force_sync_ ? ReplState::kTryDBSync : ReplState::kTryConnect; for (const auto& slot : slots_) { std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_name_, slot)); + g_pika_rm->GetSyncSlavePartitionByName(PartitionInfo(table_name_, slot)); if (slave_partition->State() == ReplState::kConnected) { s = g_pika_rm->SendRemoveSlaveNodeRequest(table_name_, slot); } @@ -611,8 +594,7 @@ void PkClusterSlotsSlaveofCmd::Do(std::shared_ptr partition) { } if (is_noone_) { } else { - s = g_pika_rm->ActivateSyncSlavePartition( - RmNode(ip_, port_, table_name_, slot), state); + s = g_pika_rm->ActivateSyncSlavePartition(RmNode(ip_, port_, table_name_, slot), state); if (!s.ok()) { break; } @@ -646,8 +628,7 @@ void PkClusterAddTableCmd::DoInitial() { } table_name_ = "db"; table_name_ += std::to_string(table_id); - if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &slot_num_) - || slot_num_ == 0) { + if (!pstd::string2int(argv_[3].data(), argv_[3].size(), &slot_num_) || slot_num_ == 0) { res_.SetRes(CmdRes::kErrOther, "syntax error"); return; } @@ -661,10 +642,8 @@ void PkClusterAddTableCmd::Do(std::shared_ptr partition) { } SlotState expected = INFREE; - if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, - &expected, INBUSY)) { - res_.SetRes(CmdRes::kErrOther, - "Table/Slot in syncing or a change operation is under way, retry later"); + if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, &expected, INBUSY)) { + res_.SetRes(CmdRes::kErrOther, "Table/Slot in syncing or a change operation is under way, retry later"); return; } @@ -675,14 +654,14 @@ void PkClusterAddTableCmd::Do(std::shared_ptr partition) { pre_success = false; } if (pre_success) { - s = g_pika_conf->AddTable(table_name_,slot_num_); + s = g_pika_conf->AddTable(table_name_, slot_num_); if (!s.ok()) { LOG(WARNING) << "Addslots add to pika conf failed: " << s.ToString(); pre_success = false; } } if (pre_success) { - s = g_pika_server->AddTableStruct(table_name_,slot_num_); + s = g_pika_server->AddTableStruct(table_name_, slot_num_); if (!s.ok()) { LOG(WARNING) << "Addslots add to pika conf failed: " << s.ToString(); pre_success = false; @@ -700,7 +679,7 @@ void PkClusterAddTableCmd::Do(std::shared_ptr partition) { } Status PkClusterAddTableCmd::AddTableSanityCheck() { - Status s = g_pika_conf->AddTableSanityCheck(table_name_); + Status s = g_pika_conf->AddTableSanityCheck(table_name_); if (!s.ok()) { return s; } @@ -730,10 +709,9 @@ void PkClusterDelTableCmd::DoInitial() { return; } table_name_ = "db"; - table_name_ += std::to_string(table_id); + table_name_ += std::to_string(table_id); } - void PkClusterDelTableCmd::Do(std::shared_ptr partition) { std::shared_ptr
table_ptr = g_pika_server->GetTable(table_name_); if (!table_ptr) { @@ -750,10 +728,8 @@ void PkClusterDelTableCmd::Do(std::shared_ptr partition) { } SlotState expected = INFREE; - if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, - &expected, INBUSY)) { - res_.SetRes(CmdRes::kErrOther, - "Table/Slot in syncing or a change operation is under way, retry later"); + if (!std::atomic_compare_exchange_strong(&g_pika_server->slot_state_, &expected, INBUSY)) { + res_.SetRes(CmdRes::kErrOther, "Table/Slot in syncing or a change operation is under way, retry later"); return; } @@ -796,8 +772,8 @@ void PkClusterDelTableCmd::Do(std::shared_ptr partition) { LOG(INFO) << "Pika meta file overwrite success"; } -Status PkClusterDelTableCmd::DelTableSanityCheck(const std::string &table_name) { - Status s = g_pika_conf->DelTableSanityCheck(table_name); +Status PkClusterDelTableCmd::DelTableSanityCheck(const std::string& table_name) { + Status s = g_pika_conf->DelTableSanityCheck(table_name); if (!s.ok()) { return s; } @@ -808,6 +784,6 @@ Status PkClusterDelTableCmd::DelTableSanityCheck(const std::string &table_name) if (!table_ptr->TableIsEmpty()) { return Status::Corruption("table have slots!"); } - s = g_pika_rm->SyncTableSanityCheck(table_name); + s = g_pika_rm->SyncTableSanityCheck(table_name); return s; } diff --git a/src/pika_cmd_table_manager.cc b/src/pika_cmd_table_manager.cc index b0cb6ffb48..152cabf770 100644 --- a/src/pika_cmd_table_manager.cc +++ b/src/pika_cmd_table_manager.cc @@ -5,13 +5,12 @@ #include "include/pika_cmd_table_manager.h" -#include #include +#include #include "include/pika_conf.h" #include "pstd/include/pstd_mutex.h" - extern PikaConf* g_pika_conf; PikaCmdTableManager::PikaCmdTableManager() { @@ -23,7 +22,7 @@ PikaCmdTableManager::PikaCmdTableManager() { PikaCmdTableManager::~PikaCmdTableManager() { pthread_rwlock_destroy(&map_protector_); - for (const auto&item : thread_distribution_map_) { + for (const auto& item : thread_distribution_map_) { delete item.second; } DestoryCmdTable(cmds_); diff --git a/src/pika_command.cc b/src/pika_command.cc index 1d879dbde3..407903336f 100644 --- a/src/pika_command.cc +++ b/src/pika_command.cc @@ -5,28 +5,28 @@ #include "include/pika_command.h" -#include "include/pika_kv.h" +#include "include/pika_admin.h" #include "include/pika_bit.h" -#include "include/pika_set.h" +#include "include/pika_cluster.h" +#include "include/pika_cmd_table_manager.h" #include "include/pika_geo.h" -#include "include/pika_list.h" -#include "include/pika_zset.h" #include "include/pika_hash.h" -#include "include/pika_admin.h" -#include "include/pika_pubsub.h" #include "include/pika_hyperloglog.h" -#include "include/pika_slot.h" -#include "include/pika_cluster.h" -#include "include/pika_server.h" +#include "include/pika_kv.h" +#include "include/pika_list.h" +#include "include/pika_pubsub.h" #include "include/pika_rm.h" -#include "include/pika_cmd_table_manager.h" +#include "include/pika_server.h" +#include "include/pika_set.h" +#include "include/pika_slot.h" +#include "include/pika_zset.h" extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; extern PikaCmdTableManager* g_pika_cmd_table_manager; -void InitCmdTable(std::unordered_map *cmd_table) { - //Admin +void InitCmdTable(std::unordered_map* cmd_table) { + // Admin ////Slaveof Cmd* slaveofptr = new SlaveofCmd(kCmdNameSlaveof, -3, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlaveof, slaveofptr)); @@ -88,17 +88,21 @@ void InitCmdTable(std::unordered_map *cmd_table) { cmd_table->insert(std::pair(kCmdNameSlotsHashKey, slotshashkeyptr)); Cmd* slotmgrtslotasyncptr = new SlotsMgrtSlotAsyncCmd(kCmdNameSlotsMgrtSlotAsync, 8, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsMgrtSlotAsync, slotmgrtslotasyncptr)); - Cmd* slotmgrttagslotasyncptr = new SlotsMgrtTagSlotAsyncCmd(kCmdNameSlotsMgrtTagSlotAsync, 8, kCmdFlagsRead | kCmdFlagsAdmin); + Cmd* slotmgrttagslotasyncptr = + new SlotsMgrtTagSlotAsyncCmd(kCmdNameSlotsMgrtTagSlotAsync, 8, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsMgrtTagSlotAsync, slotmgrttagslotasyncptr)); Cmd* slotsdelptr = new SlotsDelCmd(kCmdNameSlotsDel, -2, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsDel, slotsdelptr)); Cmd* slotsscanptr = new SlotsScanCmd(kCmdNameSlotsScan, -3, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsScan, slotsscanptr)); - Cmd* slotmgrtexecwrapper = new SlotsMgrtExecWrapperCmd(kCmdNameSlotsMgrtExecWrapper, -3, kCmdFlagsRead | kCmdFlagsAdmin); + Cmd* slotmgrtexecwrapper = + new SlotsMgrtExecWrapperCmd(kCmdNameSlotsMgrtExecWrapper, -3, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsMgrtExecWrapper, slotmgrtexecwrapper)); - Cmd* slotmgrtasyncstatus = new SlotsMgrtAsyncStatusCmd(kCmdNameSlotsMgrtAsyncStatus, 1, kCmdFlagsRead | kCmdFlagsAdmin); + Cmd* slotmgrtasyncstatus = + new SlotsMgrtAsyncStatusCmd(kCmdNameSlotsMgrtAsyncStatus, 1, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsMgrtAsyncStatus, slotmgrtasyncstatus)); - Cmd* slotmgrtasynccancel = new SlotsMgrtAsyncCancelCmd(kCmdNameSlotsMgrtAsyncCancel, 1, kCmdFlagsRead | kCmdFlagsAdmin); + Cmd* slotmgrtasynccancel = + new SlotsMgrtAsyncCancelCmd(kCmdNameSlotsMgrtAsyncCancel, 1, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsMgrtAsyncCancel, slotmgrtasynccancel)); Cmd* slotmgrtslotptr = new SlotsMgrtSlotCmd(kCmdNameSlotsMgrtSlot, 5, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNameSlotsMgrtSlot, slotmgrtslotptr)); @@ -116,7 +120,8 @@ void InitCmdTable(std::unordered_map *cmd_table) { cmd_table->insert(std::pair(kCmdNamePkClusterAddSlots, pkclusteraddslotsptr)); Cmd* pkclusterdelslotsptr = new PkClusterDelSlotsCmd(kCmdNamePkClusterDelSlots, -3, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNamePkClusterDelSlots, pkclusterdelslotsptr)); - Cmd* pkclusterslotsslaveofptr = new PkClusterSlotsSlaveofCmd(kCmdNamePkClusterSlotsSlaveof, -5, kCmdFlagsRead | kCmdFlagsAdmin); + Cmd* pkclusterslotsslaveofptr = + new PkClusterSlotsSlaveofCmd(kCmdNamePkClusterSlotsSlaveof, -5, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNamePkClusterSlotsSlaveof, pkclusterslotsslaveofptr)); Cmd* pkclusteraddtableptr = new PkClusterAddTableCmd(kCmdNamePkClusterAddTable, 4, kCmdFlagsRead | kCmdFlagsAdmin); cmd_table->insert(std::pair(kCmdNamePkClusterAddTable, pkclusteraddtableptr)); @@ -127,7 +132,7 @@ void InitCmdTable(std::unordered_map *cmd_table) { cmd_table->insert(std::pair(kCmdNameTcmalloc, tcmallocptr)); #endif - //Kv + // Kv ////SetCmd Cmd* setptr = new SetCmd(kCmdNameSet, -3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsKv); cmd_table->insert(std::pair(kCmdNameSet, setptr)); @@ -146,7 +151,8 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* incrbyptr = new IncrbyCmd(kCmdNameIncrby, 3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsKv); cmd_table->insert(std::pair(kCmdNameIncrby, incrbyptr)); ////IncrbyfloatCmd - Cmd* incrbyfloatptr = new IncrbyfloatCmd(kCmdNameIncrbyfloat, 3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsKv); + Cmd* incrbyfloatptr = + new IncrbyfloatCmd(kCmdNameIncrbyfloat, 3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsKv); cmd_table->insert(std::pair(kCmdNameIncrbyfloat, incrbyfloatptr)); ////DecrCmd Cmd* decrptr = new DecrCmd(kCmdNameDecr, 2, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsKv); @@ -230,13 +236,15 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* pksetexatptr = new PKSetexAtCmd(kCmdNamePKSetexAt, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsKv); cmd_table->insert(std::pair(kCmdNamePKSetexAt, pksetexatptr)); ////PKScanRange - Cmd* pkscanrangeptr = new PKScanRangeCmd(kCmdNamePKScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsKv); + Cmd* pkscanrangeptr = + new PKScanRangeCmd(kCmdNamePKScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsKv); cmd_table->insert(std::pair(kCmdNamePKScanRange, pkscanrangeptr)); ////PKRScanRange - Cmd* pkrscanrangeptr = new PKRScanRangeCmd(kCmdNamePKRScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsKv); + Cmd* pkrscanrangeptr = + new PKRScanRangeCmd(kCmdNamePKRScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsKv); cmd_table->insert(std::pair(kCmdNamePKRScanRange, pkrscanrangeptr)); - //Hash + // Hash ////HDelCmd Cmd* hdelptr = new HDelCmd(kCmdNameHDel, -3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsHash); cmd_table->insert(std::pair(kCmdNameHDel, hdelptr)); @@ -253,10 +261,11 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* hexistsptr = new HExistsCmd(kCmdNameHExists, 3, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsHash); cmd_table->insert(std::pair(kCmdNameHExists, hexistsptr)); ////HIncrbyCmd - Cmd* hincrbyptr = new HIncrbyCmd(kCmdNameHIncrby, 4, kCmdFlagsWrite |kCmdFlagsSinglePartition | kCmdFlagsHash); + Cmd* hincrbyptr = new HIncrbyCmd(kCmdNameHIncrby, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsHash); cmd_table->insert(std::pair(kCmdNameHIncrby, hincrbyptr)); ////HIncrbyfloatCmd - Cmd* hincrbyfloatptr = new HIncrbyfloatCmd(kCmdNameHIncrbyfloat, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsHash); + Cmd* hincrbyfloatptr = + new HIncrbyfloatCmd(kCmdNameHIncrbyfloat, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsHash); cmd_table->insert(std::pair(kCmdNameHIncrbyfloat, hincrbyfloatptr)); ////HKeysCmd Cmd* hkeysptr = new HKeysCmd(kCmdNameHKeys, 2, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsHash); @@ -286,13 +295,15 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* hscanxptr = new HScanxCmd(kCmdNameHScanx, -3, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsHash); cmd_table->insert(std::pair(kCmdNameHScanx, hscanxptr)); ////PKHScanRange - Cmd* pkhscanrangeptr = new PKHScanRangeCmd(kCmdNamePKHScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsHash); + Cmd* pkhscanrangeptr = + new PKHScanRangeCmd(kCmdNamePKHScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsHash); cmd_table->insert(std::pair(kCmdNamePKHScanRange, pkhscanrangeptr)); ////PKHRScanRange - Cmd* pkhrscanrangeptr = new PKHRScanRangeCmd(kCmdNamePKHRScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsHash); + Cmd* pkhrscanrangeptr = + new PKHRScanRangeCmd(kCmdNamePKHRScanRange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsHash); cmd_table->insert(std::pair(kCmdNamePKHRScanRange, pkhrscanrangeptr)); - //List + // List Cmd* lindexptr = new LIndexCmd(kCmdNameLIndex, 3, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsList); cmd_table->insert(std::pair(kCmdNameLIndex, lindexptr)); Cmd* linsertptr = new LInsertCmd(kCmdNameLInsert, 5, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsList); @@ -322,7 +333,7 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* rpushxptr = new RPushxCmd(kCmdNameRPushx, 3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsList); cmd_table->insert(std::pair(kCmdNameRPushx, rpushxptr)); - //Zset + // Zset ////ZAddCmd Cmd* zaddptr = new ZAddCmd(kCmdNameZAdd, -4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZAdd, zaddptr)); @@ -342,10 +353,12 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* zrevrangeptr = new ZRevrangeCmd(kCmdNameZRevrange, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRevrange, zrevrangeptr)); ////ZRangebyscoreCmd - Cmd* zrangebyscoreptr = new ZRangebyscoreCmd(kCmdNameZRangebyscore, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); + Cmd* zrangebyscoreptr = + new ZRangebyscoreCmd(kCmdNameZRangebyscore, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRangebyscore, zrangebyscoreptr)); ////ZRevrangebyscoreCmd - Cmd* zrevrangebyscoreptr = new ZRevrangebyscoreCmd(kCmdNameZRevrangebyscore, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); + Cmd* zrevrangebyscoreptr = + new ZRevrangebyscoreCmd(kCmdNameZRevrangebyscore, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRevrangebyscore, zrevrangebyscoreptr)); ////ZCountCmd Cmd* zcountptr = new ZCountCmd(kCmdNameZCount, 4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); @@ -354,10 +367,12 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* zremptr = new ZRemCmd(kCmdNameZRem, -3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRem, zremptr)); ////ZUnionstoreCmd - Cmd* zunionstoreptr = new ZUnionstoreCmd(kCmdNameZUnionstore, -4, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsZset); + Cmd* zunionstoreptr = + new ZUnionstoreCmd(kCmdNameZUnionstore, -4, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZUnionstore, zunionstoreptr)); ////ZInterstoreCmd - Cmd* zinterstoreptr = new ZInterstoreCmd(kCmdNameZInterstore, -4, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsZset); + Cmd* zinterstoreptr = + new ZInterstoreCmd(kCmdNameZInterstore, -4, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZInterstore, zinterstoreptr)); ////ZRankCmd Cmd* zrankptr = new ZRankCmd(kCmdNameZRank, 3, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); @@ -369,22 +384,27 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* zscoreptr = new ZScoreCmd(kCmdNameZScore, 3, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZScore, zscoreptr)); ////ZRangebylexCmd - Cmd* zrangebylexptr = new ZRangebylexCmd(kCmdNameZRangebylex, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); + Cmd* zrangebylexptr = + new ZRangebylexCmd(kCmdNameZRangebylex, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRangebylex, zrangebylexptr)); ////ZRevrangebylexCmd - Cmd* zrevrangebylexptr = new ZRevrangebylexCmd(kCmdNameZRevrangebylex, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); + Cmd* zrevrangebylexptr = + new ZRevrangebylexCmd(kCmdNameZRevrangebylex, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRevrangebylex, zrevrangebylexptr)); ////ZLexcountCmd Cmd* zlexcountptr = new ZLexcountCmd(kCmdNameZLexcount, 4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZLexcount, zlexcountptr)); ////ZRemrangebyrankCmd - Cmd* zremrangebyrankptr = new ZRemrangebyrankCmd(kCmdNameZRemrangebyrank, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); + Cmd* zremrangebyrankptr = + new ZRemrangebyrankCmd(kCmdNameZRemrangebyrank, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRemrangebyrank, zremrangebyrankptr)); ////ZRemrangebyscoreCmd - Cmd* zremrangebyscoreptr = new ZRemrangebyscoreCmd(kCmdNameZRemrangebyscore, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); + Cmd* zremrangebyscoreptr = + new ZRemrangebyscoreCmd(kCmdNameZRemrangebyscore, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRemrangebyscore, zremrangebyscoreptr)); ////ZRemrangebylexCmd - Cmd* zremrangebylexptr = new ZRemrangebylexCmd(kCmdNameZRemrangebylex, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); + Cmd* zremrangebylexptr = + new ZRemrangebylexCmd(kCmdNameZRemrangebylex, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZRemrangebylex, zremrangebylexptr)); ////ZPopmax Cmd* zpopmaxptr = new ZPopmaxCmd(kCmdNameZPopmax, -2, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); @@ -393,7 +413,7 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* zpopminptr = new ZPopminCmd(kCmdNameZPopmin, -2, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsZset); cmd_table->insert(std::pair(kCmdNameZPopmin, zpopminptr)); - //Set + // Set ////SAddCmd Cmd* saddptr = new SAddCmd(kCmdNameSAdd, -3, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSAdd, saddptr)); @@ -416,13 +436,15 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* sunionptr = new SUnionCmd(kCmdNameSUnion, -2, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSUnion, sunionptr)); ////SUnionstoreCmd - Cmd* sunionstoreptr = new SUnionstoreCmd(kCmdNameSUnionstore, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsSet); + Cmd* sunionstoreptr = + new SUnionstoreCmd(kCmdNameSUnionstore, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSUnionstore, sunionstoreptr)); ////SInterCmd Cmd* sinterptr = new SInterCmd(kCmdNameSInter, -2, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSInter, sinterptr)); ////SInterstoreCmd - Cmd* sinterstoreptr = new SInterstoreCmd(kCmdNameSInterstore, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsSet); + Cmd* sinterstoreptr = + new SInterstoreCmd(kCmdNameSInterstore, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSInterstore, sinterstoreptr)); ////SIsmemberCmd Cmd* sismemberptr = new SIsmemberCmd(kCmdNameSIsmember, 3, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsSet); @@ -431,16 +453,18 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* sdiffptr = new SDiffCmd(kCmdNameSDiff, -2, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSDiff, sdiffptr)); ////SDiffstoreCmd - Cmd* sdiffstoreptr = new SDiffstoreCmd(kCmdNameSDiffstore, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsSet); + Cmd* sdiffstoreptr = + new SDiffstoreCmd(kCmdNameSDiffstore, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSDiffstore, sdiffstoreptr)); ////SMoveCmd Cmd* smoveptr = new SMoveCmd(kCmdNameSMove, 4, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSMove, smoveptr)); ////SRandmemberCmd - Cmd* srandmemberptr = new SRandmemberCmd(kCmdNameSRandmember, -2, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsSet); + Cmd* srandmemberptr = + new SRandmemberCmd(kCmdNameSRandmember, -2, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsSet); cmd_table->insert(std::pair(kCmdNameSRandmember, srandmemberptr)); - //BitMap + // BitMap ////bitsetCmd Cmd* bitsetptr = new BitSetCmd(kCmdNameBitSet, 4, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsBit); cmd_table->insert(std::pair(kCmdNameBitSet, bitsetptr)); @@ -457,55 +481,57 @@ void InitCmdTable(std::unordered_map *cmd_table) { Cmd* bitopptr = new BitOpCmd(kCmdNameBitOp, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsBit); cmd_table->insert(std::pair(kCmdNameBitOp, bitopptr)); - //HyperLogLog + // HyperLogLog ////pfaddCmd - Cmd * pfaddptr = new PfAddCmd(kCmdNamePfAdd, -2, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsHyperLogLog); + Cmd* pfaddptr = new PfAddCmd(kCmdNamePfAdd, -2, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsHyperLogLog); cmd_table->insert(std::pair(kCmdNamePfAdd, pfaddptr)); ////pfcountCmd - Cmd * pfcountptr = new PfCountCmd(kCmdNamePfCount, -2, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsHyperLogLog); + Cmd* pfcountptr = new PfCountCmd(kCmdNamePfCount, -2, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsHyperLogLog); cmd_table->insert(std::pair(kCmdNamePfCount, pfcountptr)); ////pfmergeCmd - Cmd * pfmergeptr = new PfMergeCmd(kCmdNamePfMerge, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsHyperLogLog); + Cmd* pfmergeptr = + new PfMergeCmd(kCmdNamePfMerge, -3, kCmdFlagsWrite | kCmdFlagsMultiPartition | kCmdFlagsHyperLogLog); cmd_table->insert(std::pair(kCmdNamePfMerge, pfmergeptr)); - //GEO + // GEO ////GepAdd - Cmd * geoaddptr = new GeoAddCmd(kCmdNameGeoAdd, -5, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsGeo); + Cmd* geoaddptr = new GeoAddCmd(kCmdNameGeoAdd, -5, kCmdFlagsWrite | kCmdFlagsSinglePartition | kCmdFlagsGeo); cmd_table->insert(std::pair(kCmdNameGeoAdd, geoaddptr)); ////GeoPos - Cmd * geoposptr = new GeoPosCmd(kCmdNameGeoPos, -2, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsGeo); + Cmd* geoposptr = new GeoPosCmd(kCmdNameGeoPos, -2, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsGeo); cmd_table->insert(std::pair(kCmdNameGeoPos, geoposptr)); ////GeoDist - Cmd * geodistptr = new GeoDistCmd(kCmdNameGeoDist, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsGeo); + Cmd* geodistptr = new GeoDistCmd(kCmdNameGeoDist, -4, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsGeo); cmd_table->insert(std::pair(kCmdNameGeoDist, geodistptr)); ////GeoHash - Cmd * geohashptr = new GeoHashCmd(kCmdNameGeoHash, -2, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsGeo); + Cmd* geohashptr = new GeoHashCmd(kCmdNameGeoHash, -2, kCmdFlagsRead | kCmdFlagsSinglePartition | kCmdFlagsGeo); cmd_table->insert(std::pair(kCmdNameGeoHash, geohashptr)); ////GeoRadius - Cmd * georadiusptr = new GeoRadiusCmd(kCmdNameGeoRadius, -6, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsGeo); + Cmd* georadiusptr = new GeoRadiusCmd(kCmdNameGeoRadius, -6, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsGeo); cmd_table->insert(std::pair(kCmdNameGeoRadius, georadiusptr)); ////GeoRadiusByMember - Cmd * georadiusbymemberptr = new GeoRadiusByMemberCmd(kCmdNameGeoRadiusByMember, -5, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsGeo); + Cmd* georadiusbymemberptr = + new GeoRadiusByMemberCmd(kCmdNameGeoRadiusByMember, -5, kCmdFlagsRead | kCmdFlagsMultiPartition | kCmdFlagsGeo); cmd_table->insert(std::pair(kCmdNameGeoRadiusByMember, georadiusbymemberptr)); - //PubSub + // PubSub ////Publish - Cmd * publishptr = new PublishCmd(kCmdNamePublish, 3, kCmdFlagsRead | kCmdFlagsPubSub); + Cmd* publishptr = new PublishCmd(kCmdNamePublish, 3, kCmdFlagsRead | kCmdFlagsPubSub); cmd_table->insert(std::pair(kCmdNamePublish, publishptr)); ////Subscribe - Cmd * subscribeptr = new SubscribeCmd(kCmdNameSubscribe, -2, kCmdFlagsRead | kCmdFlagsPubSub); + Cmd* subscribeptr = new SubscribeCmd(kCmdNameSubscribe, -2, kCmdFlagsRead | kCmdFlagsPubSub); cmd_table->insert(std::pair(kCmdNameSubscribe, subscribeptr)); ////UnSubscribe - Cmd * unsubscribeptr = new UnSubscribeCmd(kCmdNameUnSubscribe, -1, kCmdFlagsRead | kCmdFlagsPubSub); + Cmd* unsubscribeptr = new UnSubscribeCmd(kCmdNameUnSubscribe, -1, kCmdFlagsRead | kCmdFlagsPubSub); cmd_table->insert(std::pair(kCmdNameUnSubscribe, unsubscribeptr)); ////PSubscribe - Cmd * psubscribeptr = new PSubscribeCmd(kCmdNamePSubscribe, -2, kCmdFlagsRead | kCmdFlagsPubSub); + Cmd* psubscribeptr = new PSubscribeCmd(kCmdNamePSubscribe, -2, kCmdFlagsRead | kCmdFlagsPubSub); cmd_table->insert(std::pair(kCmdNamePSubscribe, psubscribeptr)); ////PUnSubscribe - Cmd * punsubscribeptr = new PUnSubscribeCmd(kCmdNamePUnSubscribe, -1, kCmdFlagsRead | kCmdFlagsPubSub); + Cmd* punsubscribeptr = new PUnSubscribeCmd(kCmdNamePUnSubscribe, -1, kCmdFlagsRead | kCmdFlagsPubSub); cmd_table->insert(std::pair(kCmdNamePUnSubscribe, punsubscribeptr)); ////PubSub - Cmd * pubsubptr = new PubSubCmd(kCmdNamePubSub, -2, kCmdFlagsRead | kCmdFlagsPubSub); + Cmd* pubsubptr = new PubSubCmd(kCmdNamePubSub, -2, kCmdFlagsRead | kCmdFlagsPubSub); cmd_table->insert(std::pair(kCmdNamePubSub, pubsubptr)); } @@ -524,12 +550,11 @@ void DestoryCmdTable(CmdTable* cmd_table) { } } -void Cmd::Initial(const PikaCmdArgsType& argv, - const std::string& table_name) { +void Cmd::Initial(const PikaCmdArgsType& argv, const std::string& table_name) { argv_ = argv; table_name_ = table_name; - res_.clear(); // Clear res content - Clear(); // Clear cmd, Derived class can has own implement + res_.clear(); // Clear res content + Clear(); // Clear cmd, Derived class can has own implement DoInitial(); }; @@ -568,8 +593,7 @@ void Cmd::ProcessFlushDBCmd() { for (const auto& partition_item : table->partitions_) { std::shared_ptr partition = partition_item.second; PartitionInfo p_info(partition->GetTableName(), partition->GetPartitionId()); - if (g_pika_rm->sync_master_partitions_.find(p_info) - == g_pika_rm->sync_master_partitions_.end()) { + if (g_pika_rm->sync_master_partitions_.find(p_info) == g_pika_rm->sync_master_partitions_.end()) { res_.SetRes(CmdRes::kErrOther, "Partition not found"); return; } @@ -595,8 +619,7 @@ void Cmd::ProcessFlushAllCmd() { for (const auto& partition_item : table_item.second->partitions_) { std::shared_ptr partition = partition_item.second; PartitionInfo p_info(partition->GetTableName(), partition->GetPartitionId()); - if (g_pika_rm->sync_master_partitions_.find(p_info) - == g_pika_rm->sync_master_partitions_.end()) { + if (g_pika_rm->sync_master_partitions_.find(p_info) == g_pika_rm->sync_master_partitions_.end()) { res_.SetRes(CmdRes::kErrOther, "Partition not found"); return; } @@ -627,8 +650,7 @@ void Cmd::ProcessSinglePartitionCmd() { } std::shared_ptr sync_partition = - g_pika_rm->GetSyncMasterPartitionByName( - PartitionInfo(partition->GetTableName(), partition->GetPartitionId())); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(partition->GetTableName(), partition->GetPartitionId())); if (!sync_partition) { res_.SetRes(CmdRes::kErrOther, "Partition not found"); return; @@ -636,9 +658,8 @@ void Cmd::ProcessSinglePartitionCmd() { ProcessCommand(partition, sync_partition); } -void Cmd::ProcessCommand(std::shared_ptr partition, - std::shared_ptr sync_partition, - const HintKeys& hint_keys) { +void Cmd::ProcessCommand(std::shared_ptr partition, std::shared_ptr sync_partition, + const HintKeys& hint_keys) { if (stage_ == kNone) { InternalProcessCommand(partition, sync_partition, hint_keys); } else { @@ -651,7 +672,7 @@ void Cmd::ProcessCommand(std::shared_ptr partition, } void Cmd::InternalProcessCommand(std::shared_ptr partition, - std::shared_ptr sync_partition, const HintKeys& hint_keys) { + std::shared_ptr sync_partition, const HintKeys& hint_keys) { pstd::lock::MultiRecordLock record_lock(partition->LockMgr()); if (is_write()) { if (!hint_keys.empty() && is_multi_partition() && !g_pika_conf->classic_mode()) { @@ -667,7 +688,7 @@ void Cmd::InternalProcessCommand(std::shared_ptr partition, } DoCommand(partition, hint_keys); if (g_pika_conf->slowlog_slower_than() >= 0) { - do_duration_ += pstd::NowMicros() - start_us; + do_duration_ += pstd::NowMicros() - start_us; } DoBinlog(sync_partition); @@ -697,9 +718,7 @@ void Cmd::DoCommand(std::shared_ptr partition, const HintKeys& hint_k } void Cmd::DoBinlog(std::shared_ptr partition) { - if (res().ok() - && is_write() - && g_pika_conf->write_binlog()) { + if (res().ok() && is_write() && g_pika_conf->write_binlog()) { std::shared_ptr conn_ptr = GetConn(); std::shared_ptr resp_ptr = GetResp(); // Consider that dummy cmd appended by system, both conn and resp are null. @@ -714,11 +733,11 @@ void Cmd::DoBinlog(std::shared_ptr partition) { return; } - Status s = partition->ConsensusProposeLog(shared_from_this(), - std::dynamic_pointer_cast(conn_ptr), resp_ptr); + Status s = partition->ConsensusProposeLog(shared_from_this(), std::dynamic_pointer_cast(conn_ptr), + resp_ptr); if (!s.ok()) { LOG(WARNING) << partition->SyncPartitionInfo().ToString() - << " Writing binlog failed, maybe no space left on device " << s.ToString(); + << " Writing binlog failed, maybe no space left on device " << s.ToString(); res().SetRes(CmdRes::kErrOther, s.ToString()); return; } @@ -745,16 +764,15 @@ void Cmd::ProcessMultiPartitionCmd() { CmdStage current_stage = stage_; for (auto& key : cur_key) { // in sharding mode we select partition by key - uint32_t partition_id = g_pika_cmd_table_manager->DistributeKey(key, table->PartitionNum()); + uint32_t partition_id = g_pika_cmd_table_manager->DistributeKey(key, table->PartitionNum()); std::unordered_map::iterator iter = process_map.find(partition_id); if (iter == process_map.end()) { - std::shared_ptr partition = table->GetPartitionById(partition_id); + std::shared_ptr partition = table->GetPartitionById(partition_id); if (!partition) { res_.SetRes(CmdRes::kErrOther, "Partition not found"); return; } - std::shared_ptr sync_partition = - g_pika_rm->GetSyncMasterPartitionByName( + std::shared_ptr sync_partition = g_pika_rm->GetSyncMasterPartitionByName( PartitionInfo(partition->GetTableName(), partition->GetPartitionId())); if (!sync_partition) { res_.SetRes(CmdRes::kErrOther, "Partition not found"); @@ -780,34 +798,18 @@ void Cmd::ProcessMultiPartitionCmd() { } } -void Cmd::ProcessDoNotSpecifyPartitionCmd() { - Do(); -} +void Cmd::ProcessDoNotSpecifyPartitionCmd() { Do(); } -bool Cmd::is_write() const { - return ((flag_ & kCmdFlagsMaskRW) == kCmdFlagsWrite); -} -bool Cmd::is_local() const { - return ((flag_ & kCmdFlagsMaskLocal) == kCmdFlagsLocal); -} +bool Cmd::is_write() const { return ((flag_ & kCmdFlagsMaskRW) == kCmdFlagsWrite); } +bool Cmd::is_local() const { return ((flag_ & kCmdFlagsMaskLocal) == kCmdFlagsLocal); } // Others need to be suspended when a suspend command run -bool Cmd::is_suspend() const { - return ((flag_ & kCmdFlagsMaskSuspend) == kCmdFlagsSuspend); -} +bool Cmd::is_suspend() const { return ((flag_ & kCmdFlagsMaskSuspend) == kCmdFlagsSuspend); } // Must with admin auth -bool Cmd::is_admin_require() const { - return ((flag_ & kCmdFlagsMaskAdminRequire) == kCmdFlagsAdminRequire); -} -bool Cmd::is_single_partition() const { - return ((flag_ & kCmdFlagsMaskPartition) == kCmdFlagsSinglePartition); -} -bool Cmd::is_multi_partition() const { - return ((flag_ & kCmdFlagsMaskPartition) == kCmdFlagsMultiPartition); -} +bool Cmd::is_admin_require() const { return ((flag_ & kCmdFlagsMaskAdminRequire) == kCmdFlagsAdminRequire); } +bool Cmd::is_single_partition() const { return ((flag_ & kCmdFlagsMaskPartition) == kCmdFlagsSinglePartition); } +bool Cmd::is_multi_partition() const { return ((flag_ & kCmdFlagsMaskPartition) == kCmdFlagsMultiPartition); } -bool Cmd::is_classic_mode() const { - return g_pika_conf->classic_mode(); -} +bool Cmd::is_classic_mode() const { return g_pika_conf->classic_mode(); } bool Cmd::HashtagIsConsistent(const std::string& lhs, const std::string& rhs) const { if (is_classic_mode() == false) { @@ -818,27 +820,14 @@ bool Cmd::HashtagIsConsistent(const std::string& lhs, const std::string& rhs) co return true; } +std::string Cmd::name() const { return name_; } +CmdRes& Cmd::res() { return res_; } -std::string Cmd::name() const { - return name_; -} -CmdRes& Cmd::res() { - return res_; -} +std::string Cmd::table_name() const { return table_name_; } -std::string Cmd::table_name() const { - return table_name_; -} +const PikaCmdArgsType& Cmd::argv() const { return argv_; } -const PikaCmdArgsType& Cmd::argv() const { - return argv_; -} - -std::string Cmd::ToBinlog(uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { +std::string Cmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, argv_.size(), "*"); @@ -848,19 +837,12 @@ std::string Cmd::ToBinlog(uint32_t exec_time, RedisAppendContent(content, v); } - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } bool Cmd::CheckArg(int num) const { - if ((arity_ > 0 && num != arity_) - || (arity_ < 0 && num < -arity_)) { + if ((arity_ > 0 && num != arity_) || (arity_ < 0 && num < -arity_)) { return false; } return true; @@ -875,22 +857,12 @@ void Cmd::LogCommand() const { LOG(INFO) << "command:" << command; } -void Cmd::SetConn(const std::shared_ptr conn) { - conn_ = conn; -} +void Cmd::SetConn(const std::shared_ptr conn) { conn_ = conn; } -std::shared_ptr Cmd::GetConn() { - return conn_.lock(); -} +std::shared_ptr Cmd::GetConn() { return conn_.lock(); } -void Cmd::SetResp(const std::shared_ptr resp) { - resp_ = resp; -} +void Cmd::SetResp(const std::shared_ptr resp) { resp_ = resp; } -std::shared_ptr Cmd::GetResp() { - return resp_.lock(); -} +std::shared_ptr Cmd::GetResp() { return resp_.lock(); } -void Cmd::SetStage(CmdStage stage) { - stage_ = stage; -} +void Cmd::SetStage(CmdStage stage) { stage_ = stage; } diff --git a/src/pika_conf.cc b/src/pika_conf.cc index fbcf9bd558..29452fd26a 100644 --- a/src/pika_conf.cc +++ b/src/pika_conf.cc @@ -7,15 +7,14 @@ #include -#include #include +#include #include "pstd/include/env.h" #include "include/pika_define.h" -PikaConf::PikaConf(const std::string& path) - : pstd::BaseConf(path), conf_path_(path) { +PikaConf::PikaConf(const std::string& path) : pstd::BaseConf(path), conf_path_(path) { pthread_rwlock_init(&rwlock_, NULL); local_meta_ = new PikaMeta(); } @@ -40,8 +39,7 @@ Status PikaConf::InternalGetTargetTable(const std::string& table_name, uint32_t* return Status::OK(); } -Status PikaConf::TablePartitionsSanityCheck(const std::string& table_name, - const std::set& partition_ids, +Status PikaConf::TablePartitionsSanityCheck(const std::string& table_name, const std::set& partition_ids, bool is_add) { RWLock l(&rwlock_, false); uint32_t table_index = 0; @@ -62,8 +60,7 @@ Status PikaConf::TablePartitionsSanityCheck(const std::string& table_name, return Status::OK(); } -Status PikaConf::AddTablePartitions(const std::string& table_name, - const std::set& partition_ids) { +Status PikaConf::AddTablePartitions(const std::string& table_name, const std::set& partition_ids) { Status s = TablePartitionsSanityCheck(table_name, partition_ids, true); if (!s.ok()) { return s; @@ -81,8 +78,7 @@ Status PikaConf::AddTablePartitions(const std::string& table_name, return s; } -Status PikaConf::RemoveTablePartitions(const std::string& table_name, - const std::set& partition_ids) { +Status PikaConf::RemoveTablePartitions(const std::string& table_name, const std::set& partition_ids) { Status s = TablePartitionsSanityCheck(table_name, partition_ids, false); if (!s.ok()) { return s; @@ -100,24 +96,24 @@ Status PikaConf::RemoveTablePartitions(const std::string& table_name, return s; } -Status PikaConf::AddTable(const std::string &table_name, const uint32_t slot_num) { +Status PikaConf::AddTable(const std::string& table_name, const uint32_t slot_num) { Status s = AddTableSanityCheck(table_name); if (!s.ok()) { - return s; + return s; } RWLock l(&rwlock_, true); - table_structs_.push_back({table_name,slot_num,{}}); + table_structs_.push_back({table_name, slot_num, {}}); s = local_meta_->StableSave(table_structs_); return s; } -Status PikaConf::DelTable(const std::string &table_name) { +Status PikaConf::DelTable(const std::string& table_name) { Status s = DelTableSanityCheck(table_name); if (!s.ok()) { - return s; + return s; } RWLock l(&rwlock_, true); - for (auto iter = table_structs_.begin();iter != table_structs_.end();iter++) { + for (auto iter = table_structs_.begin(); iter != table_structs_.end(); iter++) { if (iter->table_name == table_name) { table_structs_.erase(iter); break; @@ -126,7 +122,7 @@ Status PikaConf::DelTable(const std::string &table_name) { return local_meta_->StableSave(table_structs_); } -Status PikaConf::AddTableSanityCheck(const std::string &table_name) { +Status PikaConf::AddTableSanityCheck(const std::string& table_name) { RWLock l(&rwlock_, false); uint32_t table_index = 0; Status s = InternalGetTargetTable(table_name, &table_index); @@ -136,14 +132,13 @@ Status PikaConf::AddTableSanityCheck(const std::string &table_name) { return Status::OK(); } -Status PikaConf::DelTableSanityCheck(const std::string &table_name) { +Status PikaConf::DelTableSanityCheck(const std::string& table_name) { RWLock l(&rwlock_, false); uint32_t table_index = 0; return InternalGetTargetTable(table_name, &table_index); } -int PikaConf::Load() -{ +int PikaConf::Load() { int ret = LoadConf(); if (ret != 0) { return ret; @@ -151,7 +146,7 @@ int PikaConf::Load() GetConfInt("timeout", &timeout_); if (timeout_ < 0) { - timeout_ = 60; // 60s + timeout_ = 60; // 60s } GetConfStr("server-id", &server_id_); if (server_id_.empty()) { @@ -168,7 +163,7 @@ int PikaConf::Load() } GetConfInt("root-connection-num", &root_connection_num_); if (root_connection_num_ < 0) { - root_connection_num_ = 2; + root_connection_num_ = 2; } std::string swe; @@ -196,18 +191,18 @@ int PikaConf::Load() bgsave_path_ += "/"; } GetConfInt("dump-expire", &expire_dump_days_); - if (expire_dump_days_ < 0 ) { - expire_dump_days_ = 0; + if (expire_dump_days_ < 0) { + expire_dump_days_ = 0; } GetConfStr("dump-prefix", &bgsave_prefix_); GetConfInt("expire-logs-nums", &expire_logs_nums_); - if (expire_logs_nums_ <= 10 ) { - expire_logs_nums_ = 10; + if (expire_logs_nums_ <= 10) { + expire_logs_nums_ = 10; } GetConfInt("expire-logs-days", &expire_logs_days_); - if (expire_logs_days_ <= 0 ) { - expire_logs_days_ = 1; + if (expire_logs_days_ <= 0) { + expire_logs_days_ = 1; } GetConfStr("compression", &compression_); GetConfStr("compression_per_level", &compression_per_level_); @@ -255,14 +250,12 @@ int PikaConf::Load() std::string instance_mode; GetConfStr("instance-mode", &instance_mode); - classic_mode_.store(instance_mode.empty() - || !strcasecmp(instance_mode.data(), "classic")); + classic_mode_.store(instance_mode.empty() || !strcasecmp(instance_mode.data(), "classic")); if (classic_mode_.load()) { GetConfInt("databases", &databases_); if (databases_ < 1 || databases_ > 8) { - LOG(FATAL) << "config databases error, limit [1 ~ 8], the actual is: " - << databases_; + LOG(FATAL) << "config databases error, limit [1 ~ 8], the actual is: " << databases_; } for (int idx = 0; idx < databases_; ++idx) { table_structs_.push_back({"db" + std::to_string(idx), 1, {0}}); @@ -271,8 +264,7 @@ int PikaConf::Load() GetConfInt("default-slot-num", &default_slot_num_); if (default_slot_num_ <= 0) { LOG(FATAL) << "config default-slot-num error," - << " it should greater than zero, the actual is: " - << default_slot_num_; + << " it should greater than zero, the actual is: " << default_slot_num_; } std::string pika_meta_path = db_path_ + kPikaMeta; if (!pstd::FileExists(pika_meta_path)) { @@ -288,25 +280,22 @@ int PikaConf::Load() int tmp_replication_num = 0; GetConfInt("replication-num", &tmp_replication_num); if (tmp_replication_num > 4 || tmp_replication_num < 0) { - LOG(FATAL) << "replication-num " << tmp_replication_num << - "is invalid, please pick from [0...4]"; + LOG(FATAL) << "replication-num " << tmp_replication_num << "is invalid, please pick from [0...4]"; } replication_num_.store(tmp_replication_num); int tmp_consensus_level = 0; GetConfInt("consensus-level", &tmp_consensus_level); - if (tmp_consensus_level < 0 || - tmp_consensus_level > replication_num_.load()) { + if (tmp_consensus_level < 0 || tmp_consensus_level > replication_num_.load()) { LOG(FATAL) << "consensus-level " << tmp_consensus_level - << " is invalid, current replication-num: " << replication_num_.load() - << ", please pick from 0 to replication-num" - << " [0..." << replication_num_.load() << "]"; + << " is invalid, current replication-num: " << replication_num_.load() + << ", please pick from 0 to replication-num" + << " [0..." << replication_num_.load() << "]"; } consensus_level_.store(tmp_consensus_level); - if (classic_mode_.load() && - (consensus_level_.load() != 0 || replication_num_.load() != 0)) { + if (classic_mode_.load() && (consensus_level_.load() != 0 || replication_num_.load() != 0)) { LOG(FATAL) << "consensus-level & replication-num only configurable under sharding mode," - << " set it to be 0 if you are using classic mode"; + << " set it to be 0 if you are using classic mode"; } compact_cron_ = ""; @@ -327,16 +316,16 @@ int PikaConf::Load() std::string::size_type len = compact_cron.length(); std::string::size_type colon = compact_cron.find("-"); std::string::size_type underline = compact_cron.find("/"); - if (colon == std::string::npos || underline == std::string::npos || - colon >= underline || colon + 1 >= len || + if (colon == std::string::npos || underline == std::string::npos || colon >= underline || colon + 1 >= len || colon + 1 == underline || underline + 1 >= len) { - compact_cron_ = ""; + compact_cron_ = ""; } else { int week = std::atoi(week_str.c_str()); int start = std::atoi(compact_cron.substr(0, colon).c_str()); int end = std::atoi(compact_cron.substr(colon + 1, underline).c_str()); int usage = std::atoi(compact_cron.substr(underline + 1).c_str()); - if ((have_week && (week < 1 || week > 7)) || start < 0 || start > 23 || end < 0 || end > 23 || usage < 0 || usage > 100) { + if ((have_week && (week < 1 || week > 7)) || start < 0 || start > 23 || end < 0 || end > 23 || usage < 0 || + usage > 100) { compact_cron_ = ""; } } @@ -351,7 +340,7 @@ int PikaConf::Load() compact_interval_ = ""; } else { int interval = std::atoi(compact_interval_.substr(0, slash).c_str()); - int usage = std::atoi(compact_interval_.substr(slash+1).c_str()); + int usage = std::atoi(compact_interval_.substr(slash + 1).c_str()); if (interval <= 0 || usage < 0 || usage > 100) { compact_interval_ = ""; } @@ -360,8 +349,8 @@ int PikaConf::Load() // write_buffer_size GetConfInt64Human("write-buffer-size", &write_buffer_size_); - if (write_buffer_size_ <= 0 ) { - write_buffer_size_ = 268435456; // 256Mb + if (write_buffer_size_ <= 0) { + write_buffer_size_ = 268435456; // 256Mb } // arena_block_size @@ -378,8 +367,8 @@ int PikaConf::Load() // rate-limiter-bandwidth GetConfInt64("rate-limiter-bandwidth", &rate_limiter_bandwidth_); - if (rate_limiter_bandwidth_ <= 0 ) { - rate_limiter_bandwidth_ = 200 * 1024 * 1024; // 200MB + if (rate_limiter_bandwidth_ <= 0) { + rate_limiter_bandwidth_ = 200 * 1024 * 1024; // 200MB } // max_write_buffer_num @@ -392,13 +381,13 @@ int PikaConf::Load() // max_client_response_size GetConfInt64Human("max-client-response-size", &max_client_response_size_); if (max_client_response_size_ <= 0) { - max_client_response_size_ = 1073741824; // 1Gb + max_client_response_size_ = 1073741824; // 1Gb } // target_file_size_base GetConfIntHuman("target-file-size-base", &target_file_size_base_); if (target_file_size_base_ <= 0) { - target_file_size_base_ = 1048576; // 10Mb + target_file_size_base_ = 1048576; // 10Mb } max_cache_statistic_keys_ = 0; @@ -409,8 +398,7 @@ int PikaConf::Load() small_compaction_threshold_ = 5000; GetConfInt("small-compaction-threshold", &small_compaction_threshold_); - if (small_compaction_threshold_ <= 0 - || small_compaction_threshold_ >= 100000) { + if (small_compaction_threshold_ <= 0 || small_compaction_threshold_ >= 100000) { small_compaction_threshold_ = 5000; } @@ -481,16 +469,15 @@ int PikaConf::Load() // daemonize std::string dmz; GetConfStr("daemonize", &dmz); - daemonize_ = (dmz == "yes") ? true : false; + daemonize_ = (dmz == "yes") ? true : false; // binlog std::string wb; GetConfStr("write-binlog", &wb); write_binlog_ = (wb == "no") ? false : true; GetConfIntHuman("binlog-file-size", &binlog_file_size_); - if (binlog_file_size_ < 1024 - || static_cast(binlog_file_size_) > (1024LL * 1024 * 1024)) { - binlog_file_size_ = 100 * 1024 * 1024; // 100M + if (binlog_file_size_ < 1024 || static_cast(binlog_file_size_) > (1024LL * 1024 * 1024)) { + binlog_file_size_ = 100 * 1024 * 1024; // 100M } GetConfStr("pidfile", &pidfile_); @@ -526,8 +513,7 @@ int PikaConf::Load() // max conn rbuf size int tmp_max_conn_rbuf_size = PIKA_MAX_CONN_RBUF; GetConfIntHuman("max-conn-rbuf-size", &tmp_max_conn_rbuf_size); - if (tmp_max_conn_rbuf_size == PIKA_MAX_CONN_RBUF_LB - || tmp_max_conn_rbuf_size == PIKA_MAX_CONN_RBUF_HB) { + if (tmp_max_conn_rbuf_size == PIKA_MAX_CONN_RBUF_LB || tmp_max_conn_rbuf_size == PIKA_MAX_CONN_RBUF_HB) { max_conn_rbuf_size_.store(tmp_max_conn_rbuf_size); } else { max_conn_rbuf_size_.store(PIKA_MAX_CONN_RBUF); @@ -601,7 +587,7 @@ int PikaConf::ConfigRewrite() { return WriteBack(); } -rocksdb::CompressionType PikaConf::GetCompression(const std::string &value) { +rocksdb::CompressionType PikaConf::GetCompression(const std::string& value) { if (value == "snappy") { return rocksdb::CompressionType::kSnappyCompression; } else if (value == "zlib") { @@ -628,7 +614,7 @@ std::vector PikaConf::compression_per_level() { } std::vector strings; pstd::StringSplit(compression_per_level_.substr(left + 1, right - left - 1), ':', strings); - for (const auto &item: strings) { + for (const auto& item : strings) { types.push_back(GetCompression(pstd::StringTrim(item))); } return types; diff --git a/src/pika_consensus.cc b/src/pika_consensus.cc index b0deb0b955..aa282592de 100644 --- a/src/pika_consensus.cc +++ b/src/pika_consensus.cc @@ -5,11 +5,11 @@ #include "include/pika_consensus.h" -#include "include/pika_conf.h" -#include "include/pika_server.h" #include "include/pika_client_conn.h" -#include "include/pika_rm.h" #include "include/pika_cmd_table_manager.h" +#include "include/pika_conf.h" +#include "include/pika_rm.h" +#include "include/pika_server.h" extern PikaServer* g_pika_server; extern PikaConf* g_pika_conf; @@ -28,7 +28,7 @@ Context::~Context() { } Status Context::StableSave() { - char *p = save_->GetData(); + char* p = save_->GetData(); memcpy(p, &(applied_index_.b_offset.filenum), sizeof(uint32_t)); p += 4; memcpy(p, &(applied_index_.b_offset.offset), sizeof(uint64_t)); @@ -87,13 +87,9 @@ void Context::Reset(const LogOffset& offset) { /* SyncProgress */ -SyncProgress::SyncProgress() { - pthread_rwlock_init(&rwlock_, NULL); -} +SyncProgress::SyncProgress() { pthread_rwlock_init(&rwlock_, NULL); } -SyncProgress::~SyncProgress() { - pthread_rwlock_destroy(&rwlock_); -} +SyncProgress::~SyncProgress() { pthread_rwlock_destroy(&rwlock_); } std::shared_ptr SyncProgress::GetSlaveNode(const std::string& ip, int port) { std::string slave_key = ip + std::to_string(port); @@ -114,18 +110,16 @@ std::unordered_map SyncProgress::GetAllMatchIndex() { return match_index_; } -Status SyncProgress::AddSlaveNode(const std::string& ip, int port, - const std::string& table_name, uint32_t partition_id, int session_id) { +Status SyncProgress::AddSlaveNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, + int session_id) { std::string slave_key = ip + std::to_string(port); std::shared_ptr exist_ptr = GetSlaveNode(ip, port); if (exist_ptr) { - LOG(WARNING) << "SlaveNode " << exist_ptr->ToString() << - " already exist, set new session " << session_id; + LOG(WARNING) << "SlaveNode " << exist_ptr->ToString() << " already exist, set new session " << session_id; exist_ptr->SetSessionId(session_id); return Status::OK(); } - std::shared_ptr slave_ptr = - std::make_shared(ip, port, table_name, partition_id, session_id); + std::shared_ptr slave_ptr = std::make_shared(ip, port, table_name, partition_id, session_id); slave_ptr->SetLastSendTime(pstd::NowMicros()); slave_ptr->SetLastRecvTime(pstd::NowMicros()); @@ -149,11 +143,11 @@ Status SyncProgress::RemoveSlaveNode(const std::string& ip, int port) { return Status::OK(); } -Status SyncProgress::Update(const std::string& ip, int port, const LogOffset& start, - const LogOffset& end, LogOffset* committed_index) { +Status SyncProgress::Update(const std::string& ip, int port, const LogOffset& start, const LogOffset& end, + LogOffset* committed_index) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } LogOffset acked_offset; @@ -166,7 +160,7 @@ Status SyncProgress::Update(const std::string& ip, int port, const LogOffset& st } // update match_index_ // shared slave_ptr->slave_mu - match_index_[ip+std::to_string(port)] = acked_offset; + match_index_[ip + std::to_string(port)] = acked_offset; } // if consensus_level == 0 LogOffset() return @@ -198,12 +192,9 @@ LogOffset SyncProgress::InternalCalCommittedIndex(std::unordered_map(logs_.size()); -} +int MemLog::Size() { return static_cast(logs_.size()); } // purge [begin, offset] Status MemLog::PurgeLogs(const LogOffset& offset, std::vector* logs) { @@ -281,10 +272,11 @@ int MemLog::InternalFindLogByBinlogOffset(const LogOffset& offset) { /* ConsensusCoordinator */ -ConsensusCoordinator::ConsensusCoordinator(const std::string& table_name, uint32_t partition_id) : table_name_(table_name), partition_id_(partition_id) { +ConsensusCoordinator::ConsensusCoordinator(const std::string& table_name, uint32_t partition_id) + : table_name_(table_name), partition_id_(partition_id) { std::string table_log_path = g_pika_conf->log_path() + "log_" + table_name + "/"; - std::string log_path = g_pika_conf->classic_mode() ? - table_log_path : table_log_path + std::to_string(partition_id) + "/"; + std::string log_path = + g_pika_conf->classic_mode() ? table_log_path : table_log_path + std::to_string(partition_id) + "/"; context_ = std::make_shared(log_path + kContext); stable_logger_ = std::make_shared(table_name, partition_id, log_path); mem_logger_ = std::make_shared(); @@ -294,9 +286,7 @@ ConsensusCoordinator::ConsensusCoordinator(const std::string& table_name, uint32 } } -ConsensusCoordinator::~ConsensusCoordinator() { - pthread_rwlock_destroy(&term_rwlock_); -} +ConsensusCoordinator::~ConsensusCoordinator() { pthread_rwlock_destroy(&term_rwlock_); } // since it is invoked in constructor all locks not hold void ConsensusCoordinator::Init() { @@ -304,11 +294,11 @@ void ConsensusCoordinator::Init() { context_->Init(); committed_index_ = context_->applied_index_; - //load term_ + // load term_ term_ = stable_logger_->Logger()->term(); - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << "Restore applied index " << context_->applied_index_.ToString() << " current term " << term_; + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "Restore applied index " + << context_->applied_index_.ToString() << " current term " << term_; if (committed_index_ == LogOffset()) { return; } @@ -319,13 +309,13 @@ void ConsensusCoordinator::Init() { net::RedisParser redis_parser; redis_parser.RedisParserInit(REDIS_PARSER_REQUEST, settings); PikaBinlogReader binlog_reader; - int res = binlog_reader.Seek(stable_logger_->Logger(), - committed_index_.b_offset.filenum, committed_index_.b_offset.offset); + int res = + binlog_reader.Seek(stable_logger_->Logger(), committed_index_.b_offset.filenum, committed_index_.b_offset.offset); if (res) { LOG(FATAL) << PartitionInfo(table_name_, partition_id_).ToString() << "Binlog reader init failed"; } - while(1) { + while (1) { LogOffset offset; std::string binlog; Status s = binlog_reader.Get(&binlog, &(offset.b_offset.filenum), &(offset.b_offset.offset)); @@ -345,8 +335,7 @@ void ConsensusCoordinator::Init() { const char* redis_parser_start = binlog.data() + BINLOG_ENCODE_LEN; int redis_parser_len = static_cast(binlog.size()) - BINLOG_ENCODE_LEN; int processed_len = 0; - net::RedisParserStatus ret = redis_parser.ProcessInputBuffer( - redis_parser_start, redis_parser_len, &processed_len); + net::RedisParserStatus ret = redis_parser.ProcessInputBuffer(redis_parser_start, redis_parser_len, &processed_len); if (ret != net::kRedisParserDone) { LOG(FATAL) << PartitionInfo(table_name_, partition_id_).ToString() << "Redis parser parse failed"; return; @@ -368,11 +357,11 @@ Status ConsensusCoordinator::Reset(const LogOffset& offset) { } UpdateTerm(offset.l_offset.term); - Status s = stable_logger_->Logger()->SetProducerStatus( - offset.b_offset.filenum, offset.b_offset.offset, - offset.l_offset.term, offset.l_offset.index); + Status s = stable_logger_->Logger()->SetProducerStatus(offset.b_offset.filenum, offset.b_offset.offset, + offset.l_offset.term, offset.l_offset.index); if (!s.ok()) { - LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() << "Consensus reset status failed " << s.ToString(); + LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() << "Consensus reset status failed " + << s.ToString(); return s; } @@ -384,10 +373,8 @@ Status ConsensusCoordinator::Reset(const LogOffset& offset) { return Status::OK(); } -Status ConsensusCoordinator::ProposeLog( - std::shared_ptr cmd_ptr, - std::shared_ptr conn_ptr, - std::shared_ptr resp_ptr) { +Status ConsensusCoordinator::ProposeLog(std::shared_ptr cmd_ptr, std::shared_ptr conn_ptr, + std::shared_ptr resp_ptr) { LogOffset log_offset; stable_logger_->Logger()->Lock(); @@ -417,9 +404,9 @@ Status ConsensusCoordinator::ProposeLog( return Status::OK(); } -Status ConsensusCoordinator::InternalAppendLog(const BinlogItem& item, - std::shared_ptr cmd_ptr, std::shared_ptr conn_ptr, - std::shared_ptr resp_ptr) { +Status ConsensusCoordinator::InternalAppendLog(const BinlogItem& item, std::shared_ptr cmd_ptr, + std::shared_ptr conn_ptr, + std::shared_ptr resp_ptr) { LogOffset log_offset; Status s = InternalAppendBinlog(item, cmd_ptr, &log_offset); if (!s.ok()) { @@ -436,8 +423,8 @@ Status ConsensusCoordinator::InternalAppendLog(const BinlogItem& item, Status ConsensusCoordinator::ProcessLeaderLog(std::shared_ptr cmd_ptr, const BinlogItem& attribute) { LogOffset last_index = mem_logger_->last_offset(); if (attribute.logic_id() < last_index.l_offset.index) { - LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() - << "Drop log from leader logic_id " << attribute.logic_id() << " cur last index " << last_index.l_offset.index; + LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() << "Drop log from leader logic_id " + << attribute.logic_id() << " cur last index " << last_index.l_offset.index; return Status::OK(); } @@ -476,8 +463,8 @@ Status ConsensusCoordinator::ProcessLocalUpdate(const LogOffset& leader_commit) return Status::OK(); } -Status ConsensusCoordinator::UpdateSlave(const std::string& ip, int port, - const LogOffset& start, const LogOffset& end) { +Status ConsensusCoordinator::UpdateSlave(const std::string& ip, int port, const LogOffset& start, + const LogOffset& end) { LogOffset committed_index; Status s = sync_pros_.Update(ip, port, start, end, &committed_index); if (!s.ok()) { @@ -491,8 +478,9 @@ Status ConsensusCoordinator::UpdateSlave(const std::string& ip, int port, // do not commit log which is not current term log if (committed_index.l_offset.term != term()) { LOG_EVERY_N(INFO, 1000) << "Will not commit log term which is not equals to current term" - << " To updated committed_index" << committed_index.ToString() << " current term " << term() - << " from " << ip << " " << port << " start " << start.ToString() << " end " << end.ToString(); + << " To updated committed_index" << committed_index.ToString() << " current term " << term() + << " from " << ip << " " << port << " start " << start.ToString() << " end " + << end.ToString(); return Status::OK(); } @@ -515,7 +503,8 @@ Status ConsensusCoordinator::UpdateSlave(const std::string& ip, int port, return Status::OK(); } -bool ConsensusCoordinator::InternalUpdateCommittedIndex(const LogOffset& slave_committed_index, LogOffset* updated_committed_index) { +bool ConsensusCoordinator::InternalUpdateCommittedIndex(const LogOffset& slave_committed_index, + LogOffset* updated_committed_index) { if (slave_committed_index <= committed_index_) { return false; } @@ -524,17 +513,13 @@ bool ConsensusCoordinator::InternalUpdateCommittedIndex(const LogOffset& slave_c return true; } -Status ConsensusCoordinator::InternalAppendBinlog(const BinlogItem& item, - std::shared_ptr cmd_ptr, LogOffset* log_offset) { - std::string binlog = cmd_ptr->ToBinlog(item.exec_time(), - item.term_id(), - item.logic_id(), - item.filenum(), - item.offset()); +Status ConsensusCoordinator::InternalAppendBinlog(const BinlogItem& item, std::shared_ptr cmd_ptr, + LogOffset* log_offset) { + std::string binlog = + cmd_ptr->ToBinlog(item.exec_time(), item.term_id(), item.logic_id(), item.filenum(), item.offset()); Status s = stable_logger_->Logger()->Put(binlog); if (!s.ok()) { - std::string table_name = cmd_ptr->table_name().empty() - ? g_pika_conf->default_table() : cmd_ptr->table_name(); + std::string table_name = cmd_ptr->table_name().empty() ? g_pika_conf->default_table() : cmd_ptr->table_name(); std::shared_ptr
table = g_pika_server->GetTable(table_name); if (table) { table->SetBinlogIoError(); @@ -544,8 +529,7 @@ Status ConsensusCoordinator::InternalAppendBinlog(const BinlogItem& item, uint32_t filenum; uint64_t offset; stable_logger_->Logger()->GetProducerStatus(&filenum, &offset); - *log_offset = LogOffset(BinlogOffset(filenum, offset), - LogicOffset(item.term_id(), item.logic_id())); + *log_offset = LogOffset(BinlogOffset(filenum, offset), LogicOffset(item.term_id(), item.logic_id())); return Status::OK(); } @@ -627,8 +611,7 @@ void ConsensusCoordinator::InternalApply(const MemLog::LogItem& log) { arg->offset = log.offset; arg->table_name = table_name_; arg->partition_id = partition_id_; - g_pika_server->ScheduleClientBgThreads( - PikaClientConn::DoExecTask, arg, log.cmd_ptr->current_key().front()); + g_pika_server->ScheduleClientBgThreads(PikaClientConn::DoExecTask, arg, log.cmd_ptr->current_key().front()); } void ConsensusCoordinator::InternalApplyFollower(const MemLog::LogItem& log) { @@ -660,13 +643,14 @@ Status ConsensusCoordinator::TruncateTo(const LogOffset& offset) { if (!s.ok()) { return s; } - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << " Founded truncate pos " << founded_offset.ToString(); + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << " Founded truncate pos " + << founded_offset.ToString(); LogOffset committed = committed_index(); stable_logger_->Logger()->Lock(); if (founded_offset.l_offset.index == committed.l_offset.index) { mem_logger_->Reset(committed); } else { - Status s = mem_logger_->TruncateTo(founded_offset); + Status s = mem_logger_->TruncateTo(founded_offset); if (!s.ok()) { stable_logger_->Logger()->Unlock(); return s; @@ -683,8 +667,7 @@ Status ConsensusCoordinator::TruncateTo(const LogOffset& offset) { Status ConsensusCoordinator::GetBinlogOffset(const BinlogOffset& start_offset, LogOffset* log_offset) { PikaBinlogReader binlog_reader; - int res = binlog_reader.Seek(stable_logger_->Logger(), - start_offset.filenum, start_offset.offset); + int res = binlog_reader.Seek(stable_logger_->Logger(), start_offset.filenum, start_offset.offset); if (res) { return Status::Corruption("Binlog reader init failed"); } @@ -708,17 +691,14 @@ Status ConsensusCoordinator::GetBinlogOffset(const BinlogOffset& start_offset, L // start_offset 0,0 end_offset 1,129, result will include binlog (1,129) // start_offset 0,0 end_offset 1,0, result will NOT include binlog (1,xxx) // start_offset 0,0 end_offset 0,0, resulet will NOT include binlog(0,xxx) -Status ConsensusCoordinator::GetBinlogOffset( - const BinlogOffset& start_offset, - const BinlogOffset& end_offset, - std::vector* log_offset) { +Status ConsensusCoordinator::GetBinlogOffset(const BinlogOffset& start_offset, const BinlogOffset& end_offset, + std::vector* log_offset) { PikaBinlogReader binlog_reader; - int res = binlog_reader.Seek(stable_logger_->Logger(), - start_offset.filenum, start_offset.offset); + int res = binlog_reader.Seek(stable_logger_->Logger(), start_offset.filenum, start_offset.offset); if (res) { return Status::Corruption("Binlog reader init failed"); } - while(1) { + while (1) { BinlogOffset b_offset; std::string binlog; Status s = binlog_reader.Get(&binlog, &(b_offset.filenum), &(b_offset.offset)); @@ -743,17 +723,15 @@ Status ConsensusCoordinator::GetBinlogOffset( return Status::OK(); } -Status ConsensusCoordinator::FindBinlogFileNum( - const std::map binlogs, - uint64_t target_index, uint32_t start_filenum, - uint32_t* founded_filenum) { +Status ConsensusCoordinator::FindBinlogFileNum(const std::map binlogs, uint64_t target_index, + uint32_t start_filenum, uint32_t* founded_filenum) { // low boundary & high boundary uint32_t lb_binlogs = binlogs.begin()->first; uint32_t hb_binlogs = binlogs.rbegin()->first; bool first_time_left = false; bool first_time_right = false; uint32_t filenum = start_filenum; - while(1) { + while (1) { LogOffset first_offset; Status s = GetBinlogOffset(BinlogOffset(filenum, 0), &first_offset); if (!s.ok()) { @@ -762,12 +740,12 @@ Status ConsensusCoordinator::FindBinlogFileNum( if (target_index < first_offset.l_offset.index) { if (first_time_right) { // last filenum - filenum = filenum -1; + filenum = filenum - 1; break; } // move left first_time_left = true; - if (filenum == 0 || filenum - 1 < lb_binlogs) { + if (filenum == 0 || filenum - 1 < lb_binlogs) { return Status::NotFound(std::to_string(target_index) + " hit low boundary"); } filenum = filenum - 1; @@ -789,11 +767,10 @@ Status ConsensusCoordinator::FindBinlogFileNum( return Status::OK(); } -Status ConsensusCoordinator::FindLogicOffsetBySearchingBinlog( - const BinlogOffset& hint_offset, uint64_t target_index, LogOffset* found_offset) { - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << "FindLogicOffsetBySearchingBinlog hint offset " << hint_offset.ToString() - << " target_index " << target_index; +Status ConsensusCoordinator::FindLogicOffsetBySearchingBinlog(const BinlogOffset& hint_offset, uint64_t target_index, + LogOffset* found_offset) { + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "FindLogicOffsetBySearchingBinlog hint offset " + << hint_offset.ToString() << " target_index " << target_index; BinlogOffset start_offset; std::map binlogs; if (!stable_logger_->GetBinlogFiles(&binlogs)) { @@ -824,7 +801,8 @@ Status ConsensusCoordinator::FindLogicOffsetBySearchingBinlog( } for (auto& offset : offsets) { if (offset.l_offset.index == target_index) { - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "Founded " << target_index << " " << offset.ToString(); + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "Founded " << target_index << " " + << offset.ToString(); *found_offset = offset; return Status::OK(); } @@ -832,15 +810,16 @@ Status ConsensusCoordinator::FindLogicOffsetBySearchingBinlog( return Status::NotFound("Logic index not found"); } -Status ConsensusCoordinator::FindLogicOffset(const BinlogOffset& start_offset, uint64_t target_index, LogOffset* found_offset) { +Status ConsensusCoordinator::FindLogicOffset(const BinlogOffset& start_offset, uint64_t target_index, + LogOffset* found_offset) { LogOffset possible_offset; Status s = GetBinlogOffset(start_offset, &possible_offset); if (!s.ok() || possible_offset.l_offset.index != target_index) { if (!s.ok()) { LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "GetBinlogOffset res: " << s.ToString(); } else { - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "GetBInlogOffset res: " << s.ToString() << - " possible_offset " << possible_offset.ToString() << " target_index " << target_index; + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "GetBInlogOffset res: " << s.ToString() + << " possible_offset " << possible_offset.ToString() << " target_index " << target_index; } return FindLogicOffsetBySearchingBinlog(start_offset, target_index, found_offset); } @@ -851,8 +830,7 @@ Status ConsensusCoordinator::FindLogicOffset(const BinlogOffset& start_offset, u Status ConsensusCoordinator::GetLogsBefore(const BinlogOffset& start_offset, std::vector* hints) { BinlogOffset traversal_end = start_offset; BinlogOffset traversal_start(traversal_end.filenum, 0); - traversal_start.filenum = - traversal_start.filenum == 0 ? 0 : traversal_start.filenum - 1; + traversal_start.filenum = traversal_start.filenum == 0 ? 0 : traversal_start.filenum - 1; std::map binlogs; if (!stable_logger_->GetBinlogFiles(&binlogs)) { return Status::Corruption("Get binlog files failed"); @@ -872,30 +850,30 @@ Status ConsensusCoordinator::GetLogsBefore(const BinlogOffset& start_offset, std return Status::OK(); } -Status ConsensusCoordinator::LeaderNegotiate( - const LogOffset& f_last_offset, bool* reject, std::vector* hints) { +Status ConsensusCoordinator::LeaderNegotiate(const LogOffset& f_last_offset, bool* reject, + std::vector* hints) { uint64_t f_index = f_last_offset.l_offset.index; - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << "LeaderNeotiate follower last offset " - << f_last_offset.ToString() - << " first_offsert " << stable_logger_->first_offset().ToString() - << " last_offset " << mem_logger_->last_offset().ToString(); + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "LeaderNeotiate follower last offset " + << f_last_offset.ToString() << " first_offsert " << stable_logger_->first_offset().ToString() + << " last_offset " << mem_logger_->last_offset().ToString(); *reject = true; if (f_index > mem_logger_->last_offset().l_offset.index) { // hints starts from last_offset() - 100; Status s = GetLogsBefore(mem_logger_->last_offset().b_offset, hints); if (!s.ok()) { - LOG(WARNING) << f_index << " is larger than last index " << mem_logger_->last_offset().ToString() << " get logs before last index failed " << s.ToString(); + LOG(WARNING) << f_index << " is larger than last index " << mem_logger_->last_offset().ToString() + << " get logs before last index failed " << s.ToString(); return s; } LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << "follower index larger then last_offset index, get logs before " << mem_logger_->last_offset().ToString(); + << "follower index larger then last_offset index, get logs before " + << mem_logger_->last_offset().ToString(); return Status::OK(); } if (f_index < stable_logger_->first_offset().l_offset.index) { // need full sync - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << f_index << " not found current first index" << stable_logger_->first_offset().ToString(); + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << f_index << " not found current first index" + << stable_logger_->first_offset().ToString(); return Status::NotFound("logic index"); } if (f_last_offset.l_offset.index == 0) { @@ -907,29 +885,27 @@ Status ConsensusCoordinator::LeaderNegotiate( Status s = FindLogicOffset(f_last_offset.b_offset, f_index, &found_offset); if (!s.ok()) { if (s.IsNotFound()) { - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << f_last_offset.ToString() << " not found " << s.ToString(); + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << f_last_offset.ToString() << " not found " + << s.ToString(); return s; } else { - LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() - << "find logic offset failed" << s.ToString(); + LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() << "find logic offset failed" + << s.ToString(); return s; } } - if (found_offset.l_offset.term != f_last_offset.l_offset.term - || !(f_last_offset.b_offset == found_offset.b_offset)) { + if (found_offset.l_offset.term != f_last_offset.l_offset.term || !(f_last_offset.b_offset == found_offset.b_offset)) { Status s = GetLogsBefore(found_offset.b_offset, hints); if (!s.ok()) { - LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() - << "Try to get logs before " << found_offset.ToString() << " failed"; + LOG(WARNING) << PartitionInfo(table_name_, partition_id_).ToString() << "Try to get logs before " + << found_offset.ToString() << " failed"; return s; } return Status::OK(); } - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << "Found equal offset " << found_offset.ToString(); + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "Found equal offset " << found_offset.ToString(); *reject = false; return Status::OK(); } @@ -939,8 +915,8 @@ Status ConsensusCoordinator::FollowerNegotiate(const std::vector& hin if (hints.empty()) { return Status::Corruption("hints empty"); } - LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() - << "FollowerNegotiate from " << hints[0].ToString() << " to " << hints[hints.size() - 1].ToString(); + LOG(INFO) << PartitionInfo(table_name_, partition_id_).ToString() << "FollowerNegotiate from " << hints[0].ToString() + << " to " << hints[hints.size() - 1].ToString(); if (mem_logger_->last_offset().l_offset.index < hints[0].l_offset.index) { *reply_offset = mem_logger_->last_offset(); return Status::OK(); @@ -948,7 +924,7 @@ Status ConsensusCoordinator::FollowerNegotiate(const std::vector& hin if (committed_index().l_offset.index > hints[hints.size() - 1].l_offset.index) { return Status::Corruption("invalid hints all smaller than committed_index"); } - if (mem_logger_->last_offset().l_offset.index > hints[hints.size() - 1].l_offset.index) { + if (mem_logger_->last_offset().l_offset.index > hints[hints.size() - 1].l_offset.index) { LogOffset truncate_offset = hints[hints.size() - 1]; // trunck to hints end Status s = TruncateTo(truncate_offset); diff --git a/src/pika_data_distribution.cc b/src/pika_data_distribution.cc index 13e2e53fc0..df43c19e4b 100644 --- a/src/pika_data_distribution.cc +++ b/src/pika_data_distribution.cc @@ -8,22 +8,19 @@ const std::string kTagBegin = "{"; const std::string kTagEnd = "}"; -void HashModulo::Init() { -} +void HashModulo::Init() {} uint32_t HashModulo::Distribute(const std::string& str, uint32_t partition_num) { - return std::hash()(str) % partition_num; + return std::hash()(str) % partition_num; } -void Crc32::Init() { - Crc32TableInit(IEEE_POLY); -} +void Crc32::Init() { Crc32TableInit(IEEE_POLY); } void Crc32::Crc32TableInit(uint32_t poly) { int i, j; - for (i = 0; i < 256; i ++) { + for (i = 0; i < 256; i++) { uint32_t crc = i; - for (j = 0; j < 8; j ++) { + for (j = 0; j < 8; j++) { if (crc & 1) { crc = (crc >> 1) ^ poly; } else { @@ -34,7 +31,7 @@ void Crc32::Crc32TableInit(uint32_t poly) { } } -uint32_t Crc32::Distribute(const std::string &str, uint32_t partition_num) { +uint32_t Crc32::Distribute(const std::string& str, uint32_t partition_num) { std::string key = GetHashkey(str); uint32_t crc = Crc32Update(0, key.data(), (int)key.size()); assert(partition_num != 0); @@ -44,14 +41,14 @@ uint32_t Crc32::Distribute(const std::string &str, uint32_t partition_num) { uint32_t Crc32::Crc32Update(uint32_t crc, const char* buf, int len) { int i; crc = ~crc; - for (i = 0; i < len; i ++) { + for (i = 0; i < len; i++) { crc = crc32tab[(uint8_t)((char)crc ^ buf[i])] ^ (crc >> 8); } return ~crc; } std::string GetHashkey(const std::string& key) { - auto beg = key.find_first_of(kTagBegin); + auto beg = key.find_first_of(kTagBegin); if (beg == std::string::npos) { return key; } diff --git a/src/pika_dispatch_thread.cc b/src/pika_dispatch_thread.cc index bb4a8a2629..93007e9be5 100644 --- a/src/pika_dispatch_thread.cc +++ b/src/pika_dispatch_thread.cc @@ -13,12 +13,10 @@ extern PikaConf* g_pika_conf; extern PikaServer* g_pika_server; -PikaDispatchThread::PikaDispatchThread(std::set &ips, int port, int work_num, - int cron_interval, int queue_limit, int max_conn_rbuf_size) - : conn_factory_(max_conn_rbuf_size), - handles_(this) { - thread_rep_ = net::NewDispatchThread(ips, port, work_num, &conn_factory_, - cron_interval, queue_limit, &handles_); +PikaDispatchThread::PikaDispatchThread(std::set& ips, int port, int work_num, int cron_interval, + int queue_limit, int max_conn_rbuf_size) + : conn_factory_(max_conn_rbuf_size), handles_(this) { + thread_rep_ = net::NewDispatchThread(ips, port, work_num, &conn_factory_, cron_interval, queue_limit, &handles_); thread_rep_->set_thread_name("Dispatcher"); } @@ -28,33 +26,23 @@ PikaDispatchThread::~PikaDispatchThread() { delete thread_rep_; } -int PikaDispatchThread::StartThread() { - return thread_rep_->StartThread(); -} +int PikaDispatchThread::StartThread() { return thread_rep_->StartThread(); } -int64_t PikaDispatchThread::ThreadClientList(std::vector *clients) { - std::vector conns_info = - thread_rep_->conns_info(); +int64_t PikaDispatchThread::ThreadClientList(std::vector* clients) { + std::vector conns_info = thread_rep_->conns_info(); if (clients != nullptr) { for (auto& info : conns_info) { clients->push_back({ - info.fd, - info.ip_port, - info.last_interaction.tv_sec, - nullptr /* NetConn pointer, doesn't need here */ - }); + info.fd, info.ip_port, info.last_interaction.tv_sec, nullptr /* NetConn pointer, doesn't need here */ + }); } } return conns_info.size(); } -bool PikaDispatchThread::ClientKill(const std::string& ip_port) { - return thread_rep_->KillConn(ip_port); -} +bool PikaDispatchThread::ClientKill(const std::string& ip_port) { return thread_rep_->KillConn(ip_port); } -void PikaDispatchThread::ClientKillAll() { - thread_rep_->KillAllConns(); -} +void PikaDispatchThread::ClientKillAll() { thread_rep_->KillAllConns(); } bool PikaDispatchThread::Handles::AccessHandle(std::string& ip) const { if (ip == "127.0.0.1") { @@ -62,8 +50,8 @@ bool PikaDispatchThread::Handles::AccessHandle(std::string& ip) const { } int client_num = pika_disptcher_->thread_rep_->conn_num(); - if ((client_num >= g_pika_conf->maxclients() + g_pika_conf->root_connection_num()) - || (client_num >= g_pika_conf->maxclients() && ip != g_pika_server->host())) { + if ((client_num >= g_pika_conf->maxclients() + g_pika_conf->root_connection_num()) || + (client_num >= g_pika_conf->maxclients() && ip != g_pika_server->host())) { LOG(WARNING) << "Max connections reach, Deny new comming: " << ip; return false; } diff --git a/src/pika_geo.cc b/src/pika_geo.cc index 9dd0bf0de3..94537f4bea 100644 --- a/src/pika_geo.cc +++ b/src/pika_geo.cc @@ -85,7 +85,7 @@ void GeoPosCmd::Do(std::shared_ptr partition) { rocksdb::Status s = partition->db()->ZScore(key_, member, &score); if (s.ok()) { double xy[2]; - GeoHashBits hash = { .bits = (uint64_t)score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, xy); res_.AppendArrayLen(2); @@ -98,18 +98,18 @@ void GeoPosCmd::Do(std::shared_ptr partition) { len = pstd::d2string(latitude, sizeof(latitude), xy[1]); res_.AppendStringLen(len); res_.AppendContent(latitude); - + } else if (s.IsNotFound()) { res_.AppendStringLen(-1); continue; } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); - continue; + continue; } } } -static double length_converter(double meters, const std::string & unit) { +static double length_converter(double meters, const std::string& unit) { if (unit == "m") { return meters; } else if (unit == "km") { @@ -123,7 +123,7 @@ static double length_converter(double meters, const std::string & unit) { } } -static bool check_unit(const std::string & unit) { +static bool check_unit(const std::string& unit) { if (unit == "m" || unit == "km" || unit == "ft" || unit == "mi") { return true; } else { @@ -161,26 +161,26 @@ void GeoDistCmd::Do(std::shared_ptr partition) { double first_score, second_score, first_xy[2], second_xy[2]; rocksdb::Status s = partition->db()->ZScore(key_, first_pos_, &first_score); if (s.ok()) { - GeoHashBits hash = { .bits = (uint64_t)first_score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)first_score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, first_xy); } else if (s.IsNotFound()) { res_.AppendStringLen(-1); return; } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); - return; + return; } s = partition->db()->ZScore(key_, second_pos_, &second_score); if (s.ok()) { - GeoHashBits hash = { .bits = (uint64_t)second_score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)second_score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, second_xy); } else if (s.IsNotFound()) { res_.AppendStringLen(-1); return; } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); - return; + return; } double distance = geohashGetDistance(first_xy[0], first_xy[1], second_xy[0], second_xy[1]); @@ -205,14 +205,14 @@ void GeoHashCmd::DoInitial() { } void GeoHashCmd::Do(std::shared_ptr partition) { - const char * geoalphabet= "0123456789bcdefghjkmnpqrstuvwxyz"; + const char* geoalphabet = "0123456789bcdefghjkmnpqrstuvwxyz"; res_.AppendArrayLen(members_.size()); for (const auto& member : members_) { double score; rocksdb::Status s = partition->db()->ZScore(key_, member, &score); if (s.ok()) { double xy[2]; - GeoHashBits hash = { .bits = (uint64_t)score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, xy); GeoHashRange r[2]; GeoHashBits encode_hash; @@ -225,7 +225,7 @@ void GeoHashCmd::Do(std::shared_ptr partition) { char buf[12]; int i; for (i = 0; i < 11; i++) { - int idx = (encode_hash.bits >> (52-((i+1)*5))) & 0x1f; + int idx = (encode_hash.bits >> (52 - ((i + 1) * 5))) & 0x1f; buf[i] = geoalphabet[idx]; } buf[11] = '\0'; @@ -237,20 +237,20 @@ void GeoHashCmd::Do(std::shared_ptr partition) { continue; } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); - continue; + continue; } } } -static bool sort_distance_asc(const NeighborPoint & pos1, const NeighborPoint & pos2) { +static bool sort_distance_asc(const NeighborPoint& pos1, const NeighborPoint& pos2) { return pos1.distance < pos2.distance; } -static bool sort_distance_desc(const NeighborPoint & pos1, const NeighborPoint & pos2) { +static bool sort_distance_desc(const NeighborPoint& pos1, const NeighborPoint& pos2) { return pos1.distance > pos2.distance; } -static void GetAllNeighbors(std::shared_ptr partition, std::string & key, GeoRange & range, CmdRes & res) { +static void GetAllNeighbors(std::shared_ptr partition, std::string& key, GeoRange& range, CmdRes& res) { rocksdb::Status s; double longitude = range.longitude, latitude = range.latitude, distance = range.distance; int count_limit = 0; @@ -285,15 +285,15 @@ static void GetAllNeighbors(std::shared_ptr partition, std::string & int last_processed = 0; for (size_t i = 0; i < sizeof(neighbors) / sizeof(*neighbors); i++) { GeoHashFix52Bits min, max; - if (HASHISZERO(neighbors[i])) - continue; + if (HASHISZERO(neighbors[i])) continue; min = geohashAlign52Bits(neighbors[i]); neighbors[i].bits++; max = geohashAlign52Bits(neighbors[i]); // When a huge Radius (in the 5000 km range or more) is used, // adjacent neighbors can be the same, so need to remove duplicated elements - if(last_processed && neighbors[i].bits == neighbors[last_processed].bits && neighbors[i].step == neighbors[last_processed].step) { - continue; + if (last_processed && neighbors[i].bits == neighbors[last_processed].bits && + neighbors[i].step == neighbors[last_processed].step) { + continue; } std::vector score_members; s = partition->db()->ZRangebyscore(key, (double)min, (double)max, true, true, &score_members); @@ -304,9 +304,9 @@ static void GetAllNeighbors(std::shared_ptr partition, std::string & // Insert into result only if the point is within the search area. for (size_t i = 0; i < score_members.size(); ++i) { double xy[2], real_distance; - GeoHashBits hash = { .bits = (uint64_t)score_members[i].score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)score_members[i].score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, xy); - if(geohashGetDistanceIfInRadiusWGS84(longitude, latitude, xy[0], xy[1], distance, &real_distance)) { + if (geohashGetDistanceIfInRadiusWGS84(longitude, latitude, xy[0], xy[1], distance, &real_distance)) { NeighborPoint item; item.member = score_members[i].member; item.score = score_members[i].score; @@ -316,7 +316,7 @@ static void GetAllNeighbors(std::shared_ptr partition, std::string & } last_processed = i; } - + // If using the count opiton if (range.count) { count_limit = static_cast(result.size()) < range.count_limit ? result.size() : range.count_limit; @@ -326,10 +326,10 @@ static void GetAllNeighbors(std::shared_ptr partition, std::string & // If using sort option if (range.sort == Asc) { std::sort(result.begin(), result.end(), sort_distance_asc); - } else if(range.sort == Desc) { + } else if (range.sort == Desc) { std::sort(result.begin(), result.end(), sort_distance_desc); } - + if (range.store || range.storedist) { // Target key, create a sorted set with the results. std::vector score_members; @@ -348,21 +348,21 @@ static void GetAllNeighbors(std::shared_ptr partition, std::string & return; } else { // No target key, return results to user. - + // For each the result res.AppendArrayLen(count_limit); for (int i = 0; i < count_limit; ++i) { if (range.option_num != 0) { - res.AppendArrayLen(range.option_num+1); + res.AppendArrayLen(range.option_num + 1); } // Member res.AppendStringLen(result[i].member.size()); res.AppendContent(result[i].member); - + // If using withdist option - if (range.withdist) { + if (range.withdist) { double xy[2]; - GeoHashBits hash = { .bits = (uint64_t)result[i].score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)result[i].score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, xy); double distance = geohashGetDistance(longitude, latitude, xy[0], xy[1]); distance = length_converter(distance, range.unit); @@ -377,9 +377,9 @@ static void GetAllNeighbors(std::shared_ptr partition, std::string & } // If using withcoord option if (range.withcoord) { - res.AppendArrayLen(2); + res.AppendArrayLen(2); double xy[2]; - GeoHashBits hash = { .bits = (uint64_t)result[i].score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)result[i].score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, xy); char longitude[32]; @@ -416,16 +416,16 @@ void GeoRadiusCmd::DoInitial() { range_.withdist = true; range_.option_num++; } else if (!strcasecmp(argv_[pos].c_str(), "withhash")) { - range_.withhash = true; + range_.withhash = true; range_.option_num++; } else if (!strcasecmp(argv_[pos].c_str(), "withcoord")) { - range_.withcoord = true; + range_.withcoord = true; range_.option_num++; } else if (!strcasecmp(argv_[pos].c_str(), "count")) { - range_.count = true; - if (argv_.size() < (pos+2)) { + range_.count = true; + if (argv_.size() < (pos + 2)) { res_.SetRes(CmdRes::kSyntaxErr); - return; + return; } std::string str_count = argv_[++pos]; for (auto s : str_count) { @@ -433,26 +433,26 @@ void GeoRadiusCmd::DoInitial() { res_.SetRes(CmdRes::kErrOther, "value is not an integer or out of range"); return; } - } + } range_.count_limit = std::stoi(str_count); } else if (!strcasecmp(argv_[pos].c_str(), "store")) { range_.store = true; - if (argv_.size() < (pos+2)) { + if (argv_.size() < (pos + 2)) { res_.SetRes(CmdRes::kSyntaxErr); - return; + return; } range_.storekey = argv_[++pos]; } else if (!strcasecmp(argv_[pos].c_str(), "storedist")) { range_.storedist = true; - if (argv_.size() < (pos+2)) { + if (argv_.size() < (pos + 2)) { res_.SetRes(CmdRes::kSyntaxErr); - return; + return; } range_.storekey = argv_[++pos]; } else if (!strcasecmp(argv_[pos].c_str(), "asc")) { - range_.sort = Asc; + range_.sort = Asc; } else if (!strcasecmp(argv_[pos].c_str(), "desc")) { - range_.sort = Desc; + range_.sort = Desc; } else { res_.SetRes(CmdRes::kSyntaxErr); return; @@ -460,14 +460,13 @@ void GeoRadiusCmd::DoInitial() { pos++; } if (range_.store && (range_.withdist || range_.withcoord || range_.withhash)) { - res_.SetRes(CmdRes::kErrOther, "STORE option in GEORADIUS is not compatible with WITHDIST, WITHHASH and WITHCOORDS options"); + res_.SetRes(CmdRes::kErrOther, + "STORE option in GEORADIUS is not compatible with WITHDIST, WITHHASH and WITHCOORDS options"); return; } } -void GeoRadiusCmd::Do(std::shared_ptr partition) { - GetAllNeighbors(partition, key_, range_, this->res_); -} +void GeoRadiusCmd::Do(std::shared_ptr partition) { GetAllNeighbors(partition, key_, range_, this->res_); } void GeoRadiusByMemberCmd::DoInitial() { if (!CheckArg(argv_.size())) { @@ -488,16 +487,16 @@ void GeoRadiusByMemberCmd::DoInitial() { range_.withdist = true; range_.option_num++; } else if (!strcasecmp(argv_[pos].c_str(), "withhash")) { - range_.withhash = true; + range_.withhash = true; range_.option_num++; } else if (!strcasecmp(argv_[pos].c_str(), "withcoord")) { - range_.withcoord = true; + range_.withcoord = true; range_.option_num++; } else if (!strcasecmp(argv_[pos].c_str(), "count")) { - range_.count = true; - if (argv_.size() < (pos+2)) { + range_.count = true; + if (argv_.size() < (pos + 2)) { res_.SetRes(CmdRes::kSyntaxErr); - return; + return; } std::string str_count = argv_[++pos]; for (auto s : str_count) { @@ -505,26 +504,26 @@ void GeoRadiusByMemberCmd::DoInitial() { res_.SetRes(CmdRes::kErrOther, "value is not an integer or out of range"); return; } - } + } range_.count_limit = std::stoi(str_count); } else if (!strcasecmp(argv_[pos].c_str(), "store")) { range_.store = true; - if (argv_.size() < (pos+2)) { + if (argv_.size() < (pos + 2)) { res_.SetRes(CmdRes::kSyntaxErr); - return; + return; } range_.storekey = argv_[++pos]; } else if (!strcasecmp(argv_[pos].c_str(), "storedist")) { range_.storedist = true; - if (argv_.size() < (pos+2)) { + if (argv_.size() < (pos + 2)) { res_.SetRes(CmdRes::kSyntaxErr); - return; + return; } range_.storekey = argv_[++pos]; } else if (!strcasecmp(argv_[pos].c_str(), "asc")) { - range_.sort = Asc; + range_.sort = Asc; } else if (!strcasecmp(argv_[pos].c_str(), "desc")) { - range_.sort = Desc; + range_.sort = Desc; } else { res_.SetRes(CmdRes::kSyntaxErr); return; @@ -532,7 +531,8 @@ void GeoRadiusByMemberCmd::DoInitial() { pos++; } if (range_.store && (range_.withdist || range_.withcoord || range_.withhash)) { - res_.SetRes(CmdRes::kErrOther, "STORE option in GEORADIUS is not compatible with WITHDIST, WITHHASH and WITHCOORDS options"); + res_.SetRes(CmdRes::kErrOther, + "STORE option in GEORADIUS is not compatible with WITHDIST, WITHHASH and WITHCOORDS options"); return; } } @@ -542,7 +542,7 @@ void GeoRadiusByMemberCmd::Do(std::shared_ptr partition) { rocksdb::Status s = partition->db()->ZScore(key_, range_.member, &score); if (s.ok()) { double xy[2]; - GeoHashBits hash = { .bits = (uint64_t)score, .step = GEO_STEP_MAX }; + GeoHashBits hash = {.bits = (uint64_t)score, .step = GEO_STEP_MAX}; geohashDecodeToLongLatWGS84(hash, xy); range_.longitude = xy[0]; range_.latitude = xy[1]; diff --git a/src/pika_geohash.cc b/src/pika_geohash.cc index 2ad66314b8..c041a18724 100644 --- a/src/pika_geohash.cc +++ b/src/pika_geohash.cc @@ -50,246 +50,226 @@ * From: https://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN */ static inline uint64_t interleave64(uint32_t xlo, uint32_t ylo) { - static const uint64_t B[] = {0x5555555555555555ULL, 0x3333333333333333ULL, - 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL, - 0x0000FFFF0000FFFFULL}; - static const unsigned int S[] = {1, 2, 4, 8, 16}; + static const uint64_t B[] = {0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, + 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL}; + static const unsigned int S[] = {1, 2, 4, 8, 16}; - uint64_t x = xlo; - uint64_t y = ylo; + uint64_t x = xlo; + uint64_t y = ylo; - x = (x | (x << S[4])) & B[4]; - y = (y | (y << S[4])) & B[4]; + x = (x | (x << S[4])) & B[4]; + y = (y | (y << S[4])) & B[4]; - x = (x | (x << S[3])) & B[3]; - y = (y | (y << S[3])) & B[3]; + x = (x | (x << S[3])) & B[3]; + y = (y | (y << S[3])) & B[3]; - x = (x | (x << S[2])) & B[2]; - y = (y | (y << S[2])) & B[2]; + x = (x | (x << S[2])) & B[2]; + y = (y | (y << S[2])) & B[2]; - x = (x | (x << S[1])) & B[1]; - y = (y | (y << S[1])) & B[1]; + x = (x | (x << S[1])) & B[1]; + y = (y | (y << S[1])) & B[1]; - x = (x | (x << S[0])) & B[0]; - y = (y | (y << S[0])) & B[0]; + x = (x | (x << S[0])) & B[0]; + y = (y | (y << S[0])) & B[0]; - return x | (y << 1); + return x | (y << 1); } /* reverse the interleave process * derived from http://stackoverflow.com/questions/4909263 */ static inline uint64_t deinterleave64(uint64_t interleaved) { - static const uint64_t B[] = {0x5555555555555555ULL, 0x3333333333333333ULL, - 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL, - 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; - static const unsigned int S[] = {0, 1, 2, 4, 8, 16}; + static const uint64_t B[] = {0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, + 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; + static const unsigned int S[] = {0, 1, 2, 4, 8, 16}; - uint64_t x = interleaved; - uint64_t y = interleaved >> 1; + uint64_t x = interleaved; + uint64_t y = interleaved >> 1; - x = (x | (x >> S[0])) & B[0]; - y = (y | (y >> S[0])) & B[0]; + x = (x | (x >> S[0])) & B[0]; + y = (y | (y >> S[0])) & B[0]; - x = (x | (x >> S[1])) & B[1]; - y = (y | (y >> S[1])) & B[1]; + x = (x | (x >> S[1])) & B[1]; + y = (y | (y >> S[1])) & B[1]; - x = (x | (x >> S[2])) & B[2]; - y = (y | (y >> S[2])) & B[2]; + x = (x | (x >> S[2])) & B[2]; + y = (y | (y >> S[2])) & B[2]; - x = (x | (x >> S[3])) & B[3]; - y = (y | (y >> S[3])) & B[3]; + x = (x | (x >> S[3])) & B[3]; + y = (y | (y >> S[3])) & B[3]; - x = (x | (x >> S[4])) & B[4]; - y = (y | (y >> S[4])) & B[4]; + x = (x | (x >> S[4])) & B[4]; + y = (y | (y >> S[4])) & B[4]; - x = (x | (x >> S[5])) & B[5]; - y = (y | (y >> S[5])) & B[5]; + x = (x | (x >> S[5])) & B[5]; + y = (y | (y >> S[5])) & B[5]; - return x | (y << 32); + return x | (y << 32); } -void geohashGetCoordRange(GeoHashRange *long_range, GeoHashRange *lat_range) { - /* These are constraints from EPSG:900913 / EPSG:3785 / OSGEO:41001 */ - /* We can't geocode at the north/south pole. */ - long_range->max = GEO_LONG_MAX; - long_range->min = GEO_LONG_MIN; - lat_range->max = GEO_LAT_MAX; - lat_range->min = GEO_LAT_MIN; +void geohashGetCoordRange(GeoHashRange* long_range, GeoHashRange* lat_range) { + /* These are constraints from EPSG:900913 / EPSG:3785 / OSGEO:41001 */ + /* We can't geocode at the north/south pole. */ + long_range->max = GEO_LONG_MAX; + long_range->min = GEO_LONG_MIN; + lat_range->max = GEO_LAT_MAX; + lat_range->min = GEO_LAT_MIN; } -int geohashEncode(const GeoHashRange *long_range, const GeoHashRange *lat_range, - double longitude, double latitude, uint8_t step, - GeoHashBits *hash) { - /* Check basic arguments sanity. */ - if (hash == NULL || step > 32 || step == 0 || - RANGEPISZERO(lat_range) || RANGEPISZERO(long_range)) return 0; - - /* Return an error when trying to index outside the supported - * constraints. */ - if (longitude > 180 || longitude < -180 || - latitude > 85.05112878 || latitude < -85.05112878) return 0; - - hash->bits = 0; - hash->step = step; - - if (latitude < lat_range->min || latitude > lat_range->max || - longitude < long_range->min || longitude > long_range->max) { - return 0; - } - - double lat_offset = - (latitude - lat_range->min) / (lat_range->max - lat_range->min); - double long_offset = - (longitude - long_range->min) / (long_range->max - long_range->min); - - /* convert to fixed point based on the step size */ - lat_offset *= (1ULL << step); - long_offset *= (1ULL << step); - hash->bits = interleave64(lat_offset, long_offset); - return 1; -} +int geohashEncode(const GeoHashRange* long_range, const GeoHashRange* lat_range, double longitude, double latitude, + uint8_t step, GeoHashBits* hash) { + /* Check basic arguments sanity. */ + if (hash == NULL || step > 32 || step == 0 || RANGEPISZERO(lat_range) || RANGEPISZERO(long_range)) return 0; -int geohashEncodeType(double longitude, double latitude, uint8_t step, GeoHashBits *hash) { - GeoHashRange r[2] = {{0}}; - geohashGetCoordRange(&r[0], &r[1]); - return geohashEncode(&r[0], &r[1], longitude, latitude, step, hash); -} + /* Return an error when trying to index outside the supported + * constraints. */ + if (longitude > 180 || longitude < -180 || latitude > 85.05112878 || latitude < -85.05112878) return 0; + + hash->bits = 0; + hash->step = step; -int geohashEncodeWGS84(double longitude, double latitude, uint8_t step, - GeoHashBits *hash) { - return geohashEncodeType(longitude, latitude, step, hash); + if (latitude < lat_range->min || latitude > lat_range->max || longitude < long_range->min || + longitude > long_range->max) { + return 0; + } + + double lat_offset = (latitude - lat_range->min) / (lat_range->max - lat_range->min); + double long_offset = (longitude - long_range->min) / (long_range->max - long_range->min); + + /* convert to fixed point based on the step size */ + lat_offset *= (1ULL << step); + long_offset *= (1ULL << step); + hash->bits = interleave64(lat_offset, long_offset); + return 1; } -int geohashDecode(const GeoHashRange long_range, const GeoHashRange lat_range, - const GeoHashBits hash, GeoHashArea *area) { - if (HASHISZERO(hash) || NULL == area || RANGEISZERO(lat_range) || - RANGEISZERO(long_range)) { - return 0; - } - - area->hash = hash; - uint8_t step = hash.step; - uint64_t hash_sep = deinterleave64(hash.bits); /* hash = [LAT][LONG] */ - - double lat_scale = lat_range.max - lat_range.min; - double long_scale = long_range.max - long_range.min; - - uint32_t ilato = hash_sep; /* get lat part of deinterleaved hash */ - uint32_t ilono = hash_sep >> 32; /* shift over to get long part of hash */ - - /* divide by 2**step. - * Then, for 0-1 coordinate, multiply times scale and add - to the min to get the absolute coordinate. */ - area->latitude.min = - lat_range.min + (ilato * 1.0 / (1ull << step)) * lat_scale; - area->latitude.max = - lat_range.min + ((ilato + 1) * 1.0 / (1ull << step)) * lat_scale; - area->longitude.min = - long_range.min + (ilono * 1.0 / (1ull << step)) * long_scale; - area->longitude.max = - long_range.min + ((ilono + 1) * 1.0 / (1ull << step)) * long_scale; - - return 1; +int geohashEncodeType(double longitude, double latitude, uint8_t step, GeoHashBits* hash) { + GeoHashRange r[2] = {{0}}; + geohashGetCoordRange(&r[0], &r[1]); + return geohashEncode(&r[0], &r[1], longitude, latitude, step, hash); } -int geohashDecodeType(const GeoHashBits hash, GeoHashArea *area) { - GeoHashRange r[2] = {{0}}; - geohashGetCoordRange(&r[0], &r[1]); - return geohashDecode(r[0], r[1], hash, area); +int geohashEncodeWGS84(double longitude, double latitude, uint8_t step, GeoHashBits* hash) { + return geohashEncodeType(longitude, latitude, step, hash); } -int geohashDecodeWGS84(const GeoHashBits hash, GeoHashArea *area) { - return geohashDecodeType(hash, area); +int geohashDecode(const GeoHashRange long_range, const GeoHashRange lat_range, const GeoHashBits hash, + GeoHashArea* area) { + if (HASHISZERO(hash) || NULL == area || RANGEISZERO(lat_range) || RANGEISZERO(long_range)) { + return 0; + } + + area->hash = hash; + uint8_t step = hash.step; + uint64_t hash_sep = deinterleave64(hash.bits); /* hash = [LAT][LONG] */ + + double lat_scale = lat_range.max - lat_range.min; + double long_scale = long_range.max - long_range.min; + + uint32_t ilato = hash_sep; /* get lat part of deinterleaved hash */ + uint32_t ilono = hash_sep >> 32; /* shift over to get long part of hash */ + + /* divide by 2**step. + * Then, for 0-1 coordinate, multiply times scale and add + to the min to get the absolute coordinate. */ + area->latitude.min = lat_range.min + (ilato * 1.0 / (1ull << step)) * lat_scale; + area->latitude.max = lat_range.min + ((ilato + 1) * 1.0 / (1ull << step)) * lat_scale; + area->longitude.min = long_range.min + (ilono * 1.0 / (1ull << step)) * long_scale; + area->longitude.max = long_range.min + ((ilono + 1) * 1.0 / (1ull << step)) * long_scale; + + return 1; } -int geohashDecodeAreaToLongLat(const GeoHashArea *area, double *xy) { - if (!xy) return 0; - xy[0] = (area->longitude.min + area->longitude.max) / 2; - xy[1] = (area->latitude.min + area->latitude.max) / 2; - return 1; +int geohashDecodeType(const GeoHashBits hash, GeoHashArea* area) { + GeoHashRange r[2] = {{0}}; + geohashGetCoordRange(&r[0], &r[1]); + return geohashDecode(r[0], r[1], hash, area); } -int geohashDecodeToLongLatType(const GeoHashBits hash, double *xy) { - GeoHashArea area = {{0}}; - if (!xy || !geohashDecodeType(hash, &area)) - return 0; - return geohashDecodeAreaToLongLat(&area, xy); +int geohashDecodeWGS84(const GeoHashBits hash, GeoHashArea* area) { return geohashDecodeType(hash, area); } + +int geohashDecodeAreaToLongLat(const GeoHashArea* area, double* xy) { + if (!xy) return 0; + xy[0] = (area->longitude.min + area->longitude.max) / 2; + xy[1] = (area->latitude.min + area->latitude.max) / 2; + return 1; } -int geohashDecodeToLongLatWGS84(const GeoHashBits hash, double *xy) { - return geohashDecodeToLongLatType(hash, xy); +int geohashDecodeToLongLatType(const GeoHashBits hash, double* xy) { + GeoHashArea area = {{0}}; + if (!xy || !geohashDecodeType(hash, &area)) return 0; + return geohashDecodeAreaToLongLat(&area, xy); } -static void geohash_move_x(GeoHashBits *hash, int8_t d) { - if (d == 0) - return; +int geohashDecodeToLongLatWGS84(const GeoHashBits hash, double* xy) { return geohashDecodeToLongLatType(hash, xy); } + +static void geohash_move_x(GeoHashBits* hash, int8_t d) { + if (d == 0) return; - uint64_t x = hash->bits & 0xaaaaaaaaaaaaaaaaULL; - uint64_t y = hash->bits & 0x5555555555555555ULL; + uint64_t x = hash->bits & 0xaaaaaaaaaaaaaaaaULL; + uint64_t y = hash->bits & 0x5555555555555555ULL; - uint64_t zz = 0x5555555555555555ULL >> (64 - hash->step * 2); + uint64_t zz = 0x5555555555555555ULL >> (64 - hash->step * 2); - if (d > 0) { - x = x + (zz + 1); - } else { - x = x | zz; - x = x - (zz + 1); - } + if (d > 0) { + x = x + (zz + 1); + } else { + x = x | zz; + x = x - (zz + 1); + } - x &= (0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step * 2)); - hash->bits = (x | y); + x &= (0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step * 2)); + hash->bits = (x | y); } -static void geohash_move_y(GeoHashBits *hash, int8_t d) { - if (d == 0) - return; - - uint64_t x = hash->bits & 0xaaaaaaaaaaaaaaaaULL; - uint64_t y = hash->bits & 0x5555555555555555ULL; - - uint64_t zz = 0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step * 2); - if (d > 0) { - y = y + (zz + 1); - } else { - y = y | zz; - y = y - (zz + 1); - } - y &= (0x5555555555555555ULL >> (64 - hash->step * 2)); - hash->bits = (x | y); +static void geohash_move_y(GeoHashBits* hash, int8_t d) { + if (d == 0) return; + + uint64_t x = hash->bits & 0xaaaaaaaaaaaaaaaaULL; + uint64_t y = hash->bits & 0x5555555555555555ULL; + + uint64_t zz = 0xaaaaaaaaaaaaaaaaULL >> (64 - hash->step * 2); + if (d > 0) { + y = y + (zz + 1); + } else { + y = y | zz; + y = y - (zz + 1); + } + y &= (0x5555555555555555ULL >> (64 - hash->step * 2)); + hash->bits = (x | y); } -void geohashNeighbors(const GeoHashBits *hash, GeoHashNeighbors *neighbors) { - neighbors->east = *hash; - neighbors->west = *hash; - neighbors->north = *hash; - neighbors->south = *hash; - neighbors->south_east = *hash; - neighbors->south_west = *hash; - neighbors->north_east = *hash; - neighbors->north_west = *hash; +void geohashNeighbors(const GeoHashBits* hash, GeoHashNeighbors* neighbors) { + neighbors->east = *hash; + neighbors->west = *hash; + neighbors->north = *hash; + neighbors->south = *hash; + neighbors->south_east = *hash; + neighbors->south_west = *hash; + neighbors->north_east = *hash; + neighbors->north_west = *hash; - geohash_move_x(&neighbors->east, 1); - geohash_move_y(&neighbors->east, 0); + geohash_move_x(&neighbors->east, 1); + geohash_move_y(&neighbors->east, 0); - geohash_move_x(&neighbors->west, -1); - geohash_move_y(&neighbors->west, 0); + geohash_move_x(&neighbors->west, -1); + geohash_move_y(&neighbors->west, 0); - geohash_move_x(&neighbors->south, 0); - geohash_move_y(&neighbors->south, -1); + geohash_move_x(&neighbors->south, 0); + geohash_move_y(&neighbors->south, -1); - geohash_move_x(&neighbors->north, 0); - geohash_move_y(&neighbors->north, 1); + geohash_move_x(&neighbors->north, 0); + geohash_move_y(&neighbors->north, 1); - geohash_move_x(&neighbors->north_west, -1); - geohash_move_y(&neighbors->north_west, 1); + geohash_move_x(&neighbors->north_west, -1); + geohash_move_y(&neighbors->north_west, 1); - geohash_move_x(&neighbors->north_east, 1); - geohash_move_y(&neighbors->north_east, 1); + geohash_move_x(&neighbors->north_east, 1); + geohash_move_y(&neighbors->north_east, 1); - geohash_move_x(&neighbors->south_east, 1); - geohash_move_y(&neighbors->south_east, -1); + geohash_move_x(&neighbors->south_east, 1); + geohash_move_y(&neighbors->south_east, -1); - geohash_move_x(&neighbors->south_west, -1); - geohash_move_y(&neighbors->south_west, -1); + geohash_move_x(&neighbors->south_west, -1); + geohash_move_y(&neighbors->south_west, -1); } diff --git a/src/pika_geohash_helper.cc b/src/pika_geohash_helper.cc index a2f18d7090..134cec7976 100644 --- a/src/pika_geohash_helper.cc +++ b/src/pika_geohash_helper.cc @@ -34,16 +34,16 @@ * /~https://github.com/yinqiwen/ardb/blob/d42503/src/geo/geohash_helper.cpp */ -//#include "fmacros.h" +// #include "fmacros.h" #include "include/pika_geohash_helper.h" -//#include "debugmacro.h" +// #include "debugmacro.h" #include #define D_R (M_PI / 180.0) #define R_MAJOR 6378137.0 #define R_MINOR 6356752.3142 #define RATIO (R_MINOR / R_MAJOR) -#define ECCENT (sqrt(1.0 - (RATIO *RATIO))) +#define ECCENT (sqrt(1.0 - (RATIO * RATIO))) #define COM (0.5 * ECCENT) /// @brief The usual PI/180 constant @@ -60,26 +60,26 @@ static inline double rad_deg(double ang) { return ang / D_R; } /* This function is used in order to estimate the step (bits precision) * of the 9 search area boxes during radius queries. */ uint8_t geohashEstimateStepsByRadius(double range_meters, double lat) { - if (range_meters == 0) return 26; - int step = 1; - while (range_meters < MERCATOR_MAX) { - range_meters *= 2; - step++; - } - step -= 2; /* Make sure range is included in most of the base cases. */ - - /* Wider range torwards the poles... Note: it is possible to do better - * than this approximation by computing the distance between meridians - * at this latitude, but this does the trick for now. */ - if (lat > 66 || lat < -66) { - step--; - if (lat > 80 || lat < -80) step--; - } - - /* Frame to valid range. */ - if (step < 1) step = 1; - if (step > 26) step = 26; - return step; + if (range_meters == 0) return 26; + int step = 1; + while (range_meters < MERCATOR_MAX) { + range_meters *= 2; + step++; + } + step -= 2; /* Make sure range is included in most of the base cases. */ + + /* Wider range torwards the poles... Note: it is possible to do better + * than this approximation by computing the distance between meridians + * at this latitude, but this does the trick for now. */ + if (lat > 66 || lat < -66) { + step--; + if (lat > 80 || lat < -80) step--; + } + + /* Frame to valid range. */ + if (step < 1) step = 1; + if (step > 26) step = 26; + return step; } /* Return the bounding box of the search area centered at latitude,longitude @@ -100,136 +100,125 @@ uint8_t geohashEstimateStepsByRadius(double range_meters, double lat) { * Since this function is currently only used as an optimization, the * optimization is not used for very big radiuses, however the function * should be fixed. */ -int geohashBoundingBox(double longitude, double latitude, double radius_meters, - double *bounds) { - if (!bounds) return 0; - - bounds[0] = longitude - rad_deg(radius_meters/EARTH_RADIUS_IN_METERS/cos(deg_rad(latitude))); - bounds[2] = longitude + rad_deg(radius_meters/EARTH_RADIUS_IN_METERS/cos(deg_rad(latitude))); - bounds[1] = latitude - rad_deg(radius_meters/EARTH_RADIUS_IN_METERS); - bounds[3] = latitude + rad_deg(radius_meters/EARTH_RADIUS_IN_METERS); - return 1; +int geohashBoundingBox(double longitude, double latitude, double radius_meters, double* bounds) { + if (!bounds) return 0; + + bounds[0] = longitude - rad_deg(radius_meters / EARTH_RADIUS_IN_METERS / cos(deg_rad(latitude))); + bounds[2] = longitude + rad_deg(radius_meters / EARTH_RADIUS_IN_METERS / cos(deg_rad(latitude))); + bounds[1] = latitude - rad_deg(radius_meters / EARTH_RADIUS_IN_METERS); + bounds[3] = latitude + rad_deg(radius_meters / EARTH_RADIUS_IN_METERS); + return 1; } /* Return a set of areas (center + 8) that are able to cover a range query * for the specified position and radius. */ GeoHashRadius geohashGetAreasByRadius(double longitude, double latitude, double radius_meters) { - GeoHashRange long_range, lat_range; - GeoHashRadius radius; - GeoHashBits hash; - GeoHashNeighbors neighbors; - GeoHashArea area; - double min_lon, max_lon, min_lat, max_lat; - double bounds[4]; - int steps; - - geohashBoundingBox(longitude, latitude, radius_meters, bounds); - min_lon = bounds[0]; - min_lat = bounds[1]; - max_lon = bounds[2]; - max_lat = bounds[3]; - - steps = geohashEstimateStepsByRadius(radius_meters,latitude); - - geohashGetCoordRange(&long_range,&lat_range); - geohashEncode(&long_range,&lat_range,longitude,latitude,steps,&hash); - geohashNeighbors(&hash,&neighbors); - geohashDecode(long_range,lat_range,hash,&area); - - /* Check if the step is enough at the limits of the covered area. - * Sometimes when the search area is near an edge of the - * area, the estimated step is not small enough, since one of the - * north / south / west / east square is too near to the search area - * to cover everything. */ - int decrease_step = 0; - { - GeoHashArea north, south, east, west; - - geohashDecode(long_range, lat_range, neighbors.north, &north); - geohashDecode(long_range, lat_range, neighbors.south, &south); - geohashDecode(long_range, lat_range, neighbors.east, &east); - geohashDecode(long_range, lat_range, neighbors.west, &west); - - if (geohashGetDistance(longitude,latitude,longitude,north.latitude.max) - < radius_meters) decrease_step = 1; - if (geohashGetDistance(longitude,latitude,longitude,south.latitude.min) - < radius_meters) decrease_step = 1; - if (geohashGetDistance(longitude,latitude,east.longitude.max,latitude) - < radius_meters) decrease_step = 1; - if (geohashGetDistance(longitude,latitude,west.longitude.min,latitude) - < radius_meters) decrease_step = 1; + GeoHashRange long_range, lat_range; + GeoHashRadius radius; + GeoHashBits hash; + GeoHashNeighbors neighbors; + GeoHashArea area; + double min_lon, max_lon, min_lat, max_lat; + double bounds[4]; + int steps; + + geohashBoundingBox(longitude, latitude, radius_meters, bounds); + min_lon = bounds[0]; + min_lat = bounds[1]; + max_lon = bounds[2]; + max_lat = bounds[3]; + + steps = geohashEstimateStepsByRadius(radius_meters, latitude); + + geohashGetCoordRange(&long_range, &lat_range); + geohashEncode(&long_range, &lat_range, longitude, latitude, steps, &hash); + geohashNeighbors(&hash, &neighbors); + geohashDecode(long_range, lat_range, hash, &area); + + /* Check if the step is enough at the limits of the covered area. + * Sometimes when the search area is near an edge of the + * area, the estimated step is not small enough, since one of the + * north / south / west / east square is too near to the search area + * to cover everything. */ + int decrease_step = 0; + { + GeoHashArea north, south, east, west; + + geohashDecode(long_range, lat_range, neighbors.north, &north); + geohashDecode(long_range, lat_range, neighbors.south, &south); + geohashDecode(long_range, lat_range, neighbors.east, &east); + geohashDecode(long_range, lat_range, neighbors.west, &west); + + if (geohashGetDistance(longitude, latitude, longitude, north.latitude.max) < radius_meters) decrease_step = 1; + if (geohashGetDistance(longitude, latitude, longitude, south.latitude.min) < radius_meters) decrease_step = 1; + if (geohashGetDistance(longitude, latitude, east.longitude.max, latitude) < radius_meters) decrease_step = 1; + if (geohashGetDistance(longitude, latitude, west.longitude.min, latitude) < radius_meters) decrease_step = 1; + } + + if (steps > 1 && decrease_step) { + steps--; + geohashEncode(&long_range, &lat_range, longitude, latitude, steps, &hash); + geohashNeighbors(&hash, &neighbors); + geohashDecode(long_range, lat_range, hash, &area); + } + + /* Exclude the search areas that are useless. */ + if (steps >= 2) { + if (area.latitude.min < min_lat) { + GZERO(neighbors.south); + GZERO(neighbors.south_west); + GZERO(neighbors.south_east); } - - if (steps > 1 && decrease_step) { - steps--; - geohashEncode(&long_range,&lat_range,longitude,latitude,steps,&hash); - geohashNeighbors(&hash,&neighbors); - geohashDecode(long_range,lat_range,hash,&area); + if (area.latitude.max > max_lat) { + GZERO(neighbors.north); + GZERO(neighbors.north_east); + GZERO(neighbors.north_west); } - - /* Exclude the search areas that are useless. */ - if (steps >= 2) { - if (area.latitude.min < min_lat) { - GZERO(neighbors.south); - GZERO(neighbors.south_west); - GZERO(neighbors.south_east); - } - if (area.latitude.max > max_lat) { - GZERO(neighbors.north); - GZERO(neighbors.north_east); - GZERO(neighbors.north_west); - } - if (area.longitude.min < min_lon) { - GZERO(neighbors.west); - GZERO(neighbors.south_west); - GZERO(neighbors.north_west); - } - if (area.longitude.max > max_lon) { - GZERO(neighbors.east); - GZERO(neighbors.south_east); - GZERO(neighbors.north_east); - } + if (area.longitude.min < min_lon) { + GZERO(neighbors.west); + GZERO(neighbors.south_west); + GZERO(neighbors.north_west); + } + if (area.longitude.max > max_lon) { + GZERO(neighbors.east); + GZERO(neighbors.south_east); + GZERO(neighbors.north_east); } - radius.hash = hash; - radius.neighbors = neighbors; - radius.area = area; - return radius; + } + radius.hash = hash; + radius.neighbors = neighbors; + radius.area = area; + return radius; } -GeoHashRadius geohashGetAreasByRadiusWGS84(double longitude, double latitude, - double radius_meters) { - return geohashGetAreasByRadius(longitude, latitude, radius_meters); +GeoHashRadius geohashGetAreasByRadiusWGS84(double longitude, double latitude, double radius_meters) { + return geohashGetAreasByRadius(longitude, latitude, radius_meters); } GeoHashFix52Bits geohashAlign52Bits(const GeoHashBits hash) { - uint64_t bits = hash.bits; - bits <<= (52 - hash.step * 2); - return bits; + uint64_t bits = hash.bits; + bits <<= (52 - hash.step * 2); + return bits; } /* Calculate distance using haversin great circle distance formula. */ double geohashGetDistance(double lon1d, double lat1d, double lon2d, double lat2d) { - double lat1r, lon1r, lat2r, lon2r, u, v; - lat1r = deg_rad(lat1d); - lon1r = deg_rad(lon1d); - lat2r = deg_rad(lat2d); - lon2r = deg_rad(lon2d); - u = sin((lat2r - lat1r) / 2); - v = sin((lon2r - lon1r) / 2); - return 2.0 * EARTH_RADIUS_IN_METERS * - asin(sqrt(u * u + cos(lat1r) * cos(lat2r) * v * v)); + double lat1r, lon1r, lat2r, lon2r, u, v; + lat1r = deg_rad(lat1d); + lon1r = deg_rad(lon1d); + lat2r = deg_rad(lat2d); + lon2r = deg_rad(lon2d); + u = sin((lat2r - lat1r) / 2); + v = sin((lon2r - lon1r) / 2); + return 2.0 * EARTH_RADIUS_IN_METERS * asin(sqrt(u * u + cos(lat1r) * cos(lat2r) * v * v)); } -int geohashGetDistanceIfInRadius(double x1, double y1, - double x2, double y2, double radius, - double *distance) { - *distance = geohashGetDistance(x1, y1, x2, y2); - if (*distance > radius) return 0; - return 1; +int geohashGetDistanceIfInRadius(double x1, double y1, double x2, double y2, double radius, double* distance) { + *distance = geohashGetDistance(x1, y1, x2, y2); + if (*distance > radius) return 0; + return 1; } -int geohashGetDistanceIfInRadiusWGS84(double x1, double y1, double x2, - double y2, double radius, - double *distance) { - return geohashGetDistanceIfInRadius(x1, y1, x2, y2, radius, distance); +int geohashGetDistanceIfInRadiusWGS84(double x1, double y1, double x2, double y2, double radius, double* distance) { + return geohashGetDistanceIfInRadius(x1, y1, x2, y2, radius, distance); } diff --git a/src/pika_hash.cc b/src/pika_hash.cc index 1fdbbaa27b..f1a0ebda78 100644 --- a/src/pika_hash.cc +++ b/src/pika_hash.cc @@ -9,7 +9,7 @@ #include "include/pika_conf.h" -extern PikaConf *g_pika_conf; +extern PikaConf* g_pika_conf; void HDelCmd::DoInitial() { if (!CheckArg(argv_.size())) { @@ -18,7 +18,7 @@ void HDelCmd::DoInitial() { } key_ = argv_[1]; PikaCmdArgsType::iterator iter = argv_.begin(); - iter++; + iter++; iter++; fields_.assign(iter, argv_.end()); return; @@ -129,7 +129,6 @@ void HGetallCmd::Do(std::shared_ptr partition) { return; } - void HExistsCmd::DoInitial() { if (!CheckArg(argv_.size())) { res_.SetRes(CmdRes::kWrongNum, kCmdNameHExists); @@ -259,7 +258,7 @@ void HMgetCmd::DoInitial() { PikaCmdArgsType::iterator iter = argv_.begin(); iter++; iter++; - fields_.assign(iter, argv_.end()); + fields_.assign(iter, argv_.end()); return; } @@ -391,8 +390,7 @@ void HScanCmd::DoInitial() { while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "count")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "count")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -429,7 +427,7 @@ void HScanCmd::Do(std::shared_ptr partition) { res_.AppendStringLen(len); res_.AppendContent(buf); - res_.AppendArrayLen(field_values.size()*2); + res_.AppendArrayLen(field_values.size() * 2); for (const auto& field_value : field_values) { res_.AppendString(field_value.field); res_.AppendString(field_value.value); @@ -451,8 +449,7 @@ void HScanxCmd::DoInitial() { size_t index = 3, argc = argv_.size(); while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "count")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "count")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -510,8 +507,7 @@ void PKHScanRangeCmd::DoInitial() { size_t index = 4, argc = argv_.size(); while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "limit")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "limit")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -535,8 +531,8 @@ void PKHScanRangeCmd::DoInitial() { void PKHScanRangeCmd::Do(std::shared_ptr partition) { std::string next_field; std::vector field_values; - rocksdb::Status s = partition->db()->PKHScanRange(key_, field_start_, field_end_, - pattern_, limit_, &field_values, &next_field); + rocksdb::Status s = + partition->db()->PKHScanRange(key_, field_start_, field_end_, pattern_, limit_, &field_values, &next_field); if (s.ok() || s.IsNotFound()) { res_.AppendArrayLen(2); @@ -565,8 +561,7 @@ void PKHRScanRangeCmd::DoInitial() { size_t index = 4, argc = argv_.size(); while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "limit")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "limit")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -590,8 +585,8 @@ void PKHRScanRangeCmd::DoInitial() { void PKHRScanRangeCmd::Do(std::shared_ptr partition) { std::string next_field; std::vector field_values; - rocksdb::Status s = partition->db()->PKHRScanRange(key_, field_start_, field_end_, - pattern_, limit_, &field_values, &next_field); + rocksdb::Status s = + partition->db()->PKHRScanRange(key_, field_start_, field_end_, pattern_, limit_, &field_values, &next_field); if (s.ok() || s.IsNotFound()) { res_.AppendArrayLen(2); diff --git a/src/pika_kv.cc b/src/pika_kv.cc index 6759438441..f67dbb5a2a 100644 --- a/src/pika_kv.cc +++ b/src/pika_kv.cc @@ -7,11 +7,11 @@ #include "pstd/include/pstd_string.h" +#include "include/pika_binlog_transverter.h" #include "include/pika_conf.h" #include "include/pika_data_distribution.h" -#include "include/pika_binlog_transverter.h" -extern PikaConf *g_pika_conf; +extern PikaConf* g_pika_conf; /* SET key value [NX] [XX] [EX ] [PX ] */ void SetCmd::DoInitial() { @@ -102,12 +102,8 @@ void SetCmd::Do(std::shared_ptr partition) { } } -std::string SetCmd::ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { +std::string SetCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) { if (condition_ == SetCmd::kEXORPX) { std::string content; content.reserve(RAW_ARGS_LEN); @@ -130,14 +126,8 @@ std::string SetCmd::ToBinlog( // value RedisAppendLen(content, value_.size(), "$"); RedisAppendContent(content, value_); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } else { return Cmd::ToBinlog(exec_time, term_id, logic_id, filenum, offset); } @@ -214,7 +204,7 @@ void IncrCmd::DoInitial() { void IncrCmd::Do(std::shared_ptr partition) { rocksdb::Status s = partition->db()->Incrby(key_, 1, &new_value_); if (s.ok()) { - res_.AppendContent(":" + std::to_string(new_value_)); + res_.AppendContent(":" + std::to_string(new_value_)); } else if (s.IsCorruption() && s.ToString() == "Corruption: Value is not a integer") { res_.SetRes(CmdRes::kInvalidInt); } else if (s.IsInvalidArgument()) { @@ -271,7 +261,7 @@ void IncrbyfloatCmd::Do(std::shared_ptr partition) { if (s.ok()) { res_.AppendStringLen(new_value_.size()); res_.AppendContent(new_value_); - } else if (s.IsCorruption() && s.ToString() == "Corruption: Value is not a vaild float"){ + } else if (s.IsCorruption() && s.ToString() == "Corruption: Value is not a vaild float") { res_.SetRes(CmdRes::kInvalidFloat); } else if (s.IsInvalidArgument()) { res_.SetRes(CmdRes::kOverFlow); @@ -293,7 +283,7 @@ void DecrCmd::DoInitial() { void DecrCmd::Do(std::shared_ptr partition) { rocksdb::Status s = partition->db()->Decrby(key_, 1, &new_value_); if (s.ok()) { - res_.AppendContent(":" + std::to_string(new_value_)); + res_.AppendContent(":" + std::to_string(new_value_)); } else if (s.IsCorruption() && s.ToString() == "Corruption: Value is not a integer") { res_.SetRes(CmdRes::kInvalidInt); } else if (s.IsInvalidArgument()) { @@ -511,12 +501,8 @@ void SetnxCmd::Do(std::shared_ptr partition) { return; } -std::string SetnxCmd::ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { +std::string SetnxCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, 3, "*"); @@ -533,14 +519,8 @@ std::string SetnxCmd::ToBinlog( RedisAppendLen(content, value_.size(), "$"); RedisAppendContent(content, value_); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } void SetexCmd::DoInitial() { @@ -566,13 +546,8 @@ void SetexCmd::Do(std::shared_ptr partition) { } } -std::string SetexCmd::ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { - +std::string SetexCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, 4, "*"); @@ -594,14 +569,8 @@ std::string SetexCmd::ToBinlog( // value RedisAppendLen(content, value_.size(), "$"); RedisAppendContent(content, value_); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } void PsetexCmd::DoInitial() { @@ -627,13 +596,8 @@ void PsetexCmd::Do(std::shared_ptr partition) { } } -std::string PsetexCmd::ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { - +std::string PsetexCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, 4, "*"); @@ -655,14 +619,8 @@ std::string PsetexCmd::ToBinlog( // value RedisAppendLen(content, value_.size(), "$"); RedisAppendContent(content, value_); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } void DelvxCmd::DoInitial() { @@ -734,8 +692,7 @@ void MsetCmd::Split(std::shared_ptr partition, const HintKeys& hint_k } } -void MsetCmd::Merge() { -} +void MsetCmd::Merge() {} void MsetnxCmd::DoInitial() { if (!CheckArg(argv_.size())) { @@ -897,12 +854,8 @@ void ExpireCmd::Do(std::shared_ptr partition) { return; } -std::string ExpireCmd::ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { +std::string ExpireCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, 3, "*"); @@ -922,14 +875,8 @@ std::string ExpireCmd::ToBinlog( RedisAppendLen(content, at.size(), "$"); RedisAppendContent(content, at); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } void PexpireCmd::DoInitial() { @@ -947,7 +894,7 @@ void PexpireCmd::DoInitial() { void PexpireCmd::Do(std::shared_ptr partition) { std::map type_status; - int64_t res = partition->db()->Expire(key_, msec_/1000, &type_status); + int64_t res = partition->db()->Expire(key_, msec_ / 1000, &type_status); if (res != -1) { res_.AppendInteger(res); } else { @@ -956,12 +903,8 @@ void PexpireCmd::Do(std::shared_ptr partition) { return; } -std::string PexpireCmd::ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { +std::string PexpireCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, argv_.size(), "*"); @@ -981,14 +924,8 @@ std::string PexpireCmd::ToBinlog( RedisAppendLen(content, at.size(), "$"); RedisAppendContent(content, at); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } void ExpireatCmd::DoInitial() { @@ -1027,12 +964,8 @@ void PexpireatCmd::DoInitial() { return; } -std::string PexpireatCmd::ToBinlog( - uint32_t exec_time, - uint32_t term_id, - uint64_t logic_id, - uint32_t filenum, - uint64_t offset) { +std::string PexpireatCmd::ToBinlog(uint32_t exec_time, uint32_t term_id, uint64_t logic_id, uint32_t filenum, + uint64_t offset) { std::string content; content.reserve(RAW_ARGS_LEN); RedisAppendLen(content, argv_.size(), "*"); @@ -1052,19 +985,13 @@ std::string PexpireatCmd::ToBinlog( RedisAppendLen(content, at.size(), "$"); RedisAppendContent(content, at); - return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, - exec_time, - term_id, - logic_id, - filenum, - offset, - content, - {}); + return PikaBinlogTransverter::BinlogEncode(BinlogType::TypeFirst, exec_time, term_id, logic_id, filenum, offset, + content, {}); } void PexpireatCmd::Do(std::shared_ptr partition) { std::map type_status; - int32_t res = partition->db()->Expireat(key_, time_stamp_ms_/1000, &type_status); + int32_t res = partition->db()->Expireat(key_, time_stamp_ms_ / 1000, &type_status); if (res != -1) { res_.AppendInteger(res); } else { @@ -1087,11 +1014,11 @@ void TtlCmd::Do(std::shared_ptr partition) { std::map type_status; type_timestamp = partition->db()->TTL(key_, &type_status); for (const auto& item : type_timestamp) { - // mean operation exception errors happen in database - if (item.second == -3) { - res_.SetRes(CmdRes::kErrOther, "ttl internal error"); - return; - } + // mean operation exception errors happen in database + if (item.second == -3) { + res_.SetRes(CmdRes::kErrOther, "ttl internal error"); + return; + } } if (type_timestamp[storage::kStrings] != -2) { res_.AppendInteger(type_timestamp[storage::kStrings]); @@ -1124,11 +1051,11 @@ void PttlCmd::Do(std::shared_ptr partition) { std::map type_status; type_timestamp = partition->db()->TTL(key_, &type_status); for (const auto& item : type_timestamp) { - // mean operation exception errors happen in database - if (item.second == -3) { - res_.SetRes(CmdRes::kErrOther, "ttl internal error"); - return; - } + // mean operation exception errors happen in database + if (item.second == -3) { + res_.SetRes(CmdRes::kErrOther, "ttl internal error"); + return; + } } if (type_timestamp[storage::kStrings] != -2) { if (type_timestamp[storage::kStrings] == -1) { @@ -1220,8 +1147,7 @@ void ScanCmd::DoInitial() { while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "count")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "count")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -1255,8 +1181,7 @@ void ScanCmd::Do(std::shared_ptr partition) { keys.clear(); batch_count = left < PIKA_SCAN_STEP_LENGTH ? left : PIKA_SCAN_STEP_LENGTH; left = left > PIKA_SCAN_STEP_LENGTH ? left - PIKA_SCAN_STEP_LENGTH : 0; - cursor_ret = partition->db()->Scan(storage::DataType::kAll, cursor_ret, - pattern_, batch_count, &keys); + cursor_ret = partition->db()->Scan(storage::DataType::kAll, cursor_ret, pattern_, batch_count, &keys); for (const auto& key : keys) { RedisAppendLen(raw, key.size(), "$"); RedisAppendContent(raw, key); @@ -1304,8 +1229,7 @@ void ScanxCmd::DoInitial() { size_t index = 3, argc = argv_.size(); while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "count")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "count")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -1338,7 +1262,7 @@ void ScanxCmd::Do(std::shared_ptr partition) { res_.AppendArrayLen(keys.size()); std::vector::iterator iter; - for (const auto& key : keys){ + for (const auto& key : keys) { res_.AppendString(key); } } else { @@ -1354,8 +1278,7 @@ void PKSetexAtCmd::DoInitial() { } key_ = argv_[1]; value_ = argv_[3]; - if (!pstd::string2int(argv_[2].data(), argv_[2].size(), &time_stamp_) - || time_stamp_ >= INT32_MAX) { + if (!pstd::string2int(argv_[2].data(), argv_[2].size(), &time_stamp_) || time_stamp_ >= INT32_MAX) { res_.SetRes(CmdRes::kInvalidInt); return; } @@ -1399,14 +1322,13 @@ void PKScanRangeCmd::DoInitial() { key_end_ = argv_[3]; // start key and end key hash tag have to be same in non classic mode if (!HashtagIsConsistent(key_start_, key_start_)) { - res_.SetRes(CmdRes::kInconsistentHashTag); - return; + res_.SetRes(CmdRes::kInconsistentHashTag); + return; } size_t index = 4, argc = argv_.size(); while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "limit")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "limit")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -1431,7 +1353,8 @@ void PKScanRangeCmd::Do(std::shared_ptr partition) { std::string next_key; std::vector keys; std::vector kvs; - rocksdb::Status s = partition->db()->PKScanRange(type_, key_start_, key_end_, pattern_, limit_, &keys, &kvs, &next_key); + rocksdb::Status s = + partition->db()->PKScanRange(type_, key_start_, key_end_, pattern_, limit_, &keys, &kvs, &next_key); if (s.ok()) { res_.AppendArrayLen(2); @@ -1448,7 +1371,7 @@ void PKScanRangeCmd::Do(std::shared_ptr partition) { } } else { res_.AppendArrayLen(keys.size()); - for (const auto& key : keys){ + for (const auto& key : keys) { res_.AppendString(key); } } @@ -1485,14 +1408,13 @@ void PKRScanRangeCmd::DoInitial() { key_end_ = argv_[3]; // start key and end key hash tag have to be same in non classic mode if (!HashtagIsConsistent(key_start_, key_start_)) { - res_.SetRes(CmdRes::kInconsistentHashTag); - return; + res_.SetRes(CmdRes::kInconsistentHashTag); + return; } size_t index = 4, argc = argv_.size(); while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "limit")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "limit")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -1517,7 +1439,8 @@ void PKRScanRangeCmd::Do(std::shared_ptr partition) { std::string next_key; std::vector keys; std::vector kvs; - rocksdb::Status s = partition->db()->PKRScanRange(type_, key_start_, key_end_, pattern_, limit_, &keys, &kvs, &next_key); + rocksdb::Status s = + partition->db()->PKRScanRange(type_, key_start_, key_end_, pattern_, limit_, &keys, &kvs, &next_key); if (s.ok()) { res_.AppendArrayLen(2); @@ -1534,7 +1457,7 @@ void PKRScanRangeCmd::Do(std::shared_ptr partition) { } } else { res_.AppendArrayLen(keys.size()); - for (const auto& key : keys){ + for (const auto& key : keys) { res_.AppendString(key); } } diff --git a/src/pika_list.cc b/src/pika_list.cc index 1e9c0819e1..d184252d37 100644 --- a/src/pika_list.cc +++ b/src/pika_list.cc @@ -5,8 +5,8 @@ #include "include/pika_list.h" -#include "pstd/include/pstd_string.h" #include "include/pika_data_distribution.h" +#include "pstd/include/pstd_string.h" void LIndexCmd::DoInitial() { if (!CheckArg(argv_.size())) { @@ -70,7 +70,7 @@ void LLenCmd::DoInitial() { void LLenCmd::Do(std::shared_ptr partition) { uint64_t llen = 0; rocksdb::Status s = partition->db()->LLen(key_, &llen); - if (s.ok() || s.IsNotFound()){ + if (s.ok() || s.IsNotFound()) { res_.AppendInteger(llen); } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); @@ -204,17 +204,17 @@ void LSetCmd::DoInitial() { value_ = argv_[3]; } void LSetCmd::Do(std::shared_ptr partition) { - rocksdb::Status s = partition->db()->LSet(key_, index_, value_); - if (s.ok()) { - res_.SetRes(CmdRes::kOk); - } else if (s.IsNotFound()) { - res_.SetRes(CmdRes::kNotFound); - } else if (s.IsCorruption() && s.ToString() == "Corruption: index out of range") { - //TODO refine return value - res_.SetRes(CmdRes::kOutOfRange); - } else { - res_.SetRes(CmdRes::kErrOther, s.ToString()); - } + rocksdb::Status s = partition->db()->LSet(key_, index_, value_); + if (s.ok()) { + res_.SetRes(CmdRes::kOk); + } else if (s.IsNotFound()) { + res_.SetRes(CmdRes::kNotFound); + } else if (s.IsCorruption() && s.ToString() == "Corruption: index out of range") { + // TODO refine return value + res_.SetRes(CmdRes::kOutOfRange); + } else { + res_.SetRes(CmdRes::kErrOther, s.ToString()); + } } void LTrimCmd::DoInitial() { diff --git a/src/pika_meta.cc b/src/pika_meta.cc index cd5438de15..7123ea2a9e 100644 --- a/src/pika_meta.cc +++ b/src/pika_meta.cc @@ -8,18 +8,11 @@ const uint32_t VERSION = 1; -PikaMeta::PikaMeta() - : local_meta_path_("") { - pthread_rwlock_init(&rwlock_, NULL); -} +PikaMeta::PikaMeta() : local_meta_path_("") { pthread_rwlock_init(&rwlock_, NULL); } -PikaMeta::~PikaMeta() { - pthread_rwlock_destroy(&rwlock_); -} +PikaMeta::~PikaMeta() { pthread_rwlock_destroy(&rwlock_); } -void PikaMeta::SetPath(const std::string& path) { - local_meta_path_ = path; -} +void PikaMeta::SetPath(const std::string& path) { local_meta_path_ = path; } /* * ******************* Meta File Format ****************** @@ -63,7 +56,7 @@ Status PikaMeta::StableSave(const std::vector& table_structs) { } uint32_t meta_str_size = meta_str.size(); - char *p = saver->GetData(); + char* p = saver->GetData(); memcpy(p, &VERSION, sizeof(uint32_t)); p += sizeof(uint32_t); memcpy(p, &meta_str_size, sizeof(uint32_t)); diff --git a/src/pika_monitor_thread.cc b/src/pika_monitor_thread.cc index ec08bab8a5..e2d46106d9 100644 --- a/src/pika_monitor_thread.cc +++ b/src/pika_monitor_thread.cc @@ -7,9 +7,7 @@ #include -PikaMonitorThread::PikaMonitorThread() - : net::Thread(), - monitor_cond_(&monitor_mutex_protector_) { +PikaMonitorThread::PikaMonitorThread() : net::Thread(), monitor_cond_(&monitor_mutex_protector_) { set_thread_name("MonitorThread"); has_monitor_clients_.store(false); } @@ -20,9 +18,7 @@ PikaMonitorThread::~PikaMonitorThread() { monitor_cond_.SignalAll(); StopThread(); } - for (std::list::iterator iter = monitor_clients_.begin(); - iter != monitor_clients_.end(); - ++iter) { + for (std::list::iterator iter = monitor_clients_.begin(); iter != monitor_clients_.end(); ++iter) { close(iter->fd); } LOG(INFO) << "PikaMonitorThread " << pthread_self() << " exit!!!"; @@ -42,7 +38,7 @@ void PikaMonitorThread::RemoveMonitorClient(const std::string& ip_port) { close(iter->fd); continue; } - if (iter->ip_port == ip_port) { + if (iter->ip_port == ip_port) { close(iter->fd); break; } @@ -55,21 +51,19 @@ void PikaMonitorThread::RemoveMonitorClient(const std::string& ip_port) { has_monitor_clients_.store(!monitor_clients_.empty()); } -void PikaMonitorThread::AddMonitorMessage(const std::string &monitor_message) { - pstd::MutexLock lm(&monitor_mutex_protector_); - if (monitor_messages_.empty() && cron_tasks_.empty()) { - monitor_messages_.push_back(monitor_message); - monitor_cond_.Signal(); - } else { - monitor_messages_.push_back(monitor_message); - } +void PikaMonitorThread::AddMonitorMessage(const std::string& monitor_message) { + pstd::MutexLock lm(&monitor_mutex_protector_); + if (monitor_messages_.empty() && cron_tasks_.empty()) { + monitor_messages_.push_back(monitor_message); + monitor_cond_.Signal(); + } else { + monitor_messages_.push_back(monitor_message); + } } int32_t PikaMonitorThread::ThreadClientList(std::vector* clients_ptr) { if (clients_ptr != NULL) { - for (std::list::iterator iter = monitor_clients_.begin(); - iter != monitor_clients_.end(); - iter++) { + for (std::list::iterator iter = monitor_clients_.begin(); iter != monitor_clients_.end(); iter++) { clients_ptr->push_back(*iter); } } @@ -86,11 +80,9 @@ void PikaMonitorThread::AddCronTask(MonitorCronTask task) { } } -bool PikaMonitorThread::FindClient(const std::string &ip_port) { +bool PikaMonitorThread::FindClient(const std::string& ip_port) { pstd::MutexLock lm(&monitor_mutex_protector_); - for (std::list::iterator iter = monitor_clients_.begin(); - iter != monitor_clients_.end(); - ++iter) { + for (std::list::iterator iter = monitor_clients_.begin(); iter != monitor_clients_.end(); ++iter) { if (iter->ip_port == ip_port) { return true; } @@ -111,9 +103,7 @@ bool PikaMonitorThread::ThreadClientKill(const std::string& ip_port) { return true; } -bool PikaMonitorThread::HasMonitorClients() { - return has_monitor_clients_.load(); -} +bool PikaMonitorThread::HasMonitorClients() { return has_monitor_clients_.load(); } net::WriteStatus PikaMonitorThread::SendMessage(int32_t fd, std::string& message) { size_t retry = 0; @@ -155,7 +145,7 @@ void* PikaMonitorThread::ThreadMain() { } if (should_stop()) { break; - } + } { pstd::MutexLock lm(&monitor_mutex_protector_); while (!cron_tasks_.empty()) { @@ -178,20 +168,16 @@ void* PikaMonitorThread::ThreadMain() { } } messages_transfer = "+"; - for (std::deque::iterator iter = messages_deque.begin(); - iter != messages_deque.end(); - ++iter) { + for (std::deque::iterator iter = messages_deque.begin(); iter != messages_deque.end(); ++iter) { messages_transfer.append(iter->data(), iter->size()); - messages_transfer.append("\n"); + messages_transfer.append("\n"); } if (messages_transfer == "+") { continue; } - messages_transfer.replace(messages_transfer.size()-1, 1, "\r\n", 0, 2); + messages_transfer.replace(messages_transfer.size() - 1, 1, "\r\n", 0, 2); monitor_mutex_protector_.Lock(); - for (std::list::iterator iter = monitor_clients_.begin(); - iter != monitor_clients_.end(); - ++iter) { + for (std::list::iterator iter = monitor_clients_.begin(); iter != monitor_clients_.end(); ++iter) { write_status = SendMessage(iter->fd, messages_transfer); if (write_status == net::kWriteError) { cron_tasks_.push({TASK_KILL, iter->ip_port}); diff --git a/src/pika_partition.cc b/src/pika_partition.cc index 5c5f312f0f..478c840af3 100644 --- a/src/pika_partition.cc +++ b/src/pika_partition.cc @@ -8,8 +8,8 @@ #include #include "include/pika_conf.h" -#include "include/pika_server.h" #include "include/pika_rm.h" +#include "include/pika_server.h" #include "pstd/include/mutex_impl.h" @@ -17,31 +17,26 @@ extern PikaConf* g_pika_conf; extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; -std::string PartitionPath(const std::string& table_path, - uint32_t partition_id) { +std::string PartitionPath(const std::string& table_path, uint32_t partition_id) { char buf[100]; snprintf(buf, sizeof(buf), "%u/", partition_id); return table_path + buf; } -std::string PartitionName(const std::string& table_name, - uint32_t partition_id) { +std::string PartitionName(const std::string& table_name, uint32_t partition_id) { char buf[256]; snprintf(buf, sizeof(buf), "(%s:%u)", table_name.data(), partition_id); return std::string(buf); } -std::string BgsaveSubPath(const std::string& table_name, - uint32_t partition_id) { +std::string BgsaveSubPath(const std::string& table_name, uint32_t partition_id) { char buf[256]; std::string partition_id_str = std::to_string(partition_id); snprintf(buf, sizeof(buf), "%s/%s", table_name.data(), partition_id_str.data()); return std::string(buf); } -std::string DbSyncPath(const std::string& sync_path, - const std::string& table_name, - const uint32_t partition_id, +std::string DbSyncPath(const std::string& sync_path, const std::string& table_name, const uint32_t partition_id, bool classic_mode) { char buf[256]; std::string partition_id_str = std::to_string(partition_id); @@ -53,27 +48,17 @@ std::string DbSyncPath(const std::string& sync_path, return sync_path + buf; } -Partition::Partition(const std::string& table_name, - uint32_t partition_id, - const std::string& table_db_path) : - table_name_(table_name), - partition_id_(partition_id), - bgsave_engine_(NULL) { - - db_path_ = g_pika_conf->classic_mode() ? - table_db_path : PartitionPath(table_db_path, partition_id_); - bgsave_sub_path_ = g_pika_conf->classic_mode() ? - table_name : BgsaveSubPath(table_name_, partition_id_); - dbsync_path_ = DbSyncPath(g_pika_conf->db_sync_path(), table_name_, - partition_id_, g_pika_conf->classic_mode()); - partition_name_ = g_pika_conf->classic_mode() ? - table_name : PartitionName(table_name_, partition_id_); +Partition::Partition(const std::string& table_name, uint32_t partition_id, const std::string& table_db_path) + : table_name_(table_name), partition_id_(partition_id), bgsave_engine_(NULL) { + db_path_ = g_pika_conf->classic_mode() ? table_db_path : PartitionPath(table_db_path, partition_id_); + bgsave_sub_path_ = g_pika_conf->classic_mode() ? table_name : BgsaveSubPath(table_name_, partition_id_); + dbsync_path_ = DbSyncPath(g_pika_conf->db_sync_path(), table_name_, partition_id_, g_pika_conf->classic_mode()); + partition_name_ = g_pika_conf->classic_mode() ? table_name : PartitionName(table_name_, partition_id_); pthread_rwlockattr_t attr; pthread_rwlockattr_init(&attr); #if !defined(__APPLE__) - pthread_rwlockattr_setkind_np(&attr, - PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); + pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); #endif pthread_rwlock_init(&db_rwlock_, &attr); @@ -131,42 +116,26 @@ void Partition::MoveToTrash() { LOG(WARNING) << "Partition DB: " << partition_name_ << " move to trash success"; } -std::string Partition::GetTableName() const { - return table_name_; -} +std::string Partition::GetTableName() const { return table_name_; } -uint32_t Partition::GetPartitionId() const { - return partition_id_; -} +uint32_t Partition::GetPartitionId() const { return partition_id_; } -std::string Partition::GetPartitionName() const { - return partition_name_; -} +std::string Partition::GetPartitionName() const { return partition_name_; } -std::shared_ptr Partition::db() const { - return db_; -} +std::shared_ptr Partition::db() const { return db_; } void Partition::Compact(const storage::DataType& type) { if (!opened_) return; db_->Compact(type); } -void Partition::DbRWLockWriter() { - pthread_rwlock_wrlock(&db_rwlock_); -} +void Partition::DbRWLockWriter() { pthread_rwlock_wrlock(&db_rwlock_); } -void Partition::DbRWLockReader() { - pthread_rwlock_rdlock(&db_rwlock_); -} +void Partition::DbRWLockReader() { pthread_rwlock_rdlock(&db_rwlock_); } -void Partition::DbRWUnLock() { - pthread_rwlock_unlock(&db_rwlock_); -} +void Partition::DbRWUnLock() { pthread_rwlock_unlock(&db_rwlock_); } -pstd::lock::LockMgr* Partition::LockMgr() { - return lock_mgr_; -} +pstd::lock::LockMgr* Partition::LockMgr() { return lock_mgr_; } void Partition::PrepareRsync() { pstd::DeleteDirIfExist(dbsync_path_); @@ -190,8 +159,7 @@ bool Partition::TryUpdateMasterOffset() { } std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_name_, partition_id_)); + g_pika_rm->GetSyncSlavePartitionByName(PartitionInfo(table_name_, partition_id_)); if (!slave_partition) { LOG(WARNING) << "Slave Partition: " << partition_name_ << " not exist"; return false; @@ -200,8 +168,7 @@ bool Partition::TryUpdateMasterOffset() { // Got new binlog offset std::ifstream is(info_path); if (!is) { - LOG(WARNING) << "Partition: " << partition_name_ - << ", Failed to open info file after db sync"; + LOG(WARNING) << "Partition: " << partition_name_ << ", Failed to open info file after db sync"; slave_partition->SetReplState(ReplState::kError); return false; } @@ -215,19 +182,24 @@ bool Partition::TryUpdateMasterOffset() { } else if (lineno > 2 && lineno < 8) { if (!pstd::string2int(line.data(), line.size(), &tmp) || tmp < 0) { LOG(WARNING) << "Partition: " << partition_name_ - << ", Format of info file after db sync error, line : " << line; + << ", Format of info file after db sync error, line : " << line; is.close(); slave_partition->SetReplState(ReplState::kError); return false; } - if (lineno == 3) { master_port = tmp; } - else if (lineno == 4) { filenum = tmp; } - else if (lineno == 5) { offset = tmp; } - else if (lineno == 6) { term = tmp; } - else if (lineno == 7) { index = tmp; } + if (lineno == 3) { + master_port = tmp; + } else if (lineno == 4) { + filenum = tmp; + } else if (lineno == 5) { + offset = tmp; + } else if (lineno == 6) { + term = tmp; + } else if (lineno == 7) { + index = tmp; + } } else if (lineno > 8) { - LOG(WARNING) << "Partition: " << partition_name_ - << ", Format of info file after db sync error, line : " << line; + LOG(WARNING) << "Partition: " << partition_name_ << ", Format of info file after db sync error, line : " << line; is.close(); slave_partition->SetReplState(ReplState::kError); return false; @@ -236,40 +208,33 @@ bool Partition::TryUpdateMasterOffset() { is.close(); LOG(INFO) << "Partition: " << partition_name_ << " Information from dbsync info" - << ", master_ip: " << master_ip - << ", master_port: " << master_port - << ", filenum: " << filenum - << ", offset: " << offset - << ", term: " << term - << ", index: " << index; + << ", master_ip: " << master_ip << ", master_port: " << master_port << ", filenum: " << filenum + << ", offset: " << offset << ", term: " << term << ", index: " << index; // Sanity check - if (master_ip != slave_partition->MasterIp() - || master_port != slave_partition->MasterPort()) { - LOG(WARNING) << "Partition: " << partition_name_ - << " Error master node ip port: " << master_ip << ":" << master_port; + if (master_ip != slave_partition->MasterIp() || master_port != slave_partition->MasterPort()) { + LOG(WARNING) << "Partition: " << partition_name_ << " Error master node ip port: " << master_ip << ":" + << master_port; slave_partition->SetReplState(ReplState::kError); return false; } pstd::DeleteFile(info_path); if (!ChangeDb(dbsync_path_)) { - LOG(WARNING) << "Partition: " << partition_name_ - << ", Failed to change db"; + LOG(WARNING) << "Partition: " << partition_name_ << ", Failed to change db"; slave_partition->SetReplState(ReplState::kError); return false; } // Update master offset std::shared_ptr master_partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name_, partition_id_)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name_, partition_id_)); if (!master_partition) { LOG(WARNING) << "Master Partition: " << partition_name_ << " not exist"; return false; } if (g_pika_conf->consensus_level() != 0) { - master_partition->ConsensusReset( - LogOffset(BinlogOffset(filenum, offset), LogicOffset(term, index))); + master_partition->ConsensusReset(LogOffset(BinlogOffset(filenum, offset), LogicOffset(term, index))); } else { master_partition->Logger()->SetProducerStatus(filenum, offset); } @@ -283,7 +248,6 @@ bool Partition::TryUpdateMasterOffset() { * db remain the old one if return false */ bool Partition::ChangeDb(const std::string& new_path) { - std::string tmp_path(db_path_); if (tmp_path.back() == '/') { tmp_path.resize(tmp_path.size() - 1); @@ -292,19 +256,18 @@ bool Partition::ChangeDb(const std::string& new_path) { pstd::DeleteDirIfExist(tmp_path); RWLock l(&db_rwlock_, true); - LOG(INFO) << "Partition: "<< partition_name_ - << ", Prepare change db from: " << tmp_path; + LOG(INFO) << "Partition: " << partition_name_ << ", Prepare change db from: " << tmp_path; db_.reset(); if (0 != pstd::RenameFile(db_path_.c_str(), tmp_path)) { LOG(WARNING) << "Partition: " << partition_name_ - << ", Failed to rename db path when change db, error: " << strerror(errno); + << ", Failed to rename db path when change db, error: " << strerror(errno); return false; } if (0 != pstd::RenameFile(new_path.c_str(), db_path_.c_str())) { LOG(WARNING) << "Partition: " << partition_name_ - << ", Failed to rename new db path when change db, error: " << strerror(errno); + << ", Failed to rename new db path when change db, error: " << strerror(errno); return false; } @@ -350,13 +313,12 @@ void Partition::DoBgSave(void* arg) { out.open(info.path + "/" + kBgsaveInfoFile, std::ios::in | std::ios::trunc); if (out.is_open()) { out << (time(NULL) - info.start_time) << "s\n" - << g_pika_server->host() << "\n" - << g_pika_server->port() << "\n" - << info.offset.b_offset.filenum << "\n" - << info.offset.b_offset.offset << "\n"; + << g_pika_server->host() << "\n" + << g_pika_server->port() << "\n" + << info.offset.b_offset.filenum << "\n" + << info.offset.b_offset.offset << "\n"; if (g_pika_conf->consensus_level() != 0) { - out << info.offset.l_offset.term << "\n" - << info.offset.l_offset.index << "\n"; + out << info.offset.l_offset.term << "\n" << info.offset.l_offset.index << "\n"; } out.close(); } @@ -378,9 +340,8 @@ bool Partition::RunBgsaveEngine() { LOG(INFO) << partition_name_ << " after prepare bgsave"; BgSaveInfo info = bgsave_info(); - LOG(INFO) << partition_name_ << " bgsave_info: path=" << info.path - << ", filenum=" << info.offset.b_offset.filenum - << ", offset=" << info.offset.b_offset.offset; + LOG(INFO) << partition_name_ << " bgsave_info: path=" << info.path << ", filenum=" << info.offset.b_offset.filenum + << ", offset=" << info.offset.b_offset.offset; // Backup to tmp dir rocksdb::Status s = bgsave_engine_->CreateNewBackup(info.path); @@ -426,7 +387,8 @@ bool Partition::InitBgsaveEngine() { return false; } - std::shared_ptr partition = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name_, partition_id_)); + std::shared_ptr partition = + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name_, partition_id_)); if (!partition) { LOG(WARNING) << partition_name_ << " not found"; return false; @@ -523,7 +485,7 @@ void Partition::InitKeyScan() { char s_time[32]; int len = strftime(s_time, sizeof(s_time), "%Y-%m-%d %H:%M:%S", localtime(&key_scan_info_.start_time)); key_scan_info_.s_start_time.assign(s_time, len); - key_scan_info_.duration = -1; // duration -1 mean the task in processing + key_scan_info_.duration = -1; // duration -1 mean the task in processing } KeyScanInfo Partition::GetKeyScanInfo() { @@ -539,8 +501,8 @@ Status Partition::GetKeyNum(std::vector* key_info) { } InitKeyScan(); key_scan_info_.key_scaning_ = true; - key_scan_info_.duration = -2; // duration -2 mean the task in waiting status, - // has not been scheduled for exec + key_scan_info_.duration = -2; // duration -2 mean the task in waiting status, + // has not been scheduled for exec rocksdb::Status s = db_->GetKeyNum(key_info); key_scan_info_.key_scaning_ = false; if (!s.ok()) { diff --git a/src/pika_pubsub.cc b/src/pika_pubsub.cc index 5d6e207ac7..9812131de5 100644 --- a/src/pika_pubsub.cc +++ b/src/pika_pubsub.cc @@ -7,26 +7,28 @@ #include "include/pika_server.h" -extern PikaServer *g_pika_server; +extern PikaServer* g_pika_server; - -static std::string ConstructPubSubResp( - const std::string& cmd, - const std::vector>& result) { +static std::string ConstructPubSubResp(const std::string& cmd, const std::vector>& result) { std::stringstream resp; if (result.size() == 0) { - resp << "*3\r\n" << "$" << cmd.length() << "\r\n" << cmd << "\r\n" << - "$" << -1 << "\r\n" << ":" << 0 << "\r\n"; + resp << "*3\r\n" + << "$" << cmd.length() << "\r\n" + << cmd << "\r\n" + << "$" << -1 << "\r\n" + << ":" << 0 << "\r\n"; } for (auto it = result.begin(); it != result.end(); it++) { - resp << "*3\r\n" << "$" << cmd.length() << "\r\n" << cmd << "\r\n" << - "$" << it->first.length() << "\r\n" << it->first << "\r\n" << - ":" << it->second << "\r\n"; + resp << "*3\r\n" + << "$" << cmd.length() << "\r\n" + << cmd << "\r\n" + << "$" << it->first.length() << "\r\n" + << it->first << "\r\n" + << ":" << it->second << "\r\n"; } return resp.str(); } - void PublishCmd::DoInitial() { if (!CheckArg(argv_.size())) { res_.SetRes(CmdRes::kWrongNum, kCmdNamePublish); @@ -53,11 +55,11 @@ void SubscribeCmd::Do(std::shared_ptr partition) { std::shared_ptr conn = GetConn(); if (!conn) { res_.SetRes(CmdRes::kErrOther, kCmdNameSubscribe); - LOG(WARNING) << name_ << " weak ptr is empty"; + LOG(WARNING) << name_ << " weak ptr is empty"; return; } std::shared_ptr cli_conn = std::dynamic_pointer_cast(conn); - std::vector channels; + std::vector channels; for (size_t i = 1; i < argv_.size(); i++) { channels.push_back(argv_[i]); } @@ -65,12 +67,12 @@ void SubscribeCmd::Do(std::shared_ptr partition) { cli_conn->server_thread()->MoveConnOut(conn->fd()); cli_conn->SetIsPubSub(true); cli_conn->SetHandleType(net::HandleType::kSynchronous); - cli_conn->SetWriteCompleteCallback([cli_conn](){ - if (!cli_conn->IsPubSub()) { - return; - } - cli_conn->set_is_writable(true); - g_pika_server->EnablePublish(cli_conn->fd()); + cli_conn->SetWriteCompleteCallback([cli_conn]() { + if (!cli_conn->IsPubSub()) { + return; + } + cli_conn->set_is_writable(true); + g_pika_server->EnablePublish(cli_conn->fd()); }); } std::vector> result; @@ -86,7 +88,7 @@ void UnSubscribeCmd::DoInitial() { } void UnSubscribeCmd::Do(std::shared_ptr partition) { - std::vector channels; + std::vector channels; for (size_t i = 1; i < argv_.size(); i++) { channels.push_back(argv_[i]); } @@ -94,7 +96,7 @@ void UnSubscribeCmd::Do(std::shared_ptr partition) { std::shared_ptr conn = GetConn(); if (!conn) { res_.SetRes(CmdRes::kErrOther, kCmdNameUnSubscribe); - LOG(WARNING) << name_ << " weak ptr is empty"; + LOG(WARNING) << name_ << " weak ptr is empty"; return; } std::shared_ptr cli_conn = std::dynamic_pointer_cast(conn); @@ -107,13 +109,13 @@ void UnSubscribeCmd::Do(std::shared_ptr partition) { * the client will exit the Pub/Sub state */ cli_conn->SetIsPubSub(false); - cli_conn->SetWriteCompleteCallback([cli_conn, conn](){ - if (cli_conn->IsPubSub()) { - return; - } - cli_conn->set_is_writable(false); - cli_conn->SetHandleType(net::HandleType::kAsynchronous); - cli_conn->server_thread()->MoveConnIn(conn, net::NotifyType::kNotiWait); + cli_conn->SetWriteCompleteCallback([cli_conn, conn]() { + if (cli_conn->IsPubSub()) { + return; + } + cli_conn->set_is_writable(false); + cli_conn->SetHandleType(net::HandleType::kAsynchronous); + cli_conn->server_thread()->MoveConnIn(conn, net::NotifyType::kNotiWait); }); } return res_.SetRes(CmdRes::kNone, ConstructPubSubResp(name_, result)); @@ -130,7 +132,7 @@ void PSubscribeCmd::Do(std::shared_ptr partition) { std::shared_ptr conn = GetConn(); if (!conn) { res_.SetRes(CmdRes::kErrOther, kCmdNamePSubscribe); - LOG(WARNING) << name_ << " weak ptr is empty"; + LOG(WARNING) << name_ << " weak ptr is empty"; return; } std::shared_ptr cli_conn = std::dynamic_pointer_cast(conn); @@ -138,15 +140,15 @@ void PSubscribeCmd::Do(std::shared_ptr partition) { cli_conn->server_thread()->MoveConnOut(conn->fd()); cli_conn->SetIsPubSub(true); cli_conn->SetHandleType(net::HandleType::kSynchronous); - cli_conn->SetWriteCompleteCallback([cli_conn](){ - if (!cli_conn->IsPubSub()) { - return; - } - cli_conn->set_is_writable(true); - g_pika_server->EnablePublish(cli_conn->fd()); + cli_conn->SetWriteCompleteCallback([cli_conn]() { + if (!cli_conn->IsPubSub()) { + return; + } + cli_conn->set_is_writable(true); + g_pika_server->EnablePublish(cli_conn->fd()); }); } - std::vector channels; + std::vector channels; for (size_t i = 1; i < argv_.size(); i++) { channels.push_back(argv_[i]); } @@ -163,7 +165,7 @@ void PUnSubscribeCmd::DoInitial() { } void PUnSubscribeCmd::Do(std::shared_ptr partition) { - std::vector channels; + std::vector channels; for (size_t i = 1; i < argv_.size(); i++) { channels.push_back(argv_[i]); } @@ -171,7 +173,7 @@ void PUnSubscribeCmd::Do(std::shared_ptr partition) { std::shared_ptr conn = GetConn(); if (!conn) { res_.SetRes(CmdRes::kErrOther, kCmdNamePUnSubscribe); - LOG(WARNING) << name_ << " weak ptr is empty"; + LOG(WARNING) << name_ << " weak ptr is empty"; return; } std::shared_ptr cli_conn = std::dynamic_pointer_cast(conn); @@ -184,13 +186,13 @@ void PUnSubscribeCmd::Do(std::shared_ptr partition) { * the client will exit the Pub/Sub state */ cli_conn->SetIsPubSub(false); - cli_conn->SetWriteCompleteCallback([cli_conn, conn](){ - if (cli_conn->IsPubSub()) { - return; - } - cli_conn->set_is_writable(false); - cli_conn->SetHandleType(net::HandleType::kAsynchronous); - cli_conn->server_thread()->MoveConnIn(conn, net::NotifyType::kNotiWait); + cli_conn->SetWriteCompleteCallback([cli_conn, conn]() { + if (cli_conn->IsPubSub()) { + return; + } + cli_conn->set_is_writable(false); + cli_conn->SetHandleType(net::HandleType::kAsynchronous); + cli_conn->server_thread()->MoveConnIn(conn, net::NotifyType::kNotiWait); }); } return res_.SetRes(CmdRes::kNone, ConstructPubSubResp(name_, result)); @@ -202,24 +204,24 @@ void PubSubCmd::DoInitial() { return; } subcommand_ = argv_[1]; - if (strcasecmp(subcommand_.data(), "channels") - && strcasecmp(subcommand_.data(), "numsub") - && strcasecmp(subcommand_.data(), "numpat")) { + if (strcasecmp(subcommand_.data(), "channels") && strcasecmp(subcommand_.data(), "numsub") && + strcasecmp(subcommand_.data(), "numpat")) { res_.SetRes(CmdRes::kErrOther, "Unknown PUBSUB subcommand or wrong number of arguments for '" + subcommand_ + "'"); } for (size_t i = 2; i < argv_.size(); i++) { - arguments_.push_back(argv_[i]); + arguments_.push_back(argv_[i]); } } void PubSubCmd::Do(std::shared_ptr partition) { if (!strcasecmp(subcommand_.data(), "channels")) { std::string pattern = ""; - std::vector result; + std::vector result; if (arguments_.size() == 1) { pattern = arguments_[0]; } else if (arguments_.size() > 1) { - res_.SetRes(CmdRes::kErrOther, "Unknown PUBSUB subcommand or wrong number of arguments for '" + subcommand_ + "'"); + res_.SetRes(CmdRes::kErrOther, + "Unknown PUBSUB subcommand or wrong number of arguments for '" + subcommand_ + "'"); return; } g_pika_server->PubSubChannels(pattern, &result); @@ -235,7 +237,7 @@ void PubSubCmd::Do(std::shared_ptr partition) { res_.AppendArrayLen(result.size() * 2); for (auto it = result.begin(); it != result.end(); ++it) { res_.AppendStringLen(it->first.length()); - res_.AppendContent(it->first); + res_.AppendContent(it->first); res_.AppendInteger(it->second); } return; @@ -245,4 +247,3 @@ void PubSubCmd::Do(std::shared_ptr partition) { } return; } - diff --git a/src/pika_repl_bgworker.cc b/src/pika_repl_bgworker.cc index c893153a3c..76a1b82d2b 100644 --- a/src/pika_repl_bgworker.cc +++ b/src/pika_repl_bgworker.cc @@ -7,18 +7,17 @@ #include -#include "include/pika_rm.h" +#include "include/pika_cmd_table_manager.h" #include "include/pika_conf.h" +#include "include/pika_rm.h" #include "include/pika_server.h" -#include "include/pika_cmd_table_manager.h" extern PikaConf* g_pika_conf; extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; extern PikaCmdTableManager* g_pika_cmd_table_manager; -PikaReplBgWorker::PikaReplBgWorker(int queue_size) - : bg_thread_(queue_size) { +PikaReplBgWorker::PikaReplBgWorker(int queue_size) : bg_thread_(queue_size) { bg_thread_.set_thread_name("ReplBgWorker"); net::RedisParserSettings settings; settings.DealMessage = &(PikaReplBgWorker::HandleWriteBinlog); @@ -28,25 +27,15 @@ PikaReplBgWorker::PikaReplBgWorker(int queue_size) partition_id_ = 0; } -int PikaReplBgWorker::StartThread() { - return bg_thread_.StartThread(); -} +int PikaReplBgWorker::StartThread() { return bg_thread_.StartThread(); } -int PikaReplBgWorker::StopThread() { - return bg_thread_.StopThread(); -} +int PikaReplBgWorker::StopThread() { return bg_thread_.StopThread(); } -void PikaReplBgWorker::Schedule(net::TaskFunc func, void* arg) { - bg_thread_.Schedule(func, arg); -} +void PikaReplBgWorker::Schedule(net::TaskFunc func, void* arg) { bg_thread_.Schedule(func, arg); } -void PikaReplBgWorker::QueueClear() { - bg_thread_.QueueClear(); -} +void PikaReplBgWorker::QueueClear() { bg_thread_.QueueClear(); } -void PikaReplBgWorker::ParseBinlogOffset( - const InnerMessage::BinlogOffset pb_offset, - LogOffset* offset) { +void PikaReplBgWorker::ParseBinlogOffset(const InnerMessage::BinlogOffset pb_offset, LogOffset* offset) { offset->b_offset.filenum = pb_offset.filenum(); offset->b_offset.offset = pb_offset.offset(); offset->l_offset.term = pb_offset.term(); @@ -57,7 +46,7 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { ReplClientWriteBinlogTaskArg* task_arg = static_cast(arg); const std::shared_ptr res = task_arg->res; std::shared_ptr conn = task_arg->conn; - std::vector* index = static_cast* >(task_arg->res_private_data); + std::vector* index = static_cast*>(task_arg->res_private_data); PikaReplBgWorker* worker = task_arg->worker; worker->ip_port_ = conn->ip_port(); @@ -100,13 +89,12 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { } // table_name and partition_id in the vector are same in the bgworker, - // because DispatchBinlogRes() have been order them. + // because DispatchBinlogRes() have been order them. worker->table_name_ = table_name; worker->partition_id_ = partition_id; std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName( - PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!partition) { LOG(WARNING) << "Partition " << table_name << "_" << partition_id << " Not Found"; delete index; @@ -115,8 +103,7 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { } std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncSlavePartitionByName(PartitionInfo(table_name, partition_id)); if (!slave_partition) { LOG(WARNING) << "Slave Partition " << table_name << "_" << partition_id << " Not Found"; delete index; @@ -127,12 +114,12 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { if (res->has_consensus_meta()) { const InnerMessage::ConsensusMeta& meta = res->consensus_meta(); if (meta.term() > partition->ConsensusTerm()) { - LOG(INFO) << "Update " << table_name << "_" << partition_id << " term from " - << partition->ConsensusTerm() << " to " << meta.term(); + LOG(INFO) << "Update " << table_name << "_" << partition_id << " term from " << partition->ConsensusTerm() + << " to " << meta.term(); partition->ConsensusUpdateTerm(meta.term()); - } else if (meta.term() < partition->ConsensusTerm()) /*outdated pb*/{ + } else if (meta.term() < partition->ConsensusTerm()) /*outdated pb*/ { LOG(WARNING) << "Drop outdated binlog sync response " << table_name << "_" << partition_id - << " recv term: " << meta.term() << " local term: " << partition->ConsensusTerm(); + << " recv term: " << meta.term() << " local term: " << partition->ConsensusTerm(); delete index; delete task_arg; return; @@ -142,10 +129,9 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { LogOffset prev_offset; ParseBinlogOffset(res->consensus_meta().log_offset(), &prev_offset); if (last_offset.l_offset.index != 0 && - (last_offset.l_offset != prev_offset.l_offset - || last_offset.b_offset != prev_offset.b_offset)) { - LOG(WARNING) << "last_offset " << last_offset.ToString() << - " NOT equal to pb prev_offset " << prev_offset.ToString(); + (last_offset.l_offset != prev_offset.l_offset || last_offset.b_offset != prev_offset.b_offset)) { + LOG(WARNING) << "last_offset " << last_offset.ToString() << " NOT equal to pb prev_offset " + << prev_offset.ToString(); slave_partition->SetReplState(ReplState::kTryConnect); delete index; delete task_arg; @@ -158,23 +144,20 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { const InnerMessage::InnerResponse::BinlogSync& binlog_res = res->binlog_sync((*index)[i]); // if pika are not current a slave or partition not in // BinlogSync state, we drop remain write binlog task - if ((g_pika_conf->classic_mode() && !(g_pika_server->role() & PIKA_ROLE_SLAVE)) - || ((slave_partition->State() != ReplState::kConnected) - && (slave_partition->State() != ReplState::kWaitDBSync))) { + if ((g_pika_conf->classic_mode() && !(g_pika_server->role() & PIKA_ROLE_SLAVE)) || + ((slave_partition->State() != ReplState::kConnected) && (slave_partition->State() != ReplState::kWaitDBSync))) { delete index; delete task_arg; return; } if (slave_partition->MasterSessionId() != binlog_res.session_id()) { - LOG(WARNING)<< "Check SessionId Mismatch: " << slave_partition->MasterIp() - << ":" << slave_partition->MasterPort() << ", " - << slave_partition->SyncPartitionInfo().ToString() - << " expected_session: " << binlog_res.session_id() << ", actual_session:" - << slave_partition->MasterSessionId(); - LOG(WARNING) << "Check Session failed " - << binlog_res.partition().table_name() - << "_" << binlog_res.partition().partition_id(); + LOG(WARNING) << "Check SessionId Mismatch: " << slave_partition->MasterIp() << ":" + << slave_partition->MasterPort() << ", " << slave_partition->SyncPartitionInfo().ToString() + << " expected_session: " << binlog_res.session_id() + << ", actual_session:" << slave_partition->MasterSessionId(); + LOG(WARNING) << "Check Session failed " << binlog_res.partition().table_name() << "_" + << binlog_res.partition().partition_id(); slave_partition->SetReplState(ReplState::kTryConnect); delete index; delete task_arg; @@ -195,8 +178,8 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { const char* redis_parser_start = binlog_res.binlog().data() + BINLOG_ENCODE_LEN; int redis_parser_len = static_cast(binlog_res.binlog().size()) - BINLOG_ENCODE_LEN; int processed_len = 0; - net::RedisParserStatus ret = worker->redis_parser_.ProcessInputBuffer( - redis_parser_start, redis_parser_len, &processed_len); + net::RedisParserStatus ret = + worker->redis_parser_.ProcessInputBuffer(redis_parser_start, redis_parser_len, &processed_len); if (ret != net::kRedisParserDone) { LOG(WARNING) << "Redis parser failed"; slave_partition->SetReplState(ReplState::kTryConnect); @@ -223,7 +206,7 @@ void PikaReplBgWorker::HandleBGWorkerWriteBinlog(void* arg) { // Reply Ack to master immediately std::shared_ptr logger = partition->Logger(); logger->GetProducerStatus(&productor_status.b_offset.filenum, &productor_status.b_offset.offset, - &productor_status.l_offset.term, &productor_status.l_offset.index); + &productor_status.l_offset.term, &productor_status.l_offset.index); ack_end = productor_status; ack_end.l_offset.term = pb_end.l_offset.term; } @@ -238,10 +221,9 @@ int PikaReplBgWorker::HandleWriteBinlog(net::RedisParser* parser, const net::Red // Monitor related std::string monitor_message; if (g_pika_server->HasMonitorClients()) { - std::string table_name = g_pika_conf->classic_mode() - ? worker->table_name_.substr(2) : worker->table_name_; - std::string monitor_message = std::to_string(1.0 * pstd::NowMicros() / 1000000) - + " [" + table_name + " " + worker->ip_port_ + "]"; + std::string table_name = g_pika_conf->classic_mode() ? worker->table_name_.substr(2) : worker->table_name_; + std::string monitor_message = + std::to_string(1.0 * pstd::NowMicros() / 1000000) + " [" + table_name + " " + worker->ip_port_ + "]"; for (const auto& item : argv) { monitor_message += " " + pstd::ToRead(item); } @@ -262,8 +244,8 @@ int PikaReplBgWorker::HandleWriteBinlog(net::RedisParser* parser, const net::Red g_pika_server->UpdateQueryNumAndExecCountTable(worker->table_name_, opt, c_ptr->is_write()); - std::shared_ptr partition - = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(worker->table_name_, worker->partition_id_)); + std::shared_ptr partition = + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(worker->table_name_, worker->partition_id_)); if (!partition) { LOG(WARNING) << worker->table_name_ << worker->partition_id_ << "Not found."; } @@ -311,7 +293,7 @@ void PikaReplBgWorker::HandleBGWorkerWriteDB(void* arg) { if (g_pika_conf->consensus_level() != 0) { std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (partition == nullptr) { LOG(WARNING) << "Sync Master Partition not exist " << table_name << partition_id; return; diff --git a/src/pika_repl_client.cc b/src/pika_repl_client.cc index d21e84c10b..06954d3943 100644 --- a/src/pika_repl_client.cc +++ b/src/pika_repl_client.cc @@ -5,14 +5,14 @@ #include "include/pika_repl_client.h" -#include -#include #include +#include +#include #include "net/include/net_cli.h" #include "net/include/redis_cli.h" -#include "pstd/include/pstd_coding.h" #include "pstd/include/env.h" +#include "pstd/include/pstd_coding.h" #include "pstd/include/pstd_string.h" #include "include/pika_rm.h" @@ -41,13 +41,14 @@ PikaReplClient::~PikaReplClient() { int PikaReplClient::Start() { int res = client_thread_->StartThread(); if (res != net::kSuccess) { - LOG(FATAL) << "Start ReplClient ClientThread Error: " << res << (res == net::kCreateThreadError ? ": create thread error " : ": other error"); + LOG(FATAL) << "Start ReplClient ClientThread Error: " << res + << (res == net::kCreateThreadError ? ": create thread error " : ": other error"); } for (size_t i = 0; i < bg_workers_.size(); ++i) { res = bg_workers_[i]->StartThread(); if (res != net::kSuccess) { LOG(FATAL) << "Start Pika Repl Worker Thread Error: " << res - << (res == net::kCreateThreadError ? ": create thread error " : ": other error"); + << (res == net::kCreateThreadError ? ": create thread error " : ": other error"); } } return res; @@ -67,21 +68,20 @@ void PikaReplClient::Schedule(net::TaskFunc func, void* arg) { } void PikaReplClient::ScheduleWriteBinlogTask(std::string table_partition, - const std::shared_ptr res, - std::shared_ptr conn, void* res_private_data) { + const std::shared_ptr res, + std::shared_ptr conn, void* res_private_data) { size_t index = GetHashIndex(table_partition, true); ReplClientWriteBinlogTaskArg* task_arg = - new ReplClientWriteBinlogTaskArg(res, conn, res_private_data, bg_workers_[index]); + new ReplClientWriteBinlogTaskArg(res, conn, res_private_data, bg_workers_[index]); bg_workers_[index]->Schedule(&PikaReplBgWorker::HandleBGWorkerWriteBinlog, static_cast(task_arg)); } -void PikaReplClient::ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, - const LogOffset& offset, const std::string& table_name, uint32_t partition_id) { +void PikaReplClient::ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, const LogOffset& offset, + const std::string& table_name, uint32_t partition_id) { const PikaCmdArgsType& argv = cmd_ptr->argv(); std::string dispatch_key = argv.size() >= 2 ? argv[1] : argv[0]; size_t index = GetHashIndex(dispatch_key, false); - ReplClientWriteDBTaskArg* task_arg = - new ReplClientWriteDBTaskArg(cmd_ptr, offset, table_name, partition_id); + ReplClientWriteDBTaskArg* task_arg = new ReplClientWriteDBTaskArg(cmd_ptr, offset, table_name, partition_id); bg_workers_[index]->Schedule(&PikaReplBgWorker::HandleBGWorkerWriteDB, static_cast(task_arg)); } @@ -94,10 +94,7 @@ Status PikaReplClient::Write(const std::string& ip, const int port, const std::s return client_thread_->Write(ip, port, msg); } -Status PikaReplClient::Close(const std::string& ip, const int port) { - return client_thread_->Close(ip, port); -} - +Status PikaReplClient::Close(const std::string& ip, const int port) { return client_thread_->Close(ip, port); } Status PikaReplClient::SendMetaSync() { std::string local_ip; @@ -106,14 +103,14 @@ Status PikaReplClient::SendMetaSync() { if ((cli->Connect(g_pika_server->master_ip(), g_pika_server->master_port(), "")).ok()) { struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); - getsockname(cli->fd(), (struct sockaddr*) &laddr, &llen); + getsockname(cli->fd(), (struct sockaddr*)&laddr, &llen); std::string tmp_local_ip(inet_ntoa(laddr.sin_addr)); local_ip = tmp_local_ip; cli->Close(); delete cli; } else { - LOG(WARNING) << "Failed to connect master, Master (" - << g_pika_server->master_ip() << ":" << g_pika_server->master_port() << "), try reconnect"; + LOG(WARNING) << "Failed to connect master, Master (" << g_pika_server->master_ip() << ":" + << g_pika_server->master_port() << "), try reconnect"; // Sleep three seconds to avoid frequent try Meta Sync // when the connection fails sleep(3); @@ -138,21 +135,16 @@ Status PikaReplClient::SendMetaSync() { std::string master_ip = g_pika_server->master_ip(); int master_port = g_pika_server->master_port(); if (!request.SerializeToString(&to_send)) { - LOG(WARNING) << "Serialize Meta Sync Request Failed, to Master (" - << master_ip << ":" << master_port << ")"; + LOG(WARNING) << "Serialize Meta Sync Request Failed, to Master (" << master_ip << ":" << master_port << ")"; return Status::Corruption("Serialize Failed"); } - LOG(INFO) << "Try Send Meta Sync Request to Master (" - << master_ip << ":" << master_port << ")"; + LOG(INFO) << "Try Send Meta Sync Request to Master (" << master_ip << ":" << master_port << ")"; return client_thread_->Write(master_ip, master_port + kPortShiftReplServer, to_send); } -Status PikaReplClient::SendPartitionDBSync(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, - const BinlogOffset& boffset, +Status PikaReplClient::SendPartitionDBSync(const std::string& ip, uint32_t port, const std::string& table_name, + uint32_t partition_id, const BinlogOffset& boffset, const std::string& local_ip) { InnerMessage::InnerRequest request; request.set_type(InnerMessage::kDBSync); @@ -170,19 +162,14 @@ Status PikaReplClient::SendPartitionDBSync(const std::string& ip, std::string to_send; if (!request.SerializeToString(&to_send)) { - LOG(WARNING) << "Serialize Partition DBSync Request Failed, to Master (" - << ip << ":" << port << ")"; + LOG(WARNING) << "Serialize Partition DBSync Request Failed, to Master (" << ip << ":" << port << ")"; return Status::Corruption("Serialize Failed"); } return client_thread_->Write(ip, port + kPortShiftReplServer, to_send); } - -Status PikaReplClient::SendPartitionTrySync(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, - const BinlogOffset& boffset, +Status PikaReplClient::SendPartitionTrySync(const std::string& ip, uint32_t port, const std::string& table_name, + uint32_t partition_id, const BinlogOffset& boffset, const std::string& local_ip) { InnerMessage::InnerRequest request; request.set_type(InnerMessage::kTrySync); @@ -200,13 +187,14 @@ Status PikaReplClient::SendPartitionTrySync(const std::string& ip, if (g_pika_conf->consensus_level() != 0) { std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!partition) { return Status::Corruption("partition not found"); } LogOffset last_index = partition->ConsensusLastIndex(); uint32_t term = partition->ConsensusTerm(); - LOG(INFO) << PartitionInfo(table_name, partition_id).ToString() << " TrySync Increase self term from " << term << " to " << term + 1; + LOG(INFO) << PartitionInfo(table_name, partition_id).ToString() << " TrySync Increase self term from " << term + << " to " << term + 1; term++; partition->ConsensusUpdateTerm(term); InnerMessage::ConsensusMeta* consensus_meta = request.mutable_consensus_meta(); @@ -220,20 +208,15 @@ Status PikaReplClient::SendPartitionTrySync(const std::string& ip, std::string to_send; if (!request.SerializeToString(&to_send)) { - LOG(WARNING) << "Serialize Partition TrySync Request Failed, to Master (" - << ip << ":" << port << ")"; + LOG(WARNING) << "Serialize Partition TrySync Request Failed, to Master (" << ip << ":" << port << ")"; return Status::Corruption("Serialize Failed"); } return client_thread_->Write(ip, port + kPortShiftReplServer, to_send); } -Status PikaReplClient::SendPartitionBinlogSync(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, - const LogOffset& ack_start, - const LogOffset& ack_end, - const std::string& local_ip, +Status PikaReplClient::SendPartitionBinlogSync(const std::string& ip, uint32_t port, const std::string& table_name, + uint32_t partition_id, const LogOffset& ack_start, + const LogOffset& ack_end, const std::string& local_ip, bool is_first_send) { InnerMessage::InnerRequest request; request.set_type(InnerMessage::kBinlogSync); @@ -258,8 +241,7 @@ Status PikaReplClient::SendPartitionBinlogSync(const std::string& ip, ack_range_end->set_index(ack_end.l_offset.index); std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncSlavePartitionByName(PartitionInfo(table_name, partition_id)); if (!slave_partition) { LOG(WARNING) << "Slave Partition: " << table_name << "_" << partition_id << " not exist"; return Status::NotFound("SyncSlavePartition NotFound"); @@ -269,22 +251,17 @@ Status PikaReplClient::SendPartitionBinlogSync(const std::string& ip, std::string to_send; if (!request.SerializeToString(&to_send)) { - LOG(WARNING) << "Serialize Partition BinlogSync Request Failed, to Master (" - << ip << ":" << port << ")"; + LOG(WARNING) << "Serialize Partition BinlogSync Request Failed, to Master (" << ip << ":" << port << ")"; return Status::Corruption("Serialize Failed"); } return client_thread_->Write(ip, port + kPortShiftReplServer, to_send); } -Status PikaReplClient::SendRemoveSlaveNode(const std::string& ip, - uint32_t port, - const std::string& table_name, - uint32_t partition_id, - const std::string& local_ip) { +Status PikaReplClient::SendRemoveSlaveNode(const std::string& ip, uint32_t port, const std::string& table_name, + uint32_t partition_id, const std::string& local_ip) { InnerMessage::InnerRequest request; request.set_type(InnerMessage::kRemoveSlaveNode); - InnerMessage::InnerRequest::RemoveSlaveNode* remove_slave_node = - request.add_remove_slave_node(); + InnerMessage::InnerRequest::RemoveSlaveNode* remove_slave_node = request.add_remove_slave_node(); InnerMessage::Node* node = remove_slave_node->mutable_node(); node->set_ip(local_ip); node->set_port(g_pika_server->port()); @@ -295,8 +272,8 @@ Status PikaReplClient::SendRemoveSlaveNode(const std::string& ip, std::string to_send; if (!request.SerializeToString(&to_send)) { - LOG(WARNING) << "Serialize Remove Slave Node Failed, to Master (" - << ip << ":" << port << "), " << table_name << "_" << partition_id; + LOG(WARNING) << "Serialize Remove Slave Node Failed, to Master (" << ip << ":" << port << "), " << table_name << "_" + << partition_id; return Status::Corruption("Serialize Failed"); } return client_thread_->Write(ip, port + kPortShiftReplServer, to_send); diff --git a/src/pika_repl_client_conn.cc b/src/pika_repl_client_conn.cc index e9345167ef..e725420369 100644 --- a/src/pika_repl_client_conn.cc +++ b/src/pika_repl_client_conn.cc @@ -5,38 +5,34 @@ #include "include/pika_repl_client_conn.h" -#include +#include #include -#include +#include -#include "include/pika_server.h" #include "include/pika_rm.h" +#include "include/pika_server.h" #include "pstd/include/pstd_string.h" #include "include/pika_rm.h" #include "include/pika_server.h" +#include "pika_inner_message.pb.h" + extern PikaConf* g_pika_conf; extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; -PikaReplClientConn::PikaReplClientConn(int fd, - const std::string& ip_port, - net::Thread* thread, - void* worker_specific_data, - net::NetMultiplexer* mpx) - : net::PbConn(fd, ip_port, thread, mpx) { -} +PikaReplClientConn::PikaReplClientConn(int fd, const std::string& ip_port, net::Thread* thread, + void* worker_specific_data, net::NetMultiplexer* mpx) + : net::PbConn(fd, ip_port, thread, mpx) {} -bool PikaReplClientConn::IsTableStructConsistent( - const std::vector& current_tables, - const std::vector& expect_tables) { +bool PikaReplClientConn::IsTableStructConsistent(const std::vector& current_tables, + const std::vector& expect_tables) { if (current_tables.size() != expect_tables.size()) { return false; } for (const auto& table_struct : current_tables) { - if (find(expect_tables.begin(), expect_tables.end(), - table_struct) == expect_tables.end()) { + if (find(expect_tables.begin(), expect_tables.end(), table_struct) == expect_tables.end()) { return false; } } @@ -44,44 +40,45 @@ bool PikaReplClientConn::IsTableStructConsistent( } int PikaReplClientConn::DealMessage() { - std::shared_ptr response = std::make_shared(); + std::shared_ptr response = std::make_shared(); ::google::protobuf::io::ArrayInputStream input(rbuf_ + cur_pos_ - header_len_, header_len_); ::google::protobuf::io::CodedInputStream decoder(&input); decoder.SetTotalBytesLimit(g_pika_conf->max_conn_rbuf_size()); bool success = response->ParseFromCodedStream(&decoder) && decoder.ConsumedEntireMessage(); if (!success) { - LOG(WARNING) << "ParseFromArray FAILED! " << " msg_len: " << header_len_; + LOG(WARNING) << "ParseFromArray FAILED! " + << " msg_len: " << header_len_; g_pika_server->SyncError(); return -1; } switch (response->type()) { - case InnerMessage::kMetaSync: - { - ReplClientTaskArg* task_arg = new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kMetaSync: { + ReplClientTaskArg* task_arg = + new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplClientBGTask(&PikaReplClientConn::HandleMetaSyncResponse, static_cast(task_arg)); break; } - case InnerMessage::kDBSync: - { - ReplClientTaskArg* task_arg = new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kDBSync: { + ReplClientTaskArg* task_arg = + new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplClientBGTask(&PikaReplClientConn::HandleDBSyncResponse, static_cast(task_arg)); break; } - case InnerMessage::kTrySync: - { - ReplClientTaskArg* task_arg = new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kTrySync: { + ReplClientTaskArg* task_arg = + new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplClientBGTask(&PikaReplClientConn::HandleTrySyncResponse, static_cast(task_arg)); break; } - case InnerMessage::kBinlogSync: - { + case InnerMessage::kBinlogSync: { DispatchBinlogRes(response); break; } - case InnerMessage::kRemoveSlaveNode: - { - ReplClientTaskArg* task_arg = new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); - g_pika_rm->ScheduleReplClientBGTask(&PikaReplClientConn::HandleRemoveSlaveNodeResponse, static_cast(task_arg)); + case InnerMessage::kRemoveSlaveNode: { + ReplClientTaskArg* task_arg = + new ReplClientTaskArg(response, std::dynamic_pointer_cast(shared_from_this())); + g_pika_rm->ScheduleReplClientBGTask(&PikaReplClientConn::HandleRemoveSlaveNodeResponse, + static_cast(task_arg)); break; } default: @@ -113,9 +110,9 @@ void PikaReplClientConn::HandleMetaSyncResponse(void* arg) { const InnerMessage::InnerResponse_MetaSync meta_sync = response->meta_sync(); if (g_pika_conf->classic_mode() != meta_sync.classic_mode()) { - LOG(WARNING) << "Self in " << (g_pika_conf->classic_mode() ? "classic" : "sharding") - << " mode, but master in " << (meta_sync.classic_mode() ? "classic" : "sharding") - << " mode, failed to establish master-slave relationship"; + LOG(WARNING) << "Self in " << (g_pika_conf->classic_mode() ? "classic" : "sharding") << " mode, but master in " + << (meta_sync.classic_mode() ? "classic" : "sharding") + << " mode, failed to establish master-slave relationship"; g_pika_server->SyncError(); conn->NotifyClose(); delete task_arg; @@ -125,15 +122,14 @@ void PikaReplClientConn::HandleMetaSyncResponse(void* arg) { std::vector master_table_structs; for (int idx = 0; idx < meta_sync.tables_info_size(); ++idx) { InnerMessage::InnerResponse_MetaSync_TableInfo table_info = meta_sync.tables_info(idx); - master_table_structs.push_back({table_info.table_name(), - static_cast(table_info.partition_num()), {0}}); + master_table_structs.push_back({table_info.table_name(), static_cast(table_info.partition_num()), {0}}); } std::vector self_table_structs = g_pika_conf->table_structs(); if (!PikaReplClientConn::IsTableStructConsistent(self_table_structs, master_table_structs)) { LOG(WARNING) << "Self table structs(number of databases: " << self_table_structs.size() - << ") inconsistent with master(number of databases: " << master_table_structs.size() - << "), failed to establish master-slave relationship"; + << ") inconsistent with master(number of databases: " << master_table_structs.size() + << "), failed to establish master-slave relationship"; g_pika_server->SyncError(); conn->NotifyClose(); delete task_arg; @@ -156,11 +152,10 @@ void PikaReplClientConn::HandleDBSyncResponse(void* arg) { int32_t session_id = db_sync_response.session_id(); const InnerMessage::Partition partition_response = db_sync_response.partition(); std::string table_name = partition_response.table_name(); - uint32_t partition_id = partition_response.partition_id(); + uint32_t partition_id = partition_response.partition_id(); std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncSlavePartitionByName(PartitionInfo(table_name, partition_id)); if (!slave_partition) { LOG(WARNING) << "Slave Partition: " << table_name << ":" << partition_id << " Not Found"; delete task_arg; @@ -198,9 +193,9 @@ void PikaReplClientConn::HandleTrySyncResponse(void* arg) { const InnerMessage::InnerResponse_TrySync& try_sync_response = response->try_sync(); const InnerMessage::Partition& partition_response = try_sync_response.partition(); std::string table_name = partition_response.table_name(); - uint32_t partition_id = partition_response.partition_id(); + uint32_t partition_id = partition_response.partition_id(); std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!partition) { LOG(WARNING) << "Partition: " << table_name << ":" << partition_id << " Not Found"; delete task_arg; @@ -208,8 +203,7 @@ void PikaReplClientConn::HandleTrySyncResponse(void* arg) { } std::shared_ptr slave_partition = - g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncSlavePartitionByName(PartitionInfo(table_name, partition_id)); if (!slave_partition) { LOG(WARNING) << "Slave Partition: " << table_name << ":" << partition_id << " Not Found"; delete task_arg; @@ -220,12 +214,12 @@ void PikaReplClientConn::HandleTrySyncResponse(void* arg) { if (response->has_consensus_meta()) { const InnerMessage::ConsensusMeta& meta = response->consensus_meta(); if (meta.term() > partition->ConsensusTerm()) { - LOG(INFO) << "Update " << table_name << ":" << partition_id - << " term from " << partition->ConsensusTerm() << " to " << meta.term(); + LOG(INFO) << "Update " << table_name << ":" << partition_id << " term from " << partition->ConsensusTerm() + << " to " << meta.term(); partition->ConsensusUpdateTerm(meta.term()); - } else if (meta.term() < partition->ConsensusTerm()) /*outdated pb*/{ + } else if (meta.term() < partition->ConsensusTerm()) /*outdated pb*/ { LOG(WARNING) << "Drop outdated trysync response " << table_name << ":" << partition_id - << " recv term: " << meta.term() << " local term: " << partition->ConsensusTerm(); + << " recv term: " << meta.term() << " local term: " << partition->ConsensusTerm(); delete task_arg; return; } @@ -255,10 +249,10 @@ void PikaReplClientConn::HandleTrySyncResponse(void* arg) { // after connected, update receive time first to avoid connection timeout slave_partition->SetLastRecvTime(pstd::NowMicros()); - LOG(INFO) << "Partition: " << partition_name << " TrySync Ok"; + LOG(INFO) << "Partition: " << partition_name << " TrySync Ok"; } else if (try_sync_response.reply_code() == InnerMessage::InnerResponse::TrySync::kSyncPointBePurged) { slave_partition->SetReplState(ReplState::kTryDBSync); - LOG(INFO) << "Partition: " << partition_name << " Need To Try DBSync"; + LOG(INFO) << "Partition: " << partition_name << " Need To Try DBSync"; } else if (try_sync_response.reply_code() == InnerMessage::InnerResponse::TrySync::kSyncPointLarger) { slave_partition->SetReplState(ReplState::kError); LOG(WARNING) << "Partition: " << partition_name << " TrySync Error, Because the invalid filenum and offset"; @@ -269,10 +263,9 @@ void PikaReplClientConn::HandleTrySyncResponse(void* arg) { delete task_arg; } -Status PikaReplClientConn::TrySyncConsensusCheck( - const InnerMessage::ConsensusMeta& consensus_meta, - const std::shared_ptr& partition, - const std::shared_ptr& slave_partition) { +Status PikaReplClientConn::TrySyncConsensusCheck(const InnerMessage::ConsensusMeta& consensus_meta, + const std::shared_ptr& partition, + const std::shared_ptr& slave_partition) { std::vector hints; for (int i = 0; i < consensus_meta.hint_size(); ++i) { InnerMessage::BinlogOffset pb_offset = consensus_meta.hint(i); @@ -293,15 +286,13 @@ Status PikaReplClientConn::TrySyncConsensusCheck( return s; } - void PikaReplClientConn::DispatchBinlogRes(const std::shared_ptr res) { // partition to a bunch of binlog chips std::unordered_map*, hash_partition_info> par_binlog; for (int i = 0; i < res->binlog_sync_size(); ++i) { const InnerMessage::InnerResponse::BinlogSync& binlog_res = res->binlog_sync(i); // hash key: table + partition_id - PartitionInfo p_info(binlog_res.partition().table_name(), - binlog_res.partition().partition_id()); + PartitionInfo p_info(binlog_res.partition().table_name(), binlog_res.partition().partition_id()); if (par_binlog.find(p_info) == par_binlog.end()) { par_binlog[p_info] = new std::vector(); } @@ -314,16 +305,14 @@ void PikaReplClientConn::DispatchBinlogRes(const std::shared_ptrGetSyncSlavePartitionByName( PartitionInfo(binlog_nums.first.table_name_, binlog_nums.first.partition_id_)); if (!slave_partition) { - LOG(WARNING) << "Slave Partition: " << binlog_nums.first.table_name_ << "_" - << binlog_nums.first.partition_id_ << " not exist"; + LOG(WARNING) << "Slave Partition: " << binlog_nums.first.table_name_ << "_" << binlog_nums.first.partition_id_ + << " not exist"; break; } slave_partition->SetLastRecvTime(pstd::NowMicros()); - g_pika_rm->ScheduleWriteBinlogTask( - binlog_nums.first.table_name_ + std::to_string(binlog_nums.first.partition_id_), - res, - std::dynamic_pointer_cast(shared_from_this()), - reinterpret_cast(binlog_nums.second)); + g_pika_rm->ScheduleWriteBinlogTask(binlog_nums.first.table_name_ + std::to_string(binlog_nums.first.partition_id_), + res, std::dynamic_pointer_cast(shared_from_this()), + reinterpret_cast(binlog_nums.second)); } } @@ -339,4 +328,3 @@ void PikaReplClientConn::HandleRemoveSlaveNodeResponse(void* arg) { } delete task_arg; } - diff --git a/src/pika_repl_client_thread.cc b/src/pika_repl_client_thread.cc index 67da19f82d..3ef2033051 100644 --- a/src/pika_repl_client_thread.cc +++ b/src/pika_repl_client_thread.cc @@ -5,17 +5,16 @@ #include "include/pika_repl_client_thread.h" -#include "include/pika_server.h" #include "include/pika_rm.h" +#include "include/pika_server.h" #include "pstd/include/pstd_string.h" extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; -PikaReplClientThread::PikaReplClientThread(int cron_interval, int keepalive_timeout) : - ClientThread(&conn_factory_, cron_interval, keepalive_timeout, &handle_, NULL) { -} +PikaReplClientThread::PikaReplClientThread(int cron_interval, int keepalive_timeout) + : ClientThread(&conn_factory_, cron_interval, keepalive_timeout, &handle_, NULL) {} void PikaReplClientThread::ReplClientHandle::FdClosedHandle(int fd, const std::string& ip_port) const { LOG(INFO) << "ReplClient Close conn, fd=" << fd << ", ip_port=" << ip_port; @@ -25,9 +24,8 @@ void PikaReplClientThread::ReplClientHandle::FdClosedHandle(int fd, const std::s LOG(WARNING) << "Parse ip_port error " << ip_port; return; } - if (ip == g_pika_server->master_ip() - && port == g_pika_server->master_port() + kPortShiftReplServer - && PIKA_REPL_ERROR != g_pika_server->repl_state()) { // if state machine in error state, no retry + if (ip == g_pika_server->master_ip() && port == g_pika_server->master_port() + kPortShiftReplServer && + PIKA_REPL_ERROR != g_pika_server->repl_state()) { // if state machine in error state, no retry LOG(WARNING) << "Master conn disconnect : " << ip_port << " try reconnect"; g_pika_server->ResetMetaSyncStatus(); } @@ -42,10 +40,9 @@ void PikaReplClientThread::ReplClientHandle::FdTimeoutHandle(int fd, const std:: LOG(WARNING) << "Parse ip_port error " << ip_port; return; } - if (ip == g_pika_server->master_ip() - && port == g_pika_server->master_port() + kPortShiftReplServer - && PIKA_REPL_ERROR != g_pika_server->repl_state() - && g_pika_rm->CheckSlavePartitionState(ip, port)) { // if state machine in error state, no retry + if (ip == g_pika_server->master_ip() && port == g_pika_server->master_port() + kPortShiftReplServer && + PIKA_REPL_ERROR != g_pika_server->repl_state() && + g_pika_rm->CheckSlavePartitionState(ip, port)) { // if state machine in error state, no retry LOG(WARNING) << "Master conn timeout : " << ip_port << " try reconnect"; g_pika_server->ResetMetaSyncStatus(); } diff --git a/src/pika_repl_server.cc b/src/pika_repl_server.cc index c87f482173..444adbcb3d 100644 --- a/src/pika_repl_server.cc +++ b/src/pika_repl_server.cc @@ -7,17 +7,15 @@ #include -#include "include/pika_rm.h" #include "include/pika_conf.h" +#include "include/pika_rm.h" #include "include/pika_server.h" extern PikaConf* g_pika_conf; extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; -PikaReplServer::PikaReplServer(const std::set& ips, - int port, - int cron_interval) { +PikaReplServer::PikaReplServer(const std::set& ips, int port, int cron_interval) { server_tp_ = new net::ThreadPool(PIKA_REPL_SERVER_TP_SIZE, 100000); pika_repl_server_thread_ = new PikaReplServerThread(ips, port, cron_interval); pika_repl_server_thread_->set_thread_name("PikaReplServer"); @@ -35,12 +33,15 @@ int PikaReplServer::Start() { int res = pika_repl_server_thread_->StartThread(); if (res != net::kSuccess) { LOG(FATAL) << "Start Pika Repl Server Thread Error: " << res - << (res == net::kBindError ? ": bind port " + std::to_string(pika_repl_server_thread_->ListenPort()) + " conflict" : ": create thread error ") - << ", Listen on this port to handle the request sent by the Slave"; + << (res == net::kBindError + ? ": bind port " + std::to_string(pika_repl_server_thread_->ListenPort()) + " conflict" + : ": create thread error ") + << ", Listen on this port to handle the request sent by the Slave"; } res = server_tp_->start_thread_pool(); if (res != net::kSuccess) { - LOG(FATAL) << "Start ThreadPool Error: " << res << (res == net::kCreateThreadError ? ": create thread error " : ": other error"); + LOG(FATAL) << "Start ThreadPool Error: " << res + << (res == net::kCreateThreadError ? ": create thread error " : ": other error"); } return res; } @@ -51,9 +52,8 @@ int PikaReplServer::Stop() { return 0; } -pstd::Status PikaReplServer::SendSlaveBinlogChips(const std::string& ip, - int port, - const std::vector& tasks) { +pstd::Status PikaReplServer::SendSlaveBinlogChips(const std::string& ip, int port, + const std::vector& tasks) { InnerMessage::InnerResponse response; BuildBinlogSyncResp(tasks, &response); @@ -81,21 +81,19 @@ pstd::Status PikaReplServer::SendSlaveBinlogChips(const std::string& ip, return Write(ip, port, binlog_chip_pb); } -void PikaReplServer::BuildBinlogOffset(const LogOffset& offset, - InnerMessage::BinlogOffset* boffset) { +void PikaReplServer::BuildBinlogOffset(const LogOffset& offset, InnerMessage::BinlogOffset* boffset) { boffset->set_filenum(offset.b_offset.filenum); boffset->set_offset(offset.b_offset.offset); boffset->set_term(offset.l_offset.term); boffset->set_index(offset.l_offset.index); } -void PikaReplServer::BuildBinlogSyncResp(const std::vector& tasks, - InnerMessage::InnerResponse* response) { +void PikaReplServer::BuildBinlogSyncResp(const std::vector& tasks, InnerMessage::InnerResponse* response) { response->set_code(InnerMessage::kOk); response->set_type(InnerMessage::Type::kBinlogSync); LogOffset prev_offset; bool founded = false; - for (const auto& task :tasks) { + for (const auto& task : tasks) { if (!task.binlog_chip_.binlog_.empty() && !founded) { // find the first not keepalive prev_offset prev_offset = task.prev_offset_; @@ -120,14 +118,12 @@ void PikaReplServer::BuildBinlogSyncResp(const std::vector& tasks, } // write consensus_meta - InnerMessage::ConsensusMeta* consensus_meta - = response->mutable_consensus_meta(); + InnerMessage::ConsensusMeta* consensus_meta = response->mutable_consensus_meta(); InnerMessage::BinlogOffset* last_log = consensus_meta->mutable_log_offset(); BuildBinlogOffset(prev_offset, last_log); // commit LogOffset committed_index; - std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(p_info); + std::shared_ptr partition = g_pika_rm->GetSyncMasterPartitionByName(p_info); if (!partition) { LOG(WARNING) << "SyncPartition " << p_info.ToString() << " Not Found."; return; @@ -139,17 +135,14 @@ void PikaReplServer::BuildBinlogSyncResp(const std::vector& tasks, } } -pstd::Status PikaReplServer::Write(const std::string& ip, - const int port, - const std::string& msg) { +pstd::Status PikaReplServer::Write(const std::string& ip, const int port, const std::string& msg) { pstd::RWLock l(&client_conn_rwlock_, false); const std::string ip_port = pstd::IpPortString(ip, port); if (client_conn_map_.find(ip_port) == client_conn_map_.end()) { return Status::NotFound("The " + ip_port + " fd cannot be found"); } int fd = client_conn_map_[ip_port]; - std::shared_ptr conn = - std::dynamic_pointer_cast(pika_repl_server_thread_->get_conn(fd)); + std::shared_ptr conn = std::dynamic_pointer_cast(pika_repl_server_thread_->get_conn(fd)); if (conn == nullptr) { return Status::NotFound("The" + ip_port + " conn cannot be found"); } @@ -162,9 +155,7 @@ pstd::Status PikaReplServer::Write(const std::string& ip, return Status::OK(); } -void PikaReplServer::Schedule(net::TaskFunc func, void* arg){ - server_tp_->Schedule(func, arg); -} +void PikaReplServer::Schedule(net::TaskFunc func, void* arg) { server_tp_->Schedule(func, arg); } void PikaReplServer::UpdateClientConnMap(const std::string& ip_port, int fd) { pstd::RWLock l(&client_conn_rwlock_, true); @@ -183,7 +174,4 @@ void PikaReplServer::RemoveClientConn(int fd) { } } -void PikaReplServer::KillAllConns() { - return pika_repl_server_thread_->KillAllConns(); -} - +void PikaReplServer::KillAllConns() { return pika_repl_server_thread_->KillAllConns(); } diff --git a/src/pika_repl_server_conn.cc b/src/pika_repl_server_conn.cc index 1c47a62ebc..a4044ff6da 100644 --- a/src/pika_repl_server_conn.cc +++ b/src/pika_repl_server_conn.cc @@ -13,15 +13,11 @@ extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; -PikaReplServerConn::PikaReplServerConn(int fd, - std::string ip_port, - net::Thread* thread, - void* worker_specific_data, net::NetMultiplexer* mpx) - : PbConn(fd, ip_port, thread, mpx) { -} +PikaReplServerConn::PikaReplServerConn(int fd, std::string ip_port, net::Thread* thread, void* worker_specific_data, + net::NetMultiplexer* mpx) + : PbConn(fd, ip_port, thread, mpx) {} -PikaReplServerConn::~PikaReplServerConn() { -} +PikaReplServerConn::~PikaReplServerConn() {} void PikaReplServerConn::HandleMetaSyncRequest(void* arg) { ReplServerTaskArg* task_arg = static_cast(arg); @@ -34,13 +30,11 @@ void PikaReplServerConn::HandleMetaSyncRequest(void* arg) { InnerMessage::InnerResponse response; response.set_type(InnerMessage::kMetaSync); - if (!g_pika_conf->requirepass().empty() - && g_pika_conf->requirepass() != masterauth) { + if (!g_pika_conf->requirepass().empty() && g_pika_conf->requirepass() != masterauth) { response.set_code(InnerMessage::kError); response.set_reply("Auth with master error, Invalid masterauth"); } else { - LOG(INFO) << "Receive MetaSync, Slave ip: " << node.ip() << ", Slave port:" - << node.port(); + LOG(INFO) << "Receive MetaSync, Slave ip: " << node.ip() << ", Slave port:" << node.port(); std::vector table_structs = g_pika_conf->table_structs(); bool success = g_pika_server->TryAddSlave(node.ip(), node.port(), conn->fd(), table_structs); const std::string ip_port = pstd::IpPortString(node.ip(), node.port()); @@ -62,8 +56,7 @@ void PikaReplServerConn::HandleMetaSyncRequest(void* arg) { } std::string reply_str; - if (!response.SerializeToString(&reply_str) - || conn->WriteResp(reply_str)) { + if (!response.SerializeToString(&reply_str) || conn->WriteResp(reply_str)) { LOG(WARNING) << "Process MetaSync request serialization failed"; conn->NotifyClose(); delete task_arg; @@ -96,36 +89,33 @@ void PikaReplServerConn::HandleTrySyncRequest(void* arg) { bool pre_success = true; response.set_type(InnerMessage::Type::kTrySync); std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!partition) { response.set_code(InnerMessage::kError); response.set_reply("Partition not found"); - LOG(WARNING) << "Table Name: " << table_name << " Partition ID: " - << partition_id << " Not Found, TrySync Error"; + LOG(WARNING) << "Table Name: " << table_name << " Partition ID: " << partition_id << " Not Found, TrySync Error"; pre_success = false; } else { partition_name = partition->PartitionName(); - LOG(INFO) << "Receive Trysync, Slave ip: " << node.ip() << ", Slave port:" - << node.port() << ", Partition: " << partition_name << ", filenum: " - << slave_boffset.filenum() << ", pro_offset: " << slave_boffset.offset(); + LOG(INFO) << "Receive Trysync, Slave ip: " << node.ip() << ", Slave port:" << node.port() + << ", Partition: " << partition_name << ", filenum: " << slave_boffset.filenum() + << ", pro_offset: " << slave_boffset.offset(); response.set_code(InnerMessage::kOk); } if (pre_success && req->has_consensus_meta()) { - if (partition->GetNumberOfSlaveNode() >= g_pika_conf->replication_num() - && !partition->CheckSlaveNodeExist(node.ip(), node.port())) { - LOG(WARNING) << "Current replication num: " - << partition->GetNumberOfSlaveNode() - << " hits configuration replication-num " - << g_pika_conf->replication_num() << " stop trysync."; + if (partition->GetNumberOfSlaveNode() >= g_pika_conf->replication_num() && + !partition->CheckSlaveNodeExist(node.ip(), node.port())) { + LOG(WARNING) << "Current replication num: " << partition->GetNumberOfSlaveNode() + << " hits configuration replication-num " << g_pika_conf->replication_num() << " stop trysync."; pre_success = false; } if (pre_success) { const InnerMessage::ConsensusMeta& meta = req->consensus_meta(); // need to response to outdated pb, new follower count on this response to update term if (meta.term() > partition->ConsensusTerm()) { - LOG(INFO) << "Update " << partition_name - << " term from " << partition->ConsensusTerm() << " to " << meta.term(); + LOG(INFO) << "Update " << partition_name << " term from " << partition->ConsensusTerm() << " to " + << meta.term(); partition->ConsensusUpdateTerm(meta.term()); } } @@ -141,8 +131,7 @@ void PikaReplServerConn::HandleTrySyncRequest(void* arg) { } std::string reply_str; - if (!response.SerializeToString(&reply_str) - || conn->WriteResp(reply_str)) { + if (!response.SerializeToString(&reply_str) || conn->WriteResp(reply_str)) { LOG(WARNING) << "Handle Try Sync Failed"; conn->NotifyClose(); delete task_arg; @@ -152,11 +141,10 @@ void PikaReplServerConn::HandleTrySyncRequest(void* arg) { delete task_arg; } -bool PikaReplServerConn::TrySyncUpdateSlaveNode( - const std::shared_ptr& partition, - const InnerMessage::InnerRequest::TrySync& try_sync_request, - const std::shared_ptr& conn, - InnerMessage::InnerResponse::TrySync* try_sync_response) { +bool PikaReplServerConn::TrySyncUpdateSlaveNode(const std::shared_ptr& partition, + const InnerMessage::InnerRequest::TrySync& try_sync_request, + const std::shared_ptr& conn, + InnerMessage::InnerResponse::TrySync* try_sync_response) { InnerMessage::Node node = try_sync_request.node(); std::string partition_name = partition->PartitionName(); @@ -194,11 +182,10 @@ bool PikaReplServerConn::TrySyncUpdateSlaveNode( return true; } -bool PikaReplServerConn::TrySyncConsensusOffsetCheck( - const std::shared_ptr& partition, - const InnerMessage::ConsensusMeta& meta, - InnerMessage::InnerResponse* response, - InnerMessage::InnerResponse::TrySync* try_sync_response) { +bool PikaReplServerConn::TrySyncConsensusOffsetCheck(const std::shared_ptr& partition, + const InnerMessage::ConsensusMeta& meta, + InnerMessage::InnerResponse* response, + InnerMessage::InnerResponse::TrySync* try_sync_response) { LogOffset last_log_offset; last_log_offset.b_offset.filenum = meta.log_offset().filenum(); last_log_offset.b_offset.offset = meta.log_offset().offset(); @@ -228,10 +215,9 @@ bool PikaReplServerConn::TrySyncConsensusOffsetCheck( return true; } -bool PikaReplServerConn::TrySyncOffsetCheck( - const std::shared_ptr& partition, - const InnerMessage::InnerRequest::TrySync& try_sync_request, - InnerMessage::InnerResponse::TrySync* try_sync_response) { +bool PikaReplServerConn::TrySyncOffsetCheck(const std::shared_ptr& partition, + const InnerMessage::InnerRequest::TrySync& try_sync_request, + InnerMessage::InnerResponse::TrySync* try_sync_response) { InnerMessage::Node node = try_sync_request.node(); InnerMessage::BinlogOffset slave_boffset = try_sync_request.binlog_offset(); std::string partition_name = partition->PartitionName(); @@ -240,21 +226,19 @@ bool PikaReplServerConn::TrySyncOffsetCheck( Status s = partition->Logger()->GetProducerStatus(&(boffset.filenum), &(boffset.offset)); if (!s.ok()) { try_sync_response->set_reply_code(InnerMessage::InnerResponse::TrySync::kError); - LOG(WARNING) << "Handle TrySync, Partition: " - << partition_name << " Get binlog offset error, TrySync failed"; + LOG(WARNING) << "Handle TrySync, Partition: " << partition_name << " Get binlog offset error, TrySync failed"; return false; } InnerMessage::BinlogOffset* master_partition_boffset = try_sync_response->mutable_binlog_offset(); master_partition_boffset->set_filenum(boffset.filenum); master_partition_boffset->set_offset(boffset.offset); - if (boffset.filenum < slave_boffset.filenum() - || (boffset.filenum == slave_boffset.filenum() && boffset.offset < slave_boffset.offset())) { + if (boffset.filenum < slave_boffset.filenum() || + (boffset.filenum == slave_boffset.filenum() && boffset.offset < slave_boffset.offset())) { try_sync_response->set_reply_code(InnerMessage::InnerResponse::TrySync::kSyncPointLarger); - LOG(WARNING) << "Slave offset is larger than mine, Slave ip: " - << node.ip() << ", Slave port: " << node.port() << ", Partition: " - << partition_name << ", filenum: " << slave_boffset.filenum() - << ", pro_offset_: " << slave_boffset.offset(); + LOG(WARNING) << "Slave offset is larger than mine, Slave ip: " << node.ip() << ", Slave port: " << node.port() + << ", Partition: " << partition_name << ", filenum: " << slave_boffset.filenum() + << ", pro_offset_: " << slave_boffset.offset(); return false; } @@ -271,20 +255,16 @@ bool PikaReplServerConn::TrySyncOffsetCheck( reader.GetReaderStatus(&(seeked_offset.filenum), &(seeked_offset.offset)); if (seeked_offset.filenum != slave_boffset.filenum() || seeked_offset.offset != slave_boffset.offset()) { try_sync_response->set_reply_code(InnerMessage::InnerResponse::TrySync::kError); - LOG(WARNING) << "Slave offset is not a start point of cur log, Slave ip: " - << node.ip() << ", Slave port: " << node.port() << ", Partition: " - << partition_name << ", cloest start point, filenum: " << seeked_offset.filenum - << ", offset: " << seeked_offset.offset; + LOG(WARNING) << "Slave offset is not a start point of cur log, Slave ip: " << node.ip() + << ", Slave port: " << node.port() << ", Partition: " << partition_name + << ", cloest start point, filenum: " << seeked_offset.filenum << ", offset: " << seeked_offset.offset; return false; } return true; } -void PikaReplServerConn::BuildConsensusMeta( - const bool& reject, - const std::vector& hints, - const uint32_t& term, - InnerMessage::InnerResponse* response) { +void PikaReplServerConn::BuildConsensusMeta(const bool& reject, const std::vector& hints, + const uint32_t& term, InnerMessage::InnerResponse* response) { InnerMessage::ConsensusMeta* consensus_meta = response->mutable_consensus_meta(); consensus_meta->set_term(term); consensus_meta->set_reject(reject); @@ -324,10 +304,9 @@ void PikaReplServerConn::HandleDBSyncRequest(void* arg) { LOG(INFO) << "Handle partition DBSync Request"; bool prior_success = true; std::shared_ptr master_partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!master_partition) { - LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id << ", NotFound"; prior_success = false; } if (prior_success) { @@ -368,12 +347,10 @@ void PikaReplServerConn::HandleDBSyncRequest(void* arg) { } } - g_pika_server->TryDBSync(node.ip(), node.port() + kPortShiftRSync, - table_name, partition_id, slave_boffset.filenum()); + g_pika_server->TryDBSync(node.ip(), node.port() + kPortShiftRSync, table_name, partition_id, slave_boffset.filenum()); std::string reply_str; - if (!response.SerializeToString(&reply_str) - || conn->WriteResp(reply_str)) { + if (!response.SerializeToString(&reply_str) || conn->WriteResp(reply_str)) { LOG(WARNING) << "Handle DBSync Failed"; conn->NotifyClose(); delete task_arg; @@ -389,7 +366,7 @@ void PikaReplServerConn::HandleBinlogSyncRequest(void* arg) { std::shared_ptr conn = task_arg->conn; if (!req->has_binlog_sync()) { LOG(WARNING) << "Pb parse error"; - //conn->NotifyClose(); + // conn->NotifyClose(); delete task_arg; return; } @@ -409,11 +386,10 @@ void PikaReplServerConn::HandleBinlogSyncRequest(void* arg) { LogOffset range_start(b_range_start, l_range_start); LogOffset range_end(b_range_end, l_range_end); - std::shared_ptr master_partition - = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + std::shared_ptr master_partition = + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!master_partition) { - LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id << ", NotFound"; delete task_arg; return; } @@ -421,22 +397,21 @@ void PikaReplServerConn::HandleBinlogSyncRequest(void* arg) { if (req->has_consensus_meta()) { const InnerMessage::ConsensusMeta& meta = req->consensus_meta(); if (meta.term() > master_partition->ConsensusTerm()) { - LOG(INFO) << "Update " << table_name << ":" << partition_id - << " term from " << master_partition->ConsensusTerm() << " to " << meta.term(); + LOG(INFO) << "Update " << table_name << ":" << partition_id << " term from " << master_partition->ConsensusTerm() + << " to " << meta.term(); master_partition->ConsensusUpdateTerm(meta.term()); - } else if (meta.term() < master_partition->ConsensusTerm()) /*outdated pb*/{ + } else if (meta.term() < master_partition->ConsensusTerm()) /*outdated pb*/ { LOG(WARNING) << "Drop outdated binlog sync req " << table_name << ":" << partition_id - << " recv term: " << meta.term() << " local term: " << master_partition->ConsensusTerm(); + << " recv term: " << meta.term() << " local term: " << master_partition->ConsensusTerm(); delete task_arg; return; } } - if (!master_partition->CheckSessionId(node.ip(), node.port(), - table_name, partition_id, session_id)) { - LOG(WARNING) << "Check Session failed " << node.ip() << ":" << node.port() - << ", " << table_name << "_" << partition_id; - //conn->NotifyClose(); + if (!master_partition->CheckSessionId(node.ip(), node.port(), table_name, partition_id, session_id)) { + LOG(WARNING) << "Check Session failed " << node.ip() << ":" << node.port() << ", " << table_name << "_" + << partition_id; + // conn->NotifyClose(); delete task_arg; return; } @@ -446,8 +421,8 @@ void PikaReplServerConn::HandleBinlogSyncRequest(void* arg) { Status s = master_partition->SetLastRecvTime(node.ip(), node.port(), pstd::NowMicros()); if (!s.ok()) { - LOG(WARNING) << "SetMasterLastRecvTime failed " << node.ip() << ":" << node.port() - << ", " << table_name << "_" << partition_id << " " << s.ToString(); + LOG(WARNING) << "SetMasterLastRecvTime failed " << node.ip() << ":" << node.port() << ", " << table_name << "_" + << partition_id << " " << s.ToString(); conn->NotifyClose(); delete task_arg; return; @@ -510,8 +485,7 @@ void PikaReplServerConn::HandleRemoveSlaveNodeRequest(void* arg) { std::shared_ptr master_partition = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!master_partition) { - LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << partition_id << ", NotFound"; } Status s = master_partition->RemoveSlaveNode(node.ip(), node.port()); @@ -527,8 +501,7 @@ void PikaReplServerConn::HandleRemoveSlaveNodeRequest(void* arg) { node_response->set_port(g_pika_server->port()); std::string reply_str; - if (!response.SerializeToString(&reply_str) - || conn->WriteResp(reply_str)) { + if (!response.SerializeToString(&reply_str) || conn->WriteResp(reply_str)) { LOG(WARNING) << "Remove Slave Node Failed"; conn->NotifyClose(); delete task_arg; @@ -546,33 +519,33 @@ int PikaReplServerConn::DealMessage() { return -1; } switch (req->type()) { - case InnerMessage::kMetaSync: - { - ReplServerTaskArg* task_arg = new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kMetaSync: { + ReplServerTaskArg* task_arg = + new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplServerBGTask(&PikaReplServerConn::HandleMetaSyncRequest, task_arg); break; } - case InnerMessage::kTrySync: - { - ReplServerTaskArg* task_arg = new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kTrySync: { + ReplServerTaskArg* task_arg = + new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplServerBGTask(&PikaReplServerConn::HandleTrySyncRequest, task_arg); break; } - case InnerMessage::kDBSync: - { - ReplServerTaskArg* task_arg = new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kDBSync: { + ReplServerTaskArg* task_arg = + new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplServerBGTask(&PikaReplServerConn::HandleDBSyncRequest, task_arg); break; } - case InnerMessage::kBinlogSync: - { - ReplServerTaskArg* task_arg = new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kBinlogSync: { + ReplServerTaskArg* task_arg = + new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplServerBGTask(&PikaReplServerConn::HandleBinlogSyncRequest, task_arg); break; } - case InnerMessage::kRemoveSlaveNode: - { - ReplServerTaskArg* task_arg = new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); + case InnerMessage::kRemoveSlaveNode: { + ReplServerTaskArg* task_arg = + new ReplServerTaskArg(req, std::dynamic_pointer_cast(shared_from_this())); g_pika_rm->ScheduleReplServerBGTask(&PikaReplServerConn::HandleRemoveSlaveNodeRequest, task_arg); break; } diff --git a/src/pika_repl_server_thread.cc b/src/pika_repl_server_thread.cc index edc33f8fd0..bc636d8e7d 100644 --- a/src/pika_repl_server_thread.cc +++ b/src/pika_repl_server_thread.cc @@ -11,19 +11,15 @@ extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; -PikaReplServerThread::PikaReplServerThread(const std::set& ips, - int port, - int cron_interval) : - HolyThread(ips, port, &conn_factory_, cron_interval, &handle_, true), - conn_factory_(this), - port_(port), - serial_(0) { +PikaReplServerThread::PikaReplServerThread(const std::set& ips, int port, int cron_interval) + : HolyThread(ips, port, &conn_factory_, cron_interval, &handle_, true), + conn_factory_(this), + port_(port), + serial_(0) { set_keepalive_timeout(180); } -int PikaReplServerThread::ListenPort() { - return port_; -} +int PikaReplServerThread::ListenPort() { return port_; } void PikaReplServerThread::ReplServerHandle::FdClosedHandle(int fd, const std::string& ip_port) const { LOG(INFO) << "ServerThread Close Slave Conn, fd: " << fd << ", ip_port: " << ip_port; diff --git a/src/pika_rm.cc b/src/pika_rm.cc index 9d42d1385f..2589b4e05e 100644 --- a/src/pika_rm.cc +++ b/src/pika_rm.cc @@ -5,28 +5,27 @@ #include "include/pika_rm.h" -#include -#include #include #include +#include +#include #include "net/include/net_cli.h" #include "include/pika_conf.h" #include "include/pika_server.h" -#include "include/pika_command.h" #include "include/pika_admin.h" +#include "include/pika_command.h" -extern PikaConf *g_pika_conf; +extern PikaConf* g_pika_conf; extern PikaReplicaManager* g_pika_rm; -extern PikaServer *g_pika_server; +extern PikaServer* g_pika_server; /* SyncPartition */ SyncPartition::SyncPartition(const std::string& table_name, uint32_t partition_id) - : partition_info_(table_name, partition_id) { -} + : partition_info_(table_name, partition_id) {} std::string SyncPartition::PartitionName() { if (g_pika_conf->classic_mode()) { @@ -39,14 +38,9 @@ std::string SyncPartition::PartitionName() { /* SyncMasterPartition*/ SyncMasterPartition::SyncMasterPartition(const std::string& table_name, uint32_t partition_id) - : SyncPartition(table_name, partition_id), - session_id_(0), - coordinator_(table_name, partition_id) { -} + : SyncPartition(table_name, partition_id), session_id_(0), coordinator_(table_name, partition_id) {} -int SyncMasterPartition::GetNumberOfSlaveNode() { - return coordinator_.SyncPros().SlaveSize(); -} +int SyncMasterPartition::GetNumberOfSlaveNode() { return coordinator_.SyncPros().SlaveSize(); } bool SyncMasterPartition::CheckSlaveNodeExist(const std::string& ip, int port) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); @@ -56,8 +50,7 @@ bool SyncMasterPartition::CheckSlaveNodeExist(const std::string& ip, int port) { return true; } -Status SyncMasterPartition::GetSlaveNodeSession( - const std::string& ip, int port, int32_t* session) { +Status SyncMasterPartition::GetSlaveNodeSession(const std::string& ip, int port, int32_t* session) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { return Status::NotFound("slave " + ip + ":" + std::to_string(port) + " not found"); @@ -73,31 +66,29 @@ Status SyncMasterPartition::GetSlaveNodeSession( Status SyncMasterPartition::AddSlaveNode(const std::string& ip, int port, int session_id) { Status s = coordinator_.AddSlaveNode(ip, port, session_id); if (!s.ok()) { - LOG(WARNING) << "Add Slave Node Failed, partition: " << SyncPartitionInfo().ToString() << ", ip_port: "<< ip << ":" << port; + LOG(WARNING) << "Add Slave Node Failed, partition: " << SyncPartitionInfo().ToString() << ", ip_port: " << ip << ":" + << port; return s; } - LOG(INFO) << "Add Slave Node, partition: " << SyncPartitionInfo().ToString() << ", ip_port: "<< ip << ":" << port; + LOG(INFO) << "Add Slave Node, partition: " << SyncPartitionInfo().ToString() << ", ip_port: " << ip << ":" << port; return Status::OK(); } Status SyncMasterPartition::RemoveSlaveNode(const std::string& ip, int port) { Status s = coordinator_.RemoveSlaveNode(ip, port); if (!s.ok()) { - LOG(WARNING) << "Remove Slave Node Failed, Partition: " << SyncPartitionInfo().ToString() - << ", ip_port: "<< ip << ":" << port; + LOG(WARNING) << "Remove Slave Node Failed, Partition: " << SyncPartitionInfo().ToString() << ", ip_port: " << ip + << ":" << port; return s; } - LOG(INFO) << "Remove Slave Node, Partition: " << SyncPartitionInfo().ToString() - << ", ip_port: "<< ip << ":" << port; + LOG(INFO) << "Remove Slave Node, Partition: " << SyncPartitionInfo().ToString() << ", ip_port: " << ip << ":" << port; return Status::OK(); } -Status SyncMasterPartition::ActivateSlaveBinlogSync(const std::string& ip, - int port, - const LogOffset& offset) { +Status SyncMasterPartition::ActivateSlaveBinlogSync(const std::string& ip, int port, const LogOffset& offset) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } { @@ -123,7 +114,7 @@ Status SyncMasterPartition::ActivateSlaveBinlogSync(const std::string& ip, Status SyncMasterPartition::SyncBinlogToWq(const std::string& ip, int port) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } Status s; slave_ptr->Lock(); @@ -138,7 +129,7 @@ Status SyncMasterPartition::SyncBinlogToWq(const std::string& ip, int port) { Status SyncMasterPartition::ActivateSlaveDbSync(const std::string& ip, int port) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } slave_ptr->Lock(); @@ -161,21 +152,19 @@ Status SyncMasterPartition::ReadBinlogFileToWq(const std::shared_ptr& uint32_t filenum; uint64_t offset; if (slave_ptr->sync_win.GetTotalBinlogSize() > PIKA_MAX_CONN_RBUF_HB * 2) { - LOG(INFO) << slave_ptr->ToString() << " total binlog size in sync window is :" - << slave_ptr->sync_win.GetTotalBinlogSize(); + LOG(INFO) << slave_ptr->ToString() + << " total binlog size in sync window is :" << slave_ptr->sync_win.GetTotalBinlogSize(); break; } Status s = reader->Get(&msg, &filenum, &offset); if (s.IsEndFile()) { break; } else if (s.IsCorruption() || s.IsIOError()) { - LOG(WARNING) << SyncPartitionInfo().ToString() - << " Read Binlog error : " << s.ToString(); + LOG(WARNING) << SyncPartitionInfo().ToString() << " Read Binlog error : " << s.ToString(); return s; } BinlogItem item; - if (!PikaBinlogTransverter::BinlogItemWithoutContentDecode( - TypeFirst, msg, &item)) { + if (!PikaBinlogTransverter::BinlogItemWithoutContentDecode(TypeFirst, msg, &item)) { LOG(WARNING) << "Binlog item decode failed"; return Status::Corruption("Binlog item decode failed"); } @@ -185,7 +174,8 @@ Status SyncMasterPartition::ReadBinlogFileToWq(const std::shared_ptr& slave_ptr->sync_win.Push(SyncWinItem(sent_offset, msg.size())); slave_ptr->SetLastSendTime(pstd::NowMicros()); - RmNode rm_node(slave_ptr->Ip(), slave_ptr->Port(), slave_ptr->TableName(), slave_ptr->PartitionId(), slave_ptr->SessionId()); + RmNode rm_node(slave_ptr->Ip(), slave_ptr->Port(), slave_ptr->TableName(), slave_ptr->PartitionId(), + slave_ptr->SessionId()); WriteTask task(rm_node, BinlogChip(sent_offset, msg), slave_ptr->sent_offset); tasks.push_back(task); slave_ptr->sent_offset = sent_offset; @@ -197,7 +187,8 @@ Status SyncMasterPartition::ReadBinlogFileToWq(const std::shared_ptr& return Status::OK(); } -Status SyncMasterPartition::ConsensusUpdateSlave(const std::string& ip, int port, const LogOffset& start, const LogOffset& end) { +Status SyncMasterPartition::ConsensusUpdateSlave(const std::string& ip, int port, const LogOffset& start, + const LogOffset& end) { Status s = coordinator_.UpdateSlave(ip, port, start, end); if (!s.ok()) { LOG(WARNING) << SyncPartitionInfo().ToString() << s.ToString(); @@ -216,17 +207,13 @@ Status SyncMasterPartition::ConsensusUpdateAppliedIndex(const LogOffset& offset) return Status::OK(); } -LogOffset SyncMasterPartition::ConsensusAppliedIndex() { - return coordinator_.applied_index(); -} +LogOffset SyncMasterPartition::ConsensusAppliedIndex() { return coordinator_.applied_index(); } -Status SyncMasterPartition::GetSlaveSyncBinlogInfo(const std::string& ip, - int port, - BinlogOffset* sent_offset, +Status SyncMasterPartition::GetSlaveSyncBinlogInfo(const std::string& ip, int port, BinlogOffset* sent_offset, BinlogOffset* acked_offset) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } slave_ptr->Lock(); @@ -237,12 +224,10 @@ Status SyncMasterPartition::GetSlaveSyncBinlogInfo(const std::string& ip, return Status::OK(); } -Status SyncMasterPartition::GetSlaveState(const std::string& ip, - int port, - SlaveState* const slave_state) { +Status SyncMasterPartition::GetSlaveState(const std::string& ip, int port, SlaveState* const slave_state) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } slave_ptr->Lock(); @@ -262,8 +247,8 @@ Status SyncMasterPartition::WakeUpSlaveBinlogSync() { Status s = ReadBinlogFileToWq(slave_ptr); if (!s.ok()) { to_del.push_back(slave_ptr); - LOG(WARNING) << "WakeUpSlaveBinlogSync falied, Delete from RM, slave: " << - slave_ptr->ToStringStatus() << " " << s.ToString(); + LOG(WARNING) << "WakeUpSlaveBinlogSync falied, Delete from RM, slave: " << slave_ptr->ToStringStatus() << " " + << s.ToString(); } } } @@ -276,7 +261,7 @@ Status SyncMasterPartition::WakeUpSlaveBinlogSync() { Status SyncMasterPartition::SetLastSendTime(const std::string& ip, int port, uint64_t time) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } slave_ptr->Lock(); @@ -289,7 +274,7 @@ Status SyncMasterPartition::SetLastSendTime(const std::string& ip, int port, uin Status SyncMasterPartition::GetLastSendTime(const std::string& ip, int port, uint64_t* time) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } slave_ptr->Lock(); @@ -302,7 +287,7 @@ Status SyncMasterPartition::GetLastSendTime(const std::string& ip, int port, uin Status SyncMasterPartition::SetLastRecvTime(const std::string& ip, int port, uint64_t time) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } slave_ptr->Lock(); @@ -315,7 +300,7 @@ Status SyncMasterPartition::SetLastRecvTime(const std::string& ip, int port, uin Status SyncMasterPartition::GetLastRecvTime(const std::string& ip, int port, uint64_t* time) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - return Status::NotFound("ip " + ip + " port " + std::to_string(port)); + return Status::NotFound("ip " + ip + " port " + std::to_string(port)); } slave_ptr->Lock(); @@ -340,8 +325,7 @@ Status SyncMasterPartition::GetSafetyPurgeBinlog(std::string* safety_purge) { for (const auto& slave_iter : slaves) { std::shared_ptr slave_ptr = slave_iter.second; pstd::MutexLock l(&slave_ptr->slave_mu); - if (slave_ptr->slave_state == SlaveState::kSlaveBinlogSync - && slave_ptr->acked_offset.b_offset.filenum > 0) { + if (slave_ptr->slave_state == SlaveState::kSlaveBinlogSync && slave_ptr->acked_offset.b_offset.filenum > 0) { purge_max = std::min(slave_ptr->acked_offset.b_offset.filenum - 1, purge_max); } else { success = false; @@ -387,15 +371,17 @@ Status SyncMasterPartition::CheckSyncTimeout(uint64_t now) { pstd::MutexLock l(&slave_ptr->slave_mu); if (slave_ptr->LastRecvTime() + kRecvKeepAliveTimeout < now) { to_del.push_back(Node(slave_ptr->Ip(), slave_ptr->Port())); - } else if (slave_ptr->LastSendTime() + kSendKeepAliveTimeout < now && slave_ptr->sent_offset == slave_ptr->acked_offset) { + } else if (slave_ptr->LastSendTime() + kSendKeepAliveTimeout < now && + slave_ptr->sent_offset == slave_ptr->acked_offset) { std::vector task; - RmNode rm_node(slave_ptr->Ip(), slave_ptr->Port(), slave_ptr->TableName(), slave_ptr->PartitionId(), slave_ptr->SessionId()); + RmNode rm_node(slave_ptr->Ip(), slave_ptr->Port(), slave_ptr->TableName(), slave_ptr->PartitionId(), + slave_ptr->SessionId()); WriteTask empty_task(rm_node, BinlogChip(LogOffset(), ""), LogOffset()); task.push_back(empty_task); Status s = g_pika_rm->SendSlaveBinlogChipsRequest(slave_ptr->Ip(), slave_ptr->Port(), task); slave_ptr->SetLastSendTime(now); if (!s.ok()) { - LOG(INFO)<< "Send ping failed: " << s.ToString(); + LOG(INFO) << "Send ping failed: " << s.ToString(); return Status::Corruption("Send ping failed: " + slave_ptr->Ip() + ":" + std::to_string(slave_ptr->Port())); } } @@ -412,14 +398,15 @@ Status SyncMasterPartition::CheckSyncTimeout(uint64_t now) { std::string SyncMasterPartition::ToStringStatus() { std::stringstream tmp_stream; tmp_stream << " Current Master Session: " << session_id_ << "\r\n"; - tmp_stream << " Consensus: " << "\r\n" << coordinator_.ToStringStatus(); + tmp_stream << " Consensus: " + << "\r\n" + << coordinator_.ToStringStatus(); std::unordered_map> slaves = GetAllSlaveNodes(); int i = 0; for (auto slave_iter : slaves) { std::shared_ptr slave_ptr = slave_iter.second; pstd::MutexLock l(&slave_ptr->slave_mu); - tmp_stream << " slave[" << i << "]: " << slave_ptr->ToString() << - "\r\n" << slave_ptr->ToStringStatus(); + tmp_stream << " slave[" << i << "]: " << slave_ptr->ToString() << "\r\n" << slave_ptr->ToStringStatus(); i++; } return tmp_stream.str(); @@ -442,14 +429,14 @@ Status SyncMasterPartition::GetInfo(std::string* info) { std::unordered_map> slaves = GetAllSlaveNodes(); std::stringstream tmp_stream; - tmp_stream << " Role: Master" << "\r\n"; + tmp_stream << " Role: Master" + << "\r\n"; tmp_stream << " connected_slaves: " << slaves.size() << "\r\n"; int i = 0; for (auto slave_iter : slaves) { std::shared_ptr slave_ptr = slave_iter.second; pstd::MutexLock l(&slave_ptr->slave_mu); - tmp_stream << " slave[" << i++ << "]: " - << slave_ptr->Ip() << ":" << std::to_string(slave_ptr->Port()) << "\r\n"; + tmp_stream << " slave[" << i++ << "]: " << slave_ptr->Ip() << ":" << std::to_string(slave_ptr->Port()) << "\r\n"; tmp_stream << " replication_status: " << SlaveStateMsg[slave_ptr->slave_state] << "\r\n"; if (slave_ptr->slave_state == kSlaveBinlogSync) { BinlogOffset binlog_offset; @@ -457,9 +444,9 @@ Status SyncMasterPartition::GetInfo(std::string* info) { if (!s.ok()) { return s; } - uint64_t lag = (binlog_offset.filenum - slave_ptr->acked_offset.b_offset.filenum) * - g_pika_conf->binlog_file_size() - + (binlog_offset.offset - slave_ptr->acked_offset.b_offset.offset); + uint64_t lag = + (binlog_offset.filenum - slave_ptr->acked_offset.b_offset.filenum) * g_pika_conf->binlog_file_size() + + (binlog_offset.offset - slave_ptr->acked_offset.b_offset.offset); tmp_stream << " lag: " << lag << "\r\n"; } } @@ -472,40 +459,32 @@ int32_t SyncMasterPartition::GenSessionId() { return session_id_++; } -bool SyncMasterPartition::CheckSessionId(const std::string& ip, int port, - const std::string& table_name, +bool SyncMasterPartition::CheckSessionId(const std::string& ip, int port, const std::string& table_name, uint64_t partition_id, int session_id) { std::shared_ptr slave_ptr = GetSlaveNode(ip, port); if (!slave_ptr) { - LOG(WARNING)<< "Check SessionId Get Slave Node Error: " - << ip << ":" << port << "," << table_name << "_" << partition_id; + LOG(WARNING) << "Check SessionId Get Slave Node Error: " << ip << ":" << port << "," << table_name << "_" + << partition_id; return false; } pstd::MutexLock l(&slave_ptr->slave_mu); if (session_id != slave_ptr->SessionId()) { - LOG(WARNING)<< "Check SessionId Mismatch: " << ip << ":" << port << ", " - << table_name << "_" << partition_id << " expected_session: " << session_id - << ", actual_session:" << slave_ptr->SessionId(); + LOG(WARNING) << "Check SessionId Mismatch: " << ip << ":" << port << ", " << table_name << "_" << partition_id + << " expected_session: " << session_id << ", actual_session:" << slave_ptr->SessionId(); return false; } return true; } -Status SyncMasterPartition::ConsensusProposeLog( - std::shared_ptr cmd_ptr, - std::shared_ptr conn_ptr, - std::shared_ptr resp_ptr) { +Status SyncMasterPartition::ConsensusProposeLog(std::shared_ptr cmd_ptr, std::shared_ptr conn_ptr, + std::shared_ptr resp_ptr) { return coordinator_.ProposeLog(cmd_ptr, conn_ptr, resp_ptr); } -Status SyncMasterPartition::ConsensusSanityCheck() { - return coordinator_.CheckEnoughFollower(); -} +Status SyncMasterPartition::ConsensusSanityCheck() { return coordinator_.CheckEnoughFollower(); } -Status SyncMasterPartition::ConsensusProcessLeaderLog( - std::shared_ptr cmd_ptr, - const BinlogItem& attribute) { +Status SyncMasterPartition::ConsensusProcessLeaderLog(std::shared_ptr cmd_ptr, const BinlogItem& attribute) { return coordinator_.ProcessLeaderLog(cmd_ptr, attribute); } @@ -513,17 +492,11 @@ Status SyncMasterPartition::ConsensusProcessLocalUpdate(const LogOffset& leader_ return coordinator_.ProcessLocalUpdate(leader_commit); } -LogOffset SyncMasterPartition::ConsensusCommittedIndex() { - return coordinator_.committed_index(); -} +LogOffset SyncMasterPartition::ConsensusCommittedIndex() { return coordinator_.committed_index(); } -LogOffset SyncMasterPartition::ConsensusLastIndex() { - return coordinator_.MemLogger()->last_offset(); -} +LogOffset SyncMasterPartition::ConsensusLastIndex() { return coordinator_.MemLogger()->last_offset(); } -uint32_t SyncMasterPartition::ConsensusTerm() { - return coordinator_.term(); -} +uint32_t SyncMasterPartition::ConsensusTerm() { return coordinator_.term(); } void SyncMasterPartition::ConsensusUpdateTerm(uint32_t term) { coordinator_.UpdateTerm(term); @@ -534,8 +507,7 @@ void SyncMasterPartition::ConsensusUpdateTerm(uint32_t term) { void SyncMasterPartition::CommitPreviousLogs(const uint32_t& term) { // Append dummy cmd - std::shared_ptr dummy_ptr = - std::make_shared(kCmdDummy, 0, kCmdFlagsWrite | kCmdFlagsSinglePartition); + std::shared_ptr dummy_ptr = std::make_shared(kCmdDummy, 0, kCmdFlagsWrite | kCmdFlagsSinglePartition); PikaCmdArgsType args; args.push_back(kCmdDummy); dummy_ptr->Initial(args, SyncPartitionInfo().table_name_); @@ -548,32 +520,24 @@ std::shared_ptr SyncMasterPartition::GetSlaveNode(const std::string& return coordinator_.SyncPros().GetSlaveNode(ip, port); } -std::unordered_map> -SyncMasterPartition::GetAllSlaveNodes() { +std::unordered_map> SyncMasterPartition::GetAllSlaveNodes() { return coordinator_.SyncPros().GetAllSlaveNodes(); } -Status SyncMasterPartition::ConsensusLeaderNegotiate( - const LogOffset& f_last_offset, bool* reject, std::vector* hints) { +Status SyncMasterPartition::ConsensusLeaderNegotiate(const LogOffset& f_last_offset, bool* reject, + std::vector* hints) { return coordinator_.LeaderNegotiate(f_last_offset, reject, hints); } -Status SyncMasterPartition::ConsensusFollowerNegotiate( - const std::vector& hints, LogOffset* reply_offset) { +Status SyncMasterPartition::ConsensusFollowerNegotiate(const std::vector& hints, LogOffset* reply_offset) { return coordinator_.FollowerNegotiate(hints, reply_offset); } -Status SyncMasterPartition::ConsensusReset(LogOffset applied_offset) { - return coordinator_.Reset(applied_offset); -} +Status SyncMasterPartition::ConsensusReset(LogOffset applied_offset) { return coordinator_.Reset(applied_offset); } /* SyncSlavePartition */ -SyncSlavePartition::SyncSlavePartition(const std::string& table_name, - uint32_t partition_id) - : SyncPartition(table_name, partition_id), - m_info_(), - repl_state_(kNoConnect), - local_ip_("") { +SyncSlavePartition::SyncSlavePartition(const std::string& table_name, uint32_t partition_id) + : SyncPartition(table_name, partition_id), m_info_(), repl_state_(kNoConnect), local_ip_("") { m_info_.SetLastRecvTime(pstd::NowMicros()); } @@ -619,7 +583,7 @@ Status SyncSlavePartition::CheckSyncTimeout(uint64_t now) { Status SyncSlavePartition::GetInfo(std::string* info) { std::string tmp_str = " Role: Slave\r\n"; tmp_str += " master: " + MasterIp() + ":" + std::to_string(MasterPort()) + "\r\n"; - tmp_str += " slave status: "+ ReplStateMsg[repl_state_] + "\r\n"; + tmp_str += " slave status: " + ReplStateMsg[repl_state_] + "\r\n"; info->append(tmp_str); return Status::OK(); } @@ -639,8 +603,8 @@ void SyncSlavePartition::Deactivate() { std::string SyncSlavePartition::ToStringStatus() { return " Master: " + MasterIp() + ":" + std::to_string(MasterPort()) + "\r\n" + - " SessionId: " + std::to_string(MasterSessionId()) + "\r\n" + - " SyncStatus " + ReplStateMsg[repl_state_] + "\r\n"; + " SessionId: " + std::to_string(MasterSessionId()) + "\r\n" + " SyncStatus " + ReplStateMsg[repl_state_] + + "\r\n"; } const std::string& SyncSlavePartition::MasterIp() { @@ -695,12 +659,14 @@ void PikaReplicaManager::Start() { int ret = 0; ret = pika_repl_client_->Start(); if (ret != net::kSuccess) { - LOG(FATAL) << "Start Repl Client Error: " << ret << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); + LOG(FATAL) << "Start Repl Client Error: " << ret + << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); } ret = pika_repl_server_->Start(); if (ret != net::kSuccess) { - LOG(FATAL) << "Start Repl Server Error: " << ret << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); + LOG(FATAL) << "Start Repl Server Error: " << ret + << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); } } @@ -730,15 +696,16 @@ void PikaReplicaManager::InitPartition() { for (const auto& table : table_structs) { const std::string& table_name = table.table_name; for (const auto& partition_id : table.partition_ids) { - sync_master_partitions_[PartitionInfo(table_name, partition_id)] - = std::make_shared(table_name, partition_id); - sync_slave_partitions_[PartitionInfo(table_name, partition_id)] - = std::make_shared(table_name, partition_id); + sync_master_partitions_[PartitionInfo(table_name, partition_id)] = + std::make_shared(table_name, partition_id); + sync_slave_partitions_[PartitionInfo(table_name, partition_id)] = + std::make_shared(table_name, partition_id); } } } -void PikaReplicaManager::ProduceWriteQueue(const std::string& ip, int port, uint32_t partition_id, const std::vector& tasks) { +void PikaReplicaManager::ProduceWriteQueue(const std::string& ip, int port, uint32_t partition_id, + const std::vector& tasks) { pstd::MutexLock l(&write_queue_mu_); std::string index = ip + ":" + std::to_string(port); for (auto& task : tasks) { @@ -765,7 +732,7 @@ int PikaReplicaManager::ConsumeWriteQueue() { int batch_size = 0; for (size_t i = 0; i < batch_index; ++i) { WriteTask& task = queue.front(); - batch_size += task.binlog_chip_.binlog_.size(); + batch_size += task.binlog_chip_.binlog_.size(); // make sure SerializeToString will not over 2G if (batch_size > PIKA_MAX_CONN_RBUF_HB) { break; @@ -826,27 +793,24 @@ void PikaReplicaManager::ScheduleReplClientBGTask(net::TaskFunc func, void* arg) } void PikaReplicaManager::ScheduleWriteBinlogTask(const std::string& table_partition, - const std::shared_ptr res, - std::shared_ptr conn, - void* res_private_data) { + const std::shared_ptr res, + std::shared_ptr conn, void* res_private_data) { pika_repl_client_->ScheduleWriteBinlogTask(table_partition, res, conn, res_private_data); } -void PikaReplicaManager::ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, - const LogOffset& offset, const std::string& table_name, uint32_t partition_id) { +void PikaReplicaManager::ScheduleWriteDBTask(const std::shared_ptr cmd_ptr, const LogOffset& offset, + const std::string& table_name, uint32_t partition_id) { pika_repl_client_->ScheduleWriteDBTask(cmd_ptr, offset, table_name, partition_id); } -void PikaReplicaManager::ReplServerRemoveClientConn(int fd) { - pika_repl_server_->RemoveClientConn(fd); -} +void PikaReplicaManager::ReplServerRemoveClientConn(int fd) { pika_repl_server_->RemoveClientConn(fd); } -void PikaReplicaManager::ReplServerUpdateClientConnMap(const std::string& ip_port, - int fd) { +void PikaReplicaManager::ReplServerUpdateClientConnMap(const std::string& ip_port, int fd) { pika_repl_server_->UpdateClientConnMap(ip_port, fd); } -Status PikaReplicaManager::UpdateSyncBinlogStatus(const RmNode& slave, const LogOffset& range_start, const LogOffset& range_end) { +Status PikaReplicaManager::UpdateSyncBinlogStatus(const RmNode& slave, const LogOffset& range_start, + const LogOffset& range_end) { pstd::RWLock l(&partitions_rw_, false); if (sync_master_partitions_.find(slave.NodePartitionInfo()) == sync_master_partitions_.end()) { return Status::NotFound(slave.ToString() + " not found"); @@ -867,10 +831,10 @@ bool PikaReplicaManager::CheckSlavePartitionState(const std::string& ip, const i std::shared_ptr partition = nullptr; for (auto iter : g_pika_rm->sync_slave_partitions_) { partition = iter.second; - if (partition->State() == ReplState::kDBNoConnect && - partition->MasterIp() == ip && partition->MasterPort() + kPortShiftReplServer == port) { + if (partition->State() == ReplState::kDBNoConnect && partition->MasterIp() == ip && + partition->MasterPort() + kPortShiftReplServer == port) { LOG(INFO) << "DB: " << partition->SyncPartitionInfo().ToString() - << " has been dbslaveof no one, then will not try reconnect."; + << " has been dbslaveof no one, then will not try reconnect."; return false; } } @@ -928,8 +892,7 @@ Status PikaReplicaManager::CheckSyncTimeout(uint64_t now) { return Status::OK(); } -Status PikaReplicaManager::CheckPartitionRole( - const std::string& table, uint32_t partition_id, int* role) { +Status PikaReplicaManager::CheckPartitionRole(const std::string& table, uint32_t partition_id, int* role) { pstd::RWLock l(&partitions_rw_, false); *role = 0; PartitionInfo p_info(table, partition_id); @@ -939,9 +902,9 @@ Status PikaReplicaManager::CheckPartitionRole( if (sync_slave_partitions_.find(p_info) == sync_slave_partitions_.end()) { return Status::NotFound(table + std::to_string(partition_id) + " not found"); } - if (sync_master_partitions_[p_info]->GetNumberOfSlaveNode() != 0 - || (sync_master_partitions_[p_info]->GetNumberOfSlaveNode() == 0 - && sync_slave_partitions_[p_info]->State() == kNoConnect)) { + if (sync_master_partitions_[p_info]->GetNumberOfSlaveNode() != 0 || + (sync_master_partitions_[p_info]->GetNumberOfSlaveNode() == 0 && + sync_slave_partitions_[p_info]->State() == kNoConnect)) { *role |= PIKA_ROLE_MASTER; } if (sync_slave_partitions_[p_info]->State() != ReplState::kNoConnect) { @@ -951,8 +914,7 @@ Status PikaReplicaManager::CheckPartitionRole( return Status::OK(); } -Status PikaReplicaManager::GetPartitionInfo( - const std::string& table, uint32_t partition_id, std::string* info) { +Status PikaReplicaManager::GetPartitionInfo(const std::string& table, uint32_t partition_id, std::string* info) { int role = 0; std::string tmp_res; Status s = CheckPartitionRole(table, partition_id, &role); @@ -965,7 +927,7 @@ Status PikaReplicaManager::GetPartitionInfo( PartitionInfo p_info(table, partition_id); if (role & PIKA_ROLE_MASTER) { if (sync_master_partitions_.find(p_info) == sync_master_partitions_.end()) { - return Status::NotFound(table + std::to_string(partition_id) + " not found"); + return Status::NotFound(table + std::to_string(partition_id) + " not found"); } Status s = sync_master_partitions_[p_info]->GetInfo(info); if (!s.ok()) { @@ -988,36 +950,33 @@ Status PikaReplicaManager::GetPartitionInfo( return Status::OK(); } -Status PikaReplicaManager::SelectLocalIp(const std::string& remote_ip, - const int remote_port, +Status PikaReplicaManager::SelectLocalIp(const std::string& remote_ip, const int remote_port, std::string* const local_ip) { net::NetCli* cli = net::NewRedisCli(); cli->set_connect_timeout(1500); if ((cli->Connect(remote_ip, remote_port, "")).ok()) { struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); - getsockname(cli->fd(), (struct sockaddr*) &laddr, &llen); + getsockname(cli->fd(), (struct sockaddr*)&laddr, &llen); std::string tmp_ip(inet_ntoa(laddr.sin_addr)); *local_ip = tmp_ip; cli->Close(); delete cli; } else { - LOG(WARNING) << "Failed to connect remote node(" - << remote_ip << ":" << remote_port << ")"; + LOG(WARNING) << "Failed to connect remote node(" << remote_ip << ":" << remote_port << ")"; delete cli; return Status::Corruption("connect remote node error"); } return Status::OK(); } -Status PikaReplicaManager::ActivateSyncSlavePartition(const RmNode& node, - const ReplState& repl_state) { +Status PikaReplicaManager::ActivateSyncSlavePartition(const RmNode& node, const ReplState& repl_state) { pstd::RWLock l(&partitions_rw_, false); const PartitionInfo& p_info = node.NodePartitionInfo(); if (sync_slave_partitions_.find(p_info) == sync_slave_partitions_.end()) { return Status::NotFound("Sync Slave partition " + node.ToString() + " not found"); } - ReplState ssp_state = sync_slave_partitions_[p_info]->State(); + ReplState ssp_state = sync_slave_partitions_[p_info]->State(); if (ssp_state != ReplState::kNoConnect && ssp_state != ReplState::kDBNoConnect) { return Status::Corruption("Sync Slave partition in " + ReplStateMsg[ssp_state]); } @@ -1042,7 +1001,7 @@ Status PikaReplicaManager::DeactivateSyncSlavePartition(const PartitionInfo& p_i Status PikaReplicaManager::SendMetaSyncRequest() { Status s; if (time(NULL) - g_pika_server->GetMetaSyncTimestamp() >= PIKA_META_SYNC_MAX_WAIT_TIME || - g_pika_server->IsFirstMetaSync() == true) { + g_pika_server->IsFirstMetaSync() == true) { s = pika_repl_client_->SendMetaSync(); if (s.ok()) { g_pika_server->UpdateMetaSyncTimestamp(); @@ -1052,8 +1011,7 @@ Status PikaReplicaManager::SendMetaSyncRequest() { return s; } -Status PikaReplicaManager::SendRemoveSlaveNodeRequest(const std::string& table, - uint32_t partition_id) { +Status PikaReplicaManager::SendRemoveSlaveNodeRequest(const std::string& table, uint32_t partition_id) { pstd::Status s; pstd::RWLock l(&partitions_rw_, false); PartitionInfo p_info(table, partition_id); @@ -1061,45 +1019,38 @@ Status PikaReplicaManager::SendRemoveSlaveNodeRequest(const std::string& table, return Status::NotFound("Sync Slave partition " + p_info.ToString()); } else { std::shared_ptr s_partition = sync_slave_partitions_[p_info]; - s = pika_repl_client_->SendRemoveSlaveNode(s_partition->MasterIp(), - s_partition->MasterPort(), table, partition_id, s_partition->LocalIp()); + s = pika_repl_client_->SendRemoveSlaveNode(s_partition->MasterIp(), s_partition->MasterPort(), table, partition_id, + s_partition->LocalIp()); if (s.ok()) { s_partition->SetReplState(ReplState::kDBNoConnect); } } if (s.ok()) { - LOG(INFO) << "SlaveNode (" << table << ":" << partition_id - << "), stop sync success"; + LOG(INFO) << "SlaveNode (" << table << ":" << partition_id << "), stop sync success"; } else { - LOG(WARNING) << "SlaveNode (" << table << ":" << partition_id - << "), stop sync faild, " << s.ToString(); + LOG(WARNING) << "SlaveNode (" << table << ":" << partition_id << "), stop sync faild, " << s.ToString(); } return s; } -Status PikaReplicaManager::SendPartitionTrySyncRequest( - const std::string& table_name, size_t partition_id) { +Status PikaReplicaManager::SendPartitionTrySyncRequest(const std::string& table_name, size_t partition_id) { BinlogOffset boffset; - if (!g_pika_server->GetTablePartitionBinlogOffset( - table_name, partition_id, &boffset)) { - LOG(WARNING) << "Partition: " << table_name << ":" << partition_id - << ", Get partition binlog offset failed"; + if (!g_pika_server->GetTablePartitionBinlogOffset(table_name, partition_id, &boffset)) { + LOG(WARNING) << "Partition: " << table_name << ":" << partition_id << ", Get partition binlog offset failed"; return Status::Corruption("Partition get binlog offset error"); } std::shared_ptr slave_partition = GetSyncSlavePartitionByName(PartitionInfo(table_name, partition_id)); if (!slave_partition) { - LOG(WARNING) << "Slave Partition: " << table_name << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Slave Partition: " << table_name << ":" << partition_id << ", NotFound"; return Status::Corruption("Slave Partition not found"); } - Status status = pika_repl_client_->SendPartitionTrySync(slave_partition->MasterIp(), - slave_partition->MasterPort(), - table_name, partition_id, boffset, - slave_partition->LocalIp()); + Status status = + pika_repl_client_->SendPartitionTrySync(slave_partition->MasterIp(), slave_partition->MasterPort(), table_name, + partition_id, boffset, slave_partition->LocalIp()); if (status.ok()) { slave_partition->SetReplState(ReplState::kWaitReply); @@ -1110,21 +1061,16 @@ Status PikaReplicaManager::SendPartitionTrySyncRequest( return status; } -Status PikaReplicaManager::SendPartitionDBSyncRequest( - const std::string& table_name, size_t partition_id) { +Status PikaReplicaManager::SendPartitionDBSyncRequest(const std::string& table_name, size_t partition_id) { BinlogOffset boffset; - if (!g_pika_server->GetTablePartitionBinlogOffset( - table_name, partition_id, &boffset)) { - LOG(WARNING) << "Partition: " << table_name << ":" << partition_id - << ", Get partition binlog offset failed"; + if (!g_pika_server->GetTablePartitionBinlogOffset(table_name, partition_id, &boffset)) { + LOG(WARNING) << "Partition: " << table_name << ":" << partition_id << ", Get partition binlog offset failed"; return Status::Corruption("Partition get binlog offset error"); } - std::shared_ptr partition = - g_pika_server->GetTablePartitionById(table_name, partition_id); + std::shared_ptr partition = g_pika_server->GetTablePartitionById(table_name, partition_id); if (!partition) { - LOG(WARNING) << "Partition: " << table_name << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Partition: " << table_name << ":" << partition_id << ", NotFound"; return Status::Corruption("Partition not found"); } partition->PrepareRsync(); @@ -1132,15 +1078,12 @@ Status PikaReplicaManager::SendPartitionDBSyncRequest( std::shared_ptr slave_partition = GetSyncSlavePartitionByName(PartitionInfo(table_name, partition_id)); if (!slave_partition) { - LOG(WARNING) << "Slave Partition: " << table_name << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Slave Partition: " << table_name << ":" << partition_id << ", NotFound"; return Status::Corruption("Slave Partition not found"); } - Status status = pika_repl_client_->SendPartitionDBSync(slave_partition->MasterIp(), - slave_partition->MasterPort(), - table_name, partition_id, boffset, - slave_partition->LocalIp()); + Status status = pika_repl_client_->SendPartitionDBSync(slave_partition->MasterIp(), slave_partition->MasterPort(), + table_name, partition_id, boffset, slave_partition->LocalIp()); Status s; if (status.ok()) { @@ -1155,35 +1098,29 @@ Status PikaReplicaManager::SendPartitionDBSyncRequest( return status; } -Status PikaReplicaManager::SendPartitionBinlogSyncAckRequest( - const std::string& table, uint32_t partition_id, - const LogOffset& ack_start, const LogOffset& ack_end, - bool is_first_send) { - std::shared_ptr slave_partition = - GetSyncSlavePartitionByName(PartitionInfo(table, partition_id)); +Status PikaReplicaManager::SendPartitionBinlogSyncAckRequest(const std::string& table, uint32_t partition_id, + const LogOffset& ack_start, const LogOffset& ack_end, + bool is_first_send) { + std::shared_ptr slave_partition = GetSyncSlavePartitionByName(PartitionInfo(table, partition_id)); if (!slave_partition) { - LOG(WARNING) << "Slave Partition: " << table << ":" << partition_id - << ", NotFound"; + LOG(WARNING) << "Slave Partition: " << table << ":" << partition_id << ", NotFound"; return Status::Corruption("Slave Partition not found"); } - return pika_repl_client_->SendPartitionBinlogSync( - slave_partition->MasterIp(), slave_partition->MasterPort(), - table, partition_id, ack_start, ack_end, slave_partition->LocalIp(), - is_first_send); + return pika_repl_client_->SendPartitionBinlogSync(slave_partition->MasterIp(), slave_partition->MasterPort(), table, + partition_id, ack_start, ack_end, slave_partition->LocalIp(), + is_first_send); } Status PikaReplicaManager::CloseReplClientConn(const std::string& ip, int32_t port) { return pika_repl_client_->Close(ip, port); } -Status PikaReplicaManager::SendSlaveBinlogChipsRequest(const std::string& ip, - int port, +Status PikaReplicaManager::SendSlaveBinlogChipsRequest(const std::string& ip, int port, const std::vector& tasks) { return pika_repl_server_->SendSlaveBinlogChips(ip, port, tasks); } -std::shared_ptr -PikaReplicaManager::GetSyncMasterPartitionByName(const PartitionInfo& p_info) { +std::shared_ptr PikaReplicaManager::GetSyncMasterPartitionByName(const PartitionInfo& p_info) { pstd::RWLock l(&partitions_rw_, false); if (sync_master_partitions_.find(p_info) == sync_master_partitions_.end()) { return nullptr; @@ -1191,8 +1128,7 @@ PikaReplicaManager::GetSyncMasterPartitionByName(const PartitionInfo& p_info) { return sync_master_partitions_[p_info]; } -std::shared_ptr -PikaReplicaManager::GetSyncSlavePartitionByName(const PartitionInfo& p_info) { +std::shared_ptr PikaReplicaManager::GetSyncSlavePartitionByName(const PartitionInfo& p_info) { pstd::RWLock l(&partitions_rw_, false); if (sync_slave_partitions_.find(p_info) == sync_slave_partitions_.end()) { return nullptr; @@ -1213,17 +1149,15 @@ Status PikaReplicaManager::RunSyncSlavePartitionStateMachine() { continue; } else if (s_partition->State() == ReplState::kWaitDBSync) { std::shared_ptr partition = - g_pika_server->GetTablePartitionById( - p_info.table_name_, p_info.partition_id_); + g_pika_server->GetTablePartitionById(p_info.table_name_, p_info.partition_id_); if (partition) { partition->TryUpdateMasterOffset(); } else { - LOG(WARNING) << "Partition not found, Table Name: " - << p_info.table_name_ << " Partition Id: " << p_info.partition_id_; + LOG(WARNING) << "Partition not found, Table Name: " << p_info.table_name_ + << " Partition Id: " << p_info.partition_id_; } - } else if (s_partition->State() == ReplState::kConnected - || s_partition->State() == ReplState::kNoConnect - || s_partition->State() == ReplState::kDBNoConnect) { + } else if (s_partition->State() == ReplState::kConnected || s_partition->State() == ReplState::kNoConnect || + s_partition->State() == ReplState::kDBNoConnect) { continue; } } @@ -1233,18 +1167,16 @@ Status PikaReplicaManager::RunSyncSlavePartitionStateMachine() { Status PikaReplicaManager::AddSyncPartitionSanityCheck(const std::set& p_infos) { pstd::RWLock l(&partitions_rw_, false); for (const auto& p_info : p_infos) { - if (sync_master_partitions_.find(p_info) != sync_master_partitions_.end() - || sync_slave_partitions_.find(p_info) != sync_slave_partitions_.end()) { + if (sync_master_partitions_.find(p_info) != sync_master_partitions_.end() || + sync_slave_partitions_.find(p_info) != sync_slave_partitions_.end()) { LOG(WARNING) << "sync partition: " << p_info.ToString() << " exist"; - return Status::Corruption("sync partition " + p_info.ToString() - + " exist"); + return Status::Corruption("sync partition " + p_info.ToString() + " exist"); } } return Status::OK(); } -Status PikaReplicaManager::AddSyncPartition( - const std::set& p_infos) { +Status PikaReplicaManager::AddSyncPartition(const std::set& p_infos) { Status s = AddSyncPartitionSanityCheck(p_infos); if (!s.ok()) { return s; @@ -1252,47 +1184,36 @@ Status PikaReplicaManager::AddSyncPartition( pstd::RWLock l(&partitions_rw_, true); for (const auto& p_info : p_infos) { - sync_master_partitions_[p_info] = - std::make_shared(p_info.table_name_, - p_info.partition_id_); - sync_slave_partitions_[p_info] = - std::make_shared(p_info.table_name_, - p_info.partition_id_); + sync_master_partitions_[p_info] = std::make_shared(p_info.table_name_, p_info.partition_id_); + sync_slave_partitions_[p_info] = std::make_shared(p_info.table_name_, p_info.partition_id_); } return Status::OK(); } -Status PikaReplicaManager::RemoveSyncPartitionSanityCheck( - const std::set& p_infos) { +Status PikaReplicaManager::RemoveSyncPartitionSanityCheck(const std::set& p_infos) { pstd::RWLock l(&partitions_rw_, false); for (const auto& p_info : p_infos) { - if (sync_master_partitions_.find(p_info) == sync_master_partitions_.end() - || sync_slave_partitions_.find(p_info) == sync_slave_partitions_.end()) { + if (sync_master_partitions_.find(p_info) == sync_master_partitions_.end() || + sync_slave_partitions_.find(p_info) == sync_slave_partitions_.end()) { LOG(WARNING) << "sync partition: " << p_info.ToString() << " not found"; - return Status::Corruption("sync partition " + p_info.ToString() - + " not found"); + return Status::Corruption("sync partition " + p_info.ToString() + " not found"); } if (sync_master_partitions_[p_info]->GetNumberOfSlaveNode() != 0) { - LOG(WARNING) << "sync master partition: " << p_info.ToString() - << " in syncing"; - return Status::Corruption("sync master partition " + p_info.ToString() - + " in syncing"); + LOG(WARNING) << "sync master partition: " << p_info.ToString() << " in syncing"; + return Status::Corruption("sync master partition " + p_info.ToString() + " in syncing"); } ReplState state = sync_slave_partitions_[p_info]->State(); if (state != kNoConnect && state != kError) { - LOG(WARNING) << "sync slave partition: " << p_info.ToString() - << " in " << ReplStateMsg[state] + " state"; - return Status::Corruption("sync slave partition " + p_info.ToString() - + " in " + ReplStateMsg[state] + " state"); + LOG(WARNING) << "sync slave partition: " << p_info.ToString() << " in " << ReplStateMsg[state] + " state"; + return Status::Corruption("sync slave partition " + p_info.ToString() + " in " + ReplStateMsg[state] + " state"); } } return Status::OK(); } -Status PikaReplicaManager::RemoveSyncPartition( - const std::set& p_infos) { +Status PikaReplicaManager::RemoveSyncPartition(const std::set& p_infos) { Status s = RemoveSyncPartitionSanityCheck(p_infos); if (!s.ok()) { return s; @@ -1314,15 +1235,13 @@ Status PikaReplicaManager::SyncTableSanityCheck(const std::string& table_name) { for (const auto& master_partition : sync_master_partitions_) { if (master_partition.first.table_name_ == table_name) { LOG(WARNING) << "sync partition: " << master_partition.first.ToString() << " exist"; - return Status::Corruption("sync partition " + master_partition.first.ToString() - + " exist"); + return Status::Corruption("sync partition " + master_partition.first.ToString() + " exist"); } } for (const auto& slave_partition : sync_slave_partitions_) { if (slave_partition.first.table_name_ == table_name) { LOG(WARNING) << "sync partition: " << slave_partition.first.ToString() << " exist"; - return Status::Corruption("sync partition " + slave_partition.first.ToString() - + " exist"); + return Status::Corruption("sync partition " + slave_partition.first.ToString() + " exist"); } } return Status::OK(); @@ -1333,7 +1252,7 @@ Status PikaReplicaManager::DelSyncTable(const std::string& table_name) { if (!s.ok()) { return s; } - std::string table_log_path = g_pika_conf->log_path() + "log_" + table_name ; + std::string table_log_path = g_pika_conf->log_path() + "log_" + table_name; std::string table_log_path_tmp = table_log_path + "_deleting/"; if (pstd::RenameFile(table_log_path, table_log_path_tmp)) { LOG(WARNING) << "Failed to move log to trash, error: " << strerror(errno); @@ -1390,15 +1309,17 @@ void PikaReplicaManager::FindCommonMaster(std::string* master) { void PikaReplicaManager::RmStatus(std::string* info) { pstd::RWLock l(&partitions_rw_, false); std::stringstream tmp_stream; - tmp_stream << "Master partition(" << sync_master_partitions_.size() << "):" << "\r\n"; + tmp_stream << "Master partition(" << sync_master_partitions_.size() << "):" + << "\r\n"; for (auto& iter : sync_master_partitions_) { - tmp_stream << " Partition " << iter.second->SyncPartitionInfo().ToString() - << "\r\n" << iter.second->ToStringStatus() << "\r\n"; + tmp_stream << " Partition " << iter.second->SyncPartitionInfo().ToString() << "\r\n" + << iter.second->ToStringStatus() << "\r\n"; } - tmp_stream << "Slave partition(" << sync_slave_partitions_.size() << "):" << "\r\n"; + tmp_stream << "Slave partition(" << sync_slave_partitions_.size() << "):" + << "\r\n"; for (auto& iter : sync_slave_partitions_) { - tmp_stream << " Partition " << iter.second->SyncPartitionInfo().ToString() - << "\r\n" << iter.second->ToStringStatus() << "\r\n"; + tmp_stream << " Partition " << iter.second->SyncPartitionInfo().ToString() << "\r\n" + << iter.second->ToStringStatus() << "\r\n"; } info->append(tmp_stream.str()); } diff --git a/src/pika_rsync_service.cc b/src/pika_rsync_service.cc index 85222f5668..15c78cde39 100644 --- a/src/pika_rsync_service.cc +++ b/src/pika_rsync_service.cc @@ -11,14 +11,12 @@ #include "pstd/include/env.h" #include "pstd/include/rsync.h" -#include "include/pika_define.h" #include "include/pika_conf.h" +#include "include/pika_define.h" -extern PikaConf *g_pika_conf; +extern PikaConf* g_pika_conf; -PikaRsyncService::PikaRsyncService(const std::string& raw_path, - const int port) - : raw_path_(raw_path), port_(port) { +PikaRsyncService::PikaRsyncService(const std::string& raw_path, const int port) : raw_path_(raw_path), port_(port) { if (raw_path_.back() != '/') { raw_path_ += "/"; } @@ -97,10 +95,6 @@ int PikaRsyncService::CreateSecretFile() { return ret; } -bool PikaRsyncService::CheckRsyncAlive() { - return pstd::FileExists(pid_path_); -} +bool PikaRsyncService::CheckRsyncAlive() { return pstd::FileExists(pid_path_); } -int PikaRsyncService::ListenPort() { - return port_; -} +int PikaRsyncService::ListenPort() { return port_; } diff --git a/src/pika_server.cc b/src/pika_server.cc index 78f6c3c908..8967fb88ad 100644 --- a/src/pika_server.cc +++ b/src/pika_server.cc @@ -5,25 +5,25 @@ #include "include/pika_server.h" -#include -#include -#include +#include #include #include -#include #include +#include +#include +#include -#include "pstd/include/env.h" -#include "pstd/include/rsync.h" +#include "net/include/bg_thread.h" #include "net/include/net_cli.h" #include "net/include/net_interfaces.h" #include "net/include/redis_cli.h" -#include "net/include/bg_thread.h" +#include "pstd/include/env.h" +#include "pstd/include/rsync.h" +#include "include/pika_cmd_table_manager.h" +#include "include/pika_dispatch_thread.h" #include "include/pika_rm.h" #include "include/pika_server.h" -#include "include/pika_dispatch_thread.h" -#include "include/pika_cmd_table_manager.h" extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; @@ -40,28 +40,26 @@ void DoPurgeDir(void* arg) { void DoDBSync(void* arg) { DBSyncArg* dbsa = reinterpret_cast(arg); PikaServer* const ps = dbsa->p; - ps->DbSyncSendFile(dbsa->ip, dbsa->port, - dbsa->table_name, dbsa->partition_id); + ps->DbSyncSendFile(dbsa->ip, dbsa->port, dbsa->table_name, dbsa->partition_id); delete dbsa; } -PikaServer::PikaServer() : - exit_(false), - slot_state_(INFREE), - have_scheduled_crontask_(false), - last_check_compact_time_({0, 0}), - master_ip_(""), - master_port_(0), - repl_state_(PIKA_REPL_NO_CONNECT), - role_(PIKA_ROLE_SINGLE), - leader_protected_mode_(false), - last_meta_sync_timestamp_(0), - first_meta_sync_(false), - loop_partition_state_machine_(false), - force_full_sync_(false), - slowlog_entry_id_(0) { - - //Init server ip host +PikaServer::PikaServer() + : exit_(false), + slot_state_(INFREE), + have_scheduled_crontask_(false), + last_check_compact_time_({0, 0}), + master_ip_(""), + master_port_(0), + repl_state_(PIKA_REPL_NO_CONNECT), + role_(PIKA_ROLE_SINGLE), + leader_protected_mode_(false), + last_meta_sync_timestamp_(0), + first_meta_sync_(false), + loop_partition_state_machine_(false), + force_full_sync_(false), + slowlog_entry_id_(0) { + // Init server ip host if (!ServerInit()) { LOG(FATAL) << "ServerInit iotcl error"; } @@ -69,8 +67,7 @@ PikaServer::PikaServer() : pthread_rwlockattr_t storage_options_rw_attr; pthread_rwlockattr_init(&storage_options_rw_attr); #if !defined(__APPLE__) - pthread_rwlockattr_setkind_np(&storage_options_rw_attr, - PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); + pthread_rwlockattr_setkind_np(&storage_options_rw_attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); #endif pthread_rwlock_init(&storage_options_rw_, &storage_options_rw_attr); @@ -79,14 +76,12 @@ PikaServer::PikaServer() : pthread_rwlockattr_t tables_rw_attr; pthread_rwlockattr_init(&tables_rw_attr); #if !defined(__APPLE__) - pthread_rwlockattr_setkind_np(&tables_rw_attr, - PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); + pthread_rwlockattr_setkind_np(&tables_rw_attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); #endif pthread_rwlock_init(&tables_rw_, &tables_rw_attr); // Create thread - worker_num_ = std::min(g_pika_conf->thread_num(), - PIKA_MAX_WORKER_THREAD_NUM); + worker_num_ = std::min(g_pika_conf->thread_num(), PIKA_MAX_WORKER_THREAD_NUM); std::set ips; if (g_pika_conf->network_interface().empty()) { @@ -98,11 +93,10 @@ PikaServer::PikaServer() : // We estimate the queue size int worker_queue_limit = g_pika_conf->maxclients() / worker_num_ + 100; LOG(INFO) << "Worker queue limit is " << worker_queue_limit; - pika_dispatch_thread_ = new PikaDispatchThread(ips, port_, worker_num_, 3000, - worker_queue_limit, g_pika_conf->max_conn_rbuf_size()); + pika_dispatch_thread_ = + new PikaDispatchThread(ips, port_, worker_num_, 3000, worker_queue_limit, g_pika_conf->max_conn_rbuf_size()); pika_monitor_thread_ = new PikaMonitorThread(); - pika_rsync_service_ = new PikaRsyncService(g_pika_conf->db_sync_path(), - g_pika_conf->port() + kPortShiftRSync); + pika_rsync_service_ = new PikaRsyncService(g_pika_conf->db_sync_path(), g_pika_conf->port() + kPortShiftRSync); pika_pubsub_thread_ = new net::PubSubThread(); pika_auxiliary_thread_ = new PikaAuxiliaryThread(); @@ -113,7 +107,6 @@ PikaServer::PikaServer() : } PikaServer::~PikaServer() { - // DispatchThread will use queue of worker thread, // so we need to delete dispatch before worker. pika_client_processor_->Stop(); @@ -123,7 +116,7 @@ PikaServer::~PikaServer() { pstd::MutexLock l(&slave_mutex_); std::vector::iterator iter = slaves_.begin(); while (iter != slaves_.end()) { - iter = slaves_.erase(iter); + iter = slaves_.erase(iter); LOG(INFO) << "Delete slave success"; } } @@ -174,8 +167,8 @@ void PikaServer::Start() { ret = pika_rsync_service_->StartRsync(); if (0 != ret) { tables_.clear(); - LOG(FATAL) << "Start Rsync Error: bind port " +std::to_string(pika_rsync_service_->ListenPort()) + " failed" - << ", Listen on this port to receive Master FullSync Data"; + LOG(FATAL) << "Start Rsync Error: bind port " + std::to_string(pika_rsync_service_->ListenPort()) + " failed" + << ", Listen on this port to receive Master FullSync Data"; } // We Init Table Struct Before Start The following thread @@ -184,13 +177,15 @@ void PikaServer::Start() { ret = pika_client_processor_->Start(); if (ret != net::kSuccess) { tables_.clear(); - LOG(FATAL) << "Start PikaClientProcessor Error: " << ret << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); + LOG(FATAL) << "Start PikaClientProcessor Error: " << ret + << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); } ret = pika_dispatch_thread_->StartThread(); if (ret != net::kSuccess) { tables_.clear(); - LOG(FATAL) << "Start Dispatch Error: " << ret << (ret == net::kBindError ? ": bind port " + std::to_string(port_) + " conflict" - : ": other error") << ", Listen on this port to handle the connected redis client"; + LOG(FATAL) << "Start Dispatch Error: " << ret + << (ret == net::kBindError ? ": bind port " + std::to_string(port_) + " conflict" : ": other error") + << ", Listen on this port to handle the connected redis client"; } ret = pika_pubsub_thread_->StartThread(); if (ret != net::kSuccess) { @@ -201,7 +196,8 @@ void PikaServer::Start() { ret = pika_auxiliary_thread_->StartThread(); if (ret != net::kSuccess) { tables_.clear(); - LOG(FATAL) << "Start Auxiliary Thread Error: " << ret << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); + LOG(FATAL) << "Start Auxiliary Thread Error: " << ret + << (ret == net::kCreateThreadError ? ": create thread error " : ": other error"); } time(&start_time_s_); @@ -210,7 +206,7 @@ void PikaServer::Start() { if (!slaveof.empty()) { int32_t sep = slaveof.find(":"); std::string master_ip = slaveof.substr(0, sep); - int32_t master_port = std::stoi(slaveof.substr(sep+1)); + int32_t master_port = std::stoi(slaveof.substr(sep + 1)); if ((master_ip == "127.0.0.1" || master_ip == host_) && master_port == port_) { LOG(FATAL) << "you will slaveof yourself as the config file, please check"; } else { @@ -230,21 +226,13 @@ void PikaServer::Start() { LOG(INFO) << "Goodbye..."; } -void PikaServer::Exit() { - exit_ = true; -} +void PikaServer::Exit() { exit_ = true; } -std::string PikaServer::host() { - return host_; -} +std::string PikaServer::host() { return host_; } -int PikaServer::port() { - return port_; -} +int PikaServer::port() { return port_; } -time_t PikaServer::start_time_s() { - return start_time_s_; -} +time_t PikaServer::start_time_s() { return start_time_s_; } std::string PikaServer::master_ip() { pstd::RWLock l(&state_protector_, false); @@ -280,8 +268,7 @@ void PikaServer::CheckLeaderProtectedMode() { bool PikaServer::readonly(const std::string& table_name, const std::string& key) { pstd::RWLock l(&state_protector_, false); - if ((role_ & PIKA_ROLE_SLAVE) - && g_pika_conf->slave_read_only()) { + if ((role_ & PIKA_ROLE_SLAVE) && g_pika_conf->slave_read_only()) { return true; } if (!g_pika_conf->classic_mode()) { @@ -290,8 +277,7 @@ bool PikaServer::readonly(const std::string& table_name, const std::string& key) // swallow this error will process later return false; } - uint32_t index = g_pika_cmd_table_manager->DistributeKey( - key, table->PartitionNum()); + uint32_t index = g_pika_cmd_table_manager->DistributeKey(key, table->PartitionNum()); int role = 0; Status s = g_pika_rm->CheckPartitionRole(table_name, index, &role); if (!s.ok()) { @@ -311,14 +297,12 @@ bool PikaServer::ConsensusCheck(const std::string& table_name, const std::string if (table == nullptr) { return false; } - uint32_t index = g_pika_cmd_table_manager->DistributeKey( - key, table->PartitionNum()); + uint32_t index = g_pika_cmd_table_manager->DistributeKey(key, table->PartitionNum()); std::shared_ptr master_partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, index)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, index)); if (!master_partition) { - LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << index - << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << table_name << ":" << index << ", NotFound"; return false; } Status s = master_partition->ConsensusSanityCheck(); @@ -352,13 +336,9 @@ std::string PikaServer::repl_state_str() { } } -bool PikaServer::force_full_sync() { - return force_full_sync_; -} +bool PikaServer::force_full_sync() { return force_full_sync_; } -void PikaServer::SetForceFullSync(bool v) { - force_full_sync_ = v; -} +void PikaServer::SetForceFullSync(bool v) { force_full_sync_ = v; } void PikaServer::SetDispatchQueueLimit(int queue_limit) { rlimit limit; @@ -370,9 +350,12 @@ void PikaServer::SetDispatchQueueLimit(int queue_limit) { limit.rlim_cur = maxfiles; limit.rlim_max = maxfiles; if (setrlimit(RLIMIT_NOFILE, &limit) != -1) { - LOG(WARNING) << "your 'limit -n ' of " << old_limit << " is not enough for Redis to start. pika have successfully reconfig it to " << limit.rlim_cur; + LOG(WARNING) << "your 'limit -n ' of " << old_limit + << " is not enough for Redis to start. pika have successfully reconfig it to " << limit.rlim_cur; } else { - LOG(FATAL) << "your 'limit -n ' of " << old_limit << " is not enough for Redis to start. pika can not reconfig it(" << strerror(errno) << "), do it by yourself"; + LOG(FATAL) << "your 'limit -n ' of " << old_limit + << " is not enough for Redis to start. pika can not reconfig it(" << strerror(errno) + << "), do it by yourself"; } } pika_dispatch_thread_->SetQueueLimit(queue_limit); @@ -391,8 +374,7 @@ void PikaServer::InitTableStruct() { for (const auto& table : table_structs) { std::string name = table.table_name; uint32_t num = table.partition_num; - std::shared_ptr
table_ptr = std::make_shared
( - name, num, db_path, log_path); + std::shared_ptr
table_ptr = std::make_shared
(name, num, db_path, log_path); table_ptr->AddPartitions(table.partition_ids); tables_.emplace(name, table_ptr); } @@ -405,11 +387,10 @@ Status PikaServer::AddTableStruct(std::string table_name, uint32_t num) { } std::string db_path = g_pika_conf->db_path(); std::string log_path = g_pika_conf->log_path(); - std::shared_ptr
table_ptr = std::make_shared
( - table_name, num, db_path, log_path); + std::shared_ptr
table_ptr = std::make_shared
(table_name, num, db_path, log_path); pstd::RWLock rwl(&tables_rw_, true); tables_.emplace(table_name, table_ptr); - return Status::OK(); + return Status::OK(); } Status PikaServer::DelTableStruct(std::string table_name) { @@ -425,10 +406,10 @@ Status PikaServer::DelTableStruct(std::string table_name) { return s; } tables_.erase(table_name); - return Status::OK(); + return Status::OK(); } -std::shared_ptr
PikaServer::GetTable(const std::string &table_name) { +std::shared_ptr
PikaServer::GetTable(const std::string& table_name) { pstd::RWLock l(&tables_rw_, false); auto iter = tables_.find(table_name); return (iter == tables_.end()) ? NULL : iter->second; @@ -480,12 +461,9 @@ bool PikaServer::IsCompacting() { return false; } -bool PikaServer::IsTableExist(const std::string& table_name) { - return GetTable(table_name) ? true : false; -} +bool PikaServer::IsTableExist(const std::string& table_name) { return GetTable(table_name) ? true : false; } -bool PikaServer::IsTablePartitionExist(const std::string& table_name, - uint32_t partition_id) { +bool PikaServer::IsTablePartitionExist(const std::string& table_name, uint32_t partition_id) { std::shared_ptr
table_ptr = GetTable(table_name); if (!table_ptr) { return false; @@ -522,8 +500,7 @@ bool PikaServer::IsTableBinlogIoError(const std::string& table_name) { Status PikaServer::DoSameThingSpecificTable(const TaskType& type, const std::set& tables) { pstd::RWLock rwl(&tables_rw_, false); for (const auto& table_item : tables_) { - if (!tables.empty() - && tables.find(table_item.first) == tables.end()) { + if (!tables.empty() && tables.find(table_item.first) == tables.end()) { continue; } else { switch (type) { @@ -564,15 +541,13 @@ Status PikaServer::DoSameThingSpecificTable(const TaskType& type, const std::set void PikaServer::PreparePartitionTrySync() { pstd::RWLock rwl(&tables_rw_, false); - ReplState state = force_full_sync_ ? - ReplState::kTryDBSync : ReplState::kTryConnect; + ReplState state = force_full_sync_ ? ReplState::kTryDBSync : ReplState::kTryConnect; for (const auto& table_item : tables_) { for (const auto& partition_item : table_item.second->partitions_) { Status s = g_pika_rm->ActivateSyncSlavePartition( - RmNode(g_pika_server->master_ip(), - g_pika_server->master_port(), - table_item.second->GetTableName(), - partition_item.second->GetPartitionId()), state); + RmNode(g_pika_server->master_ip(), g_pika_server->master_port(), table_item.second->GetTableName(), + partition_item.second->GetPartitionId()), + state); if (!s.ok()) { LOG(WARNING) << s.ToString(); } @@ -605,11 +580,10 @@ void PikaServer::PartitionSetSmallCompactionThreshold(uint32_t small_compaction_ } } -bool PikaServer::GetTablePartitionBinlogOffset(const std::string& table_name, - uint32_t partition_id, +bool PikaServer::GetTablePartitionBinlogOffset(const std::string& table_name, uint32_t partition_id, BinlogOffset* const boffset) { std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!partition) { return false; } @@ -626,16 +600,12 @@ std::shared_ptr PikaServer::GetPartitionByDbName(const std::string& d return table ? table->GetPartitionById(0) : NULL; } -std::shared_ptr PikaServer::GetTablePartitionById( - const std::string& table_name, - uint32_t partition_id) { +std::shared_ptr PikaServer::GetTablePartitionById(const std::string& table_name, uint32_t partition_id) { std::shared_ptr
table = GetTable(table_name); return table ? table->GetPartitionById(partition_id) : NULL; } -std::shared_ptr PikaServer::GetTablePartitionByKey( - const std::string& table_name, - const std::string& key) { +std::shared_ptr PikaServer::GetTablePartitionByKey(const std::string& table_name, const std::string& key) { std::shared_ptr
table = GetTable(table_name); return table ? table->GetPartitionByKey(key) : NULL; } @@ -646,33 +616,27 @@ Status PikaServer::DoSameThingEveryPartition(const TaskType& type) { for (const auto& table_item : tables_) { for (const auto& partition_item : table_item.second->partitions_) { switch (type) { - case TaskType::kResetReplState: - { - slave_partition = g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_item.second->GetTableName(), - partition_item.second->GetPartitionId())); - if (slave_partition == nullptr) { - LOG(WARNING) << "Slave Partition: " << - table_item.second->GetTableName() << ":" << - partition_item.second->GetPartitionId() << " Not Found"; - } - slave_partition->SetReplState(ReplState::kNoConnect); - break; + case TaskType::kResetReplState: { + slave_partition = g_pika_rm->GetSyncSlavePartitionByName( + PartitionInfo(table_item.second->GetTableName(), partition_item.second->GetPartitionId())); + if (slave_partition == nullptr) { + LOG(WARNING) << "Slave Partition: " << table_item.second->GetTableName() << ":" + << partition_item.second->GetPartitionId() << " Not Found"; } - case TaskType::kPurgeLog: - { - std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName( - PartitionInfo(table_item.second->GetTableName(), - partition_item.second->GetPartitionId())); - if (!partition) { - LOG(WARNING) << table_item.second->GetTableName() - << partition_item.second->GetPartitionId() << " Not Found."; - break; - } - partition->StableLogger()->PurgeStableLogs(); + slave_partition->SetReplState(ReplState::kNoConnect); + break; + } + case TaskType::kPurgeLog: { + std::shared_ptr partition = g_pika_rm->GetSyncMasterPartitionByName( + PartitionInfo(table_item.second->GetTableName(), partition_item.second->GetPartitionId())); + if (!partition) { + LOG(WARNING) << table_item.second->GetTableName() << partition_item.second->GetPartitionId() + << " Not Found."; break; } + partition->StableLogger()->PurgeStableLogs(); + break; + } case TaskType::kCompactAll: partition_item.second->Compact(storage::kAll); break; @@ -686,9 +650,7 @@ Status PikaServer::DoSameThingEveryPartition(const TaskType& type) { void PikaServer::BecomeMaster() { pstd::RWLock l(&state_protector_, true); - if ((role_ & PIKA_ROLE_MASTER) == 0 - && g_pika_conf->write_binlog() - && g_pika_conf->consensus_level() > 0) { + if ((role_ & PIKA_ROLE_MASTER) == 0 && g_pika_conf->write_binlog() && g_pika_conf->consensus_level() > 0) { LOG(INFO) << "Become new master, start protect mode to waiting binlog sync and commit"; leader_protected_mode_ = true; } @@ -725,7 +687,7 @@ void PikaServer::DeleteSlave(int fd) { if (slave_num == 0) { pstd::RWLock l(&state_protector_, true); role_ &= ~PIKA_ROLE_MASTER; - leader_protected_mode_ = false; // explicitly cancel protected mode + leader_protected_mode_ = false; // explicitly cancel protected mode } } @@ -761,27 +723,26 @@ int32_t PikaServer::GetSlaveListString(std::string& slave_list_str) { pstd::MutexLock l(&slave_mutex_); std::shared_ptr master_partition = nullptr; for (const auto& slave : slaves_) { - tmp_stream << "slave" << index++ << ":ip=" << slave.ip << ",port=" << slave.port << ",conn_fd=" << slave.conn_fd << ",lag="; + tmp_stream << "slave" << index++ << ":ip=" << slave.ip << ",port=" << slave.port << ",conn_fd=" << slave.conn_fd + << ",lag="; for (const auto& ts : slave.table_structs) { for (size_t idx = 0; idx < ts.partition_num; ++idx) { std::shared_ptr partition = - g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(ts.table_name, idx)); + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(ts.table_name, idx)); if (!partition) { - LOG(WARNING) << "Sync Master Partition: " << ts.table_name << ":" << idx - << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << ts.table_name << ":" << idx << ", NotFound"; continue; } Status s = partition->GetSlaveState(slave.ip, slave.port, &slave_state); - if (s.ok() - && slave_state == SlaveState::kSlaveBinlogSync - && partition->GetSlaveSyncBinlogInfo(slave.ip, slave.port, &sent_slave_boffset, &acked_slave_boffset).ok()) { + if (s.ok() && slave_state == SlaveState::kSlaveBinlogSync && + partition->GetSlaveSyncBinlogInfo(slave.ip, slave.port, &sent_slave_boffset, &acked_slave_boffset).ok()) { Status s = partition->Logger()->GetProducerStatus(&(master_boffset.filenum), &(master_boffset.offset)); if (!s.ok()) { continue; } else { uint64_t lag = - (uint64_t)(master_boffset.filenum - sent_slave_boffset.filenum) * g_pika_conf->binlog_file_size() - + master_boffset.offset - sent_slave_boffset.offset; + (uint64_t)(master_boffset.filenum - sent_slave_boffset.filenum) * g_pika_conf->binlog_file_size() + + master_boffset.offset - sent_slave_boffset.offset; tmp_stream << "(" << partition->PartitionName() << ":" << lag << ")"; } } else { @@ -900,13 +861,10 @@ bool PikaServer::AllPartitionConnectSuccess() { for (const auto& table_item : tables_) { for (const auto& partition_item : table_item.second->partitions_) { slave_partition = g_pika_rm->GetSyncSlavePartitionByName( - PartitionInfo(table_item.second->GetTableName(), - partition_item.second->GetPartitionId())); + PartitionInfo(table_item.second->GetTableName(), partition_item.second->GetPartitionId())); if (slave_partition == nullptr) { - LOG(WARNING) << "Slave Partition: " << - table_item.second->GetTableName() << ":" << - partition_item.second->GetPartitionId() << - ", NotFound"; + LOG(WARNING) << "Slave Partition: " << table_item.second->GetTableName() << ":" + << partition_item.second->GetPartitionId() << ", NotFound"; return false; } @@ -951,12 +909,9 @@ void PikaServer::SetFirstMetaSync(bool v) { first_meta_sync_ = v; } -void PikaServer::ScheduleClientPool(net::TaskFunc func, void* arg) { - pika_client_processor_->SchedulePool(func, arg); -} +void PikaServer::ScheduleClientPool(net::TaskFunc func, void* arg) { pika_client_processor_->SchedulePool(func, arg); } -void PikaServer::ScheduleClientBgThreads( - net::TaskFunc func, void* arg, const std::string& hash_str) { +void PikaServer::ScheduleClientBgThreads(net::TaskFunc func, void* arg, const std::string& hash_str) { pika_client_processor_->ScheduleBgThreads(func, arg, hash_str); } @@ -987,12 +942,9 @@ void PikaServer::PurgeDirTaskSchedule(void (*function)(void*), void* arg) { purge_thread_.Schedule(function, arg); } -void PikaServer::DBSync(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id) { +void PikaServer::DBSync(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id) { { - std::string task_index = - DbSyncTaskIndex(ip, port, table_name, partition_id); + std::string task_index = DbSyncTaskIndex(ip, port, table_name, partition_id); pstd::MutexLock ml(&db_sync_protector_); if (db_sync_slaves_.find(task_index) != db_sync_slaves_.end()) { return; @@ -1006,41 +958,34 @@ void PikaServer::DBSync(const std::string& ip, int port, bgsave_thread_.Schedule(&DoDBSync, reinterpret_cast(arg)); } -void PikaServer::TryDBSync(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id, int32_t top) { - std::shared_ptr partition = - GetTablePartitionById(table_name, partition_id); +void PikaServer::TryDBSync(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, + int32_t top) { + std::shared_ptr partition = GetTablePartitionById(table_name, partition_id); if (!partition) { - LOG(WARNING) << "Partition: " << partition->GetPartitionName() - << " Not Found, TryDBSync Failed"; + LOG(WARNING) << "Partition: " << partition->GetPartitionName() << " Not Found, TryDBSync Failed"; return; } - std::shared_ptr sync_partition - = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); + std::shared_ptr sync_partition = + g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name, partition_id)); if (!sync_partition) { - LOG(WARNING) << "Partition: " << sync_partition->SyncPartitionInfo().ToString() - << " Not Found, TryDBSync Failed"; + LOG(WARNING) << "Partition: " << sync_partition->SyncPartitionInfo().ToString() << " Not Found, TryDBSync Failed"; return; } BgSaveInfo bgsave_info = partition->bgsave_info(); std::string logger_filename = sync_partition->Logger()->filename(); - if (pstd::IsDir(bgsave_info.path) != 0 - || !pstd::FileExists(NewFileName(logger_filename, bgsave_info.offset.b_offset.filenum)) - || top - bgsave_info.offset.b_offset.filenum > kDBSyncMaxGap) { + if (pstd::IsDir(bgsave_info.path) != 0 || + !pstd::FileExists(NewFileName(logger_filename, bgsave_info.offset.b_offset.filenum)) || + top - bgsave_info.offset.b_offset.filenum > kDBSyncMaxGap) { // Need Bgsave first partition->BgSavePartition(); } DBSync(ip, port, table_name, partition_id); } -void PikaServer::DbSyncSendFile(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id) { +void PikaServer::DbSyncSendFile(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id) { std::shared_ptr partition = GetTablePartitionById(table_name, partition_id); if (!partition) { - LOG(WARNING) << "Partition: " << partition->GetPartitionName() - << " Not Found, DbSync send file Failed"; + LOG(WARNING) << "Partition: " << partition->GetPartitionName() << " Not Found, DbSync send file Failed"; return; } @@ -1054,15 +999,14 @@ void PikaServer::DbSyncSendFile(const std::string& ip, int port, // Get all files need to send std::vector descendant; int ret = 0; - LOG(INFO) << "Partition: " << partition->GetPartitionName() - << " Start Send files in " << bg_path << " to " << ip; + LOG(INFO) << "Partition: " << partition->GetPartitionName() << " Start Send files in " << bg_path << " to " << ip; ret = pstd::GetChildren(bg_path, descendant); if (ret != 0) { std::string ip_port = pstd::IpPortString(ip, port); pstd::MutexLock ldb(&db_sync_protector_); db_sync_slaves_.erase(ip_port); LOG(WARNING) << "Partition: " << partition->GetPartitionName() - << " Get child directory when try to do sync failed, error: " << strerror(ret); + << " Get child directory when try to do sync failed, error: " << strerror(ret); return; } @@ -1084,8 +1028,7 @@ void PikaServer::DbSyncSendFile(const std::string& ip, int port, continue; } - if (pstd::IsDir(local_path) == 0 && - local_path.back() != '/') { + if (pstd::IsDir(local_path) == 0 && local_path.back() != '/') { local_path.push_back('/'); target_path.push_back('/'); } @@ -1093,11 +1036,8 @@ void PikaServer::DbSyncSendFile(const std::string& ip, int port, // We need specify the speed limit for every single file ret = pstd::RsyncSendFile(local_path, target_path, secret_file_path, remote); if (0 != ret) { - LOG(WARNING) << "Partition: " << partition->GetPartitionName() - << " RSync send file failed! From: " << *iter - << ", To: " << target_path - << ", At: " << ip << ":" << port - << ", Error: " << ret; + LOG(WARNING) << "Partition: " << partition->GetPartitionName() << " RSync send file failed! From: " << *iter + << ", To: " << target_path << ", At: " << ip << ":" << port << ", Error: " << ret; break; } } @@ -1113,13 +1053,13 @@ void PikaServer::DbSyncSendFile(const std::string& ip, int port, if (cli->Connect(ip, port, "").ok()) { struct sockaddr_in laddr; socklen_t llen = sizeof(laddr); - getsockname(cli->fd(), (struct sockaddr*) &laddr, &llen); + getsockname(cli->fd(), (struct sockaddr*)&laddr, &llen); lip = inet_ntoa(laddr.sin_addr); cli->Close(); delete cli; } else { LOG(WARNING) << "Rsync try connect slave rsync service error" - << ", slave rsync service(" << ip << ":" << port << ")"; + << ", slave rsync service(" << ip << ":" << port << ")"; delete cli; } @@ -1142,14 +1082,14 @@ void PikaServer::DbSyncSendFile(const std::string& ip, int port, if (ret != 0) { LOG(WARNING) << "Partition: " << partition->GetPartitionName() << " Send Modified Info File Failed"; } - } else if (0 != (ret = pstd::RsyncSendFile(bg_path + "/" + kBgsaveInfoFile, remote_path + "/" + kBgsaveInfoFile, secret_file_path, remote))) { + } else if (0 != (ret = pstd::RsyncSendFile(bg_path + "/" + kBgsaveInfoFile, remote_path + "/" + kBgsaveInfoFile, + secret_file_path, remote))) { LOG(WARNING) << "Partition: " << partition->GetPartitionName() << " Send Info File Failed"; } } // remove slave { - std::string task_index = - DbSyncTaskIndex(ip, port, table_name, partition_id); + std::string task_index = DbSyncTaskIndex(ip, port, table_name, partition_id); pstd::MutexLock ml(&db_sync_protector_); db_sync_slaves_.erase(task_index); } @@ -1159,13 +1099,10 @@ void PikaServer::DbSyncSendFile(const std::string& ip, int port, } } -std::string PikaServer::DbSyncTaskIndex(const std::string& ip, - int port, - const std::string& table_name, +std::string PikaServer::DbSyncTaskIndex(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id) { char buf[256]; - snprintf(buf, sizeof(buf), "%s:%d_%s:%d", - ip.data(), port, table_name.data(), partition_id); + snprintf(buf, sizeof(buf), "%s:%d_%s:%d", ip.data(), port, table_name.data(), partition_id); return buf; } @@ -1179,24 +1116,21 @@ void PikaServer::ClientKillAll() { pika_monitor_thread_->ThreadClientKill(); } -int PikaServer::ClientKill(const std::string &ip_port) { - if (pika_dispatch_thread_->ClientKill(ip_port) - || pika_monitor_thread_->ThreadClientKill(ip_port)) { +int PikaServer::ClientKill(const std::string& ip_port) { + if (pika_dispatch_thread_->ClientKill(ip_port) || pika_monitor_thread_->ThreadClientKill(ip_port)) { return 1; } return 0; } -int64_t PikaServer::ClientList(std::vector *clients) { +int64_t PikaServer::ClientList(std::vector* clients) { int64_t clients_num = 0; clients_num += pika_dispatch_thread_->ThreadClientList(clients); clients_num += pika_monitor_thread_->ThreadClientList(clients); return clients_num; } -bool PikaServer::HasMonitorClients() { - return pika_monitor_thread_->HasMonitorClients(); -} +bool PikaServer::HasMonitorClients() { return pika_monitor_thread_->HasMonitorClients(); } void PikaServer::AddMonitorMessage(const std::string& monitor_message) { pika_monitor_thread_->AddMonitorMessage(monitor_message); @@ -1238,8 +1172,7 @@ void PikaServer::SlowlogObtain(int64_t number, std::vector* slowlo void PikaServer::SlowlogPushEntry(const PikaCmdArgsType& argv, int32_t time, int64_t duration) { SlowlogEntry entry; - uint32_t slargc = (argv.size() < SLOWLOG_ENTRY_MAX_ARGC) - ? argv.size() : SLOWLOG_ENTRY_MAX_ARGC; + uint32_t slargc = (argv.size() < SLOWLOG_ENTRY_MAX_ARGC) ? argv.size() : SLOWLOG_ENTRY_MAX_ARGC; for (uint32_t idx = 0; idx < slargc; ++idx) { if (slargc != argv.size() && idx == slargc - 1) { @@ -1275,21 +1208,13 @@ void PikaServer::ResetStat() { statistic_.server_stat.qps.last_querynum.store(0); } -uint64_t PikaServer::ServerQueryNum() { - return statistic_.server_stat.qps.querynum.load(); -} +uint64_t PikaServer::ServerQueryNum() { return statistic_.server_stat.qps.querynum.load(); } -uint64_t PikaServer::ServerCurrentQps() { - return statistic_.server_stat.qps.last_sec_querynum.load(); -} +uint64_t PikaServer::ServerCurrentQps() { return statistic_.server_stat.qps.last_sec_querynum.load(); } -uint64_t PikaServer::accumulative_connections() { - return statistic_.server_stat.accumulative_connections.load(); -} +uint64_t PikaServer::accumulative_connections() { return statistic_.server_stat.accumulative_connections.load(); } -void PikaServer::incr_accumulative_connections() { - ++(statistic_.server_stat.accumulative_connections); -} +void PikaServer::incr_accumulative_connections() { ++(statistic_.server_stat.accumulative_connections); } // only one thread invoke this right now void PikaServer::ResetLastSecQuerynum() { @@ -1297,8 +1222,8 @@ void PikaServer::ResetLastSecQuerynum() { statistic_.ResetTableLastSecQuerynum(); } -void PikaServer::UpdateQueryNumAndExecCountTable(const std::string& table_name, - const std::string& command, bool is_write) { +void PikaServer::UpdateQueryNumAndExecCountTable(const std::string& table_name, const std::string& command, + bool is_write) { std::string cmd(command); statistic_.server_stat.qps.querynum++; statistic_.server_stat.exec_count_table[pstd::StringToUpper(cmd)]++; @@ -1313,18 +1238,11 @@ std::unordered_map PikaServer::ServerExecCountTable() { return res; } -QpsStatistic PikaServer::ServerTableStat(const std::string& table_name) { - return statistic_.TableStat(table_name); -} - -std::unordered_map PikaServer::ServerAllTableStat() { - return statistic_.AllTableStat(); -} +QpsStatistic PikaServer::ServerTableStat(const std::string& table_name) { return statistic_.TableStat(table_name); } +std::unordered_map PikaServer::ServerAllTableStat() { return statistic_.AllTableStat(); } -int PikaServer::SendToPeer() { - return g_pika_rm->ConsumeWriteQueue(); -} +int PikaServer::SendToPeer() { return g_pika_rm->ConsumeWriteQueue(); } void PikaServer::SignalAuxiliary() { pika_auxiliary_thread_->mu_.Lock(); @@ -1332,13 +1250,9 @@ void PikaServer::SignalAuxiliary() { pika_auxiliary_thread_->mu_.Unlock(); } -Status PikaServer::TriggerSendBinlogSync() { - return g_pika_rm->WakeUpBinlogSync(); -} +Status PikaServer::TriggerSendBinlogSync() { return g_pika_rm->WakeUpBinlogSync(); } -int PikaServer::PubSubNumPat() { - return pika_pubsub_thread_->PubSubNumPat(); -} +int PikaServer::PubSubNumPat() { return pika_pubsub_thread_->PubSubNumPat(); } int PikaServer::Publish(const std::string& channel, const std::string& msg) { int receivers = pika_pubsub_thread_->Publish(channel, msg); @@ -1349,28 +1263,23 @@ void PikaServer::EnablePublish(int fd) { pika_pubsub_thread_->UpdateConnReadyState(fd, net::PubSubThread::ReadyState::kReady); } -int PikaServer::UnSubscribe(std::shared_ptr conn, - const std::vector& channels, - bool pattern, +int PikaServer::UnSubscribe(std::shared_ptr conn, const std::vector& channels, bool pattern, std::vector>* result) { int subscribed = pika_pubsub_thread_->UnSubscribe(conn, channels, pattern, result); return subscribed; } -void PikaServer::Subscribe(std::shared_ptr conn, - const std::vector& channels, - bool pattern, +void PikaServer::Subscribe(std::shared_ptr conn, const std::vector& channels, bool pattern, std::vector>* result) { pika_pubsub_thread_->Subscribe(conn, channels, pattern, result); } -void PikaServer::PubSubChannels(const std::string& pattern, - std::vector* result) { +void PikaServer::PubSubChannels(const std::string& pattern, std::vector* result) { pika_pubsub_thread_->PubSubChannels(pattern, result); } void PikaServer::PubSubNumSub(const std::vector& channels, - std::vector>* result) { + std::vector>* result) { pika_pubsub_thread_->PubSubNumSub(channels, result); } @@ -1405,23 +1314,23 @@ void PikaServer::AutoCompactRange() { if (ci != "") { std::string::size_type slash = ci.find("/"); int interval = std::atoi(ci.substr(0, slash).c_str()); - int usage = std::atoi(ci.substr(slash+1).c_str()); + int usage = std::atoi(ci.substr(slash + 1).c_str()); struct timeval now; gettimeofday(&now, NULL); - if (last_check_compact_time_.tv_sec == 0 || - now.tv_sec - last_check_compact_time_.tv_sec >= interval * 3600) { + if (last_check_compact_time_.tv_sec == 0 || now.tv_sec - last_check_compact_time_.tv_sec >= interval * 3600) { gettimeofday(&last_check_compact_time_, NULL); if (((double)free_size / total_size) * 100 >= usage) { Status s = DoSameThingSpecificTable(TaskType::kCompactAll); if (s.ok()) { - LOG(INFO) << "[Interval]schedule compactRange, freesize: " << free_size/1048576 << "MB, disksize: " << total_size/1048576 << "MB"; + LOG(INFO) << "[Interval]schedule compactRange, freesize: " << free_size / 1048576 + << "MB, disksize: " << total_size / 1048576 << "MB"; } else { - LOG(INFO) << "[Interval]schedule compactRange Failed, freesize: " << free_size/1048576 << "MB, disksize: " << total_size/1048576 - << "MB, error: " << s.ToString(); + LOG(INFO) << "[Interval]schedule compactRange Failed, freesize: " << free_size / 1048576 + << "MB, disksize: " << total_size / 1048576 << "MB, error: " << s.ToString(); } } else { LOG(WARNING) << "compact-interval failed, because there is not enough disk space left, freesize" - << free_size/1048576 << "MB, disksize: " << total_size/1048576 << "MB"; + << free_size / 1048576 << "MB, disksize: " << total_size / 1048576 << "MB"; } } return; @@ -1444,16 +1353,16 @@ void PikaServer::AutoCompactRange() { std::string::size_type underline = compact_cron.find("/"); int week = have_week ? (std::atoi(week_str.c_str()) % 7) : 0; int start = std::atoi(compact_cron.substr(0, colon).c_str()); - int end = std::atoi(compact_cron.substr(colon+1, underline).c_str()); - int usage = std::atoi(compact_cron.substr(underline+1).c_str()); + int end = std::atoi(compact_cron.substr(colon + 1, underline).c_str()); + int usage = std::atoi(compact_cron.substr(underline + 1).c_str()); std::time_t t = std::time(nullptr); std::tm* t_m = std::localtime(&t); bool in_window = false; if (start < end && (t_m->tm_hour >= start && t_m->tm_hour < end)) { in_window = have_week ? (week == t_m->tm_wday) : true; - } else if (start > end && ((t_m->tm_hour >= start && t_m->tm_hour < 24) || - (t_m->tm_hour >= 0 && t_m->tm_hour < end))) { + } else if (start > end && + ((t_m->tm_hour >= start && t_m->tm_hour < 24) || (t_m->tm_hour >= 0 && t_m->tm_hour < end))) { in_window = have_week ? false : true; } else { have_scheduled_crontask_ = false; @@ -1463,23 +1372,22 @@ void PikaServer::AutoCompactRange() { if (((double)free_size / total_size) * 100 >= usage) { Status s = DoSameThingEveryPartition(TaskType::kCompactAll); if (s.ok()) { - LOG(INFO) << "[Cron]schedule compactRange, freesize: " << free_size/1048576 << "MB, disksize: " << total_size/1048576 << "MB"; + LOG(INFO) << "[Cron]schedule compactRange, freesize: " << free_size / 1048576 + << "MB, disksize: " << total_size / 1048576 << "MB"; } else { - LOG(INFO) << "[Cron]schedule compactRange Failed, freesize: " << free_size/1048576 << "MB, disksize: " << total_size/1048576 - << "MB, error: " << s.ToString(); + LOG(INFO) << "[Cron]schedule compactRange Failed, freesize: " << free_size / 1048576 + << "MB, disksize: " << total_size / 1048576 << "MB, error: " << s.ToString(); } have_scheduled_crontask_ = true; } else { LOG(WARNING) << "compact-cron failed, because there is not enough disk space left, freesize" - << free_size/1048576 << "MB, disksize: " << total_size/1048576 << "MB"; + << free_size / 1048576 << "MB, disksize: " << total_size / 1048576 << "MB"; } } } } -void PikaServer::AutoPurge() { - DoSameThingEveryPartition(TaskType::kPurgeLog); -} +void PikaServer::AutoPurge() { DoSameThingEveryPartition(TaskType::kPurgeLog); } void PikaServer::AutoDeleteExpiredDump() { std::string db_sync_prefix = g_pika_conf->bgsave_prefix(); @@ -1503,12 +1411,13 @@ void PikaServer::AutoDeleteExpiredDump() { } // Handle dump directory for (size_t i = 0; i < dump_dir.size(); i++) { - if (dump_dir[i].substr(0, db_sync_prefix.size()) != db_sync_prefix || dump_dir[i].size() != (db_sync_prefix.size() + 8)) { + if (dump_dir[i].substr(0, db_sync_prefix.size()) != db_sync_prefix || + dump_dir[i].size() != (db_sync_prefix.size() + 8)) { continue; } std::string str_date = dump_dir[i].substr(db_sync_prefix.size(), (dump_dir[i].size() - db_sync_prefix.size())); - char *end = NULL; + char* end = NULL; std::strtol(str_date.c_str(), &end, 10); if (*end != 0) { continue; @@ -1520,7 +1429,7 @@ void PikaServer::AutoDeleteExpiredDump() { int dump_day = std::atoi(str_date.substr(6, 2).c_str()); time_t t = time(NULL); - struct tm *now = localtime(&t); + struct tm* now = localtime(&t); int now_year = now->tm_year + 1900; int now_month = now->tm_mon + 1; int now_day = now->tm_mday; @@ -1574,37 +1483,25 @@ void PikaServer::InitStorageOptions() { storage_options_.options.max_manifest_file_size = 64 * 1024 * 1024; storage_options_.options.max_log_file_size = 512 * 1024 * 1024; - storage_options_.options.write_buffer_size = - g_pika_conf->write_buffer_size(); - storage_options_.options.arena_block_size = - g_pika_conf->arena_block_size(); + storage_options_.options.write_buffer_size = g_pika_conf->write_buffer_size(); + storage_options_.options.arena_block_size = g_pika_conf->arena_block_size(); storage_options_.options.write_buffer_manager.reset( - new rocksdb::WriteBufferManager(g_pika_conf->max_write_buffer_size())); - storage_options_.options.max_write_buffer_number = - g_pika_conf->max_write_buffer_number(); - storage_options_.options.target_file_size_base = - g_pika_conf->target_file_size_base(); - storage_options_.options.max_background_flushes = - g_pika_conf->max_background_flushes(); - storage_options_.options.max_background_compactions = - g_pika_conf->max_background_compactions(); - storage_options_.options.max_open_files = - g_pika_conf->max_cache_files(); - storage_options_.options.max_bytes_for_level_multiplier = - g_pika_conf->max_bytes_for_level_multiplier(); - storage_options_.options.optimize_filters_for_hits = - g_pika_conf->optimize_filters_for_hits(); - storage_options_.options.level_compaction_dynamic_level_bytes = - g_pika_conf->level_compaction_dynamic_level_bytes(); - - storage_options_.options.compression = - PikaConf::GetCompression(g_pika_conf->compression()); - storage_options_.options.compression_per_level = - g_pika_conf->compression_per_level(); - - //default l0 l1 noCompression l2 and more use `compression` option - if (storage_options_.options.compression_per_level.empty() - && storage_options_.options.compression != rocksdb::kNoCompression) { + new rocksdb::WriteBufferManager(g_pika_conf->max_write_buffer_size())); + storage_options_.options.max_write_buffer_number = g_pika_conf->max_write_buffer_number(); + storage_options_.options.target_file_size_base = g_pika_conf->target_file_size_base(); + storage_options_.options.max_background_flushes = g_pika_conf->max_background_flushes(); + storage_options_.options.max_background_compactions = g_pika_conf->max_background_compactions(); + storage_options_.options.max_open_files = g_pika_conf->max_cache_files(); + storage_options_.options.max_bytes_for_level_multiplier = g_pika_conf->max_bytes_for_level_multiplier(); + storage_options_.options.optimize_filters_for_hits = g_pika_conf->optimize_filters_for_hits(); + storage_options_.options.level_compaction_dynamic_level_bytes = g_pika_conf->level_compaction_dynamic_level_bytes(); + + storage_options_.options.compression = PikaConf::GetCompression(g_pika_conf->compression()); + storage_options_.options.compression_per_level = g_pika_conf->compression_per_level(); + + // default l0 l1 noCompression l2 and more use `compression` option + if (storage_options_.options.compression_per_level.empty() && + storage_options_.options.compression != rocksdb::kNoCompression) { storage_options_.options.compression_per_level.push_back(rocksdb::kNoCompression); storage_options_.options.compression_per_level.push_back(rocksdb::kNoCompression); storage_options_.options.compression_per_level.push_back(storage_options_.options.compression); @@ -1612,8 +1509,7 @@ void PikaServer::InitStorageOptions() { // For rocksdb::BlockBasedTableOptions storage_options_.table_options.block_size = g_pika_conf->block_size(); - storage_options_.table_options.cache_index_and_filter_blocks = - g_pika_conf->cache_index_and_filter_blocks(); + storage_options_.table_options.cache_index_and_filter_blocks = g_pika_conf->cache_index_and_filter_blocks(); storage_options_.block_cache_size = g_pika_conf->block_cache(); storage_options_.share_block_cache = g_pika_conf->share_block_cache(); @@ -1624,24 +1520,23 @@ void PikaServer::InitStorageOptions() { storage_options_.table_options.no_block_cache = true; } else if (storage_options_.share_block_cache) { storage_options_.table_options.block_cache = - rocksdb::NewLRUCache(storage_options_.block_cache_size, g_pika_conf->num_shard_bits()); + rocksdb::NewLRUCache(storage_options_.block_cache_size, g_pika_conf->num_shard_bits()); } storage_options_.options.rate_limiter = - std::shared_ptr(rocksdb::NewGenericRateLimiter(g_pika_conf->rate_limiter_bandwidth())); + std::shared_ptr(rocksdb::NewGenericRateLimiter(g_pika_conf->rate_limiter_bandwidth())); // For Storage small compaction storage_options_.statistics_max_size = g_pika_conf->max_cache_statistic_keys(); - storage_options_.small_compaction_threshold = - g_pika_conf->small_compaction_threshold(); + storage_options_.small_compaction_threshold = g_pika_conf->small_compaction_threshold(); } storage::Status PikaServer::RewriteStorageOptions(const storage::OptionType& option_type, - const std::unordered_map& options_map) { + const std::unordered_map& options_map) { storage::Status s; for (const auto& table_item : tables_) { pstd::RWLock partition_rwl(&table_item.second->partitions_rw_, true); - for (const auto& partition_item: table_item.second->partitions_) { + for (const auto& partition_item : table_item.second->partitions_) { partition_item.second->DbRWLockWriter(); s = partition_item.second->db()->SetOptions(option_type, storage::ALL_DB, options_map); partition_item.second->DbRWUnLock(); @@ -1653,7 +1548,8 @@ storage::Status PikaServer::RewriteStorageOptions(const storage::OptionType& opt return s; } -Status PikaServer::GetCmdRouting(std::vector& redis_cmds, std::vector* dst, bool* all_local) { +Status PikaServer::GetCmdRouting(std::vector& redis_cmds, std::vector* dst, + bool* all_local) { UNUSED(redis_cmds); UNUSED(dst); *all_local = true; diff --git a/src/pika_set.cc b/src/pika_set.cc index aee9b5563f..9bfebf11b1 100644 --- a/src/pika_set.cc +++ b/src/pika_set.cc @@ -14,7 +14,7 @@ void SAddCmd::DoInitial() { } key_ = argv_[1]; PikaCmdArgsType::iterator iter = argv_.begin(); - iter++; + iter++; iter++; members_.assign(iter, argv_.end()); return; @@ -111,8 +111,7 @@ void SScanCmd::DoInitial() { size_t argc = argv_.size(), index = 3; while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "count")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "count")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -364,7 +363,8 @@ void SRandmemberCmd::DoInitial() { if (!pstd::string2int(argv_[2].data(), argv_[2].size(), &count_)) { res_.SetRes(CmdRes::kInvalidInt); } else { - reply_arr = true;; + reply_arr = true; + ; } } return; diff --git a/src/pika_slave_node.cc b/src/pika_slave_node.cc index 3ad3097643..8a4bf47bd3 100644 --- a/src/pika_slave_node.cc +++ b/src/pika_slave_node.cc @@ -7,7 +7,7 @@ #include "include/pika_conf.h" -extern PikaConf *g_pika_conf; +extern PikaConf* g_pika_conf; /* SyncWindow */ @@ -16,8 +16,7 @@ void SyncWindow::Push(const SyncWinItem& item) { total_size_ += item.binlog_size_; } -bool SyncWindow::Update(const SyncWinItem& start_item, - const SyncWinItem& end_item, LogOffset* acked_offset) { +bool SyncWindow::Update(const SyncWinItem& start_item, const SyncWinItem& end_item, LogOffset* acked_offset) { size_t start_pos = win_.size(), end_pos = win_.size(); for (size_t i = 0; i < win_.size(); ++i) { if (win_[i] == start_item) { @@ -29,10 +28,10 @@ bool SyncWindow::Update(const SyncWinItem& start_item, } } if (start_pos == win_.size() || end_pos == win_.size()) { - LOG(WARNING) << "Ack offset Start: " << - start_item.ToString() << "End: " << end_item.ToString() << - " not found in binlog controller window." << - std::endl << "window status "<< std::endl << ToStringStatus(); + LOG(WARNING) << "Ack offset Start: " << start_item.ToString() << "End: " << end_item.ToString() + << " not found in binlog controller window." << std::endl + << "window status " << std::endl + << ToStringStatus(); return false; } for (size_t i = start_pos; i <= end_pos; ++i) { @@ -52,24 +51,22 @@ bool SyncWindow::Update(const SyncWinItem& start_item, int SyncWindow::Remaining() { std::size_t remaining_size = g_pika_conf->sync_window_size() - win_.size(); - return remaining_size > 0? remaining_size:0 ; + return remaining_size > 0 ? remaining_size : 0; } /* SlaveNode */ -SlaveNode::SlaveNode(const std::string& ip, int port, - const std::string& table_name, - uint32_t partition_id, int session_id) - : RmNode(ip, port, table_name, partition_id, session_id), - slave_state(kSlaveNotSync), - b_state(kNotSync), sent_offset(), acked_offset() { -} +SlaveNode::SlaveNode(const std::string& ip, int port, const std::string& table_name, uint32_t partition_id, + int session_id) + : RmNode(ip, port, table_name, partition_id, session_id), + slave_state(kSlaveNotSync), + b_state(kNotSync), + sent_offset(), + acked_offset() {} -SlaveNode::~SlaveNode() { -} +SlaveNode::~SlaveNode() {} -Status SlaveNode::InitBinlogFileReader(const std::shared_ptr& binlog, - const BinlogOffset& offset) { +Status SlaveNode::InitBinlogFileReader(const std::shared_ptr& binlog, const BinlogOffset& offset) { binlog_reader = std::make_shared(); int res = binlog_reader->Seek(binlog, offset.filenum, offset.offset); if (res) { @@ -82,7 +79,9 @@ std::string SlaveNode::ToStringStatus() { std::stringstream tmp_stream; tmp_stream << " Slave_state: " << SlaveStateMsg[slave_state] << "\r\n"; tmp_stream << " Binlog_sync_state: " << BinlogSyncStateMsg[b_state] << "\r\n"; - tmp_stream << " Sync_window: " << "\r\n" << sync_win.ToStringStatus(); + tmp_stream << " Sync_window: " + << "\r\n" + << sync_win.ToStringStatus(); tmp_stream << " Sent_offset: " << sent_offset.ToString() << "\r\n"; tmp_stream << " Acked_offset: " << acked_offset.ToString() << "\r\n"; tmp_stream << " Binlog_reader activated: " << (binlog_reader != nullptr) << "\r\n"; diff --git a/src/pika_slot.cc b/src/pika_slot.cc index fe335a46d7..4462e17cd8 100644 --- a/src/pika_slot.cc +++ b/src/pika_slot.cc @@ -3,11 +3,11 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. -#include "include/pika_rm.h" #include "include/pika_slot.h" -#include "include/pika_table.h" -#include "include/pika_server.h" #include "include/pika_cmd_table_manager.h" +#include "include/pika_rm.h" +#include "include/pika_server.h" +#include "include/pika_table.h" extern PikaCmdTableManager* g_pika_cmd_table_manager; extern PikaReplicaManager* g_pika_rm; @@ -123,7 +123,7 @@ void SlotsMgrtTagSlotAsyncCmd::DoInitial() { return; } - PikaCmdArgsType::const_iterator it = argv_.begin() + 1; //Remember the first args is the opt name + PikaCmdArgsType::const_iterator it = argv_.begin() + 1; // Remember the first args is the opt name dest_ip_ = *it++; pstd::StringToLower(dest_ip_); @@ -152,8 +152,8 @@ void SlotsMgrtTagSlotAsyncCmd::DoInitial() { return; } - if (!pstd::string2int(str_slot_num.data(), str_slot_num.size(), &slot_num_) - || slot_num_ < 0 || slot_num_ >= table->PartitionNum()) { + if (!pstd::string2int(str_slot_num.data(), str_slot_num.size(), &slot_num_) || slot_num_ < 0 || + slot_num_ >= table->PartitionNum()) { res_.SetRes(CmdRes::kInvalidInt, kCmdNameSlotsMgrtTagSlotAsync); return; } @@ -175,8 +175,7 @@ void SlotsMgrtTagSlotAsyncCmd::Do(std::shared_ptr partition) { std::shared_ptr master_partition = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name_, slot_num_)); if (!master_partition) { - LOG(WARNING) << "Sync Master Partition: " << table_name_ << ":" << slot_num_ - << ", NotFound"; + LOG(WARNING) << "Sync Master Partition: " << table_name_ << ":" << slot_num_ << ", NotFound"; res_.SetRes(CmdRes::kNotFound, kCmdNameSlotsMgrtTagSlotAsync); return; } @@ -217,8 +216,7 @@ void SlotsScanCmd::DoInitial() { while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "count")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "count")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -251,8 +249,7 @@ void SlotsScanCmd::Do(std::shared_ptr partition) { return; } std::vector keys; - int64_t cursor_ret = cur_partition->db()->Scan(storage::DataType::kAll, - cursor_, pattern_, count_, &keys); + int64_t cursor_ret = cur_partition->db()->Scan(storage::DataType::kAll, cursor_, pattern_, count_, &keys); res_.AppendArrayLen(2); @@ -337,7 +334,7 @@ void SlotsMgrtExecWrapperCmd::DoInitial() { PikaCmdArgsType::const_iterator it = argv_.begin() + 1; key_ = *it++; - //pstd::StringToLower(key_); + // pstd::StringToLower(key_); return; } @@ -416,9 +413,7 @@ void SlotsMgrtSlotCmd::DoInitial() { return; } -void SlotsMgrtSlotCmd::Do(std::shared_ptr partition) { - return; -} +void SlotsMgrtSlotCmd::Do(std::shared_ptr partition) { return; } // slotsmgrttagslot host port timeout slot void SlotsMgrtTagSlotCmd::DoInitial() { @@ -426,9 +421,7 @@ void SlotsMgrtTagSlotCmd::DoInitial() { return; } -void SlotsMgrtTagSlotCmd::Do(std::shared_ptr partition) { - return; -} +void SlotsMgrtTagSlotCmd::Do(std::shared_ptr partition) { return; } // slotsmgrtone host port timeout key void SlotsMgrtOneCmd::DoInitial() { @@ -436,9 +429,7 @@ void SlotsMgrtOneCmd::DoInitial() { return; } -void SlotsMgrtOneCmd::Do(std::shared_ptr partition) { - return; -} +void SlotsMgrtOneCmd::Do(std::shared_ptr partition) { return; } // slotsmgrttagone host port timeout key void SlotsMgrtTagOneCmd::DoInitial() { @@ -446,6 +437,4 @@ void SlotsMgrtTagOneCmd::DoInitial() { return; } -void SlotsMgrtTagOneCmd::Do(std::shared_ptr partition) { - return; -} +void SlotsMgrtTagOneCmd::Do(std::shared_ptr partition) { return; } diff --git a/src/pika_stable_log.cc b/src/pika_stable_log.cc index 81f03474bb..6ed0062274 100644 --- a/src/pika_stable_log.cc +++ b/src/pika_stable_log.cc @@ -8,8 +8,8 @@ #include #include "include/pika_conf.h" -#include "include/pika_server.h" #include "include/pika_rm.h" +#include "include/pika_server.h" #include "pstd/include/env.h" @@ -17,14 +17,9 @@ extern PikaConf* g_pika_conf; extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; -StableLog::StableLog(const std::string table_name, - uint32_t partition_id, const std::string& log_path) : - purging_(false), - table_name_(table_name), - partition_id_(partition_id), - log_path_(log_path) { - stable_logger_ = std::shared_ptr( - new Binlog(log_path_, g_pika_conf->binlog_file_size())); +StableLog::StableLog(const std::string table_name, uint32_t partition_id, const std::string& log_path) + : purging_(false), table_name_(table_name), partition_id_(partition_id), log_path_(log_path) { + stable_logger_ = std::shared_ptr(new Binlog(log_path_, g_pika_conf->binlog_file_size())); pthread_rwlock_init(&offset_rwlock_, NULL); std::map binlogs; if (!GetBinlogFiles(&binlogs)) { @@ -35,18 +30,14 @@ StableLog::StableLog(const std::string table_name, } } -StableLog::~StableLog() { - pthread_rwlock_destroy(&offset_rwlock_); -} +StableLog::~StableLog() { pthread_rwlock_destroy(&offset_rwlock_); } void StableLog::Leave() { Close(); RemoveStableLogDir(); } -void StableLog::Close() { - stable_logger_->Close(); -} +void StableLog::Close() { stable_logger_->Close(); } void StableLog::RemoveStableLogDir() { std::string logpath = log_path_; @@ -60,8 +51,7 @@ void StableLog::RemoveStableLogDir() { } g_pika_server->PurgeDir(logpath); - LOG(WARNING) << "Partition StableLog: " << table_name_ << ":" << partition_id_ - << " move to trash success"; + LOG(WARNING) << "Partition StableLog: " << table_name_ << ":" << partition_id_ << " move to trash success"; } bool StableLog::PurgeStableLogs(uint32_t to, bool manual) { @@ -71,18 +61,15 @@ bool StableLog::PurgeStableLogs(uint32_t to, bool manual) { LOG(WARNING) << "purge process already exist"; return false; } - PurgeStableLogArg *arg = new PurgeStableLogArg(); + PurgeStableLogArg* arg = new PurgeStableLogArg(); arg->to = to; arg->manual = manual; arg->logger = shared_from_this(); - g_pika_server-> - PurgelogsTaskSchedule(&DoPurgeStableLogs, static_cast(arg)); + g_pika_server->PurgelogsTaskSchedule(&DoPurgeStableLogs, static_cast(arg)); return true; } -void StableLog::ClearPurge() { - purging_ = false; -} +void StableLog::ClearPurge() { purging_ = false; } void StableLog::DoPurgeStableLogs(void* arg) { PurgeStableLogArg* purge_arg = static_cast(arg); @@ -104,11 +91,11 @@ bool StableLog::PurgeFiles(uint32_t to, bool manual) { std::shared_ptr master_partition = nullptr; std::map::iterator it; for (it = binlogs.begin(); it != binlogs.end(); ++it) { - if ((manual && it->first <= to) // Manual purgelogsto - || (remain_expire_num > 0) // Expire num trigger - || (binlogs.size() - delete_num > 10 // At lease remain 10 files - && stat(((log_path_ + it->second)).c_str(), &file_stat) == 0 - && file_stat.st_mtime < time(NULL) - g_pika_conf->expire_logs_days() * 24 * 3600)) { // Expire time trigger + if ((manual && it->first <= to) // Manual purgelogsto + || (remain_expire_num > 0) // Expire num trigger + || (binlogs.size() - delete_num > 10 // At lease remain 10 files + && stat(((log_path_ + it->second)).c_str(), &file_stat) == 0 && + file_stat.st_mtime < time(NULL) - g_pika_conf->expire_logs_days() * 24 * 3600)) { // Expire time trigger // We check this every time to avoid lock when we do file deletion master_partition = g_pika_rm->GetSyncMasterPartitionByName(PartitionInfo(table_name_, partition_id_)); if (!master_partition) { @@ -117,7 +104,7 @@ bool StableLog::PurgeFiles(uint32_t to, bool manual) { } if (!master_partition->BinlogCloudPurge(it->first)) { - LOG(WARNING) << log_path_ << " Could not purge "<< (it->first) << ", since it is already be used"; + LOG(WARNING) << log_path_ << " Could not purge " << (it->first) << ", since it is already be used"; return false; } @@ -127,8 +114,7 @@ bool StableLog::PurgeFiles(uint32_t to, bool manual) { ++delete_num; --remain_expire_num; } else { - LOG(WARNING) << log_path_ << " Purge log file : " << (it->second) - << " failed! error:" << s.ToString(); + LOG(WARNING) << log_path_ << " Purge log file : " << (it->second) << " failed! error:" << s.ToString(); } } else { // Break when face the first one not satisfied @@ -148,7 +134,7 @@ bool StableLog::PurgeFiles(uint32_t to, bool manual) { } } if (delete_num) { - LOG(INFO) << log_path_ << " Success purge "<< delete_num << " binlog file"; + LOG(INFO) << log_path_ << " Success purge " << delete_num << " binlog file"; } return true; } @@ -157,8 +143,7 @@ bool StableLog::GetBinlogFiles(std::map* binlogs) { std::vector children; int ret = pstd::GetChildren(log_path_, children); if (ret != 0) { - LOG(WARNING) << log_path_ << " Get all files in log path failed! error:" - << ret; + LOG(WARNING) << log_path_ << " Get all files in log path failed! error:" << ret; return false; } diff --git a/src/pika_statistic.cc b/src/pika_statistic.cc index 109a09acb3..3e15ff4349 100644 --- a/src/pika_statistic.cc +++ b/src/pika_statistic.cc @@ -18,8 +18,7 @@ QpsStatistic::QpsStatistic() last_write_querynum(0), last_sec_querynum(0), last_sec_write_querynum(0), - last_time_us(0) { -} + last_time_us(0) {} QpsStatistic::QpsStatistic(const QpsStatistic& other) { querynum = other.querynum.load(); @@ -31,8 +30,7 @@ QpsStatistic::QpsStatistic(const QpsStatistic& other) { last_time_us = other.last_time_us.load(); } -QpsStatistic::~QpsStatistic() { -} +QpsStatistic::~QpsStatistic() {} void QpsStatistic::IncreaseQueryNum(bool is_write) { querynum++; @@ -60,10 +58,8 @@ void QpsStatistic::ResetLastSecQuerynum() { cur_time_us = last_time + 1; } uint64_t delta_time_us = cur_time_us - last_time; - last_sec_querynum.store(delta_query - * 1000000 / (delta_time_us)); - last_sec_write_querynum.store(delta_write_query - * 1000000 / (delta_time_us)); + last_sec_querynum.store(delta_query * 1000000 / (delta_time_us)); + last_sec_write_querynum.store(delta_write_query * 1000000 / (delta_time_us)); last_querynum.store(cur_query); last_write_querynum.store(cur_write_query); @@ -72,8 +68,7 @@ void QpsStatistic::ResetLastSecQuerynum() { /* ServerStatistic */ -ServerStatistic::ServerStatistic() - : accumulative_connections(0) { +ServerStatistic::ServerStatistic() : accumulative_connections(0) { CmdTable* cmds = new CmdTable(); cmds->reserve(300); InitCmdTable(cmds); @@ -86,8 +81,7 @@ ServerStatistic::ServerStatistic() delete cmds; } -ServerStatistic::~ServerStatistic() { -} +ServerStatistic::~ServerStatistic() {} /* Statistic */ @@ -95,8 +89,7 @@ Statistic::Statistic() { pthread_rwlockattr_t table_stat_rw_attr; pthread_rwlockattr_init(&table_stat_rw_attr); #if !defined(__APPLE__) - pthread_rwlockattr_setkind_np(&table_stat_rw_attr, - PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); + pthread_rwlockattr_setkind_np(&table_stat_rw_attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); #endif pthread_rwlock_init(&table_stat_rw, &table_stat_rw_attr); } @@ -111,8 +104,7 @@ std::unordered_map Statistic::AllTableStat() { return table_stat; } -void Statistic::UpdateTableQps( - const std::string& table_name, const std::string& command, bool is_write) { +void Statistic::UpdateTableQps(const std::string& table_name, const std::string& command, bool is_write) { bool table_exist = true; std::unordered_map::iterator iter; { @@ -140,9 +132,3 @@ void Statistic::ResetTableLastSecQuerynum() { stat.second.ResetLastSecQuerynum(); } } - - - - - - diff --git a/src/pika_table.cc b/src/pika_table.cc index d4d1a974d2..4df2a87eaf 100644 --- a/src/pika_table.cc +++ b/src/pika_table.cc @@ -5,28 +5,23 @@ #include "include/pika_table.h" -#include "include/pika_server.h" #include "include/pika_cmd_table_manager.h" #include "include/pika_rm.h" +#include "include/pika_server.h" extern PikaServer* g_pika_server; extern PikaReplicaManager* g_pika_rm; extern PikaCmdTableManager* g_pika_cmd_table_manager; -std::string TablePath(const std::string& path, - const std::string& table_name) { +std::string TablePath(const std::string& path, const std::string& table_name) { char buf[100]; snprintf(buf, sizeof(buf), "%s/", table_name.data()); return path + buf; } -Table::Table(const std::string& table_name, - uint32_t partition_num, - const std::string& db_path, - const std::string& log_path) : - table_name_(table_name), - partition_num_(partition_num) { - +Table::Table(const std::string& table_name, uint32_t partition_num, const std::string& db_path, + const std::string& log_path) + : table_name_(table_name), partition_num_(partition_num) { db_path_ = TablePath(db_path, table_name_); log_path_ = TablePath(log_path, "log_" + table_name_); @@ -44,9 +39,7 @@ Table::~Table() { partitions_.clear(); } -std::string Table::GetTableName() { - return table_name_; -} +std::string Table::GetTableName() { return table_name_; } void Table::BgSaveTable() { pstd::RWLock l(&partitions_rw_, false); @@ -86,33 +79,24 @@ bool Table::FlushPartitionSubDB(const std::string& db_name) { return true; } -void Table::SetBinlogIoError() { - return binlog_io_error_.store(true); -} +void Table::SetBinlogIoError() { return binlog_io_error_.store(true); } -bool Table::IsBinlogIoError() { - return binlog_io_error_.load(); -} +bool Table::IsBinlogIoError() { return binlog_io_error_.load(); } -uint32_t Table::PartitionNum() { - return partition_num_; -} +uint32_t Table::PartitionNum() { return partition_num_; } Status Table::AddPartitions(const std::set& partition_ids) { pstd::RWLock l(&partitions_rw_, true); for (const uint32_t& id : partition_ids) { if (id >= partition_num_) { - return Status::Corruption("partition index out of range[0, " - + std::to_string(partition_num_ - 1) + "]"); + return Status::Corruption("partition index out of range[0, " + std::to_string(partition_num_ - 1) + "]"); } else if (partitions_.find(id) != partitions_.end()) { - return Status::Corruption("partition " - + std::to_string(id) + " already exist"); + return Status::Corruption("partition " + std::to_string(id) + " already exist"); } } for (const uint32_t& id : partition_ids) { - partitions_.emplace(id, std::make_shared( - table_name_, id, db_path_)); + partitions_.emplace(id, std::make_shared(table_name_, id, db_path_)); } return Status::OK(); } @@ -146,8 +130,8 @@ void Table::KeyScan() { } key_scan_info_.key_scaning_ = true; - key_scan_info_.duration = -2; // duration -2 mean the task in waiting status, - // has not been scheduled for exec + key_scan_info_.duration = -2; // duration -2 mean the task in waiting status, + // has not been scheduled for exec BgTaskArg* bg_task_arg = new BgTaskArg(); bg_task_arg->table = shared_from_this(); g_pika_server->KeyScanTaskSchedule(&DoKeyScan, reinterpret_cast(bg_task_arg)); @@ -227,7 +211,7 @@ void Table::Compact(const storage::DataType& type) { } } -void Table::DoKeyScan(void *arg) { +void Table::DoKeyScan(void* arg) { BgTaskArg* bg_task_arg = reinterpret_cast(arg); bg_task_arg->table->RunKeyScan(); delete bg_task_arg; @@ -238,7 +222,7 @@ void Table::InitKeyScan() { char s_time[32]; int len = strftime(s_time, sizeof(s_time), "%Y-%m-%d %H:%M:%S", localtime(&key_scan_info_.start_time)); key_scan_info_.s_start_time.assign(s_time, len); - key_scan_info_.duration = -1; // duration -1 mean the task in processing + key_scan_info_.duration = -1; // duration -1 mean the task in processing } void Table::LeaveAllPartition() { @@ -285,14 +269,13 @@ Status Table::Leave() { } Status Table::MovetoToTrash(const std::string& path) { - std::string path_tmp = path; if (path_tmp[path_tmp.length() - 1] == '/') { path_tmp.erase(path_tmp.length() - 1); } path_tmp += "_deleting/"; if (pstd::RenameFile(path, path_tmp)) { - LOG(WARNING) << "Failed to move " << path <<" to trash, error: " << strerror(errno); + LOG(WARNING) << "Failed to move " << path << " to trash, error: " << strerror(errno); return Status::Corruption("Failed to move %s to trash", path); } g_pika_server->PurgeDir(path_tmp); diff --git a/src/pika_zset.cc b/src/pika_zset.cc index 0e4d38e499..ba4d927461 100644 --- a/src/pika_zset.cc +++ b/src/pika_zset.cc @@ -75,8 +75,7 @@ void ZScanCmd::DoInitial() { size_t argc = argv_.size(), index = 3; while (index < argc) { std::string opt = argv_[index]; - if (!strcasecmp(opt.data(), "match") - || !strcasecmp(opt.data(), "count")) { + if (!strcasecmp(opt.data(), "match") || !strcasecmp(opt.data(), "count")) { index++; if (index >= argc) { res_.SetRes(CmdRes::kSyntaxErr); @@ -245,7 +244,8 @@ void ZRevrangeCmd::Do(std::shared_ptr partition) { return; } -int32_t DoScoreStrRange(std::string begin_score, std::string end_score, bool *left_close, bool *right_close, double *min_score, double *max_score) { +int32_t DoScoreStrRange(std::string begin_score, std::string end_score, bool* left_close, bool* right_close, + double* min_score, double* max_score) { if (begin_score.size() > 0 && begin_score.at(0) == '(') { *left_close = false; begin_score.erase(begin_score.begin()); @@ -256,8 +256,8 @@ int32_t DoScoreStrRange(std::string begin_score, std::string end_score, bool *le *min_score = storage::ZSET_SCORE_MAX; } else if (!pstd::string2d(begin_score.data(), begin_score.size(), min_score)) { return -1; - } - + } + if (end_score.size() > 0 && end_score.at(0) == '(') { *right_close = false; end_score.erase(end_score.begin()); @@ -272,7 +272,7 @@ int32_t DoScoreStrRange(std::string begin_score, std::string end_score, bool *le return 0; } -static void FitLimit(int64_t &count, int64_t &offset, const int64_t size) { +static void FitLimit(int64_t& count, int64_t& offset, const int64_t size) { count = count >= 0 ? count : size; offset = (offset >= 0 && offset < size) ? offset : size; count = (offset + count < size) ? count : size - offset; @@ -307,7 +307,7 @@ void ZsetRangebyscoreParentCmd::DoInitial() { if (!pstd::string2int(argv_[index].data(), argv_[index].size(), &count_)) { res_.SetRes(CmdRes::kInvalidInt); return; - } + } } else { res_.SetRes(CmdRes::kSyntaxErr); return; @@ -330,7 +330,8 @@ void ZRangebyscoreCmd::Do(std::shared_ptr partition) { return; } std::vector score_members; - rocksdb::Status s = partition->db()->ZRangebyscore(key_, min_score_, max_score_, left_close_, right_close_, &score_members); + rocksdb::Status s = + partition->db()->ZRangebyscore(key_, min_score_, max_score_, left_close_, right_close_, &score_members); if (!s.ok() && !s.IsNotFound()) { res_.SetRes(CmdRes::kErrOther, s.ToString()); return; @@ -381,7 +382,8 @@ void ZRevrangebyscoreCmd::Do(std::shared_ptr partition) { return; } std::vector score_members; - rocksdb::Status s = partition->db()->ZRevrangebyscore(key_, min_score_, max_score_, left_close_, right_close_, &score_members); + rocksdb::Status s = + partition->db()->ZRevrangebyscore(key_, min_score_, max_score_, left_close_, right_close_, &score_members); if (!s.ok() && !s.IsNotFound()) { res_.SetRes(CmdRes::kErrOther, s.ToString()); return; @@ -493,7 +495,7 @@ void ZsetUIstoreParentCmd::DoInitial() { res_.SetRes(CmdRes::kErrOther, "weight value is not a float"); return; } - weights_[index-base] = weight; + weights_[index - base] = weight; } } else if (!strcasecmp(argv_[index].data(), "aggregate")) { index++; @@ -578,7 +580,7 @@ void ZRankCmd::Do(std::shared_ptr partition) { rocksdb::Status s = partition->db()->ZRank(key_, member_, &rank); if (s.ok()) { res_.AppendInteger(rank); - } else if (s.IsNotFound()){ + } else if (s.IsNotFound()) { res_.AppendContent("$-1"); } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); @@ -598,7 +600,7 @@ void ZRevrankCmd::Do(std::shared_ptr partition) { rocksdb::Status s = partition->db()->ZRevrank(key_, member_, &revrank); if (s.ok()) { res_.AppendInteger(revrank); - } else if (s.IsNotFound()){ + } else if (s.IsNotFound()) { res_.AppendContent("$-1"); } else { res_.SetRes(CmdRes::kErrOther, s.ToString()); @@ -630,12 +632,8 @@ void ZScoreCmd::Do(std::shared_ptr partition) { return; } -static int32_t DoMemberRange(const std::string &raw_min_member, - const std::string &raw_max_member, - bool *left_close, - bool *right_close, - std::string* min_member, - std::string* max_member) { +static int32_t DoMemberRange(const std::string& raw_min_member, const std::string& raw_max_member, bool* left_close, + bool* right_close, std::string* min_member, std::string* max_member) { if (raw_min_member == "-") { *min_member = "-"; } else if (raw_min_member == "+") { @@ -752,7 +750,7 @@ void ZRevrangebylexCmd::Do(std::shared_ptr partition) { return; } FitLimit(count_, offset_, members.size()); - + res_.AppendArrayLen(count_); int64_t index = members.size() - 1 - offset_, end = index - count_; for (; index > end; index--) { @@ -837,7 +835,8 @@ void ZRemrangebyscoreCmd::Do(std::shared_ptr partition) { return; } int32_t count = 0; - rocksdb::Status s = partition->db()->ZRemrangebyscore(key_, min_score_, max_score_, left_close_, right_close_, &count); + rocksdb::Status s = + partition->db()->ZRemrangebyscore(key_, min_score_, max_score_, left_close_, right_close_, &count); if (!s.ok() && !s.IsNotFound()) { res_.SetRes(CmdRes::kErrOther, s.ToString()); return; @@ -866,7 +865,8 @@ void ZRemrangebylexCmd::Do(std::shared_ptr partition) { return; } int32_t count = 0; - rocksdb::Status s = partition->db()->ZRemrangebylex(key_, min_member_, max_member_, left_close_, right_close_, &count); + rocksdb::Status s = + partition->db()->ZRemrangebylex(key_, min_member_, max_member_, left_close_, right_close_, &count); if (!s.ok() && !s.IsNotFound()) { res_.SetRes(CmdRes::kErrOther, s.ToString()); return; @@ -875,7 +875,6 @@ void ZRemrangebylexCmd::Do(std::shared_ptr partition) { return; } - void ZPopmaxCmd::DoInitial() { if (!CheckArg(argv_.size())) { res_.SetRes(CmdRes::kWrongNum, kCmdNameZPopmax); @@ -885,7 +884,7 @@ void ZPopmaxCmd::DoInitial() { if (argv_.size() == 2) { count_ = 1; return; - } + } if (!pstd::string2int(argv_[2].data(), argv_[2].size(), (long long*)(&count_))) { res_.SetRes(CmdRes::kInvalidInt); return; @@ -910,7 +909,6 @@ void ZPopmaxCmd::Do(std::shared_ptr partition) { } } - void ZPopminCmd::DoInitial() { if (!CheckArg(argv_.size())) { res_.SetRes(CmdRes::kWrongNum, kCmdNameZPopmin); @@ -920,7 +918,7 @@ void ZPopminCmd::DoInitial() { if (argv_.size() == 2) { count_ = 1; return; - } + } if (!pstd::string2int(argv_[2].data(), argv_[2].size(), (long long*)(&count_))) { res_.SetRes(CmdRes::kInvalidInt); return; diff --git a/src/pstd/doc.h b/src/pstd/doc.h index 1fb044a9a0..08319542ad 100644 --- a/src/pstd/doc.h +++ b/src/pstd/doc.h @@ -4,5 +4,3 @@ // of patent rights can be found in the PATENTS file in the same directory. // pstd, typically as ``pika standard'', the sdk for pika. - - diff --git a/src/pstd/examples/binlog_example.cc b/src/pstd/examples/binlog_example.cc index ebc0dc8d8e..6459511abf 100644 --- a/src/pstd/examples/binlog_example.cc +++ b/src/pstd/examples/binlog_example.cc @@ -5,34 +5,34 @@ using namespace pstd; -Binlog *log; +Binlog* log; #define UNUSED(arg) ((void)arg) -void* Append(void *arg) { +void* Append(void* arg) { UNUSED(arg); int i = 0; while (true) { std::string item = "item" + std::to_string(i++); Status s = log->Append(item); - printf ("+ Append (%s) return %s\n", item.c_str(), s.ToString().c_str()); + printf("+ Append (%s) return %s\n", item.c_str(), s.ToString().c_str()); sleep(1); } return NULL; } -void* Reader(void *arg) { +void* Reader(void* arg) { UNUSED(arg); - int *id = (int *)arg; + int* id = (int*)arg; BinlogReader* reader = log->NewBinlogReader(0, 0); while (true) { std::string str; Status s = reader->ReadRecord(str); if (s.ok()) { - printf ("- Reader %u: get (%s)\n", *id, str.c_str()); + printf("- Reader %u: get (%s)\n", *id, str.c_str()); } else { - printf ("- Reader %lu: %s\n", pthread_self(), s.ToString().c_str()); + printf("- Reader %lu: %s\n", pthread_self(), s.ToString().c_str()); } sleep(1); } @@ -40,19 +40,18 @@ void* Reader(void *arg) { } int main() { - Status s = Binlog::Open("./binlog", &log); if (!s.ok()) { - printf ("Open failed %s\n", s.ToString().c_str()); + printf("Open failed %s\n", s.ToString().c_str()); return -1; } pthread_t pid; pthread_create(&pid, NULL, &Append, NULL); - pthread_t cid[3]; + pthread_t cid[3]; int id[3]; - + for (int i = 0; i < 3; i++) { id[i] = i; pthread_create(&cid[i], NULL, &Reader, &id[i]); diff --git a/src/pstd/examples/cond_lock_example.cc b/src/pstd/examples/cond_lock_example.cc index 74bb3f23b0..2bdf355ec0 100644 --- a/src/pstd/examples/cond_lock_example.cc +++ b/src/pstd/examples/cond_lock_example.cc @@ -6,8 +6,7 @@ pstd::CondLock cl; -int main() -{ +int main() { cl.Lock(); cl.Unlock(); uint32_t a = 2000; diff --git a/src/pstd/examples/conf_example.cc b/src/pstd/examples/conf_example.cc index 9fb88a0262..8c8f17c06e 100644 --- a/src/pstd/examples/conf_example.cc +++ b/src/pstd/examples/conf_example.cc @@ -3,8 +3,7 @@ using namespace pstd; -int main() -{ +int main() { BaseConf b("./conf/pika.conf"); if (b.LoadConf() == 0) { diff --git a/src/pstd/examples/hash_example.cc b/src/pstd/examples/hash_example.cc index 1e03c237e7..9070d65a1c 100644 --- a/src/pstd/examples/hash_example.cc +++ b/src/pstd/examples/hash_example.cc @@ -1,5 +1,5 @@ -#include #include +#include #include "pstd/include/pstd_hash.h" @@ -9,8 +9,8 @@ int main() { std::string output1 = sha256(input); std::string output2 = md5(input); - std::cout << "sha256('"<< input << "'): " << output1 << std::endl; - std::cout << "md5('"<< input << "'): " << output2<< std::endl; + std::cout << "sha256('" << input << "'): " << output1 << std::endl; + std::cout << "md5('" << input << "'): " << output2 << std::endl; return 0; } diff --git a/src/pstd/examples/mutex_example.cc b/src/pstd/examples/mutex_example.cc index d3e65bc3f5..45f9e97130 100644 --- a/src/pstd/examples/mutex_example.cc +++ b/src/pstd/examples/mutex_example.cc @@ -32,7 +32,6 @@ int main() { printf("sleep 999 millisecond\n"); mu.Unlock(); - + return 0; } - diff --git a/src/pstd/include/base_conf.h b/src/pstd/include/base_conf.h index 45d7f9024e..e86e9043c7 100644 --- a/src/pstd/include/base_conf.h +++ b/src/pstd/include/base_conf.h @@ -6,8 +6,8 @@ #ifndef __PSTD_INCLUDE_BASE_CONF_H__ #define __PSTD_INCLUDE_BASE_CONF_H__ -#include #include +#include #include #include @@ -18,7 +18,6 @@ namespace pstd { class BaseConf; - class BaseConf { public: struct Rep { @@ -29,51 +28,41 @@ class BaseConf { }; struct ConfItem { - ConfType type; // 0 means conf, 1 means comment + ConfType type; // 0 means conf, 1 means comment std::string name; std::string value; - ConfItem(ConfType t, const std::string &v) : - type(t), - name(""), - value(v) - {} - ConfItem(ConfType t, const std::string &n, const std::string &v) : - type(t), - name(n), - value(v) - {} + ConfItem(ConfType t, const std::string& v) : type(t), name(""), value(v) {} + ConfItem(ConfType t, const std::string& n, const std::string& v) : type(t), name(n), value(v) {} }; - explicit Rep(const std::string &p) - : path(p) { - } + explicit Rep(const std::string& p) : path(p) {} std::vector item; }; - explicit BaseConf(const std::string &path); + explicit BaseConf(const std::string& path); virtual ~BaseConf(); int LoadConf(); int32_t ReloadConf(); // return false if the item dosen't exist - bool GetConfInt(const std::string &name, int* value) const; - bool GetConfIntHuman(const std::string &name, int *value) const; - bool GetConfInt64(const std::string &name, int64_t* value) const; - bool GetConfInt64Human(const std::string &name, int64_t *value) const; + bool GetConfInt(const std::string& name, int* value) const; + bool GetConfIntHuman(const std::string& name, int* value) const; + bool GetConfInt64(const std::string& name, int64_t* value) const; + bool GetConfInt64Human(const std::string& name, int64_t* value) const; - bool GetConfStr(const std::string &name, std::string *value) const; - bool GetConfBool(const std::string &name, bool* value) const; - bool GetConfStrVec(const std::string &name, std::vector *value) const; + bool GetConfStr(const std::string& name, std::string* value) const; + bool GetConfBool(const std::string& name, bool* value) const; + bool GetConfStrVec(const std::string& name, std::vector* value) const; - bool SetConfInt(const std::string &name, const int value); - bool SetConfInt64(const std::string &name, const int64_t value); + bool SetConfInt(const std::string& name, const int value); + bool SetConfInt64(const std::string& name, const int64_t value); - bool SetConfStr(const std::string &name, const std::string &value); - bool SetConfBool(const std::string &name, const bool value); - bool SetConfStrVec(const std::string &name, const std::vector &value); + bool SetConfStr(const std::string& name, const std::string& value); + bool SetConfBool(const std::string& name, const bool value); + bool SetConfStrVec(const std::string& name, const std::vector& value); - bool CheckConfExist(const std::string &name) const; + bool CheckConfExist(const std::string& name) const; void DumpConf() const; bool WriteBack(); diff --git a/src/pstd/include/cond_lock.h b/src/pstd/include/cond_lock.h index dc70ce6569..8232cd6a5d 100644 --- a/src/pstd/include/cond_lock.h +++ b/src/pstd/include/cond_lock.h @@ -7,12 +7,12 @@ #define __INCLUDE_COND_LOCK_H__ /* * CondLock is a wrapper for condition variable. - * It contain a mutex in it's class, so we don't need other to protect the + * It contain a mutex in it's class, so we don't need other to protect the * condition variable. */ #include -#include #include +#include #include #include @@ -28,7 +28,7 @@ class CondLock { void Unlock(); void Wait(); - + /* * timeout is millisecond */ @@ -40,8 +40,8 @@ class CondLock { pthread_mutex_t mutex_; pthread_cond_t cond_; - CondLock(const CondLock&) {}; - void operator =(const CondLock&) {}; + CondLock(const CondLock&){}; + void operator=(const CondLock&){}; }; } // namespace pstd diff --git a/src/pstd/include/env.h b/src/pstd/include/env.h index 5294aafd01..ef761f3cc6 100644 --- a/src/pstd/include/env.h +++ b/src/pstd/include/env.h @@ -1,9 +1,9 @@ #ifndef __PSTD_ENV_H__ #define __PSTD_ENV_H__ +#include #include #include -#include #include "pstd/include/pstd_status.h" @@ -26,7 +26,6 @@ void SetMmapBoundSize(size_t size); extern const size_t kPageSize; - /* * File Operations */ @@ -48,18 +47,17 @@ Status DeleteFile(const std::string& fname); int RenameFile(const std::string& oldname, const std::string& newname); class FileLock { - public: - FileLock() { } - virtual ~FileLock() {}; - - int fd_; - std::string name_; + public: + FileLock() {} + virtual ~FileLock(){}; - private: + int fd_; + std::string name_; - // No copying allowed - FileLock(const FileLock&); - void operator=(const FileLock&); + private: + // No copying allowed + FileLock(const FileLock&); + void operator=(const FileLock&); }; Status LockFile(const std::string& f, FileLock** l); @@ -68,7 +66,6 @@ Status UnlockFile(FileLock* l); int GetChildren(const std::string& dir, std::vector& result); bool GetDescendant(const std::string& dir, std::vector& result); - uint64_t NowMicros(); void SleepForMicroseconds(int micros); @@ -89,7 +86,7 @@ Status NewRandomRWFile(const std::string& fname, RandomRWFile** result); // at a time to the file. class WritableFile { public: - WritableFile() { } + WritableFile() {} virtual ~WritableFile(); virtual Status Append(const Slice& data) = 0; @@ -108,22 +105,22 @@ class WritableFile { // A abstract for the sequential readable file class SequentialFile { public: - SequentialFile() {}; + SequentialFile(){}; virtual ~SequentialFile(); - //virtual Status Read(size_t n, char *&result, char *scratch) = 0; + // virtual Status Read(size_t n, char *&result, char *scratch) = 0; virtual Status Read(size_t n, Slice* result, char* scratch) = 0; virtual Status Skip(uint64_t n) = 0; - //virtual Status Close() = 0; - virtual char *ReadLine(char *buf, int n) = 0; + // virtual Status Close() = 0; + virtual char* ReadLine(char* buf, int n) = 0; }; class RWFile { -public: - RWFile() { } + public: + RWFile() {} virtual ~RWFile(); virtual char* GetData() = 0; -private: + private: // No copying allowed RWFile(const RWFile&); void operator=(const RWFile&); @@ -150,10 +147,9 @@ class RandomRWFile { // status. // // Safe for concurrent use by multiple threads. - virtual Status Read(uint64_t offset, size_t n, Slice* result, - char* scratch) const = 0; - virtual Status Close() = 0; // closes the file - virtual Status Sync() = 0; // sync data + virtual Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const = 0; + virtual Status Close() = 0; // closes the file + virtual Status Sync() = 0; // sync data /* * Sync data and/or metadata as well. @@ -161,9 +157,7 @@ class RandomRWFile { * Override this method for environments where we need to sync * metadata as well. */ - virtual Status Fsync() { - return Sync(); - } + virtual Status Fsync() { return Sync(); } /* * Pre-allocate space for a file. @@ -180,6 +174,5 @@ class RandomRWFile { void operator=(const RandomRWFile&); }; - -} // namespace pstd +} // namespace pstd #endif // __PSTD_ENV_H__ diff --git a/src/pstd/include/fmacros.h b/src/pstd/include/fmacros.h index f3623e4588..4c67133354 100644 --- a/src/pstd/include/fmacros.h +++ b/src/pstd/include/fmacros.h @@ -31,34 +31,34 @@ #define ___PSTD_FMACRO_H #ifndef _BSD_SOURCE -#define _BSD_SOURCE +# define _BSD_SOURCE #endif #if defined(__linux__) -#define _GNU_SOURCE_REDIS -#define _DEFAULT_SOURCE +# define _GNU_SOURCE_REDIS +# define _DEFAULT_SOURCE #endif #if defined(_AIX) -#define _ALL_SOURCE +# define _ALL_SOURCE #endif #if defined(__linux__) || defined(__OpenBSD__) -#define _XOPEN_SOURCE 700 +# define _XOPEN_SOURCE 700 /* * On NetBSD, _XOPEN_SOURCE undefines _NETBSD_SOURCE and * thus hides inet_aton etc. */ #elif !defined(__NetBSD__) -#define _XOPEN_SOURCE +# define _XOPEN_SOURCE #endif #if defined(__sun) -#define _POSIX_C_SOURCE 199506L +# define _POSIX_C_SOURCE 199506L #endif #ifndef _LARGEFILE_SOURCE -#define _LARGEFILE_SOURCE +# define _LARGEFILE_SOURCE #endif #define _FILE_OFFSET_BITS 64 diff --git a/src/pstd/include/lock_mgr.h b/src/pstd/include/lock_mgr.h index 2fe22c105a..97e0961c54 100644 --- a/src/pstd/include/lock_mgr.h +++ b/src/pstd/include/lock_mgr.h @@ -6,8 +6,8 @@ #ifndef __SRC_LOCK_MGR_H__ #define __SRC_LOCK_MGR_H__ -#include #include +#include #include "pstd/include/mutex.h" @@ -19,8 +19,7 @@ struct LockMapStripe; class LockMgr { public: - LockMgr(size_t default_num_stripes, int64_t max_num_locks, - std::shared_ptr factory); + LockMgr(size_t default_num_stripes, int64_t max_num_locks, std::shared_ptr factory); ~LockMgr(); diff --git a/src/pstd/include/mutex.h b/src/pstd/include/mutex.h index 331bb05c02..4de7f59869 100644 --- a/src/pstd/include/mutex.h +++ b/src/pstd/include/mutex.h @@ -61,8 +61,7 @@ class CondVar { // Returns other status if Storage should otherwis stop waiting and // fail the operation. // May return OK spuriously even if not notified. - virtual Status WaitFor(std::shared_ptr mutex, - int64_t timeout_time) = 0; + virtual Status WaitFor(std::shared_ptr mutex, int64_t timeout_time) = 0; // If any threads are waiting on *this, unblock at least one of the // waiting threads. diff --git a/src/pstd/include/posix.h b/src/pstd/include/posix.h index 9b7b9ac5f9..0244bff839 100644 --- a/src/pstd/include/posix.h +++ b/src/pstd/include/posix.h @@ -1,34 +1,33 @@ /* $begin csapp.h */ #ifndef __CSAPP_H__ -#define __CSAPP_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - +# define __CSAPP_H__ + +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include /* Default file permissions are DEF_MODE & ~DEF_UMASK */ /* $begin createmasks */ -#define DEF_MODE S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH -#define DEF_UMASK S_IWGRP|S_IWOTH +# define DEF_MODE S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH +# define DEF_UMASK S_IWGRP | S_IWOTH /* $end createmasks */ /* Simplifies calls to bind(), connect(), and accept() */ @@ -38,29 +37,29 @@ typedef struct sockaddr SA; /* Persistent state for the robust I/O (Rio) package */ /* $begin rio_t */ -#define RIO_BUFSIZE 8192 +# define RIO_BUFSIZE 8192 typedef struct { int rio_fd; /* descriptor for this internal buf */ int rio_cnt; /* unread bytes in internal buf */ - char *rio_bufptr; /* next unread byte in internal buf */ + char* rio_bufptr; /* next unread byte in internal buf */ char rio_buf[RIO_BUFSIZE]; /* internal buffer */ } rio_t; /* $end rio_t */ /* External variables */ extern int h_errno; /* defined by BIND for DNS errors */ -extern char **environ; /* defined by libc */ +extern char** environ; /* defined by libc */ /* Misc constants */ -#define MAXLINE 8192 /* max text line length */ -#define MAXBUF 8192 /* max I/O buffer size */ -#define LISTENQ 1024 /* second argument to listen() */ +# define MAXLINE 8192 /* max text line length */ +# define MAXBUF 8192 /* max I/O buffer size */ +# define LISTENQ 1024 /* second argument to listen() */ /* Process control wrappers */ pid_t Fork(void); -void Execve(const char *filename, char *const argv[], char *const envp[]); -pid_t Wait(int *status); -pid_t Waitpid(pid_t pid, int *iptr, int options); +void Execve(const char* filename, char* const argv[], char* const envp[]); +pid_t Wait(int* status); +pid_t Waitpid(pid_t pid, int* iptr, int options); void Kill(pid_t pid, int signum); unsigned int Sleep(unsigned int secs); void Pause(void); @@ -70,92 +69,90 @@ pid_t Getpgrp(); /* Signal wrappers */ typedef void handler_t(int); -handler_t *Signal(int signum, handler_t *handler); -void Sigprocmask(int how, const sigset_t *set, sigset_t *oldset); -void Sigemptyset(sigset_t *set); -void Sigfillset(sigset_t *set); -void Sigaddset(sigset_t *set, int signum); -void Sigdelset(sigset_t *set, int signum); -int Sigismember(const sigset_t *set, int signum); +handler_t* Signal(int signum, handler_t* handler); +void Sigprocmask(int how, const sigset_t* set, sigset_t* oldset); +void Sigemptyset(sigset_t* set); +void Sigfillset(sigset_t* set); +void Sigaddset(sigset_t* set, int signum); +void Sigdelset(sigset_t* set, int signum); +int Sigismember(const sigset_t* set, int signum); /* Unix I/O wrappers */ -int Open(const char *pathname, int flags, mode_t mode); -ssize_t Read(int fd, void *buf, size_t count); -ssize_t Write(int fd, const void *buf, size_t count); +int Open(const char* pathname, int flags, mode_t mode); +ssize_t Read(int fd, void* buf, size_t count); +ssize_t Write(int fd, const void* buf, size_t count); off_t Lseek(int fildes, off_t offset, int whence); void Close(int fd); -int Select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, - struct timeval *timeout); +int Select(int n, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout); int Dup2(int fd1, int fd2); -void Stat(const char *filename, struct stat *buf); -void Fstat(int fd, struct stat *buf) ; +void Stat(const char* filename, struct stat* buf); +void Fstat(int fd, struct stat* buf); /* Memory mapping wrappers */ -void *Mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset); -void Munmap(void *start, size_t length); +void* Mmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset); +void Munmap(void* start, size_t length); /* Standard I/O wrappers */ -void Fclose(FILE *fp); -FILE *Fdopen(int fd, const char *type); -char *Fgets(char *ptr, int n, FILE *stream); -FILE *Fopen(const char *filename, const char *mode); -void Fputs(const char *ptr, FILE *stream); -size_t Fread(void *ptr, size_t size, size_t nmemb, FILE *stream); -void Fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); +void Fclose(FILE* fp); +FILE* Fdopen(int fd, const char* type); +char* Fgets(char* ptr, int n, FILE* stream); +FILE* Fopen(const char* filename, const char* mode); +void Fputs(const char* ptr, FILE* stream); +size_t Fread(void* ptr, size_t size, size_t nmemb, FILE* stream); +void Fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream); /* Dynamic storage allocation wrappers */ -void *Malloc(size_t size); -void *Realloc(void *ptr, size_t size); -void *Calloc(size_t nmemb, size_t size); -void Free(void *ptr); +void* Malloc(size_t size); +void* Realloc(void* ptr, size_t size); +void* Calloc(size_t nmemb, size_t size); +void Free(void* ptr); /* Sockets interface wrappers */ int Socket(int domain, int type, int protocol); -void Setsockopt(int s, int level, int optname, const void *optval, int optlen); -void Bind(int sockfd, struct sockaddr *my_addr, int addrlen); +void Setsockopt(int s, int level, int optname, const void* optval, int optlen); +void Bind(int sockfd, struct sockaddr* my_addr, int addrlen); void Listen(int s, int backlog); -int Accept(int s, struct sockaddr *addr, socklen_t *addrlen); -void Connect(int sockfd, struct sockaddr *serv_addr, int addrlen); +int Accept(int s, struct sockaddr* addr, socklen_t* addrlen); +void Connect(int sockfd, struct sockaddr* serv_addr, int addrlen); /* DNS wrappers */ -struct hostent *Gethostbyname(const char *name); -struct hostent *Gethostbyaddr(const char *addr, int len, int type); +struct hostent* Gethostbyname(const char* name); +struct hostent* Gethostbyaddr(const char* addr, int len, int type); /* Pthreads thread control wrappers */ -void Pthread_create(pthread_t *tidp, pthread_attr_t *attrp, - void * (*routine)(void *), void *argp); -void Pthread_join(pthread_t tid, void **thread_return); +void Pthread_create(pthread_t* tidp, pthread_attr_t* attrp, void* (*routine)(void*), void* argp); +void Pthread_join(pthread_t tid, void** thread_return); void Pthread_cancel(pthread_t tid); void Pthread_detach(pthread_t tid); -void Pthread_exit(void *retval); +void Pthread_exit(void* retval); pthread_t Pthread_self(void); -void Pthread_once(pthread_once_t *once_control, void (*init_function)()); +void Pthread_once(pthread_once_t* once_control, void (*init_function)()); /* POSIX semaphore wrappers */ -void Sem_init(sem_t *sem, int pshared, unsigned int value); -void P(sem_t *sem); -void V(sem_t *sem); +void Sem_init(sem_t* sem, int pshared, unsigned int value); +void P(sem_t* sem); +void V(sem_t* sem); /* Rio (Robust I/O) package */ -ssize_t rio_readn(int fd, void *usrbuf, size_t n); -ssize_t rio_writen(int fd, void *usrbuf, size_t n); -void rio_readinitb(rio_t *rp, int fd); -ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n); -ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen); +ssize_t rio_readn(int fd, void* usrbuf, size_t n); +ssize_t rio_writen(int fd, void* usrbuf, size_t n); +void rio_readinitb(rio_t* rp, int fd); +ssize_t rio_readnb(rio_t* rp, void* usrbuf, size_t n); +ssize_t rio_readlineb(rio_t* rp, void* usrbuf, size_t maxlen); /* Wrappers for Rio package */ -ssize_t Rio_readn(int fd, void *usrbuf, size_t n); -void Rio_writen(int fd, void *usrbuf, size_t n); -void Rio_readinitb(rio_t *rp, int fd); -ssize_t Rio_readnb(rio_t *rp, void *usrbuf, size_t n); -ssize_t Rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen); +ssize_t Rio_readn(int fd, void* usrbuf, size_t n); +void Rio_writen(int fd, void* usrbuf, size_t n); +void Rio_readinitb(rio_t* rp, int fd); +ssize_t Rio_readnb(rio_t* rp, void* usrbuf, size_t n); +ssize_t Rio_readlineb(rio_t* rp, void* usrbuf, size_t maxlen); /* Client/server helper functions */ -int open_clientfd(char *hostname, int portno); +int open_clientfd(char* hostname, int portno); int open_listenfd(int portno); /* Wrappers for client/server helper functions */ -int Open_clientfd(char *hostname, int port); +int Open_clientfd(char* hostname, int port); int Open_listenfd(int port); #endif /* __CSAPP_H__ */ diff --git a/src/pstd/include/pstd_binlog.h b/src/pstd/include/pstd_binlog.h index eb03a871df..3d84bacd88 100644 --- a/src/pstd/include/pstd_binlog.h +++ b/src/pstd/include/pstd_binlog.h @@ -11,7 +11,7 @@ #include "pstd/include/pstd_status.h" #include "pstd/include/xdebug.h" -//#include "pstd_mutex.h" +// #include "pstd_mutex.h" namespace pstd { @@ -23,16 +23,16 @@ class Binlog { public: static Status Open(const std::string& path, Binlog** logptr); - Binlog() { } - virtual ~Binlog() { } + Binlog() {} + virtual ~Binlog() {} - // TODO (aa) + // TODO (aa) // 1. maybe add Options - + // // Basic API // - virtual Status Append(const std::string &item) = 0; + virtual Status Append(const std::string& item) = 0; virtual BinlogReader* NewBinlogReader(uint32_t filenum, uint64_t offset) = 0; // Set/Get Producer filenum and offset with lock @@ -40,7 +40,6 @@ class Binlog { virtual Status SetProducerStatus(uint32_t filenum, uint64_t pro_offset) = 0; private: - // No copying allowed Binlog(const Binlog&); void operator=(const Binlog&); @@ -48,20 +47,18 @@ class Binlog { class BinlogReader { public: - BinlogReader() { } - virtual ~BinlogReader() { } + BinlogReader() {} + virtual ~BinlogReader() {} - virtual Status ReadRecord(std::string &record) = 0; - //bool ReadRecord(Slice* record, std::string* scratch) = 0; + virtual Status ReadRecord(std::string& record) = 0; + // bool ReadRecord(Slice* record, std::string* scratch) = 0; private: - // No copying allowed; BinlogReader(const BinlogReader&); void operator=(const BinlogReader&); }; -} // namespace pstd - +} // namespace pstd #endif // __PSTD_BINLOG_H__ diff --git a/src/pstd/include/pstd_coding.h b/src/pstd/include/pstd_coding.h index 757f94c08b..cefc78d5df 100644 --- a/src/pstd/include/pstd_coding.h +++ b/src/pstd/include/pstd_coding.h @@ -31,8 +31,7 @@ extern void GetFixed32(std::string* dst, uint32_t* value); extern void GetFixed64(std::string* dst, uint64_t* value); extern bool GetVarint32(std::string* input, uint32_t* value); extern bool GetVarint64(std::string* input, uint64_t* value); -extern const char* GetLengthPrefixedSlice(const char* p, const char* limit, - Slice* result); +extern const char* GetLengthPrefixedSlice(const char* p, const char* limit, Slice* result); extern bool GetLengthPrefixedSlice(Slice* input, Slice* result); extern bool GetLengthPrefixedString(std::string* input, std::string* result); @@ -40,8 +39,8 @@ extern bool GetLengthPrefixedString(std::string* input, std::string* result); // in *v and return a pointer just past the parsed value, or return // NULL on error. These routines only look at bytes in the range // [p..limit-1] -extern const char* GetVarint32Ptr(const char* p,const char* limit, uint32_t* v); -extern const char* GetVarint64Ptr(const char* p,const char* limit, uint64_t* v); +extern const char* GetVarint32Ptr(const char* p, const char* limit, uint32_t* v); +extern const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* v); // Returns the length of the varint32 or varint64 encoding of "v" extern int VarintLength(uint64_t v); @@ -62,48 +61,44 @@ extern char* EncodeVarint64(char* dst, uint64_t value); // without any bounds checking. inline uint16_t DecodeFixed16(const char* ptr) { - // Load the raw bytes - uint16_t result; - memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load - return result; + // Load the raw bytes + uint16_t result; + memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load + return result; } inline uint32_t DecodeFixed32(const char* ptr) { - // Load the raw bytes - uint32_t result; - memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load - return result; + // Load the raw bytes + uint32_t result; + memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load + return result; } inline uint64_t DecodeFixed64(const char* ptr) { - // Load the raw bytes - uint64_t result; - memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load - return result; + // Load the raw bytes + uint64_t result; + memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load + return result; } -inline void GetFixed16(std::string* dst, uint16_t *value) { +inline void GetFixed16(std::string* dst, uint16_t* value) { *value = DecodeFixed16(dst->data()); dst->erase(0, sizeof(uint16_t)); } -inline void GetFixed32(std::string* dst, uint32_t *value) { +inline void GetFixed32(std::string* dst, uint32_t* value) { *value = DecodeFixed32(dst->data()); dst->erase(0, sizeof(uint32_t)); } -inline void GetFixed64(std::string* dst, uint64_t *value) { +inline void GetFixed64(std::string* dst, uint64_t* value) { *value = DecodeFixed64(dst->data()); dst->erase(0, sizeof(uint64_t)); } // Internal routine for use by fallback path of GetVarint32Ptr -extern const char* GetVarint32PtrFallback(const char* p, - const char* limit, - uint32_t* value); -inline const char* GetVarint32Ptr(const char* p, - const char* limit, - uint32_t* value) { +extern const char* GetVarint32PtrFallback(const char* p, const char* limit, uint32_t* value); +inline const char* GetVarint32Ptr(const char* p, const char* limit, uint32_t* value) { if (p < limit) { uint32_t result = *(reinterpret_cast(p)); if ((result & 128) == 0) { @@ -114,6 +109,6 @@ inline const char* GetVarint32Ptr(const char* p, return GetVarint32PtrFallback(p, limit, value); } -} // namespace leveldb +} // namespace pstd #endif // __PSTD_CODING_H__ diff --git a/src/pstd/include/pstd_define.h b/src/pstd/include/pstd_define.h index 51352a1be8..294dc482b7 100644 --- a/src/pstd/include/pstd_define.h +++ b/src/pstd/include/pstd_define.h @@ -6,5 +6,4 @@ #define COMMENT '#' #define COMMA ',' - #endif diff --git a/src/pstd/include/pstd_hash.h b/src/pstd/include/pstd_hash.h index fe25a17eeb..564ffac3ab 100644 --- a/src/pstd/include/pstd_hash.h +++ b/src/pstd/include/pstd_hash.h @@ -74,14 +74,14 @@ documentation and/or software. #ifndef __PSTD_HASH_H__ #define __PSTD_HASH_H__ -#include #include #include +#include namespace pstd { -std::string md5(const std::string &str, bool raw = false); -std::string sha256(const std::string &input, bool raw = false); +std::string md5(const std::string& str, bool raw = false); +std::string sha256(const std::string& input, bool raw = false); } // namespace pstd diff --git a/src/pstd/include/pstd_mutex.h b/src/pstd/include/pstd_mutex.h index f169c471df..c7c05416ee 100644 --- a/src/pstd/include/pstd_mutex.h +++ b/src/pstd/include/pstd_mutex.h @@ -17,7 +17,7 @@ class Mutex { void Lock(); void Unlock(); - void AssertHeld() { } + void AssertHeld() {} private: friend class CondVar; @@ -31,14 +31,13 @@ class Mutex { // DEPRECATED class RWLock { public: - RWLock(pthread_rwlock_t *mu, bool is_rwlock) : - mu_(mu) { - if (is_rwlock) { - res = pthread_rwlock_wrlock(this->mu_); - } else { - res = pthread_rwlock_rdlock(this->mu_); - } + RWLock(pthread_rwlock_t* mu, bool is_rwlock) : mu_(mu) { + if (is_rwlock) { + res = pthread_rwlock_wrlock(this->mu_); + } else { + res = pthread_rwlock_rdlock(this->mu_); } + } ~RWLock() { if (!res) { pthread_rwlock_unlock(this->mu_); @@ -47,7 +46,7 @@ class RWLock { private: int res; - pthread_rwlock_t *const mu_; + pthread_rwlock_t* const mu_; // No copying allowed RWLock(const RWLock&); void operator=(const RWLock&); @@ -73,14 +72,11 @@ class RWMutex { class ReadLock { public: - explicit ReadLock(RWMutex* rw_mu) - : rw_mu_(rw_mu) { - this->rw_mu_->ReadLock(); - } + explicit ReadLock(RWMutex* rw_mu) : rw_mu_(rw_mu) { this->rw_mu_->ReadLock(); } ~ReadLock() { this->rw_mu_->ReadUnlock(); } private: - RWMutex *const rw_mu_; + RWMutex* const rw_mu_; // No copying ReadLock(const ReadLock&); void operator=(const ReadLock&); @@ -88,14 +84,11 @@ class ReadLock { class WriteLock { public: - WriteLock(RWMutex* rw_mu) - : rw_mu_(rw_mu) { - this->rw_mu_->WriteLock(); - } + WriteLock(RWMutex* rw_mu) : rw_mu_(rw_mu) { this->rw_mu_->WriteLock(); } ~WriteLock() { this->rw_mu_->WriteUnlock(); } private: - RWMutex *const rw_mu_; + RWMutex* const rw_mu_; // No copying allowed WriteLock(const WriteLock&); void operator=(const WriteLock&); @@ -115,7 +108,7 @@ class CondVar { bool TimedWait(uint32_t timeout); void Signal(); void SignalAll(); - + private: pthread_cond_t cv_; Mutex* mu_; @@ -123,14 +116,11 @@ class CondVar { class MutexLock { public: - explicit MutexLock(Mutex *mu) - : mu_(mu) { - this->mu_->Lock(); - } + explicit MutexLock(Mutex* mu) : mu_(mu) { this->mu_->Lock(); } ~MutexLock() { this->mu_->Unlock(); } private: - Mutex *const mu_; + Mutex* const mu_; // No copying allowed MutexLock(const MutexLock&); void operator=(const MutexLock&); @@ -151,9 +141,7 @@ class RefMutex { void Ref(); void Unref(); - bool IsLastRef() { - return refs_ == 1; - } + bool IsLastRef() { return refs_ == 1; } private: pthread_mutex_t mu_; @@ -165,20 +153,19 @@ class RefMutex { }; class RecordMutex { -public: - RecordMutex() {}; + public: + RecordMutex(){}; ~RecordMutex(); void MultiLock(const std::vector& keys); - void Lock(const std::string &key); + void Lock(const std::string& key); void MultiUnlock(const std::vector& keys); - void Unlock(const std::string &key); - -private: + void Unlock(const std::string& key); + private: Mutex mutex_; - std::unordered_map records_; + std::unordered_map records_; // No copying RecordMutex(const RecordMutex&); @@ -187,14 +174,11 @@ class RecordMutex { class RecordLock { public: - RecordLock(RecordMutex *mu, const std::string &key) - : mu_(mu), key_(key) { - mu_->Lock(key_); - } + RecordLock(RecordMutex* mu, const std::string& key) : mu_(mu), key_(key) { mu_->Lock(key_); } ~RecordLock() { mu_->Unlock(key_); } private: - RecordMutex *const mu_; + RecordMutex* const mu_; std::string key_; // No copying allowed @@ -202,6 +186,6 @@ class RecordLock { void operator=(const RecordLock&); }; -} +} // namespace pstd #endif diff --git a/src/pstd/include/pstd_slice.h b/src/pstd/include/pstd_slice.h index 61d44e52c2..1ab667a0fb 100644 --- a/src/pstd/include/pstd_slice.h +++ b/src/pstd/include/pstd_slice.h @@ -30,16 +30,16 @@ namespace pstd { class Slice { public: // Create an empty slice. - Slice() : data_(""), size_(0) { } + Slice() : data_(""), size_(0) {} // Create a slice that refers to d[0,n-1]. - Slice(const char* d, size_t n) : data_(d), size_(n) { } + Slice(const char* d, size_t n) : data_(d), size_(n) {} // Create a slice that refers to the contents of "s" - Slice(const std::string& s) : data_(s.data()), size_(s.size()) { } + Slice(const std::string& s) : data_(s.data()), size_(s.size()) {} // Create a slice that refers to s[0,strlen(s)-1] - Slice(const char* s) : data_(s), size_(strlen(s)) { } + Slice(const char* s) : data_(s), size_(strlen(s)) {} // Return a pointer to the beginning of the referenced data const char* data() const { return data_; } @@ -58,7 +58,10 @@ class Slice { } // Change this slice to refer to an empty array - void clear() { data_ = ""; size_ = 0; } + void clear() { + data_ = ""; + size_ = 0; + } // Drop the first "n" bytes from this slice. void remove_prefix(size_t n) { @@ -77,10 +80,7 @@ class Slice { int compare(const Slice& b) const; // Return true iff "x" is a prefix of "*this" - bool starts_with(const Slice& x) const { - return ((size_ >= x.size_) && - (memcmp(data_, x.data_, x.size_) == 0)); - } + bool starts_with(const Slice& x) const { return ((size_ >= x.size_) && (memcmp(data_, x.data_, x.size_) == 0)); } private: const char* data_; @@ -90,25 +90,23 @@ class Slice { }; inline bool operator==(const Slice& x, const Slice& y) { - return ((x.size() == y.size()) && - (memcmp(x.data(), y.data(), x.size()) == 0)); + return ((x.size() == y.size()) && (memcmp(x.data(), y.data(), x.size()) == 0)); } -inline bool operator!=(const Slice& x, const Slice& y) { - return !(x == y); -} +inline bool operator!=(const Slice& x, const Slice& y) { return !(x == y); } inline int Slice::compare(const Slice& b) const { const size_t min_len = (size_ < b.size_) ? size_ : b.size_; int r = memcmp(data_, b.data_, min_len); if (r == 0) { - if (size_ < b.size_) r = -1; - else if (size_ > b.size_) r = +1; + if (size_ < b.size_) + r = -1; + else if (size_ > b.size_) + r = +1; } return r; } -} // namespace pstd - +} // namespace pstd #endif // __PSTD_SLICE_H__ diff --git a/src/pstd/include/pstd_status.h b/src/pstd/include/pstd_status.h index 50f17c8608..a4195aa529 100644 --- a/src/pstd/include/pstd_status.h +++ b/src/pstd/include/pstd_status.h @@ -9,7 +9,7 @@ namespace pstd { class Status { public: // Create a success status. - Status() : state_(NULL) { } + Status() : state_(NULL) {} ~Status() { delete[] state_; } // Copy the specified status. @@ -20,44 +20,24 @@ class Status { static Status OK() { return Status(); } // Return error status of an appropriate type. - static Status NotFound(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kNotFound, msg, msg2); - } - static Status Corruption(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kCorruption, msg, msg2); - } - static Status NotSupported(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kNotSupported, msg, msg2); - } + static Status NotFound(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kNotFound, msg, msg2); } + static Status Corruption(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kCorruption, msg, msg2); } + static Status NotSupported(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kNotSupported, msg, msg2); } static Status InvalidArgument(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kInvalidArgument, msg, msg2); } - static Status IOError(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kIOError, msg, msg2); - } - static Status EndFile(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kEndFile, msg, msg2); - } + static Status IOError(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kIOError, msg, msg2); } + static Status EndFile(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kEndFile, msg, msg2); } - static Status Incomplete(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kIncomplete, msg, msg2); - } + static Status Incomplete(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kIncomplete, msg, msg2); } - static Status Complete(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kComplete, msg, msg2); - } + static Status Complete(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kComplete, msg, msg2); } - static Status Timeout(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kTimeout, msg, msg2); - } + static Status Timeout(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kTimeout, msg, msg2); } - static Status AuthFailed(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kAuthFailed, msg, msg2); - } + static Status AuthFailed(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kAuthFailed, msg, msg2); } - static Status Busy(const Slice& msg, const Slice& msg2 = Slice()) { - return Status(kBusy, msg, msg2); - } + static Status Busy(const Slice& msg, const Slice& msg2 = Slice()) { return Status(kBusy, msg, msg2); } // Returns true if the status indicates success. bool ok() const { return (state_ == NULL); } @@ -76,16 +56,16 @@ class Status { // Returns true if the status indicates an EOF. bool IsEndFile() const { return code() == kEndFile; } - + // Returns true if the status is complete. bool IsComplete() const { return code() == kComplete; } - // Returns true if the status is Incomplete + // Returns true if the status is Incomplete bool IsIncomplete() const { return code() == kIncomplete; } - // Returns true if the status is InvalidArgument + // Returns true if the status is InvalidArgument bool IsInvalidArgument() const { return code() == kInvalidArgument; } - + // Returns true if the status is Timeout bool IsTimeout() const { return code() == kTimeout; } @@ -122,17 +102,13 @@ class Status { kBusy = 11 }; - Code code() const { - return (state_ == NULL) ? kOk : static_cast(state_[4]); - } + Code code() const { return (state_ == NULL) ? kOk : static_cast(state_[4]); } Status(Code code, const Slice& msg, const Slice& msg2); static const char* CopyState(const char* s); }; -inline Status::Status(const Status& s) { - state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); -} +inline Status::Status(const Status& s) { state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); } inline void Status::operator=(const Status& s) { // The following condition catches both aliasing (when this == &s), // and the common case where both s and *this are ok. @@ -142,7 +118,6 @@ inline void Status::operator=(const Status& s) { } } -} // namespace pstd - +} // namespace pstd #endif // __PSTD_STATUS_H__ diff --git a/src/pstd/include/pstd_string.h b/src/pstd/include/pstd_string.h index 6fc3da56fe..d4d5934b7c 100644 --- a/src/pstd/include/pstd_string.h +++ b/src/pstd/include/pstd_string.h @@ -40,26 +40,24 @@ namespace pstd { -int stringmatchlen(const char *p, int plen, const char *s, int slen, int nocase); -int stringmatch(const char *p, const char *s, int nocase); -long long memtoll(const char *p, int *err); -int ll2string(char *s, size_t len, long long value); -int string2int(const char *s, size_t slen, long long *value); -int string2int(const char *s, size_t slen, long *value); -int string2int(const char *s, size_t slen, unsigned long *value); -int d2string(char *buf, size_t len, double value); -int string2d(const char *buf, size_t len, double *value); -std::vector &StringSplit(const std::string &s, - char delim, std::vector &elems); -std::string StringConcat(const std::vector &elems, char delim); +int stringmatchlen(const char* p, int plen, const char* s, int slen, int nocase); +int stringmatch(const char* p, const char* s, int nocase); +long long memtoll(const char* p, int* err); +int ll2string(char* s, size_t len, long long value); +int string2int(const char* s, size_t slen, long long* value); +int string2int(const char* s, size_t slen, long* value); +int string2int(const char* s, size_t slen, unsigned long* value); +int d2string(char* buf, size_t len, double value); +int string2d(const char* buf, size_t len, double* value); +std::vector& StringSplit(const std::string& s, char delim, std::vector& elems); +std::string StringConcat(const std::vector& elems, char delim); std::string& StringToLower(std::string& ori); std::string& StringToUpper(std::string& ori); std::string IpPortString(const std::string& ip, int port); std::string ToRead(const std::string& str); -bool ParseIpPortString(const std::string& ip_port, std::string& ip, int &port); +bool ParseIpPortString(const std::string& ip_port, std::string& ip, int& port); std::string StringTrim(const std::string& ori, const std::string& charlist = " "); - } // namespace pstd #endif // __PSTD_STRING_H__ diff --git a/src/pstd/include/pstd_testharness.h b/src/pstd/include/pstd_testharness.h index 069bfa8048..7daf287163 100644 --- a/src/pstd/include/pstd_testharness.h +++ b/src/pstd/include/pstd_testharness.h @@ -47,9 +47,7 @@ class Tester { std::stringstream ss_; public: - Tester(const char* f, int l) - : ok_(true), fname_(f), line_(l) { - } + Tester(const char* f, int l) : ok_(true), fname_(f), line_(l) {} ~Tester() { if (!ok_) { @@ -74,14 +72,14 @@ class Tester { return *this; } -#define BINARY_OP(name,op) \ - template \ - Tester& name(const X& x, const Y& y) { \ - if (! (x op y)) { \ - ss_ << " failed: " << x << (" " #op " ") << y; \ - ok_ = false; \ - } \ - return *this; \ +#define BINARY_OP(name, op) \ + template \ + Tester& name(const X& x, const Y& y) { \ + if (!(x op y)) { \ + ss_ << " failed: " << x << (" " #op " ") << y; \ + ok_ = false; \ + } \ + return *this; \ } BINARY_OP(IsEq, ==) @@ -104,34 +102,32 @@ class Tester { #define ASSERT_TRUE(c) ::pstd::test::Tester(__FILE__, __LINE__).Is((c), #c) #define ASSERT_OK(s) ::pstd::test::Tester(__FILE__, __LINE__).IsOk((s)) -#define ASSERT_EQ(a,b) ::pstd::test::Tester(__FILE__, __LINE__).IsEq((a),(b)) -#define ASSERT_NE(a,b) ::pstd::test::Tester(__FILE__, __LINE__).IsNe((a),(b)) -#define ASSERT_GE(a,b) ::pstd::test::Tester(__FILE__, __LINE__).IsGe((a),(b)) -#define ASSERT_GT(a,b) ::pstd::test::Tester(__FILE__, __LINE__).IsGt((a),(b)) -#define ASSERT_LE(a,b) ::pstd::test::Tester(__FILE__, __LINE__).IsLe((a),(b)) -#define ASSERT_LT(a,b) ::pstd::test::Tester(__FILE__, __LINE__).IsLt((a),(b)) - -#define TCONCAT(a,b) TCONCAT1(a,b) -#define TCONCAT1(a,b) a##b - -#define TEST(base,name) \ -class TCONCAT(_Test_,name) : public base { \ - public: \ - void _Run(); \ - static void _RunIt() { \ - TCONCAT(_Test_,name) t; \ - t._Run(); \ - } \ -}; \ -bool TCONCAT(_Test_ignored_,name) = \ - ::pstd::test::RegisterTest(#base, #name, &TCONCAT(_Test_,name)::_RunIt); \ -void TCONCAT(_Test_,name)::_Run() +#define ASSERT_EQ(a, b) ::pstd::test::Tester(__FILE__, __LINE__).IsEq((a), (b)) +#define ASSERT_NE(a, b) ::pstd::test::Tester(__FILE__, __LINE__).IsNe((a), (b)) +#define ASSERT_GE(a, b) ::pstd::test::Tester(__FILE__, __LINE__).IsGe((a), (b)) +#define ASSERT_GT(a, b) ::pstd::test::Tester(__FILE__, __LINE__).IsGt((a), (b)) +#define ASSERT_LE(a, b) ::pstd::test::Tester(__FILE__, __LINE__).IsLe((a), (b)) +#define ASSERT_LT(a, b) ::pstd::test::Tester(__FILE__, __LINE__).IsLt((a), (b)) + +#define TCONCAT(a, b) TCONCAT1(a, b) +#define TCONCAT1(a, b) a##b + +#define TEST(base, name) \ + class TCONCAT(_Test_, name) : public base { \ + public: \ + void _Run(); \ + static void _RunIt() { \ + TCONCAT(_Test_, name) t; \ + t._Run(); \ + } \ + }; \ + bool TCONCAT(_Test_ignored_, name) = ::pstd::test::RegisterTest(#base, #name, &TCONCAT(_Test_, name)::_RunIt); \ + void TCONCAT(_Test_, name)::_Run() // Register the specified test. Typically not used directly, but // invoked via the macro expansion of TEST. extern bool RegisterTest(const char* base, const char* name, void (*func)()); - } // namespace test } // namespace pstd diff --git a/src/pstd/include/random.h b/src/pstd/include/random.h index 9fa6e3cbdf..c677e7002e 100644 --- a/src/pstd/include/random.h +++ b/src/pstd/include/random.h @@ -7,17 +7,12 @@ namespace pstd { class Random { public: - Random() { - srand(time(NULL)); - } + Random() { srand(time(NULL)); } /* * return Random number in [1...n] */ - static uint32_t Uniform(int n) { - return (random() % n) + 1; - } - + static uint32_t Uniform(int n) { return (random() % n) + 1; } }; }; // namespace pstd diff --git a/src/pstd/include/rsync.h b/src/pstd/include/rsync.h index 0a1b7efe7a..5204e28eb4 100644 --- a/src/pstd/include/rsync.h +++ b/src/pstd/include/rsync.h @@ -15,18 +15,18 @@ struct RsyncRemote { std::string host; int port; std::string module; - int kbps; //speed limit - RsyncRemote(const std::string& _host, const int _port, - const std::string& _module, const int _kbps) - : host(_host), port(_port), module(_module), kbps(_kbps) {} + int kbps; // speed limit + RsyncRemote(const std::string& _host, const int _port, const std::string& _module, const int _kbps) + : host(_host), port(_port), module(_module), kbps(_kbps) {} }; -int StartRsync(const std::string& rsync_path, const std::string& module, const std::string& ip, const int port, const std::string& passwd); +int StartRsync(const std::string& rsync_path, const std::string& module, const std::string& ip, const int port, + const std::string& passwd); int StopRsync(const std::string& path); int RsyncSendFile(const std::string& local_file_path, const std::string& remote_file_path, - const std::string& secret_file_path, const RsyncRemote& remote); + const std::string& secret_file_path, const RsyncRemote& remote); int RsyncSendClearTarget(const std::string& local_dir_path, const std::string& remote_dir_path, - const std::string& secret_file_path, const RsyncRemote& remote); + const std::string& secret_file_path, const RsyncRemote& remote); -} +} // namespace pstd #endif diff --git a/src/pstd/include/scope_record_lock.h b/src/pstd/include/scope_record_lock.h index 9ad897ca09..b91616b065 100644 --- a/src/pstd/include/scope_record_lock.h +++ b/src/pstd/include/scope_record_lock.h @@ -6,9 +6,9 @@ #ifndef __SRC_SCOPE_RECORD_LOCK_H__ #define __SRC_SCOPE_RECORD_LOCK_H__ -#include -#include #include +#include +#include #include "pstd/include/lock_mgr.h" @@ -18,13 +18,10 @@ namespace lock { class ScopeRecordLock { public: - ScopeRecordLock(LockMgr* lock_mgr, const Slice& key) : - lock_mgr_(lock_mgr), key_(key) { + ScopeRecordLock(LockMgr* lock_mgr, const Slice& key) : lock_mgr_(lock_mgr), key_(key) { lock_mgr_->TryLock(key_.ToString()); } - ~ScopeRecordLock() { - lock_mgr_->UnLock(key_.ToString()); - } + ~ScopeRecordLock() { lock_mgr_->UnLock(key_.ToString()); } private: LockMgr* const lock_mgr_; @@ -35,8 +32,7 @@ class ScopeRecordLock { class MultiScopeRecordLock { public: - MultiScopeRecordLock(LockMgr* lock_mgr, - const std::vector& keys); + MultiScopeRecordLock(LockMgr* lock_mgr, const std::vector& keys); ~MultiScopeRecordLock(); private: @@ -48,10 +44,8 @@ class MultiScopeRecordLock { class MultiRecordLock { public: - explicit MultiRecordLock(LockMgr* lock_mgr) : lock_mgr_(lock_mgr) { - } - ~MultiRecordLock() { - } + explicit MultiRecordLock(LockMgr* lock_mgr) : lock_mgr_(lock_mgr) {} + ~MultiRecordLock() {} void Lock(const std::vector& keys); void Unlock(const std::vector& keys); diff --git a/src/pstd/include/testutil.h b/src/pstd/include/testutil.h index 7e58a689f0..4ebbf8e048 100644 --- a/src/pstd/include/testutil.h +++ b/src/pstd/include/testutil.h @@ -7,9 +7,8 @@ namespace pstd { extern std::string RandomString(const int len); extern int RandomSeed(); -extern int GetTestDirectory(std::string *result); +extern int GetTestDirectory(std::string* result); }; // namespace pstd - #endif // __PSTD_INCLUDE_TESTUTIL_H__ diff --git a/src/pstd/include/version.h b/src/pstd/include/version.h index 020dc030e9..c4e9e5f55b 100644 --- a/src/pstd/include/version.h +++ b/src/pstd/include/version.h @@ -10,10 +10,10 @@ # #ifndef __PSTD_VERSION__ -#define __PSTD_VERSION__ +# define __PSTD_VERSION__ -#define PSTD_MAJOR 1 -#define PSTD_MINOR 0 -#define PSTD_PATCH 1 +# define PSTD_MAJOR 1 +# define PSTD_MINOR 0 +# define PSTD_PATCH 1 #endif diff --git a/src/pstd/include/xdebug.h b/src/pstd/include/xdebug.h index de5e84579a..39dead6c25 100644 --- a/src/pstd/include/xdebug.h +++ b/src/pstd/include/xdebug.h @@ -6,61 +6,80 @@ * @date 2014-04-25 */ -#ifndef __XDEBUG_H__ -#define __XDEBUG_H__ -#include -#include -#include -#include -#include +#ifndef __XDEBUG_H__ +# define __XDEBUG_H__ +# include +# include +# include +# include +# include -#ifdef __XDEBUG__ -#define pint(x) qf_debug("%s = %d", #x, x) -#define psize(x) qf_debug("%s = %zu", #x, x) -#define pstr(x) qf_debug("%s = %s", #x, x) +# ifdef __XDEBUG__ +# define pint(x) qf_debug("%s = %d", #x, x) +# define psize(x) qf_debug("%s = %zu", #x, x) +# define pstr(x) qf_debug("%s = %s", #x, x) // 如果A 不对, 那么就输出M -#define qf_check(A, M, ...) if(!(A)) { log_err(M, ##__VA_ARGS__); errno=0; exit(-1);} +# define qf_check(A, M, ...) \ + if (!(A)) { \ + log_err(M, ##__VA_ARGS__); \ + errno = 0; \ + exit(-1); \ + } // 用来检测程序是否执行到这里 -#define sentinel(M, ...) { qf_debug(M, ##__VA_ARGS__); errno=0;} +# define sentinel(M, ...) \ + { \ + qf_debug(M, ##__VA_ARGS__); \ + errno = 0; \ + } -#define qf_bin_debug(buf, size) \ -{ \ - fwrite(buf, 1, size, stderr); \ -} +# define qf_bin_debug(buf, size) \ + { fwrite(buf, 1, size, stderr); } -#define _debug_time_def timeval s1, e; -#define _debug_getstart gettimeofday(&s1, NULL) -#define _debug_getend gettimeofday(&e, NULL) -#define _debug_time ((int)(((e.tv_sec - s1.tv_sec) * 1000 + (e.tv_usec - s1.tv_usec) / 1000))) +# define _debug_time_def timeval s1, e; +# define _debug_getstart gettimeofday(&s1, NULL) +# define _debug_getend gettimeofday(&e, NULL) +# define _debug_time ((int)(((e.tv_sec - s1.tv_sec) * 1000 + (e.tv_usec - s1.tv_usec) / 1000))) -#define clean_errno() (errno == 0 ? "None" : strerror(errno)) -#define log_err(M, ...) \ -{ \ - fprintf(stderr, "[ERROR] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__); \ - exit(-1); \ -} -#define log_warn(M, ...) fprintf(stderr, "[WARN] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__) -#define log_info(M, ...) fprintf(stderr, "[INFO] (%s:%d) " M "\n", __FILE__, __LINE__, ##__VA_ARGS__) +# define clean_errno() (errno == 0 ? "None" : strerror(errno)) +# define log_err(M, ...) \ + { \ + fprintf(stderr, "[ERROR] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__); \ + exit(-1); \ + } +# define log_warn(M, ...) \ + fprintf(stderr, "[WARN] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__) +# define log_info(M, ...) fprintf(stderr, "[INFO] (%s:%d) " M "\n", __FILE__, __LINE__, ##__VA_ARGS__) -#else +# else -#define pint(x) {} -#define pstr(x) {} -#define qf_bin_debug(buf, size) {} +# define pint(x) \ + {} +# define pstr(x) \ + {} +# define qf_bin_debug(buf, size) \ + {} -#define _debug_time_def {} -#define _debug_getstart {} -#define _debug_getend {} -#define _debug_time 0 +# define _debug_time_def \ + {} +# define _debug_getstart \ + {} +# define _debug_getend \ + {} +# define _debug_time 0 -#define sentinel(M, ...) {} -#define qf_check(A, M, ...) {} -#define log_err(M, ...) {} -#define log_warn(M, ...) {} -#define log_info(M, ...) {} +# define sentinel(M, ...) \ + {} +# define qf_check(A, M, ...) \ + {} +# define log_err(M, ...) \ + {} +# define log_warn(M, ...) \ + {} +# define log_info(M, ...) \ + {} -#endif +# endif #endif //__XDEBUG_H__ diff --git a/src/pstd/src/base_conf.cc b/src/pstd/src/base_conf.cc index 6d66630c30..03d5769c6c 100644 --- a/src/pstd/src/base_conf.cc +++ b/src/pstd/src/base_conf.cc @@ -9,26 +9,22 @@ #include #include "pstd/include/env.h" -#include "pstd/include/xdebug.h" #include "pstd/include/pstd_string.h" +#include "pstd/include/xdebug.h" namespace pstd { -static const int kConfItemLen = 1024*1024; +static const int kConfItemLen = 1024 * 1024; -BaseConf::BaseConf(const std::string &path) - : rep_(new Rep(path)) { -} +BaseConf::BaseConf(const std::string& path) : rep_(new Rep(path)) {} -BaseConf::~BaseConf() { - delete rep_; -} +BaseConf::~BaseConf() { delete rep_; } int BaseConf::LoadConf() { if (!FileExists(rep_->path)) { return -1; } - SequentialFile *sequential_file; + SequentialFile* sequential_file; NewSequentialFile(rep_->path, &sequential_file); // read conf items @@ -52,22 +48,22 @@ int BaseConf::LoadConf() { break; } switch (line[i]) { - case SPACE: - case '\r': - case '\n': - break; - case COLON: - if (!sep_sign) { - type = Rep::kConf; - sep_sign = 1; + case SPACE: + case '\r': + case '\n': break; - } - default: - if (sep_sign == 0) { - name[name_len++] = line[i]; - } else { - value[value_len++] = line[i]; - } + case COLON: + if (!sep_sign) { + type = Rep::kConf; + sep_sign = 1; + break; + } + default: + if (sep_sign == 0) { + name[name_len++] = line[i]; + } else { + value[value_len++] = line[i]; + } } } @@ -95,7 +91,7 @@ int BaseConf::ReloadConf() { return 0; } -bool BaseConf::GetConfInt(const std::string &name, int* value) const { +bool BaseConf::GetConfInt(const std::string& name, int* value) const { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -108,7 +104,7 @@ bool BaseConf::GetConfInt(const std::string &name, int* value) const { return false; } -bool BaseConf::GetConfIntHuman(const std::string &name, int* value) const { +bool BaseConf::GetConfIntHuman(const std::string& name, int* value) const { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -130,7 +126,7 @@ bool BaseConf::GetConfIntHuman(const std::string &name, int* value) const { return false; } -bool BaseConf::GetConfInt64Human(const std::string &name, int64_t* value) const { +bool BaseConf::GetConfInt64Human(const std::string& name, int64_t* value) const { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -152,7 +148,7 @@ bool BaseConf::GetConfInt64Human(const std::string &name, int64_t* value) const return false; } -bool BaseConf::GetConfInt64(const std::string &name, int64_t* value) const { +bool BaseConf::GetConfInt64(const std::string& name, int64_t* value) const { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -165,7 +161,7 @@ bool BaseConf::GetConfInt64(const std::string &name, int64_t* value) const { return false; } -bool BaseConf::GetConfStr(const std::string &name, std::string *val) const { +bool BaseConf::GetConfStr(const std::string& name, std::string* val) const { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == 1) { continue; @@ -178,7 +174,7 @@ bool BaseConf::GetConfStr(const std::string &name, std::string *val) const { return false; } -bool BaseConf::GetConfStrVec(const std::string &name, std::vector *value) const { +bool BaseConf::GetConfStrVec(const std::string& name, std::vector* value) const { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -193,7 +189,7 @@ bool BaseConf::GetConfStrVec(const std::string &name, std::vector * break; } value->push_back(StringTrim(val_str.substr(0, pos))); - val_str = val_str.substr(pos+1); + val_str = val_str.substr(pos + 1); } return true; } @@ -201,7 +197,7 @@ bool BaseConf::GetConfStrVec(const std::string &name, std::vector * return false; } -bool BaseConf::GetConfBool(const std::string &name, bool* value) const { +bool BaseConf::GetConfBool(const std::string& name, bool* value) const { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -218,7 +214,7 @@ bool BaseConf::GetConfBool(const std::string &name, bool* value) const { return false; } -bool BaseConf::SetConfInt(const std::string &name, const int value) { +bool BaseConf::SetConfInt(const std::string& name, const int value) { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -231,7 +227,7 @@ bool BaseConf::SetConfInt(const std::string &name, const int value) { return false; } -bool BaseConf::SetConfInt64(const std::string &name, const int64_t value) { +bool BaseConf::SetConfInt64(const std::string& name, const int64_t value) { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -244,7 +240,7 @@ bool BaseConf::SetConfInt64(const std::string &name, const int64_t value) { return false; } -bool BaseConf::SetConfStr(const std::string &name, const std::string &value) { +bool BaseConf::SetConfStr(const std::string& name, const std::string& value) { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -257,7 +253,7 @@ bool BaseConf::SetConfStr(const std::string &name, const std::string &value) { return false; } -bool BaseConf::SetConfBool(const std::string &name, const bool value) { +bool BaseConf::SetConfBool(const std::string& name, const bool value) { for (size_t i = 0; i < rep_->item.size(); i++) { if (rep_->item[i].type == Rep::kComment) { continue; @@ -274,7 +270,7 @@ bool BaseConf::SetConfBool(const std::string &name, const bool value) { return false; } -bool BaseConf::SetConfStrVec(const std::string& name, const std::vector &value) { +bool BaseConf::SetConfStrVec(const std::string& name, const std::vector& value) { std::string value_str = StringConcat(value, COMMA); return SetConfStr(name, value_str); } @@ -301,7 +297,7 @@ void BaseConf::DumpConf() const { } bool BaseConf::WriteBack() { - WritableFile *write_file; + WritableFile* write_file; std::string tmp_path = rep_->path + ".tmp"; Status ret = NewWritableFile(tmp_path, &write_file); log_info("ret %s", ret.ToString().c_str()); @@ -324,7 +320,7 @@ bool BaseConf::WriteBack() { } void BaseConf::WriteSampleConf() const { - WritableFile *write_file; + WritableFile* write_file; std::string sample_path = rep_->path + ".sample"; Status ret = NewWritableFile(sample_path, &write_file); std::string tmp; @@ -340,8 +336,6 @@ void BaseConf::WriteSampleConf() const { return; } -void BaseConf::PushConfItem(const Rep::ConfItem& item) { - rep_->item.push_back(item); -} +void BaseConf::PushConfItem(const Rep::ConfItem& item) { rep_->item.push_back(item); } -} // namespace pstd +} // namespace pstd diff --git a/src/pstd/src/cond_lock.cc b/src/pstd/src/cond_lock.cc index 31dbeb6e52..12a4d4bb7b 100644 --- a/src/pstd/src/cond_lock.cc +++ b/src/pstd/src/cond_lock.cc @@ -19,25 +19,15 @@ static void PthreadCall(const char* label, int result) { } } -CondLock::CondLock() { - PthreadCall("init condlock", pthread_mutex_init(&mutex_, NULL)); -} +CondLock::CondLock() { PthreadCall("init condlock", pthread_mutex_init(&mutex_, NULL)); } -CondLock::~CondLock() { - PthreadCall("destroy condlock", pthread_mutex_unlock(&mutex_)); -} +CondLock::~CondLock() { PthreadCall("destroy condlock", pthread_mutex_unlock(&mutex_)); } -void CondLock::Lock() { - PthreadCall("mutex lock", pthread_mutex_lock(&mutex_)); -} +void CondLock::Lock() { PthreadCall("mutex lock", pthread_mutex_lock(&mutex_)); } -void CondLock::Unlock() { - PthreadCall("mutex unlock", pthread_mutex_unlock(&mutex_)); -} +void CondLock::Unlock() { PthreadCall("mutex unlock", pthread_mutex_unlock(&mutex_)); } -void CondLock::Wait() { - PthreadCall("condlock wait", pthread_cond_wait(&cond_, &mutex_)); -} +void CondLock::Wait() { PthreadCall("condlock wait", pthread_cond_wait(&cond_, &mutex_)); } void CondLock::TimedWait(uint32_t timeout) { /* @@ -55,12 +45,8 @@ void CondLock::TimedWait(uint32_t timeout) { pthread_cond_timedwait(&cond_, &mutex_, &tsp); } -void CondLock::Signal() { - PthreadCall("condlock signal", pthread_cond_signal(&cond_)); -} +void CondLock::Signal() { PthreadCall("condlock signal", pthread_cond_signal(&cond_)); } -void CondLock::Broadcast() { - PthreadCall("condlock broadcast", pthread_cond_broadcast(&cond_)); -} +void CondLock::Broadcast() { PthreadCall("condlock broadcast", pthread_cond_broadcast(&cond_)); } } // namespace pstd diff --git a/src/pstd/src/env.cc b/src/pstd/src/env.cc index 16ae46a02e..c05462b4f5 100644 --- a/src/pstd/src/env.cc +++ b/src/pstd/src/env.cc @@ -3,14 +3,14 @@ #include #include #include -#include #include -#include #include +#include +#include -#include #include #include +#include #include "pstd/include/xdebug.h" @@ -29,13 +29,13 @@ const size_t kPageSize = getpagesize(); int SetMaxFileDescriptorNum(int64_t max_file_descriptor_num) { // Try to Set the number of file descriptor - struct rlimit limit; + struct rlimit limit; if (getrlimit(RLIMIT_NOFILE, &limit) != -1) { if (limit.rlim_cur < (rlim_t)max_file_descriptor_num) { // rlim_cur could be set by any user while rlim_max are // changeable only by root. limit.rlim_cur = max_file_descriptor_num; - if(limit.rlim_cur > limit.rlim_max) { + if (limit.rlim_cur > limit.rlim_max) { limit.rlim_max = max_file_descriptor_num; } if (setrlimit(RLIMIT_NOFILE, &limit) != -1) { @@ -51,15 +51,12 @@ int SetMaxFileDescriptorNum(int64_t max_file_descriptor_num) { } } - /* * size of initial mmap size */ size_t kMmapBoundSize = 1024 * 1024 * 4; -void SetMmapBoundSize(size_t size) { - kMmapBoundSize = size; -} +void SetMmapBoundSize(size_t size) { kMmapBoundSize = size; } static Status IOError(const std::string& context, int err_number) { return Status::IOError(context, strerror(err_number)); @@ -74,9 +71,7 @@ int CreateDir(const std::string& path) { return res; } -bool FileExists(const std::string& path) { - return access(path.c_str(), F_OK) == 0; -} +bool FileExists(const std::string& path) { return access(path.c_str(), F_OK) == 0; } Status DeleteFile(const std::string& fname) { Status result; @@ -86,15 +81,14 @@ Status DeleteFile(const std::string& fname) { return result; } -int DoCreatePath(const char *path, mode_t mode) { +int DoCreatePath(const char* path, mode_t mode) { struct stat st; int status = 0; if (stat(path, &st) != 0) { /* Directory does not exist. EEXIST for race * condition */ - if (mkdir(path, mode) != 0 && errno != EEXIST) - status = -1; + if (mkdir(path, mode) != 0 && errno != EEXIST) status = -1; } else if (!S_ISDIR(st.st_mode)) { errno = ENOTDIR; status = -1; @@ -109,11 +103,11 @@ int DoCreatePath(const char *path, mode_t mode) { ** each directory in path exists, rather than optimistically creating ** the last element and working backwards. */ -int CreatePath(const std::string &path, mode_t mode) { - char *pp; - char *sp; - int status; - char *copypath = strdup(path.c_str()); +int CreatePath(const std::string& path, mode_t mode) { + char* pp; + char* sp; + int status; + char* copypath = strdup(path.c_str()); status = 0; pp = copypath; @@ -126,8 +120,7 @@ int CreatePath(const std::string &path, mode_t mode) { } pp = sp + 1; } - if (status == 0) - status = DoCreatePath(path.c_str(), mode); + if (status == 0) status = DoCreatePath(path.c_str(), mode); free(copypath); return (status); } @@ -139,7 +132,7 @@ static int LockOrUnlock(int fd, bool lock) { f.l_type = (lock ? F_WRLCK : F_UNLCK); f.l_whence = SEEK_SET; f.l_start = 0; - f.l_len = 0; // Lock/unlock entire file + f.l_len = 0; // Lock/unlock entire file return fcntl(fd, F_SETLK, &f); } @@ -222,27 +215,26 @@ int IsDir(const std::string& path) { int ret = stat(path.c_str(), &buf); if (0 == ret) { if (buf.st_mode & S_IFDIR) { - //folder + // folder return 0; } else { - //file + // file return 1; } } return -1; } -int DeleteDir(const std::string& path) -{ +int DeleteDir(const std::string& path) { char chBuf[256]; - DIR * dir = NULL; - struct dirent *ptr; + DIR* dir = NULL; + struct dirent* ptr; int ret = 0; dir = opendir(path.c_str()); if (NULL == dir) { return -1; } - while((ptr = readdir(dir)) != NULL) { + while ((ptr = readdir(dir)) != NULL) { ret = strcmp(ptr->d_name, "."); if (0 == ret) { continue; @@ -254,16 +246,15 @@ int DeleteDir(const std::string& path) snprintf(chBuf, 256, "%s/%s", path.c_str(), ptr->d_name); ret = IsDir(chBuf); if (0 == ret) { - //is dir + // is dir ret = DeleteDir(chBuf); if (0 != ret) { return -1; } - } - else if (1 == ret) { - //is file + } else if (1 == ret) { + // is file ret = remove(chBuf); - if(0 != ret) { + if (0 != ret) { return -1; } } @@ -294,8 +285,8 @@ uint64_t Du(const std::string& filename) { } sum = statbuf.st_size; if (S_ISDIR(statbuf.st_mode)) { - DIR *dir = NULL; - struct dirent *entry; + DIR* dir = NULL; + struct dirent* entry; std::string newfile; dir = opendir(filename.c_str()); @@ -320,25 +311,19 @@ uint64_t NowMicros() { return static_cast(tv.tv_sec) * 1000000 + tv.tv_usec; } -void SleepForMicroseconds(int micros) { - usleep(micros); -} +void SleepForMicroseconds(int micros) { usleep(micros); } -SequentialFile::~SequentialFile() { -} +SequentialFile::~SequentialFile() {} -class PosixSequentialFile: public SequentialFile { +class PosixSequentialFile : public SequentialFile { private: std::string filename_; FILE* file_; public: - virtual void setUnBuffer() { - setbuf(file_, NULL); - } + virtual void setUnBuffer() { setbuf(file_, NULL); } - PosixSequentialFile(const std::string& fname, FILE* f) - : filename_(fname), file_(f) { setbuf(file_, NULL); } + PosixSequentialFile(const std::string& fname, FILE* f) : filename_(fname), file_(f) { setbuf(file_, NULL); } virtual ~PosixSequentialFile() { if (file_) { @@ -371,9 +356,7 @@ class PosixSequentialFile: public SequentialFile { return Status::OK(); } - virtual char *ReadLine(char* buf, int n) override { - return fgets(buf, n, file_); - } + virtual char* ReadLine(char* buf, int n) override { return fgets(buf, n, file_); } virtual Status Close() { if (fclose(file_) != 0) { @@ -384,15 +367,13 @@ class PosixSequentialFile: public SequentialFile { } }; -WritableFile::~WritableFile() { -} +WritableFile::~WritableFile() {} // We preallocate up to an extra megabyte and use memcpy to append new // data to the file. This is safe since we either properly close the // file before reading from it, or for log files, the reading code // knows enough to skip zero suffixes. -class PosixMmapFile : public WritableFile -{ +class PosixMmapFile : public WritableFile { private: std::string filename_; int fd_; @@ -405,18 +386,13 @@ class PosixMmapFile : public WritableFile uint64_t file_offset_; // Offset of base_ in file uint64_t write_len_; // The data that written in the file - // Have we done an munmap of unsynced data? bool pending_sync_; // Roundup x to a multiple of y - static size_t Roundup(size_t x, size_t y) { - return ((x + y - 1) / y) * y; - } + static size_t Roundup(size_t x, size_t y) { return ((x + y - 1) / y) * y; } - static size_t TrimDown(size_t x, size_t y) { - return (x / y) * y; - } + static size_t TrimDown(size_t x, size_t y) { return (x / y) * y; } size_t TruncateToPageBoundary(size_t s) { s -= (s & (page_size_ - 1)); assert((s % page_size_) == 0); @@ -440,7 +416,7 @@ class PosixMmapFile : public WritableFile dst_ = NULL; // Increase the amount we map the next time, but capped at 1MB - if (map_size_ < (1<<20)) { + if (map_size_ < (1 << 20)) { map_size_ *= 2; } } @@ -457,9 +433,8 @@ class PosixMmapFile : public WritableFile log_warn("ftruncate error"); return false; } - //log_info("map_size %d fileoffset %llu", map_size_, file_offset_); - void* ptr = mmap(NULL, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, - fd_, file_offset_); + // log_info("map_size %d fileoffset %llu", map_size_, file_offset_); + void* ptr = mmap(NULL, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, file_offset_); if (ptr == MAP_FAILED) { log_warn("mmap failed"); return false; @@ -475,24 +450,23 @@ class PosixMmapFile : public WritableFile public: PosixMmapFile(const std::string& fname, int fd, size_t page_size, uint64_t write_len = 0) : filename_(fname), - fd_(fd), - page_size_(page_size), - map_size_(Roundup(kMmapBoundSize, page_size)), - base_(NULL), - limit_(NULL), - dst_(NULL), - last_sync_(NULL), - file_offset_(0), - write_len_(write_len), - pending_sync_(false) { - if (write_len_ != 0) { - while (map_size_ < write_len_) { - map_size_ += (1024 * 1024); - } - } - assert((page_size & (page_size - 1)) == 0); + fd_(fd), + page_size_(page_size), + map_size_(Roundup(kMmapBoundSize, page_size)), + base_(NULL), + limit_(NULL), + dst_(NULL), + last_sync_(NULL), + file_offset_(0), + write_len_(write_len), + pending_sync_(false) { + if (write_len_ != 0) { + while (map_size_ < write_len_) { + map_size_ += (1024 * 1024); } - + } + assert((page_size & (page_size - 1)) == 0); + } ~PosixMmapFile() { if (fd_ >= 0) { @@ -545,9 +519,7 @@ class PosixMmapFile : public WritableFile return s; } - virtual Status Flush() { - return Status::OK(); - } + virtual Status Flush() { return Status::OK(); } virtual Status Sync() { Status s; @@ -591,175 +563,160 @@ class PosixMmapFile : public WritableFile return Status::OK(); } - virtual uint64_t Filesize() { - return write_len_ + file_offset_ + (dst_ - base_); - } + virtual uint64_t Filesize() { return write_len_ + file_offset_ + (dst_ - base_); } }; +RWFile::~RWFile() {} -RWFile::~RWFile() { -} - -class MmapRWFile : public RWFile -{ +class MmapRWFile : public RWFile { public: - MmapRWFile(const std::string& fname, int fd, size_t page_size) - : filename_(fname), - fd_(fd), - page_size_(page_size), - map_size_(Roundup(65536, page_size)), - base_(NULL) { - DoMapRegion(); - } - - ~MmapRWFile() { - if (fd_ >= 0) { - munmap(base_, map_size_); - } - } - - bool DoMapRegion() { + MmapRWFile(const std::string& fname, int fd, size_t page_size) + : filename_(fname), fd_(fd), page_size_(page_size), map_size_(Roundup(65536, page_size)), base_(NULL) { + DoMapRegion(); + } + + ~MmapRWFile() { + if (fd_ >= 0) { + munmap(base_, map_size_); + } + } + + bool DoMapRegion() { #if defined(__APPLE__) - if (ftruncate(fd_, map_size_) != 0) { + if (ftruncate(fd_, map_size_) != 0) { #else - if (posix_fallocate(fd_, 0, map_size_) != 0) { + if (posix_fallocate(fd_, 0, map_size_) != 0) { #endif - return false; - } - void* ptr = mmap(NULL, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0); - if (ptr == MAP_FAILED) { - return false; - } - base_ = reinterpret_cast(ptr); - return true; - } - - char* GetData() { return base_; } - char* base() { return base_; } + return false; + } + void* ptr = mmap(NULL, map_size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0); + if (ptr == MAP_FAILED) { + return false; + } + base_ = reinterpret_cast(ptr); + return true; + } + + char* GetData() { return base_; } + char* base() { return base_; } private: - static size_t Roundup(size_t x, size_t y) { - return ((x + y - 1) / y) * y; - } - std::string filename_; - int fd_; - size_t page_size_; - size_t map_size_; - char* base_; + static size_t Roundup(size_t x, size_t y) { return ((x + y - 1) / y) * y; } + std::string filename_; + int fd_; + size_t page_size_; + size_t map_size_; + char* base_; }; class PosixRandomRWFile : public RandomRWFile { private: - const std::string filename_; - int fd_; - bool pending_sync_; - bool pending_fsync_; - //bool fallocate_with_keep_size_; + const std::string filename_; + int fd_; + bool pending_sync_; + bool pending_fsync_; + // bool fallocate_with_keep_size_; public: - PosixRandomRWFile(const std::string& fname, int fd) - : filename_(fname), - fd_(fd), - pending_sync_(false), - pending_fsync_(false) { - //fallocate_with_keep_size_ = options.fallocate_with_keep_size; - } - - ~PosixRandomRWFile() { - if (fd_ >= 0) { - Close(); - } - } - - virtual Status Write(uint64_t offset, const Slice& data) override { - const char* src = data.data(); - size_t left = data.size(); - Status s; - pending_sync_ = true; - pending_fsync_ = true; - - while (left != 0) { - ssize_t done = pwrite(fd_, src, left, offset); - if (done < 0) { - if (errno == EINTR) { - continue; - } - return IOError(filename_, errno); - } - - left -= done; - src += done; - offset += done; - } - - return Status::OK(); - } - - virtual Status Read(uint64_t offset, size_t n, Slice* result, - char* scratch) const override { - Status s; - ssize_t r = -1; - size_t left = n; - char* ptr = scratch; - while (left > 0) { - r = pread(fd_, ptr, left, static_cast(offset)); - if (r <= 0) { - if (errno == EINTR) { - continue; - } - break; - } - ptr += r; - offset += r; - left -= r; - } - *result = Slice(scratch, (r < 0) ? 0 : n - left); - if (r < 0) { - s = IOError(filename_, errno); - } - return s; - } - - virtual Status Close() override { - Status s = Status::OK(); - if (fd_ >= 0 && close(fd_) < 0) { - s = IOError(filename_, errno); - } - fd_ = -1; - return s; - } - - virtual Status Sync() override { + PosixRandomRWFile(const std::string& fname, int fd) + : filename_(fname), fd_(fd), pending_sync_(false), pending_fsync_(false) { + // fallocate_with_keep_size_ = options.fallocate_with_keep_size; + } + + ~PosixRandomRWFile() { + if (fd_ >= 0) { + Close(); + } + } + + virtual Status Write(uint64_t offset, const Slice& data) override { + const char* src = data.data(); + size_t left = data.size(); + Status s; + pending_sync_ = true; + pending_fsync_ = true; + + while (left != 0) { + ssize_t done = pwrite(fd_, src, left, offset); + if (done < 0) { + if (errno == EINTR) { + continue; + } + return IOError(filename_, errno); + } + + left -= done; + src += done; + offset += done; + } + + return Status::OK(); + } + + virtual Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const override { + Status s; + ssize_t r = -1; + size_t left = n; + char* ptr = scratch; + while (left > 0) { + r = pread(fd_, ptr, left, static_cast(offset)); + if (r <= 0) { + if (errno == EINTR) { + continue; + } + break; + } + ptr += r; + offset += r; + left -= r; + } + *result = Slice(scratch, (r < 0) ? 0 : n - left); + if (r < 0) { + s = IOError(filename_, errno); + } + return s; + } + + virtual Status Close() override { + Status s = Status::OK(); + if (fd_ >= 0 && close(fd_) < 0) { + s = IOError(filename_, errno); + } + fd_ = -1; + return s; + } + + virtual Status Sync() override { #if defined(__APPLE__) - if (pending_sync_ && fsync(fd_) < 0) { + if (pending_sync_ && fsync(fd_) < 0) { #else - if (pending_sync_ && fdatasync(fd_) < 0) { + if (pending_sync_ && fdatasync(fd_) < 0) { #endif - return IOError(filename_, errno); - } - pending_sync_ = false; - return Status::OK(); - } - - virtual Status Fsync() override { - if (pending_fsync_ && fsync(fd_) < 0) { - return IOError(filename_, errno); - } - pending_fsync_ = false; - pending_sync_ = false; - return Status::OK(); - } - -// virtual Status Allocate(off_t offset, off_t len) override { -// TEST_KILL_RANDOM(rocksdb_kill_odds); -// int alloc_status = fallocate( -// fd_, fallocate_with_keep_size_ ? FALLOC_FL_KEEP_SIZE : 0, offset, len); -// if (alloc_status == 0) { -// return Status::OK(); -// } else { -// return IOError(filename_, errno); -// } -// } + return IOError(filename_, errno); + } + pending_sync_ = false; + return Status::OK(); + } + + virtual Status Fsync() override { + if (pending_fsync_ && fsync(fd_) < 0) { + return IOError(filename_, errno); + } + pending_fsync_ = false; + pending_sync_ = false; + return Status::OK(); + } + + // virtual Status Allocate(off_t offset, off_t len) override { + // TEST_KILL_RANDOM(rocksdb_kill_odds); + // int alloc_status = fallocate( + // fd_, fallocate_with_keep_size_ ? FALLOC_FL_KEEP_SIZE : 0, offset, len); + // if (alloc_status == 0) { + // return Status::OK(); + // } else { + // return IOError(filename_, errno); + // } + // } }; Status NewSequentialFile(const std::string& fname, SequentialFile** result) { @@ -821,4 +778,4 @@ Status NewRandomRWFile(const std::string& fname, RandomRWFile** result) { return s; } -} // namespace pstd +} // namespace pstd diff --git a/src/pstd/src/lock_mgr.cc b/src/pstd/src/lock_mgr.cc index d86d67b47e..342acc6645 100644 --- a/src/pstd/src/lock_mgr.cc +++ b/src/pstd/src/lock_mgr.cc @@ -4,16 +4,16 @@ // of patent rights can be found in the PATENTS file in the same directory. #ifndef __STDC_FORMAT_MACROS -#define __STDC_FORMAT_MACROS +# define __STDC_FORMAT_MACROS #endif #include "pstd/include/lock_mgr.h" -#include -#include #include -#include #include +#include +#include +#include #include "pstd/include/mutex.h" @@ -41,9 +41,7 @@ struct LockMapStripe { // Map of #num_stripes LockMapStripes struct LockMap { - explicit LockMap(size_t num_stripes, - std::shared_ptr factory) - : num_stripes_(num_stripes) { + explicit LockMap(size_t num_stripes, std::shared_ptr factory) : num_stripes_(num_stripes) { lock_map_stripes_.reserve(num_stripes); for (size_t i = 0; i < num_stripes; i++) { LockMapStripe* stripe = new LockMapStripe(factory); @@ -75,14 +73,11 @@ size_t LockMap::GetStripe(const std::string& key) const { return stripe; } -LockMgr::LockMgr(size_t default_num_stripes, - int64_t max_num_locks, - std::shared_ptr mutex_factory) +LockMgr::LockMgr(size_t default_num_stripes, int64_t max_num_locks, std::shared_ptr mutex_factory) : default_num_stripes_(default_num_stripes), max_num_locks_(max_num_locks), mutex_factory_(mutex_factory), - lock_map_(std::shared_ptr( - new LockMap(default_num_stripes, mutex_factory))) {} + lock_map_(std::shared_ptr(new LockMap(default_num_stripes, mutex_factory))) {} LockMgr::~LockMgr() {} @@ -99,8 +94,7 @@ Status LockMgr::TryLock(const std::string& key) { } // Helper function for TryLock(). -Status LockMgr::Acquire(LockMapStripe* stripe, - const std::string& key) { +Status LockMgr::Acquire(LockMapStripe* stripe, const std::string& key) { Status result; // we wait indefinitely to acquire the lock @@ -131,17 +125,15 @@ Status LockMgr::Acquire(LockMapStripe* stripe, // Try to lock this key after we have acquired the mutex. // REQUIRED: Stripe mutex must be held. -Status LockMgr::AcquireLocked(LockMapStripe* stripe, - const std::string& key) { +Status LockMgr::AcquireLocked(LockMapStripe* stripe, const std::string& key) { Status result; // Check if this key is already locked if (stripe->keys.find(key) != stripe->keys.end()) { // Lock already held - result = Status::Busy("LockTimeout"); + result = Status::Busy("LockTimeout"); } else { // Lock not held. // Check lock limit - if (max_num_locks_ > 0 && - lock_map_->lock_cnt.load(std::memory_order_acquire) >= max_num_locks_) { + if (max_num_locks_ > 0 && lock_map_->lock_cnt.load(std::memory_order_acquire) >= max_num_locks_) { result = Status::Busy("LockLimit"); } else { // acquire lock diff --git a/src/pstd/src/mutex_impl.cc b/src/pstd/src/mutex_impl.cc index 6b67c399d1..68e1573771 100644 --- a/src/pstd/src/mutex_impl.cc +++ b/src/pstd/src/mutex_impl.cc @@ -3,7 +3,6 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. - #include #include @@ -37,8 +36,7 @@ class CondVarImpl : public CondVar { Status Wait(std::shared_ptr mutex) override; - Status WaitFor(std::shared_ptr mutex, - int64_t timeout_time) override; + Status WaitFor(std::shared_ptr mutex, int64_t timeout_time) override; void Notify() override { cv_.notify_one(); } @@ -48,15 +46,9 @@ class CondVarImpl : public CondVar { std::condition_variable cv_; }; -std::shared_ptr -MutexFactoryImpl::AllocateMutex() { - return std::shared_ptr(new MutexImpl()); -} +std::shared_ptr MutexFactoryImpl::AllocateMutex() { return std::shared_ptr(new MutexImpl()); } -std::shared_ptr -MutexFactoryImpl::AllocateCondVar() { - return std::shared_ptr(new CondVarImpl()); -} +std::shared_ptr MutexFactoryImpl::AllocateCondVar() { return std::shared_ptr(new CondVarImpl()); } Status MutexImpl::Lock() { mutex_.lock(); @@ -87,8 +79,7 @@ Status MutexImpl::TryLockFor(int64_t timeout_time) { return Status::OK(); } -Status CondVarImpl::Wait( - std::shared_ptr mutex) { +Status CondVarImpl::Wait(std::shared_ptr mutex) { auto mutex_impl = reinterpret_cast(mutex.get()); std::unique_lock lock(mutex_impl->mutex_, std::adopt_lock); @@ -100,8 +91,7 @@ Status CondVarImpl::Wait( return Status::OK(); } -Status CondVarImpl::WaitFor( - std::shared_ptr mutex, int64_t timeout_time) { +Status CondVarImpl::WaitFor(std::shared_ptr mutex, int64_t timeout_time) { Status s; auto mutex_impl = reinterpret_cast(mutex.get()); diff --git a/src/pstd/src/posix.cc b/src/pstd/src/posix.cc index 135b6dcb4e..0ad482b07a 100644 --- a/src/pstd/src/posix.cc +++ b/src/pstd/src/posix.cc @@ -1,13 +1,12 @@ -#include "pstd/include/xdebug.h" #include "pstd/include/posix.h" - +#include "pstd/include/xdebug.h" + /********************************************* * Wrappers for Unix process control functions ********************************************/ /* $begin forkwrapper */ -pid_t Fork(void) -{ +pid_t Fork(void) { pid_t pid; if ((pid = fork()) < 0) { @@ -17,38 +16,34 @@ pid_t Fork(void) } /* $end forkwrapper */ -void Execve(const char *filename, char *const argv[], char *const envp[]) -{ +void Execve(const char* filename, char* const argv[], char* const envp[]) { if (execve(filename, argv, envp) < 0) { log_err("Execve error: %s\n", strerror(errno)); } } /* $begin wait */ -pid_t Wait(int *status) -{ +pid_t Wait(int* status) { pid_t pid; - if ((pid = wait(status)) < 0) { + if ((pid = wait(status)) < 0) { log_err("Wait error: %s\n", strerror(errno)); } return pid; } /* $end wait */ -pid_t Waitpid(pid_t pid, int *iptr, int options) -{ +pid_t Waitpid(pid_t pid, int* iptr, int options) { pid_t retpid; - if ((retpid = waitpid(pid, iptr, options)) < 0) { + if ((retpid = waitpid(pid, iptr, options)) < 0) { log_err("Waitpid error: %s\n", strerror(errno)); } - return(retpid); + return (retpid); } /* $begin kill */ -void Kill(pid_t pid, int signum) -{ +void Kill(pid_t pid, int signum) { int rc; if ((rc = kill(pid, signum)) < 0) { @@ -57,20 +52,14 @@ void Kill(pid_t pid, int signum) } /* $end kill */ -void Pause() -{ +void Pause() { (void)pause(); return; } -unsigned int Sleep(unsigned int secs) -{ - return sleep(secs); -} +unsigned int Sleep(unsigned int secs) { return sleep(secs); } -unsigned int Alarm(unsigned int seconds) { - return alarm(seconds); -} +unsigned int Alarm(unsigned int seconds) { return alarm(seconds); } void Setpgid(pid_t pid, pid_t pgid) { int rc; @@ -81,20 +70,17 @@ void Setpgid(pid_t pid, pid_t pgid) { return; } -pid_t Getpgrp(void) { - return getpgrp(); -} +pid_t Getpgrp(void) { return getpgrp(); } /************************************ - * Wrappers for Unix signal functions + * Wrappers for Unix signal functions ***********************************/ /* $begin sigaction */ -handler_t *Signal(int signum, handler_t *handler) -{ +handler_t* Signal(int signum, handler_t* handler) { struct sigaction action, old_action; - action.sa_handler = handler; + action.sa_handler = handler; sigemptyset(&action.sa_mask); /* block sigs of type being handled */ action.sa_flags = SA_RESTART; /* restart syscalls if possible */ @@ -105,48 +91,42 @@ handler_t *Signal(int signum, handler_t *handler) } /* $end sigaction */ -void Sigprocmask(int how, const sigset_t *set, sigset_t *oldset) -{ +void Sigprocmask(int how, const sigset_t* set, sigset_t* oldset) { if (sigprocmask(how, set, oldset) < 0) { log_err("Sigprocmask error: %s\n", strerror(errno)); } return; } -void Sigemptyset(sigset_t *set) -{ +void Sigemptyset(sigset_t* set) { if (sigemptyset(set) < 0) { log_err("Sigemptyset error: %s\n", strerror(errno)); } return; } -void Sigfillset(sigset_t *set) -{ +void Sigfillset(sigset_t* set) { if (sigfillset(set) < 0) { log_err("Sigfillset error: %s\n", strerror(errno)); } return; } -void Sigaddset(sigset_t *set, int signum) -{ +void Sigaddset(sigset_t* set, int signum) { if (sigaddset(set, signum) < 0) { log_err("Sigaddset error: %s\n", strerror(errno)); } return; } -void Sigdelset(sigset_t *set, int signum) -{ +void Sigdelset(sigset_t* set, int signum) { if (sigdelset(set, signum) < 0) { log_err("Sigdelset error: %s\n", strerror(errno)); } return; } -int Sigismember(const sigset_t *set, int signum) -{ +int Sigismember(const sigset_t* set, int signum) { int rc; if ((rc = sigismember(set, signum)) < 0) { log_err("Sigismember error: %s\n", strerror(errno)); @@ -154,33 +134,29 @@ int Sigismember(const sigset_t *set, int signum) return rc; } - /******************************** * Wrappers for Unix I/O routines ********************************/ -int Open(const char *pathname, int flags, mode_t mode) -{ +int Open(const char* pathname, int flags, mode_t mode) { int rc; - if ((rc = open(pathname, flags, mode)) < 0) { + if ((rc = open(pathname, flags, mode)) < 0) { log_err("Open error: %s\n", strerror(errno)); } return rc; } -ssize_t Read(int fd, void *buf, size_t count) -{ +ssize_t Read(int fd, void* buf, size_t count) { ssize_t rc; - if ((rc = read(fd, buf, count)) < 0) { + if ((rc = read(fd, buf, count)) < 0) { log_err("Read error: %s\n", strerror(errno)); } return rc; } -ssize_t Write(int fd, const void *buf, size_t count) -{ +ssize_t Write(int fd, const void* buf, size_t count) { ssize_t rc; if ((rc = write(fd, buf, count)) < 0) { @@ -189,8 +165,7 @@ ssize_t Write(int fd, const void *buf, size_t count) return rc; } -off_t Lseek(int fildes, off_t offset, int whence) -{ +off_t Lseek(int fildes, off_t offset, int whence) { off_t rc; if ((rc = lseek(fildes, offset, whence)) < 0) { @@ -199,8 +174,7 @@ off_t Lseek(int fildes, off_t offset, int whence) return rc; } -void Close(int fd) -{ +void Close(int fd) { int rc; if ((rc = close(fd)) < 0) { @@ -208,9 +182,7 @@ void Close(int fd) } } -int Select(int n, fd_set *readfds, fd_set *writefds, - fd_set *exceptfds, struct timeval *timeout) -{ +int Select(int n, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, struct timeval* timeout) { int rc; if ((rc = select(n, readfds, writefds, exceptfds, timeout)) < 0) { @@ -219,8 +191,7 @@ int Select(int n, fd_set *readfds, fd_set *writefds, return rc; } -int Dup2(int fd1, int fd2) -{ +int Dup2(int fd1, int fd2) { int rc; if ((rc = dup2(fd1, fd2)) < 0) { @@ -229,15 +200,13 @@ int Dup2(int fd1, int fd2) return rc; } -void Stat(const char *filename, struct stat *buf) -{ +void Stat(const char* filename, struct stat* buf) { if (stat(filename, buf) < 0) { log_err("Stat error: %s\n", strerror(errno)); } } -void Fstat(int fd, struct stat *buf) -{ +void Fstat(int fd, struct stat* buf) { if (fstat(fd, buf) < 0) { log_err("Fstat error: %s\n", strerror(errno)); } @@ -246,18 +215,16 @@ void Fstat(int fd, struct stat *buf) /*************************************** * Wrappers for memory mapping functions ***************************************/ -void *Mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset) -{ - void *ptr; +void* Mmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset) { + void* ptr; - if ((ptr = mmap(addr, len, prot, flags, fd, offset)) == ((void *) -1)) { + if ((ptr = mmap(addr, len, prot, flags, fd, offset)) == ((void*)-1)) { log_err("mmap error: %s\n", strerror(errno)); } - return(ptr); + return (ptr); } -void Munmap(void *start, size_t length) -{ +void Munmap(void* start, size_t length) { if (munmap(start, length) < 0) { log_err("munmap error: %s\n", strerror(errno)); } @@ -267,29 +234,26 @@ void Munmap(void *start, size_t length) * Wrappers for dynamic storage allocation functions ***************************************************/ -void *Malloc(size_t size) -{ - void *p; +void* Malloc(size_t size) { + void* p; - if ((p = malloc(size)) == NULL) { + if ((p = malloc(size)) == NULL) { log_err("Malloc error: %s\n", strerror(errno)); } return p; } -void *Realloc(void *ptr, size_t size) -{ - void *p; +void* Realloc(void* ptr, size_t size) { + void* p; - if ((p = realloc(ptr, size)) == NULL) { + if ((p = realloc(ptr, size)) == NULL) { log_err("Realloc error: %s\n", strerror(errno)); } return p; } -void *Calloc(size_t nmemb, size_t size) -{ - void *p; +void* Calloc(size_t nmemb, size_t size) { + void* p; if ((p = calloc(nmemb, size)) == NULL) { log_err("Calloc error: %s\n", strerror(errno)); @@ -297,24 +261,19 @@ void *Calloc(size_t nmemb, size_t size) return p; } -void Free(void *ptr) -{ - free(ptr); -} +void Free(void* ptr) { free(ptr); } /****************************************** * Wrappers for the Standard I/O functions. ******************************************/ -void Fclose(FILE *fp) -{ +void Fclose(FILE* fp) { if (fclose(fp) != 0) { log_err("Fclose error: %s\n", strerror(errno)); } } -FILE *Fdopen(int fd, const char *type) -{ - FILE *fp; +FILE* Fdopen(int fd, const char* type) { + FILE* fp; if ((fp = fdopen(fd, type)) == NULL) { log_err("Fdopen error: %s\n", strerror(errno)); @@ -323,9 +282,8 @@ FILE *Fdopen(int fd, const char *type) return fp; } -char *Fgets(char *ptr, int n, FILE *stream) -{ - char *rptr; +char* Fgets(char* ptr, int n, FILE* stream) { + char* rptr; if (((rptr = fgets(ptr, n, stream)) == NULL) && ferror(stream)) { log_err("Fgets error"); @@ -334,9 +292,8 @@ char *Fgets(char *ptr, int n, FILE *stream) return rptr; } -FILE *Fopen(const char *filename, const char *mode) -{ - FILE *fp; +FILE* Fopen(const char* filename, const char* mode) { + FILE* fp; if ((fp = fopen(filename, mode)) == NULL) { log_err("Fopen error: %s\n", strerror(errno)); @@ -345,37 +302,32 @@ FILE *Fopen(const char *filename, const char *mode) return fp; } -void Fputs(const char *ptr, FILE *stream) -{ +void Fputs(const char* ptr, FILE* stream) { if (fputs(ptr, stream) == EOF) { log_err("Fputs error: %s\n", strerror(errno)); } } -size_t Fread(void *ptr, size_t size, size_t nmemb, FILE *stream) -{ +size_t Fread(void* ptr, size_t size, size_t nmemb, FILE* stream) { size_t n; - if (((n = fread(ptr, size, nmemb, stream)) < nmemb) && ferror(stream)) { + if (((n = fread(ptr, size, nmemb, stream)) < nmemb) && ferror(stream)) { log_err("Fread error: %s\n", strerror(errno)); } return n; } -void Fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) -{ +void Fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream) { if (fwrite(ptr, size, nmemb, stream) < nmemb) { log_err("Fwrite error: %s\n", strerror(errno)); } } - -/**************************** +/**************************** * Sockets interface wrappers ****************************/ -int Socket(int domain, int type, int protocol) -{ +int Socket(int domain, int type, int protocol) { int rc; if ((rc = socket(domain, type, protocol)) < 0) { @@ -384,8 +336,7 @@ int Socket(int domain, int type, int protocol) return rc; } -void Setsockopt(int s, int level, int optname, const void *optval, int optlen) -{ +void Setsockopt(int s, int level, int optname, const void* optval, int optlen) { int rc; if ((rc = setsockopt(s, level, optname, optval, optlen)) < 0) { @@ -393,8 +344,7 @@ void Setsockopt(int s, int level, int optname, const void *optval, int optlen) } } -void Bind(int sockfd, struct sockaddr *my_addr, int addrlen) -{ +void Bind(int sockfd, struct sockaddr* my_addr, int addrlen) { int rc; if ((rc = bind(sockfd, my_addr, addrlen)) < 0) { @@ -402,17 +352,15 @@ void Bind(int sockfd, struct sockaddr *my_addr, int addrlen) } } -void Listen(int s, int backlog) -{ +void Listen(int s, int backlog) { int rc; - if ((rc = listen(s, backlog)) < 0) { + if ((rc = listen(s, backlog)) < 0) { log_err("Listen error: %s\n", strerror(errno)); } } -int Accept(int s, struct sockaddr *addr, socklen_t *addrlen) -{ +int Accept(int s, struct sockaddr* addr, socklen_t* addrlen) { int rc; if ((rc = accept(s, addr, addrlen)) < 0) { @@ -421,8 +369,7 @@ int Accept(int s, struct sockaddr *addr, socklen_t *addrlen) return rc; } -void Connect(int sockfd, struct sockaddr *serv_addr, int addrlen) -{ +void Connect(int sockfd, struct sockaddr* serv_addr, int addrlen) { int rc; if ((rc = connect(sockfd, serv_addr, addrlen)) < 0) { @@ -431,13 +378,12 @@ void Connect(int sockfd, struct sockaddr *serv_addr, int addrlen) } /************************ - * DNS interface wrappers + * DNS interface wrappers ***********************/ /* $begin gethostbyname */ -struct hostent *Gethostbyname(const char *name) -{ - struct hostent *p; +struct hostent* Gethostbyname(const char* name) { + struct hostent* p; if ((p = gethostbyname(name)) == NULL) { log_err("%s: DNS error %d\n", "Gethostbyname error", h_errno); @@ -446,9 +392,8 @@ struct hostent *Gethostbyname(const char *name) } /* $end gethostbyname */ -struct hostent *Gethostbyaddr(const char *addr, int len, int type) -{ - struct hostent *p; +struct hostent* Gethostbyaddr(const char* addr, int len, int type) { + struct hostent* p; if ((p = gethostbyaddr(addr, len, type)) == NULL) { log_err("%s: DNS error %d\n", "Gethostbyaddr error", h_errno); @@ -460,9 +405,7 @@ struct hostent *Gethostbyaddr(const char *addr, int len, int type) * Wrappers for Pthreads thread control functions ************************************************/ -void Pthread_create(pthread_t *tidp, pthread_attr_t *attrp, - void * (*routine)(void *), void *argp) -{ +void Pthread_create(pthread_t* tidp, pthread_attr_t* attrp, void* (*routine)(void*), void* argp) { int rc; if ((rc = pthread_create(tidp, attrp, routine, argp)) != 0) { @@ -478,7 +421,7 @@ void Pthread_cancel(pthread_t tid) { } } -void Pthread_join(pthread_t tid, void **thread_return) { +void Pthread_join(pthread_t tid, void** thread_return) { int rc; if ((rc = pthread_join(tid, thread_return)) != 0) { @@ -496,38 +439,29 @@ void Pthread_detach(pthread_t tid) { } /* $end detach */ -void Pthread_exit(void *retval) { - pthread_exit(retval); -} +void Pthread_exit(void* retval) { pthread_exit(retval); } -pthread_t Pthread_self(void) { - return pthread_self(); -} +pthread_t Pthread_self(void) { return pthread_self(); } -void Pthread_once(pthread_once_t *once_control, void (*init_function)()) { - pthread_once(once_control, init_function); -} +void Pthread_once(pthread_once_t* once_control, void (*init_function)()) { pthread_once(once_control, init_function); } /******************************* * Wrappers for Posix semaphores *******************************/ -void Sem_init(sem_t *sem, int pshared, unsigned int value) -{ +void Sem_init(sem_t* sem, int pshared, unsigned int value) { if (sem_init(sem, pshared, value) < 0) { log_err("Sem_init error: %s\n", strerror(errno)); } } -void P(sem_t *sem) -{ +void P(sem_t* sem) { if (sem_wait(sem) < 0) { log_err("P error: %s\n", strerror(errno)); } } -void V(sem_t *sem) -{ +void V(sem_t* sem) { if (sem_post(sem) < 0) { log_err("V error: %s\n", strerror(errno)); } @@ -540,25 +474,23 @@ void V(sem_t *sem) * rio_readn - robustly read n bytes (unbuffered) */ /* $begin rio_readn */ -ssize_t rio_readn(int fd, void *usrbuf, size_t n) -{ +ssize_t rio_readn(int fd, void* usrbuf, size_t n) { size_t nleft = n; ssize_t nread; - char *bufp = (char *)usrbuf; + char* bufp = (char*)usrbuf; while (nleft > 0) { if ((nread = read(fd, bufp, nleft)) < 0) { if (errno == EINTR) /* interrupted by sig handler return */ - nread = 0; /* and call read() again */ + nread = 0; /* and call read() again */ else - return -1; /* errno set by read() */ - } - else if (nread == 0) - break; /* EOF */ + return -1; /* errno set by read() */ + } else if (nread == 0) + break; /* EOF */ nleft -= nread; bufp += nread; } - return (n - nleft); /* return >= 0 */ + return (n - nleft); /* return >= 0 */ } /* $end rio_readn */ @@ -566,18 +498,17 @@ ssize_t rio_readn(int fd, void *usrbuf, size_t n) * rio_writen - robustly write n bytes (unbuffered) */ /* $begin rio_writen */ -ssize_t rio_writen(int fd, void *usrbuf, size_t n) -{ +ssize_t rio_writen(int fd, void* usrbuf, size_t n) { size_t nleft = n; ssize_t nwritten; - char *bufp = (char *)usrbuf; + char* bufp = (char*)usrbuf; while (nleft > 0) { if ((nwritten = write(fd, bufp, nleft)) <= 0) { - if (errno == EINTR) /* interrupted by sig handler return */ - nwritten = 0; /* and call write() again */ + if (errno == EINTR) /* interrupted by sig handler return */ + nwritten = 0; /* and call write() again */ else - return -1; /* errorno set by write() */ + return -1; /* errorno set by write() */ } nleft -= nwritten; bufp += nwritten; @@ -586,8 +517,7 @@ ssize_t rio_writen(int fd, void *usrbuf, size_t n) } /* $end rio_writen */ - -/* +/* * rio_read - This is a wrapper for the Unix read() function that * transfers min(n, rio_cnt) bytes from an internal buffer to a user * buffer, where n is the number of bytes requested by the user and @@ -596,27 +526,23 @@ ssize_t rio_writen(int fd, void *usrbuf, size_t n) * read() if the internal buffer is empty. */ /* $begin rio_read */ -static ssize_t rio_read(rio_t *rp, char *usrbuf, size_t n) -{ +static ssize_t rio_read(rio_t* rp, char* usrbuf, size_t n) { int cnt; - while (rp->rio_cnt <= 0) { /* refill if buf is empty */ - rp->rio_cnt = read(rp->rio_fd, rp->rio_buf, - sizeof(rp->rio_buf)); + while (rp->rio_cnt <= 0) { /* refill if buf is empty */ + rp->rio_cnt = read(rp->rio_fd, rp->rio_buf, sizeof(rp->rio_buf)); if (rp->rio_cnt < 0) { if (errno != EINTR) /* interrupted by sig handler return */ return -1; - } - else if (rp->rio_cnt == 0) /* EOF */ + } else if (rp->rio_cnt == 0) /* EOF */ return 0; - else + else rp->rio_bufptr = rp->rio_buf; /* reset buffer ptr */ } /* Copy min(n, rp->rio_cnt) bytes from internal buf to user buf */ - cnt = n; - if (rp->rio_cnt < (int)n) - cnt = rp->rio_cnt; + cnt = n; + if (rp->rio_cnt < (int)n) cnt = rp->rio_cnt; memcpy(usrbuf, rp->rio_bufptr, cnt); rp->rio_bufptr += cnt; rp->rio_cnt -= cnt; @@ -628,10 +554,9 @@ static ssize_t rio_read(rio_t *rp, char *usrbuf, size_t n) * rio_readinitb - Associate a descriptor with a read buffer and reset buffer */ /* $begin rio_readinitb */ -void rio_readinitb(rio_t *rp, int fd) -{ - rp->rio_fd = fd; - rp->rio_cnt = 0; +void rio_readinitb(rio_t* rp, int fd) { + rp->rio_fd = fd; + rp->rio_cnt = 0; rp->rio_bufptr = rp->rio_buf; } /* $end rio_readinitb */ @@ -640,50 +565,46 @@ void rio_readinitb(rio_t *rp, int fd) * rio_readnb - Robustly read n bytes (buffered) */ /* $begin rio_readnb */ -ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n) -{ +ssize_t rio_readnb(rio_t* rp, void* usrbuf, size_t n) { size_t nleft = n; ssize_t nread; - char *bufp = (char *)usrbuf; + char* bufp = (char*)usrbuf; while (nleft > 0) { if ((nread = rio_read(rp, bufp, nleft)) < 0) { if (errno == EINTR) /* interrupted by sig handler return */ - nread = 0; /* call read() again */ + nread = 0; /* call read() again */ else - return -1; /* errno set by read() */ - } - else if (nread == 0) - break; /* EOF */ + return -1; /* errno set by read() */ + } else if (nread == 0) + break; /* EOF */ nleft -= nread; bufp += nread; } - return (n - nleft); /* return >= 0 */ + return (n - nleft); /* return >= 0 */ } /* $end rio_readnb */ -/* +/* * rio_readlineb - robustly read a text line (buffered) */ /* $begin rio_readlineb */ -ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen) -{ +ssize_t rio_readlineb(rio_t* rp, void* usrbuf, size_t maxlen) { size_t n; int rc; - char c, *bufp = (char *)usrbuf; + char c, *bufp = (char*)usrbuf; - for (n = 1; n < maxlen; n++) { + for (n = 1; n < maxlen; n++) { if ((rc = rio_read(rp, &c, 1)) == 1) { *bufp++ = c; - if (c == '\n') - break; + if (c == '\n') break; } else if (rc == 0) { if (n == 1) return 0; /* EOF, no data read */ else - break; /* EOF, some data was read */ + break; /* EOF, some data was read */ } else - return -1; /* error */ + return -1; /* error */ } *bufp = 0; return n; @@ -693,8 +614,7 @@ ssize_t rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen) /********************************** * Wrappers for robust I/O routines **********************************/ -ssize_t Rio_readn(int fd, void *ptr, size_t nbytes) -{ +ssize_t Rio_readn(int fd, void* ptr, size_t nbytes) { ssize_t n; if ((n = rio_readn(fd, ptr, nbytes)) < 0) { @@ -703,20 +623,15 @@ ssize_t Rio_readn(int fd, void *ptr, size_t nbytes) return n; } -void Rio_writen(int fd, void *usrbuf, size_t n) -{ +void Rio_writen(int fd, void* usrbuf, size_t n) { if (rio_writen(fd, usrbuf, n) != (ssize_t)n) { log_err("Rio_writen error: %s\n", strerror(errno)); } } -void Rio_readinitb(rio_t *rp, int fd) -{ - rio_readinitb(rp, fd); -} +void Rio_readinitb(rio_t* rp, int fd) { rio_readinitb(rp, fd); } -ssize_t Rio_readnb(rio_t *rp, void *usrbuf, size_t n) -{ +ssize_t Rio_readnb(rio_t* rp, void* usrbuf, size_t n) { ssize_t rc; if ((rc = rio_readnb(rp, usrbuf, n)) < 0) { @@ -725,106 +640,91 @@ ssize_t Rio_readnb(rio_t *rp, void *usrbuf, size_t n) return rc; } -ssize_t Rio_readlineb(rio_t *rp, void *usrbuf, size_t maxlen) -{ +ssize_t Rio_readlineb(rio_t* rp, void* usrbuf, size_t maxlen) { ssize_t rc; if ((rc = rio_readlineb(rp, usrbuf, maxlen)) < 0) { log_err("Rio_readlineb error: %s\n", strerror(errno)); } return rc; -} +} -/******************************** +/******************************** * Client/server helper functions ********************************/ /* - * open_clientfd - open connection to server at + * open_clientfd - open connection to server at * and return a socket descriptor ready for reading and writing. - * Returns -1 and sets errno on Unix error. + * Returns -1 and sets errno on Unix error. * Returns -2 and sets h_errno on DNS (gethostbyname) error. */ /* $begin open_clientfd */ -int open_clientfd(char *hostname, int port) -{ +int open_clientfd(char* hostname, int port) { int clientfd; - struct hostent *hp; + struct hostent* hp; struct sockaddr_in serveraddr; - if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) - return -1; /* check errno for cause of error */ + if ((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -1; /* check errno for cause of error */ /* Fill in the server's IP address and port */ - if ((hp = gethostbyname(hostname)) == NULL) - return -2; /* check h_errno for cause of error */ - bzero((char *) &serveraddr, sizeof(serveraddr)); + if ((hp = gethostbyname(hostname)) == NULL) return -2; /* check h_errno for cause of error */ + bzero((char*)&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; - bcopy((char *)hp->h_addr_list[0], - (char *)&serveraddr.sin_addr.s_addr, hp->h_length); + bcopy((char*)hp->h_addr_list[0], (char*)&serveraddr.sin_addr.s_addr, hp->h_length); serveraddr.sin_port = htons(port); /* Establish a connection with the server */ - if (connect(clientfd, (SA *) &serveraddr, sizeof(serveraddr)) < 0) - return -1; + if (connect(clientfd, (SA*)&serveraddr, sizeof(serveraddr)) < 0) return -1; return clientfd; } /* $end open_clientfd */ -/* +/* * open_listenfd - open and return a listening socket on port * Returns -1 and sets errno on Unix error. */ /* $begin open_listenfd */ -int open_listenfd(int port) -{ - int listenfd, optval=1; +int open_listenfd(int port) { + int listenfd, optval = 1; struct sockaddr_in serveraddr; /* Create a socket descriptor */ - if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) - return -1; + if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -1; /* Eliminates "Address already in use" error from bind. */ - if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, - (const void *)&optval , sizeof(int)) < 0) - return -1; + if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void*)&optval, sizeof(int)) < 0) return -1; /* Listenfd will be an endpoint for all requests to port on any IP address for this host */ - bzero((char *) &serveraddr, sizeof(serveraddr)); - serveraddr.sin_family = AF_INET; - serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); - serveraddr.sin_port = htons((unsigned short)port); - if (bind(listenfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0) - return -1; + bzero((char*)&serveraddr, sizeof(serveraddr)); + serveraddr.sin_family = AF_INET; + serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); + serveraddr.sin_port = htons((unsigned short)port); + if (bind(listenfd, (SA*)&serveraddr, sizeof(serveraddr)) < 0) return -1; /* Make it a listening socket ready to accept connection requests */ - if (listen(listenfd, LISTENQ) < 0) - return -1; + if (listen(listenfd, LISTENQ) < 0) return -1; return listenfd; } /* $end open_listenfd */ /****************************************** - * Wrappers for the client/server helper routines + * Wrappers for the client/server helper routines ******************************************/ -int Open_clientfd(char *hostname, int port) -{ +int Open_clientfd(char* hostname, int port) { int rc; if ((rc = open_clientfd(hostname, port)) < 0) { if (rc == -1) { log_err("Open_clientfd Unix error: %s\n", strerror(errno)); - } - else { + } else { log_err("%s: DNS error %d\n", "Open_clientfd DNS error", h_errno); } } return rc; } -int Open_listenfd(int port) -{ +int Open_listenfd(int port) { int rc; if ((rc = open_listenfd(port)) < 0) { diff --git a/src/pstd/src/pstd_binlog_impl.cc b/src/pstd/src/pstd_binlog_impl.cc index 752b067ee1..9e889e7aae 100644 --- a/src/pstd/src/pstd_binlog_impl.cc +++ b/src/pstd/src/pstd_binlog_impl.cc @@ -5,11 +5,11 @@ #include "pstd/src/pstd_binlog_impl.h" +#include #include -#include -#include #include -#include +#include +#include namespace pstd { @@ -20,20 +20,12 @@ std::string NewFileName(const std::string name, const uint32_t current) { } // Version -Version::Version(RWFile *save) - : pro_offset_(0), - pro_num_(0), - item_num_(0), - save_(save) { - assert(save_ != NULL); -} +Version::Version(RWFile* save) : pro_offset_(0), pro_num_(0), item_num_(0), save_(save) { assert(save_ != NULL); } -Version::~Version() { - StableSave(); -} +Version::~Version() { StableSave(); } Status Version::StableSave() { - char *p = save_->GetData(); + char* p = save_->GetData(); memcpy(p, &pro_offset_, sizeof(uint64_t)); p += 16; memcpy(p, &item_num_, sizeof(uint32_t)); @@ -58,7 +50,7 @@ Status Version::Init() { Status Binlog::Open(const std::string& path, Binlog** logptr) { *logptr = NULL; - BinlogImpl *impl = new BinlogImpl(path, kBinlogSize); + BinlogImpl* impl = new BinlogImpl(path, kBinlogSize); Status s = impl->Recover(); if (s.ok()) { *logptr = impl; @@ -69,12 +61,7 @@ Status Binlog::Open(const std::string& path, Binlog** logptr) { } BinlogImpl::BinlogImpl(const std::string& path, const int file_size) - : exit_all_consume_(false), - path_(path), - file_size_(file_size), - version_(NULL), - queue_(NULL), - versionfile_(NULL) { + : exit_all_consume_(false), path_(path), file_size_(file_size), version_(NULL), queue_(NULL), versionfile_(NULL) { if (path_.back() != '/') { path_.push_back('/'); } @@ -104,20 +91,20 @@ Status BinlogImpl::Recover() { return s; } - // recover memtable - //MemTable *mem = new MemTable(file_size_); - //mem->Ref(); - //mem->RecoverFromFile(profile); - //memtables_[pro_num_] = mem; + // recover memtable + // MemTable *mem = new MemTable(file_size_); + // mem->Ref(); + // mem->RecoverFromFile(profile); + // memtables_[pro_num_] = mem; } else { s = NewWritableFile(profile, &queue_); if (!s.ok()) { return s; } - //MemTable *mem = new MemTable(file_size_); - //mem->Ref(); - //memtables_[pro_num_] = mem; + // MemTable *mem = new MemTable(file_size_); + // mem->Ref(); + // memtables_[pro_num_] = mem; } InitOffset(); @@ -144,7 +131,7 @@ Status BinlogImpl::GetProducerStatus(uint32_t* filenum, uint64_t* offset) { } // Note: mutex lock should be held -Status BinlogImpl::Append(const std::string &item) { +Status BinlogImpl::Append(const std::string& item) { Status s; // Check to roll log file @@ -162,7 +149,7 @@ Status BinlogImpl::Append(const std::string &item) { version_->pro_offset_ = 0; version_->pro_num_ = pro_num_; version_->StableSave(); - //version_->debug(); + // version_->debug(); } } @@ -177,7 +164,7 @@ Status BinlogImpl::Append(const std::string &item) { return s; } -Status BinlogImpl::EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset) { +Status BinlogImpl::EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset) { Status s; assert(n <= 0xffffff); assert(block_offset_ + kHeaderSize + n <= kBlockSize); @@ -210,9 +197,9 @@ Status BinlogImpl::EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, i return s; } -Status BinlogImpl::Produce(const Slice &item, int *temp_pro_offset) { +Status BinlogImpl::Produce(const Slice& item, int* temp_pro_offset) { Status s; - const char *ptr = item.data(); + const char* ptr = item.data(); size_t left = item.size(); bool begin = true; @@ -224,7 +211,7 @@ Status BinlogImpl::Produce(const Slice &item, int *temp_pro_offset) { if (leftover > 0) { queue_->Append(Slice("\x00\x00\x00\x00\x00\x00\x00", leftover)); *temp_pro_offset += leftover; - //version_->StableSave(); + // version_->StableSave(); } block_offset_ = 0; } @@ -251,8 +238,8 @@ Status BinlogImpl::Produce(const Slice &item, int *temp_pro_offset) { return s; } - -Status BinlogImpl::AppendBlank(WritableFile *file, uint64_t len) { + +Status BinlogImpl::AppendBlank(WritableFile* file, uint64_t len) { if (len < kHeaderSize) { return Status::OK(); } @@ -270,7 +257,7 @@ Status BinlogImpl::AppendBlank(WritableFile *file, uint64_t len) { if (len % kBlockSize < kHeaderSize) { n = 0; } else { - n = (uint32_t) ((len % kBlockSize) - kHeaderSize); + n = (uint32_t)((len % kBlockSize) - kHeaderSize); } char buf[kBlockSize]; @@ -348,7 +335,7 @@ BinlogReader* BinlogImpl::NewBinlogReader(uint32_t filenum, uint64_t offset) { return NULL; } - BinlogReaderImpl* reader = new BinlogReaderImpl(this, path_, filenum, offset); + BinlogReaderImpl* reader = new BinlogReaderImpl(this, path_, filenum, offset); Status s = reader->Trim(); if (!s.ok()) { log_info("Trim offset failed: %s", s.ToString().c_str()); @@ -358,17 +345,17 @@ BinlogReader* BinlogImpl::NewBinlogReader(uint32_t filenum, uint64_t offset) { return reader; } -BinlogReaderImpl::BinlogReaderImpl(Binlog* log, const std::string &path, uint32_t filenum, uint64_t offset) - : log_(log), - path_(path), - filenum_(filenum), - offset_(offset), - should_exit_(false), - initial_offset_(0), - last_record_offset_(offset_ % kBlockSize), - end_of_buffer_offset_(kBlockSize), - queue_(NULL), - backing_store_(new char[kBlockSize]) { +BinlogReaderImpl::BinlogReaderImpl(Binlog* log, const std::string& path, uint32_t filenum, uint64_t offset) + : log_(log), + path_(path), + filenum_(filenum), + offset_(offset), + should_exit_(false), + initial_offset_(0), + last_record_offset_(offset_ % kBlockSize), + end_of_buffer_offset_(kBlockSize), + queue_(NULL), + backing_store_(new char[kBlockSize]) { std::string confile = NewFileName(path_ + kBinlogPrefix, filenum_); if (!NewSequentialFile(confile, &queue_).ok()) { log_info("Reader new sequtialfile failed"); @@ -377,7 +364,7 @@ BinlogReaderImpl::BinlogReaderImpl(Binlog* log, const std::string &path, uint32_ BinlogReaderImpl::~BinlogReaderImpl() { delete queue_; - delete [] backing_store_; + delete[] backing_store_; } Status BinlogReaderImpl::Trim() { @@ -407,7 +394,7 @@ Status BinlogReaderImpl::Trim() { return Status::OK(); } -uint64_t BinlogReaderImpl::GetNext(Status &result) { +uint64_t BinlogReaderImpl::GetNext(Status& result) { uint64_t offset = 0; Status s; @@ -448,7 +435,7 @@ uint64_t BinlogReaderImpl::GetNext(Status &result) { return offset; } -unsigned int BinlogReaderImpl::ReadPhysicalRecord(Slice *result) { +unsigned int BinlogReaderImpl::ReadPhysicalRecord(Slice* result) { Status s; uint64_t zero_space = end_of_buffer_offset_ - last_record_offset_; if (zero_space <= kHeaderSize) { @@ -476,7 +463,7 @@ unsigned int BinlogReaderImpl::ReadPhysicalRecord(Slice *result) { } buffer_.clear(); - //std::cout<<"2 --> offset_: "< offset_: "<Read(length, &buffer_, backing_store_); *result = Slice(buffer_.data(), buffer_.size()); last_record_offset_ += kHeaderSize + length; @@ -486,7 +473,7 @@ unsigned int BinlogReaderImpl::ReadPhysicalRecord(Slice *result) { return type; } -Status BinlogReaderImpl::Consume(std::string &scratch) { +Status BinlogReaderImpl::Consume(std::string& scratch) { Status s; if (last_record_offset_ < initial_offset_) { return Status::IOError("last_record_offset exceed"); @@ -527,13 +514,13 @@ Status BinlogReaderImpl::Consume(std::string &scratch) { break; } } - //DLOG(INFO) << "Binlog Sender consumer a msg: " << scratch; + // DLOG(INFO) << "Binlog Sender consumer a msg: " << scratch; return Status::OK(); } -// Get a whole message; +// Get a whole message; // the status will be OK, IOError or Corruption; -Status BinlogReaderImpl::ReadRecord(std::string &scratch) { +Status BinlogReaderImpl::ReadRecord(std::string& scratch) { scratch.clear(); Status s; uint32_t pro_num; @@ -568,11 +555,11 @@ Status BinlogReaderImpl::ReadRecord(std::string &scratch) { break; } } - + if (should_exit_) { return Status::Corruption("should exit"); } return s; } -} // namespace pstd +} // namespace pstd diff --git a/src/pstd/src/pstd_binlog_impl.h b/src/pstd/src/pstd_binlog_impl.h index 4f80c8d1bb..1c50c3f7d5 100644 --- a/src/pstd/src/pstd_binlog_impl.h +++ b/src/pstd/src/pstd_binlog_impl.h @@ -6,15 +6,15 @@ #ifndef __PSTD_BINLOG_IMPL_H__ #define __PSTD_BINLOG_IMPL_H__ -#include +#include #include +#include #include -#include #include "pstd/include/env.h" #include "pstd/include/pstd_binlog.h" -#include "pstd/include/pstd_status.h" #include "pstd/include/pstd_mutex.h" +#include "pstd/include/pstd_status.h" namespace pstd { @@ -26,7 +26,7 @@ class BinlogReader; const std::string kBinlogPrefix = "binlog"; const std::string kManifest = "manifest"; const int kBinlogSize = 128; -//const int kBinlogSize = (100 << 20); +// const int kBinlogSize = (100 << 20); const int kBlockSize = (64 << 10); // Header is Type(1 byte), length (3 bytes), time (4 bytes) const size_t kHeaderSize = 1 + 3 + 4; @@ -50,8 +50,8 @@ class BinlogImpl : public Binlog { // // Basic API // - virtual Status Append(const std::string &item); - //Status Append(const char* item, int len); + virtual Status Append(const std::string& item); + // Status Append(const char* item, int len); virtual BinlogReader* NewBinlogReader(uint32_t filenum, uint64_t offset); virtual Status GetProducerStatus(uint32_t* filenum, uint64_t* offset); @@ -64,20 +64,18 @@ class BinlogImpl : public Binlog { // More specify API, used by Pika // Status Recover(); - static Status AppendBlank(WritableFile *file, uint64_t len); - WritableFile *queue() { return queue_; } - uint64_t file_size() { - return file_size_; - } + static Status AppendBlank(WritableFile* file, uint64_t len); + WritableFile* queue() { return queue_; } + uint64_t file_size() { return file_size_; } - void Lock() { mutex_.Lock(); } - void Unlock() { mutex_.Unlock(); } + void Lock() { mutex_.Lock(); } + void Unlock() { mutex_.Unlock(); } void InitOffset(); - Status EmitPhysicalRecord(RecordType t, const char *ptr, size_t n, int *temp_pro_offset); + Status EmitPhysicalRecord(RecordType t, const char* ptr, size_t n, int* temp_pro_offset); // Produce - Status Produce(const Slice &item, int *pro_offset); + Status Produce(const Slice& item, int* pro_offset); private: Mutex mutex_; @@ -88,18 +86,18 @@ class BinlogImpl : public Binlog { uint64_t record_num_; Version* version_; - WritableFile *queue_; - RWFile *versionfile_; + WritableFile* queue_; + RWFile* versionfile_; int block_offset_; char* pool_; - //std::unordered_map memtables_; + // std::unordered_map memtables_; // Not use - //std::string filename; - //int32_t retry_; - //uint32_t consumer_num_; + // std::string filename; + // int32_t retry_; + // uint32_t consumer_num_; // No copying allowed BinlogImpl(const BinlogImpl&); @@ -108,7 +106,7 @@ class BinlogImpl : public Binlog { class Version { public: - Version(RWFile *save); + Version(RWFile* save); ~Version(); Status Init(); @@ -123,16 +121,15 @@ class Version { void debug() { ReadLock(&this->rwlock_); - printf ("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); + printf("Current pro_num %u pro_offset %lu\n", pro_num_, pro_offset_); } private: - - RWFile *save_; + RWFile* save_; // Not used - //uint64_t con_offset_; - //uint32_t con_num_; + // uint64_t con_offset_; + // uint32_t con_num_; // No copying allowed; Version(const Version&); @@ -144,20 +141,20 @@ class BinlogReaderImpl : public BinlogReader { BinlogReaderImpl(Binlog* log, const std::string& path, uint32_t filenum, uint64_t offset); ~BinlogReaderImpl(); - //bool ReadRecord(Slice* record, std::string* scratch); - virtual Status ReadRecord(std::string &record); + // bool ReadRecord(Slice* record, std::string* scratch); + virtual Status ReadRecord(std::string& record); private: friend class BinlogImpl; - //Status Parse(std::string &scratch); - Status Consume(std::string &scratch); - unsigned int ReadPhysicalRecord(Slice *fragment); + // Status Parse(std::string &scratch); + Status Consume(std::string& scratch); + unsigned int ReadPhysicalRecord(Slice* fragment); // Tirm offset to first record behind offered offset. Status Trim(); // Return next record end offset in a block, store in result if error encounted. - uint64_t GetNext(Status &result); + uint64_t GetNext(Status& result); Binlog* log_; std::string path_; @@ -179,7 +176,6 @@ class BinlogReaderImpl : public BinlogReader { void operator=(const BinlogReaderImpl&); }; -} // namespace pstd - +} // namespace pstd #endif // __PSTD_BINLOG_IMPL_H__ diff --git a/src/pstd/src/pstd_coding.cc b/src/pstd/src/pstd_coding.cc index 7ccba1af41..3b917b4bce 100644 --- a/src/pstd/src/pstd_coding.cc +++ b/src/pstd/src/pstd_coding.cc @@ -7,17 +7,11 @@ namespace pstd { -void EncodeFixed16(char* buf, uint16_t value) { - memcpy(buf, &value, sizeof(value)); -} +void EncodeFixed16(char* buf, uint16_t value) { memcpy(buf, &value, sizeof(value)); } -void EncodeFixed32(char* buf, uint32_t value) { - memcpy(buf, &value, sizeof(value)); -} +void EncodeFixed32(char* buf, uint32_t value) { memcpy(buf, &value, sizeof(value)); } -void EncodeFixed64(char* buf, uint64_t value) { - memcpy(buf, &value, sizeof(value)); -} +void EncodeFixed64(char* buf, uint64_t value) { memcpy(buf, &value, sizeof(value)); } void PutFixed16(std::string* dst, uint16_t value) { char buf[sizeof(value)]; @@ -41,26 +35,26 @@ char* EncodeVarint32(char* dst, uint32_t v) { // Operate on characters as unsigneds unsigned char* ptr = reinterpret_cast(dst); static const int B = 128; - if (v < (1<<7)) { + if (v < (1 << 7)) { *(ptr++) = v; - } else if (v < (1<<14)) { + } else if (v < (1 << 14)) { *(ptr++) = v | B; - *(ptr++) = v>>7; - } else if (v < (1<<21)) { + *(ptr++) = v >> 7; + } else if (v < (1 << 21)) { *(ptr++) = v | B; - *(ptr++) = (v>>7) | B; - *(ptr++) = v>>14; - } else if (v < (1<<28)) { + *(ptr++) = (v >> 7) | B; + *(ptr++) = v >> 14; + } else if (v < (1 << 28)) { *(ptr++) = v | B; - *(ptr++) = (v>>7) | B; - *(ptr++) = (v>>14) | B; - *(ptr++) = v>>21; + *(ptr++) = (v >> 7) | B; + *(ptr++) = (v >> 14) | B; + *(ptr++) = v >> 21; } else { *(ptr++) = v | B; - *(ptr++) = (v>>7) | B; - *(ptr++) = (v>>14) | B; - *(ptr++) = (v>>21) | B; - *(ptr++) = v>>28; + *(ptr++) = (v >> 7) | B; + *(ptr++) = (v >> 14) | B; + *(ptr++) = (v >> 21) | B; + *(ptr++) = v >> 28; } return reinterpret_cast(ptr); } @@ -75,7 +69,7 @@ char* EncodeVarint64(char* dst, uint64_t v) { static const int B = 128; unsigned char* ptr = reinterpret_cast(dst); while (v >= B) { - *(ptr++) = (v & (B-1)) | B; + *(ptr++) = (v & (B - 1)) | B; v >>= 7; } *(ptr++) = static_cast(v); @@ -102,9 +96,7 @@ int VarintLength(uint64_t v) { return len; } -const char* GetVarint32PtrFallback(const char* p, - const char* limit, - uint32_t* value) { +const char* GetVarint32PtrFallback(const char* p, const char* limit, uint32_t* value) { uint32_t result = 0; for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) { uint32_t byte = *(reinterpret_cast(p)); @@ -174,8 +166,7 @@ bool GetVarint64(Slice* input, uint64_t* value) { } } -const char* GetLengthPrefixedSlice(const char* p, const char* limit, - Slice* result) { +const char* GetLengthPrefixedSlice(const char* p, const char* limit, Slice* result) { uint32_t len; p = GetVarint32Ptr(p, limit, &len); if (p == NULL) return NULL; @@ -186,8 +177,7 @@ const char* GetLengthPrefixedSlice(const char* p, const char* limit, bool GetLengthPrefixedSlice(Slice* input, Slice* result) { uint32_t len; - if (GetVarint32(input, &len) && - input->size() >= len) { + if (GetVarint32(input, &len) && input->size() >= len) { *result = Slice(input->data(), len); input->remove_prefix(len); return true; @@ -198,8 +188,7 @@ bool GetLengthPrefixedSlice(Slice* input, Slice* result) { bool GetLengthPrefixedString(std::string* input, std::string* result) { uint32_t len; - if (GetVarint32(input, &len) && - input->size() >= len) { + if (GetVarint32(input, &len) && input->size() >= len) { *result = (*input).substr(0, len); input->erase(0, len); return true; @@ -208,4 +197,4 @@ bool GetLengthPrefixedString(std::string* input, std::string* result) { } } -} // namespace leveldb +} // namespace pstd diff --git a/src/pstd/src/pstd_hash.cc b/src/pstd/src/pstd_hash.cc index adbbf1c4e8..5f1698d31c 100644 --- a/src/pstd/src/pstd_hash.cc +++ b/src/pstd/src/pstd_hash.cc @@ -1,7 +1,7 @@ /* * Updated to C++, zedwood.com 2012 * Based on Olivier Gay's version - * See Modified BSD License below: + * See Modified BSD License below: * * FIPS 180-2 SHA-224/256/384/512 implementation * Issue date: 04/30/2005 @@ -71,11 +71,10 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. - +#include "pstd/include/pstd_hash.h" +#include #include #include -#include -#include "pstd/include/pstd_hash.h" namespace pstd { @@ -86,44 +85,43 @@ class SHA256 { typedef unsigned long long uint64; const static uint32 sha256_k[]; - static const unsigned int SHA224_256_BLOCK_SIZE = (512/8); + static const unsigned int SHA224_256_BLOCK_SIZE = (512 / 8); + public: void init(); - void update(const unsigned char *message, unsigned int len); - void final(unsigned char *digest); - static const unsigned int DIGEST_SIZE = ( 256 / 8); + void update(const unsigned char* message, unsigned int len); + void final(unsigned char* digest); + static const unsigned int DIGEST_SIZE = (256 / 8); protected: - void transform(const unsigned char *message, unsigned int block_nb); + void transform(const unsigned char* message, unsigned int block_nb); unsigned int m_tot_len; unsigned int m_len; - unsigned char m_block[2*SHA224_256_BLOCK_SIZE]; + unsigned char m_block[2 * SHA224_256_BLOCK_SIZE]; uint32 m_h[8]; }; -#define SHA2_SHFR(x, n) (x >> n) -#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) +#define SHA2_SHFR(x, n) (x >> n) +#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) +#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) +#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) #define SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA256_F1(x) (SHA2_ROTR(x, 2) ^ SHA2_ROTR(x, 13) ^ SHA2_ROTR(x, 22)) -#define SHA256_F2(x) (SHA2_ROTR(x, 6) ^ SHA2_ROTR(x, 11) ^ SHA2_ROTR(x, 25)) -#define SHA256_F3(x) (SHA2_ROTR(x, 7) ^ SHA2_ROTR(x, 18) ^ SHA2_SHFR(x, 3)) +#define SHA256_F1(x) (SHA2_ROTR(x, 2) ^ SHA2_ROTR(x, 13) ^ SHA2_ROTR(x, 22)) +#define SHA256_F2(x) (SHA2_ROTR(x, 6) ^ SHA2_ROTR(x, 11) ^ SHA2_ROTR(x, 25)) +#define SHA256_F3(x) (SHA2_ROTR(x, 7) ^ SHA2_ROTR(x, 18) ^ SHA2_SHFR(x, 3)) #define SHA256_F4(x) (SHA2_ROTR(x, 17) ^ SHA2_ROTR(x, 19) ^ SHA2_SHFR(x, 10)) -#define SHA2_UNPACK32(x, str) \ -{ \ - *((str) + 3) = (uint8) ((x) ); \ - *((str) + 2) = (uint8) ((x) >> 8); \ - *((str) + 1) = (uint8) ((x) >> 16); \ - *((str) + 0) = (uint8) ((x) >> 24); \ -} -#define SHA2_PACK32(str, x) \ -{ \ - *(x) = ((uint32) *((str) + 3) ) \ - | ((uint32) *((str) + 2) << 8) \ - | ((uint32) *((str) + 1) << 16) \ - | ((uint32) *((str) + 0) << 24); \ -} +#define SHA2_UNPACK32(x, str) \ + { \ + *((str) + 3) = (uint8)((x)); \ + *((str) + 2) = (uint8)((x) >> 8); \ + *((str) + 1) = (uint8)((x) >> 16); \ + *((str) + 0) = (uint8)((x) >> 24); \ + } +#define SHA2_PACK32(str, x) \ + { \ + *(x) = ((uint32) * ((str) + 3)) | ((uint32) * ((str) + 2) << 8) | ((uint32) * ((str) + 1) << 16) | \ + ((uint32) * ((str) + 0) << 24); \ + } // a small class for calculating MD5 hashes of strings or byte arrays // it is not meant to be fast or secure @@ -137,12 +135,12 @@ class SHA256 { // assumes that char is 8 bit and int is 32 bit class MD5 { public: - typedef unsigned int size_type; // must be 32bit + typedef unsigned int size_type; // must be 32bit MD5(); MD5(const std::string& text); - void update(const unsigned char *buf, size_type length); - void update(const char *buf, size_type length); + void update(const unsigned char* buf, size_type length); + void update(const char* buf, size_type length); MD5& finalize(); std::string hexdigest() const; std::string rawdigest() const; @@ -150,19 +148,19 @@ class MD5 { private: void init(); - typedef unsigned char uint1; // 8bit - typedef unsigned int uint4; // 32bit - enum {blocksize = 64}; // VC6 won't eat a const static int here + typedef unsigned char uint1; // 8bit + typedef unsigned int uint4; // 32bit + enum { blocksize = 64 }; // VC6 won't eat a const static int here void transform(const uint1 block[blocksize]); static void decode(uint4 output[], const uint1 input[], size_type len); static void encode(uint1 output[], const uint4 input[], size_type len); bool finalized; - uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk - uint4 count[2]; // 64bit counter for number of bits (lo, hi) - uint4 state[4]; // digest so far - uint1 digest[16]; // the result + uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk + uint4 count[2]; // 64bit counter for number of bits (lo, hi) + uint4 state[4]; // digest so far + uint1 digest[16]; // the result // low level logic operations static inline uint4 F(uint4 x, uint4 y, uint4 z); @@ -170,52 +168,42 @@ class MD5 { static inline uint4 H(uint4 x, uint4 y, uint4 z); static inline uint4 I(uint4 x, uint4 y, uint4 z); static inline uint4 rotate_left(uint4 x, int n); - static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); -}; - -const unsigned int SHA256::sha256_k[64] = {//UL = uint32 - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + static inline void FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); }; -void SHA256::transform(const unsigned char *message, unsigned int block_nb) { +const unsigned int SHA256::sha256_k[64] = { // UL = uint32 + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + +void SHA256::transform(const unsigned char* message, unsigned int block_nb) { uint32 w[64]; uint32 wv[8]; uint32 t1, t2; - const unsigned char *sub_block; + const unsigned char* sub_block; int i; int j; - for (i = 0; i < (int) block_nb; i++) { + for (i = 0; i < (int)block_nb; i++) { sub_block = message + (i << 6); for (j = 0; j < 16; j++) { SHA2_PACK32(&sub_block[j << 2], &w[j]); } for (j = 16; j < 64; j++) { - w[j] = SHA256_F4(w[j - 2]) + w[j - 7] + SHA256_F3(w[j - 15]) + w[j - 16]; + w[j] = SHA256_F4(w[j - 2]) + w[j - 7] + SHA256_F3(w[j - 15]) + w[j - 16]; } for (j = 0; j < 8; j++) { wv[j] = m_h[j]; } for (j = 0; j < 64; j++) { - t1 = wv[7] + SHA256_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) - + sha256_k[j] + w[j]; + t1 = wv[7] + SHA256_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) + sha256_k[j] + w[j]; t2 = SHA256_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); wv[7] = wv[6]; wv[6] = wv[5]; @@ -245,10 +233,10 @@ void SHA256::init() { m_tot_len = 0; } -void SHA256::update(const unsigned char *message, unsigned int len) { +void SHA256::update(const unsigned char* message, unsigned int len) { unsigned int block_nb; unsigned int new_len, rem_len, tmp_len; - const unsigned char *shifted_message; + const unsigned char* shifted_message; tmp_len = SHA224_256_BLOCK_SIZE - m_len; rem_len = len < tmp_len ? len : tmp_len; memcpy(&m_block[m_len], message, rem_len); @@ -267,31 +255,30 @@ void SHA256::update(const unsigned char *message, unsigned int len) { m_tot_len += (block_nb + 1) << 6; } -void SHA256::final(unsigned char *digest) { +void SHA256::final(unsigned char* digest) { unsigned int block_nb; unsigned int pm_len; unsigned int len_b; int i; - block_nb = (1 + ((SHA224_256_BLOCK_SIZE - 9) - < (m_len % SHA224_256_BLOCK_SIZE))); + block_nb = (1 + ((SHA224_256_BLOCK_SIZE - 9) < (m_len % SHA224_256_BLOCK_SIZE))); len_b = (m_tot_len + m_len) << 3; pm_len = block_nb << 6; memset(m_block + m_len, 0, pm_len - m_len); m_block[m_len] = 0x80; SHA2_UNPACK32(len_b, m_block + pm_len - 4); transform(m_block, block_nb); - for (i = 0 ; i < 8; i++) { + for (i = 0; i < 8; i++) { SHA2_UNPACK32(m_h[i], &digest[i << 2]); } } -std::string sha256(const std::string &input, bool raw) { +std::string sha256(const std::string& input, bool raw) { unsigned char digest[SHA256::DIGEST_SIZE]; - memset(digest,0,SHA256::DIGEST_SIZE); + memset(digest, 0, SHA256::DIGEST_SIZE); SHA256 ctx = SHA256(); ctx.init(); - ctx.update( (unsigned char*)input.c_str(), input.length()); + ctx.update((unsigned char*)input.c_str(), input.length()); ctx.final(digest); if (raw) { @@ -301,10 +288,9 @@ std::string sha256(const std::string &input, bool raw) { } return res; } - char buf[2*SHA256::DIGEST_SIZE+1]; - buf[2*SHA256::DIGEST_SIZE] = 0; - for (size_t i = 0; i < SHA256::DIGEST_SIZE; i++) - sprintf(buf+i*2, "%02x", digest[i]); + char buf[2 * SHA256::DIGEST_SIZE + 1]; + buf[2 * SHA256::DIGEST_SIZE] = 0; + for (size_t i = 0; i < SHA256::DIGEST_SIZE; i++) sprintf(buf + i * 2, "%02x", digest[i]); return std::string(buf); } @@ -331,56 +317,44 @@ std::string sha256(const std::string &input, bool raw) { /////////////////////////////////////////////// // F, G, H and I are basic MD5 functions. -inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { - return (x&y) | (~x&z); -} +inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { return (x & y) | (~x & z); } -inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { - return (x&z) | (y&~z); -} +inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { return (x & z) | (y & ~z); } -inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { - return x^y^z; -} +inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { return x ^ y ^ z; } -inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { - return y ^ (x | ~z); -} +inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { return y ^ (x | ~z); } // rotate_left rotates x left n bits. -inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { - return (x << n) | (x >> (32-n)); -} +inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { return (x << n) | (x >> (32 - n)); } // FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. // Rotation is separate from addition to prevent recomputation. -inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a+ F(b,c,d) + x + ac, s) + b; +inline void MD5::FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + F(b, c, d) + x + ac, s) + b; } -inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + G(b,c,d) + x + ac, s) + b; +inline void MD5::GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + G(b, c, d) + x + ac, s) + b; } -inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + H(b,c,d) + x + ac, s) + b; +inline void MD5::HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + H(b, c, d) + x + ac, s) + b; } -inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + I(b,c,d) + x + ac, s) + b; +inline void MD5::II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + I(b, c, d) + x + ac, s) + b; } ////////////////////////////////////////////// // default ctor, just initailize -MD5::MD5() { - init(); -} +MD5::MD5() { init(); } ////////////////////////////////////////////// // nifty shortcut ctor, compute MD5 for string and finalize it right away -MD5::MD5(const std::string &text) { +MD5::MD5(const std::string& text) { init(); update(text.c_str(), text.length()); finalize(); @@ -389,7 +363,7 @@ MD5::MD5(const std::string &text) { ////////////////////////////// void MD5::init() { - finalized=false; + finalized = false; count[0] = 0; count[1] = 0; @@ -406,8 +380,8 @@ void MD5::init() { // decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. void MD5::decode(uint4 output[], const uint1 input[], size_type len) { for (unsigned int i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) | - (((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24); + output[i] = ((uint4)input[j]) | (((uint4)input[j + 1]) << 8) | (((uint4)input[j + 2]) << 16) | + (((uint4)input[j + 3]) << 24); } ////////////////////////////// @@ -417,9 +391,9 @@ void MD5::decode(uint4 output[], const uint1 input[], size_type len) { void MD5::encode(uint1 output[], const uint4 input[], size_type len) { for (size_type i = 0, j = 0; j < len; i++, j += 4) { output[j] = input[i] & 0xff; - output[j+1] = (input[i] >> 8) & 0xff; - output[j+2] = (input[i] >> 16) & 0xff; - output[j+3] = (input[i] >> 24) & 0xff; + output[j + 1] = (input[i] >> 8) & 0xff; + output[j + 2] = (input[i] >> 16) & 0xff; + output[j + 3] = (input[i] >> 24) & 0xff; } } @@ -428,79 +402,79 @@ void MD5::encode(uint1 output[], const uint4 input[], size_type len) { // apply MD5 algo on a block void MD5::transform(const uint1 block[blocksize]) { uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - decode (x, block, blocksize); + decode(x, block, blocksize); /* Round 1 */ - FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ - FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ - FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ - FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ - FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ - FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ - FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ - FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ - FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ - FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ - FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ + FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ + FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ + FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ + FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ + FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ + FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ + FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ + FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ + FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ + FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ - GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ - GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ - GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ - GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ - GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ - GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ - GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ - GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ - GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ - GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ - GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ + GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ + GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ + GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ + GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ + GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ + GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ + GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ + GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ + GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ + GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ - HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ - HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ - HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ - HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ - HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ - HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ - HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ - HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ - HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ - HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ + HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ + HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ + HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ + HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ + HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ + HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ + HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ + HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ + HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ + HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ - II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ - II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ - II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ - II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ - II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ - II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ - II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ - II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ - II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ - II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ + II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ + II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ + II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ + II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ + II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ + II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ + II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ + II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ + II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ + II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ state[0] += a; state[1] += b; @@ -520,8 +494,7 @@ void MD5::update(const unsigned char input[], size_type length) { size_type index = count[0] / 8 % blocksize; // Update number of bits - if ((count[0] += (length << 3)) < (length << 3)) - count[1]++; + if ((count[0] += (length << 3)) < (length << 3)) count[1]++; count[1] += (length >> 29); // number of bytes we need to fill in buffer @@ -530,42 +503,35 @@ void MD5::update(const unsigned char input[], size_type length) { size_type i; // transform as many times as possible. - if (length >= firstpart) - { + if (length >= firstpart) { // fill buffer first, transform memcpy(&buffer[index], input, firstpart); transform(buffer); // transform chunks of blocksize (64 bytes) - for (i = firstpart; i + blocksize <= length; i += blocksize) - transform(&input[i]); + for (i = firstpart; i + blocksize <= length; i += blocksize) transform(&input[i]); index = 0; - } - else + } else i = 0; // buffer remaining input - memcpy(&buffer[index], &input[i], length-i); + memcpy(&buffer[index], &input[i], length - i); } ////////////////////////////// // for convenience provide a verson with signed char -void MD5::update(const char input[], size_type length) { - update((const unsigned char*)input, length); -} +void MD5::update(const char input[], size_type length) { update((const unsigned char*)input, length); } ////////////////////////////// // MD5 finalization. Ends an MD5 message-digest operation, writing the // the message digest and zeroizing the context. MD5& MD5::finalize() { - static unsigned char padding[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; + static unsigned char padding[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; if (!finalized) { // Save number of bits @@ -587,7 +553,7 @@ MD5& MD5::finalize() { memset(buffer, 0, sizeof buffer); memset(count, 0, sizeof count); - finalized=true; + finalized = true; } return *this; @@ -597,20 +563,17 @@ MD5& MD5::finalize() { // return hex representation of digest as string std::string MD5::hexdigest() const { - if (!finalized) - return ""; + if (!finalized) return ""; char buf[33]; - for (int i=0; i<16; i++) - sprintf(buf+i*2, "%02x", digest[i]); - buf[32]=0; + for (int i = 0; i < 16; i++) sprintf(buf + i * 2, "%02x", digest[i]); + buf[32] = 0; return std::string(buf); } std::string MD5::rawdigest() const { - if (!finalized) - return ""; + if (!finalized) return ""; std::string res; for (unsigned int i = 0; i < 16; ++i) { res.append(1, digest[i]); @@ -620,13 +583,11 @@ std::string MD5::rawdigest() const { ////////////////////////////// -std::ostream& operator<<(std::ostream& out, MD5 md5) { - return out << md5.hexdigest(); -} +std::ostream& operator<<(std::ostream& out, MD5 md5) { return out << md5.hexdigest(); } ////////////////////////////// -std::string md5(const std::string &str, bool raw) { +std::string md5(const std::string& str, bool raw) { MD5 md5 = MD5(str); if (raw) { diff --git a/src/pstd/src/pstd_mutex.cc b/src/pstd/src/pstd_mutex.cc index 1b677d5f6c..dc8c53815a 100644 --- a/src/pstd/src/pstd_mutex.cc +++ b/src/pstd/src/pstd_mutex.cc @@ -1,9 +1,9 @@ #include "pstd/include/pstd_mutex.h" -#include #include #include #include +#include #include @@ -28,58 +28,31 @@ static bool PthreadTimeoutCall(const char* label, int result) { return true; } -Mutex::Mutex() { - PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL)); -} +Mutex::Mutex() { PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL)); } -Mutex::~Mutex() { - PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_)); -} +Mutex::~Mutex() { PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_)); } -void Mutex::Lock() { - PthreadCall("lock", pthread_mutex_lock(&mu_)); -} +void Mutex::Lock() { PthreadCall("lock", pthread_mutex_lock(&mu_)); } -void Mutex::Unlock() { - PthreadCall("unlock", pthread_mutex_unlock(&mu_)); -} +void Mutex::Unlock() { PthreadCall("unlock", pthread_mutex_unlock(&mu_)); } -RWMutex::RWMutex() { - PthreadCall("init rw mutex", pthread_rwlock_init(&rw_mu_, NULL)); -} +RWMutex::RWMutex() { PthreadCall("init rw mutex", pthread_rwlock_init(&rw_mu_, NULL)); } -RWMutex::~RWMutex() { - PthreadCall("destroy rw mutex", pthread_rwlock_destroy(&rw_mu_)); -} +RWMutex::~RWMutex() { PthreadCall("destroy rw mutex", pthread_rwlock_destroy(&rw_mu_)); } -void RWMutex::ReadLock() { - PthreadCall("rw readlock", pthread_rwlock_rdlock(&rw_mu_)); -} +void RWMutex::ReadLock() { PthreadCall("rw readlock", pthread_rwlock_rdlock(&rw_mu_)); } -void RWMutex::WriteLock() { - PthreadCall("rw writelock", pthread_rwlock_wrlock(&rw_mu_)); -} +void RWMutex::WriteLock() { PthreadCall("rw writelock", pthread_rwlock_wrlock(&rw_mu_)); } -void RWMutex::WriteUnlock() { - PthreadCall("rw write unlock", pthread_rwlock_unlock(&rw_mu_)); -} +void RWMutex::WriteUnlock() { PthreadCall("rw write unlock", pthread_rwlock_unlock(&rw_mu_)); } -void RWMutex::ReadUnlock() { - PthreadCall("rw read unlock", pthread_rwlock_unlock(&rw_mu_)); -} +void RWMutex::ReadUnlock() { PthreadCall("rw read unlock", pthread_rwlock_unlock(&rw_mu_)); } -CondVar::CondVar(Mutex* mu) - : mu_(mu) { - PthreadCall("init cv", pthread_cond_init(&cv_, NULL)); - } +CondVar::CondVar(Mutex* mu) : mu_(mu) { PthreadCall("init cv", pthread_cond_init(&cv_, NULL)); } -CondVar::~CondVar() { - PthreadCall("destroy cv", pthread_cond_destroy(&cv_)); -} +CondVar::~CondVar() { PthreadCall("destroy cv", pthread_cond_destroy(&cv_)); } -void CondVar::Wait() { - PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_)); -} +void CondVar::Wait() { PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_)); } // return false if timeout bool CondVar::TimedWait(uint32_t timeout) { @@ -95,34 +68,23 @@ bool CondVar::TimedWait(uint32_t timeout) { tsp.tv_sec = now.tv_sec + usec / 1000000; tsp.tv_nsec = (usec % 1000000) * 1000; - return PthreadTimeoutCall("timewait", - pthread_cond_timedwait(&cv_, &mu_->mu_, &tsp)); + return PthreadTimeoutCall("timewait", pthread_cond_timedwait(&cv_, &mu_->mu_, &tsp)); } -void CondVar::Signal() { - PthreadCall("signal", pthread_cond_signal(&cv_)); -} +void CondVar::Signal() { PthreadCall("signal", pthread_cond_signal(&cv_)); } -void CondVar::SignalAll() { - PthreadCall("broadcast", pthread_cond_broadcast(&cv_)); -} +void CondVar::SignalAll() { PthreadCall("broadcast", pthread_cond_broadcast(&cv_)); } -void InitOnce(OnceType* once, void (*initializer)()) { - PthreadCall("once", pthread_once(once, initializer)); -} +void InitOnce(OnceType* once, void (*initializer)()) { PthreadCall("once", pthread_once(once, initializer)); } RefMutex::RefMutex() { refs_ = 0; PthreadCall("init mutex", pthread_mutex_init(&mu_, nullptr)); } -RefMutex::~RefMutex() { - PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_)); -} +RefMutex::~RefMutex() { PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_)); } -void RefMutex::Ref() { - refs_++; -} +void RefMutex::Ref() { refs_++; } void RefMutex::Unref() { --refs_; if (refs_ == 0) { @@ -130,36 +92,32 @@ void RefMutex::Unref() { } } -void RefMutex::Lock() { - PthreadCall("lock", pthread_mutex_lock(&mu_)); -} +void RefMutex::Lock() { PthreadCall("lock", pthread_mutex_lock(&mu_)); } -void RefMutex::Unlock() { - PthreadCall("unlock", pthread_mutex_unlock(&mu_)); -} +void RefMutex::Unlock() { PthreadCall("unlock", pthread_mutex_unlock(&mu_)); } RecordMutex::~RecordMutex() { mutex_.Lock(); - - std::unordered_map::const_iterator it = records_.begin(); + + std::unordered_map::const_iterator it = records_.begin(); for (; it != records_.end(); it++) { delete it->second; } mutex_.Unlock(); } -void RecordMutex::Lock(const std::string &key) { +void RecordMutex::Lock(const std::string& key) { mutex_.Lock(); - std::unordered_map::const_iterator it = records_.find(key); + std::unordered_map::const_iterator it = records_.find(key); if (it != records_.end()) { - RefMutex *ref_mutex = it->second; + RefMutex* ref_mutex = it->second; ref_mutex->Ref(); mutex_.Unlock(); ref_mutex->Lock(); } else { - RefMutex *ref_mutex = new RefMutex(); + RefMutex* ref_mutex = new RefMutex(); records_.insert(std::make_pair(key, ref_mutex)); ref_mutex->Ref(); @@ -169,12 +127,12 @@ void RecordMutex::Lock(const std::string &key) { } } -void RecordMutex::Unlock(const std::string &key) { +void RecordMutex::Unlock(const std::string& key) { mutex_.Lock(); - std::unordered_map::const_iterator it = records_.find(key); - + std::unordered_map::const_iterator it = records_.find(key); + if (it != records_.end()) { - RefMutex *ref_mutex = it->second; + RefMutex* ref_mutex = it->second; if (ref_mutex->IsLastRef()) { records_.erase(it); @@ -186,5 +144,4 @@ void RecordMutex::Unlock(const std::string &key) { mutex_.Unlock(); } -} - +} // namespace pstd diff --git a/src/pstd/src/pstd_status.cc b/src/pstd/src/pstd_status.cc index 82dafc8681..aa34633d6e 100644 --- a/src/pstd/src/pstd_status.cc +++ b/src/pstd/src/pstd_status.cc @@ -2,8 +2,8 @@ // 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 #include "pstd/include/pstd_status.h" +#include namespace pstd { @@ -39,46 +39,46 @@ std::string Status::ToString() const { char tmp[30]; const char* type; switch (code()) { - case kOk: - type = "OK"; - break; - case kNotFound: - type = "NotFound: "; - break; - case kCorruption: - type = "Corruption: "; - break; - case kNotSupported: - type = "Not implemented: "; - break; - case kInvalidArgument: - type = "Invalid argument: "; - break; - case kIOError: - type = "IO error: "; - break; - case kEndFile: - type = "End file: "; - break; - case kIncomplete: - type = "InComplete: "; - break; - case kComplete: - type = "Complete: "; - break; - case kTimeout: - type = "Timeout: "; - break; - case kAuthFailed: - type = "AuthFailed: "; - break; - case kBusy: - type = "Busy:"; - break; - default: - snprintf(tmp, sizeof(tmp), "Unknown code(%d): ", static_cast(code())); - type = tmp; - break; + case kOk: + type = "OK"; + break; + case kNotFound: + type = "NotFound: "; + break; + case kCorruption: + type = "Corruption: "; + break; + case kNotSupported: + type = "Not implemented: "; + break; + case kInvalidArgument: + type = "Invalid argument: "; + break; + case kIOError: + type = "IO error: "; + break; + case kEndFile: + type = "End file: "; + break; + case kIncomplete: + type = "InComplete: "; + break; + case kComplete: + type = "Complete: "; + break; + case kTimeout: + type = "Timeout: "; + break; + case kAuthFailed: + type = "AuthFailed: "; + break; + case kBusy: + type = "Busy:"; + break; + default: + snprintf(tmp, sizeof(tmp), "Unknown code(%d): ", static_cast(code())); + type = tmp; + break; } std::string result(type); uint32_t length; @@ -88,5 +88,4 @@ std::string Status::ToString() const { } } - -} // namespace pstd +} // namespace pstd diff --git a/src/pstd/src/pstd_testharness.cc b/src/pstd/src/pstd_testharness.cc index e70fcebd4e..03f4aab441 100644 --- a/src/pstd/src/pstd_testharness.cc +++ b/src/pstd/src/pstd_testharness.cc @@ -28,7 +28,7 @@ struct Test { void (*func)(); }; std::vector* tests; -} +} // namespace bool RegisterTest(const char* base, const char* name, void (*func)()) { if (tests == NULL) { diff --git a/src/pstd/src/rsync.cc b/src/pstd/src/rsync.cc index 5bbfea280b..a2f5e9d774 100644 --- a/src/pstd/src/rsync.cc +++ b/src/pstd/src/rsync.cc @@ -8,16 +8,11 @@ namespace pstd { // Clean files for rsync info, such as the lock, log, pid, conf file -static bool CleanRsyncInfo(const std::string& path) { - return pstd::DeleteDirIfExist(path + kRsyncSubDir); -} +static bool CleanRsyncInfo(const std::string& path) { return pstd::DeleteDirIfExist(path + kRsyncSubDir); } -int StartRsync(const std::string& raw_path, - const std::string& module, - const std::string& ip, - const int port, +int StartRsync(const std::string& raw_path, const std::string& module, const std::string& ip, const int port, const std::string& passwd) { - // Sanity check + // Sanity check if (raw_path.empty() || module.empty() || passwd.empty()) { return -1; } @@ -81,7 +76,7 @@ int StartRsync(const std::string& raw_path, } int StopRsync(const std::string& raw_path) { - // Sanity check + // Sanity check if (raw_path.empty()) { log_warn("empty rsync path!"); return -1; @@ -94,11 +89,11 @@ int StopRsync(const std::string& raw_path) { std::string pid_file(path + kRsyncSubDir + "/" + kRsyncPidFile); if (!FileExists(pid_file)) { log_warn("no rsync pid file found"); - return 0; // Rsync deamon is not exist + return 0; // Rsync deamon is not exist } // Kill Rsync - SequentialFile *sequential_file; + SequentialFile* sequential_file; if (!NewSequentialFile(pid_file, &sequential_file).ok()) { log_warn("no rsync pid file found"); return 0; @@ -112,7 +107,7 @@ int StopRsync(const std::string& raw_path) { }; delete sequential_file; - + pid_t pid = atoi(line); if (pid <= 1) { @@ -131,17 +126,13 @@ int StopRsync(const std::string& raw_path) { return ret; } -int RsyncSendFile(const std::string& local_file_path, - const std::string& remote_file_path, - const std::string& secret_file_path, - const RsyncRemote& remote) { +int RsyncSendFile(const std::string& local_file_path, const std::string& remote_file_path, + const std::string& secret_file_path, const RsyncRemote& remote) { std::stringstream ss; - ss << """rsync -avP --bwlimit=" << remote.kbps - << " --password-file=" << secret_file_path - << " --port=" << remote.port - << " " << local_file_path - << " " << kRsyncUser << "@" << remote.host - << "::" << remote.module << "/" << remote_file_path; + ss << "" + "rsync -avP --bwlimit=" + << remote.kbps << " --password-file=" << secret_file_path << " --port=" << remote.port << " " << local_file_path + << " " << kRsyncUser << "@" << remote.host << "::" << remote.module << "/" << remote_file_path; std::string rsync_cmd = ss.str(); int ret = system(rsync_cmd.c_str()); if (ret == 0 || (WIFEXITED(ret) && !WEXITSTATUS(ret))) { @@ -151,10 +142,8 @@ int RsyncSendFile(const std::string& local_file_path, return ret; } -int RsyncSendClearTarget(const std::string& local_dir_path, - const std::string& remote_dir_path, - const std::string& secret_file_path, - const RsyncRemote& remote) { +int RsyncSendClearTarget(const std::string& local_dir_path, const std::string& remote_dir_path, + const std::string& secret_file_path, const RsyncRemote& remote) { if (local_dir_path.empty() || remote_dir_path.empty()) { return -2; } @@ -166,11 +155,8 @@ int RsyncSendClearTarget(const std::string& local_dir_path, remote_dir.append("/"); } std::stringstream ss; - ss << "rsync -avP --delete --port=" << remote.port - << " --password-file=" << secret_file_path - << " " << local_dir - << " " << kRsyncUser << "@" << remote.host - << "::" << remote.module << "/" << remote_dir; + ss << "rsync -avP --delete --port=" << remote.port << " --password-file=" << secret_file_path << " " << local_dir + << " " << kRsyncUser << "@" << remote.host << "::" << remote.module << "/" << remote_dir; std::string rsync_cmd = ss.str(); int ret = system(rsync_cmd.c_str()); if (ret == 0 || (WIFEXITED(ret) && !WEXITSTATUS(ret))) { diff --git a/src/pstd/src/scope_record_lock.cc b/src/pstd/src/scope_record_lock.cc index 11f51242b0..1c7d46f556 100644 --- a/src/pstd/src/scope_record_lock.cc +++ b/src/pstd/src/scope_record_lock.cc @@ -9,14 +9,11 @@ namespace pstd { namespace lock { -MultiScopeRecordLock::MultiScopeRecordLock(LockMgr* lock_mgr, - const std::vector& keys) : - lock_mgr_(lock_mgr), - keys_(keys) { +MultiScopeRecordLock::MultiScopeRecordLock(LockMgr* lock_mgr, const std::vector& keys) + : lock_mgr_(lock_mgr), keys_(keys) { std::string pre_key; std::sort(keys_.begin(), keys_.end()); - if (!keys_.empty() && - keys_[0].empty()) { + if (!keys_.empty() && keys_[0].empty()) { lock_mgr_->TryLock(pre_key); } @@ -29,8 +26,7 @@ MultiScopeRecordLock::MultiScopeRecordLock(LockMgr* lock_mgr, } MultiScopeRecordLock::~MultiScopeRecordLock() { std::string pre_key; - if (!keys_.empty() && - keys_[0].empty()) { + if (!keys_.empty() && keys_[0].empty()) { lock_mgr_->UnLock(pre_key); } @@ -61,7 +57,6 @@ void MultiRecordLock::Lock(const std::vector& keys) { } } - void MultiRecordLock::Unlock(const std::vector& keys) { std::vector internal_keys = keys; std::sort(internal_keys.begin(), internal_keys.end()); diff --git a/src/pstd/src/testutil.cc b/src/pstd/src/testutil.cc index 87411dd00a..34064d2152 100644 --- a/src/pstd/src/testutil.cc +++ b/src/pstd/src/testutil.cc @@ -15,7 +15,7 @@ std::string RandomString(const int len) { return std::string(buf, len); } -int GetTestDirectory(std::string *result) { +int GetTestDirectory(std::string* result) { const char* env = getenv("TEST_TMPDIR"); if (env && env[0] != '\0') { *result = env; diff --git a/src/pstd/tests/base_conf_test.cc b/src/pstd/tests/base_conf_test.cc index 7e4ee7bbae..fe7a9d875f 100644 --- a/src/pstd/tests/base_conf_test.cc +++ b/src/pstd/tests/base_conf_test.cc @@ -6,11 +6,10 @@ #include #include -#include "pstd/include/env.h" #include "pstd/include/base_conf.h" -#include "pstd/include/testutil.h" +#include "pstd/include/env.h" #include "pstd/include/pstd_testharness.h" - +#include "pstd/include/testutil.h" namespace pstd { @@ -25,17 +24,16 @@ class BaseConfTest { Status CreateSampleConf() { std::vector sample_conf = { - "test_int : 1\n", - "test_str : abkxk\n", - "test_vec : four, five, six\n", - "test_bool : yes\n", + "test_int : 1\n", + "test_str : abkxk\n", + "test_vec : four, five, six\n", + "test_bool : yes\n", }; - WritableFile *write_file; + WritableFile* write_file; Status ret = NewWritableFile(test_conf_, &write_file); - if (!ret.ok()) - return ret; - for (std::string &item : sample_conf) { + if (!ret.ok()) return ret; + for (std::string& item : sample_conf) { write_file->Append(item); } delete write_file; @@ -50,7 +48,7 @@ class BaseConfTest { TEST(BaseConfTest, WriteReadConf) { ASSERT_OK(CreateSampleConf()); - BaseConf *conf = new BaseConf(test_conf_); + BaseConf* conf = new BaseConf(test_conf_); ASSERT_EQ(conf->LoadConf(), 0); // Write configuration diff --git a/src/pstd/tests/slash_binlog_test.cc b/src/pstd/tests/slash_binlog_test.cc index 551ccb3cef..bca80fe74d 100644 --- a/src/pstd/tests/slash_binlog_test.cc +++ b/src/pstd/tests/slash_binlog_test.cc @@ -5,18 +5,16 @@ #include #include "pstd/include/env.h" -#include "pstd/include/testutil.h" -#include "pstd/include/pstd_testharness.h" #include "pstd/include/pstd_binlog.h" +#include "pstd/include/pstd_testharness.h" +#include "pstd/include/testutil.h" #include "pstd/src/pstd_binlog_impl.h" namespace pstd { class BinlogTest { public: - BinlogTest() - : log_(NULL), - reader_(NULL) { + BinlogTest() : log_(NULL), reader_(NULL) { GetTestDirectory(&tmpdir_); DeleteDirIfExist(tmpdir_); ASSERT_OK(Binlog::Open(tmpdir_, &log_)); @@ -26,9 +24,10 @@ class BinlogTest { delete log_; DeleteDirIfExist(tmpdir_); } + protected: - Binlog *log_; - BinlogReader *reader_; + Binlog* log_; + BinlogReader* reader_; const std::string test_item_ = "pstd_item"; std::string tmpdir_; }; diff --git a/src/pstd/tests/slash_coding_test.cc b/src/pstd/tests/slash_coding_test.cc index 875df68528..c42a46ab4e 100644 --- a/src/pstd/tests/slash_coding_test.cc +++ b/src/pstd/tests/slash_coding_test.cc @@ -14,7 +14,7 @@ namespace pstd { -class Coding { }; +class Coding {}; TEST(Coding, Fixed32) { std::string s; @@ -44,15 +44,15 @@ TEST(Coding, Fixed64) { uint64_t v = static_cast(1) << power; uint64_t actual; actual = DecodeFixed64(p); - ASSERT_EQ(v-1, actual); + ASSERT_EQ(v - 1, actual); p += sizeof(uint64_t); actual = DecodeFixed64(p); - ASSERT_EQ(v+0, actual); + ASSERT_EQ(v + 0, actual); p += sizeof(uint64_t); actual = DecodeFixed64(p); - ASSERT_EQ(v+1, actual); + ASSERT_EQ(v + 1, actual); p += sizeof(uint64_t); } } @@ -113,8 +113,8 @@ TEST(Coding, Varint64) { // Test values near powers of two const uint64_t power = 1ull << k; values.push_back(power); - values.push_back(power-1); - values.push_back(power+1); + values.push_back(power - 1); + values.push_back(power + 1); } std::string s; @@ -134,14 +134,12 @@ TEST(Coding, Varint64) { ASSERT_EQ(VarintLength(actual), p - start); } ASSERT_EQ(p, limit); - } TEST(Coding, Varint32Overflow) { uint32_t result; std::string input("\x81\x82\x83\x84\x85\x11"); - ASSERT_TRUE(GetVarint32Ptr(input.data(), input.data() + input.size(), &result) - == NULL); + ASSERT_TRUE(GetVarint32Ptr(input.data(), input.data() + input.size(), &result) == NULL); } TEST(Coding, Varint32Truncation) { @@ -159,8 +157,7 @@ TEST(Coding, Varint32Truncation) { TEST(Coding, Varint64Overflow) { uint64_t result; std::string input("\x81\x82\x83\x84\x85\x81\x82\x83\x84\x85\x11"); - ASSERT_TRUE(GetVarint64Ptr(input.data(), input.data() + input.size(), &result) - == NULL); + ASSERT_TRUE(GetVarint64Ptr(input.data(), input.data() + input.size(), &result) == NULL); } TEST(Coding, Varint64Truncation) { diff --git a/src/pstd/tests/slash_env_test.cc b/src/pstd/tests/slash_env_test.cc index a930f54f55..de719c141a 100644 --- a/src/pstd/tests/slash_env_test.cc +++ b/src/pstd/tests/slash_env_test.cc @@ -8,12 +8,12 @@ // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "pstd/include/env.h" -#include "pstd/include/testutil.h" #include "pstd/include/pstd_testharness.h" +#include "pstd/include/testutil.h" namespace pstd { -class EnvTest { }; +class EnvTest {}; TEST(EnvTest, SetMaxFileDescriptorNum) { ASSERT_EQ(0, SetMaxFileDescriptorNum(10)); diff --git a/src/pstd/tests/slash_string_test.cc b/src/pstd/tests/slash_string_test.cc index e473af2139..1fe22f63cb 100644 --- a/src/pstd/tests/slash_string_test.cc +++ b/src/pstd/tests/slash_string_test.cc @@ -35,50 +35,50 @@ TEST(StringTest, test_string2ll) { long long v; /* May not start with +. */ - strcpy(buf,"+1"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, "+1"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); /* Leading space. */ - strcpy(buf," 1"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, " 1"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); /* Trailing space. */ - strcpy(buf,"1 "); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, "1 "); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); - strcpy(buf,"-1"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "-1"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, -1); - strcpy(buf,"0"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "0"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, 0); - strcpy(buf,"1"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "1"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, 1); - strcpy(buf,"99"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "99"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, 99); - strcpy(buf,"-99"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "-99"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, -99); - strcpy(buf,"-9223372036854775808"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "-9223372036854775808"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, LLONG_MIN); - strcpy(buf,"-9223372036854775809"); /* overflow */ - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, "-9223372036854775809"); /* overflow */ + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); - strcpy(buf,"9223372036854775807"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "9223372036854775807"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, LLONG_MAX); - strcpy(buf,"9223372036854775808"); /* overflow */ - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, "9223372036854775808"); /* overflow */ + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); } TEST(StringTest, test_string2l) { @@ -86,43 +86,43 @@ TEST(StringTest, test_string2l) { long v; /* May not start with +. */ - strcpy(buf,"+1"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, "+1"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); - strcpy(buf,"-1"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "-1"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, -1); - strcpy(buf,"0"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "0"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, 0); - strcpy(buf,"1"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "1"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, 1); - strcpy(buf,"99"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "99"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, 99); - strcpy(buf,"-99"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "-99"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, -99); #if LONG_MAX != LLONG_MAX - strcpy(buf,"-2147483648"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "-2147483648"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, LONG_MIN); - strcpy(buf,"-2147483649"); /* overflow */ - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, "-2147483649"); /* overflow */ + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); - strcpy(buf,"2147483647"); - ASSERT_EQ(string2int(buf,strlen(buf),&v), 1); + strcpy(buf, "2147483647"); + ASSERT_EQ(string2int(buf, strlen(buf), &v), 1); ASSERT_EQ(v, LONG_MAX); - strcpy(buf,"2147483648"); /* overflow */ - ASSERT_EQ(string2int(buf,strlen(buf),&v), 0); + strcpy(buf, "2147483648"); /* overflow */ + ASSERT_EQ(string2int(buf, strlen(buf), &v), 0); #endif } diff --git a/src/pstd/tests/test_main.cc b/src/pstd/tests/test_main.cc index 5d9590a428..1b0604368d 100644 --- a/src/pstd/tests/test_main.cc +++ b/src/pstd/tests/test_main.cc @@ -1,5 +1,3 @@ #include "pstd/include/pstd_testharness.h" -int main() { - return pstd::test::RunAllTests(); -} +int main() { return pstd::test::RunAllTests(); } diff --git a/src/storage/benchmark/storage_bench.cc b/src/storage/benchmark/storage_bench.cc index ba0104cc36..20c2b2ae9b 100644 --- a/src/storage/benchmark/storage_bench.cc +++ b/src/storage/benchmark/storage_bench.cc @@ -3,10 +3,10 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. +#include #include -#include #include -#include +#include #include "storage/storage.h" @@ -38,31 +38,35 @@ void BenchSet() { jobs.clear(); auto start = std::chrono::system_clock::now(); for (size_t i = 0; i < THREADNUM; ++i) { - jobs.emplace_back([&db](size_t kv_num) { - for (size_t j = 0; j < kv_num; ++j) { - db.Set(key, value); - } - }, kv_num); + jobs.emplace_back( + [&db](size_t kv_num) { + for (size_t j = 0; j < kv_num; ++j) { + db.Set(key, value); + } + }, + kv_num); } for (auto& job : jobs) { job.join(); } auto end = system_clock::now(); - duration elapsed_seconds = end-start; + duration elapsed_seconds = end - start; auto cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 1, Set " << THREADNUM * kv_num << " Cost: " - << cost << "s QPS: " << (THREADNUM * kv_num) / cost << std::endl; + std::cout << "Test case 1, Set " << THREADNUM * kv_num << " Cost: " << cost + << "s QPS: " << (THREADNUM * kv_num) / cost << std::endl; kv_num = 100000; jobs.clear(); start = system_clock::now(); for (size_t i = 0; i < THREADNUM; ++i) { - jobs.emplace_back([&db](size_t kv_num) { - for (size_t j = 0; j < kv_num; ++j) { - db.Set(key, value); - } - }, kv_num); + jobs.emplace_back( + [&db](size_t kv_num) { + for (size_t j = 0; j < kv_num; ++j) { + db.Set(key, value); + } + }, + kv_num); } for (auto& job : jobs) { @@ -71,8 +75,8 @@ void BenchSet() { end = system_clock::now(); elapsed_seconds = end - start; cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 2, Set " << THREADNUM * kv_num << " Cost: " - << cost << "s QPS: " << (THREADNUM * kv_num) / cost << std::endl; + std::cout << "Test case 2, Set " << THREADNUM * kv_num << " Cost: " << cost + << "s QPS: " << (THREADNUM * kv_num) / cost << std::endl; } void BenchHGetall() { @@ -109,8 +113,7 @@ void BenchHGetall() { auto end = system_clock::now(); duration elapsed_seconds = end - start; auto cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 1, HGetall " << fvs_out.size() - << " Field HashTable Cost: "<< cost << "ms" << std::endl; + std::cout << "Test case 1, HGetall " << fvs_out.size() << " Field HashTable Cost: " << cost << "ms" << std::endl; // 1. Create the hash table then insert hash table 10000000 field // 2. Delete the hash table @@ -141,8 +144,7 @@ void BenchHGetall() { end = system_clock::now(); elapsed_seconds = end - start; cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 2, HGetall " << fvs_out.size() - << " Field HashTable Cost: "<< cost << "ms" << std::endl; + std::cout << "Test case 2, HGetall " << fvs_out.size() << " Field HashTable Cost: " << cost << "ms" << std::endl; // 1. Create the hash table then insert hash table 10000000 field // 2. Delete hash table 9990000 field, the hash table remain 10000 field @@ -166,8 +168,7 @@ void BenchHGetall() { end = system_clock::now(); elapsed_seconds = end - start; cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 3, HGetall " << fvs_out.size() - << " Field HashTable Cost: "<< cost << "ms" << std::endl; + std::cout << "Test case 3, HGetall " << fvs_out.size() << " Field HashTable Cost: " << cost << "ms" << std::endl; } void BenchScan() { @@ -187,22 +188,24 @@ void BenchScan() { jobs.clear(); auto start = std::chrono::system_clock::now(); for (size_t i = 0; i < THREADNUM; ++i) { - jobs.emplace_back([&db](size_t kv_num) { - for (size_t j = 0; j < kv_num; ++j) { - std::string key_prefix = key + std::to_string(j); - db.Set(key_prefix, value); - } - }, kv_num); + jobs.emplace_back( + [&db](size_t kv_num) { + for (size_t j = 0; j < kv_num; ++j) { + std::string key_prefix = key + std::to_string(j); + db.Set(key_prefix, value); + } + }, + kv_num); } for (auto& job : jobs) { job.join(); } auto end = system_clock::now(); - duration elapsed_seconds = end-start; + duration elapsed_seconds = end - start; auto cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 1, Set " << THREADNUM * kv_num << " Cost: " - << cost << "s QPS: " << (THREADNUM * kv_num) / cost << std::endl; + std::cout << "Test case 1, Set " << THREADNUM * kv_num << " Cost: " << cost + << "s QPS: " << (THREADNUM * kv_num) / cost << std::endl; // Scan 100000 std::vector keys; @@ -211,8 +214,7 @@ void BenchScan() { end = system_clock::now(); elapsed_seconds = end - start; cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 2, Scan " << 100000 << " Cost: " - << cost << "s" << std::endl; + std::cout << "Test case 2, Scan " << 100000 << " Cost: " << cost << "s" << std::endl; // Scan 10000000 keys.clear(); @@ -221,11 +223,9 @@ void BenchScan() { end = system_clock::now(); elapsed_seconds = end - start; cost = duration_cast(elapsed_seconds).count(); - std::cout << "Test case 3, Scan " << kv_num << " Cost: " - << cost << "s" << std::endl; + std::cout << "Test case 3, Scan " << kv_num << " Cost: " << cost << "s" << std::endl; } - int main(int argc, char** argv) { // keys BenchSet(); diff --git a/src/storage/examples/hashes_example.cc b/src/storage/examples/hashes_example.cc index 05f0415a4a..0a766e595f 100644 --- a/src/storage/examples/hashes_example.cc +++ b/src/storage/examples/hashes_example.cc @@ -60,8 +60,7 @@ int main() { s = db.HMGet("TEST_HASH", fields, &vss); printf("HMget return: %s\n", s.ToString().c_str()); for (uint32_t idx = 0; idx != fields.size(); idx++) { - printf("idx = %d, field = %s, value = %s\n", - idx, fields[idx].c_str(), vss[idx].value.c_str()); + printf("idx = %d, field = %s, value = %s\n", idx, fields[idx].c_str(), vss[idx].value.c_str()); } // HLEN diff --git a/src/storage/examples/sets_example.cc b/src/storage/examples/sets_example.cc index b22ece0f0c..af002adc59 100644 --- a/src/storage/examples/sets_example.cc +++ b/src/storage/examples/sets_example.cc @@ -22,7 +22,7 @@ int main() { } // SAdd int32_t ret = 0; - std::vector members {"MM1", "MM2", "MM3", "MM2"}; + std::vector members{"MM1", "MM2", "MM3", "MM2"}; s = db.SAdd("SADD_KEY", members, &ret); printf("SAdd return: %s, ret = %d\n", s.ToString().c_str(), ret); diff --git a/src/storage/examples/strings_example.cc b/src/storage/examples/strings_example.cc index a5e19fd0f6..a4241b8b95 100644 --- a/src/storage/examples/strings_example.cc +++ b/src/storage/examples/strings_example.cc @@ -33,13 +33,11 @@ int main() { // SetBit s = db.SetBit("SETBIT_KEY", 7, 1, &ret); - printf("SetBit return: %s, ret: %d\n", - s.ToString().c_str(), ret); + printf("SetBit return: %s, ret: %d\n", s.ToString().c_str(), ret); // GetSet s = db.GetSet("TEST_KEY", "Hello", &value); - printf("GetSet return: %s, old_value: %s", - s.ToString().c_str(), value.c_str()); + printf("GetSet return: %s, old_value: %s", s.ToString().c_str(), value.c_str()); // SetBit s = db.SetBit("SETBIT_KEY", 7, 1, &ret); @@ -47,8 +45,7 @@ int main() { // GetBit s = db.GetBit("SETBIT_KEY", 7, &ret); - printf("GetBit return: %s, ret: %d\n", - s.ToString().c_str(), ret); + printf("GetBit return: %s, ret: %d\n", s.ToString().c_str(), ret); // MSet std::vector kvs; @@ -59,19 +56,16 @@ int main() { // MGet std::vector vss; - std::vector keys {"TEST_KEY1", - "TEST_KEY2", "TEST_KEY_NOT_EXIST"}; + std::vector keys{"TEST_KEY1", "TEST_KEY2", "TEST_KEY_NOT_EXIST"}; s = db.MGet(keys, &vss); printf("MGet return: %s\n", s.ToString().c_str()); for (size_t idx = 0; idx != keys.size(); idx++) { - printf("idx = %d, keys = %s, value = %s\n", - idx, keys[idx].c_str(), vss[idx].value.c_str()); + printf("idx = %d, keys = %s, value = %s\n", idx, keys[idx].c_str(), vss[idx].value.c_str()); } // Setnx s = db.Setnx("TEST_KEY", "TEST_VALUE", &ret); - printf("Setnx return: %s, value: %s, ret: %d\n", - s.ToString().c_str(), value.c_str(), ret); + printf("Setnx return: %s, value: %s, ret: %d\n", s.ToString().c_str(), value.c_str(), ret); // MSetnx s = db.MSetnx(kvs, &ret); @@ -83,16 +77,14 @@ int main() { // Getrange s = db.Getrange("TEST_KEY", 0, -1, &value); - printf("Getrange return: %s, value: %s\n", - s.ToString().c_str(), value.c_str()); + printf("Getrange return: %s, value: %s\n", s.ToString().c_str(), value.c_str()); // Append std::string append_value; s = db.Set("TEST_KEY", "TEST_VALUE"); s = db.Append("TEST_KEY", "APPEND_VALUE", &ret); s = db.Get("TEST_KEY", &append_value); - printf("Append return: %s, value: %s, ret: %d\n", - s.ToString().c_str(), append_value.c_str(), ret); + printf("Append return: %s, value: %s, ret: %d\n", s.ToString().c_str(), append_value.c_str(), ret); // BitCount s = db.BitCount("TEST_KEY", 0, -1, &ret, false); @@ -107,23 +99,19 @@ int main() { s = db.Set("BITOP_KEY1", "FOOBAR"); s = db.Set("BITOP_KEY2", "ABCDEF"); s = db.Set("BITOP_KEY3", "STORAGE"); - std::vector src_keys {"BITOP_KEY1", "BITOP_KEY2", "BITOP_KEY3"}; + std::vector src_keys{"BITOP_KEY1", "BITOP_KEY2", "BITOP_KEY3"}; // and - s = db.BitOp(storage::BitOpType::kBitOpAnd, - "BITOP_DESTKEY", src_keys, &bitop_ret); + s = db.BitOp(storage::BitOpType::kBitOpAnd, "BITOP_DESTKEY", src_keys, &bitop_ret); printf("BitOp return: %s, ret: %d\n", s.ToString().c_str(), bitop_ret); // or - s = db.BitOp(storage::BitOpType::kBitOpOr, - "BITOP_DESTKEY", src_keys, &bitop_ret); + s = db.BitOp(storage::BitOpType::kBitOpOr, "BITOP_DESTKEY", src_keys, &bitop_ret); printf("BitOp return: %s, ret: %d\n", s.ToString().c_str(), bitop_ret); // xor - s = db.BitOp(storage::BitOpType::kBitOpXor, - "BITOP_DESTKEY", src_keys, &bitop_ret); + s = db.BitOp(storage::BitOpType::kBitOpXor, "BITOP_DESTKEY", src_keys, &bitop_ret); printf("BitOp return: %s, ret: %d\n", s.ToString().c_str(), bitop_ret); // not - std::vector not_keys {"BITOP_KEY1"}; - s = db.BitOp(storage::BitOpType::kBitOpNot, - "BITOP_DESTKEY", not_keys, &bitop_ret); + std::vector not_keys{"BITOP_KEY1"}; + s = db.BitOp(storage::BitOpType::kBitOpNot, "BITOP_DESTKEY", not_keys, &bitop_ret); printf("BitOp return: %s, ret: %d\n", s.ToString().c_str(), bitop_ret); // BitPos @@ -153,8 +141,7 @@ int main() { // Incrbyfloat s = db.Set("INCRBYFLOAT_KEY", "10.50"); s = db.Incrbyfloat("INCRBYFLOAT_KEY", "0.1", &value); - printf("Incrbyfloat return: %s, value: %s\n", - s.ToString().c_str(), value.c_str()); + printf("Incrbyfloat return: %s, value: %s\n", s.ToString().c_str(), value.c_str()); // Setex s = db.Setex("TEST_KEY", "TEST_VALUE", 1); @@ -169,7 +156,6 @@ int main() { s = db.Strlen("TEST_KEY", &len); printf("Strlen return: %s, strlen: %d\n", s.ToString().c_str(), len); - // Expire std::map key_status; s = db.Set("EXPIRE_KEY", "EXPIREVALUE"); diff --git a/src/storage/include/storage/backupable.h b/src/storage/include/storage/backupable.h index ec5979cd68..a72e232c63 100644 --- a/src/storage/include/storage/backupable.h +++ b/src/storage/include/storage/backupable.h @@ -8,65 +8,63 @@ #include "rocksdb/db.h" -#include "util.h" -#include "storage.h" #include "db_checkpoint.h" +#include "storage.h" +#include "util.h" namespace storage { - const std::string DEFAULT_BK_PATH = "dump"; //Default backup root dir - const std::string DEFAULT_RS_PATH = "db"; //Default restore root dir - - // Arguments which will used by BackupSave Thread - // p_engine for BackupEngine handler - // backup_dir - // key_type kv, hash, list, set or zset - struct BackupSaveArgs { - void *p_engine; - const std::string backup_dir; - const std::string key_type; - Status res; - - BackupSaveArgs(void *_p_engine, - const std::string &_backup_dir, - const std::string &_key_type) +const std::string DEFAULT_BK_PATH = "dump"; // Default backup root dir +const std::string DEFAULT_RS_PATH = "db"; // Default restore root dir + +// Arguments which will used by BackupSave Thread +// p_engine for BackupEngine handler +// backup_dir +// key_type kv, hash, list, set or zset +struct BackupSaveArgs { + void* p_engine; + const std::string backup_dir; + const std::string key_type; + Status res; + + BackupSaveArgs(void* _p_engine, const std::string& _backup_dir, const std::string& _key_type) : p_engine(_p_engine), backup_dir(_backup_dir), key_type(_key_type) {} - }; - - struct BackupContent { - std::vector live_files; - rocksdb::VectorLogPtr live_wal_files; - uint64_t manifest_file_size = 0; - uint64_t sequence_number = 0; - }; - - class BackupEngine { - public: - ~BackupEngine(); - static Status Open(Storage *db, BackupEngine** backup_engine_ptr); - - Status SetBackupContent(); - - Status CreateNewBackup(const std::string &dir); - - void StopBackup(); - - Status CreateNewBackupSpecify(const std::string &dir, const std::string &type); - - private: - BackupEngine() {} - - std::map engines_; - std::map backup_content_; - std::map backup_pthread_ts_; - - Status NewCheckpoint(rocksdb::DB* rocksdb_db, const std::string& type); - std::string GetSaveDirByType(const std::string _dir, const std::string& _type) const { - std::string backup_dir = _dir.empty() ? DEFAULT_BK_PATH : _dir; - return backup_dir + ((backup_dir.back() != '/') ? "/" : "") + _type; - } - Status WaitBackupPthread(); - }; +}; + +struct BackupContent { + std::vector live_files; + rocksdb::VectorLogPtr live_wal_files; + uint64_t manifest_file_size = 0; + uint64_t sequence_number = 0; +}; + +class BackupEngine { + public: + ~BackupEngine(); + static Status Open(Storage* db, BackupEngine** backup_engine_ptr); + + Status SetBackupContent(); + + Status CreateNewBackup(const std::string& dir); + + void StopBackup(); + + Status CreateNewBackupSpecify(const std::string& dir, const std::string& type); + + private: + BackupEngine() {} + + std::map engines_; + std::map backup_content_; + std::map backup_pthread_ts_; + + Status NewCheckpoint(rocksdb::DB* rocksdb_db, const std::string& type); + std::string GetSaveDirByType(const std::string _dir, const std::string& _type) const { + std::string backup_dir = _dir.empty() ? DEFAULT_BK_PATH : _dir; + return backup_dir + ((backup_dir.back() != '/') ? "/" : "") + _type; + } + Status WaitBackupPthread(); +}; } // namespace storage #endif // SRC_BACKUPABLE_H_ diff --git a/src/storage/include/storage/db_checkpoint.h b/src/storage/include/storage/db_checkpoint.h index bbc0a71ed6..ecd7984afb 100644 --- a/src/storage/include/storage/db_checkpoint.h +++ b/src/storage/include/storage/db_checkpoint.h @@ -7,9 +7,9 @@ #ifndef ROCKSDB_LITE -#include -#include "rocksdb/status.h" -#include "rocksdb/transaction_log.h" +# include +# include "rocksdb/status.h" +# include "rocksdb/transaction_log.h" namespace rocksdb { @@ -29,13 +29,12 @@ class DBCheckpoint { // The directory will be an absolute path virtual Status CreateCheckpoint(const std::string& checkpoint_dir) = 0; - virtual Status GetCheckpointFiles(std::vector &live_files, - VectorLogPtr &live_wal_files, uint64_t &manifest_file_size, - uint64_t &sequence_number) = 0; + virtual Status GetCheckpointFiles(std::vector& live_files, VectorLogPtr& live_wal_files, + uint64_t& manifest_file_size, uint64_t& sequence_number) = 0; - virtual Status CreateCheckpointWithFiles(const std::string& checkpoint_dir, - std::vector &live_files, VectorLogPtr &live_wal_files, - uint64_t manifest_file_size, uint64_t sequence_number) = 0; + virtual Status CreateCheckpointWithFiles(const std::string& checkpoint_dir, std::vector& live_files, + VectorLogPtr& live_wal_files, uint64_t manifest_file_size, + uint64_t sequence_number) = 0; virtual ~DBCheckpoint() {} }; diff --git a/src/storage/include/storage/storage.h b/src/storage/include/storage/storage.h index b5dc7672b1..f110f286a1 100644 --- a/src/storage/include/storage/storage.h +++ b/src/storage/include/storage/storage.h @@ -6,20 +6,20 @@ #ifndef INCLUDE_STORAGE_STORAGE_H_ #define INCLUDE_STORAGE_STORAGE_H_ -#include -#include +#include #include +#include #include +#include #include -#include -#include "rocksdb/status.h" +#include "rocksdb/convenience.h" +#include "rocksdb/filter_policy.h" #include "rocksdb/options.h" #include "rocksdb/rate_limiter.h" #include "rocksdb/slice.h" +#include "rocksdb/status.h" #include "rocksdb/table.h" -#include "rocksdb/filter_policy.h" -#include "rocksdb/convenience.h" #include "pstd/include/pstd_mutex.h" @@ -30,7 +30,7 @@ const double ZSET_SCORE_MIN = std::numeric_limits::lowest(); const std::string PROPERTY_TYPE_ROCKSDB_MEMTABLE = "rocksdb.cur-size-all-mem-tables"; const std::string PROPERTY_TYPE_ROCKSDB_TABLE_READER = "rocksdb.estimate-table-readers-mem"; -const std::string PROPERTY_TYPE_ROCKSDB_BACKGROUND_ERRORS = "rocksdb.background-errors"; +const std::string PROPERTY_TYPE_ROCKSDB_BACKGROUND_ERRORS = "rocksdb.background-errors"; const std::string ALL_DB = "all"; const std::string STRINGS_DB = "strings"; @@ -56,7 +56,6 @@ class RedisZSets; class HyperLogLog; enum class OptionType; - template class LRUCache; @@ -67,19 +66,14 @@ struct StorageOptions { bool share_block_cache = false; size_t statistics_max_size = 0; size_t small_compaction_threshold = 5000; - Status ResetOptions(const OptionType& option_type, - const std::unordered_map& options_map); + Status ResetOptions(const OptionType& option_type, const std::unordered_map& options_map); }; struct KeyValue { std::string key; std::string value; - bool operator == (const KeyValue& kv) const { - return (kv.key == key && kv.value == value); - } - bool operator < (const KeyValue& kv) const { - return key < kv.key; - } + bool operator==(const KeyValue& kv) const { return (kv.key == key && kv.value == value); } + bool operator<(const KeyValue& kv) const { return key < kv.key; } }; struct KeyInfo { @@ -92,97 +86,54 @@ struct KeyInfo { struct ValueStatus { std::string value; Status status; - bool operator == (const ValueStatus& vs) const { - return (vs.value == value && vs.status == status); - } + bool operator==(const ValueStatus& vs) const { return (vs.value == value && vs.status == status); } }; struct FieldValue { std::string field; std::string value; - bool operator == (const FieldValue& fv) const { - return (fv.field == field && fv.value == value); - } + bool operator==(const FieldValue& fv) const { return (fv.field == field && fv.value == value); } }; struct KeyVersion { std::string key; int32_t version; - bool operator == (const KeyVersion& kv) const { - return (kv.key == key && kv.version == version); - } + bool operator==(const KeyVersion& kv) const { return (kv.key == key && kv.version == version); } }; struct ScoreMember { double score; std::string member; - bool operator == (const ScoreMember& sm) const { - return (sm.score == score && sm.member == member); - } + bool operator==(const ScoreMember& sm) const { return (sm.score == score && sm.member == member); } }; -enum BeforeOrAfter { - Before, - After -}; +enum BeforeOrAfter { Before, After }; -enum DataType { - kAll, - kStrings, - kHashes, - kLists, - kZSets, - kSets -}; +enum DataType { kAll, kStrings, kHashes, kLists, kZSets, kSets }; -const char DataTypeTag[] = { - 'a', 'k', 'h', 'l', 'z','s' -}; +const char DataTypeTag[] = {'a', 'k', 'h', 'l', 'z', 's'}; enum class OptionType { kDB, kColumnFamily, }; -enum ColumnFamilyType { - kMeta, - kData, - kMetaAndData -}; +enum ColumnFamilyType { kMeta, kData, kMetaAndData }; -enum AGGREGATE { - SUM, - MIN, - MAX -}; +enum AGGREGATE { SUM, MIN, MAX }; -enum BitOpType { - kBitOpAnd = 1, - kBitOpOr, - kBitOpXor, - kBitOpNot, - kBitOpDefault -}; +enum BitOpType { kBitOpAnd = 1, kBitOpOr, kBitOpXor, kBitOpNot, kBitOpDefault }; -enum Operation { - kNone = 0, - kCleanAll, - kCleanStrings, - kCleanHashes, - kCleanZSets, - kCleanSets, - kCleanLists, - kCompactKey -}; +enum Operation { kNone = 0, kCleanAll, kCleanStrings, kCleanHashes, kCleanZSets, kCleanSets, kCleanLists, kCompactKey }; struct BGTask { DataType type; Operation operation; std::string argv; - BGTask(const DataType& _type = DataType::kAll, - const Operation& _opeation = Operation::kNone, - const std::string& _argv = "") : type(_type), operation(_opeation), argv(_argv) {} + BGTask(const DataType& _type = DataType::kAll, const Operation& _opeation = Operation::kNone, + const std::string& _argv = "") + : type(_type), operation(_opeation), argv(_argv) {} }; class Storage { @@ -226,8 +177,7 @@ class Storage { // Returns the values of all specified keys. For every key // that does not hold a string value or does not exist, the // special value nil is returned - Status MGet(const std::vector& keys, - std::vector* vss); + Status MGet(const std::vector& keys, std::vector* vss); // Set key to hold string value if key does not exist // return 1 if the key was set @@ -253,13 +203,11 @@ class Storage { // Set key to hold string value if key does not exist // return the length of the string after it was modified by the command - Status Setrange(const Slice& key, int64_t start_offset, - const Slice& value, int32_t* ret); + Status Setrange(const Slice& key, int64_t start_offset, const Slice& value, int32_t* ret); // Returns the substring of the string value stored at key, // determined by the offsets start and end (both are inclusive) - Status Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, - std::string* ret); + Status Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, std::string* ret); // If key already exists and is a string, this command appends the value at // the end of the string @@ -269,24 +217,19 @@ class Storage { // Count the number of set bits (population counting) in a string. // return the number of bits set to 1 // note: if need to specified offset, set have_range to true - Status BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, - int32_t* ret, bool have_offset); + Status BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, int32_t* ret, bool have_offset); // Perform a bitwise operation between multiple keys // and store the result in the destination key - Status BitOp(BitOpType op, const std::string& dest_key, - const std::vector& src_keys, int64_t* ret); + Status BitOp(BitOpType op, const std::string& dest_key, const std::vector& src_keys, int64_t* ret); // Return the position of the first bit set to 1 or 0 in a string // BitPos key 0 Status BitPos(const Slice& key, int32_t bit, int64_t* ret); // BitPos key 0 [start] - Status BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t* ret); + Status BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t* ret); // BitPos key 0 [start] [end] - Status BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t end_offset, - int64_t* ret); + Status BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t end_offset, int64_t* ret); // Decrements the number stored at key by decrement // return the value of key after the decrement @@ -314,14 +257,12 @@ class Storage { // timestamp in the past will delete the key immediately. Status PKSetexAt(const Slice& key, const Slice& value, int32_t timestamp); - // Hashes Commands // Sets field in the hash stored at key to value. If key does not exist, a new // key holding a hash is created. If field already exists in the hash, it is // overwritten. - Status HSet(const Slice& key, const Slice& field, const Slice& value, - int32_t* res); + Status HSet(const Slice& key, const Slice& field, const Slice& value, int32_t* res); // Returns the value associated with field in the hash stored at key. // the value associated with field, or nil when field is not present in the @@ -331,37 +272,30 @@ class Storage { // Sets the specified fields to their respective values in the hash stored at // key. This command overwrites any specified fields already existing in the // hash. If key does not exist, a new key holding a hash is created. - Status HMSet(const Slice& key, - const std::vector& fvs); + Status HMSet(const Slice& key, const std::vector& fvs); // Returns the values associated with the specified fields in the hash stored // at key. // For every field that does not exist in the hash, a nil value is returned. // Because a non-existing keys are treated as empty hashes, running HMGET // against a non-existing key will return a list of nil values. - Status HMGet(const Slice& key, - const std::vector& fields, - std::vector* vss); + Status HMGet(const Slice& key, const std::vector& fields, std::vector* vss); // Returns all fields and values of the hash stored at key. In the returned // value, every field name is followed by its value, so the length of the // reply is twice the size of the hash. - Status HGetall(const Slice& key, - std::vector* fvs); + Status HGetall(const Slice& key, std::vector* fvs); // Returns all field names in the hash stored at key. - Status HKeys(const Slice& key, - std::vector* fields); + Status HKeys(const Slice& key, std::vector* fields); // Returns all values in the hash stored at key. - Status HVals(const Slice& key, - std::vector* values); + Status HVals(const Slice& key, std::vector* values); // Sets field in the hash stored at key to value, only if field does not yet // exist. If key does not exist, a new key holding a hash is created. If field // already exists, this operation has no effect. - Status HSetnx(const Slice& key, const Slice& field, const Slice& value, - int32_t* ret); + Status HSetnx(const Slice& key, const Slice& field, const Slice& value, int32_t* ret); // Returns the number of fields contained in the hash stored at key. // Return 0 when key does not exist. @@ -381,8 +315,7 @@ class Storage { // increment. If key does not exist, a new key holding a hash is created. If // field does not exist the value is set to 0 before the operation is // performed. - Status HIncrby(const Slice& key, const Slice& field, int64_t value, - int64_t* ret); + Status HIncrby(const Slice& key, const Slice& field, int64_t value, int64_t* ret); // Increment the specified field of a hash stored at key, and representing a // floating point number, by the specified increment. If the increment value @@ -394,47 +327,39 @@ class Storage { // The field contains a value of the wrong type (not a string). // The current field content or the specified increment are not parsable as a // double precision floating point number. - Status HIncrbyfloat(const Slice& key, const Slice& field, - const Slice& by, std::string* new_value); + Status HIncrbyfloat(const Slice& key, const Slice& field, const Slice& by, std::string* new_value); // Removes the specified fields from the hash stored at key. Specified fields // that do not exist within this hash are ignored. If key does not exist, it // is treated as an empty hash and this command returns 0. - Status HDel(const Slice& key, const std::vector& fields, - int32_t* ret); + Status HDel(const Slice& key, const std::vector& fields, int32_t* ret); // See SCAN for HSCAN documentation. - Status HScan(const Slice& key, int64_t cursor, const std::string& pattern, - int64_t count, std::vector* field_values, int64_t* next_cursor); + Status HScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* field_values, int64_t* next_cursor); // Iterate over a Hash table of fields // return next_field that the user need to use as the start_field argument // in the next call - Status HScanx(const Slice& key, const std::string start_field, const std::string& pattern, - int64_t count, std::vector* field_values, std::string* next_field); + Status HScanx(const Slice& key, const std::string start_field, const std::string& pattern, int64_t count, + std::vector* field_values, std::string* next_field); // Iterate over a Hash table of fields by specified range // return next_field that the user need to use as the start_field argument // in the next call - Status PKHScanRange(const Slice& key, - const Slice& field_start, const std::string& field_end, - const Slice& pattern, int32_t limit, - std::vector* field_values, std::string* next_field); + Status PKHScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, const Slice& pattern, + int32_t limit, std::vector* field_values, std::string* next_field); // part from the reversed ordering, PKHRSCANRANGE is similar to PKHScanRange - Status PKHRScanRange(const Slice& key, - const Slice& field_start, const std::string& field_end, - const Slice& pattern, int32_t limit, - std::vector* field_values, std::string* next_field); - + Status PKHRScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, const Slice& pattern, + int32_t limit, std::vector* field_values, std::string* next_field); // Sets Commands // Add the specified members to the set stored at key. Specified members that // are already a member of this set are ignored. If key does not exist, a new // set is created before adding the specified members. - Status SAdd(const Slice& key, const std::vector& members, - int32_t* ret); + Status SAdd(const Slice& key, const std::vector& members, int32_t* ret); // Returns the set cardinality (number of elements) of the set stored at key. Status SCard(const Slice& key, int32_t* ret); @@ -447,8 +372,7 @@ class Storage { // key2 = {c} // key3 = {a, c, e} // SDIFF key1 key2 key3 = {b, d} - Status SDiff(const std::vector& keys, - std::vector* members); + Status SDiff(const std::vector& keys, std::vector* members); // This command is equal to SDIFF, but instead of returning the resulting set, // it is stored in destination. @@ -461,9 +385,7 @@ class Storage { // key3 = {a, c, e} // SDIFFSTORE destination key1 key2 key3 // destination = {b, d} - Status SDiffstore(const Slice& destination, - const std::vector& keys, - int32_t* ret); + Status SDiffstore(const Slice& destination, const std::vector& keys, int32_t* ret); // Returns the members of the set resulting from the intersection of all the // given sets. @@ -473,8 +395,7 @@ class Storage { // key2 = {c} // key3 = {a, c, e} // SINTER key1 key2 key3 = {c} - Status SInter(const std::vector& keys, - std::vector* members); + Status SInter(const std::vector& keys, std::vector* members); // This command is equal to SINTER, but instead of returning the resulting // set, it is stored in destination. @@ -487,13 +408,10 @@ class Storage { // key3 = {a, c, e} // SINTERSTORE destination key1 key2 key3 // destination = {a, c} - Status SInterstore(const Slice& destination, - const std::vector& keys, - int32_t* ret); + Status SInterstore(const Slice& destination, const std::vector& keys, int32_t* ret); // Returns if member is a member of the set stored at key. - Status SIsmember(const Slice& key, const Slice& member, - int32_t* ret); + Status SIsmember(const Slice& key, const Slice& member, int32_t* ret); // Returns all the members of the set value stored at key. // This has the same effect as running SINTER with one argument key. @@ -502,8 +420,7 @@ class Storage { // Remove the specified members from the set stored at key. Specified members // that are not a member of this set are ignored. If key does not exist, it is // treated as an empty set and this command returns 0. - Status SRem(const Slice& key, const std::vector& members, - int32_t* ret); + Status SRem(const Slice& key, const std::vector& members, int32_t* ret); // Removes and returns one random elements from the set value store at key. Status SPop(const Slice& key, std::string* member); @@ -515,8 +432,7 @@ class Storage { // behavior changes and the command is allowed to return the same element // multiple times. In this case the number of returned elements is the // absolute value of the specified count - Status SRandmember(const Slice& key, int32_t count, - std::vector* members); + Status SRandmember(const Slice& key, int32_t count, std::vector* members); // Move member from the set at source to the set at destination. This // operation is atomic. In every given moment the element will appear to be a @@ -527,8 +443,7 @@ class Storage { // removed from the source set and added to the destination set. When the // specified element already exists in the destination set, it is only removed // from the source set. - Status SMove(const Slice& source, const Slice& destination, - const Slice& member, int32_t* ret); + Status SMove(const Slice& source, const Slice& destination, const Slice& member, int32_t* ret); // Returns the members of the set resulting from the union of all the given // sets. @@ -538,8 +453,7 @@ class Storage { // key2 = {c} // key3 = {a, c, e} // SUNION key1 key2 key3 = {a, b, c, d, e} - Status SUnion(const std::vector& keys, - std::vector* members); + Status SUnion(const std::vector& keys, std::vector* members); // This command is equal to SUNION, but instead of returning the resulting // set, it is stored in destination. @@ -551,33 +465,28 @@ class Storage { // key3 = {c, d, e} // SUNIONSTORE destination key1 key2 key3 // destination = {a, b, c, d, e} - Status SUnionstore(const Slice& destination, - const std::vector& keys, - int32_t* ret); + Status SUnionstore(const Slice& destination, const std::vector& keys, int32_t* ret); // See SCAN for SSCAN documentation. - Status SScan(const Slice& key, int64_t cursor, const std::string& pattern, - int64_t count, std::vector* members, int64_t* next_cursor); + Status SScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* members, int64_t* next_cursor); // Lists Commands // Insert all the specified values at the head of the list stored at key. If // key does not exist, it is created as empty list before performing the push // operations. - Status LPush(const Slice& key, const std::vector& values, - uint64_t* ret); + Status LPush(const Slice& key, const std::vector& values, uint64_t* ret); // Insert all the specified values at the tail of the list stored at key. If // key does not exist, it is created as empty list before performing the push // operation. - Status RPush(const Slice& key, const std::vector& values, - uint64_t* ret); + Status RPush(const Slice& key, const std::vector& values, uint64_t* ret); // Returns the specified elements of the list stored at key. The offsets start // and stop are zero-based indexes, with 0 being the first element of the list // (the head of the list), 1 being the next element and so on. - Status LRange(const Slice& key, int64_t start, int64_t stop, - std::vector* ret); + Status LRange(const Slice& key, int64_t start, int64_t stop, std::vector* ret); // Removes the first count occurrences of elements equal to value from the // list stored at key. The count argument influences the operation in the @@ -607,8 +516,8 @@ class Storage { // When key does not exist, it is considered an empty list and no operation is // performed. // An error is returned when key exists but does not hold a list value. - Status LInsert(const Slice& key, const BeforeOrAfter& before_or_after, - const std::string& pivot, const std::string& value, int64_t* ret); + Status LInsert(const Slice& key, const BeforeOrAfter& before_or_after, const std::string& pivot, + const std::string& value, int64_t* ret); // Inserts value at the head of the list stored at key, only if key already // exists and holds a list. In contrary to LPUSH, no operation will be @@ -653,29 +562,23 @@ class Storage { // equivalent to removing the last element from the list and pushing it as // first element of the list, so it can be considered as a list rotation // command. - Status RPoplpush(const Slice& source, - const Slice& destination, - std::string* element); + Status RPoplpush(const Slice& source, const Slice& destination, std::string* element); // Zsets Commands - //Pop the maximum count score_members which have greater score in the sorted set. - //And return the result in the score_members,If the total number of the sorted - //set less than count, it will pop out the total number of sorted set. If two - //ScoreMember's score were the same, the lexicographic predominant elements will - //be pop out. - Status ZPopMax(const Slice& key, - const int64_t count, - std::vector* score_members); - - //Pop the minimum count score_members which have less score in the sorted set. - //And return the result in the score_members,If the total number of the sorted - //set less than count, it will pop out the total number of sorted set. If two - //ScoreMember's score were the same, the lexicographic predominant elements will - //not be pop out. - Status ZPopMin(const Slice& key, - const int64_t count, - std::vector* score_members); + // Pop the maximum count score_members which have greater score in the sorted set. + // And return the result in the score_members,If the total number of the sorted + // set less than count, it will pop out the total number of sorted set. If two + // ScoreMember's score were the same, the lexicographic predominant elements will + // be pop out. + Status ZPopMax(const Slice& key, const int64_t count, std::vector* score_members); + + // Pop the minimum count score_members which have less score in the sorted set. + // And return the result in the score_members,If the total number of the sorted + // set less than count, it will pop out the total number of sorted set. If two + // ScoreMember's score were the same, the lexicographic predominant elements will + // not be pop out. + Status ZPopMin(const Slice& key, const int64_t count, std::vector* score_members); // Adds all the specified members with the specified scores to the sorted set // stored at key. It is possible to specify multiple score / member pairs. If @@ -688,15 +591,12 @@ class Storage { // does not hold a sorted set, an error is returned. // The score values should be the string representation of a double precision // floating point number. +inf and -inf values are valid values as well. - Status ZAdd(const Slice& key, - const std::vector& score_members, - int32_t* ret); + Status ZAdd(const Slice& key, const std::vector& score_members, int32_t* ret); // Returns the sorted set cardinality (number of elements) of the sorted set // stored at key. Status ZCard(const Slice& key, int32_t* ret); - // Returns the number of elements in the sorted set at key with a score // between min and max. // @@ -706,12 +606,7 @@ class Storage { // Note: the command has a complexity of just O(log(N)) because it uses // elements ranks (see ZRANK) to get an idea of the range. Because of this // there is no need to do a work proportional to the size of the range. - Status ZCount(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int32_t* ret); + Status ZCount(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret); // Increments the score of member in the sorted set stored at key by // increment. If member does not exist in the sorted set, it is added with @@ -724,10 +619,7 @@ class Storage { // The score value should be the string representation of a numeric value, and // accepts double precision floating point numbers. It is possible to provide // a negative value to decrement the score. - Status ZIncrby(const Slice& key, - const Slice& member, - double increment, - double* ret); + Status ZIncrby(const Slice& key, const Slice& member, double increment, double* ret); // Returns the specified range of elements in the sorted set stored at key. // The elements are considered to be ordered from the lowest to the highest @@ -754,10 +646,7 @@ class Storage { // value1,score1,...,valueN,scoreN instead of value1,...,valueN. Client // libraries are free to return a more appropriate data type (suggestion: an // array with (value, score) arrays/tuples). - Status ZRange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members); + Status ZRange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members); // Returns all the elements in the sorted set at key with a score between min // and max (including elements with score equal to min or max). The elements @@ -795,11 +684,7 @@ class Storage { // Return value // Array reply: list of elements in the specified score range (optionally with // their scores). - Status ZRangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, + Status ZRangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, std::vector* score_members); // Returns all the elements in the sorted set at key with a score between min @@ -838,14 +723,8 @@ class Storage { // Return value // Array reply: list of elements in the specified score range (optionally with // their scores). - Status ZRangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members); + Status ZRangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int64_t count, + int64_t offset, std::vector* score_members); // Returns the rank of member in the sorted set stored at key, with the scores // ordered from low to high. The rank (or index) is 0-based, which means that @@ -853,17 +732,13 @@ class Storage { // // Use ZREVRANK to get the rank of an element with the scores ordered from // high to low. - Status ZRank(const Slice& key, - const Slice& member, - int32_t* rank); + Status ZRank(const Slice& key, const Slice& member, int32_t* rank); // Removes the specified members from the sorted set stored at key. Non // existing members are ignored. // // An error is returned when key exists and does not hold a sorted set. - Status ZRem(const Slice& key, - std::vector members, - int32_t* ret); + Status ZRem(const Slice& key, std::vector members, int32_t* ret); // Removes all elements in the sorted set stored at key with rank between // start and stop. Both start and stop are 0 -based indexes with 0 being the @@ -871,20 +746,11 @@ class Storage { // they indicate offsets starting at the element with the highest score. For // example: -1 is the element with the highest score, -2 the element with the // second highest score and so forth. - Status ZRemrangebyrank(const Slice& key, - int32_t start, - int32_t stop, - int32_t* ret); - + Status ZRemrangebyrank(const Slice& key, int32_t start, int32_t stop, int32_t* ret); // Removes all elements in the sorted set stored at key with a score between // min and max (inclusive). - Status ZRemrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int32_t* ret); + Status ZRemrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret); // Returns the specified range of elements in the sorted set stored at key. // The elements are considered to be ordered from the highest to the lowest @@ -892,10 +758,7 @@ class Storage { // score. // // Apart from the reversed ordering, ZREVRANGE is similar to ZRANGE. - Status ZRevrange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members); + Status ZRevrange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members); // Returns all the elements in the sorted set at key with a score between max // and min (including elements with score equal to max or min). In contrary to @@ -907,11 +770,7 @@ class Storage { // // Apart from the reversed ordering, ZREVRANGEBYSCORE is similar to // ZRANGEBYSCORE. - Status ZRevrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, + Status ZRevrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, std::vector* score_members); // Returns all the elements in the sorted set at key with a score between max @@ -924,21 +783,13 @@ class Storage { // // Apart from the reversed ordering, ZREVRANGEBYSCORE is similar to // ZRANGEBYSCORE. - Status ZRevrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members); + Status ZRevrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int64_t count, + int64_t offset, std::vector* score_members); // Returns the rank of member in the sorted set stored at key, with the scores // ordered from high to low. The rank (or index) is 0-based, which means that // the member with the highest score has rank 0. - Status ZRevrank(const Slice& key, - const Slice& member, - int32_t* rank); + Status ZRevrank(const Slice& key, const Slice& member, int32_t* rank); // Returns the score of member in the sorted set at key. // @@ -967,11 +818,8 @@ class Storage { // maximum score of an element across the inputs where it exists. // // If destination already exists, it is overwritten. - Status ZUnionstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret); + Status ZUnionstore(const Slice& destination, const std::vector& keys, const std::vector& weights, + const AGGREGATE agg, int32_t* ret); // Computes the intersection of numkeys sorted sets given by the specified // keys, and stores the result in destination. It is mandatory to provide the @@ -987,11 +835,8 @@ class Storage { // For a description of the WEIGHTS and AGGREGATE options, see ZUNIONSTORE. // // If destination already exists, it is overwritten. - Status ZInterstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret); + Status ZInterstore(const Slice& destination, const std::vector& keys, const std::vector& weights, + const AGGREGATE agg, int32_t* ret); // When all the elements in a sorted set are inserted with the same score, in // order to force lexicographical ordering, this command returns all the @@ -1009,11 +854,7 @@ class Storage { // if offset is large, the sorted set needs to be traversed for offset // elements before getting to the elements to return, which can add up to O(N) // time complexity. - Status ZRangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, + Status ZRangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, std::vector* members); // When all the elements in a sorted set are inserted with the same score, in @@ -1026,11 +867,7 @@ class Storage { // Note: the command has a complexity of just O(log(N)) because it uses // elements ranks (see ZRANK) to get an idea of the range. Because of this // there is no need to do a work proportional to the size of the range. - Status ZLexcount(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, + Status ZLexcount(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, int32_t* ret); // When all the elements in a sorted set are inserted with the same score, in @@ -1041,16 +878,12 @@ class Storage { // The meaning of min and max are the same of the ZRANGEBYLEX command. // Similarly, this command actually returns the same elements that ZRANGEBYLEX // would return if called with the same min and max arguments. - Status ZRemrangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, + Status ZRemrangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, int32_t* ret); // See SCAN for ZSCAN documentation. - Status ZScan(const Slice& key, int64_t cursor, const std::string& pattern, - int64_t count, std::vector* score_members, int64_t* next_cursor); + Status ZScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* score_members, int64_t* next_cursor); // Keys Commands @@ -1061,74 +894,55 @@ class Storage { // Set a timeout on key // return -1 operation exception errors happen in database // return >=0 success - int32_t Expire(const Slice& key, int32_t ttl, - std::map* type_status); + int32_t Expire(const Slice& key, int32_t ttl, std::map* type_status); // Removes the specified keys // return -1 operation exception errors happen in database // return >=0 the number of keys that were removed - int64_t Del(const std::vector& keys, - std::map* type_status); + int64_t Del(const std::vector& keys, std::map* type_status); // Removes the specified keys of the specified type // return -1 operation exception errors happen in database // return >= 0 the number of keys that were removed - int64_t DelByType(const std::vector& keys, - const DataType& type); + int64_t DelByType(const std::vector& keys, const DataType& type); // Iterate over a collection of elements // return an updated cursor that the user need to use as the cursor argument // in the next call - int64_t Scan(const DataType& dtype, int64_t cursor, - const std::string& pattern, int64_t count, + int64_t Scan(const DataType& dtype, int64_t cursor, const std::string& pattern, int64_t count, std::vector* keys); // Iterate over a collection of elements, obtaining the item which timeout // conforms to the inequality (min_ttl < item_ttl < max_ttl) // return an updated cursor that the user need to use as the cursor argument // in the next call - int64_t PKExpireScan(const DataType& dtype, int64_t cursor, - int32_t min_ttl, int32_t max_ttl, - int64_t count, std::vector* keys); + int64_t PKExpireScan(const DataType& dtype, int64_t cursor, int32_t min_ttl, int32_t max_ttl, int64_t count, + std::vector* keys); // Iterate over a collection of elements by specified range // return a next_key that the user need to use as the key_start argument // in the next call - Status PKScanRange(const DataType& data_type, - const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, - std::vector* keys, std::vector* kvs, - std::string* next_key); + Status PKScanRange(const DataType& data_type, const Slice& key_start, const Slice& key_end, const Slice& pattern, + int32_t limit, std::vector* keys, std::vector* kvs, std::string* next_key); // part from the reversed ordering, PKRSCANRANGE is similar to PKScanRange - Status PKRScanRange(const DataType& data_type, - const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, - std::vector* keys, std::vector* kvs, - std::string* next_key); + Status PKRScanRange(const DataType& data_type, const Slice& key_start, const Slice& key_end, const Slice& pattern, + int32_t limit, std::vector* keys, std::vector* kvs, std::string* next_key); // Traverses the database of the specified type, removing the Key that matches // the pattern - Status PKPatternMatchDel(const DataType& data_type, - const std::string& pattern, - int32_t* ret); - + Status PKPatternMatchDel(const DataType& data_type, const std::string& pattern, int32_t* ret); // Iterate over a collection of elements // return next_key that the user need to use as the start_key argument // in the next call - Status Scanx(const DataType& data_type, - const std::string& start_key, - const std::string& pattern, - int64_t count, - std::vector* keys, - std::string* next_key); + Status Scanx(const DataType& data_type, const std::string& start_key, const std::string& pattern, int64_t count, + std::vector* keys, std::string* next_key); // Returns if key exists. // return -1 operation exception errors happen in database // return >=0 the number of keys existing - int64_t Exists(const std::vector& keys, - std::map* type_status); + int64_t Exists(const std::vector& keys, std::map* type_status); // EXPIREAT has the same effect and semantic as EXPIRE, but instead of // specifying the number of seconds representing the TTL (time to live), it @@ -1137,8 +951,7 @@ class Storage { // return -1 operation exception errors happen in database // return 0 if key does not exist // return >=1 if the timueout was set - int32_t Expireat(const Slice& key, int32_t timestamp, - std::map* type_status); + int32_t Expireat(const Slice& key, int32_t timestamp, std::map* type_status); // Remove the existing timeout on key, turning the key from volatile (a key // with an expire set) to persistent (a key that will never expire as no @@ -1146,24 +959,19 @@ class Storage { // return -1 operation exception errors happen in database // return 0 if key does not exist or does not have an associated timeout // return >=1 if the timueout was set - int32_t Persist(const Slice& key, - std::map* type_status); + int32_t Persist(const Slice& key, std::map* type_status); // Returns the remaining time to live of a key that has a timeout. // return -3 operation exception errors happen in database // return -2 if the key does not exist // return -1 if the key exists but has not associated expire // return > 0 TTL in seconds - std::map TTL(const Slice& key, - std::map* type_status); + std::map TTL(const Slice& key, std::map* type_status); // Reutrns the data type of the key Status Type(const std::string& key, std::string* type); - Status Keys(const DataType& data_type, - const std::string& pattern, - std::vector* keys); - + Status Keys(const DataType& data_type, const std::string& pattern, std::vector* keys); // Iterate through all the data in the database. void ScanDatabase(const DataType& type); @@ -1175,8 +983,7 @@ class Storage { }; // Adds all the element arguments to the HyperLogLog data structure stored // at the variable name specified as first argument. - Status PfAdd(const Slice& key, const std::vector& values, - bool* update); + Status PfAdd(const Slice& key, const std::vector& values, bool* update); // When called with a single key, returns the approximated cardinality // computed by the HyperLogLog data structure stored at the specified @@ -1202,8 +1009,7 @@ class Storage { std::string GetCurrentTaskType(); Status GetUsage(const std::string& property, uint64_t* const result); - Status GetUsage(const std::string& property, - std::map* const type_result); + Status GetUsage(const std::string& property, std::map* const type_result); uint64_t GetProperty(const std::string& db_type, const std::string& property); Status GetKeyNum(std::vector* key_infos); @@ -1235,7 +1041,6 @@ class Storage { // For scan keys in data base std::atomic scan_keynum_exit_; - }; } // namespace storage diff --git a/src/storage/include/storage/util.h b/src/storage/include/storage/util.h index fe91f6bbd5..4b13a5be9c 100644 --- a/src/storage/include/storage/util.h +++ b/src/storage/include/storage/util.h @@ -6,31 +6,30 @@ #ifndef SRC_UTIL_H_ #define SRC_UTIL_H_ -#include -#include -#include #include #include #include +#include +#include +#include namespace storage { - uint32_t Digits10(uint64_t v); - int Int64ToStr(char* dst, size_t dstlen, int64_t svalue); - int StrToInt64(const char *s, size_t slen, int64_t *value); - int StringMatch(const char *pattern, int pattern_len, const char *string, - int string_len, int nocase); - int StrToLongDouble(const char* s, size_t slen, long double* ldval); - int LongDoubleToStr(long double ldval, std::string* value); - int do_mkdir(const char *path, mode_t mode); - int mkpath(const char *path, mode_t mode); - int delete_dir(const char* dirname); - int is_dir(const char* filename); - int CalculateMetaStartAndEndKey(const std::string& key, std::string* meta_start_key, std::string* meta_end_key); - int CalculateDataStartAndEndKey(const std::string& key, std::string* data_start_key, std::string* data_end_key); - bool isTailWildcard(const std::string& pattern); - void GetFilepath(const char *path, const char *filename, char *filepath); - bool DeleteFiles(const char* path); -} +uint32_t Digits10(uint64_t v); +int Int64ToStr(char* dst, size_t dstlen, int64_t svalue); +int StrToInt64(const char* s, size_t slen, int64_t* value); +int StringMatch(const char* pattern, int pattern_len, const char* string, int string_len, int nocase); +int StrToLongDouble(const char* s, size_t slen, long double* ldval); +int LongDoubleToStr(long double ldval, std::string* value); +int do_mkdir(const char* path, mode_t mode); +int mkpath(const char* path, mode_t mode); +int delete_dir(const char* dirname); +int is_dir(const char* filename); +int CalculateMetaStartAndEndKey(const std::string& key, std::string* meta_start_key, std::string* meta_end_key); +int CalculateDataStartAndEndKey(const std::string& key, std::string* data_start_key, std::string* data_end_key); +bool isTailWildcard(const std::string& pattern); +void GetFilepath(const char* path, const char* filename, char* filepath); +bool DeleteFiles(const char* path); +} // namespace storage #endif // SRC_UTIL_H_ diff --git a/src/storage/src/backupable.cc b/src/storage/src/backupable.cc index d89c869a90..f51588b958 100644 --- a/src/storage/src/backupable.cc +++ b/src/storage/src/backupable.cc @@ -21,8 +21,7 @@ BackupEngine::~BackupEngine() { engines_.clear(); } -Status BackupEngine::NewCheckpoint(rocksdb::DB* rocksdb_db, - const std::string& type) { +Status BackupEngine::NewCheckpoint(rocksdb::DB* rocksdb_db, const std::string& type) { rocksdb::DBCheckpoint* checkpoint; Status s = rocksdb::DBCheckpoint::Create(rocksdb_db, &checkpoint); if (!s.ok()) { @@ -33,8 +32,7 @@ Status BackupEngine::NewCheckpoint(rocksdb::DB* rocksdb_db, return s; } -Status BackupEngine::Open(storage::Storage *storage, - BackupEngine** backup_engine_ptr) { +Status BackupEngine::Open(storage::Storage* storage, BackupEngine** backup_engine_ptr) { *backup_engine_ptr = new BackupEngine(); if (!*backup_engine_ptr) { return Status::Corruption("New BackupEngine failed!"); @@ -42,7 +40,7 @@ Status BackupEngine::Open(storage::Storage *storage, // Create BackupEngine for each db type rocksdb::Status s; - rocksdb::DB *rocksdb_db; + rocksdb::DB* rocksdb_db; std::string types[] = {STRINGS_DB, HASHES_DB, LISTS_DB, ZSETS_DB, SETS_DB}; for (const auto& type : types) { if ((rocksdb_db = storage->GetDBByType(type)) == NULL) { @@ -66,9 +64,8 @@ Status BackupEngine::SetBackupContent() { for (const auto& engine : engines_) { // Get backup content BackupContent bcontent; - s = engine.second->GetCheckpointFiles(bcontent.live_files, - bcontent.live_wal_files, - bcontent.manifest_file_size, bcontent.sequence_number); + s = engine.second->GetCheckpointFiles(bcontent.live_files, bcontent.live_wal_files, bcontent.manifest_file_size, + bcontent.sequence_number); if (!s.ok()) { // log_warn("get backup files faild for type: %s", engine.first.c_str()); return s; @@ -78,22 +75,15 @@ Status BackupEngine::SetBackupContent() { return s; } -Status BackupEngine::CreateNewBackupSpecify(const std::string &backup_dir, - const std::string &type) { - std::map::iterator it_engine = - engines_.find(type); - std::map::iterator it_content = - backup_content_.find(type); +Status BackupEngine::CreateNewBackupSpecify(const std::string& backup_dir, const std::string& type) { + std::map::iterator it_engine = engines_.find(type); + std::map::iterator it_content = backup_content_.find(type); std::string dir = GetSaveDirByType(backup_dir, type); delete_dir(dir.c_str()); - if (it_content != backup_content_.end() && - it_engine != engines_.end()) { + if (it_content != backup_content_.end() && it_engine != engines_.end()) { Status s = it_engine->second->CreateCheckpointWithFiles( - dir, - it_content->second.live_files, - it_content->second.live_wal_files, - it_content->second.manifest_file_size, + dir, it_content->second.live_files, it_content->second.live_wal_files, it_content->second.manifest_file_size, it_content->second.sequence_number); if (!s.ok()) { // log_warn("backup engine create new failed, type: %s, error %s", @@ -108,11 +98,10 @@ Status BackupEngine::CreateNewBackupSpecify(const std::string &backup_dir, return Status::OK(); } -void* ThreadFuncSaveSpecify(void *arg) { +void* ThreadFuncSaveSpecify(void* arg) { BackupSaveArgs* arg_ptr = static_cast(arg); BackupEngine* p = static_cast(arg_ptr->p_engine); - arg_ptr->res = p->CreateNewBackupSpecify(arg_ptr->backup_dir, - arg_ptr->key_type); + arg_ptr->res = p->CreateNewBackupSpecify(arg_ptr->backup_dir, arg_ptr->key_type); pthread_exit(&(arg_ptr->res)); } @@ -120,7 +109,7 @@ Status BackupEngine::WaitBackupPthread() { int ret; Status s = Status::OK(); for (auto& pthread : backup_pthread_ts_) { - void *res; + void* res; if ((ret = pthread_join(pthread.second, &res)) != 0) { // log_warn("pthread_join failed with backup thread for key_type: // %s, error %d", pthread.first.c_str(), ret); @@ -137,21 +126,18 @@ Status BackupEngine::WaitBackupPthread() { return s; } - -Status BackupEngine::CreateNewBackup(const std::string &dir) { +Status BackupEngine::CreateNewBackup(const std::string& dir) { Status s = Status::OK(); std::vector args; for (const auto& engine : engines_) { pthread_t tid; - BackupSaveArgs *arg = new BackupSaveArgs( - reinterpret_cast(this), dir, engine.first); + BackupSaveArgs* arg = new BackupSaveArgs(reinterpret_cast(this), dir, engine.first); args.push_back(arg); if (pthread_create(&tid, NULL, &ThreadFuncSaveSpecify, arg) != 0) { s = Status::Corruption("pthead_create failed."); break; } - if (!(backup_pthread_ts_.insert( - std::make_pair(engine.first, tid)).second)) { + if (!(backup_pthread_ts_.insert(std::make_pair(engine.first, tid)).second)) { // log_warn("thread open dupilicated, type: %s", engine.first.c_str()); backup_pthread_ts_[engine.first] = tid; } diff --git a/src/storage/src/base_data_key_format.h b/src/storage/src/base_data_key_format.h index cdf7b9d657..423e379b10 100644 --- a/src/storage/src/base_data_key_format.h +++ b/src/storage/src/base_data_key_format.h @@ -6,11 +6,13 @@ #ifndef SRC_BASE_DATA_KEY_FORMAT_H_ #define SRC_BASE_DATA_KEY_FORMAT_H_ +#include "pstd/include/pstd_coding.h" + namespace storage { class BaseDataKey { public: - BaseDataKey(const Slice& key, int32_t version, const Slice& data) : - start_(nullptr), key_(key), version_(version), data_(data) {} + BaseDataKey(const Slice& key, int32_t version, const Slice& data) + : start_(nullptr), key_(key), version_(version), data_(data) {} ~BaseDataKey() { if (start_ != space_) { @@ -34,11 +36,11 @@ class BaseDataKey { } start_ = dst; - EncodeFixed32(dst, key_.size()); + pstd::EncodeFixed32(dst, key_.size()); dst += sizeof(int32_t); memcpy(dst, key_.data(), key_.size()); dst += key_.size(); - EncodeFixed32(dst, version_); + pstd::EncodeFixed32(dst, version_); dst += sizeof(int32_t); memcpy(dst, data_.data(), data_.size()); return Slice(start_, needed); @@ -56,39 +58,33 @@ class ParsedBaseDataKey { public: explicit ParsedBaseDataKey(const std::string* key) { const char* ptr = key->data(); - int32_t key_len = DecodeFixed32(ptr); + int32_t key_len = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); key_ = Slice(ptr, key_len); ptr += key_len; - version_ = DecodeFixed32(ptr); + version_ = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); data_ = Slice(ptr, key->size() - key_len - sizeof(int32_t) * 2); } explicit ParsedBaseDataKey(const Slice& key) { const char* ptr = key.data(); - int32_t key_len = DecodeFixed32(ptr); + int32_t key_len = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); key_ = Slice(ptr, key_len); ptr += key_len; - version_ = DecodeFixed32(ptr); + version_ = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); data_ = Slice(ptr, key.size() - key_len - sizeof(int32_t) * 2); } virtual ~ParsedBaseDataKey() = default; - Slice key() { - return key_; - } + Slice key() { return key_; } - int32_t version() { - return version_; - } + int32_t version() { return version_; } - Slice data() { - return data_; - } + Slice data() { return data_; } protected: Slice key_; @@ -98,35 +94,23 @@ class ParsedBaseDataKey { class ParsedHashesDataKey : public ParsedBaseDataKey { public: - explicit ParsedHashesDataKey(const std::string* key) - : ParsedBaseDataKey(key) {} - explicit ParsedHashesDataKey(const Slice& key) - : ParsedBaseDataKey(key) {} - Slice field() { - return data_; - } + explicit ParsedHashesDataKey(const std::string* key) : ParsedBaseDataKey(key) {} + explicit ParsedHashesDataKey(const Slice& key) : ParsedBaseDataKey(key) {} + Slice field() { return data_; } }; class ParsedSetsMemberKey : public ParsedBaseDataKey { public: - explicit ParsedSetsMemberKey(const std::string* key) - : ParsedBaseDataKey(key) {} - explicit ParsedSetsMemberKey(const Slice& key) - : ParsedBaseDataKey(key) {} - Slice member() { - return data_; - } + explicit ParsedSetsMemberKey(const std::string* key) : ParsedBaseDataKey(key) {} + explicit ParsedSetsMemberKey(const Slice& key) : ParsedBaseDataKey(key) {} + Slice member() { return data_; } }; class ParsedZSetsMemberKey : public ParsedBaseDataKey { public: - explicit ParsedZSetsMemberKey(const std::string* key) - : ParsedBaseDataKey(key) {} - explicit ParsedZSetsMemberKey(const Slice& key) - : ParsedBaseDataKey(key) {} - Slice member() { - return data_; - } + explicit ParsedZSetsMemberKey(const std::string* key) : ParsedBaseDataKey(key) {} + explicit ParsedZSetsMemberKey(const Slice& key) : ParsedBaseDataKey(key) {} + Slice member() { return data_; } }; typedef BaseDataKey HashesDataKey; diff --git a/src/storage/src/base_filter.h b/src/storage/src/base_filter.h index c507fb7989..97c7df5891 100644 --- a/src/storage/src/base_filter.h +++ b/src/storage/src/base_filter.h @@ -6,47 +6,41 @@ #ifndef SRC_BASE_FILTER_H_ #define SRC_BASE_FILTER_H_ -#include #include +#include #include -#include "src/debug.h" -#include "src/base_meta_value_format.h" -#include "src/base_data_key_format.h" #include "rocksdb/compaction_filter.h" +#include "src/base_data_key_format.h" +#include "src/base_meta_value_format.h" +#include "src/debug.h" namespace storage { class BaseMetaFilter : public rocksdb::CompactionFilter { public: BaseMetaFilter() = default; - bool Filter(int level, const rocksdb::Slice& key, - const rocksdb::Slice& value, - std::string* new_value, bool* value_changed) const override { + bool Filter(int level, const rocksdb::Slice& key, const rocksdb::Slice& value, std::string* new_value, + bool* value_changed) const override { int64_t unix_time; rocksdb::Env::Default()->GetCurrentTime(&unix_time); int32_t cur_time = static_cast(unix_time); ParsedBaseMetaValue parsed_base_meta_value(value); - Trace("==========================START=========================="); - Trace("[MetaFilter], key: %s, count = %d, timestamp: %d, cur_time: %d, version: %d", - key.ToString().c_str(), - parsed_base_meta_value.count(), - parsed_base_meta_value.timestamp(), - cur_time, + TRACE("==========================START=========================="); + TRACE("[MetaFilter], key: %s, count = %d, timestamp: %d, cur_time: %d, version: %d", key.ToString().c_str(), + parsed_base_meta_value.count(), parsed_base_meta_value.timestamp(), cur_time, parsed_base_meta_value.version()); - if (parsed_base_meta_value.timestamp() != 0 - && parsed_base_meta_value.timestamp() < cur_time - && parsed_base_meta_value.version() < cur_time) { - Trace("Drop[Stale & version < cur_time]"); + if (parsed_base_meta_value.timestamp() != 0 && parsed_base_meta_value.timestamp() < cur_time && + parsed_base_meta_value.version() < cur_time) { + TRACE("Drop[Stale & version < cur_time]"); return true; } - if (parsed_base_meta_value.count() == 0 - && parsed_base_meta_value.version() < cur_time) { - Trace("Drop[Empty & version < cur_time]"); + if (parsed_base_meta_value.count() == 0 && parsed_base_meta_value.version() < cur_time) { + TRACE("Drop[Empty & version < cur_time]"); return true; } - Trace("Reserve"); + TRACE("Reserve"); return false; } @@ -57,34 +51,28 @@ class BaseMetaFilterFactory : public rocksdb::CompactionFilterFactory { public: BaseMetaFilterFactory() = default; std::unique_ptr CreateCompactionFilter( - const rocksdb::CompactionFilter::Context& context) override { + const rocksdb::CompactionFilter::Context& context) override { return std::unique_ptr(new BaseMetaFilter()); } - const char* Name() const override { - return "BaseMetaFilterFactory"; - } + const char* Name() const override { return "BaseMetaFilterFactory"; } }; class BaseDataFilter : public rocksdb::CompactionFilter { public: - BaseDataFilter(rocksdb::DB* db, - std::vector* cf_handles_ptr) : - db_(db), - cf_handles_ptr_(cf_handles_ptr), - cur_key_(""), - meta_not_found_(false), - cur_meta_version_(0), - cur_meta_timestamp_(0) {} - - bool Filter(int level, const Slice& key, - const rocksdb::Slice& value, - std::string* new_value, bool* value_changed) const override { + BaseDataFilter(rocksdb::DB* db, std::vector* cf_handles_ptr) + : db_(db), + cf_handles_ptr_(cf_handles_ptr), + cur_key_(""), + meta_not_found_(false), + cur_meta_version_(0), + cur_meta_timestamp_(0) {} + + bool Filter(int level, const Slice& key, const rocksdb::Slice& value, std::string* new_value, + bool* value_changed) const override { ParsedBaseDataKey parsed_base_data_key(key); - Trace("==========================START=========================="); - Trace("[DataFilter], key: %s, data = %s, version = %d", - parsed_base_data_key.key().ToString().c_str(), - parsed_base_data_key.data().ToString().c_str(), - parsed_base_data_key.version()); + TRACE("==========================START=========================="); + TRACE("[DataFilter], key: %s, data = %s, version = %d", parsed_base_data_key.key().ToString().c_str(), + parsed_base_data_key.data().ToString().c_str(), parsed_base_data_key.version()); if (parsed_base_data_key.key().ToString() != cur_key_) { cur_key_ = parsed_base_data_key.key().ToString(); @@ -93,8 +81,7 @@ class BaseDataFilter : public rocksdb::CompactionFilter { if (cf_handles_ptr_->size() == 0) { return false; } - Status s = db_->Get(default_read_options_, - (*cf_handles_ptr_)[0], cur_key_, &meta_value); + Status s = db_->Get(default_read_options_, (*cf_handles_ptr_)[0], cur_key_, &meta_value); if (s.ok()) { meta_not_found_ = false; ParsedBaseMetaValue parsed_base_meta_value(&meta_value); @@ -104,29 +91,28 @@ class BaseDataFilter : public rocksdb::CompactionFilter { meta_not_found_ = true; } else { cur_key_ = ""; - Trace("Reserve[Get meta_key faild]"); + TRACE("Reserve[Get meta_key faild]"); return false; } } if (meta_not_found_) { - Trace("Drop[Meta key not exist]"); + TRACE("Drop[Meta key not exist]"); return true; } int64_t unix_time; rocksdb::Env::Default()->GetCurrentTime(&unix_time); - if (cur_meta_timestamp_ != 0 - && cur_meta_timestamp_ < static_cast(unix_time)) { - Trace("Drop[Timeout]"); + if (cur_meta_timestamp_ != 0 && cur_meta_timestamp_ < static_cast(unix_time)) { + TRACE("Drop[Timeout]"); return true; } if (cur_meta_version_ > parsed_base_data_key.version()) { - Trace("Drop[data_key_version < cur_meta_version]"); + TRACE("Drop[data_key_version < cur_meta_version]"); return true; } else { - Trace("Reserve[data_key_version == cur_meta_version]"); + TRACE("Reserve[data_key_version == cur_meta_version]"); return false; } } @@ -145,18 +131,13 @@ class BaseDataFilter : public rocksdb::CompactionFilter { class BaseDataFilterFactory : public rocksdb::CompactionFilterFactory { public: - BaseDataFilterFactory(rocksdb::DB** db_ptr, - std::vector* handles_ptr) - : db_ptr_(db_ptr), cf_handles_ptr_(handles_ptr) { - } + BaseDataFilterFactory(rocksdb::DB** db_ptr, std::vector* handles_ptr) + : db_ptr_(db_ptr), cf_handles_ptr_(handles_ptr) {} std::unique_ptr CreateCompactionFilter( - const rocksdb::CompactionFilter::Context& context) override { - return std::unique_ptr( - new BaseDataFilter(*db_ptr_, cf_handles_ptr_)); - } - const char* Name() const override { - return "BaseDataFilterFactory"; + const rocksdb::CompactionFilter::Context& context) override { + return std::unique_ptr(new BaseDataFilter(*db_ptr_, cf_handles_ptr_)); } + const char* Name() const override { return "BaseDataFilterFactory"; } private: rocksdb::DB** db_ptr_; diff --git a/src/storage/src/base_meta_value_format.h b/src/storage/src/base_meta_value_format.h index 3337f4d668..46a2815131 100644 --- a/src/storage/src/base_meta_value_format.h +++ b/src/storage/src/base_meta_value_format.h @@ -14,9 +14,7 @@ namespace storage { class BaseMetaValue : public InternalValue { public: - explicit BaseMetaValue(const Slice& user_value) : - InternalValue(user_value) { - } + explicit BaseMetaValue(const Slice& user_value) : InternalValue(user_value) {} size_t AppendTimestampAndVersion() override { size_t usize = user_value_.size(); char* dst = start_; @@ -43,52 +41,41 @@ class BaseMetaValue : public InternalValue { class ParsedBaseMetaValue : public ParsedInternalValue { public: // Use this constructor after rocksdb::DB::Get(); - explicit ParsedBaseMetaValue(std::string* internal_value_str) : - ParsedInternalValue(internal_value_str) { + explicit ParsedBaseMetaValue(std::string* internal_value_str) : ParsedInternalValue(internal_value_str) { if (internal_value_str->size() >= kBaseMetaValueSuffixLength) { - user_value_ = Slice(internal_value_str->data(), - internal_value_str->size() - kBaseMetaValueSuffixLength); - version_ = DecodeFixed32(internal_value_str->data() + - internal_value_str->size() - sizeof(int32_t) * 2); - timestamp_ = DecodeFixed32(internal_value_str->data() + - internal_value_str->size() - sizeof(int32_t)); + user_value_ = Slice(internal_value_str->data(), internal_value_str->size() - kBaseMetaValueSuffixLength); + version_ = DecodeFixed32(internal_value_str->data() + internal_value_str->size() - sizeof(int32_t) * 2); + timestamp_ = DecodeFixed32(internal_value_str->data() + internal_value_str->size() - sizeof(int32_t)); } count_ = DecodeFixed32(internal_value_str->data()); } // Use this constructor in rocksdb::CompactionFilter::Filter(); - explicit ParsedBaseMetaValue(const Slice& internal_value_slice) : - ParsedInternalValue(internal_value_slice) { + explicit ParsedBaseMetaValue(const Slice& internal_value_slice) : ParsedInternalValue(internal_value_slice) { if (internal_value_slice.size() >= kBaseMetaValueSuffixLength) { - user_value_ = Slice(internal_value_slice.data(), - internal_value_slice.size() - kBaseMetaValueSuffixLength); - version_ = DecodeFixed32(internal_value_slice.data() + - internal_value_slice.size() - sizeof(int32_t) * 2); - timestamp_ = DecodeFixed32(internal_value_slice.data() + - internal_value_slice.size() - sizeof(int32_t)); + user_value_ = Slice(internal_value_slice.data(), internal_value_slice.size() - kBaseMetaValueSuffixLength); + version_ = DecodeFixed32(internal_value_slice.data() + internal_value_slice.size() - sizeof(int32_t) * 2); + timestamp_ = DecodeFixed32(internal_value_slice.data() + internal_value_slice.size() - sizeof(int32_t)); } count_ = DecodeFixed32(internal_value_slice.data()); } void StripSuffix() override { if (value_ != nullptr) { - value_->erase(value_->size() - kBaseMetaValueSuffixLength, - kBaseMetaValueSuffixLength); + value_->erase(value_->size() - kBaseMetaValueSuffixLength, kBaseMetaValueSuffixLength); } } void SetVersionToValue() override { if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - kBaseMetaValueSuffixLength; + char* dst = const_cast(value_->data()) + value_->size() - kBaseMetaValueSuffixLength; EncodeFixed32(dst, version_); } } void SetTimestampToValue() override { if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - sizeof(int32_t); + char* dst = const_cast(value_->data()) + value_->size() - sizeof(int32_t); EncodeFixed32(dst, timestamp_); } } @@ -100,9 +87,7 @@ class ParsedBaseMetaValue : public ParsedInternalValue { return this->UpdateVersion(); } - int32_t count() { - return count_; - } + int32_t count() { return count_; } void set_count(int32_t count) { count_ = count; diff --git a/src/storage/src/base_value_format.h b/src/storage/src/base_value_format.h index 24844561d5..06b3adbfd9 100644 --- a/src/storage/src/base_value_format.h +++ b/src/storage/src/base_value_format.h @@ -8,38 +8,30 @@ #include -#include "src/coding.h" #include "rocksdb/env.h" #include "rocksdb/slice.h" +#include "src/coding.h" namespace storage { class InternalValue { public: - explicit InternalValue(const Slice& user_value) : - start_(nullptr), - user_value_(user_value), - version_(0), - timestamp_(0) { - } + explicit InternalValue(const rocksdb::Slice& user_value) + : start_(nullptr), user_value_(user_value), version_(0), timestamp_(0) {} virtual ~InternalValue() { if (start_ != space_) { delete[] start_; } } - void set_timestamp(int32_t timestamp = 0) { - timestamp_ = timestamp; - } + void set_timestamp(int32_t timestamp = 0) { timestamp_ = timestamp; } void SetRelativeTimestamp(int32_t ttl) { int64_t unix_time; rocksdb::Env::Default()->GetCurrentTime(&unix_time); timestamp_ = static_cast(unix_time) + ttl; } - void set_version(int32_t version = 0) { - version_ = version; - } + void set_version(int32_t version = 0) { version_ = version; } static const size_t kDefaultValueSuffixLength = sizeof(int32_t) * 2; - virtual const Slice Encode() { + virtual const rocksdb::Slice Encode() { size_t usize = user_value_.size(); size_t needed = usize + kDefaultValueSuffixLength; char* dst; @@ -55,14 +47,14 @@ class InternalValue { } start_ = dst; size_t len = AppendTimestampAndVersion(); - return Slice(start_, len); + return rocksdb::Slice(start_, len); } virtual size_t AppendTimestampAndVersion() = 0; protected: char space_[200]; char* start_; - Slice user_value_; + rocksdb::Slice user_value_; int32_t version_; int32_t timestamp_; }; @@ -72,40 +64,26 @@ class ParsedInternalValue { // Use this constructor after rocksdb::DB::Get(), since we use this in // the implement of user interfaces and may need to modify the // original value suffix, so the value_ must point to the string - explicit ParsedInternalValue(std::string* value) : - value_(value), - version_(0), - timestamp_(0) { - } + explicit ParsedInternalValue(std::string* value) : value_(value), version_(0), timestamp_(0) {} // Use this constructor in rocksdb::CompactionFilter::Filter(), // since we use this in Compaction process, all we need to do is parsing - // the Slice, so don't need to modify the original value, value_ can be + // the rocksdb::Slice, so don't need to modify the original value, value_ can be // set to nullptr - explicit ParsedInternalValue(const Slice& value) : - value_(nullptr), - version_(0), - timestamp_(0) { - } + explicit ParsedInternalValue(const rocksdb::Slice& value) : value_(nullptr), version_(0), timestamp_(0) {} virtual ~ParsedInternalValue() = default; - Slice user_value() { - return user_value_; - } + rocksdb::Slice user_value() { return user_value_; } - int32_t version() { - return version_; - } + int32_t version() { return version_; } void set_version(int32_t version) { version_ = version; SetVersionToValue(); } - int32_t timestamp() { - return timestamp_; - } + int32_t timestamp() { return timestamp_; } void set_timestamp(int32_t timestamp) { timestamp_ = timestamp; @@ -119,9 +97,7 @@ class ParsedInternalValue { SetTimestampToValue(); } - bool IsPermanentSurvival() { - return timestamp_ == 0; - } + bool IsPermanentSurvival() { return timestamp_ == 0; } bool IsStale() { if (timestamp_ == 0) { @@ -138,11 +114,10 @@ class ParsedInternalValue { virtual void SetVersionToValue() = 0; virtual void SetTimestampToValue() = 0; std::string* value_; - Slice user_value_; + rocksdb::Slice user_value_; int32_t version_; int32_t timestamp_; }; - } // namespace storage #endif // SRC_BASE_VALUE_FORMAT_H_ diff --git a/src/storage/src/coding.h b/src/storage/src/coding.h index 04a96cc1d5..37825edb11 100644 --- a/src/storage/src/coding.h +++ b/src/storage/src/coding.h @@ -7,23 +7,23 @@ #define SRC_CODING_H_ #if defined(__APPLE__) -#include // __BYTE_ORDER -#define __BYTE_ORDER __DARWIN_BYTE_ORDER -#define __LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN +# include // __BYTE_ORDER +# define __BYTE_ORDER __DARWIN_BYTE_ORDER +# define __LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN #elif defined(__FreeBSD__) -#include // __BYTE_ORDER +# include // __BYTE_ORDER #else -#include // __BYTE_ORDER +# include // __BYTE_ORDER #endif #undef STORAGE_PLATFORM_IS_LITTLE_ENDIAN #ifndef STORAGE_PLATFORM_IS_LITTLE_ENDIAN -#define STORAGE_PLATFORM_IS_LITTLE_ENDIAN (__BYTE_ORDER == __LITTLE_ENDIAN) +# define STORAGE_PLATFORM_IS_LITTLE_ENDIAN (__BYTE_ORDER == __LITTLE_ENDIAN) #endif #include namespace storage { - static const bool kLittleEndian = STORAGE_PLATFORM_IS_LITTLE_ENDIAN; +static const bool kLittleEndian = STORAGE_PLATFORM_IS_LITTLE_ENDIAN; #undef STORAGE_PLATFORM_IS_LITTLE_ENDIAN inline void EncodeFixed32(char* buf, uint32_t value) { @@ -59,10 +59,10 @@ inline uint32_t DecodeFixed32(const char* ptr) { memcpy(&result, ptr, sizeof(result)); // gcc optimizes this to a plain load return result; } else { - return ((static_cast(static_cast(ptr[0]))) - | (static_cast(static_cast(ptr[1])) << 8) - | (static_cast(static_cast(ptr[2])) << 16) - | (static_cast(static_cast(ptr[3])) << 24)); + return ((static_cast(static_cast(ptr[0]))) | + (static_cast(static_cast(ptr[1])) << 8) | + (static_cast(static_cast(ptr[2])) << 16) | + (static_cast(static_cast(ptr[3])) << 24)); } } diff --git a/src/storage/src/custom_comparator.h b/src/storage/src/custom_comparator.h index 043f1a99ed..1aaec7666b 100644 --- a/src/storage/src/custom_comparator.h +++ b/src/storage/src/custom_comparator.h @@ -8,19 +8,18 @@ #include "string" #include "src/coding.h" +#include "rocksdb/comparator.h" namespace storage { class ListsDataKeyComparatorImpl : public rocksdb::Comparator { public: - ListsDataKeyComparatorImpl() { } + ListsDataKeyComparatorImpl() {} // keep compatible with blackwidow - const char* Name() const override { - return "blackwidow.ListsDataKeyComparator"; - } + const char* Name() const override { return "blackwidow.ListsDataKeyComparator"; } - int Compare(const Slice& a, const Slice& b) const override { + int Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const override { assert(!a.empty() && !b.empty()); const char* ptr_a = a.data(); const char* ptr_b = b.data(); @@ -30,15 +29,14 @@ class ListsDataKeyComparatorImpl : public rocksdb::Comparator { int32_t key_b_len = DecodeFixed32(ptr_b); ptr_a += sizeof(int32_t); ptr_b += sizeof(int32_t); - Slice sets_key_a(ptr_a, key_a_len); - Slice sets_key_b(ptr_b, key_b_len); + rocksdb::Slice sets_key_a(ptr_a, key_a_len); + rocksdb::Slice sets_key_b(ptr_b, key_b_len); ptr_a += key_a_len; ptr_b += key_b_len; if (sets_key_a != sets_key_b) { return sets_key_a.compare(sets_key_b); } - if (ptr_a - a.data() == a_size && - ptr_b - b.data() == b_size) { + if (ptr_a - a.data() == a_size && ptr_b - b.data() == b_size) { return 0; } else if (ptr_a - a.data() == a_size) { return -1; @@ -53,8 +51,7 @@ class ListsDataKeyComparatorImpl : public rocksdb::Comparator { if (version_a != version_b) { return version_a < version_b ? -1 : 1; } - if (ptr_a - a.data() == a_size && - ptr_b - b.data() == b_size) { + if (ptr_a - a.data() == a_size && ptr_b - b.data() == b_size) { return 0; } else if (ptr_a - a.data() == a_size) { return -1; @@ -73,19 +70,13 @@ class ListsDataKeyComparatorImpl : public rocksdb::Comparator { } } - bool Equal(const Slice& a, const Slice& b) const override { - return !Compare(a, b); - } + bool Equal(const rocksdb::Slice& a, const rocksdb::Slice& b) const override { return !Compare(a, b); } - void FindShortestSeparator(std::string* start, - const Slice& limit) const override { - } + void FindShortestSeparator(std::string* start, const rocksdb::Slice& limit) const override {} - void FindShortSuccessor(std::string* key) const override { - } + void FindShortSuccessor(std::string* key) const override {} }; - /* * | | | | | | * 4 Bytes Key Size Bytes 4 Bytes 8 Bytes @@ -93,16 +84,12 @@ class ListsDataKeyComparatorImpl : public rocksdb::Comparator { class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { public: // keep compatible with blackwidow - const char* Name() const override { - return "blackwidow.ZSetsScoreKeyComparator"; - } - int Compare(const Slice& a, const Slice& b) const override { + const char* Name() const override { return "blackwidow.ZSetsScoreKeyComparator"; } + int Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const override { assert(a.size() > sizeof(int32_t)); - assert(a.size() >= DecodeFixed32(a.data()) - + 2 * sizeof(int32_t) + sizeof(uint64_t)); + assert(a.size() >= DecodeFixed32(a.data()) + 2 * sizeof(int32_t) + sizeof(uint64_t)); assert(b.size() > sizeof(int32_t)); - assert(b.size() >= DecodeFixed32(b.data()) - + 2 * sizeof(int32_t) + sizeof(uint64_t)); + assert(b.size() >= DecodeFixed32(b.data()) + 2 * sizeof(int32_t) + sizeof(uint64_t)); const char* ptr_a = a.data(); const char* ptr_b = b.data(); @@ -110,8 +97,8 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { int32_t b_size = static_cast(b.size()); int32_t key_a_len = DecodeFixed32(ptr_a); int32_t key_b_len = DecodeFixed32(ptr_b); - Slice key_a_prefix(ptr_a, key_a_len + 2 * sizeof(int32_t)); - Slice key_b_prefix(ptr_b, key_b_len + 2 * sizeof(int32_t)); + rocksdb::Slice key_a_prefix(ptr_a, key_a_len + 2 * sizeof(int32_t)); + rocksdb::Slice key_b_prefix(ptr_b, key_b_len + 2 * sizeof(int32_t)); ptr_a += key_a_len + 2 * sizeof(int32_t); ptr_b += key_b_len + 2 * sizeof(int32_t); int ret = key_a_prefix.compare(key_b_prefix); @@ -128,7 +115,7 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { ptr_a += sizeof(uint64_t); ptr_b += sizeof(uint64_t); if (a_score != b_score) { - return a_score < b_score ? -1 : 1; + return a_score < b_score ? -1 : 1; } else { if (ptr_a - a.data() == a_size && ptr_b - b.data() == b_size) { return 0; @@ -137,8 +124,8 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { } else if (ptr_b - b.data() == b_size) { return 1; } else { - Slice key_a_member(ptr_a, a_size - (ptr_a - a.data())); - Slice key_b_member(ptr_b, b_size - (ptr_b - b.data())); + rocksdb::Slice key_a_member(ptr_a, a_size - (ptr_a - a.data())); + rocksdb::Slice key_b_member(ptr_b, b_size - (ptr_b - b.data())); ret = key_a_member.compare(key_b_member); if (ret) { return ret; @@ -148,9 +135,7 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { return 0; } - bool Equal(const Slice& a, const Slice& b) const override { - return !Compare(a, b); - } + bool Equal(const rocksdb::Slice& a, const rocksdb::Slice& b) const override { return !Compare(a, b); } void ParseAndPrintZSetsScoreKey(const std::string& from, const std::string& str) { const char* ptr = str.data(); @@ -169,10 +154,9 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { double score = *reinterpret_cast(ptr_key_score); ptr += sizeof(uint64_t); - std::string member(ptr, str.size() - (key_len + 2 * sizeof(int32_t) + sizeof(uint64_t))); - printf("%s: total_len[%lu], key_len[%d], key[%s], version[%d], score[%lf], member[%s]\n", - from.data(), str.size(), key_len, key.data(), version, score, member.data()); + printf("%s: total_len[%lu], key_len[%d], key[%s], version[%d], score[%lf], member[%s]\n", from.data(), str.size(), + key_len, key.data(), version, score, member.data()); } // Advanced functions: these are used to reduce the space requirements @@ -181,21 +165,18 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { // If *start < limit, changes *start to a short string in [start,limit). // Simple comparator implementations may return with *start unchanged, // i.e., an implementation of this method that does nothing is correct. - void FindShortestSeparator(std::string* start, - const Slice& limit) const override { + void FindShortestSeparator(std::string* start, const rocksdb::Slice& limit) const override { assert(start->size() > sizeof(int32_t)); - assert(start->size() >= DecodeFixed32(start->data()) - + 2 * sizeof(int32_t) + sizeof(uint64_t)); + assert(start->size() >= DecodeFixed32(start->data()) + 2 * sizeof(int32_t) + sizeof(uint64_t)); assert(limit.size() > sizeof(int32_t)); - assert(limit.size() >= DecodeFixed32(limit.data()) - + 2 * sizeof(int32_t) + sizeof(uint64_t)); + assert(limit.size() >= DecodeFixed32(limit.data()) + 2 * sizeof(int32_t) + sizeof(uint64_t)); const char* ptr_start = start->data(); const char* ptr_limit = limit.data(); int32_t key_start_len = DecodeFixed32(ptr_start); int32_t key_limit_len = DecodeFixed32(ptr_limit); - Slice key_start_prefix(ptr_start, key_start_len + 2 * sizeof(int32_t)); - Slice key_limit_prefix(ptr_limit, key_limit_len + 2 * sizeof(int32_t)); + rocksdb::Slice key_start_prefix(ptr_start, key_start_len + 2 * sizeof(int32_t)); + rocksdb::Slice key_limit_prefix(ptr_limit, key_limit_len + 2 * sizeof(int32_t)); ptr_start += key_start_len + 2 * sizeof(int32_t); ptr_limit += key_limit_len + 2 * sizeof(int32_t); if (key_start_prefix.compare(key_limit_prefix)) { @@ -227,8 +208,7 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { // Find length of common prefix size_t min_length = std::min(key_start_member.size(), key_limit_member.size()); size_t diff_index = 0; - while ((diff_index < min_length) && - (key_start_member[diff_index] == key_limit_member[diff_index])) { + while ((diff_index < min_length) && (key_start_member[diff_index] == key_limit_member[diff_index])) { diff_index++; } @@ -244,8 +224,7 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { } assert(key_start_member_byte < key_limit_member_byte); - if (diff_index < key_limit_member.size() - 1 - || key_start_member_byte + 1 < key_limit_member_byte) { + if (diff_index < key_limit_member.size() - 1 || key_start_member_byte + 1 < key_limit_member_byte) { key_start_member[diff_index]++; key_start_member.resize(diff_index + 1); start->resize(key_start_len + 2 * sizeof(int32_t) + sizeof(uint64_t)); @@ -264,11 +243,11 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { // Keep moving until we find the first non 0xFF byte to // increment it if (static_cast(key_start_member[diff_index]) < static_cast(0xff)) { - key_start_member[diff_index]++; - key_start_member.resize(diff_index + 1); - start->resize(key_start_len + 2 * sizeof(int32_t) + sizeof(uint64_t)); - start->append(key_start_member); - break; + key_start_member[diff_index]++; + key_start_member.resize(diff_index + 1); + start->resize(key_start_len + 2 * sizeof(int32_t) + sizeof(uint64_t)); + start->append(key_start_member); + break; } diff_index++; } @@ -279,8 +258,7 @@ class ZSetsScoreKeyComparatorImpl : public rocksdb::Comparator { // Changes *key to a short string >= *key. // Simple comparator implementations may return with *key unchanged, // i.e., an implementation of this method that does nothing is correct. - void FindShortSuccessor(std::string* key) const override { - } + void FindShortSuccessor(std::string* key) const override {} }; } // namespace storage diff --git a/src/storage/src/db_checkpoint.cc b/src/storage/src/db_checkpoint.cc index 3384f42dc7..f572343bfe 100644 --- a/src/storage/src/db_checkpoint.cc +++ b/src/storage/src/db_checkpoint.cc @@ -9,16 +9,16 @@ #ifndef ROCKSDB_LITE -#include "storage/db_checkpoint.h" +# include "storage/db_checkpoint.h" -#ifndef __STDC_FORMAT_MACROS -#define __STDC_FORMAT_MACROS -#endif +# ifndef __STDC_FORMAT_MACROS +# define __STDC_FORMAT_MACROS +# endif -#include +# include -#include "rocksdb/db.h" -#include "file/file_util.h" +# include "file/file_util.h" +# include "rocksdb/db.h" // #include "file/filename.h" namespace rocksdb { @@ -39,16 +39,12 @@ class DBCheckpointImpl : public DBCheckpoint { Status CreateCheckpoint(const std::string& checkpoint_dir) override; using DBCheckpoint::GetCheckpointFiles; - Status GetCheckpointFiles(std::vector &live_files, - VectorLogPtr &live_wal_files, - uint64_t &manifest_file_size, - uint64_t &sequence_number) override; + Status GetCheckpointFiles(std::vector& live_files, VectorLogPtr& live_wal_files, + uint64_t& manifest_file_size, uint64_t& sequence_number) override; using DBCheckpoint::CreateCheckpointWithFiles; - Status CreateCheckpointWithFiles(const std::string& checkpoint_dir, - std::vector &live_files, - VectorLogPtr &live_wal_files, - uint64_t manifest_file_size, + Status CreateCheckpointWithFiles(const std::string& checkpoint_dir, std::vector& live_files, + VectorLogPtr& live_wal_files, uint64_t manifest_file_size, uint64_t sequence_number) override; private: @@ -60,30 +56,22 @@ Status DBCheckpoint::Create(DB* db, DBCheckpoint** checkpoint_ptr) { return Status::OK(); } -Status DBCheckpoint::CreateCheckpoint(const std::string& checkpoint_dir) { - return Status::NotSupported(""); -} +Status DBCheckpoint::CreateCheckpoint(const std::string& checkpoint_dir) { return Status::NotSupported(""); } // Builds an openable snapshot of RocksDB Status DBCheckpointImpl::CreateCheckpoint(const std::string& checkpoint_dir) { std::vector live_files; VectorLogPtr live_wal_files; uint64_t manifest_file_size, sequence_number; - Status s = GetCheckpointFiles(live_files, - live_wal_files, manifest_file_size, sequence_number); + Status s = GetCheckpointFiles(live_files, live_wal_files, manifest_file_size, sequence_number); if (s.ok()) { - s = CreateCheckpointWithFiles(checkpoint_dir, - live_files, live_wal_files, manifest_file_size, sequence_number); + s = CreateCheckpointWithFiles(checkpoint_dir, live_files, live_wal_files, manifest_file_size, sequence_number); } return s; } -Status DBCheckpointImpl::GetCheckpointFiles( - std::vector &live_files, - VectorLogPtr &live_wal_files, - uint64_t &manifest_file_size, - uint64_t &sequence_number) { - +Status DBCheckpointImpl::GetCheckpointFiles(std::vector& live_files, VectorLogPtr& live_wal_files, + uint64_t& manifest_file_size, uint64_t& sequence_number) { Status s; sequence_number = db_->GetLatestSequenceNumber(); @@ -105,12 +93,9 @@ Status DBCheckpointImpl::GetCheckpointFiles( return s; } -Status DBCheckpointImpl::CreateCheckpointWithFiles( - const std::string& checkpoint_dir, - std::vector &live_files, - VectorLogPtr &live_wal_files, - uint64_t manifest_file_size, - uint64_t sequence_number) { +Status DBCheckpointImpl::CreateCheckpointWithFiles(const std::string& checkpoint_dir, + std::vector& live_files, VectorLogPtr& live_wal_files, + uint64_t manifest_file_size, uint64_t sequence_number) { bool same_fs = true; Status s = db_->GetEnv()->FileExists(checkpoint_dir); @@ -122,8 +107,7 @@ Status DBCheckpointImpl::CreateCheckpointWithFiles( } size_t wal_size = live_wal_files.size(); - Log(db_->GetOptions().info_log, - "Started the snapshot process -- creating snapshot in directory %s", + Log(db_->GetOptions().info_log, "Started the snapshot process -- creating snapshot in directory %s", checkpoint_dir.c_str()); std::string full_private_path = checkpoint_dir + ".tmp"; @@ -142,8 +126,7 @@ Status DBCheckpointImpl::CreateCheckpointWithFiles( break; } // we should only get sst, options, manifest and current files here - assert(type == kTableFile || type == kDescriptorFile || - type == kCurrentFile || type == kOptionsFile); + assert(type == kTableFile || type == kDescriptorFile || type == kCurrentFile || type == kOptionsFile); assert(live_files[i].size() > 0 && live_files[i][0] == '/'); if (type == kCurrentFile) { // We will craft the current file manually to ensure it's consistent with @@ -162,8 +145,7 @@ Status DBCheckpointImpl::CreateCheckpointWithFiles( // * always copy if cross-device link if ((type == kTableFile) && same_fs) { Log(db_->GetOptions().info_log, "Hard Linking %s", src_fname.c_str()); - s = db_->GetEnv()->LinkFile(db_->GetName() + src_fname, - full_private_path + src_fname); + s = db_->GetEnv()->LinkFile(db_->GetName() + src_fname, full_private_path + src_fname); if (s.IsNotSupported()) { same_fs = false; s = Status::OK(); @@ -171,27 +153,22 @@ Status DBCheckpointImpl::CreateCheckpointWithFiles( } if ((type != kTableFile) || (!same_fs)) { Log(db_->GetOptions().info_log, "Copying %s", src_fname.c_str()); -#if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 3)) - s = CopyFile(db_->GetEnv(), db_->GetName() + src_fname, - full_private_path + src_fname, +# if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 3)) + s = CopyFile(db_->GetEnv(), db_->GetName() + src_fname, full_private_path + src_fname, (type == kDescriptorFile) ? manifest_file_size : 0); -#else - s = CopyFile(db_->GetFileSystem(), db_->GetName() + src_fname, - full_private_path + src_fname, - (type == kDescriptorFile) ? manifest_file_size : 0, - false, nullptr, Temperature::kUnknown); -#endif +# else + s = CopyFile(db_->GetFileSystem(), db_->GetName() + src_fname, full_private_path + src_fname, + (type == kDescriptorFile) ? manifest_file_size : 0, false, nullptr, Temperature::kUnknown); +# endif } } if (s.ok() && !current_fname.empty() && !manifest_fname.empty()) { // 5.17.2 Createfile with new argv use_fsync -#if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 17)) - s = CreateFile(db_->GetEnv(), full_private_path + current_fname, - manifest_fname.substr(1) + "\n"); -#else - s = CreateFile(db_->GetFileSystem(), full_private_path + current_fname, - manifest_fname.substr(1) + "\n", false); -#endif +# if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 17)) + s = CreateFile(db_->GetEnv(), full_private_path + current_fname, manifest_fname.substr(1) + "\n"); +# else + s = CreateFile(db_->GetFileSystem(), full_private_path + current_fname, manifest_fname.substr(1) + "\n", false); +# endif } // Log(db_->GetOptions().info_log, // "Number of log files %" ROCKSDB_PRIszt, live_wal_files.size()); @@ -199,50 +176,38 @@ Status DBCheckpointImpl::CreateCheckpointWithFiles( // Link WAL files. Copy exact size of last one because it is the only one // that has changes after the last flush. for (size_t i = 0; s.ok() && i < wal_size; ++i) { - if ((live_wal_files[i]->Type() == kAliveLogFile) && - (live_wal_files[i]->StartSequence() >= sequence_number)) { + if ((live_wal_files[i]->Type() == kAliveLogFile) && (live_wal_files[i]->StartSequence() >= sequence_number)) { if (i + 1 == wal_size) { - Log(db_->GetOptions().info_log, "Copying %s", - live_wal_files[i]->PathName().c_str()); -#if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 3)) - s = CopyFile(db_->GetEnv(), - db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), - full_private_path + live_wal_files[i]->PathName(), - live_wal_files[i]->SizeFileBytes()); -#else - s = CopyFile(db_->GetFileSystem(), - db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), - full_private_path + live_wal_files[i]->PathName(), - live_wal_files[i]->SizeFileBytes(), false, + Log(db_->GetOptions().info_log, "Copying %s", live_wal_files[i]->PathName().c_str()); +# if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 3)) + s = CopyFile(db_->GetEnv(), db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), + full_private_path + live_wal_files[i]->PathName(), live_wal_files[i]->SizeFileBytes()); +# else + s = CopyFile(db_->GetFileSystem(), db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), + full_private_path + live_wal_files[i]->PathName(), live_wal_files[i]->SizeFileBytes(), false, nullptr, Temperature::kUnknown); -#endif +# endif break; } if (same_fs) { // we only care about live log files - Log(db_->GetOptions().info_log, "Hard Linking %s", - live_wal_files[i]->PathName().c_str()); - s = db_->GetEnv()->LinkFile( - db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), - full_private_path + live_wal_files[i]->PathName()); + Log(db_->GetOptions().info_log, "Hard Linking %s", live_wal_files[i]->PathName().c_str()); + s = db_->GetEnv()->LinkFile(db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), + full_private_path + live_wal_files[i]->PathName()); if (s.IsNotSupported()) { same_fs = false; s = Status::OK(); } } if (!same_fs) { - Log(db_->GetOptions().info_log, "Copying %s", - live_wal_files[i]->PathName().c_str()); -#if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 3)) - s = CopyFile(db_->GetEnv(), - db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), + Log(db_->GetOptions().info_log, "Copying %s", live_wal_files[i]->PathName().c_str()); +# if (ROCKSDB_MAJOR < 5 || (ROCKSDB_MAJOR == 5 && ROCKSDB_MINOR < 3)) + s = CopyFile(db_->GetEnv(), db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), full_private_path + live_wal_files[i]->PathName(), 0); -#else - s = CopyFile(db_->GetFileSystem(), - db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), - full_private_path + live_wal_files[i]->PathName(), - 0, false, nullptr, Temperature::kUnknown); -#endif +# else + s = CopyFile(db_->GetFileSystem(), db_->GetOptions().wal_dir + live_wal_files[i]->PathName(), + full_private_path + live_wal_files[i]->PathName(), 0, false, nullptr, Temperature::kUnknown); +# endif } } } @@ -264,28 +229,24 @@ Status DBCheckpointImpl::CreateCheckpointWithFiles( if (!s.ok()) { // clean all the files we might have created - Log(db_->GetOptions().info_log, "Snapshot failed -- %s", - s.ToString().c_str()); + Log(db_->GetOptions().info_log, "Snapshot failed -- %s", s.ToString().c_str()); // we have to delete the dir and all its children std::vector subchildren; db_->GetEnv()->GetChildren(full_private_path, &subchildren); for (auto& subchild : subchildren) { std::string subchild_path = full_private_path + "/" + subchild; Status s1 = db_->GetEnv()->DeleteFile(subchild_path); - Log(db_->GetOptions().info_log, "Delete file %s -- %s", - subchild_path.c_str(), s1.ToString().c_str()); + Log(db_->GetOptions().info_log, "Delete file %s -- %s", subchild_path.c_str(), s1.ToString().c_str()); } // finally delete the private dir Status s1 = db_->GetEnv()->DeleteDir(full_private_path); - Log(db_->GetOptions().info_log, "Delete dir %s -- %s", - full_private_path.c_str(), s1.ToString().c_str()); + Log(db_->GetOptions().info_log, "Delete dir %s -- %s", full_private_path.c_str(), s1.ToString().c_str()); return s; } // here we know that we succeeded and installed the new snapshot Log(db_->GetOptions().info_log, "Snapshot DONE. All is good"); - Log(db_->GetOptions().info_log, "Snapshot sequence number: %" PRIu64, - sequence_number); + Log(db_->GetOptions().info_log, "Snapshot sequence number: %" PRIu64, sequence_number); return s; } diff --git a/src/storage/src/debug.h b/src/storage/src/debug.h index 442ea38f1b..fe78c14695 100644 --- a/src/storage/src/debug.h +++ b/src/storage/src/debug.h @@ -7,11 +7,11 @@ #define SRC_DEBUG_H_ #ifndef NDEBUG -#define Trace(M, ...) fprintf(stderr, "[Trace] (%s:%d) " M "\n", __FILE__, __LINE__, ##__VA_ARGS__) -#define Debug(M, ...) fprintf(stderr, "[Debug] (%s:%d) " M "\n", __FILE__, __LINE__, ##__VA_ARGS__) +# define TRACE(M, ...) fprintf(stderr, "[TRACE] (%s:%d) " M "\n", __FILE__, __LINE__, ##__VA_ARGS__) +# define DEBUG(M, ...) fprintf(stderr, "[Debug] (%s:%d) " M "\n", __FILE__, __LINE__, ##__VA_ARGS__) #else -#define Trace(M, ...) {} -#define Debug(M, ...) {} +# define TRACE(M, ...) {} +# define DEBUG(M, ...) {} #endif // NDEBUG #endif // SRC_DEBUG_H_ diff --git a/src/storage/src/lists_data_key_format.h b/src/storage/src/lists_data_key_format.h index 33cc503936..cb73bbea0e 100644 --- a/src/storage/src/lists_data_key_format.h +++ b/src/storage/src/lists_data_key_format.h @@ -6,14 +6,15 @@ #ifndef SRC_LISTS_DATA_KEY_FORMAT_H_ #define SRC_LISTS_DATA_KEY_FORMAT_H_ +#include "pstd/include/pstd_coding.h" + #include namespace storage { class ListsDataKey { public: - ListsDataKey(const Slice& key, int32_t version, uint64_t index) : - start_(nullptr), key_(key), version_(version), index_(index) { - } + ListsDataKey(const rocksdb::Slice& key, int32_t version, uint64_t index) + : start_(nullptr), key_(key), version_(version), index_(index) {} ~ListsDataKey() { if (start_ != space_) { @@ -21,7 +22,7 @@ class ListsDataKey { } } - const Slice Encode() { + const rocksdb::Slice Encode() { size_t usize = key_.size(); size_t needed = usize + sizeof(int32_t) * 2 + sizeof(uint64_t); char* dst; @@ -36,20 +37,20 @@ class ListsDataKey { } } start_ = dst; - EncodeFixed32(dst, key_.size()); + pstd::EncodeFixed32(dst, key_.size()); dst += sizeof(int32_t); memcpy(dst, key_.data(), key_.size()); dst += key_.size(); - EncodeFixed32(dst, version_); + pstd::EncodeFixed32(dst, version_); dst += sizeof(int32_t); - EncodeFixed64(dst, index_); - return Slice(start_, needed); + pstd::EncodeFixed64(dst, index_); + return rocksdb::Slice(start_, needed); } private: char space_[200]; char* start_; - Slice key_; + rocksdb::Slice key_; int32_t version_; uint64_t index_; }; @@ -58,42 +59,36 @@ class ParsedListsDataKey { public: explicit ParsedListsDataKey(const std::string* key) { const char* ptr = key->data(); - int32_t key_len = DecodeFixed32(ptr); + int32_t key_len = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); - key_ = Slice(ptr, key_len); + key_ = rocksdb::Slice(ptr, key_len); ptr += key_len; - version_ = DecodeFixed32(ptr); + version_ = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); - index_ = DecodeFixed64(ptr); + index_ = pstd::DecodeFixed64(ptr); } - explicit ParsedListsDataKey(const Slice& key) { + explicit ParsedListsDataKey(const rocksdb::Slice& key) { const char* ptr = key.data(); - int32_t key_len = DecodeFixed32(ptr); + int32_t key_len = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); - key_ = Slice(ptr, key_len); + key_ = rocksdb::Slice(ptr, key_len); ptr += key_len; - version_ = DecodeFixed32(ptr); + version_ = pstd::DecodeFixed32(ptr); ptr += sizeof(int32_t); - index_ = DecodeFixed64(ptr); + index_ = pstd::DecodeFixed64(ptr); } virtual ~ParsedListsDataKey() = default; - Slice key() { - return key_; - } + rocksdb::Slice key() { return key_; } - int32_t version() { - return version_; - } + int32_t version() { return version_; } - uint64_t index() { - return index_; - } + uint64_t index() { return index_; } private: - Slice key_; + rocksdb::Slice key_; int32_t version_; uint64_t index_; }; diff --git a/src/storage/src/lists_filter.h b/src/storage/src/lists_filter.h index 382bfb5e19..b9ab89a459 100644 --- a/src/storage/src/lists_filter.h +++ b/src/storage/src/lists_filter.h @@ -6,47 +6,42 @@ #ifndef SRC_LISTS_FILTER_H_ #define SRC_LISTS_FILTER_H_ -#include #include +#include #include +#include "rocksdb/compaction_filter.h" +#include "rocksdb/db.h" #include "src/debug.h" -#include "src/lists_meta_value_format.h" #include "src/lists_data_key_format.h" -#include "rocksdb/compaction_filter.h" +#include "src/lists_meta_value_format.h" namespace storage { class ListsMetaFilter : public rocksdb::CompactionFilter { public: ListsMetaFilter() = default; - bool Filter(int level, const rocksdb::Slice& key, - const rocksdb::Slice& value, - std::string* new_value, bool* value_changed) const override { + bool Filter(int level, const rocksdb::Slice& key, const rocksdb::Slice& value, std::string* new_value, + bool* value_changed) const override { int64_t unix_time; rocksdb::Env::Default()->GetCurrentTime(&unix_time); int32_t cur_time = static_cast(unix_time); ParsedListsMetaValue parsed_lists_meta_value(value); - Trace("==========================START=========================="); - Trace("[ListMetaFilter], key: %s, count = %lu, timestamp: %d, cur_time: %d, version: %d", - key.ToString().c_str(), - parsed_lists_meta_value.count(), - parsed_lists_meta_value.timestamp(), - cur_time, + TRACE("==========================START=========================="); + TRACE("[ListMetaFilter], key: %s, count = %lu, timestamp: %d, cur_time: %d, version: %d", key.ToString().c_str(), + parsed_lists_meta_value.count(), parsed_lists_meta_value.timestamp(), cur_time, parsed_lists_meta_value.version()); - if (parsed_lists_meta_value.timestamp() != 0 - && parsed_lists_meta_value.timestamp() < cur_time - && parsed_lists_meta_value.version() < cur_time) { - Trace("Drop[Stale & version < cur_time]"); + if (parsed_lists_meta_value.timestamp() != 0 && parsed_lists_meta_value.timestamp() < cur_time && + parsed_lists_meta_value.version() < cur_time) { + TRACE("Drop[Stale & version < cur_time]"); return true; } - if (parsed_lists_meta_value.count() == 0 - && parsed_lists_meta_value.version() < cur_time) { - Trace("Drop[Empty & version < cur_time]"); + if (parsed_lists_meta_value.count() == 0 && parsed_lists_meta_value.version() < cur_time) { + TRACE("Drop[Empty & version < cur_time]"); return true; } - Trace("Reserve"); + TRACE("Reserve"); return false; } @@ -57,34 +52,27 @@ class ListsMetaFilterFactory : public rocksdb::CompactionFilterFactory { public: ListsMetaFilterFactory() = default; std::unique_ptr CreateCompactionFilter( - const rocksdb::CompactionFilter::Context& context) override { + const rocksdb::CompactionFilter::Context& context) override { return std::unique_ptr(new ListsMetaFilter()); } - const char* Name() const override { - return "ListsMetaFilterFactory"; - } + const char* Name() const override { return "ListsMetaFilterFactory"; } }; class ListsDataFilter : public rocksdb::CompactionFilter { public: - ListsDataFilter(rocksdb::DB* db, - std::vector* cf_handles_ptr) : - db_(db), - cf_handles_ptr_(cf_handles_ptr), - meta_not_found_(false), - cur_meta_version_(0), - cur_meta_timestamp_(0) {} - - bool Filter(int level, const rocksdb::Slice& key, - const rocksdb::Slice& value, - std::string* new_value, bool* value_changed) const override { + ListsDataFilter(rocksdb::DB* db, std::vector* cf_handles_ptr) + : db_(db), + cf_handles_ptr_(cf_handles_ptr), + meta_not_found_(false), + cur_meta_version_(0), + cur_meta_timestamp_(0) {} + + bool Filter(int level, const rocksdb::Slice& key, const rocksdb::Slice& value, std::string* new_value, + bool* value_changed) const override { ParsedListsDataKey parsed_lists_data_key(key); - Trace("==========================START=========================="); - Trace("[DataFilter], key: %s, index = %lu, data = %s, version = %d", - parsed_lists_data_key.key().ToString().c_str(), - parsed_lists_data_key.index(), - value.ToString().c_str(), - parsed_lists_data_key.version()); + TRACE("==========================START=========================="); + TRACE("[DataFilter], key: %s, index = %lu, data = %s, version = %d", parsed_lists_data_key.key().ToString().c_str(), + parsed_lists_data_key.index(), value.ToString().c_str(), parsed_lists_data_key.version()); if (parsed_lists_data_key.key().ToString() != cur_key_) { cur_key_ = parsed_lists_data_key.key().ToString(); @@ -93,8 +81,7 @@ class ListsDataFilter : public rocksdb::CompactionFilter { if (cf_handles_ptr_->size() == 0) { return false; } - Status s = db_->Get(default_read_options_, - (*cf_handles_ptr_)[0], cur_key_, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, (*cf_handles_ptr_)[0], cur_key_, &meta_value); if (s.ok()) { meta_not_found_ = false; ParsedListsMetaValue parsed_lists_meta_value(&meta_value); @@ -104,29 +91,28 @@ class ListsDataFilter : public rocksdb::CompactionFilter { meta_not_found_ = true; } else { cur_key_ = ""; - Trace("Reserve[Get meta_key faild]"); + TRACE("Reserve[Get meta_key faild]"); return false; } } if (meta_not_found_) { - Trace("Drop[Meta key not exist]"); + TRACE("Drop[Meta key not exist]"); return true; } int64_t unix_time; rocksdb::Env::Default()->GetCurrentTime(&unix_time); - if (cur_meta_timestamp_ != 0 - && cur_meta_timestamp_ < static_cast(unix_time)) { - Trace("Drop[Timeout]"); + if (cur_meta_timestamp_ != 0 && cur_meta_timestamp_ < static_cast(unix_time)) { + TRACE("Drop[Timeout]"); return true; } if (cur_meta_version_ > parsed_lists_data_key.version()) { - Trace("Drop[list_data_key_version < cur_meta_version]"); + TRACE("Drop[list_data_key_version < cur_meta_version]"); return true; } else { - Trace("Reserve[list_data_key_version == cur_meta_version]"); + TRACE("Reserve[list_data_key_version == cur_meta_version]"); return false; } } @@ -145,18 +131,14 @@ class ListsDataFilter : public rocksdb::CompactionFilter { class ListsDataFilterFactory : public rocksdb::CompactionFilterFactory { public: - ListsDataFilterFactory(rocksdb::DB** db_ptr, - std::vector* handles_ptr) - : db_ptr_(db_ptr), cf_handles_ptr_(handles_ptr) {} + ListsDataFilterFactory(rocksdb::DB** db_ptr, std::vector* handles_ptr) + : db_ptr_(db_ptr), cf_handles_ptr_(handles_ptr) {} std::unique_ptr CreateCompactionFilter( const rocksdb::CompactionFilter::Context& context) override { - return std::unique_ptr( - new ListsDataFilter(*db_ptr_, cf_handles_ptr_)); - } - const char* Name() const override { - return "ListsDataFilterFactory"; + return std::unique_ptr(new ListsDataFilter(*db_ptr_, cf_handles_ptr_)); } + const char* Name() const override { return "ListsDataFilterFactory"; } private: rocksdb::DB** db_ptr_; diff --git a/src/storage/src/lists_meta_value_format.h b/src/storage/src/lists_meta_value_format.h index 493466c654..afb24bde42 100644 --- a/src/storage/src/lists_meta_value_format.h +++ b/src/storage/src/lists_meta_value_format.h @@ -17,11 +17,8 @@ const uint64_t InitalRightIndex = 9223372036854775808U; class ListsMetaValue : public InternalValue { public: - explicit ListsMetaValue(const Slice& user_value) : - InternalValue(user_value), - left_index_(InitalLeftIndex), - right_index_(InitalRightIndex) { - } + explicit ListsMetaValue(const rocksdb::Slice& user_value) + : InternalValue(user_value), left_index_(InitalLeftIndex), right_index_(InitalRightIndex) {} size_t AppendTimestampAndVersion() override { size_t usize = user_value_.size(); @@ -35,7 +32,7 @@ class ListsMetaValue : public InternalValue { } virtual size_t AppendIndex() { - char * dst = start_; + char* dst = start_; dst += user_value_.size() + 2 * sizeof(int32_t); EncodeFixed64(dst, left_index_); dst += sizeof(int64_t); @@ -43,10 +40,9 @@ class ListsMetaValue : public InternalValue { return 2 * sizeof(int64_t); } - static const size_t kDefaultValueSuffixLength = sizeof(int32_t) * 2 + - sizeof(int64_t) * 2; + static const size_t kDefaultValueSuffixLength = sizeof(int32_t) * 2 + sizeof(int64_t) * 2; - const Slice Encode() override { + const rocksdb::Slice Encode() override { size_t usize = user_value_.size(); size_t needed = usize + kDefaultValueSuffixLength; char* dst; @@ -55,9 +51,9 @@ class ListsMetaValue : public InternalValue { } else { dst = new char[needed]; } - start_ = dst; + start_ = dst; size_t len = AppendTimestampAndVersion() + AppendIndex(); - return Slice(start_, len); + return rocksdb::Slice(start_, len); } int32_t UpdateVersion() { @@ -71,21 +67,13 @@ class ListsMetaValue : public InternalValue { return version_; } - uint64_t left_index() { - return left_index_; - } + uint64_t left_index() { return left_index_; } - void ModifyLeftIndex(uint64_t index) { - left_index_ -= index; - } + void ModifyLeftIndex(uint64_t index) { left_index_ -= index; } - uint64_t right_index() { - return right_index_; - } + uint64_t right_index() { return right_index_; } - void ModifyRightIndex(uint64_t index) { - right_index_ += index; - } + void ModifyRightIndex(uint64_t index) { right_index_ += index; } private: uint64_t left_index_; @@ -95,88 +83,67 @@ class ListsMetaValue : public InternalValue { class ParsedListsMetaValue : public ParsedInternalValue { public: // Use this constructor after rocksdb::DB::Get(); - explicit ParsedListsMetaValue(std::string* internal_value_str) : - ParsedInternalValue(internal_value_str), - count_(0), - left_index_(0), - right_index_(0) { + explicit ParsedListsMetaValue(std::string* internal_value_str) + : ParsedInternalValue(internal_value_str), count_(0), left_index_(0), right_index_(0) { assert(internal_value_str->size() >= kListsMetaValueSuffixLength); if (internal_value_str->size() >= kListsMetaValueSuffixLength) { - user_value_ = Slice(internal_value_str->data(), - internal_value_str->size() - kListsMetaValueSuffixLength); - version_ = DecodeFixed32(internal_value_str->data() + - internal_value_str->size() - sizeof(int32_t) * 2 - - sizeof(int64_t) * 2); - timestamp_ = DecodeFixed32(internal_value_str->data() + - internal_value_str->size() - sizeof(int32_t) - - sizeof(int64_t) * 2); - left_index_ = DecodeFixed64(internal_value_str->data() + - internal_value_str->size() - sizeof(int64_t) * 2); - right_index_ = DecodeFixed64(internal_value_str->data() + - internal_value_str->size() - sizeof(int64_t)); + user_value_ = rocksdb::Slice(internal_value_str->data(), internal_value_str->size() - kListsMetaValueSuffixLength); + version_ = DecodeFixed32(internal_value_str->data() + internal_value_str->size() - sizeof(int32_t) * 2 - + sizeof(int64_t) * 2); + timestamp_ = DecodeFixed32(internal_value_str->data() + internal_value_str->size() - sizeof(int32_t) - + sizeof(int64_t) * 2); + left_index_ = DecodeFixed64(internal_value_str->data() + internal_value_str->size() - sizeof(int64_t) * 2); + right_index_ = DecodeFixed64(internal_value_str->data() + internal_value_str->size() - sizeof(int64_t)); } count_ = DecodeFixed64(internal_value_str->data()); } // Use this constructor in rocksdb::CompactionFilter::Filter(); - explicit ParsedListsMetaValue(const Slice& internal_value_slice) : - ParsedInternalValue(internal_value_slice), - count_(0), - left_index_(0), - right_index_(0) { + explicit ParsedListsMetaValue(const rocksdb::Slice& internal_value_slice) + : ParsedInternalValue(internal_value_slice), count_(0), left_index_(0), right_index_(0) { assert(internal_value_slice.size() >= kListsMetaValueSuffixLength); if (internal_value_slice.size() >= kListsMetaValueSuffixLength) { - user_value_ = Slice(internal_value_slice.data(), - internal_value_slice.size() - kListsMetaValueSuffixLength); - version_ = DecodeFixed32(internal_value_slice.data() + - internal_value_slice.size() - sizeof(int32_t) * 2 - - sizeof(int64_t) * 2); - timestamp_ = DecodeFixed32(internal_value_slice.data() + - internal_value_slice.size() - sizeof(int32_t) - - sizeof(int64_t) * 2); - left_index_ = DecodeFixed64(internal_value_slice.data() + - internal_value_slice.size() - sizeof(int64_t) * 2); - right_index_ = DecodeFixed64(internal_value_slice.data() + - internal_value_slice.size() - sizeof(int64_t)); + user_value_ = rocksdb::Slice(internal_value_slice.data(), internal_value_slice.size() - kListsMetaValueSuffixLength); + version_ = DecodeFixed32(internal_value_slice.data() + internal_value_slice.size() - sizeof(int32_t) * 2 - + sizeof(int64_t) * 2); + timestamp_ = DecodeFixed32(internal_value_slice.data() + internal_value_slice.size() - sizeof(int32_t) - + sizeof(int64_t) * 2); + left_index_ = DecodeFixed64(internal_value_slice.data() + internal_value_slice.size() - sizeof(int64_t) * 2); + right_index_ = DecodeFixed64(internal_value_slice.data() + internal_value_slice.size() - sizeof(int64_t)); } count_ = DecodeFixed64(internal_value_slice.data()); } void StripSuffix() override { if (value_ != nullptr) { - value_->erase(value_->size() - kListsMetaValueSuffixLength, - kListsMetaValueSuffixLength); + value_->erase(value_->size() - kListsMetaValueSuffixLength, kListsMetaValueSuffixLength); } } void SetVersionToValue() override { if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - kListsMetaValueSuffixLength; + char* dst = const_cast(value_->data()) + value_->size() - kListsMetaValueSuffixLength; EncodeFixed32(dst, version_); } } void SetTimestampToValue() override { if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - sizeof(int32_t) - 2 * sizeof(int64_t); + char* dst = const_cast(value_->data()) + value_->size() - sizeof(int32_t) - 2 * sizeof(int64_t); EncodeFixed32(dst, timestamp_); } } void SetIndexToValue() { if (value_ != nullptr) { - char *dst = const_cast(value_->data()) + value_->size() - - 2 * sizeof(int64_t); - EncodeFixed64(dst, left_index_); + char* dst = const_cast(value_->data()) + value_->size() - 2 * sizeof(int64_t); + EncodeFixed64(dst, left_index_); dst += sizeof(int64_t); EncodeFixed64(dst, right_index_); } } - static const size_t kListsMetaValueSuffixLength = - 2 * sizeof(int32_t) + 2 * sizeof(int64_t); + static const size_t kListsMetaValueSuffixLength = 2 * sizeof(int32_t) + 2 * sizeof(int64_t); int32_t InitialMetaValue() { this->set_count(0); @@ -186,9 +153,7 @@ class ParsedListsMetaValue : public ParsedInternalValue { return this->UpdateVersion(); } - uint64_t count() { - return count_; - } + uint64_t count() { return count_; } void set_count(uint64_t count) { count_ = count; @@ -218,15 +183,12 @@ class ParsedListsMetaValue : public ParsedInternalValue { return version_; } - uint64_t left_index() { - return left_index_; - } + uint64_t left_index() { return left_index_; } void set_left_index(uint64_t index) { left_index_ = index; if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - 2 * sizeof(int64_t); + char* dst = const_cast(value_->data()) + value_->size() - 2 * sizeof(int64_t); EncodeFixed64(dst, left_index_); } } @@ -234,21 +196,17 @@ class ParsedListsMetaValue : public ParsedInternalValue { void ModifyLeftIndex(uint64_t index) { left_index_ -= index; if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - 2 * sizeof(int64_t); + char* dst = const_cast(value_->data()) + value_->size() - 2 * sizeof(int64_t); EncodeFixed64(dst, left_index_); } } - uint64_t right_index() { - return right_index_; - } + uint64_t right_index() { return right_index_; } void set_right_index(uint64_t index) { right_index_ = index; if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - sizeof(int64_t); + char* dst = const_cast(value_->data()) + value_->size() - sizeof(int64_t); EncodeFixed64(dst, right_index_); } } @@ -256,8 +214,7 @@ class ParsedListsMetaValue : public ParsedInternalValue { void ModifyRightIndex(uint64_t index) { right_index_ += index; if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - sizeof(int64_t); + char* dst = const_cast(value_->data()) + value_->size() - sizeof(int64_t); EncodeFixed64(dst, right_index_); } } @@ -270,4 +227,3 @@ class ParsedListsMetaValue : public ParsedInternalValue { } // namespace storage #endif // SRC_LISTS_META_VALUE_FORMAT_H_ - diff --git a/src/storage/src/lock_mgr.cc b/src/storage/src/lock_mgr.cc index d5033918c7..b6b2ec5500 100644 --- a/src/storage/src/lock_mgr.cc +++ b/src/storage/src/lock_mgr.cc @@ -4,18 +4,18 @@ // of patent rights can be found in the PATENTS file in the same directory. #ifndef __STDC_FORMAT_MACROS -#define __STDC_FORMAT_MACROS +# define __STDC_FORMAT_MACROS #endif #include "src/lock_mgr.h" -#include -#include #include #include +#include +#include -#include "src/mutex.h" #include "src/murmurhash.h" +#include "src/mutex.h" namespace storage { @@ -39,9 +39,7 @@ struct LockMapStripe { // Map of #num_stripes LockMapStripes struct LockMap { - explicit LockMap(size_t num_stripes, - std::shared_ptr factory) - : num_stripes_(num_stripes) { + explicit LockMap(size_t num_stripes, std::shared_ptr factory) : num_stripes_(num_stripes) { lock_map_stripes_.reserve(num_stripes); for (size_t i = 0; i < num_stripes; i++) { LockMapStripe* stripe = new LockMapStripe(factory); @@ -74,14 +72,11 @@ size_t LockMap::GetStripe(const std::string& key) const { return stripe; } -LockMgr::LockMgr(size_t default_num_stripes, - int64_t max_num_locks, - std::shared_ptr mutex_factory) +LockMgr::LockMgr(size_t default_num_stripes, int64_t max_num_locks, std::shared_ptr mutex_factory) : default_num_stripes_(default_num_stripes), max_num_locks_(max_num_locks), mutex_factory_(mutex_factory), - lock_map_(std::shared_ptr( - new LockMap(default_num_stripes, mutex_factory))) {} + lock_map_(std::shared_ptr(new LockMap(default_num_stripes, mutex_factory))) {} LockMgr::~LockMgr() {} @@ -98,8 +93,7 @@ Status LockMgr::TryLock(const std::string& key) { } // Helper function for TryLock(). -Status LockMgr::Acquire(LockMapStripe* stripe, - const std::string& key) { +Status LockMgr::Acquire(LockMapStripe* stripe, const std::string& key) { Status result; // we wait indefinitely to acquire the lock @@ -130,17 +124,15 @@ Status LockMgr::Acquire(LockMapStripe* stripe, // Try to lock this key after we have acquired the mutex. // REQUIRED: Stripe mutex must be held. -Status LockMgr::AcquireLocked(LockMapStripe* stripe, - const std::string& key) { +Status LockMgr::AcquireLocked(LockMapStripe* stripe, const std::string& key) { Status result; // Check if this key is already locked if (stripe->keys.find(key) != stripe->keys.end()) { // Lock already held - result = Status::Busy(Status::SubCode::kLockTimeout); + result = Status::Busy(Status::SubCode::kLockTimeout); } else { // Lock not held. // Check lock limit - if (max_num_locks_ > 0 && - lock_map_->lock_cnt.load(std::memory_order_acquire) >= max_num_locks_) { + if (max_num_locks_ > 0 && lock_map_->lock_cnt.load(std::memory_order_acquire) >= max_num_locks_) { result = Status::Busy(Status::SubCode::kLockLimit); } else { // acquire lock diff --git a/src/storage/src/lock_mgr.h b/src/storage/src/lock_mgr.h index b8b2ad5ce1..4607ce1cba 100644 --- a/src/storage/src/lock_mgr.h +++ b/src/storage/src/lock_mgr.h @@ -6,8 +6,8 @@ #ifndef SRC_LOCK_MGR_H_ #define SRC_LOCK_MGR_H_ -#include #include +#include #include "src/mutex.h" @@ -18,8 +18,7 @@ struct LockMapStripe; class LockMgr { public: - LockMgr(size_t default_num_stripes, int64_t max_num_locks, - std::shared_ptr factory); + LockMgr(size_t default_num_stripes, int64_t max_num_locks, std::shared_ptr factory); ~LockMgr(); diff --git a/src/storage/src/lru_cache.h b/src/storage/src/lru_cache.h index 9848efc0d1..ea5928a4a5 100644 --- a/src/storage/src/lru_cache.h +++ b/src/storage/src/lru_cache.h @@ -6,10 +6,12 @@ #ifndef SRC_LRU_CACHE_H_ #define SRC_LRU_CACHE_H_ -#include #include +#include #include +#include "rocksdb/status.h" + #include "pstd/include/pstd_mutex.h" namespace storage { @@ -39,12 +41,10 @@ class HandleTable { }; template -HandleTable::HandleTable() { -} +HandleTable::HandleTable() {} template -HandleTable::~HandleTable() { -} +HandleTable::~HandleTable() {} template size_t HandleTable::TableSize() { @@ -71,8 +71,7 @@ LRUHandle* HandleTable::Remove(const T1& key) { } template -LRUHandle* HandleTable::Insert(const T1& key, - LRUHandle* const handle) { +LRUHandle* HandleTable::Insert(const T1& key, LRUHandle* const handle) { LRUHandle* old = NULL; if (table_.find(key) != table_.end()) { old = table_[key]; @@ -82,7 +81,6 @@ LRUHandle* HandleTable::Insert(const T1& key, return old; } - template class LRUCache { public: @@ -94,10 +92,10 @@ class LRUCache { size_t Capacity(); void SetCapacity(size_t capacity); - Status Lookup(const T1& key, T2* value); - Status Insert(const T1& key, const T2& value, size_t charge = 1); - Status Remove(const T1& key); - Status Clear(); + rocksdb::Status Lookup(const T1& key, T2* value); + rocksdb::Status Insert(const T1& key, const T2& value, size_t charge = 1); + rocksdb::Status Remove(const T1& key); + rocksdb::Status Clear(); // Just for test bool LRUAndHandleTableConsistent(); @@ -125,10 +123,7 @@ class LRUCache { }; template -LRUCache::LRUCache() - : capacity_(0), - usage_(0), - size_(0) { +LRUCache::LRUCache() : capacity_(0), usage_(0), size_(0) { // Make empty circular linked lists. lru_.next = &lru_; lru_.prev = &lru_; @@ -165,21 +160,21 @@ void LRUCache::SetCapacity(size_t capacity) { } template -Status LRUCache::Lookup(const T1& key, T2* const value) { +rocksdb::Status LRUCache::Lookup(const T1& key, T2* const value) { pstd::MutexLock l(&mutex_); LRUHandle* handle = handle_table_.Lookup(key); if (handle != NULL) { LRU_MoveToHead(handle); *value = handle->value; } - return (handle == NULL) ? Status::NotFound() : Status::OK(); + return (handle == NULL) ? rocksdb::Status::NotFound() : rocksdb::Status::OK(); } template -Status LRUCache::Insert(const T1& key, const T2& value, size_t charge) { +rocksdb::Status LRUCache::Insert(const T1& key, const T2& value, size_t charge) { pstd::MutexLock l(&mutex_); if (capacity_ == 0) { - return Status::Corruption("capacity is empty"); + return rocksdb::Status::Corruption("capacity is empty"); } else { LRUHandle* handle = new LRUHandle(); handle->key = key; @@ -191,28 +186,28 @@ Status LRUCache::Insert(const T1& key, const T2& value, size_t charge) { FinishErase(handle_table_.Insert(key, handle)); LRU_Trim(); } - return Status::OK(); + return rocksdb::Status::OK(); } template -Status LRUCache::Remove(const T1& key) { +rocksdb::Status LRUCache::Remove(const T1& key) { pstd::MutexLock l(&mutex_); bool erased = FinishErase(handle_table_.Remove(key)); - return erased ? Status::OK() : Status::NotFound(); + return erased ? rocksdb::Status::OK() : rocksdb::Status::NotFound(); } template -Status LRUCache::Clear() { +rocksdb::Status LRUCache::Clear() { pstd::MutexLock l(&mutex_); LRUHandle* old = NULL; while (lru_.next != &lru_) { old = lru_.next; - bool erased = FinishErase(handle_table_.Remove(old->key)); - if (!erased) { // to avoid unused variable when compiled NDEBUG + bool erased = FinishErase(handle_table_.Remove(old->key)); + if (!erased) { // to avoid unused variable when compiled NDEBUG assert(erased); } } - return Status::OK(); + return rocksdb::Status::OK(); } template @@ -234,16 +229,14 @@ bool LRUCache::LRUAndHandleTableConsistent() { } template -bool LRUCache::LRUAsExpected( - const std::vector>& expect) { +bool LRUCache::LRUAsExpected(const std::vector>& expect) { if (Size() != expect.size()) { return false; } else { size_t idx = 0; LRUHandle* current = lru_.prev; while (current != &lru_) { - if (current->key != expect[idx].first - || current->value != expect[idx].second) { + if (current->key != expect[idx].first || current->value != expect[idx].second) { return false; } else { idx++; @@ -259,8 +252,8 @@ void LRUCache::LRU_Trim() { LRUHandle* old = NULL; while (usage_ > capacity_ && lru_.next != &lru_) { old = lru_.next; - bool erased = FinishErase(handle_table_.Remove(old->key)); - if (!erased) { // to avoid unused variable when compiled NDEBUG + bool erased = FinishErase(handle_table_.Remove(old->key)); + if (!erased) { // to avoid unused variable when compiled NDEBUG assert(erased); } } @@ -302,4 +295,3 @@ bool LRUCache::FinishErase(LRUHandle* const e) { } // namespace storage #endif // SRC_LRU_CACHE_H_ - diff --git a/src/storage/src/murmurhash.cc b/src/storage/src/murmurhash.cc index 9bb428f5c5..851a5ec264 100644 --- a/src/storage/src/murmurhash.cc +++ b/src/storage/src/murmurhash.cc @@ -20,44 +20,51 @@ // // 64-bit hash for 64-bit platforms -uint64_t MurmurHash64A(const void * key, int len, unsigned int seed) { - const uint64_t m = 0xc6a4a7935bd1e995; - const int r = 47; +uint64_t MurmurHash64A(const void* key, int len, unsigned int seed) { + const uint64_t m = 0xc6a4a7935bd1e995; + const int r = 47; - uint64_t h = seed ^ (len * m); + uint64_t h = seed ^ (len * m); - const uint64_t * data = (const uint64_t *)key; - const uint64_t * end = data + (len/8); + const uint64_t* data = (const uint64_t*)key; + const uint64_t* end = data + (len / 8); - while (data != end) { - uint64_t k = *data++; + while (data != end) { + uint64_t k = *data++; - k *= m; - k ^= k >> r; - k *= m; + k *= m; + k ^= k >> r; + k *= m; - h ^= k; - h *= m; - } - - const unsigned char * data2 = (const unsigned char*)data; - - switch (len & 7) { - case 7: h ^= ((uint64_t)data2[6]) << 48; // fallthrough - case 6: h ^= ((uint64_t)data2[5]) << 40; // fallthrough - case 5: h ^= ((uint64_t)data2[4]) << 32; // fallthrough - case 4: h ^= ((uint64_t)data2[3]) << 24; // fallthrough - case 3: h ^= ((uint64_t)data2[2]) << 16; // fallthrough - case 2: h ^= ((uint64_t)data2[1]) << 8; // fallthrough - case 1: h ^= ((uint64_t)data2[0]); - h *= m; - } - - h ^= h >> r; + h ^= k; h *= m; - h ^= h >> r; - - return h; + } + + const unsigned char* data2 = (const unsigned char*)data; + + switch (len & 7) { + case 7: + h ^= ((uint64_t)data2[6]) << 48; // fallthrough + case 6: + h ^= ((uint64_t)data2[5]) << 40; // fallthrough + case 5: + h ^= ((uint64_t)data2[4]) << 32; // fallthrough + case 4: + h ^= ((uint64_t)data2[3]) << 24; // fallthrough + case 3: + h ^= ((uint64_t)data2[2]) << 16; // fallthrough + case 2: + h ^= ((uint64_t)data2[1]) << 8; // fallthrough + case 1: + h ^= ((uint64_t)data2[0]); + h *= m; + } + + h ^= h >> r; + h *= m; + h ^= h >> r; + + return h; } #elif defined(__i386__) @@ -75,52 +82,55 @@ uint64_t MurmurHash64A(const void * key, int len, unsigned int seed) { // 2. It will not produce the same results on little-endian and big-endian // machines. -unsigned int MurmurHash2(const void * key, int len, unsigned int seed) { - // 'm' and 'r' are mixing constants generated offline. - // They're not really 'magic', they just happen to work well. +unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { + // 'm' and 'r' are mixing constants generated offline. + // They're not really 'magic', they just happen to work well. - const unsigned int m = 0x5bd1e995; - const int r = 24; + const unsigned int m = 0x5bd1e995; + const int r = 24; - // Initialize the hash to a 'random' value + // Initialize the hash to a 'random' value - unsigned int h = seed ^ len; + unsigned int h = seed ^ len; - // Mix 4 bytes at a time into the hash + // Mix 4 bytes at a time into the hash - const unsigned char * data = (const unsigned char *)key; + const unsigned char* data = (const unsigned char*)key; - while (len >= 4) { - unsigned int k = *(unsigned int *)data; + while (len >= 4) { + unsigned int k = *(unsigned int*)data; - k *= m; - k ^= k >> r; - k *= m; + k *= m; + k ^= k >> r; + k *= m; - h *= m; - h ^= k; + h *= m; + h ^= k; - data += 4; - len -= 4; - } + data += 4; + len -= 4; + } - // Handle the last few bytes of the input array + // Handle the last few bytes of the input array - switch (len) { - case 3: h ^= data[2] << 16; // fallthrough - case 2: h ^= data[1] << 8; // fallthrough - case 1: h ^= data[0]; - h *= m; - } + switch (len) { + case 3: + h ^= data[2] << 16; // fallthrough + case 2: + h ^= data[1] << 8; // fallthrough + case 1: + h ^= data[0]; + h *= m; + } - // Do a few final mixes of the hash to ensure the last few - // bytes are well-incorporated. + // Do a few final mixes of the hash to ensure the last few + // bytes are well-incorporated. - h ^= h >> 13; - h *= m; - h ^= h >> 15; + h ^= h >> 13; + h *= m; + h ^= h >> 15; - return h; + return h; } #else @@ -130,45 +140,48 @@ unsigned int MurmurHash2(const void * key, int len, unsigned int seed) { // Same as MurmurHash2, but endian- and alignment-neutral. // Half the speed though, alas. -unsigned int MurmurHashNeutral2(const void * key, int len, unsigned int seed) { - const unsigned int m = 0x5bd1e995; - const int r = 24; - - unsigned int h = seed ^ len; - - const unsigned char * data = (const unsigned char *)key; +unsigned int MurmurHashNeutral2(const void* key, int len, unsigned int seed) { + const unsigned int m = 0x5bd1e995; + const int r = 24; - while (len >= 4) { - unsigned int k; + unsigned int h = seed ^ len; - k = data[0]; - k |= data[1] << 8; - k |= data[2] << 16; - k |= data[3] << 24; + const unsigned char* data = (const unsigned char*)key; - k *= m; - k ^= k >> r; - k *= m; + while (len >= 4) { + unsigned int k; - h *= m; - h ^= k; + k = data[0]; + k |= data[1] << 8; + k |= data[2] << 16; + k |= data[3] << 24; - data += 4; - len -= 4; - } + k *= m; + k ^= k >> r; + k *= m; - switch (len) { - case 3: h ^= data[2] << 16; // fallthrough - case 2: h ^= data[1] << 8; // fallthrough - case 1: h ^= data[0]; - h *= m; - } - - h ^= h >> 13; h *= m; - h ^= h >> 15; - - return h; + h ^= k; + + data += 4; + len -= 4; + } + + switch (len) { + case 3: + h ^= data[2] << 16; // fallthrough + case 2: + h ^= data[1] << 8; // fallthrough + case 1: + h ^= data[0]; + h *= m; + } + + h ^= h >> 13; + h *= m; + h ^= h >> 15; + + return h; } #endif diff --git a/src/storage/src/murmurhash.h b/src/storage/src/murmurhash.h index dcb1fa7841..2a14711adb 100644 --- a/src/storage/src/murmurhash.h +++ b/src/storage/src/murmurhash.h @@ -16,21 +16,21 @@ #include "rocksdb/slice.h" #if defined(__x86_64__) -#define MURMUR_HASH MurmurHash64A -uint64_t MurmurHash64A(const void * key, int len, unsigned int seed); -#define MurmurHash MurmurHash64A +# define MURMUR_HASH MurmurHash64A +uint64_t MurmurHash64A(const void* key, int len, unsigned int seed); +# define MurmurHash MurmurHash64A typedef uint64_t murmur_t; #elif defined(__i386__) -#define MURMUR_HASH MurmurHash2 -unsigned int MurmurHash2(const void * key, int len, unsigned int seed); -#define MurmurHash MurmurHash2 +# define MURMUR_HASH MurmurHash2 +unsigned int MurmurHash2(const void* key, int len, unsigned int seed); +# define MurmurHash MurmurHash2 typedef unsigned int murmur_t; #else -#define MURMUR_HASH MurmurHashNeutral2 -unsigned int MurmurHashNeutral2(const void * key, int len, unsigned int seed); -#define MurmurHash MurmurHashNeutral2 +# define MURMUR_HASH MurmurHashNeutral2 +unsigned int MurmurHashNeutral2(const void* key, int len, unsigned int seed); +# define MurmurHash MurmurHashNeutral2 typedef unsigned int murmur_t; #endif @@ -38,9 +38,7 @@ typedef unsigned int murmur_t; namespace storage { using Slice = rocksdb::Slice; struct murmur_hash { - size_t operator()(const Slice& slice) const { - return MurmurHash(slice.data(), static_cast(slice.size()), 0); - } + size_t operator()(const Slice& slice) const { return MurmurHash(slice.data(), static_cast(slice.size()), 0); } }; -} // storage +} // namespace storage #endif // SRC_MURMURHASH_H_ diff --git a/src/storage/src/mutex.h b/src/storage/src/mutex.h index 5c271dba22..e99d4313c5 100644 --- a/src/storage/src/mutex.h +++ b/src/storage/src/mutex.h @@ -59,8 +59,7 @@ class CondVar { // Returns other status if Storage should otherwis stop waiting and // fail the operation. // May return OK spuriously even if not notified. - virtual Status WaitFor(std::shared_ptr mutex, - int64_t timeout_time) = 0; + virtual Status WaitFor(std::shared_ptr mutex, int64_t timeout_time) = 0; // If any threads are waiting on *this, unblock at least one of the // waiting threads. diff --git a/src/storage/src/mutex_impl.cc b/src/storage/src/mutex_impl.cc index 2ddbdc875c..06a378c218 100644 --- a/src/storage/src/mutex_impl.cc +++ b/src/storage/src/mutex_impl.cc @@ -3,7 +3,6 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. - #include #include @@ -36,8 +35,7 @@ class CondVarImpl : public CondVar { Status Wait(std::shared_ptr mutex) override; - Status WaitFor(std::shared_ptr mutex, - int64_t timeout_time) override; + Status WaitFor(std::shared_ptr mutex, int64_t timeout_time) override; void Notify() override { cv_.notify_one(); } @@ -47,15 +45,9 @@ class CondVarImpl : public CondVar { std::condition_variable cv_; }; -std::shared_ptr -MutexFactoryImpl::AllocateMutex() { - return std::shared_ptr(new MutexImpl()); -} +std::shared_ptr MutexFactoryImpl::AllocateMutex() { return std::shared_ptr(new MutexImpl()); } -std::shared_ptr -MutexFactoryImpl::AllocateCondVar() { - return std::shared_ptr(new CondVarImpl()); -} +std::shared_ptr MutexFactoryImpl::AllocateCondVar() { return std::shared_ptr(new CondVarImpl()); } Status MutexImpl::Lock() { mutex_.lock(); @@ -86,8 +78,7 @@ Status MutexImpl::TryLockFor(int64_t timeout_time) { return Status::OK(); } -Status CondVarImpl::Wait( - std::shared_ptr mutex) { +Status CondVarImpl::Wait(std::shared_ptr mutex) { auto mutex_impl = reinterpret_cast(mutex.get()); std::unique_lock lock(mutex_impl->mutex_, std::adopt_lock); @@ -99,8 +90,7 @@ Status CondVarImpl::Wait( return Status::OK(); } -Status CondVarImpl::WaitFor( - std::shared_ptr mutex, int64_t timeout_time) { +Status CondVarImpl::WaitFor(std::shared_ptr mutex, int64_t timeout_time) { Status s; auto mutex_impl = reinterpret_cast(mutex.get()); diff --git a/src/storage/src/options_helper.cc b/src/storage/src/options_helper.cc index 050ca55891..43e1ac4d99 100644 --- a/src/storage/src/options_helper.cc +++ b/src/storage/src/options_helper.cc @@ -20,7 +20,7 @@ static bool strToInt(const std::string& value, int* num, int base = 10) { static bool strToUint64(const std::string& value, uint64_t* num, int base = 10) { size_t end; *num = std::stoull(value, &end, base); - return end < value.size() ? false : true; + return end < value.size() ? false : true; } // strToUint32 may throw exception @@ -37,9 +37,7 @@ static bool strToUint32(const std::string& value, uint32_t* num, int base = 10) return true; } - -bool ParseOptionMember(const MemberType& member_type, - const std::string& value, char* member_address) { +bool ParseOptionMember(const MemberType& member_type, const std::string& value, char* member_address) { switch (member_type) { case MemberType::kInt: { int intVal; diff --git a/src/storage/src/options_helper.h b/src/storage/src/options_helper.h index 90232fc899..8ef81e2434 100644 --- a/src/storage/src/options_helper.h +++ b/src/storage/src/options_helper.h @@ -37,7 +37,8 @@ inline int offset_of(T1 T2::*member) { static std::unordered_map mutable_db_options_member_type_info = { {"max_background_jobs", {offsetof(struct rocksdb::DBOptions, max_background_jobs), MemberType::kInt}}, {"max_background_compactions", {offsetof(struct rocksdb::DBOptions, max_background_compactions), MemberType::kInt}}, - // {"base_background_compactions", {offsetof(struct rocksdb::DBOptions, base_background_compactions), MemberType::kInt}}, + // {"base_background_compactions", {offsetof(struct rocksdb::DBOptions, base_background_compactions), + // MemberType::kInt}}, {"max_open_files", {offsetof(struct rocksdb::DBOptions, max_open_files), MemberType::kInt}}, {"bytes_per_sync", {offsetof(struct rocksdb::DBOptions, bytes_per_sync), MemberType::kUint64T}}, {"delayed_write_rate", {offsetof(struct rocksdb::DBOptions, delayed_write_rate), MemberType::kUint64T}}, @@ -50,19 +51,23 @@ static std::unordered_map mutable_cf_options_member {"max_write_buffer_number", {offset_of(&rocksdb::ColumnFamilyOptions::max_write_buffer_number), MemberType::kInt}}, {"write_buffer_size", {offset_of(&rocksdb::ColumnFamilyOptions::write_buffer_size), MemberType::kSizeT}}, {"target_file_size_base", {offset_of(&rocksdb::ColumnFamilyOptions::target_file_size_base), MemberType::kUint64T}}, - {"target_file_size_multiplier", {offset_of(&rocksdb::ColumnFamilyOptions::target_file_size_multiplier), MemberType::kInt}}, + {"target_file_size_multiplier", + {offset_of(&rocksdb::ColumnFamilyOptions::target_file_size_multiplier), MemberType::kInt}}, {"arena_block_size", {offset_of(&rocksdb::ColumnFamilyOptions::arena_block_size), MemberType::kSizeT}}, - {"level0_file_num_compaction_trigger", {offset_of(&rocksdb::ColumnFamilyOptions::level0_file_num_compaction_trigger), MemberType::kInt}}, - {"level0_slowdown_writes_trigger", {offset_of(&rocksdb::ColumnFamilyOptions::level0_slowdown_writes_trigger), MemberType::kInt}}, - {"level0_stop_writes_trigger", {offset_of(&rocksdb::ColumnFamilyOptions::level0_stop_writes_trigger), MemberType::kInt}}, + {"level0_file_num_compaction_trigger", + {offset_of(&rocksdb::ColumnFamilyOptions::level0_file_num_compaction_trigger), MemberType::kInt}}, + {"level0_slowdown_writes_trigger", + {offset_of(&rocksdb::ColumnFamilyOptions::level0_slowdown_writes_trigger), MemberType::kInt}}, + {"level0_stop_writes_trigger", + {offset_of(&rocksdb::ColumnFamilyOptions::level0_stop_writes_trigger), MemberType::kInt}}, {"max_compaction_bytes", {offset_of(&rocksdb::ColumnFamilyOptions::max_compaction_bytes), MemberType::kUint64T}}, - {"soft_pending_compaction_bytes_limit", {offset_of(&rocksdb::ColumnFamilyOptions::soft_pending_compaction_bytes_limit), MemberType::kUint64T}}, - {"hard_pending_compaction_bytes_limit", {offset_of(&rocksdb::ColumnFamilyOptions::hard_pending_compaction_bytes_limit), MemberType::kUint64T}}, + {"soft_pending_compaction_bytes_limit", + {offset_of(&rocksdb::ColumnFamilyOptions::soft_pending_compaction_bytes_limit), MemberType::kUint64T}}, + {"hard_pending_compaction_bytes_limit", + {offset_of(&rocksdb::ColumnFamilyOptions::hard_pending_compaction_bytes_limit), MemberType::kUint64T}}, }; -extern bool ParseOptionMember(const MemberType& member_type, - const std::string& value, - char* member_address); +extern bool ParseOptionMember(const MemberType& member_type, const std::string& value, char* member_address); } // namespace storage #endif // SRC_OPTIONS_HELPER_H diff --git a/src/storage/src/redis.cc b/src/storage/src/redis.cc index 185d743924..e69df57f1d 100644 --- a/src/storage/src/redis.cc +++ b/src/storage/src/redis.cc @@ -33,21 +33,14 @@ Redis::~Redis() { delete scan_cursors_store_; } -Status Redis::GetScanStartPoint(const Slice& key, - const Slice& pattern, - int64_t cursor, - std::string* start_point) { - std::string index_key = key.ToString() + "_" - + pattern.ToString() + "_" + std::to_string(cursor); +Status Redis::GetScanStartPoint(const Slice& key, const Slice& pattern, int64_t cursor, std::string* start_point) { + std::string index_key = key.ToString() + "_" + pattern.ToString() + "_" + std::to_string(cursor); return scan_cursors_store_->Lookup(index_key, start_point); } -Status Redis::StoreScanNextPoint(const Slice& key, - const Slice& pattern, - int64_t cursor, +Status Redis::StoreScanNextPoint(const Slice& key, const Slice& pattern, int64_t cursor, const std::string& next_point) { - std::string index_key = key.ToString() + "_" - + pattern.ToString() + "_" + std::to_string(cursor); + std::string index_key = key.ToString() + "_" + pattern.ToString() + "_" + std::to_string(cursor); return scan_cursors_store_->Insert(index_key, next_point); } @@ -61,8 +54,7 @@ Status Redis::SetSmallCompactionThreshold(size_t small_compaction_threshold) { return Status::OK(); } -Status Redis::UpdateSpecificKeyStatistics(const std::string& key, - size_t count) { +Status Redis::UpdateSpecificKeyStatistics(const std::string& key, size_t count) { if (statistics_store_->Capacity() && count) { size_t total = 0; statistics_store_->Lookup(key, &total); @@ -72,8 +64,7 @@ Status Redis::UpdateSpecificKeyStatistics(const std::string& key, return Status::OK(); } -Status Redis::AddCompactKeyTaskIfNeeded(const std::string& key, - size_t total) { +Status Redis::AddCompactKeyTaskIfNeeded(const std::string& key, size_t total) { if (total < small_compaction_threshold_) { return Status::OK(); } else { @@ -83,8 +74,7 @@ Status Redis::AddCompactKeyTaskIfNeeded(const std::string& key, return Status::OK(); } -Status Redis::SetOptions(const OptionType& option_type, - const std::unordered_map& options) { +Status Redis::SetOptions(const OptionType& option_type, const std::unordered_map& options) { if (option_type == OptionType::kDB) { return db_->SetDBOptions(options); } @@ -94,7 +84,7 @@ Status Redis::SetOptions(const OptionType& option_type, Status s; for (auto handle : handles_) { s = db_->SetOptions(handle, options); - if(!s.ok()) break; + if (!s.ok()) break; } return s; } diff --git a/src/storage/src/redis.h b/src/storage/src/redis.h index bb15907347..5ac9a6416e 100644 --- a/src/storage/src/redis.h +++ b/src/storage/src/redis.h @@ -6,13 +6,13 @@ #ifndef SRC_REDIS_H_ #define SRC_REDIS_H_ -#include #include +#include #include #include "rocksdb/db.h" -#include "rocksdb/status.h" #include "rocksdb/slice.h" +#include "rocksdb/status.h" #include "src/lock_mgr.h" #include "src/lru_cache.h" @@ -28,39 +28,27 @@ class Redis { Redis(Storage* const storage, const DataType& type); virtual ~Redis(); - rocksdb::DB* GetDB() { - return db_; - } + rocksdb::DB* GetDB() { return db_; } Status SetOptions(const OptionType& option_type, const std::unordered_map& options); // Common Commands - virtual Status Open(const StorageOptions& storage_options, - const std::string& db_path) = 0; - virtual Status CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, + virtual Status Open(const StorageOptions& storage_options, const std::string& db_path) = 0; + virtual Status CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type = kMetaAndData) = 0; virtual Status GetProperty(const std::string& property, uint64_t* out) = 0; virtual Status ScanKeyNum(KeyInfo* key_info) = 0; - virtual Status ScanKeys(const std::string& pattern, - std::vector* keys) = 0; + virtual Status ScanKeys(const std::string& pattern, std::vector* keys) = 0; virtual Status PKPatternMatchDel(const std::string& pattern, int32_t* ret) = 0; // Keys Commands virtual Status Expire(const Slice& key, int32_t ttl) = 0; virtual Status Del(const Slice& key) = 0; - virtual bool Scan(const std::string& start_key, - const std::string& pattern, - std::vector* keys, - int64_t* count, - std::string* next_key) = 0; - virtual bool PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) = 0; - virtual Status Expireat(const Slice& key, - int32_t timestamp) = 0; + virtual bool Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, + int64_t* count, std::string* next_key) = 0; + virtual bool PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) = 0; + virtual Status Expireat(const Slice& key, int32_t timestamp) = 0; virtual Status Persist(const Slice& key) = 0; virtual Status TTL(const Slice& key, int64_t* timestamp) = 0; @@ -80,10 +68,8 @@ class Redis { // For Scan LRUCache* scan_cursors_store_; - Status GetScanStartPoint(const Slice& key, const Slice& pattern, - int64_t cursor, std::string* start_point); - Status StoreScanNextPoint(const Slice& key, const Slice& pattern, - int64_t cursor, const std::string& next_point); + Status GetScanStartPoint(const Slice& key, const Slice& pattern, int64_t cursor, std::string* start_point); + Status StoreScanNextPoint(const Slice& key, const Slice& pattern, int64_t cursor, const std::string& next_point); // For Statistics std::atomic small_compaction_threshold_; @@ -95,4 +81,3 @@ class Redis { } // namespace storage #endif // SRC_REDIS_H_ - diff --git a/src/storage/src/redis_hashes.cc b/src/storage/src/redis_hashes.cc index b6aae0f4f7..375c27eee3 100644 --- a/src/storage/src/redis_hashes.cc +++ b/src/storage/src/redis_hashes.cc @@ -7,19 +7,16 @@ #include -#include "storage/util.h" #include "src/base_filter.h" #include "src/scope_record_lock.h" #include "src/scope_snapshot.h" +#include "storage/util.h" namespace storage { -RedisHashes::RedisHashes(Storage* const s, const DataType& type) - : Redis(s, type) { -} +RedisHashes::RedisHashes(Storage* const s, const DataType& type) : Redis(s, type) {} -Status RedisHashes::Open(const StorageOptions& storage_options, - const std::string& db_path) { +Status RedisHashes::Open(const StorageOptions& storage_options, const std::string& db_path) { statistics_store_->SetCapacity(storage_options.statistics_max_size); small_compaction_threshold_ = storage_options.small_compaction_threshold; @@ -28,8 +25,7 @@ Status RedisHashes::Open(const StorageOptions& storage_options, if (s.ok()) { // create column family rocksdb::ColumnFamilyHandle* cf; - s = db_->CreateColumnFamily(rocksdb::ColumnFamilyOptions(), - "data_cf", &cf); + s = db_->CreateColumnFamily(rocksdb::ColumnFamilyOptions(), "data_cf", &cf); if (!s.ok()) { return s; } @@ -42,10 +38,8 @@ Status RedisHashes::Open(const StorageOptions& storage_options, rocksdb::DBOptions db_ops(storage_options.options); rocksdb::ColumnFamilyOptions meta_cf_ops(storage_options.options); rocksdb::ColumnFamilyOptions data_cf_ops(storage_options.options); - meta_cf_ops.compaction_filter_factory = - std::make_shared(); - data_cf_ops.compaction_filter_factory = - std::make_shared(&db_, &handles_); + meta_cf_ops.compaction_filter_factory = std::make_shared(); + data_cf_ops.compaction_filter_factory = std::make_shared(&db_, &handles_); // use the bloom filter policy to reduce disk reads rocksdb::BlockBasedTableOptions table_ops(storage_options.table_options); @@ -53,29 +47,21 @@ Status RedisHashes::Open(const StorageOptions& storage_options, rocksdb::BlockBasedTableOptions meta_cf_table_ops(table_ops); rocksdb::BlockBasedTableOptions data_cf_table_ops(table_ops); if (!storage_options.share_block_cache && storage_options.block_cache_size > 0) { - meta_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); - data_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); + meta_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); + data_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); } - meta_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); - data_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(data_cf_table_ops)); + meta_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); + data_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(data_cf_table_ops)); std::vector column_families; // Meta CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor(rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); // Data CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - "data_cf", data_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor("data_cf", data_cf_ops)); return rocksdb::DB::Open(db_ops, db_path, column_families, &handles_, &db_); } -Status RedisHashes::CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, - const ColumnFamilyType& type) { +Status RedisHashes::CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type) { if (type == kMeta || type == kMetaAndData) { db_->CompactRange(default_compact_range_options_, handles_[0], begin, end); } @@ -110,12 +96,9 @@ Status RedisHashes::ScanKeyNum(KeyInfo* key_info) { rocksdb::Env::Default()->GetCurrentTime(&curtime); rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedHashesMetaValue parsed_hashes_meta_value(iter->value()); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { invaild_keys++; } else { keys++; @@ -134,8 +117,7 @@ Status RedisHashes::ScanKeyNum(KeyInfo* key_info) { return Status::OK(); } -Status RedisHashes::ScanKeys(const std::string& pattern, - std::vector* keys) { +Status RedisHashes::ScanKeys(const std::string& pattern, std::vector* keys) { std::string key; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -144,15 +126,11 @@ Status RedisHashes::ScanKeys(const std::string& pattern, iterator_options.fill_cache = false; rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedHashesMetaValue parsed_hashes_meta_value(iter->value()); - if (!parsed_hashes_meta_value.IsStale() - && parsed_hashes_meta_value.count() != 0) { + if (!parsed_hashes_meta_value.IsStale() && parsed_hashes_meta_value.count() != 0) { key = iter->key().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } } @@ -161,8 +139,7 @@ Status RedisHashes::ScanKeys(const std::string& pattern, return Status::OK(); } -Status RedisHashes::PKPatternMatchDel(const std::string& pattern, - int32_t* ret) { +Status RedisHashes::PKPatternMatchDel(const std::string& pattern, int32_t* ret) { rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); @@ -180,9 +157,8 @@ Status RedisHashes::PKPatternMatchDel(const std::string& pattern, key = iter->key().ToString(); meta_value = iter->value().ToString(); ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (!parsed_hashes_meta_value.IsStale() - && parsed_hashes_meta_value.count() - && StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { + if (!parsed_hashes_meta_value.IsStale() && parsed_hashes_meta_value.count() && + StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { parsed_hashes_meta_value.InitialMetaValue(); batch.Put(handles_[0], key, meta_value); } @@ -210,9 +186,7 @@ Status RedisHashes::PKPatternMatchDel(const std::string& pattern, return s; } -Status RedisHashes::HDel(const Slice& key, - const std::vector& fields, - int32_t* ret) { +Status RedisHashes::HDel(const Slice& key, const std::vector& fields, int32_t* ret) { uint32_t statistic = 0; std::vector filtered_fields; std::unordered_set field_set; @@ -237,8 +211,7 @@ Status RedisHashes::HDel(const Slice& key, Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { *ret = 0; return Status::OK(); } else { @@ -246,8 +219,7 @@ Status RedisHashes::HDel(const Slice& key, version = parsed_hashes_meta_value.version(); for (const auto& field : filtered_fields) { HashesDataKey hashes_data_key(key, version, field); - s = db_->Get(read_options, handles_[1], - hashes_data_key.Encode(), &data_value); + s = db_->Get(read_options, handles_[1], hashes_data_key.Encode(), &data_value); if (s.ok()) { del_cnt++; statistic++; @@ -278,8 +250,7 @@ Status RedisHashes::HExists(const Slice& key, const Slice& field) { return HGet(key, field, &value); } -Status RedisHashes::HGet(const Slice& key, const Slice& field, - std::string* value) { +Status RedisHashes::HGet(const Slice& key, const Slice& field, std::string* value) { std::string meta_value; int32_t version = 0; rocksdb::ReadOptions read_options; @@ -302,8 +273,7 @@ Status RedisHashes::HGet(const Slice& key, const Slice& field, return s; } -Status RedisHashes::HGetall(const Slice& key, - std::vector* fvs) { +Status RedisHashes::HGetall(const Slice& key, std::vector* fvs) { rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; @@ -323,12 +293,9 @@ Status RedisHashes::HGetall(const Slice& key, HashesDataKey hashes_data_key(key, version, ""); Slice prefix = hashes_data_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); - fvs->push_back({parsed_hashes_data_key.field().ToString(), - iter->value().ToString()}); + fvs->push_back({parsed_hashes_data_key.field().ToString(), iter->value().ToString()}); } delete iter; } @@ -336,8 +303,7 @@ Status RedisHashes::HGetall(const Slice& key, return s; } -Status RedisHashes::HIncrby(const Slice& key, const Slice& field, int64_t value, - int64_t* ret) { +Status RedisHashes::HIncrby(const Slice& key, const Slice& field, int64_t value, int64_t* ret) { *ret = 0; rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -350,8 +316,7 @@ Status RedisHashes::HIncrby(const Slice& key, const Slice& field, int64_t value, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { version = parsed_hashes_meta_value.UpdateVersion(); parsed_hashes_meta_value.set_count(1); parsed_hashes_meta_value.set_timestamp(0); @@ -364,15 +329,13 @@ Status RedisHashes::HIncrby(const Slice& key, const Slice& field, int64_t value, } else { version = parsed_hashes_meta_value.version(); HashesDataKey hashes_data_key(key, version, field); - s = db_->Get(default_read_options_, handles_[1], - hashes_data_key.Encode(), &old_value); + s = db_->Get(default_read_options_, handles_[1], hashes_data_key.Encode(), &old_value); if (s.ok()) { int64_t ival = 0; if (!StrToInt64(old_value.data(), old_value.size(), &ival)) { return Status::Corruption("hash value is not an integer"); } - if ((value >= 0 && LLONG_MAX - value < ival) || - (value < 0 && LLONG_MIN - value > ival)) { + if ((value >= 0 && LLONG_MAX - value < ival) || (value < 0 && LLONG_MIN - value > ival)) { return Status::InvalidArgument("Overflow"); } *ret = ival + value; @@ -411,8 +374,7 @@ Status RedisHashes::HIncrby(const Slice& key, const Slice& field, int64_t value, return s; } -Status RedisHashes::HIncrbyfloat(const Slice& key, const Slice& field, - const Slice& by, std::string* new_value) { +Status RedisHashes::HIncrbyfloat(const Slice& key, const Slice& field, const Slice& by, std::string* new_value) { new_value->clear(); rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -430,8 +392,7 @@ Status RedisHashes::HIncrbyfloat(const Slice& key, const Slice& field, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { version = parsed_hashes_meta_value.UpdateVersion(); parsed_hashes_meta_value.set_count(1); parsed_hashes_meta_value.set_timestamp(0); @@ -443,13 +404,11 @@ Status RedisHashes::HIncrbyfloat(const Slice& key, const Slice& field, } else { version = parsed_hashes_meta_value.version(); HashesDataKey hashes_data_key(key, version, field); - s = db_->Get(default_read_options_, handles_[1], - hashes_data_key.Encode(), &old_value_str); + s = db_->Get(default_read_options_, handles_[1], hashes_data_key.Encode(), &old_value_str); if (s.ok()) { long double total; long double old_value; - if (StrToLongDouble(old_value_str.data(), - old_value_str.size(), &old_value) == -1) { + if (StrToLongDouble(old_value_str.data(), old_value_str.size(), &old_value) == -1) { return Status::Corruption("value is not a vaild float"); } @@ -486,8 +445,7 @@ Status RedisHashes::HIncrbyfloat(const Slice& key, const Slice& field, return s; } -Status RedisHashes::HKeys(const Slice& key, - std::vector* fields) { +Status RedisHashes::HKeys(const Slice& key, std::vector* fields) { rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; @@ -507,9 +465,7 @@ Status RedisHashes::HKeys(const Slice& key, HashesDataKey hashes_data_key(key, version, ""); Slice prefix = hashes_data_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); fields->push_back(parsed_hashes_data_key.field().ToString()); } @@ -539,9 +495,7 @@ Status RedisHashes::HLen(const Slice& key, int32_t* ret) { return s; } -Status RedisHashes::HMGet(const Slice& key, - const std::vector& fields, - std::vector* vss) { +Status RedisHashes::HMGet(const Slice& key, const std::vector& fields, std::vector* vss) { vss->clear(); int32_t version = 0; @@ -555,8 +509,7 @@ Status RedisHashes::HMGet(const Slice& key, Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if ((is_stale = parsed_hashes_meta_value.IsStale()) - || parsed_hashes_meta_value.count() == 0) { + if ((is_stale = parsed_hashes_meta_value.IsStale()) || parsed_hashes_meta_value.count() == 0) { for (size_t idx = 0; idx < fields.size(); ++idx) { vss->push_back({std::string(), Status::NotFound()}); } @@ -565,8 +518,7 @@ Status RedisHashes::HMGet(const Slice& key, version = parsed_hashes_meta_value.version(); for (const auto& field : fields) { HashesDataKey hashes_data_key(key, version, field); - s = db_->Get(read_options, handles_[1], - hashes_data_key.Encode(), &value); + s = db_->Get(read_options, handles_[1], hashes_data_key.Encode(), &value); if (s.ok()) { vss->push_back({value, Status::OK()}); } else if (s.IsNotFound()) { @@ -586,8 +538,7 @@ Status RedisHashes::HMGet(const Slice& key, return s; } -Status RedisHashes::HMSet(const Slice& key, - const std::vector& fvs) { +Status RedisHashes::HMSet(const Slice& key, const std::vector& fvs) { uint32_t statistic = 0; std::unordered_set fields; std::vector filtered_fvs; @@ -607,8 +558,7 @@ Status RedisHashes::HMSet(const Slice& key, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { version = parsed_hashes_meta_value.InitialMetaValue(); parsed_hashes_meta_value.set_count(filtered_fvs.size()); batch.Put(handles_[0], key, meta_value); @@ -622,8 +572,7 @@ Status RedisHashes::HMSet(const Slice& key, version = parsed_hashes_meta_value.version(); for (const auto& fv : filtered_fvs) { HashesDataKey hashes_data_key(key, version, fv.field); - s = db_->Get(default_read_options_, handles_[1], - hashes_data_key.Encode(), &data_value); + s = db_->Get(default_read_options_, handles_[1], hashes_data_key.Encode(), &data_value); if (s.ok()) { statistic++; batch.Put(handles_[1], hashes_data_key.Encode(), fv.value); @@ -653,8 +602,7 @@ Status RedisHashes::HMSet(const Slice& key, return s; } -Status RedisHashes::HSet(const Slice& key, const Slice& field, - const Slice& value, int32_t* res) { +Status RedisHashes::HSet(const Slice& key, const Slice& field, const Slice& value, int32_t* res) { rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -664,8 +612,7 @@ Status RedisHashes::HSet(const Slice& key, const Slice& field, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { version = parsed_hashes_meta_value.InitialMetaValue(); parsed_hashes_meta_value.set_count(1); batch.Put(handles_[0], key, meta_value); @@ -676,8 +623,7 @@ Status RedisHashes::HSet(const Slice& key, const Slice& field, version = parsed_hashes_meta_value.version(); std::string data_value; HashesDataKey hashes_data_key(key, version, field); - s = db_->Get(default_read_options_, - handles_[1], hashes_data_key.Encode(), &data_value); + s = db_->Get(default_read_options_, handles_[1], hashes_data_key.Encode(), &data_value); if (s.ok()) { *res = 0; if (data_value == value.ToString()) { @@ -712,8 +658,7 @@ Status RedisHashes::HSet(const Slice& key, const Slice& field, return s; } -Status RedisHashes::HSetnx(const Slice& key, const Slice& field, - const Slice& value, int32_t* ret) { +Status RedisHashes::HSetnx(const Slice& key, const Slice& field, const Slice& value, int32_t* ret) { rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -722,8 +667,7 @@ Status RedisHashes::HSetnx(const Slice& key, const Slice& field, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { version = parsed_hashes_meta_value.InitialMetaValue(); parsed_hashes_meta_value.set_count(1); batch.Put(handles_[0], key, meta_value); @@ -734,8 +678,7 @@ Status RedisHashes::HSetnx(const Slice& key, const Slice& field, version = parsed_hashes_meta_value.version(); HashesDataKey hashes_data_key(key, version, field); std::string data_value; - s = db_->Get(default_read_options_, handles_[1], - hashes_data_key.Encode(), &data_value); + s = db_->Get(default_read_options_, handles_[1], hashes_data_key.Encode(), &data_value); if (s.ok()) { *ret = 0; } else if (s.IsNotFound()) { @@ -762,8 +705,7 @@ Status RedisHashes::HSetnx(const Slice& key, const Slice& field, return db_->Write(default_write_options_, &batch); } -Status RedisHashes::HVals(const Slice& key, - std::vector* values) { +Status RedisHashes::HVals(const Slice& key, std::vector* values) { rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; @@ -783,9 +725,7 @@ Status RedisHashes::HVals(const Slice& key, HashesDataKey hashes_data_key(key, version, ""); Slice prefix = hashes_data_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { values->push_back(iter->value().ToString()); } delete iter; @@ -794,8 +734,7 @@ Status RedisHashes::HVals(const Slice& key, return s; } -Status RedisHashes::HStrlen(const Slice& key, - const Slice& field, int32_t* len) { +Status RedisHashes::HStrlen(const Slice& key, const Slice& field, int32_t* len) { std::string value; Status s = HGet(key, field, &value); if (s.ok()) { @@ -806,12 +745,8 @@ Status RedisHashes::HStrlen(const Slice& key, return s; } -Status RedisHashes::HScan(const Slice& key, - int64_t cursor, - const std::string& pattern, - int64_t count, - std::vector* field_values, - int64_t* next_cursor) { +Status RedisHashes::HScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* field_values, int64_t* next_cursor) { *next_cursor = 0; field_values->clear(); if (cursor < 0) { @@ -830,8 +765,7 @@ Status RedisHashes::HScan(const Slice& key, Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { *next_cursor = 0; return Status::NotFound(); } else { @@ -853,21 +787,17 @@ Status RedisHashes::HScan(const Slice& key, HashesDataKey hashes_start_data_key(key, version, start_point); std::string prefix = hashes_data_prefix.Encode().ToString(); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(hashes_start_data_key.Encode()); - iter->Valid() && rest > 0 && iter->key().starts_with(prefix); + for (iter->Seek(hashes_start_data_key.Encode()); iter->Valid() && rest > 0 && iter->key().starts_with(prefix); iter->Next()) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); std::string field = parsed_hashes_data_key.field().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), field.data(), field.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), field.data(), field.size(), 0)) { field_values->push_back({field, iter->value().ToString()}); } rest--; } - if (iter->Valid() - && (iter->key().compare(prefix) <= 0 - || iter->key().starts_with(prefix))) { + if (iter->Valid() && (iter->key().compare(prefix) <= 0 || iter->key().starts_with(prefix))) { *next_cursor = cursor + step_length; ParsedHashesDataKey parsed_hashes_data_key(iter->key()); std::string next_field = parsed_hashes_data_key.field().ToString(); @@ -884,11 +814,8 @@ Status RedisHashes::HScan(const Slice& key, return Status::OK(); } -Status RedisHashes::HScanx(const Slice& key, - const std::string start_field, - const std::string& pattern, - int64_t count, std::vector* field_values, - std::string* next_field) { +Status RedisHashes::HScanx(const Slice& key, const std::string start_field, const std::string& pattern, int64_t count, + std::vector* field_values, std::string* next_field) { next_field->clear(); field_values->clear(); @@ -901,8 +828,7 @@ Status RedisHashes::HScanx(const Slice& key, Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { *next_field = ""; return Status::NotFound(); } else { @@ -911,13 +837,11 @@ Status RedisHashes::HScanx(const Slice& key, HashesDataKey hashes_start_data_key(key, version, start_field); std::string prefix = hashes_data_prefix.Encode().ToString(); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(hashes_start_data_key.Encode()); - iter->Valid() && rest > 0 && iter->key().starts_with(prefix); + for (iter->Seek(hashes_start_data_key.Encode()); iter->Valid() && rest > 0 && iter->key().starts_with(prefix); iter->Next()) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); std::string field = parsed_hashes_data_key.field().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), field.data(), field.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), field.data(), field.size(), 0)) { field_values->push_back({field, iter->value().ToString()}); } rest--; @@ -938,12 +862,8 @@ Status RedisHashes::HScanx(const Slice& key, return Status::OK(); } -Status RedisHashes::PKHScanRange(const Slice& key, - const Slice& field_start, - const std::string& field_end, - const Slice& pattern, - int32_t limit, - std::vector* field_values, +Status RedisHashes::PKHScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, + const Slice& pattern, int32_t limit, std::vector* field_values, std::string* next_field) { next_field->clear(); field_values->clear(); @@ -958,17 +878,14 @@ Status RedisHashes::PKHScanRange(const Slice& key, bool start_no_limit = !field_start.compare(""); bool end_no_limit = !field_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (field_start.compare(field_end) > 0)) { + if (!start_no_limit && !end_no_limit && (field_start.compare(field_end) > 0)) { return Status::InvalidArgument("error in given range"); } Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { return Status::NotFound(); } else { int32_t version = parsed_hashes_meta_value.version(); @@ -977,15 +894,13 @@ Status RedisHashes::PKHScanRange(const Slice& key, std::string prefix = hashes_data_prefix.Encode().ToString(); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); for (iter->Seek(start_no_limit ? prefix : hashes_start_data_key.Encode()); - iter->Valid() && remain > 0 && iter->key().starts_with(prefix); - iter->Next()) { + iter->Valid() && remain > 0 && iter->key().starts_with(prefix); iter->Next()) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); std::string field = parsed_hashes_data_key.field().ToString(); if (!end_no_limit && field.compare(field_end) > 0) { break; } - if (StringMatch(pattern.data(), - pattern.size(), field.data(), field.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), field.data(), field.size(), 0)) { field_values->push_back({field, iter->value().ToString()}); } remain--; @@ -993,8 +908,7 @@ Status RedisHashes::PKHScanRange(const Slice& key, if (iter->Valid() && iter->key().starts_with(prefix)) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); - if (end_no_limit - || parsed_hashes_data_key.field().compare(field_end) <= 0) { + if (end_no_limit || parsed_hashes_data_key.field().compare(field_end) <= 0) { *next_field = parsed_hashes_data_key.field().ToString(); } } @@ -1006,12 +920,8 @@ Status RedisHashes::PKHScanRange(const Slice& key, return Status::OK(); } -Status RedisHashes::PKHRScanRange(const Slice& key, - const Slice& field_start, - const std::string& field_end, - const Slice& pattern, - int32_t limit, - std::vector* field_values, +Status RedisHashes::PKHRScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, + const Slice& pattern, int32_t limit, std::vector* field_values, std::string* next_field) { next_field->clear(); field_values->clear(); @@ -1026,38 +936,31 @@ Status RedisHashes::PKHRScanRange(const Slice& key, bool start_no_limit = !field_start.compare(""); bool end_no_limit = !field_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (field_start.compare(field_end) < 0)) { + if (!start_no_limit && !end_no_limit && (field_start.compare(field_end) < 0)) { return Status::InvalidArgument("error in given range"); } Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedHashesMetaValue parsed_hashes_meta_value(&meta_value); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { return Status::NotFound(); } else { int32_t version = parsed_hashes_meta_value.version(); int32_t start_key_version = start_no_limit ? version + 1 : version; - std::string start_key_field = start_no_limit ? - "" : field_start.ToString(); + std::string start_key_field = start_no_limit ? "" : field_start.ToString(); HashesDataKey hashes_data_prefix(key, version, Slice()); - HashesDataKey hashes_start_data_key( - key, start_key_version, start_key_field); + HashesDataKey hashes_start_data_key(key, start_key_version, start_key_field); std::string prefix = hashes_data_prefix.Encode().ToString(); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); for (iter->SeekForPrev(hashes_start_data_key.Encode().ToString()); - iter->Valid() && remain > 0 && iter->key().starts_with(prefix); - iter->Prev()) { + iter->Valid() && remain > 0 && iter->key().starts_with(prefix); iter->Prev()) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); std::string field = parsed_hashes_data_key.field().ToString(); if (!end_no_limit && field.compare(field_end) < 0) { break; } - if (StringMatch(pattern.data(), - pattern.size(), field.data(), field.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), field.data(), field.size(), 0)) { field_values->push_back({field, iter->value().ToString()}); } remain--; @@ -1065,8 +968,7 @@ Status RedisHashes::PKHRScanRange(const Slice& key, if (iter->Valid() && iter->key().starts_with(prefix)) { ParsedHashesDataKey parsed_hashes_data_key(iter->key()); - if (end_no_limit - || parsed_hashes_data_key.field().compare(field_end) >= 0) { + if (end_no_limit || parsed_hashes_data_key.field().compare(field_end) >= 0) { *next_field = parsed_hashes_data_key.field().ToString(); } } @@ -1078,12 +980,8 @@ Status RedisHashes::PKHRScanRange(const Slice& key, return Status::OK(); } -Status RedisHashes::PKScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +Status RedisHashes::PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1097,9 +995,7 @@ Status RedisHashes::PKScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) > 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) > 0)) { return Status::InvalidArgument("error in given range"); } @@ -1110,16 +1006,13 @@ Status RedisHashes::PKScanRange(const Slice& key_start, it->Seek(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedHashesMetaValue parsed_hashes_meta_value(it->value()); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { it->Next(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1127,11 +1020,9 @@ Status RedisHashes::PKScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedHashesMetaValue parsed_hashes_meta_value(it->value()); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { it->Next(); } else { *next_key = it->key().ToString(); @@ -1142,12 +1033,8 @@ Status RedisHashes::PKScanRange(const Slice& key_start, return Status::OK(); } -Status RedisHashes::PKRScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +Status RedisHashes::PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1161,9 +1048,7 @@ Status RedisHashes::PKRScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) < 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) < 0)) { return Status::InvalidArgument("error in given range"); } @@ -1174,16 +1059,13 @@ Status RedisHashes::PKRScanRange(const Slice& key_start, it->SeekForPrev(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedHashesMetaValue parsed_hashes_meta_value(it->value()); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { it->Prev(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1191,11 +1073,9 @@ Status RedisHashes::PKRScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedHashesMetaValue parsed_hashes_meta_value(it->value()); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { it->Prev(); } else { *next_key = it->key().ToString(); @@ -1206,7 +1086,6 @@ Status RedisHashes::PKRScanRange(const Slice& key_start, return Status::OK(); } - Status RedisHashes::Expire(const Slice& key, int32_t ttl) { std::string meta_value; ScopeRecordLock l(lock_mgr_, key); @@ -1250,11 +1129,8 @@ Status RedisHashes::Del(const Slice& key) { return s; } -bool RedisHashes::Scan(const std::string& start_key, - const std::string& pattern, - std::vector* keys, - int64_t* count, - std::string* next_key) { +bool RedisHashes::Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, + int64_t* count, std::string* next_key) { std::string meta_key; bool is_finish = true; rocksdb::ReadOptions iterator_options; @@ -1268,14 +1144,12 @@ bool RedisHashes::Scan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*count) > 0) { ParsedHashesMetaValue parsed_meta_value(it->value()); - if (parsed_meta_value.IsStale() - || parsed_meta_value.count() == 0) { + if (parsed_meta_value.IsStale() || parsed_meta_value.count() == 0) { it->Next(); continue; } else { meta_key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - meta_key.data(), meta_key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), meta_key.data(), meta_key.size(), 0)) { keys->push_back(meta_key); } (*count)--; @@ -1283,10 +1157,8 @@ bool RedisHashes::Scan(const std::string& start_key, } } - std::string prefix = isTailWildcard(pattern) ? - pattern.substr(0, pattern.size() - 1) : ""; - if (it->Valid() - && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { + std::string prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; + if (it->Valid() && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { *next_key = it->key().ToString(); is_finish = false; } else { @@ -1296,11 +1168,8 @@ bool RedisHashes::Scan(const std::string& start_key, return is_finish; } -bool RedisHashes::PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) { +bool RedisHashes::PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) { bool is_finish = true; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -1312,13 +1181,12 @@ bool RedisHashes::PKExpireScan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*leftover_visits) > 0) { ParsedHashesMetaValue parsed_hashes_meta_value(it->value()); - if (parsed_hashes_meta_value.IsStale() - || parsed_hashes_meta_value.count() == 0) { + if (parsed_hashes_meta_value.IsStale() || parsed_hashes_meta_value.count() == 0) { it->Next(); continue; } else { - if (min_timestamp < parsed_hashes_meta_value.timestamp() - && parsed_hashes_meta_value.timestamp() < max_timestamp) { + if (min_timestamp < parsed_hashes_meta_value.timestamp() && + parsed_hashes_meta_value.timestamp() < max_timestamp) { keys->push_back(it->key().ToString()); } (*leftover_visits)--; @@ -1372,7 +1240,7 @@ Status RedisHashes::Persist(const Slice& key) { int32_t timestamp = parsed_hashes_meta_value.timestamp(); if (timestamp == 0) { return Status::NotFound("Not have an associated timeout"); - } else { + } else { parsed_hashes_meta_value.set_timestamp(0); s = db_->Put(default_write_options_, handles_[0], key, meta_value); } @@ -1418,36 +1286,28 @@ void RedisHashes::ScanDatabase() { printf("\n***************Hashes Meta Data***************\n"); auto meta_iter = db_->NewIterator(iterator_options, handles_[0]); - for (meta_iter->SeekToFirst(); - meta_iter->Valid(); - meta_iter->Next()) { + for (meta_iter->SeekToFirst(); meta_iter->Valid(); meta_iter->Next()) { ParsedHashesMetaValue parsed_hashes_meta_value(meta_iter->value()); int32_t survival_time = 0; if (parsed_hashes_meta_value.timestamp() != 0) { - survival_time = parsed_hashes_meta_value.timestamp() - current_time > 0 ? - parsed_hashes_meta_value.timestamp() - current_time : -1; + survival_time = parsed_hashes_meta_value.timestamp() - current_time > 0 + ? parsed_hashes_meta_value.timestamp() - current_time + : -1; } printf("[key : %-30s] [count : %-10d] [timestamp : %-10d] [version : %d] [survival_time : %d]\n", - meta_iter->key().ToString().c_str(), - parsed_hashes_meta_value.count(), - parsed_hashes_meta_value.timestamp(), - parsed_hashes_meta_value.version(), - survival_time); + meta_iter->key().ToString().c_str(), parsed_hashes_meta_value.count(), parsed_hashes_meta_value.timestamp(), + parsed_hashes_meta_value.version(), survival_time); } delete meta_iter; printf("\n***************Hashes Field Data***************\n"); auto field_iter = db_->NewIterator(iterator_options, handles_[1]); - for (field_iter->SeekToFirst(); - field_iter->Valid(); - field_iter->Next()) { + for (field_iter->SeekToFirst(); field_iter->Valid(); field_iter->Next()) { ParsedHashesDataKey parsed_hashes_data_key(field_iter->key()); printf("[key : %-30s] [field : %-20s] [value : %-20s] [version : %d]\n", - parsed_hashes_data_key.key().ToString().c_str(), - parsed_hashes_data_key.field().ToString().c_str(), - field_iter->value().ToString().c_str(), - parsed_hashes_data_key.version()); + parsed_hashes_data_key.key().ToString().c_str(), parsed_hashes_data_key.field().ToString().c_str(), + field_iter->value().ToString().c_str(), parsed_hashes_data_key.version()); } delete field_iter; } diff --git a/src/storage/src/redis_hashes.h b/src/storage/src/redis_hashes.h index acdceeeee8..e86eca570c 100644 --- a/src/storage/src/redis_hashes.h +++ b/src/storage/src/redis_hashes.h @@ -7,8 +7,8 @@ #define SRC_REDIS_HASHES_H_ #include -#include #include +#include #include "src/redis.h" @@ -20,79 +20,49 @@ class RedisHashes : public Redis { ~RedisHashes() = default; // Common Commands - Status Open(const StorageOptions& storage_options, - const std::string& db_path) override; - Status CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, + Status Open(const StorageOptions& storage_options, const std::string& db_path) override; + Status CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type = kMetaAndData) override; Status GetProperty(const std::string& property, uint64_t* out) override; Status ScanKeyNum(KeyInfo* key_info) override; - Status ScanKeys(const std::string& pattern, - std::vector* keys) override; + Status ScanKeys(const std::string& pattern, std::vector* keys) override; Status PKPatternMatchDel(const std::string& pattern, int32_t* ret) override; // Hashes Commands - Status HDel(const Slice& key, const std::vector& fields, - int32_t* ret); + Status HDel(const Slice& key, const std::vector& fields, int32_t* ret); Status HExists(const Slice& key, const Slice& field); Status HGet(const Slice& key, const Slice& field, std::string* value); - Status HGetall(const Slice& key, - std::vector* fvs); - Status HIncrby(const Slice& key, const Slice& field, int64_t value, - int64_t* ret); - Status HIncrbyfloat(const Slice& key, const Slice& field, - const Slice& by, std::string* new_value); - Status HKeys(const Slice& key, - std::vector* fields); + Status HGetall(const Slice& key, std::vector* fvs); + Status HIncrby(const Slice& key, const Slice& field, int64_t value, int64_t* ret); + Status HIncrbyfloat(const Slice& key, const Slice& field, const Slice& by, std::string* new_value); + Status HKeys(const Slice& key, std::vector* fields); Status HLen(const Slice& key, int32_t* ret); - Status HMGet(const Slice& key, const std::vector& fields, - std::vector* vss); - Status HMSet(const Slice& key, - const std::vector& fvs); - Status HSet(const Slice& key, const Slice& field, const Slice& value, - int32_t* ret); - Status HSetnx(const Slice& key, const Slice& field, const Slice& value, - int32_t* ret); - Status HVals(const Slice& key, - std::vector* values); + Status HMGet(const Slice& key, const std::vector& fields, std::vector* vss); + Status HMSet(const Slice& key, const std::vector& fvs); + Status HSet(const Slice& key, const Slice& field, const Slice& value, int32_t* ret); + Status HSetnx(const Slice& key, const Slice& field, const Slice& value, int32_t* ret); + Status HVals(const Slice& key, std::vector* values); Status HStrlen(const Slice& key, const Slice& field, int32_t* len); - Status HScan(const Slice& key, int64_t cursor, - const std::string& pattern, int64_t count, + Status HScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, std::vector* field_values, int64_t* next_cursor); - Status HScanx(const Slice& key, const std::string start_field, - const std::string& pattern, int64_t count, - std::vector* field_values, - std::string* next_field); - Status PKHScanRange(const Slice& key, - const Slice& field_start, - const std::string& field_end, - const Slice& pattern, int32_t limit, - std::vector* field_values, - std::string* next_field); - Status PKHRScanRange(const Slice& key, - const Slice& field_start, const std::string& field_end, - const Slice& pattern, int32_t limit, - std::vector* field_values, - std::string* next_field); - Status PKScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status HScanx(const Slice& key, const std::string start_field, const std::string& pattern, int64_t count, + std::vector* field_values, std::string* next_field); + Status PKHScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, const Slice& pattern, + int32_t limit, std::vector* field_values, std::string* next_field); + Status PKHRScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, const Slice& pattern, + int32_t limit, std::vector* field_values, std::string* next_field); + Status PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* keys, std::string* next_key); - Status PKRScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* keys, std::string* next_key); - // Keys Commands Status Expire(const Slice& key, int32_t ttl) override; Status Del(const Slice& key) override; - bool Scan(const std::string& start_key, const std::string& pattern, - std::vector* keys, - int64_t* count, std::string* next_key) override; - bool PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) override; + bool Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, int64_t* count, + std::string* next_key) override; + bool PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) override; Status Expireat(const Slice& key, int32_t timestamp) override; Status Persist(const Slice& key) override; Status TTL(const Slice& key, int64_t* timestamp) override; diff --git a/src/storage/src/redis_hyperloglog.cc b/src/storage/src/redis_hyperloglog.cc index 0f2d1c5c71..47fa936538 100644 --- a/src/storage/src/redis_hyperloglog.cc +++ b/src/storage/src/redis_hyperloglog.cc @@ -3,10 +3,10 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. +#include "src/redis_hyperloglog.h" +#include #include #include -#include -#include "src/redis_hyperloglog.h" #include "src/storage_murmur3.h" namespace storage { @@ -28,18 +28,14 @@ HyperLogLog::HyperLogLog(uint8_t precision, std::string origin_register) { } } -HyperLogLog::~HyperLogLog() { - delete [] register_; -} +HyperLogLog::~HyperLogLog() { delete[] register_; } std::string HyperLogLog::Add(const char* value, uint32_t len) { uint32_t hash_value; - MurmurHash3_x86_32(value, len, HLL_HASH_SEED, - static_cast(&hash_value)); + MurmurHash3_x86_32(value, len, HLL_HASH_SEED, static_cast(&hash_value)); int32_t index = hash_value & ((1 << b_) - 1); uint8_t rank = Nctz((hash_value >> b_), 32 - b_); - if (rank > register_[index]) - register_[index] = rank; + if (rank > register_[index]) register_[index] = rank; std::string result(m_, 0); for (uint32_t i = 0; i < m_; ++i) { result[i] = register_[i]; @@ -80,7 +76,7 @@ double HyperLogLog::Alpha() const { return 0.709; default: return 0.7213 / (1 + 1.079 / m_); - } + } } uint32_t HyperLogLog::CountZero() const { @@ -93,7 +89,7 @@ uint32_t HyperLogLog::CountZero() const { return count; } -std::string HyperLogLog::Merge(const HyperLogLog & hll) { +std::string HyperLogLog::Merge(const HyperLogLog& hll) { if (m_ != hll.m_) { // TODO(shq) the number of registers doesn't match } @@ -111,8 +107,6 @@ std::string HyperLogLog::Merge(const HyperLogLog & hll) { } // ::__builtin_ctz(x): 返回右起第一个‘1’之后的0的个数 -uint8_t HyperLogLog::Nctz(uint32_t x, int b) { - return (uint8_t)std::min(b, ::__builtin_ctz(x)) + 1; -} +uint8_t HyperLogLog::Nctz(uint32_t x, int b) { return (uint8_t)std::min(b, ::__builtin_ctz(x)) + 1; } } // namespace storage diff --git a/src/storage/src/redis_hyperloglog.h b/src/storage/src/redis_hyperloglog.h index e835d07734..3cd54ffaa6 100644 --- a/src/storage/src/redis_hyperloglog.h +++ b/src/storage/src/redis_hyperloglog.h @@ -35,4 +35,3 @@ class HyperLogLog { } // namespace storage #endif // SRC_REDIS_HYPERLOGLOG_H_ - diff --git a/src/storage/src/redis_lists.cc b/src/storage/src/redis_lists.cc index 8730589e79..31745643bd 100644 --- a/src/storage/src/redis_lists.cc +++ b/src/storage/src/redis_lists.cc @@ -3,14 +3,13 @@ // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. - #include -#include "storage/util.h" -#include "src/redis_lists.h" #include "src/lists_filter.h" +#include "src/redis_lists.h" #include "src/scope_record_lock.h" #include "src/scope_snapshot.h" +#include "storage/util.h" namespace storage { @@ -19,12 +18,9 @@ const rocksdb::Comparator* ListsDataKeyComparator() { return &ldkc; } -RedisLists::RedisLists(Storage* const s, const DataType& type) - : Redis(s, type) { -} +RedisLists::RedisLists(Storage* const s, const DataType& type) : Redis(s, type) {} -Status RedisLists::Open(const StorageOptions& storage_options, - const std::string& db_path) { +Status RedisLists::Open(const StorageOptions& storage_options, const std::string& db_path) { statistics_store_->SetCapacity(storage_options.statistics_max_size); small_compaction_threshold_ = storage_options.small_compaction_threshold; @@ -48,10 +44,8 @@ Status RedisLists::Open(const StorageOptions& storage_options, rocksdb::DBOptions db_ops(storage_options.options); rocksdb::ColumnFamilyOptions meta_cf_ops(storage_options.options); rocksdb::ColumnFamilyOptions data_cf_ops(storage_options.options); - meta_cf_ops.compaction_filter_factory = - std::make_shared(); - data_cf_ops.compaction_filter_factory = - std::make_shared(&db_, &handles_); + meta_cf_ops.compaction_filter_factory = std::make_shared(); + data_cf_ops.compaction_filter_factory = std::make_shared(&db_, &handles_); data_cf_ops.comparator = ListsDataKeyComparator(); // use the bloom filter policy to reduce disk reads @@ -60,29 +54,21 @@ Status RedisLists::Open(const StorageOptions& storage_options, rocksdb::BlockBasedTableOptions meta_cf_table_ops(table_ops); rocksdb::BlockBasedTableOptions data_cf_table_ops(table_ops); if (!storage_options.share_block_cache && storage_options.block_cache_size > 0) { - meta_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); - data_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); + meta_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); + data_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); } - meta_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); - data_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(data_cf_table_ops)); + meta_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); + data_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(data_cf_table_ops)); std::vector column_families; // Meta CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor(rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); // Data CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - "data_cf", data_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor("data_cf", data_cf_ops)); return rocksdb::DB::Open(db_ops, db_path, column_families, &handles_, &db_); } -Status RedisLists::CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, - const ColumnFamilyType& type) { +Status RedisLists::CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type) { if (type == kMeta || type == kMetaAndData) { db_->CompactRange(default_compact_range_options_, handles_[0], begin, end); } @@ -117,12 +103,9 @@ Status RedisLists::ScanKeyNum(KeyInfo* key_info) { rocksdb::Env::Default()->GetCurrentTime(&curtime); rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedListsMetaValue parsed_lists_meta_value(iter->value()); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { invaild_keys++; } else { keys++; @@ -141,8 +124,7 @@ Status RedisLists::ScanKeyNum(KeyInfo* key_info) { return Status::OK(); } -Status RedisLists::ScanKeys(const std::string& pattern, - std::vector* keys) { +Status RedisLists::ScanKeys(const std::string& pattern, std::vector* keys) { std::string key; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -151,15 +133,11 @@ Status RedisLists::ScanKeys(const std::string& pattern, iterator_options.fill_cache = false; rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedListsMetaValue parsed_lists_meta_value(iter->value()); - if (!parsed_lists_meta_value.IsStale() - && parsed_lists_meta_value.count() != 0) { + if (!parsed_lists_meta_value.IsStale() && parsed_lists_meta_value.count() != 0) { key = iter->key().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } } @@ -168,8 +146,7 @@ Status RedisLists::ScanKeys(const std::string& pattern, return Status::OK(); } -Status RedisLists::PKPatternMatchDel(const std::string& pattern, - int32_t* ret) { +Status RedisLists::PKPatternMatchDel(const std::string& pattern, int32_t* ret) { rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); @@ -187,9 +164,8 @@ Status RedisLists::PKPatternMatchDel(const std::string& pattern, key = iter->key().ToString(); meta_value = iter->value().ToString(); ParsedListsMetaValue parsed_lists_meta_value(&meta_value); - if (!parsed_lists_meta_value.IsStale() - && parsed_lists_meta_value.count() - && StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { + if (!parsed_lists_meta_value.IsStale() && parsed_lists_meta_value.count() && + StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { parsed_lists_meta_value.InitialMetaValue(); batch.Put(handles_[0], key, meta_value); } @@ -217,9 +193,7 @@ Status RedisLists::PKPatternMatchDel(const std::string& pattern, return s; } -Status RedisLists::LIndex(const Slice& key, - int64_t index, - std::string* element) { +Status RedisLists::LIndex(const Slice& key, int64_t index, std::string* element) { rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; @@ -236,14 +210,11 @@ Status RedisLists::LIndex(const Slice& key, return Status::NotFound(); } else { std::string tmp_element; - uint64_t target_index = index >= 0 ? - parsed_lists_meta_value.left_index() + index + 1 : - parsed_lists_meta_value.right_index() + index; - if (parsed_lists_meta_value.left_index() < target_index - && target_index < parsed_lists_meta_value.right_index()) { + uint64_t target_index = + index >= 0 ? parsed_lists_meta_value.left_index() + index + 1 : parsed_lists_meta_value.right_index() + index; + if (parsed_lists_meta_value.left_index() < target_index && target_index < parsed_lists_meta_value.right_index()) { ListsDataKey lists_data_key(key, version, target_index); - s = db_->Get(read_options, - handles_[1], lists_data_key.Encode(), &tmp_element); + s = db_->Get(read_options, handles_[1], lists_data_key.Encode(), &tmp_element); if (s.ok()) { *element = tmp_element; } @@ -255,11 +226,8 @@ Status RedisLists::LIndex(const Slice& key, return s; } -Status RedisLists::LInsert(const Slice& key, - const BeforeOrAfter& before_or_after, - const std::string& pivot, - const std::string& value, - int64_t* ret) { +Status RedisLists::LInsert(const Slice& key, const BeforeOrAfter& before_or_after, const std::string& pivot, + const std::string& value, int64_t* ret) { *ret = 0; rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -276,18 +244,15 @@ Status RedisLists::LInsert(const Slice& key, uint64_t pivot_index = 0; uint32_t version = parsed_lists_meta_value.version(); uint64_t current_index = parsed_lists_meta_value.left_index() + 1; - rocksdb::Iterator* iter = - db_->NewIterator(default_read_options_, handles_[1]); + rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[1]); ListsDataKey start_data_key(key, version, current_index); - for (iter->Seek(start_data_key.Encode()); - iter->Valid() - && current_index < parsed_lists_meta_value.right_index(); + for (iter->Seek(start_data_key.Encode()); iter->Valid() && current_index < parsed_lists_meta_value.right_index(); iter->Next(), current_index++) { - if (strcmp(iter->value().ToString().data(), pivot.data()) == 0) { - find_pivot = true; - pivot_index = current_index; - break; - } + if (strcmp(iter->value().ToString().data(), pivot.data()) == 0) { + find_pivot = true; + pivot_index = current_index; + break; + } } delete iter; if (!find_pivot) { @@ -296,26 +261,22 @@ Status RedisLists::LInsert(const Slice& key, } else { uint64_t target_index; std::vector list_nodes; - uint64_t mid_index = parsed_lists_meta_value.left_index() - + (parsed_lists_meta_value.right_index() - - parsed_lists_meta_value.left_index()) / 2; + uint64_t mid_index = parsed_lists_meta_value.left_index() + + (parsed_lists_meta_value.right_index() - parsed_lists_meta_value.left_index()) / 2; if (pivot_index <= mid_index) { - target_index = (before_or_after == Before) - ? pivot_index - 1 : pivot_index; + target_index = (before_or_after == Before) ? pivot_index - 1 : pivot_index; current_index = parsed_lists_meta_value.left_index() + 1; - rocksdb::Iterator* first_half_iter = - db_->NewIterator(default_read_options_, handles_[1]); + rocksdb::Iterator* first_half_iter = db_->NewIterator(default_read_options_, handles_[1]); ListsDataKey start_data_key(key, version, current_index); - for (first_half_iter->Seek(start_data_key.Encode()); - first_half_iter->Valid() && current_index <= pivot_index; + for (first_half_iter->Seek(start_data_key.Encode()); first_half_iter->Valid() && current_index <= pivot_index; first_half_iter->Next(), current_index++) { - if (current_index == pivot_index) { - if (before_or_after == After) { - list_nodes.push_back(first_half_iter->value().ToString()); - } - break; + if (current_index == pivot_index) { + if (before_or_after == After) { + list_nodes.push_back(first_half_iter->value().ToString()); } - list_nodes.push_back(first_half_iter->value().ToString()); + break; + } + list_nodes.push_back(first_half_iter->value().ToString()); } delete first_half_iter; @@ -326,21 +287,17 @@ Status RedisLists::LInsert(const Slice& key, } parsed_lists_meta_value.ModifyLeftIndex(1); } else { - target_index = (before_or_after == Before) - ? pivot_index : pivot_index + 1; + target_index = (before_or_after == Before) ? pivot_index : pivot_index + 1; current_index = pivot_index; - rocksdb::Iterator* after_half_iter = - db_->NewIterator(default_read_options_, handles_[1]); + rocksdb::Iterator* after_half_iter = db_->NewIterator(default_read_options_, handles_[1]); ListsDataKey start_data_key(key, version, current_index); for (after_half_iter->Seek(start_data_key.Encode()); - after_half_iter->Valid() - && current_index < parsed_lists_meta_value.right_index(); + after_half_iter->Valid() && current_index < parsed_lists_meta_value.right_index(); after_half_iter->Next(), current_index++) { - if (current_index == pivot_index - && before_or_after == BeforeOrAfter::After) { - continue; - } - list_nodes.push_back(after_half_iter->value().ToString()); + if (current_index == pivot_index && before_or_after == BeforeOrAfter::After) { + continue; + } + list_nodes.push_back(after_half_iter->value().ToString()); } delete after_half_iter; @@ -399,8 +356,7 @@ Status RedisLists::LPop(const Slice& key, std::string* element) { int32_t version = parsed_lists_meta_value.version(); uint64_t first_node_index = parsed_lists_meta_value.left_index() + 1; ListsDataKey lists_data_key(key, version, first_node_index); - s = db_->Get(default_read_options_, - handles_[1], lists_data_key.Encode(), element); + s = db_->Get(default_read_options_, handles_[1], lists_data_key.Encode(), element); if (s.ok()) { batch.Delete(handles_[1], lists_data_key.Encode()); statistic++; @@ -418,9 +374,7 @@ Status RedisLists::LPop(const Slice& key, std::string* element) { return s; } -Status RedisLists::LPush(const Slice& key, - const std::vector& values, - uint64_t* ret) { +Status RedisLists::LPush(const Slice& key, const std::vector& values, uint64_t* ret) { *ret = 0; rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -431,8 +385,7 @@ Status RedisLists::LPush(const Slice& key, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedListsMetaValue parsed_lists_meta_value(&meta_value); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { version = parsed_lists_meta_value.InitialMetaValue(); } else { version = parsed_lists_meta_value.version(); @@ -493,8 +446,7 @@ Status RedisLists::LPushx(const Slice& key, const Slice& value, uint64_t* len) { return s; } -Status RedisLists::LRange(const Slice& key, int64_t start, int64_t stop, - std::vector* ret) { +Status RedisLists::LRange(const Slice& key, int64_t start, int64_t stop, std::vector* ret) { rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; @@ -513,16 +465,11 @@ Status RedisLists::LRange(const Slice& key, int64_t start, int64_t stop, int32_t version = parsed_lists_meta_value.version(); uint64_t origin_left_index = parsed_lists_meta_value.left_index() + 1; uint64_t origin_right_index = parsed_lists_meta_value.right_index() - 1; - uint64_t sublist_left_index = start >= 0 ? - origin_left_index + start : - origin_right_index + start + 1; - uint64_t sublist_right_index = stop >= 0 ? - origin_left_index + stop : - origin_right_index + stop + 1; - - if (sublist_left_index > sublist_right_index - || sublist_left_index > origin_right_index - || sublist_right_index < origin_left_index) { + uint64_t sublist_left_index = start >= 0 ? origin_left_index + start : origin_right_index + start + 1; + uint64_t sublist_right_index = stop >= 0 ? origin_left_index + stop : origin_right_index + stop + 1; + + if (sublist_left_index > sublist_right_index || sublist_left_index > origin_right_index || + sublist_right_index < origin_left_index) { return Status::OK(); } else { if (sublist_left_index < origin_left_index) { @@ -531,12 +478,10 @@ Status RedisLists::LRange(const Slice& key, int64_t start, int64_t stop, if (sublist_right_index > origin_right_index) { sublist_right_index = origin_right_index; } - rocksdb::Iterator* iter = db_->NewIterator(read_options, - handles_[1]); + rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); uint64_t current_index = sublist_left_index; ListsDataKey start_data_key(key, version, current_index); - for (iter->Seek(start_data_key.Encode()); - iter->Valid() && current_index <= sublist_right_index; + for (iter->Seek(start_data_key.Encode()); iter->Valid() && current_index <= sublist_right_index; iter->Next(), current_index++) { ret->push_back(iter->value().ToString()); } @@ -549,8 +494,7 @@ Status RedisLists::LRange(const Slice& key, int64_t start, int64_t stop, } } -Status RedisLists::LRem(const Slice& key, int64_t count, - const Slice& value, uint64_t* ret) { +Status RedisLists::LRem(const Slice& key, int64_t count, const Slice& value, uint64_t* ret) { *ret = 0; rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -574,11 +518,8 @@ Status RedisLists::LRem(const Slice& key, int64_t count, ListsDataKey stop_data_key(key, version, stop_index); if (count >= 0) { current_index = start_index; - rocksdb::Iterator* iter = - db_->NewIterator(default_read_options_, handles_[1]); - for (iter->Seek(start_data_key.Encode()); - iter->Valid() - && current_index <= stop_index && (!count || rest != 0); + rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[1]); + for (iter->Seek(start_data_key.Encode()); iter->Valid() && current_index <= stop_index && (!count || rest != 0); iter->Next(), current_index++) { if (strcmp(iter->value().ToString().data(), value.data()) == 0) { target_index.push_back(current_index); @@ -590,11 +531,8 @@ Status RedisLists::LRem(const Slice& key, int64_t count, delete iter; } else { current_index = stop_index; - rocksdb::Iterator* iter = - db_->NewIterator(default_read_options_, handles_[1]); - for (iter->Seek(stop_data_key.Encode()); - iter->Valid() - && current_index >= start_index && (!count || rest != 0); + rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[1]); + for (iter->Seek(stop_data_key.Encode()); iter->Valid() && current_index >= start_index && (!count || rest != 0); iter->Prev(), current_index--) { if (strcmp(iter->value().ToString().data(), value.data()) == 0) { target_index.push_back(current_index); @@ -610,23 +548,18 @@ Status RedisLists::LRem(const Slice& key, int64_t count, return Status::NotFound(); } else { rest = target_index.size(); - uint64_t sublist_left_index = (count >= 0) - ? target_index[0] : target_index[target_index.size() - 1]; - uint64_t sublist_right_index = (count >= 0) - ? target_index[target_index.size() - 1] : target_index[0]; + uint64_t sublist_left_index = (count >= 0) ? target_index[0] : target_index[target_index.size() - 1]; + uint64_t sublist_right_index = (count >= 0) ? target_index[target_index.size() - 1] : target_index[0]; uint64_t left_part_len = sublist_right_index - start_index; uint64_t right_part_len = stop_index - sublist_left_index; if (left_part_len <= right_part_len) { uint64_t left = sublist_right_index; - current_index = sublist_right_index; + current_index = sublist_right_index; ListsDataKey sublist_right_key(key, version, sublist_right_index); - rocksdb::Iterator* iter = - db_->NewIterator(default_read_options_, handles_[1]); - for (iter->Seek(sublist_right_key.Encode()); - iter->Valid() && current_index >= start_index; + rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[1]); + for (iter->Seek(sublist_right_key.Encode()); iter->Valid() && current_index >= start_index; iter->Prev(), current_index--) { - if (!strcmp(iter->value().ToString().data(), value.data()) - && rest > 0) { + if (!strcmp(iter->value().ToString().data(), value.data()) && rest > 0) { rest--; } else { ListsDataKey lists_data_key(key, version, left--); @@ -643,13 +576,10 @@ Status RedisLists::LRem(const Slice& key, int64_t count, uint64_t right = sublist_left_index; current_index = sublist_left_index; ListsDataKey sublist_left_key(key, version, sublist_left_index); - rocksdb::Iterator* iter = - db_->NewIterator(default_read_options_, handles_[1]); - for (iter->Seek(sublist_left_key.Encode()); - iter->Valid() && current_index <= stop_index; + rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[1]); + for (iter->Seek(sublist_left_key.Encode()); iter->Valid() && current_index <= stop_index; iter->Next(), current_index++) { - if (!strcmp(iter->value().ToString().data(), value.data()) - && rest > 0) { + if (!strcmp(iter->value().ToString().data(), value.data()) && rest > 0) { rest--; } else { ListsDataKey lists_data_key(key, version, right++); @@ -692,16 +622,14 @@ Status RedisLists::LSet(const Slice& key, int64_t index, const Slice& value) { return Status::NotFound(); } else { uint32_t version = parsed_lists_meta_value.version(); - uint64_t target_index = index >= 0 ? - parsed_lists_meta_value.left_index() + index + 1 - : parsed_lists_meta_value.right_index() + index; - if (target_index <= parsed_lists_meta_value.left_index() - || target_index >= parsed_lists_meta_value.right_index()) { + uint64_t target_index = + index >= 0 ? parsed_lists_meta_value.left_index() + index + 1 : parsed_lists_meta_value.right_index() + index; + if (target_index <= parsed_lists_meta_value.left_index() || + target_index >= parsed_lists_meta_value.right_index()) { return Status::Corruption("index out of range"); } ListsDataKey lists_data_key(key, version, target_index); - s = db_->Put(default_write_options_, handles_[1], - lists_data_key.Encode(), value); + s = db_->Put(default_write_options_, handles_[1], lists_data_key.Encode(), value); statistic++; UpdateSpecificKeyStatistics(key.ToString(), statistic); return s; @@ -727,16 +655,11 @@ Status RedisLists::LTrim(const Slice& key, int64_t start, int64_t stop) { } else { uint64_t origin_left_index = parsed_lists_meta_value.left_index() + 1; uint64_t origin_right_index = parsed_lists_meta_value.right_index() - 1; - uint64_t sublist_left_index = start >= 0 ? - origin_left_index + start : - origin_right_index + start + 1; - uint64_t sublist_right_index = stop >= 0 ? - origin_left_index + stop : - origin_right_index + stop + 1; - - if (sublist_left_index > sublist_right_index - || sublist_left_index > origin_right_index - || sublist_right_index < origin_left_index) { + uint64_t sublist_left_index = start >= 0 ? origin_left_index + start : origin_right_index + start + 1; + uint64_t sublist_right_index = stop >= 0 ? origin_left_index + stop : origin_right_index + stop + 1; + + if (sublist_left_index > sublist_right_index || sublist_left_index > origin_right_index || + sublist_right_index < origin_left_index) { parsed_lists_meta_value.InitialMetaValue(); batch.Put(handles_[0], key, meta_value); } else { @@ -748,24 +671,18 @@ Status RedisLists::LTrim(const Slice& key, int64_t start, int64_t stop) { sublist_right_index = origin_right_index; } - uint64_t delete_node_num = (sublist_left_index - origin_left_index) - + (origin_right_index - sublist_right_index); - parsed_lists_meta_value.ModifyLeftIndex( - -(sublist_left_index - origin_left_index)); - parsed_lists_meta_value.ModifyRightIndex( - -(origin_right_index - sublist_right_index)); + uint64_t delete_node_num = + (sublist_left_index - origin_left_index) + (origin_right_index - sublist_right_index); + parsed_lists_meta_value.ModifyLeftIndex(-(sublist_left_index - origin_left_index)); + parsed_lists_meta_value.ModifyRightIndex(-(origin_right_index - sublist_right_index)); parsed_lists_meta_value.ModifyCount(-delete_node_num); batch.Put(handles_[0], key, meta_value); - for (uint64_t idx = origin_left_index; - idx < sublist_left_index; - ++idx) { + for (uint64_t idx = origin_left_index; idx < sublist_left_index; ++idx) { statistic++; ListsDataKey lists_data_key(key, version, idx); batch.Delete(handles_[1], lists_data_key.Encode()); } - for (uint64_t idx = origin_right_index; - idx > sublist_right_index; - --idx) { + for (uint64_t idx = origin_right_index; idx > sublist_right_index; --idx) { statistic++; ListsDataKey lists_data_key(key, version, idx); batch.Delete(handles_[1], lists_data_key.Encode()); @@ -797,8 +714,7 @@ Status RedisLists::RPop(const Slice& key, std::string* element) { int32_t version = parsed_lists_meta_value.version(); uint64_t last_node_index = parsed_lists_meta_value.right_index() - 1; ListsDataKey lists_data_key(key, version, last_node_index); - s = db_->Get(default_read_options_, - handles_[1], lists_data_key.Encode(), element); + s = db_->Get(default_read_options_, handles_[1], lists_data_key.Encode(), element); if (s.ok()) { batch.Delete(handles_[1], lists_data_key.Encode()); statistic++; @@ -816,15 +732,12 @@ Status RedisLists::RPop(const Slice& key, std::string* element) { return s; } -Status RedisLists::RPoplpush(const Slice& source, - const Slice& destination, - std::string* element) { +Status RedisLists::RPoplpush(const Slice& source, const Slice& destination, std::string* element) { element->clear(); uint32_t statistic = 0; Status s; rocksdb::WriteBatch batch; - MultiScopeRecordLock l(lock_mgr_, - {source.ToString(), destination.ToString()}); + MultiScopeRecordLock l(lock_mgr_, {source.ToString(), destination.ToString()}); if (!source.compare(destination)) { std::string meta_value; s = db_->Get(default_read_options_, handles_[0], source, &meta_value); @@ -839,8 +752,7 @@ Status RedisLists::RPoplpush(const Slice& source, int32_t version = parsed_lists_meta_value.version(); uint64_t last_node_index = parsed_lists_meta_value.right_index() - 1; ListsDataKey lists_data_key(source, version, last_node_index); - s = db_->Get(default_read_options_, - handles_[1], lists_data_key.Encode(), &target); + s = db_->Get(default_read_options_, handles_[1], lists_data_key.Encode(), &target); if (s.ok()) { *element = target; if (parsed_lists_meta_value.count() == 1) { @@ -881,8 +793,7 @@ Status RedisLists::RPoplpush(const Slice& source, version = parsed_lists_meta_value.version(); uint64_t last_node_index = parsed_lists_meta_value.right_index() - 1; ListsDataKey lists_data_key(source, version, last_node_index); - s = db_->Get(default_read_options_, - handles_[1], lists_data_key.Encode(), &target); + s = db_->Get(default_read_options_, handles_[1], lists_data_key.Encode(), &target); if (s.ok()) { batch.Delete(handles_[1], lists_data_key.Encode()); statistic++; @@ -898,12 +809,10 @@ Status RedisLists::RPoplpush(const Slice& source, } std::string destination_meta_value; - s = db_->Get(default_read_options_, - handles_[0], destination, &destination_meta_value); + s = db_->Get(default_read_options_, handles_[0], destination, &destination_meta_value); if (s.ok()) { ParsedListsMetaValue parsed_lists_meta_value(&destination_meta_value); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { version = parsed_lists_meta_value.InitialMetaValue(); } else { version = parsed_lists_meta_value.version(); @@ -936,9 +845,7 @@ Status RedisLists::RPoplpush(const Slice& source, return s; } -Status RedisLists::RPush(const Slice& key, - const std::vector& values, - uint64_t* ret) { +Status RedisLists::RPush(const Slice& key, const std::vector& values, uint64_t* ret) { *ret = 0; rocksdb::WriteBatch batch; @@ -948,8 +855,7 @@ Status RedisLists::RPush(const Slice& key, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedListsMetaValue parsed_lists_meta_value(&meta_value); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { version = parsed_lists_meta_value.InitialMetaValue(); } else { version = parsed_lists_meta_value.version(); @@ -1010,12 +916,8 @@ Status RedisLists::RPushx(const Slice& key, const Slice& value, uint64_t* len) { return s; } -Status RedisLists::PKScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +Status RedisLists::PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1029,9 +931,7 @@ Status RedisLists::PKScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) > 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) > 0)) { return Status::InvalidArgument("error in given range"); } @@ -1042,16 +942,13 @@ Status RedisLists::PKScanRange(const Slice& key_start, it->Seek(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedListsMetaValue parsed_lists_meta_value(it->value()); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { it->Next(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1059,11 +956,9 @@ Status RedisLists::PKScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedListsMetaValue parsed_lists_meta_value(it->value()); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { it->Next(); } else { *next_key = it->key().ToString(); @@ -1074,12 +969,8 @@ Status RedisLists::PKScanRange(const Slice& key_start, return Status::OK(); } -Status RedisLists::PKRScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +Status RedisLists::PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1093,9 +984,7 @@ Status RedisLists::PKRScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) < 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) < 0)) { return Status::InvalidArgument("error in given range"); } @@ -1106,16 +995,13 @@ Status RedisLists::PKRScanRange(const Slice& key_start, it->SeekForPrev(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedListsMetaValue parsed_lists_meta_value(it->value()); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { it->Prev(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1123,11 +1009,9 @@ Status RedisLists::PKRScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedListsMetaValue parsed_lists_meta_value(it->value()); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { it->Prev(); } else { *next_key = it->key().ToString(); @@ -1181,11 +1065,8 @@ Status RedisLists::Del(const Slice& key) { return s; } -bool RedisLists::Scan(const std::string& start_key, - const std::string& pattern, - std::vector* keys, - int64_t* count, - std::string* next_key) { +bool RedisLists::Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, + int64_t* count, std::string* next_key) { std::string meta_key; bool is_finish = true; rocksdb::ReadOptions iterator_options; @@ -1199,14 +1080,12 @@ bool RedisLists::Scan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*count) > 0) { ParsedListsMetaValue parsed_lists_meta_value(it->value()); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { it->Next(); continue; } else { meta_key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - meta_key.data(), meta_key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), meta_key.data(), meta_key.size(), 0)) { keys->push_back(meta_key); } (*count)--; @@ -1214,10 +1093,8 @@ bool RedisLists::Scan(const std::string& start_key, } } - std::string prefix = isTailWildcard(pattern) ? - pattern.substr(0, pattern.size() - 1) : ""; - if (it->Valid() - && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { + std::string prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; + if (it->Valid() && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { *next_key = it->key().ToString(); is_finish = false; } else { @@ -1227,11 +1104,8 @@ bool RedisLists::Scan(const std::string& start_key, return is_finish; } -bool RedisLists::PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) { +bool RedisLists::PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) { bool is_finish = true; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -1243,13 +1117,11 @@ bool RedisLists::PKExpireScan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*leftover_visits) > 0) { ParsedListsMetaValue parsed_lists_meta_value(it->value()); - if (parsed_lists_meta_value.IsStale() - || parsed_lists_meta_value.count() == 0) { + if (parsed_lists_meta_value.IsStale() || parsed_lists_meta_value.count() == 0) { it->Next(); continue; } else { - if (min_timestamp < parsed_lists_meta_value.timestamp() - && parsed_lists_meta_value.timestamp() < max_timestamp) { + if (min_timestamp < parsed_lists_meta_value.timestamp() && parsed_lists_meta_value.timestamp() < max_timestamp) { keys->push_back(it->key().ToString()); } (*leftover_visits)--; @@ -1349,41 +1221,33 @@ void RedisLists::ScanDatabase() { printf("\n***************List Meta Data***************\n"); auto meta_iter = db_->NewIterator(iterator_options, handles_[0]); - for (meta_iter->SeekToFirst(); - meta_iter->Valid(); - meta_iter->Next()) { + for (meta_iter->SeekToFirst(); meta_iter->Valid(); meta_iter->Next()) { ParsedListsMetaValue parsed_lists_meta_value(meta_iter->value()); int32_t survival_time = 0; if (parsed_lists_meta_value.timestamp() != 0) { - survival_time = parsed_lists_meta_value.timestamp() - current_time > 0 ? - parsed_lists_meta_value.timestamp() - current_time : -1; + survival_time = parsed_lists_meta_value.timestamp() - current_time > 0 + ? parsed_lists_meta_value.timestamp() - current_time + : -1; } - printf("[key : %-30s] [count : %-10lu] [left index : %-10lu] [right index : %-10lu] [timestamp : %-10d] [version : %d] [survival_time : %d]\n", - meta_iter->key().ToString().c_str(), - parsed_lists_meta_value.count(), - parsed_lists_meta_value.left_index(), - parsed_lists_meta_value.right_index(), - parsed_lists_meta_value.timestamp(), - parsed_lists_meta_value.version(), - survival_time); + printf( + "[key : %-30s] [count : %-10lu] [left index : %-10lu] [right index : %-10lu] [timestamp : %-10d] [version : " + "%d] [survival_time : %d]\n", + meta_iter->key().ToString().c_str(), parsed_lists_meta_value.count(), parsed_lists_meta_value.left_index(), + parsed_lists_meta_value.right_index(), parsed_lists_meta_value.timestamp(), parsed_lists_meta_value.version(), + survival_time); } delete meta_iter; printf("\n***************List Node Data***************\n"); auto data_iter = db_->NewIterator(iterator_options, handles_[1]); - for (data_iter->SeekToFirst(); - data_iter->Valid(); - data_iter->Next()) { + for (data_iter->SeekToFirst(); data_iter->Valid(); data_iter->Next()) { ParsedListsDataKey parsed_lists_data_key(data_iter->key()); printf("[key : %-30s] [index : %-10lu] [data : %-20s] [version : %d]\n", - parsed_lists_data_key.key().ToString().c_str(), - parsed_lists_data_key.index(), - data_iter->value().ToString().c_str(), - parsed_lists_data_key.version()); + parsed_lists_data_key.key().ToString().c_str(), parsed_lists_data_key.index(), + data_iter->value().ToString().c_str(), parsed_lists_data_key.version()); } delete data_iter; } -} // namespace storage - +} // namespace storage diff --git a/src/storage/src/redis_lists.h b/src/storage/src/redis_lists.h index c81a005d06..cf5a2305a9 100644 --- a/src/storage/src/redis_lists.h +++ b/src/storage/src/redis_lists.h @@ -7,11 +7,11 @@ #define SRC_REDIS_LISTS_H_ #include -#include #include +#include -#include "src/redis.h" #include "src/custom_comparator.h" +#include "src/redis.h" namespace storage { @@ -21,58 +21,42 @@ class RedisLists : public Redis { ~RedisLists() = default; // Common commands - Status Open(const StorageOptions& storage_options, - const std::string& db_path) override; - Status CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, + Status Open(const StorageOptions& storage_options, const std::string& db_path) override; + Status CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type = kMetaAndData) override; Status GetProperty(const std::string& property, uint64_t* out) override; Status ScanKeyNum(KeyInfo* key_info) override; - Status ScanKeys(const std::string& pattern, - std::vector* keys) override; + Status ScanKeys(const std::string& pattern, std::vector* keys) override; Status PKPatternMatchDel(const std::string& pattern, int32_t* ret) override; - // Lists commands; Status LIndex(const Slice& key, int64_t index, std::string* element); - Status LInsert(const Slice& key, const BeforeOrAfter& before_or_after, - const std::string& pivot, const std::string& value, - int64_t* ret); + Status LInsert(const Slice& key, const BeforeOrAfter& before_or_after, const std::string& pivot, + const std::string& value, int64_t* ret); Status LLen(const Slice& key, uint64_t* len); Status LPop(const Slice& key, std::string* element); - Status LPush(const Slice& key, const std::vector& values, - uint64_t* ret); + Status LPush(const Slice& key, const std::vector& values, uint64_t* ret); Status LPushx(const Slice& key, const Slice& value, uint64_t* len); - Status LRange(const Slice& key, int64_t start, int64_t stop, - std::vector* ret); - Status LRem(const Slice& key, int64_t count, - const Slice& value, uint64_t* ret); + Status LRange(const Slice& key, int64_t start, int64_t stop, std::vector* ret); + Status LRem(const Slice& key, int64_t count, const Slice& value, uint64_t* ret); Status LSet(const Slice& key, int64_t index, const Slice& value); Status LTrim(const Slice& key, int64_t start, int64_t stop); Status RPop(const Slice& key, std::string* element); - Status RPoplpush(const Slice& source, const Slice& destination, - std::string* element); - Status RPush(const Slice& key, const std::vector& values, - uint64_t* ret); + Status RPoplpush(const Slice& source, const Slice& destination, std::string* element); + Status RPush(const Slice& key, const std::vector& values, uint64_t* ret); Status RPushx(const Slice& key, const Slice& value, uint64_t* len); - Status PKScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* keys, std::string* next_key); - Status PKRScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* keys, std::string* next_key); // Keys Commands Status Expire(const Slice& key, int32_t ttl) override; Status Del(const Slice& key) override; - bool Scan(const std::string& start_key, const std::string& pattern, - std::vector* keys, - int64_t* count, std::string* next_key) override; - bool PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) override; + bool Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, int64_t* count, + std::string* next_key) override; + bool PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) override; Status Expireat(const Slice& key, int32_t timestamp) override; Status Persist(const Slice& key) override; Status TTL(const Slice& key, int64_t* timestamp) override; diff --git a/src/storage/src/redis_sets.cc b/src/storage/src/redis_sets.cc index dcac952c68..cd93650cce 100644 --- a/src/storage/src/redis_sets.cc +++ b/src/storage/src/redis_sets.cc @@ -5,31 +5,29 @@ #include "src/redis_sets.h" +#include #include #include #include -#include -#include "storage/util.h" #include "src/base_filter.h" -#include "src/scope_snapshot.h" #include "src/scope_record_lock.h" +#include "src/scope_snapshot.h" +#include "storage/util.h" namespace storage { -RedisSets::RedisSets(Storage* const s, const DataType& type) - : Redis(s, type) { +RedisSets::RedisSets(Storage* const s, const DataType& type) : Redis(s, type) { spop_counts_store_ = new LRUCache(); spop_counts_store_->SetCapacity(1000); } -Status RedisSets::Open(const StorageOptions& storage_options, - const std::string& db_path) { +rocksdb::Status RedisSets::Open(const StorageOptions& storage_options, const std::string& db_path) { statistics_store_->SetCapacity(storage_options.statistics_max_size); small_compaction_threshold_ = storage_options.small_compaction_threshold; rocksdb::Options ops(storage_options.options); - Status s = rocksdb::DB::Open(ops, db_path, &db_); + rocksdb::Status s = rocksdb::DB::Open(ops, db_path, &db_); if (s.ok()) { // create column family rocksdb::ColumnFamilyHandle* cf; @@ -47,10 +45,8 @@ Status RedisSets::Open(const StorageOptions& storage_options, rocksdb::DBOptions db_ops(storage_options.options); rocksdb::ColumnFamilyOptions meta_cf_ops(storage_options.options); rocksdb::ColumnFamilyOptions member_cf_ops(storage_options.options); - meta_cf_ops.compaction_filter_factory = - std::make_shared(); - member_cf_ops.compaction_filter_factory = - std::make_shared(&db_, &handles_); + meta_cf_ops.compaction_filter_factory = std::make_shared(); + member_cf_ops.compaction_filter_factory = std::make_shared(&db_, &handles_); // use the bloom filter policy to reduce disk reads rocksdb::BlockBasedTableOptions table_ops(storage_options.table_options); @@ -58,48 +54,40 @@ Status RedisSets::Open(const StorageOptions& storage_options, rocksdb::BlockBasedTableOptions meta_cf_table_ops(table_ops); rocksdb::BlockBasedTableOptions member_cf_table_ops(table_ops); if (!storage_options.share_block_cache && storage_options.block_cache_size > 0) { - meta_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); - member_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); + meta_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); + member_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); } - meta_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); - member_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(member_cf_table_ops)); + meta_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); + member_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(member_cf_table_ops)); std::vector column_families; // Meta CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor(rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); // Member CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - "member_cf", member_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor("member_cf", member_cf_ops)); return rocksdb::DB::Open(db_ops, db_path, column_families, &handles_, &db_); } -Status RedisSets::CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, - const ColumnFamilyType& type) { +rocksdb::Status RedisSets::CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type) { if (type == kMeta || type == kMetaAndData) { db_->CompactRange(default_compact_range_options_, handles_[0], begin, end); } if (type == kData || type == kMetaAndData) { db_->CompactRange(default_compact_range_options_, handles_[1], begin, end); } - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::GetProperty(const std::string& property, uint64_t* out) { +rocksdb::Status RedisSets::GetProperty(const std::string& property, uint64_t* out) { std::string value; db_->GetProperty(handles_[0], property, &value); *out = std::strtoull(value.c_str(), NULL, 10); db_->GetProperty(handles_[1], property, &value); *out += std::strtoull(value.c_str(), NULL, 10); - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::ScanKeyNum(KeyInfo* key_info) { +rocksdb::Status RedisSets::ScanKeyNum(KeyInfo* key_info) { uint64_t keys = 0; uint64_t expires = 0; uint64_t ttl_sum = 0; @@ -115,12 +103,9 @@ Status RedisSets::ScanKeyNum(KeyInfo* key_info) { rocksdb::Env::Default()->GetCurrentTime(&curtime); rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedSetsMetaValue parsed_sets_meta_value(iter->value()); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { invaild_keys++; } else { keys++; @@ -136,11 +121,10 @@ Status RedisSets::ScanKeyNum(KeyInfo* key_info) { key_info->expires = expires; key_info->avg_ttl = (expires != 0) ? ttl_sum / expires : 0; key_info->invaild_keys = invaild_keys; - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::ScanKeys(const std::string& pattern, - std::vector* keys) { +rocksdb::Status RedisSets::ScanKeys(const std::string& pattern, std::vector* keys) { std::string key; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -149,25 +133,20 @@ Status RedisSets::ScanKeys(const std::string& pattern, iterator_options.fill_cache = false; rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedSetsMetaValue parsed_sets_meta_value(iter->value()); - if (!parsed_sets_meta_value.IsStale() - && parsed_sets_meta_value.count() != 0) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() != 0) { key = iter->key().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } } } delete iter; - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::PKPatternMatchDel(const std::string& pattern, - int32_t* ret) { +rocksdb::Status RedisSets::PKPatternMatchDel(const std::string& pattern, int32_t* ret) { rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); @@ -177,7 +156,7 @@ Status RedisSets::PKPatternMatchDel(const std::string& pattern, std::string key; std::string meta_value; int32_t total_delete = 0; - Status s; + rocksdb::Status s; rocksdb::WriteBatch batch; rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); iter->SeekToFirst(); @@ -185,9 +164,8 @@ Status RedisSets::PKPatternMatchDel(const std::string& pattern, key = iter->key().ToString(); meta_value = iter->value().ToString(); ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (!parsed_sets_meta_value.IsStale() - && parsed_sets_meta_value.count() - && StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() && + StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { parsed_sets_meta_value.InitialMetaValue(); batch.Put(handles_[0], key, meta_value); } @@ -215,8 +193,7 @@ Status RedisSets::PKPatternMatchDel(const std::string& pattern, return s; } -Status RedisSets::SAdd(const Slice& key, - const std::vector& members, int32_t* ret) { +rocksdb::Status RedisSets::SAdd(const Slice& key, const std::vector& members, int32_t* ret) { std::unordered_set unique; std::vector filtered_members; for (const auto& member : members) { @@ -230,11 +207,10 @@ Status RedisSets::SAdd(const Slice& key, ScopeRecordLock l(lock_mgr_, key); int32_t version = 0; std::string meta_value; - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { version = parsed_sets_meta_value.InitialMetaValue(); parsed_sets_meta_value.set_count(filtered_members.size()); batch.Put(handles_[0], key, meta_value); @@ -249,8 +225,7 @@ Status RedisSets::SAdd(const Slice& key, version = parsed_sets_meta_value.version(); for (const auto& member : filtered_members) { SetsMemberKey sets_member_key(key, version, member); - s = db_->Get(default_read_options_, handles_[1], - sets_member_key.Encode(), &member_value); + s = db_->Get(default_read_options_, handles_[1], sets_member_key.Encode(), &member_value); if (s.ok()) { } else if (s.IsNotFound()) { cnt++; @@ -261,7 +236,7 @@ Status RedisSets::SAdd(const Slice& key, } *ret = cnt; if (cnt == 0) { - return Status::OK(); + return rocksdb::Status::OK(); } else { parsed_sets_meta_value.ModifyCount(cnt); batch.Put(handles_[0], key, meta_value); @@ -284,28 +259,27 @@ Status RedisSets::SAdd(const Slice& key, return db_->Write(default_write_options_, &batch); } -Status RedisSets::SCard(const Slice& key, int32_t* ret) { +rocksdb::Status RedisSets::SCard(const Slice& key, int32_t* ret) { *ret = 0; std::string meta_value; - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else { *ret = parsed_sets_meta_value.count(); if (*ret == 0) { - return Status::NotFound("Deleted"); + return rocksdb::Status::NotFound("Deleted"); } } } return s; } -Status RedisSets::SDiff(const std::vector& keys, - std::vector* members) { +rocksdb::Status RedisSets::SDiff(const std::vector& keys, std::vector* members) { if (keys.size() <= 0) { - return Status::Corruption("SDiff invalid parameter, no keys"); + return rocksdb::Status::Corruption("SDiff invalid parameter, no keys"); } rocksdb::ReadOptions read_options; @@ -316,14 +290,13 @@ Status RedisSets::SDiff(const std::vector& keys, ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; std::vector vaild_sets; - Status s; + rocksdb::Status s; for (uint32_t idx = 1; idx < keys.size(); ++idx) { s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (!parsed_sets_meta_value.IsStale() - && parsed_sets_meta_value.count() != 0) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() != 0) { vaild_sets.push_back({keys[idx], parsed_sets_meta_value.version()}); } } else if (!s.IsNotFound()) { @@ -334,8 +307,7 @@ Status RedisSets::SDiff(const std::vector& keys, s = db_->Get(read_options, handles_[0], keys[0], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (!parsed_sets_meta_value.IsStale() - && parsed_sets_meta_value.count() != 0) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() != 0) { bool found; Slice prefix; std::string member_value; @@ -343,18 +315,14 @@ Status RedisSets::SDiff(const std::vector& keys, SetsMemberKey sets_member_key(keys[0], version, Slice()); prefix = sets_member_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); Slice member = parsed_sets_member_key.member(); found = false; for (const auto& key_version : vaild_sets) { - SetsMemberKey sets_member_key(key_version.key, - key_version.version, member); - s = db_->Get(read_options, handles_[1], - sets_member_key.Encode(), &member_value); + SetsMemberKey sets_member_key(key_version.key, key_version.version, member); + s = db_->Get(read_options, handles_[1], sets_member_key.Encode(), &member_value); if (s.ok()) { found = true; break; @@ -372,14 +340,12 @@ Status RedisSets::SDiff(const std::vector& keys, } else if (!s.IsNotFound()) { return s; } - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::SDiffstore(const Slice& destination, - const std::vector& keys, - int32_t* ret) { +rocksdb::Status RedisSets::SDiffstore(const Slice& destination, const std::vector& keys, int32_t* ret) { if (keys.size() <= 0) { - return Status::Corruption("SDiffsotre invalid parameter, no keys"); + return rocksdb::Status::Corruption("SDiffsotre invalid parameter, no keys"); } rocksdb::WriteBatch batch; @@ -392,14 +358,13 @@ Status RedisSets::SDiffstore(const Slice& destination, ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; std::vector vaild_sets; - Status s; + rocksdb::Status s; for (uint32_t idx = 1; idx < keys.size(); ++idx) { s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (!parsed_sets_meta_value.IsStale() - && parsed_sets_meta_value.count() != 0) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() != 0) { vaild_sets.push_back({keys[idx], parsed_sets_meta_value.version()}); } } else if (!s.IsNotFound()) { @@ -411,26 +376,21 @@ Status RedisSets::SDiffstore(const Slice& destination, s = db_->Get(read_options, handles_[0], keys[0], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (!parsed_sets_meta_value.IsStale() - && parsed_sets_meta_value.count() != 0) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() != 0) { bool found; std::string member_value; version = parsed_sets_meta_value.version(); SetsMemberKey sets_member_key(keys[0], version, Slice()); Slice prefix = sets_member_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); Slice member = parsed_sets_member_key.member(); found = false; for (const auto& key_version : vaild_sets) { - SetsMemberKey sets_member_key(key_version.key, - key_version.version, member); - s = db_->Get(read_options, handles_[1], - sets_member_key.Encode(), &member_value); + SetsMemberKey sets_member_key(key_version.key, key_version.version, member); + s = db_->Get(read_options, handles_[1], sets_member_key.Encode(), &member_value); if (s.ok()) { found = true; break; @@ -476,10 +436,9 @@ Status RedisSets::SDiffstore(const Slice& destination, return s; } -Status RedisSets::SInter(const std::vector& keys, - std::vector* members) { +rocksdb::Status RedisSets::SInter(const std::vector& keys, std::vector* members) { if (keys.size() <= 0) { - return Status::Corruption("SInter invalid parameter, no keys"); + return rocksdb::Status::Corruption("SInter invalid parameter, no keys"); } rocksdb::ReadOptions read_options; @@ -490,20 +449,19 @@ Status RedisSets::SInter(const std::vector& keys, ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; std::vector vaild_sets; - Status s; + rocksdb::Status s; for (uint32_t idx = 1; idx < keys.size(); ++idx) { s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { - return Status::OK(); + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { + return rocksdb::Status::OK(); } else { vaild_sets.push_back({keys[idx], parsed_sets_meta_value.version()}); } } else if (s.IsNotFound()) { - return Status::OK(); + return rocksdb::Status::OK(); } else { return s; } @@ -512,9 +470,8 @@ Status RedisSets::SInter(const std::vector& keys, s = db_->Get(read_options, handles_[0], keys[0], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { - return Status::OK(); + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { + return rocksdb::Status::OK(); } else { bool reliable; std::string member_value; @@ -522,18 +479,14 @@ Status RedisSets::SInter(const std::vector& keys, SetsMemberKey sets_member_key(keys[0], version, Slice()); Slice prefix = sets_member_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); Slice member = parsed_sets_member_key.member(); reliable = true; for (const auto& key_version : vaild_sets) { - SetsMemberKey sets_member_key(key_version.key, - key_version.version, member); - s = db_->Get(read_options, handles_[1], - sets_member_key.Encode(), &member_value); + SetsMemberKey sets_member_key(key_version.key, key_version.version, member); + s = db_->Get(read_options, handles_[1], sets_member_key.Encode(), &member_value); if (s.ok()) { continue; } else if (s.IsNotFound()) { @@ -551,18 +504,16 @@ Status RedisSets::SInter(const std::vector& keys, delete iter; } } else if (s.IsNotFound()) { - return Status::OK(); + return rocksdb::Status::OK(); } else { return s; } - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::SInterstore(const Slice& destination, - const std::vector& keys, - int32_t* ret) { +rocksdb::Status RedisSets::SInterstore(const Slice& destination, const std::vector& keys, int32_t* ret) { if (keys.size() <= 0) { - return Status::Corruption("SInterstore invalid parameter, no keys"); + return rocksdb::Status::Corruption("SInterstore invalid parameter, no keys"); } rocksdb::WriteBatch batch; @@ -576,14 +527,13 @@ Status RedisSets::SInterstore(const Slice& destination, ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; std::vector vaild_sets; - Status s; + rocksdb::Status s; for (uint32_t idx = 1; idx < keys.size(); ++idx) { s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { have_invalid_sets = true; break; } else { @@ -602,8 +552,7 @@ Status RedisSets::SInterstore(const Slice& destination, s = db_->Get(read_options, handles_[0], keys[0], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { have_invalid_sets = true; } else { bool reliable; @@ -612,18 +561,14 @@ Status RedisSets::SInterstore(const Slice& destination, SetsMemberKey sets_member_key(keys[0], version, Slice()); Slice prefix = sets_member_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); Slice member = parsed_sets_member_key.member(); reliable = true; for (const auto& key_version : vaild_sets) { - SetsMemberKey sets_member_key(key_version.key, - key_version.version, member); - s = db_->Get(read_options, handles_[1], - sets_member_key.Encode(), &member_value); + SetsMemberKey sets_member_key(key_version.key, key_version.version, member); + s = db_->Get(read_options, handles_[1], sets_member_key.Encode(), &member_value); if (s.ok()) { continue; } else if (s.IsNotFound()) { @@ -673,8 +618,7 @@ Status RedisSets::SInterstore(const Slice& destination, return s; } -Status RedisSets::SIsmember(const Slice& key, const Slice& member, - int32_t* ret) { +rocksdb::Status RedisSets::SIsmember(const Slice& key, const Slice& member, int32_t* ret) { *ret = 0; rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; @@ -683,19 +627,18 @@ Status RedisSets::SIsmember(const Slice& key, const Slice& member, int32_t version = 0; ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; - Status s = db_->Get(read_options, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { std::string member_value; version = parsed_sets_meta_value.version(); SetsMemberKey sets_member_key(key, version, member); - s = db_->Get(read_options, handles_[1], - sets_member_key.Encode(), &member_value); + s = db_->Get(read_options, handles_[1], sets_member_key.Encode(), &member_value); *ret = s.ok() ? 1 : 0; } } else if (s.IsNotFound()) { @@ -704,8 +647,7 @@ Status RedisSets::SIsmember(const Slice& key, const Slice& member, return s; } -Status RedisSets::SMembers(const Slice& key, - std::vector* members) { +rocksdb::Status RedisSets::SMembers(const Slice& key, std::vector* members) { rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; @@ -713,21 +655,19 @@ Status RedisSets::SMembers(const Slice& key, int32_t version = 0; ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; - Status s = db_->Get(read_options, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { version = parsed_sets_meta_value.version(); SetsMemberKey sets_member_key(key, version, Slice()); Slice prefix = sets_member_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); members->push_back(parsed_sets_member_key.member().ToString()); } @@ -737,8 +677,7 @@ Status RedisSets::SMembers(const Slice& key, return s; } -Status RedisSets::SMove(const Slice& source, const Slice& destination, - const Slice& member, int32_t* ret) { +rocksdb::Status RedisSets::SMove(const Slice& source, const Slice& destination, const Slice& member, int32_t* ret) { *ret = 0; rocksdb::WriteBatch batch; rocksdb::ReadOptions read_options; @@ -746,27 +685,26 @@ Status RedisSets::SMove(const Slice& source, const Slice& destination, int32_t version = 0; uint32_t statistic = 0; std::string meta_value; - std::vector keys {source.ToString(), destination.ToString()}; + std::vector keys{source.ToString(), destination.ToString()}; MultiScopeRecordLock ml(lock_mgr_, keys); if (source == destination) { *ret = 1; - return Status::OK(); + return rocksdb::Status::OK(); } - Status s = db_->Get(default_read_options_, handles_[0], source, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], source, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { std::string member_value; version = parsed_sets_meta_value.version(); SetsMemberKey sets_member_key(source, version, member); - s = db_->Get(default_read_options_, handles_[1], - sets_member_key.Encode(), &member_value); + s = db_->Get(default_read_options_, handles_[1], sets_member_key.Encode(), &member_value); if (s.ok()) { *ret = 1; parsed_sets_meta_value.ModifyCount(-1); @@ -775,14 +713,14 @@ Status RedisSets::SMove(const Slice& source, const Slice& destination, statistic++; } else if (s.IsNotFound()) { *ret = 0; - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { return s; } } } else if (s.IsNotFound()) { *ret = 0; - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { return s; } @@ -790,8 +728,7 @@ Status RedisSets::SMove(const Slice& source, const Slice& destination, s = db_->Get(default_read_options_, handles_[0], destination, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { version = parsed_sets_meta_value.InitialMetaValue(); parsed_sets_meta_value.set_count(1); batch.Put(handles_[0], destination, meta_value); @@ -801,8 +738,7 @@ Status RedisSets::SMove(const Slice& source, const Slice& destination, std::string member_value; version = parsed_sets_meta_value.version(); SetsMemberKey sets_member_key(destination, version, member); - s = db_->Get(default_read_options_, handles_[1], - sets_member_key.Encode(), &member_value); + s = db_->Get(default_read_options_, handles_[1], sets_member_key.Encode(), &member_value); if (s.IsNotFound()) { parsed_sets_meta_value.ModifyCount(1); batch.Put(handles_[0], destination, meta_value); @@ -827,9 +763,7 @@ Status RedisSets::SMove(const Slice& source, const Slice& destination, return s; } -Status RedisSets::SPop(const Slice& key, - std::string* member, - bool* need_compact) { +rocksdb::Status RedisSets::SPop(const Slice& key, std::string* member, bool* need_compact) { std::default_random_engine engine; std::string meta_value; @@ -837,13 +771,13 @@ Status RedisSets::SPop(const Slice& key, ScopeRecordLock l(lock_mgr_, key); uint64_t start_us = pstd::NowMicros(); - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { engine.seed(time(NULL)); int32_t cur_index = 0; @@ -853,9 +787,7 @@ Status RedisSets::SPop(const Slice& key, SetsMemberKey sets_member_key(key, version, Slice()); auto iter = db_->NewIterator(default_read_options_, handles_[1]); - for (iter->Seek(sets_member_key.Encode()); - iter->Valid() && cur_index < size; - iter->Next(), cur_index++) { + for (iter->Seek(sets_member_key.Encode()); iter->Valid() && cur_index < size; iter->Next(), cur_index++) { if (cur_index == target_index) { batch.Delete(handles_[1], iter->key()); ParsedSetsMemberKey parsed_sets_member_key(iter->key()); @@ -874,30 +806,26 @@ Status RedisSets::SPop(const Slice& key, uint64_t count = 0; uint64_t duration = pstd::NowMicros() - start_us; AddAndGetSpopCount(key.ToString(), &count); - if (duration >= SPOP_COMPACT_THRESHOLD_DURATION - || count >= SPOP_COMPACT_THRESHOLD_COUNT) { + if (duration >= SPOP_COMPACT_THRESHOLD_DURATION || count >= SPOP_COMPACT_THRESHOLD_COUNT) { *need_compact = true; ResetSpopCount(key.ToString()); } return db_->Write(default_write_options_, &batch); } -Status RedisSets::ResetSpopCount(const std::string& key) { - return spop_counts_store_->Remove(key); -} +rocksdb::Status RedisSets::ResetSpopCount(const std::string& key) { return spop_counts_store_->Remove(key); } -Status RedisSets::AddAndGetSpopCount(const std::string& key, uint64_t* count) { +rocksdb::Status RedisSets::AddAndGetSpopCount(const std::string& key, uint64_t* count) { size_t old_count = 0; spop_counts_store_->Lookup(key, &old_count); spop_counts_store_->Insert(key, old_count + 1); *count = old_count + 1; - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::SRandmember(const Slice& key, int32_t count, - std::vector* members) { +rocksdb::Status RedisSets::SRandmember(const Slice& key, int32_t count, std::vector* members) { if (count == 0) { - return Status::OK(); + return rocksdb::Status::OK(); } members->clear(); @@ -910,13 +838,13 @@ Status RedisSets::SRandmember(const Slice& key, int32_t count, std::vector targets; std::unordered_set unique; - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { int32_t size = parsed_sets_meta_value.count(); int32_t version = parsed_sets_meta_value.version(); @@ -944,15 +872,12 @@ Status RedisSets::SRandmember(const Slice& key, int32_t count, int32_t cur_index = 0, idx = 0; SetsMemberKey sets_member_key(key, version, Slice()); auto iter = db_->NewIterator(default_read_options_, handles_[1]); - for (iter->Seek(sets_member_key.Encode()); - iter->Valid() && cur_index < size; - iter->Next(), cur_index++) { + for (iter->Seek(sets_member_key.Encode()); iter->Valid() && cur_index < size; iter->Next(), cur_index++) { if (static_cast(idx) >= targets.size()) { break; } ParsedSetsMemberKey parsed_sets_member_key(iter->key()); - while (static_cast(idx) < targets.size() - && cur_index == targets[idx]) { + while (static_cast(idx) < targets.size() && cur_index == targets[idx]) { idx++; members->push_back(parsed_sets_member_key.member().ToString()); } @@ -965,9 +890,7 @@ Status RedisSets::SRandmember(const Slice& key, int32_t count, return s; } -Status RedisSets::SRem(const Slice& key, - const std::vector& members, - int32_t* ret) { +rocksdb::Status RedisSets::SRem(const Slice& key, const std::vector& members, int32_t* ret) { *ret = 0; rocksdb::WriteBatch batch; ScopeRecordLock l(lock_mgr_, key); @@ -975,21 +898,20 @@ Status RedisSets::SRem(const Slice& key, int32_t version = 0; uint32_t statistic = 0; std::string meta_value; - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("stale"); + return rocksdb::Status::NotFound("stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { int32_t cnt = 0; std::string member_value; version = parsed_sets_meta_value.version(); for (const auto& member : members) { SetsMemberKey sets_member_key(key, version, member); - s = db_->Get(default_read_options_, handles_[1], - sets_member_key.Encode(), &member_value); + s = db_->Get(default_read_options_, handles_[1], sets_member_key.Encode(), &member_value); if (s.ok()) { cnt++; statistic++; @@ -1005,7 +927,7 @@ Status RedisSets::SRem(const Slice& key, } } else if (s.IsNotFound()) { *ret = 0; - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { return s; } @@ -1014,10 +936,9 @@ Status RedisSets::SRem(const Slice& key, return s; } -Status RedisSets::SUnion(const std::vector& keys, - std::vector* members) { +rocksdb::Status RedisSets::SUnion(const std::vector& keys, std::vector* members) { if (keys.size() <= 0) { - return Status::Corruption("SUnion invalid parameter, no keys"); + return rocksdb::Status::Corruption("SUnion invalid parameter, no keys"); } rocksdb::ReadOptions read_options; @@ -1027,14 +948,13 @@ Status RedisSets::SUnion(const std::vector& keys, ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; std::vector vaild_sets; - Status s; + rocksdb::Status s; for (uint32_t idx = 0; idx < keys.size(); ++idx) { s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (!parsed_sets_meta_value.IsStale() && - parsed_sets_meta_value.count() != 0) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() != 0) { vaild_sets.push_back({keys[idx], parsed_sets_meta_value.version()}); } } else if (!s.IsNotFound()) { @@ -1045,13 +965,10 @@ Status RedisSets::SUnion(const std::vector& keys, Slice prefix; std::map result_flag; for (const auto& key_version : vaild_sets) { - SetsMemberKey sets_member_key(key_version.key, - key_version.version, Slice()); + SetsMemberKey sets_member_key(key_version.key, key_version.version, Slice()); prefix = sets_member_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); std::string member = parsed_sets_member_key.member().ToString(); if (result_flag.find(member) == result_flag.end()) { @@ -1061,14 +978,12 @@ Status RedisSets::SUnion(const std::vector& keys, } delete iter; } - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::SUnionstore(const Slice& destination, - const std::vector& keys, - int32_t* ret) { +rocksdb::Status RedisSets::SUnionstore(const Slice& destination, const std::vector& keys, int32_t* ret) { if (keys.size() <= 0) { - return Status::Corruption("SUnionstore invalid parameter, no keys"); + return rocksdb::Status::Corruption("SUnionstore invalid parameter, no keys"); } rocksdb::WriteBatch batch; @@ -1081,14 +996,13 @@ Status RedisSets::SUnionstore(const Slice& destination, ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; std::vector vaild_sets; - Status s; + rocksdb::Status s; for (uint32_t idx = 0; idx < keys.size(); ++idx) { s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (!parsed_sets_meta_value.IsStale() && - parsed_sets_meta_value.count() != 0) { + if (!parsed_sets_meta_value.IsStale() && parsed_sets_meta_value.count() != 0) { vaild_sets.push_back({keys[idx], parsed_sets_meta_value.version()}); } } else if (!s.IsNotFound()) { @@ -1100,13 +1014,10 @@ Status RedisSets::SUnionstore(const Slice& destination, std::vector members; std::map result_flag; for (const auto& key_version : vaild_sets) { - SetsMemberKey sets_member_key(key_version.key, - key_version.version, Slice()); + SetsMemberKey sets_member_key(key_version.key, key_version.version, Slice()); prefix = sets_member_key.Encode(); auto iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(prefix); - iter->Valid() && iter->key().starts_with(prefix); - iter->Next()) { + for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); std::string member = parsed_sets_member_key.member().ToString(); if (result_flag.find(member) == result_flag.end()) { @@ -1144,17 +1055,13 @@ Status RedisSets::SUnionstore(const Slice& destination, return s; } -Status RedisSets::SScan(const Slice& key, - int64_t cursor, - const std::string& pattern, - int64_t count, - std::vector* members, - int64_t* next_cursor) { +rocksdb::Status RedisSets::SScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* members, int64_t* next_cursor) { *next_cursor = 0; members->clear(); if (cursor < 0) { *next_cursor = 0; - return Status::OK(); + return rocksdb::Status::OK(); } int64_t rest = count; @@ -1165,13 +1072,12 @@ Status RedisSets::SScan(const Slice& key, std::string meta_value; ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; - Status s = db_->Get(read_options, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { *next_cursor = 0; - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { std::string sub_member; std::string start_point; @@ -1191,21 +1097,17 @@ Status RedisSets::SScan(const Slice& key, SetsMemberKey sets_member_key(key, version, start_point); std::string prefix = sets_member_prefix.Encode().ToString(); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(sets_member_key.Encode()); - iter->Valid() && rest > 0 && iter->key().starts_with(prefix); + for (iter->Seek(sets_member_key.Encode()); iter->Valid() && rest > 0 && iter->key().starts_with(prefix); iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(iter->key()); std::string member = parsed_sets_member_key.member().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), member.data(), member.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), member.data(), member.size(), 0)) { members->push_back(member); } rest--; } - if (iter->Valid() - && (iter->key().compare(prefix) <= 0 - || iter->key().starts_with(prefix))) { + if (iter->Valid() && (iter->key().compare(prefix) <= 0 || iter->key().starts_with(prefix))) { *next_cursor = cursor + step_length; ParsedSetsMemberKey parsed_sets_member_key(iter->key()); std::string next_member = parsed_sets_member_key.member().ToString(); @@ -1219,15 +1121,11 @@ Status RedisSets::SScan(const Slice& key, *next_cursor = 0; return s; } - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::PKScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +rocksdb::Status RedisSets::PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1241,10 +1139,8 @@ Status RedisSets::PKScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) > 0)) { - return Status::InvalidArgument("error in given range"); + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) > 0)) { + return rocksdb::Status::InvalidArgument("error in given range"); } rocksdb::Iterator* it = db_->NewIterator(iterator_options, handles_[0]); @@ -1254,16 +1150,13 @@ Status RedisSets::PKScanRange(const Slice& key_start, it->Seek(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedSetsMetaValue parsed_meta_value(it->value()); - if (parsed_meta_value.IsStale() - || parsed_meta_value.count() == 0) { + if (parsed_meta_value.IsStale() || parsed_meta_value.count() == 0) { it->Next(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1271,11 +1164,9 @@ Status RedisSets::PKScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedSetsMetaValue parsed_sets_meta_value(it->value()); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { it->Next(); } else { *next_key = it->key().ToString(); @@ -1283,15 +1174,11 @@ Status RedisSets::PKScanRange(const Slice& key_start, } } delete it; - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::PKRScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +rocksdb::Status RedisSets::PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1305,10 +1192,8 @@ Status RedisSets::PKRScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) < 0)) { - return Status::InvalidArgument("error in given range"); + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) < 0)) { + return rocksdb::Status::InvalidArgument("error in given range"); } rocksdb::Iterator* it = db_->NewIterator(iterator_options, handles_[0]); @@ -1318,16 +1203,13 @@ Status RedisSets::PKRScanRange(const Slice& key_start, it->SeekForPrev(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedSetsMetaValue parsed_sets_meta_value(it->value()); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { it->Prev(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1335,11 +1217,9 @@ Status RedisSets::PKRScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedSetsMetaValue parsed_sets_meta_value(it->value()); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { it->Prev(); } else { *next_key = it->key().ToString(); @@ -1347,19 +1227,19 @@ Status RedisSets::PKRScanRange(const Slice& key_start, } } delete it; - return Status::OK(); + return rocksdb::Status::OK(); } -Status RedisSets::Expire(const Slice& key, int32_t ttl) { +rocksdb::Status RedisSets::Expire(const Slice& key, int32_t ttl) { std::string meta_value; ScopeRecordLock l(lock_mgr_, key); - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } if (ttl > 0) { @@ -1373,16 +1253,16 @@ Status RedisSets::Expire(const Slice& key, int32_t ttl) { return s; } -Status RedisSets::Del(const Slice& key) { +rocksdb::Status RedisSets::Del(const Slice& key) { std::string meta_value; ScopeRecordLock l(lock_mgr_, key); - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { uint32_t statistic = parsed_sets_meta_value.count(); parsed_sets_meta_value.InitialMetaValue(); @@ -1393,11 +1273,8 @@ Status RedisSets::Del(const Slice& key) { return s; } -bool RedisSets::Scan(const std::string& start_key, - const std::string& pattern, - std::vector* keys, - int64_t* count, - std::string* next_key) { +bool RedisSets::Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, + int64_t* count, std::string* next_key) { std::string meta_key; bool is_finish = true; rocksdb::ReadOptions iterator_options; @@ -1411,14 +1288,12 @@ bool RedisSets::Scan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*count) > 0) { ParsedSetsMetaValue parsed_meta_value(it->value()); - if (parsed_meta_value.IsStale() - || parsed_meta_value.count() == 0) { + if (parsed_meta_value.IsStale() || parsed_meta_value.count() == 0) { it->Next(); continue; } else { meta_key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - meta_key.data(), meta_key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), meta_key.data(), meta_key.size(), 0)) { keys->push_back(meta_key); } (*count)--; @@ -1426,10 +1301,8 @@ bool RedisSets::Scan(const std::string& start_key, } } - std::string prefix = isTailWildcard(pattern) ? - pattern.substr(0, pattern.size() - 1) : ""; - if (it->Valid() - && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { + std::string prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; + if (it->Valid() && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { *next_key = it->key().ToString(); is_finish = false; } else { @@ -1439,11 +1312,8 @@ bool RedisSets::Scan(const std::string& start_key, return is_finish; } -bool RedisSets::PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) { +bool RedisSets::PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) { bool is_finish = true; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -1455,13 +1325,11 @@ bool RedisSets::PKExpireScan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*leftover_visits) > 0) { ParsedSetsMetaValue parsed_sets_meta_value(it->value()); - if (parsed_sets_meta_value.IsStale() - || parsed_sets_meta_value.count() == 0) { + if (parsed_sets_meta_value.IsStale() || parsed_sets_meta_value.count() == 0) { it->Next(); continue; } else { - if (min_timestamp < parsed_sets_meta_value.timestamp() - && parsed_sets_meta_value.timestamp() < max_timestamp) { + if (min_timestamp < parsed_sets_meta_value.timestamp() && parsed_sets_meta_value.timestamp() < max_timestamp) { keys->push_back(it->key().ToString()); } (*leftover_visits)--; @@ -1479,16 +1347,16 @@ bool RedisSets::PKExpireScan(const std::string& start_key, return is_finish; } -Status RedisSets::Expireat(const Slice& key, int32_t timestamp) { +rocksdb::Status RedisSets::Expireat(const Slice& key, int32_t timestamp) { std::string meta_value; ScopeRecordLock l(lock_mgr_, key); - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { if (timestamp > 0) { parsed_sets_meta_value.set_timestamp(timestamp); @@ -1501,20 +1369,20 @@ Status RedisSets::Expireat(const Slice& key, int32_t timestamp) { return s; } -Status RedisSets::Persist(const Slice& key) { +rocksdb::Status RedisSets::Persist(const Slice& key) { std::string meta_value; ScopeRecordLock l(lock_mgr_, key); - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_sets_meta_value(&meta_value); if (parsed_sets_meta_value.IsStale()) { - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_sets_meta_value.count() == 0) { - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { int32_t timestamp = parsed_sets_meta_value.timestamp(); if (timestamp == 0) { - return Status::NotFound("Not have an associated timeout"); + return rocksdb::Status::NotFound("Not have an associated timeout"); } else { parsed_sets_meta_value.set_timestamp(0); return db_->Put(default_write_options_, handles_[0], key, meta_value); @@ -1524,17 +1392,17 @@ Status RedisSets::Persist(const Slice& key) { return s; } -Status RedisSets::TTL(const Slice& key, int64_t* timestamp) { +rocksdb::Status RedisSets::TTL(const Slice& key, int64_t* timestamp) { std::string meta_value; - Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); + rocksdb::Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedSetsMetaValue parsed_setes_meta_value(&meta_value); if (parsed_setes_meta_value.IsStale()) { *timestamp = -2; - return Status::NotFound("Stale"); + return rocksdb::Status::NotFound("Stale"); } else if (parsed_setes_meta_value.count() == 0) { *timestamp = -2; - return Status::NotFound(); + return rocksdb::Status::NotFound(); } else { *timestamp = parsed_setes_meta_value.timestamp(); if (*timestamp == 0) { @@ -1561,35 +1429,27 @@ void RedisSets::ScanDatabase() { printf("\n***************Sets Meta Data***************\n"); auto meta_iter = db_->NewIterator(iterator_options, handles_[0]); - for (meta_iter->SeekToFirst(); - meta_iter->Valid(); - meta_iter->Next()) { + for (meta_iter->SeekToFirst(); meta_iter->Valid(); meta_iter->Next()) { ParsedSetsMetaValue parsed_sets_meta_value(meta_iter->value()); int32_t survival_time = 0; if (parsed_sets_meta_value.timestamp() != 0) { - survival_time = parsed_sets_meta_value.timestamp() - current_time > 0 ? - parsed_sets_meta_value.timestamp() - current_time : -1; + survival_time = parsed_sets_meta_value.timestamp() - current_time > 0 + ? parsed_sets_meta_value.timestamp() - current_time + : -1; } printf("[key : %-30s] [count : %-10d] [timestamp : %-10d] [version : %d] [survival_time : %d]\n", - meta_iter->key().ToString().c_str(), - parsed_sets_meta_value.count(), - parsed_sets_meta_value.timestamp(), - parsed_sets_meta_value.version(), - survival_time); + meta_iter->key().ToString().c_str(), parsed_sets_meta_value.count(), parsed_sets_meta_value.timestamp(), + parsed_sets_meta_value.version(), survival_time); } delete meta_iter; printf("\n***************Sets Member Data***************\n"); auto member_iter = db_->NewIterator(iterator_options, handles_[1]); - for (member_iter->SeekToFirst(); - member_iter->Valid(); - member_iter->Next()) { + for (member_iter->SeekToFirst(); member_iter->Valid(); member_iter->Next()) { ParsedSetsMemberKey parsed_sets_member_key(member_iter->key()); - printf("[key : %-30s] [member : %-20s] [version : %d]\n", - parsed_sets_member_key.key().ToString().c_str(), - parsed_sets_member_key.member().ToString().c_str(), - parsed_sets_member_key.version()); + printf("[key : %-30s] [member : %-20s] [version : %d]\n", parsed_sets_member_key.key().ToString().c_str(), + parsed_sets_member_key.member().ToString().c_str(), parsed_sets_member_key.version()); } delete member_iter; } diff --git a/src/storage/src/redis_sets.h b/src/storage/src/redis_sets.h index fc0d7c9551..f091204d13 100644 --- a/src/storage/src/redis_sets.h +++ b/src/storage/src/redis_sets.h @@ -7,17 +7,17 @@ #define SRC_REDIS_SETS_H_ #include -#include #include +#include #include "pstd/include/env.h" -#include "src/redis.h" -#include "src/lru_cache.h" #include "src/custom_comparator.h" +#include "src/lru_cache.h" +#include "src/redis.h" -#define SPOP_COMPACT_THRESHOLD_COUNT 500 -#define SPOP_COMPACT_THRESHOLD_DURATION 1000 * 1000 // 1000ms +#define SPOP_COMPACT_THRESHOLD_COUNT 500 +#define SPOP_COMPACT_THRESHOLD_DURATION 1000 * 1000 // 1000ms namespace storage { @@ -27,68 +27,43 @@ class RedisSets : public Redis { ~RedisSets() = default; // Common Commands - Status Open(const StorageOptions& storage_options, - const std::string& db_path) override; - Status CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, + Status Open(const StorageOptions& storage_options, const std::string& db_path) override; + Status CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type = kMetaAndData) override; Status GetProperty(const std::string& property, uint64_t* out) override; Status ScanKeyNum(KeyInfo* key_info) override; - Status ScanKeys(const std::string& pattern, - std::vector* keys) override; + Status ScanKeys(const std::string& pattern, std::vector* keys) override; Status PKPatternMatchDel(const std::string& pattern, int32_t* ret) override; // Setes Commands - Status SAdd(const Slice& key, - const std::vector& members, int32_t* ret); + Status SAdd(const Slice& key, const std::vector& members, int32_t* ret); Status SCard(const Slice& key, int32_t* ret); - Status SDiff(const std::vector& keys, - std::vector* members); - Status SDiffstore(const Slice& destination, - const std::vector& keys, - int32_t* ret); - Status SInter(const std::vector& keys, - std::vector* members); - Status SInterstore(const Slice& destination, - const std::vector& keys, - int32_t* ret); - Status SIsmember(const Slice& key, const Slice& member, - int32_t* ret); - Status SMembers(const Slice& key, - std::vector* members); - Status SMove(const Slice& source, const Slice& destination, - const Slice& member, int32_t* ret); + Status SDiff(const std::vector& keys, std::vector* members); + Status SDiffstore(const Slice& destination, const std::vector& keys, int32_t* ret); + Status SInter(const std::vector& keys, std::vector* members); + Status SInterstore(const Slice& destination, const std::vector& keys, int32_t* ret); + Status SIsmember(const Slice& key, const Slice& member, int32_t* ret); + Status SMembers(const Slice& key, std::vector* members); + Status SMove(const Slice& source, const Slice& destination, const Slice& member, int32_t* ret); Status SPop(const Slice& key, std::string* member, bool* need_compact); - Status SRandmember(const Slice& key, int32_t count, - std::vector* members); - Status SRem(const Slice& key, const std::vector& members, - int32_t* ret); - Status SUnion(const std::vector& keys, - std::vector* members); - Status SUnionstore(const Slice& destination, - const std::vector& keys, - int32_t* ret); - Status SScan(const Slice& key, int64_t cursor, - const std::string& pattern, int64_t count, + Status SRandmember(const Slice& key, int32_t count, std::vector* members); + Status SRem(const Slice& key, const std::vector& members, int32_t* ret); + Status SUnion(const std::vector& keys, std::vector* members); + Status SUnionstore(const Slice& destination, const std::vector& keys, int32_t* ret); + Status SScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, std::vector* members, int64_t* next_cursor); - Status PKScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* keys, std::string* next_key); - Status PKRScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* keys, std::string* next_key); // Keys Commands Status Expire(const Slice& key, int32_t ttl) override; Status Del(const Slice& key) override; - bool Scan(const std::string& start_key, const std::string& pattern, - std::vector* keys, - int64_t* count, std::string* next_key) override; - bool PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) override; + bool Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, int64_t* count, + std::string* next_key) override; + bool PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) override; Status Expireat(const Slice& key, int32_t timestamp) override; Status Persist(const Slice& key) override; Status TTL(const Slice& key, int64_t* timestamp) override; diff --git a/src/storage/src/redis_strings.cc b/src/storage/src/redis_strings.cc index a0e4edeb25..8b4164d22a 100644 --- a/src/storage/src/redis_strings.cc +++ b/src/storage/src/redis_strings.cc @@ -5,24 +5,21 @@ #include "src/redis_strings.h" -#include -#include #include +#include #include +#include -#include "storage/util.h" -#include "src/strings_filter.h" #include "src/scope_record_lock.h" #include "src/scope_snapshot.h" +#include "src/strings_filter.h" +#include "storage/util.h" namespace storage { -RedisStrings::RedisStrings(Storage* const s, const DataType& type) - : Redis(s, type) { -} +RedisStrings::RedisStrings(Storage* const s, const DataType& type) : Redis(s, type) {} -Status RedisStrings::Open(const StorageOptions& storage_options, - const std::string& db_path) { +Status RedisStrings::Open(const StorageOptions& storage_options, const std::string& db_path) { rocksdb::Options ops(storage_options.options); ops.compaction_filter_factory = std::make_shared(); @@ -37,8 +34,7 @@ Status RedisStrings::Open(const StorageOptions& storage_options, return rocksdb::DB::Open(ops, db_path, &db_); } -Status RedisStrings::CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, +Status RedisStrings::CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type) { return db_->CompactRange(default_compact_range_options_, begin, end); } @@ -68,9 +64,7 @@ Status RedisStrings::ScanKeyNum(KeyInfo* key_info) { // Note: This is a string type and does not need to pass the column family as // a parameter, use the default column family rocksdb::Iterator* iter = db_->NewIterator(iterator_options); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedStringsValue parsed_strings_value(iter->value()); if (parsed_strings_value.IsStale()) { invaild_keys++; @@ -91,8 +85,7 @@ Status RedisStrings::ScanKeyNum(KeyInfo* key_info) { return Status::OK(); } -Status RedisStrings::ScanKeys(const std::string& pattern, - std::vector* keys) { +Status RedisStrings::ScanKeys(const std::string& pattern, std::vector* keys) { std::string key; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -103,14 +96,11 @@ Status RedisStrings::ScanKeys(const std::string& pattern, // Note: This is a string type and does not need to pass the column family as // a parameter, use the default column family rocksdb::Iterator* iter = db_->NewIterator(iterator_options); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedStringsValue parsed_strings_value(iter->value()); if (!parsed_strings_value.IsStale()) { key = iter->key().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } } @@ -119,8 +109,7 @@ Status RedisStrings::ScanKeys(const std::string& pattern, return Status::OK(); } -Status RedisStrings::PKPatternMatchDel(const std::string& pattern, - int32_t* ret) { +Status RedisStrings::PKPatternMatchDel(const std::string& pattern, int32_t* ret) { rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); @@ -138,8 +127,7 @@ Status RedisStrings::PKPatternMatchDel(const std::string& pattern, key = iter->key().ToString(); value = iter->value().ToString(); ParsedStringsValue parsed_strings_value(&value); - if (!parsed_strings_value.IsStale() - && StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { + if (!parsed_strings_value.IsStale() && StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { batch.Delete(key); } // In order to be more efficient, we use batch deletion here @@ -167,8 +155,7 @@ Status RedisStrings::PKPatternMatchDel(const std::string& pattern, return s; } -Status RedisStrings::Append(const Slice& key, const Slice& value, - int32_t* ret) { +Status RedisStrings::Append(const Slice& key, const Slice& value, int32_t* ret) { std::string old_value; *ret = 0; ScopeRecordLock l(lock_mgr_, key); @@ -198,32 +185,22 @@ Status RedisStrings::Append(const Slice& key, const Slice& value, int GetBitCount(const unsigned char* value, int64_t bytes) { int bit_num = 0; - static const unsigned char bitsinbyte[256] = - {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; + static const unsigned char bitsinbyte[256] = { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, + 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, + 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, + 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, + 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, + 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, + 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; for (int i = 0; i < bytes; i++) { bit_num += bitsinbyte[static_cast(value[i])]; } return bit_num; } -Status RedisStrings::BitCount(const Slice& key, - int64_t start_offset, int64_t end_offset, - int32_t* ret, bool have_range) { +Status RedisStrings::BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, int32_t* ret, + bool have_range) { *ret = 0; std::string value; Status s = db_->Get(default_read_options_, key, &value); @@ -233,8 +210,7 @@ Status RedisStrings::BitCount(const Slice& key, return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); - const unsigned char* bit_value = - reinterpret_cast(value.data()); + const unsigned char* bit_value = reinterpret_cast(value.data()); int64_t value_length = value.length(); if (have_range) { if (start_offset < 0) { @@ -251,7 +227,7 @@ Status RedisStrings::BitCount(const Slice& key, } if (end_offset >= value_length) { - end_offset = value_length -1; + end_offset = value_length - 1; } if (start_offset > end_offset) { return Status::OK(); @@ -260,8 +236,7 @@ Status RedisStrings::BitCount(const Slice& key, start_offset = 0; end_offset = std::max(value_length - 1, static_cast(0)); } - *ret = GetBitCount(bit_value + start_offset, - end_offset - start_offset + 1); + *ret = GetBitCount(bit_value + start_offset, end_offset - start_offset + 1); } } else { return s; @@ -269,9 +244,7 @@ Status RedisStrings::BitCount(const Slice& key, return Status::OK(); } -std::string BitOpOperate(BitOpType op, - const std::vector &src_values, - int64_t max_len) { +std::string BitOpOperate(BitOpType op, const std::vector& src_values, int64_t max_len) { char* dest_value = new char[max_len]; char byte, output; @@ -313,9 +286,7 @@ std::string BitOpOperate(BitOpType op, return dest_str; } -Status RedisStrings::BitOp(BitOpType op, - const std::string& dest_key, - const std::vector& src_keys, +Status RedisStrings::BitOp(BitOpType op, const std::string& dest_key, const std::vector& src_keys, int64_t* ret) { Status s; if (op == kBitOpNot && src_keys.size() != 1) { @@ -351,8 +322,7 @@ Status RedisStrings::BitOp(BitOpType op, std::string dest_value = BitOpOperate(op, src_values, max_len); *ret = dest_value.size(); - StringsValue strings_value(Slice(dest_value.c_str(), - static_cast(max_len))); + StringsValue strings_value(Slice(dest_value.c_str(), static_cast(max_len))); ScopeRecordLock l(lock_mgr_, dest_key); return db_->Put(default_write_options_, dest_key, strings_value.Encode()); } @@ -377,8 +347,7 @@ Status RedisStrings::Decrby(const Slice& key, int64_t value, int64_t* ret) { if (*end != 0) { return Status::Corruption("Value is not a integer"); } - if ((value >= 0 && LLONG_MIN + value > ival) || - (value < 0 && LLONG_MAX + value < ival)) { + if ((value >= 0 && LLONG_MIN + value > ival) || (value < 0 && LLONG_MAX + value < ival)) { return Status::InvalidArgument("Overflow"); } *ret = ival - value; @@ -439,9 +408,7 @@ Status RedisStrings::GetBit(const Slice& key, int64_t offset, int32_t* ret) { return Status::OK(); } -Status RedisStrings::Getrange(const Slice& key, - int64_t start_offset, int64_t end_offset, - std::string* ret) { +Status RedisStrings::Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, std::string* ret) { *ret = ""; std::string value; Status s = db_->Get(default_read_options_, key, &value); @@ -454,14 +421,11 @@ Status RedisStrings::Getrange(const Slice& key, int64_t size = value.size(); int64_t start_t = start_offset >= 0 ? start_offset : size + start_offset; int64_t end_t = end_offset >= 0 ? end_offset : size + end_offset; - if (start_t > size - 1 || - (start_t != 0 && start_t > end_t) || - (start_t != 0 && end_t < 0) - ) { + if (start_t > size - 1 || (start_t != 0 && start_t > end_t) || (start_t != 0 && end_t < 0)) { return Status::OK(); } if (start_t < 0) { - start_t = 0; + start_t = 0; } if (end_t >= size) { end_t = size - 1; @@ -469,7 +433,7 @@ Status RedisStrings::Getrange(const Slice& key, if (start_t == 0 && end_t < 0) { end_t = 0; } - *ret = value.substr(start_t, end_t-start_t+1); + *ret = value.substr(start_t, end_t - start_t + 1); return Status::OK(); } } else { @@ -477,8 +441,7 @@ Status RedisStrings::Getrange(const Slice& key, } } -Status RedisStrings::GetSet(const Slice& key, const Slice& value, - std::string* old_value) { +Status RedisStrings::GetSet(const Slice& key, const Slice& value, std::string* old_value) { ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, old_value); if (s.ok()) { @@ -516,8 +479,7 @@ Status RedisStrings::Incrby(const Slice& key, int64_t value, int64_t* ret) { if (*end != 0) { return Status::Corruption("Value is not a integer"); } - if ((value >= 0 && LLONG_MAX - value < ival) || - (value < 0 && LLONG_MIN - value > ival)) { + if ((value >= 0 && LLONG_MAX - value < ival) || (value < 0 && LLONG_MIN - value > ival)) { return Status::InvalidArgument("Overflow"); } *ret = ival + value; @@ -537,8 +499,7 @@ Status RedisStrings::Incrby(const Slice& key, int64_t value, int64_t* ret) { } } -Status RedisStrings::Incrbyfloat(const Slice& key, const Slice& value, - std::string* ret) { +Status RedisStrings::Incrbyfloat(const Slice& key, const Slice& value, std::string* ret) { std::string old_value, new_value; long double long_double_by; if (StrToLongDouble(value.data(), value.size(), &long_double_by) == -1) { @@ -557,8 +518,7 @@ Status RedisStrings::Incrbyfloat(const Slice& key, const Slice& value, int32_t timestamp = parsed_strings_value.timestamp(); std::string old_user_value = parsed_strings_value.value().ToString(); long double total, old_number; - if (StrToLongDouble(old_user_value.data(), - old_user_value.size(), &old_number) == -1) { + if (StrToLongDouble(old_user_value.data(), old_user_value.size(), &old_number) == -1) { return Status::Corruption("Value is not a vaild float"); } total = old_number + long_double_by; @@ -580,8 +540,7 @@ Status RedisStrings::Incrbyfloat(const Slice& key, const Slice& value, } } -Status RedisStrings::MGet(const std::vector& keys, - std::vector* vss) { +Status RedisStrings::MGet(const std::vector& keys, std::vector* vss) { vss->clear(); Status s; @@ -597,8 +556,7 @@ Status RedisStrings::MGet(const std::vector& keys, if (parsed_strings_value.IsStale()) { vss->push_back({std::string(), Status::NotFound("Stale")}); } else { - vss->push_back( - {parsed_strings_value.user_value().ToString(), Status::OK()}); + vss->push_back({parsed_strings_value.user_value().ToString(), Status::OK()}); } } else if (s.IsNotFound()) { vss->push_back({std::string(), Status::NotFound()}); @@ -612,7 +570,7 @@ Status RedisStrings::MGet(const std::vector& keys, Status RedisStrings::MSet(const std::vector& kvs) { std::vector keys; - for (const auto& kv : kvs) { + for (const auto& kv : kvs) { keys.push_back(kv.key); } @@ -625,8 +583,7 @@ Status RedisStrings::MSet(const std::vector& kvs) { return db_->Write(default_write_options_, &batch); } -Status RedisStrings::MSetnx(const std::vector& kvs, - int32_t* ret) { +Status RedisStrings::MSetnx(const std::vector& kvs, int32_t* ret) { Status s; bool exists = false; *ret = 0; @@ -650,17 +607,13 @@ Status RedisStrings::MSetnx(const std::vector& kvs, return s; } -Status RedisStrings::Set(const Slice& key, - const Slice& value) { +Status RedisStrings::Set(const Slice& key, const Slice& value) { StringsValue strings_value(value); ScopeRecordLock l(lock_mgr_, key); return db_->Put(default_write_options_, key, strings_value.Encode()); } -Status RedisStrings::Setxx(const Slice& key, - const Slice& value, - int32_t* ret, - const int32_t ttl) { +Status RedisStrings::Setxx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { bool not_found = true; std::string old_value; StringsValue strings_value(value); @@ -687,8 +640,7 @@ Status RedisStrings::Setxx(const Slice& key, } } -Status RedisStrings::SetBit(const Slice& key, int64_t offset, - int32_t on, int32_t* ret) { +Status RedisStrings::SetBit(const Slice& key, int64_t offset, int32_t on, int32_t* ret) { std::string meta_value; if (offset < 0) { return Status::InvalidArgument("offset < 0"); @@ -727,7 +679,7 @@ Status RedisStrings::SetBit(const Slice& key, int64_t offset, data_value.append(1, byte_val); } StringsValue strings_value(data_value); - return db_->Put(rocksdb::WriteOptions(), key, strings_value.Encode()); + return db_->Put(rocksdb::WriteOptions(), key, strings_value.Encode()); } else { return s; } @@ -743,10 +695,7 @@ Status RedisStrings::Setex(const Slice& key, const Slice& value, int32_t ttl) { return db_->Put(default_write_options_, key, strings_value.Encode()); } -Status RedisStrings::Setnx(const Slice& key, - const Slice& value, - int32_t* ret, - const int32_t ttl) { +Status RedisStrings::Setnx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { *ret = 0; std::string old_value; ScopeRecordLock l(lock_mgr_, key); @@ -776,10 +725,7 @@ Status RedisStrings::Setnx(const Slice& key, return s; } -Status RedisStrings::Setvx(const Slice& key, - const Slice& value, - const Slice& new_value, - int32_t* ret, +Status RedisStrings::Setvx(const Slice& key, const Slice& value, const Slice& new_value, int32_t* ret, const int32_t ttl) { *ret = 0; std::string old_value; @@ -836,8 +782,7 @@ Status RedisStrings::Delvx(const Slice& key, const Slice& value, int32_t* ret) { return s; } -Status RedisStrings::Setrange(const Slice& key, int64_t start_offset, - const Slice& value, int32_t* ret) { +Status RedisStrings::Setrange(const Slice& key, int64_t start_offset, const Slice& value, int32_t* ret) { std::string old_value; std::string new_value; if (start_offset < 0) { @@ -879,7 +824,7 @@ Status RedisStrings::Setrange(const Slice& key, int64_t start_offset, return s; } -Status RedisStrings::Strlen(const Slice& key, int32_t *len) { +Status RedisStrings::Strlen(const Slice& key, int32_t* len) { std::string value; Status s = Get(key, &value); if (s.ok()) { @@ -893,8 +838,8 @@ Status RedisStrings::Strlen(const Slice& key, int32_t *len) { int32_t GetBitPos(const unsigned char* s, unsigned int bytes, int bit) { uint64_t word = 0; uint64_t skip_val = 0; - unsigned char* value = const_cast(s); - uint64_t* l = reinterpret_cast(value); + unsigned char* value = const_cast(s); + uint64_t* l = reinterpret_cast(value); int pos = 0; if (bit == 0) { skip_val = std::numeric_limits::max(); @@ -910,7 +855,7 @@ int32_t GetBitPos(const unsigned char* s, unsigned int bytes, int bit) { bytes = bytes - sizeof(*l); pos = pos + 8 * sizeof(*l); } - unsigned char * c = reinterpret_cast(l); + unsigned char* c = reinterpret_cast(l); for (size_t j = 0; j < sizeof(*l); j++) { word = word << 8; if (bytes) { @@ -936,8 +881,7 @@ int32_t GetBitPos(const unsigned char* s, unsigned int bytes, int bit) { return pos; } -Status RedisStrings::BitPos(const Slice& key, int32_t bit, - int64_t* ret) { +Status RedisStrings::BitPos(const Slice& key, int32_t bit, int64_t* ret) { Status s; std::string value; s = db_->Get(default_read_options_, key, &value); @@ -952,8 +896,7 @@ Status RedisStrings::BitPos(const Slice& key, int32_t bit, return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); - const unsigned char* bit_value = - reinterpret_cast(value.data()); + const unsigned char* bit_value = reinterpret_cast(value.data()); int64_t value_length = value.length(); int64_t start_offset = 0; int64_t end_offset = std::max(value_length - 1, static_cast(0)); @@ -973,8 +916,7 @@ Status RedisStrings::BitPos(const Slice& key, int32_t bit, return Status::OK(); } -Status RedisStrings::BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t* ret) { +Status RedisStrings::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t* ret) { Status s; std::string value; s = db_->Get(default_read_options_, key, &value); @@ -989,8 +931,7 @@ Status RedisStrings::BitPos(const Slice& key, int32_t bit, return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); - const unsigned char* bit_value = - reinterpret_cast(value.data()); + const unsigned char* bit_value = reinterpret_cast(value.data()); int64_t value_length = value.length(); int64_t end_offset = std::max(value_length - 1, static_cast(0)); if (start_offset < 0) { @@ -1023,9 +964,7 @@ Status RedisStrings::BitPos(const Slice& key, int32_t bit, return Status::OK(); } -Status RedisStrings::BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t end_offset, - int64_t* ret) { +Status RedisStrings::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t end_offset, int64_t* ret) { Status s; std::string value; s = db_->Get(default_read_options_, key, &value); @@ -1040,8 +979,7 @@ Status RedisStrings::BitPos(const Slice& key, int32_t bit, return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); - const unsigned char* bit_value = - reinterpret_cast(value.data()); + const unsigned char* bit_value = reinterpret_cast(value.data()); int64_t value_length = value.length(); if (start_offset < 0) { start_offset = start_offset + value_length; @@ -1090,12 +1028,8 @@ Status RedisStrings::PKSetexAt(const Slice& key, const Slice& value, int32_t tim return db_->Put(default_write_options_, key, strings_value.Encode()); } -Status RedisStrings::PKScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* kvs, - std::string* next_key) { +Status RedisStrings::PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* kvs, std::string* next_key) { next_key->clear(); std::string key, value; @@ -1109,9 +1043,7 @@ Status RedisStrings::PKScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) > 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) > 0)) { return Status::InvalidArgument("error in given range"); } @@ -1124,16 +1056,14 @@ Status RedisStrings::PKScanRange(const Slice& key_start, it->Seek(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Next(); } else { key = it->key().ToString(); value = parsed_strings_value.value().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { kvs->push_back({key, value}); } remain--; @@ -1141,8 +1071,7 @@ Status RedisStrings::PKScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Next(); @@ -1155,12 +1084,8 @@ Status RedisStrings::PKScanRange(const Slice& key_start, return Status::OK(); } -Status RedisStrings::PKRScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* kvs, - std::string* next_key) { +Status RedisStrings::PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* kvs, std::string* next_key) { std::string key, value; int32_t remain = limit; rocksdb::ReadOptions iterator_options; @@ -1172,9 +1097,7 @@ Status RedisStrings::PKRScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) < 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) < 0)) { return Status::InvalidArgument("error in given range"); } @@ -1187,16 +1110,14 @@ Status RedisStrings::PKRScanRange(const Slice& key_start, it->SeekForPrev(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Prev(); } else { key = it->key().ToString(); value = parsed_strings_value.value().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { kvs->push_back({key, value}); } remain--; @@ -1204,8 +1125,7 @@ Status RedisStrings::PKRScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Prev(); @@ -1218,7 +1138,6 @@ Status RedisStrings::PKRScanRange(const Slice& key_start, return Status::OK(); } - Status RedisStrings::Expire(const Slice& key, int32_t ttl) { std::string value; ScopeRecordLock l(lock_mgr_, key); @@ -1252,11 +1171,8 @@ Status RedisStrings::Del(const Slice& key) { return s; } -bool RedisStrings::Scan(const std::string& start_key, - const std::string& pattern, - std::vector* keys, - int64_t* count, - std::string* next_key) { +bool RedisStrings::Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, + int64_t* count, std::string* next_key) { std::string key; bool is_finish = true; rocksdb::ReadOptions iterator_options; @@ -1277,8 +1193,7 @@ bool RedisStrings::Scan(const std::string& start_key, continue; } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } (*count)--; @@ -1286,10 +1201,8 @@ bool RedisStrings::Scan(const std::string& start_key, } } - std::string prefix = isTailWildcard(pattern) ? - pattern.substr(0, pattern.size() - 1) : ""; - if (it->Valid() - && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { + std::string prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; + if (it->Valid() && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { is_finish = false; *next_key = it->key().ToString(); } else { @@ -1299,11 +1212,8 @@ bool RedisStrings::Scan(const std::string& start_key, return is_finish; } -bool RedisStrings::PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) { +bool RedisStrings::PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) { bool is_finish = true; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -1320,8 +1230,7 @@ bool RedisStrings::PKExpireScan(const std::string& start_key, it->Next(); continue; } else { - if (min_timestamp < parsed_strings_value.timestamp() - && parsed_strings_value.timestamp() < max_timestamp) { + if (min_timestamp < parsed_strings_value.timestamp() && parsed_strings_value.timestamp() < max_timestamp) { keys->push_back(it->key().ToString()); } (*leftover_visits)--; @@ -1415,22 +1324,17 @@ void RedisStrings::ScanDatabase() { printf("\n***************String Data***************\n"); auto iter = db_->NewIterator(iterator_options); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedStringsValue parsed_strings_value(iter->value()); int32_t survival_time = 0; if (parsed_strings_value.timestamp() != 0) { - survival_time = parsed_strings_value.timestamp() - current_time > 0 ? - parsed_strings_value.timestamp() - current_time : -1; + survival_time = + parsed_strings_value.timestamp() - current_time > 0 ? parsed_strings_value.timestamp() - current_time : -1; } printf("[key : %-30s] [value : %-30s] [timestamp : %-10d] [version : %d] [survival_time : %d]\n", - iter->key().ToString().c_str(), - parsed_strings_value.value().ToString().c_str(), - parsed_strings_value.timestamp(), - parsed_strings_value.version(), - survival_time); + iter->key().ToString().c_str(), parsed_strings_value.value().ToString().c_str(), + parsed_strings_value.timestamp(), parsed_strings_value.version(), survival_time); } delete iter; } diff --git a/src/storage/src/redis_strings.h b/src/storage/src/redis_strings.h index 7f9e5e9e47..e7449e877c 100644 --- a/src/storage/src/redis_strings.h +++ b/src/storage/src/redis_strings.h @@ -6,9 +6,9 @@ #ifndef SRC_REDIS_STRINGS_H_ #define SRC_REDIS_STRINGS_H_ +#include #include #include -#include #include "src/redis.h" @@ -20,75 +20,54 @@ class RedisStrings : public Redis { ~RedisStrings() = default; // Common Commands - Status Open(const StorageOptions& storage_options, - const std::string& db_path) override; - Status CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, + Status Open(const StorageOptions& storage_options, const std::string& db_path) override; + Status CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type = kMetaAndData) override; Status GetProperty(const std::string& property, uint64_t* out) override; Status ScanKeyNum(KeyInfo* key_info) override; - Status ScanKeys(const std::string& pattern, - std::vector* keys) override; + Status ScanKeys(const std::string& pattern, std::vector* keys) override; Status PKPatternMatchDel(const std::string& pattern, int32_t* ret) override; // Strings Commands Status Append(const Slice& key, const Slice& value, int32_t* ret); - Status BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, - int32_t* ret, bool have_offset); - Status BitOp(BitOpType op, const std::string& dest_key, - const std::vector& src_keys, int64_t* ret); + Status BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, int32_t* ret, bool have_offset); + Status BitOp(BitOpType op, const std::string& dest_key, const std::vector& src_keys, int64_t* ret); Status Decrby(const Slice& key, int64_t value, int64_t* ret); Status Get(const Slice& key, std::string* value); Status GetBit(const Slice& key, int64_t offset, int32_t* ret); - Status Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, - std::string* ret); + Status Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, std::string* ret); Status GetSet(const Slice& key, const Slice& value, std::string* old_value); Status Incrby(const Slice& key, int64_t value, int64_t* ret); Status Incrbyfloat(const Slice& key, const Slice& value, std::string* ret); - Status MGet(const std::vector& keys, - std::vector* vss); + Status MGet(const std::vector& keys, std::vector* vss); Status MSet(const std::vector& kvs); Status MSetnx(const std::vector& kvs, int32_t* ret); Status Set(const Slice& key, const Slice& value); - Status Setxx(const Slice& key, const Slice& value, - int32_t* ret, const int32_t ttl = 0); - Status SetBit(const Slice& key, int64_t offset, - int32_t value, int32_t* ret); + Status Setxx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl = 0); + Status SetBit(const Slice& key, int64_t offset, int32_t value, int32_t* ret); Status Setex(const Slice& key, const Slice& value, int32_t ttl); - Status Setnx(const Slice& key, const Slice& value, - int32_t* ret, const int32_t ttl = 0); - Status Setvx(const Slice& key, const Slice& value, - const Slice& new_value, int32_t* ret, const int32_t ttl = 0); + Status Setnx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl = 0); + Status Setvx(const Slice& key, const Slice& value, const Slice& new_value, int32_t* ret, const int32_t ttl = 0); Status Delvx(const Slice& key, const Slice& value, int32_t* ret); - Status Setrange(const Slice& key, int64_t start_offset, - const Slice& value, int32_t* ret); - Status Strlen(const Slice& key, int32_t *len); + Status Setrange(const Slice& key, int64_t start_offset, const Slice& value, int32_t* ret); + Status Strlen(const Slice& key, int32_t* len); Status BitPos(const Slice& key, int32_t bit, int64_t* ret); - Status BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t* ret); - Status BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t end_offset, - int64_t* ret); + Status BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t* ret); + Status BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t end_offset, int64_t* ret); Status PKSetexAt(const Slice& key, const Slice& value, int32_t timestamp); - Status PKScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* kvs, std::string* next_key); - Status PKRScanRange(const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, + Status PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector* kvs, std::string* next_key); // Keys Commands Status Expire(const Slice& key, int32_t ttl) override; Status Del(const Slice& key) override; - bool Scan(const std::string& start_key, const std::string& pattern, - std::vector* keys, - int64_t* count, std::string* next_key) override; - bool PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) override; + bool Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, int64_t* count, + std::string* next_key) override; + bool PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) override; Status Expireat(const Slice& key, int32_t timestamp) override; Status Persist(const Slice& key) override; Status TTL(const Slice& key, int64_t* timestamp) override; diff --git a/src/storage/src/redis_zsets.cc b/src/storage/src/redis_zsets.cc index 87e01cafe5..55bde72c83 100644 --- a/src/storage/src/redis_zsets.cc +++ b/src/storage/src/redis_zsets.cc @@ -5,16 +5,16 @@ #include "src/redis_zsets.h" +#include +#include #include #include -#include -#include #include "iostream" -#include "storage/util.h" -#include "src/zsets_filter.h" #include "src/scope_record_lock.h" #include "src/scope_snapshot.h" +#include "src/zsets_filter.h" +#include "storage/util.h" namespace storage { @@ -23,12 +23,9 @@ rocksdb::Comparator* ZSetsScoreKeyComparator() { return &zsets_score_key_compare; } -RedisZSets::RedisZSets(Storage* const s, const DataType& type) - : Redis(s, type) { -} +RedisZSets::RedisZSets(Storage* const s, const DataType& type) : Redis(s, type) {} -Status RedisZSets::Open(const StorageOptions& storage_options, - const std::string& db_path) { +Status RedisZSets::Open(const StorageOptions& storage_options, const std::string& db_path) { statistics_store_->SetCapacity(storage_options.statistics_max_size); small_compaction_threshold_ = storage_options.small_compaction_threshold; @@ -36,8 +33,7 @@ Status RedisZSets::Open(const StorageOptions& storage_options, Status s = rocksdb::DB::Open(ops, db_path, &db_); if (s.ok()) { rocksdb::ColumnFamilyHandle *dcf = nullptr, *scf = nullptr; - s = db_->CreateColumnFamily(rocksdb::ColumnFamilyOptions(), - "data_cf", &dcf); + s = db_->CreateColumnFamily(rocksdb::ColumnFamilyOptions(), "data_cf", &dcf); if (!s.ok()) { return s; } @@ -56,12 +52,9 @@ Status RedisZSets::Open(const StorageOptions& storage_options, rocksdb::ColumnFamilyOptions meta_cf_ops(storage_options.options); rocksdb::ColumnFamilyOptions data_cf_ops(storage_options.options); rocksdb::ColumnFamilyOptions score_cf_ops(storage_options.options); - meta_cf_ops.compaction_filter_factory = - std::make_shared(); - data_cf_ops.compaction_filter_factory = - std::make_shared(&db_, &handles_); - score_cf_ops.compaction_filter_factory = - std::make_shared(&db_, &handles_); + meta_cf_ops.compaction_filter_factory = std::make_shared(); + data_cf_ops.compaction_filter_factory = std::make_shared(&db_, &handles_); + score_cf_ops.compaction_filter_factory = std::make_shared(&db_, &handles_); score_cf_ops.comparator = ZSetsScoreKeyComparator(); // use the bloom filter policy to reduce disk reads @@ -71,33 +64,22 @@ Status RedisZSets::Open(const StorageOptions& storage_options, rocksdb::BlockBasedTableOptions data_cf_table_ops(table_ops); rocksdb::BlockBasedTableOptions score_cf_table_ops(table_ops); if (!storage_options.share_block_cache && storage_options.block_cache_size > 0) { - meta_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); - data_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); - score_cf_table_ops.block_cache = - rocksdb::NewLRUCache(storage_options.block_cache_size); + meta_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); + data_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); + score_cf_table_ops.block_cache = rocksdb::NewLRUCache(storage_options.block_cache_size); } - meta_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); - data_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(data_cf_table_ops)); - score_cf_ops.table_factory.reset( - rocksdb::NewBlockBasedTableFactory(score_cf_table_ops)); + meta_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(meta_cf_table_ops)); + data_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(data_cf_table_ops)); + score_cf_ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(score_cf_table_ops)); std::vector column_families; - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - "data_cf", data_cf_ops)); - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - "score_cf", score_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor(rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor("data_cf", data_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor("score_cf", score_cf_ops)); return rocksdb::DB::Open(db_ops, db_path, column_families, &handles_, &db_); } -Status RedisZSets::CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, - const ColumnFamilyType& type) { +Status RedisZSets::CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type) { if (type == kMeta || type == kMetaAndData) { db_->CompactRange(default_compact_range_options_, handles_[0], begin, end); } @@ -135,12 +117,9 @@ Status RedisZSets::ScanKeyNum(KeyInfo* key_info) { rocksdb::Env::Default()->GetCurrentTime(&curtime); rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedZSetsMetaValue parsed_zsets_meta_value(iter->value()); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { invaild_keys++; } else { keys++; @@ -159,8 +138,7 @@ Status RedisZSets::ScanKeyNum(KeyInfo* key_info) { return Status::OK(); } -Status RedisZSets::ScanKeys(const std::string& pattern, - std::vector* keys) { +Status RedisZSets::ScanKeys(const std::string& pattern, std::vector* keys) { std::string key; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -169,15 +147,11 @@ Status RedisZSets::ScanKeys(const std::string& pattern, iterator_options.fill_cache = false; rocksdb::Iterator* iter = db_->NewIterator(iterator_options, handles_[0]); - for (iter->SeekToFirst(); - iter->Valid(); - iter->Next()) { + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedZSetsMetaValue parsed_zsets_meta_value(iter->value()); - if (!parsed_zsets_meta_value.IsStale() - && parsed_zsets_meta_value.count() != 0) { + if (!parsed_zsets_meta_value.IsStale() && parsed_zsets_meta_value.count() != 0) { key = iter->key().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } } @@ -186,8 +160,7 @@ Status RedisZSets::ScanKeys(const std::string& pattern, return Status::OK(); } -Status RedisZSets::PKPatternMatchDel(const std::string& pattern, - int32_t* ret) { +Status RedisZSets::PKPatternMatchDel(const std::string& pattern, int32_t* ret) { rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); @@ -205,9 +178,8 @@ Status RedisZSets::PKPatternMatchDel(const std::string& pattern, key = iter->key().ToString(); meta_value = iter->value().ToString(); ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (!parsed_zsets_meta_value.IsStale() - && parsed_zsets_meta_value.count() - && StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { + if (!parsed_zsets_meta_value.IsStale() && parsed_zsets_meta_value.count() && + StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { parsed_zsets_meta_value.InitialMetaValue(); batch.Put(handles_[0], key, meta_value); } @@ -235,9 +207,7 @@ Status RedisZSets::PKPatternMatchDel(const std::string& pattern, return s; } -Status RedisZSets::ZPopMax(const Slice& key, - const int64_t count, - std::vector* score_members) { +Status RedisZSets::ZPopMax(const Slice& key, const int64_t count, std::vector* score_members) { uint32_t statistic = 0; score_members->clear(); rocksdb::WriteBatch batch; @@ -254,17 +224,13 @@ Status RedisZSets::ZPopMax(const Slice& key, int32_t num = parsed_zsets_meta_value.count(); num = num <= count ? num : count; int32_t version = parsed_zsets_meta_value.version(); - ZSetsScoreKey zsets_score_key(key, version, - std::numeric_limits::max(), Slice()); + ZSetsScoreKey zsets_score_key(key, version, std::numeric_limits::max(), Slice()); rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[2]); int32_t del_cnt = 0; - for (iter->SeekForPrev(zsets_score_key.Encode()); - iter->Valid() && del_cnt < num; - iter->Prev()) { + for (iter->SeekForPrev(zsets_score_key.Encode()); iter->Valid() && del_cnt < num; iter->Prev()) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); score_members->emplace_back( - ScoreMember{parsed_zsets_score_key.score(), - parsed_zsets_score_key.member().ToString()}); + ScoreMember{parsed_zsets_score_key.score(), parsed_zsets_score_key.member().ToString()}); ZSetsMemberKey zsets_member_key(key, version, parsed_zsets_score_key.member()); ++statistic; ++del_cnt; @@ -273,19 +239,17 @@ Status RedisZSets::ZPopMax(const Slice& key, } delete iter; parsed_zsets_meta_value.ModifyCount(-del_cnt); - batch.Put(handles_[0], key, meta_value); + batch.Put(handles_[0], key, meta_value); s = db_->Write(default_write_options_, &batch); UpdateSpecificKeyStatistics(key.ToString(), statistic); return s; - } + } } else { return s; - } + } } -Status RedisZSets::ZPopMin(const Slice& key, - const int64_t count, - std::vector* score_members) { +Status RedisZSets::ZPopMin(const Slice& key, const int64_t count, std::vector* score_members) { uint32_t statistic = 0; score_members->clear(); rocksdb::WriteBatch batch; @@ -302,17 +266,13 @@ Status RedisZSets::ZPopMin(const Slice& key, int32_t num = parsed_zsets_meta_value.count(); num = num <= count ? num : count; int32_t version = parsed_zsets_meta_value.version(); - ZSetsScoreKey zsets_score_key(key, version, - std::numeric_limits::lowest(), Slice()); + ZSetsScoreKey zsets_score_key(key, version, std::numeric_limits::lowest(), Slice()); rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[2]); int32_t del_cnt = 0; - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && del_cnt < num; - iter->Next()) { + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && del_cnt < num; iter->Next()) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); score_members->emplace_back( - ScoreMember{parsed_zsets_score_key.score(), - parsed_zsets_score_key.member().ToString()} ); + ScoreMember{parsed_zsets_score_key.score(), parsed_zsets_score_key.member().ToString()}); ZSetsMemberKey zsets_member_key(key, version, parsed_zsets_score_key.member()); ++statistic; ++del_cnt; @@ -321,19 +281,17 @@ Status RedisZSets::ZPopMin(const Slice& key, } delete iter; parsed_zsets_meta_value.ModifyCount(-del_cnt); - batch.Put(handles_[0], key, meta_value); + batch.Put(handles_[0], key, meta_value); s = db_->Write(default_write_options_, &batch); UpdateSpecificKeyStatistics(key.ToString(), statistic); return s; - } + } } else { return s; - } + } } -Status RedisZSets::ZAdd(const Slice& key, - const std::vector& score_members, - int32_t* ret) { +Status RedisZSets::ZAdd(const Slice& key, const std::vector& score_members, int32_t* ret) { *ret = 0; uint32_t statistic = 0; std::unordered_set unique; @@ -354,8 +312,7 @@ Status RedisZSets::ZAdd(const Slice& key, if (s.ok()) { bool vaild = true; ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { vaild = false; version = parsed_zsets_meta_value.InitialMetaValue(); } else { @@ -369,8 +326,7 @@ Status RedisZSets::ZAdd(const Slice& key, bool not_found = true; ZSetsMemberKey zsets_member_key(key, version, sm.member); if (vaild) { - s = db_->Get(default_read_options_, - handles_[1], zsets_member_key.Encode(), &data_value); + s = db_->Get(default_read_options_, handles_[1], zsets_member_key.Encode(), &data_value); if (s.ok()) { not_found = false; uint64_t tmp = DecodeFixed64(data_value.data()); @@ -392,8 +348,7 @@ Status RedisZSets::ZAdd(const Slice& key, const void* ptr_score = reinterpret_cast(&sm.score); EncodeFixed64(score_buf, *reinterpret_cast(ptr_score)); - batch.Put(handles_[1], - zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); + batch.Put(handles_[1], zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); ZSetsScoreKey zsets_score_key(key, version, sm.score, sm.member); batch.Put(handles_[2], zsets_score_key.Encode(), Slice()); @@ -414,8 +369,7 @@ Status RedisZSets::ZAdd(const Slice& key, ZSetsMemberKey zsets_member_key(key, version, sm.member); const void* ptr_score = reinterpret_cast(&sm.score); EncodeFixed64(score_buf, *reinterpret_cast(ptr_score)); - batch.Put(handles_[1], - zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); + batch.Put(handles_[1], zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); ZSetsScoreKey zsets_score_key(key, version, sm.score, sm.member); batch.Put(handles_[2], zsets_score_key.Encode(), Slice()); @@ -429,7 +383,6 @@ Status RedisZSets::ZAdd(const Slice& key, return s; } - Status RedisZSets::ZCard(const Slice& key, int32_t* card) { *card = 0; std::string meta_value; @@ -450,12 +403,7 @@ Status RedisZSets::ZCard(const Slice& key, int32_t* card) { return s; } -Status RedisZSets::ZCount(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int32_t* ret) { +Status RedisZSets::ZCount(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret) { *ret = 0; rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -479,31 +427,29 @@ Status RedisZSets::ZCount(const Slice& key, ScoreMember score_member; ZSetsScoreKey zsets_score_key(key, version, min, Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && cur_index <= stop_index; - iter->Next(), ++cur_index) { - bool left_pass = false; - bool right_pass = false; - ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); - if (parsed_zsets_score_key.key() != key) { - break; - } - if (parsed_zsets_score_key.version() != version) { - break; - } - if ((left_close && min <= parsed_zsets_score_key.score()) - || (!left_close && min < parsed_zsets_score_key.score())) { - left_pass = true; - } - if ((right_close && parsed_zsets_score_key.score() <= max) - || (!right_close && parsed_zsets_score_key.score() < max)) { - right_pass = true; - } - if (left_pass && right_pass) { - cnt++; - } else if (!right_pass) { - break; - } + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { + bool left_pass = false; + bool right_pass = false; + ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); + if (parsed_zsets_score_key.key() != key) { + break; + } + if (parsed_zsets_score_key.version() != version) { + break; + } + if ((left_close && min <= parsed_zsets_score_key.score()) || + (!left_close && min < parsed_zsets_score_key.score())) { + left_pass = true; + } + if ((right_close && parsed_zsets_score_key.score() <= max) || + (!right_close && parsed_zsets_score_key.score() < max)) { + right_pass = true; + } + if (left_pass && right_pass) { + cnt++; + } else if (!right_pass) { + break; + } } delete iter; *ret = cnt; @@ -512,10 +458,7 @@ Status RedisZSets::ZCount(const Slice& key, return s; } -Status RedisZSets::ZIncrby(const Slice& key, - const Slice& member, - double increment, - double* ret) { +Status RedisZSets::ZIncrby(const Slice& key, const Slice& member, double increment, double* ret) { *ret = 0; uint32_t statistic = 0; double score = 0; @@ -527,16 +470,14 @@ Status RedisZSets::ZIncrby(const Slice& key, Status s = db_->Get(default_read_options_, handles_[0], key, &meta_value); if (s.ok()) { ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { version = parsed_zsets_meta_value.InitialMetaValue(); } else { version = parsed_zsets_meta_value.version(); } std::string data_value; ZSetsMemberKey zsets_member_key(key, version, member); - s = db_->Get(default_read_options_, - handles_[1], zsets_member_key.Encode(), &data_value); + s = db_->Get(default_read_options_, handles_[1], zsets_member_key.Encode(), &data_value); if (s.ok()) { uint64_t tmp = DecodeFixed64(data_value.data()); const void* ptr_tmp = reinterpret_cast(&tmp); @@ -567,8 +508,7 @@ Status RedisZSets::ZIncrby(const Slice& key, ZSetsMemberKey zsets_member_key(key, version, member); const void* ptr_score = reinterpret_cast(&score); EncodeFixed64(score_buf, *reinterpret_cast(ptr_score)); - batch.Put(handles_[1], - zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); + batch.Put(handles_[1], zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); ZSetsScoreKey zsets_score_key(key, version, score, member); batch.Put(handles_[2], zsets_score_key.Encode(), Slice()); @@ -578,10 +518,7 @@ Status RedisZSets::ZIncrby(const Slice& key, return s; } -Status RedisZSets::ZRange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members) { +Status RedisZSets::ZRange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members) { score_members->clear(); rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -601,22 +538,17 @@ Status RedisZSets::ZRange(const Slice& key, int32_t count = parsed_zsets_meta_value.count(); int32_t version = parsed_zsets_meta_value.version(); int32_t start_index = start >= 0 ? start : count + start; - int32_t stop_index = stop >= 0 ? stop : count + stop; + int32_t stop_index = stop >= 0 ? stop : count + stop; start_index = start_index <= 0 ? 0 : start_index; stop_index = stop_index >= count ? count - 1 : stop_index; - if (start_index > stop_index - || start_index >= count - || stop_index < 0) { + if (start_index > stop_index || start_index >= count || stop_index < 0) { return s; } int32_t cur_index = 0; ScoreMember score_member; - ZSetsScoreKey zsets_score_key(key, version, - std::numeric_limits::lowest(), Slice()); + ZSetsScoreKey zsets_score_key(key, version, std::numeric_limits::lowest(), Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && cur_index <= stop_index; - iter->Next(), ++cur_index) { + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { if (cur_index >= start_index) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); score_member.score = parsed_zsets_score_key.score(); @@ -630,14 +562,8 @@ Status RedisZSets::ZRange(const Slice& key, return s; } -Status RedisZSets::ZRangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members) { +Status RedisZSets::ZRangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, + int64_t count, int64_t offset, std::vector* score_members) { score_members->clear(); rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -660,24 +586,22 @@ Status RedisZSets::ZRangebyscore(const Slice& key, ScoreMember score_member; ZSetsScoreKey zsets_score_key(key, version, min, Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && index <= stop_index; - iter->Next(), ++index) { + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && index <= stop_index; iter->Next(), ++index) { bool left_pass = false; bool right_pass = false; ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); if (parsed_zsets_score_key.key() != key) { - break; + break; } if (parsed_zsets_score_key.version() != version) { - break; + break; } - if ((left_close && min <= parsed_zsets_score_key.score()) - || (!left_close && min < parsed_zsets_score_key.score())) { + if ((left_close && min <= parsed_zsets_score_key.score()) || + (!left_close && min < parsed_zsets_score_key.score())) { left_pass = true; } - if ((right_close && parsed_zsets_score_key.score() <= max) - || (!right_close && parsed_zsets_score_key.score() < max)) { + if ((right_close && parsed_zsets_score_key.score() <= max) || + (!right_close && parsed_zsets_score_key.score() < max)) { right_pass = true; } if (left_pass && right_pass) { @@ -703,9 +627,7 @@ Status RedisZSets::ZRangebyscore(const Slice& key, return s; } -Status RedisZSets::ZRank(const Slice& key, - const Slice& member, - int32_t* rank) { +Status RedisZSets::ZRank(const Slice& key, const Slice& member, int32_t* rank) { *rank = -1; rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -715,7 +637,7 @@ Status RedisZSets::ZRank(const Slice& key, read_options.snapshot = snapshot; Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { - ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); + ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); if (parsed_zsets_meta_value.IsStale()) { return Status::NotFound("Stale"); } else if (parsed_zsets_meta_value.count() == 0) { @@ -726,17 +648,14 @@ Status RedisZSets::ZRank(const Slice& key, int32_t index = 0; int32_t stop_index = parsed_zsets_meta_value.count() - 1; ScoreMember score_member; - ZSetsScoreKey zsets_score_key(key, version, - std::numeric_limits::lowest(), Slice()); + ZSetsScoreKey zsets_score_key(key, version, std::numeric_limits::lowest(), Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && index <= stop_index; - iter->Next(), ++index) { - ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); - if (!parsed_zsets_score_key.member().compare(member)) { - found = true; - break; - } + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && index <= stop_index; iter->Next(), ++index) { + ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); + if (!parsed_zsets_score_key.member().compare(member)) { + found = true; + break; + } } delete iter; if (found) { @@ -750,9 +669,7 @@ Status RedisZSets::ZRank(const Slice& key, return s; } -Status RedisZSets::ZRem(const Slice& key, - std::vector members, - int32_t* ret) { +Status RedisZSets::ZRem(const Slice& key, std::vector members, int32_t* ret) { *ret = 0; uint32_t statistic = 0; std::unordered_set unique; @@ -780,8 +697,7 @@ Status RedisZSets::ZRem(const Slice& key, int32_t version = parsed_zsets_meta_value.version(); for (const auto& member : filtered_members) { ZSetsMemberKey zsets_member_key(key, version, member); - s = db_->Get(default_read_options_, - handles_[1], zsets_member_key.Encode(), &data_value); + s = db_->Get(default_read_options_, handles_[1], zsets_member_key.Encode(), &data_value); if (s.ok()) { del_cnt++; statistic++; @@ -808,10 +724,7 @@ Status RedisZSets::ZRem(const Slice& key, return s; } -Status RedisZSets::ZRemrangebyrank(const Slice& key, - int32_t start, - int32_t stop, - int32_t* ret) { +Status RedisZSets::ZRemrangebyrank(const Slice& key, int32_t start, int32_t stop, int32_t* ret) { *ret = 0; uint32_t statistic = 0; std::string meta_value; @@ -831,23 +744,18 @@ Status RedisZSets::ZRemrangebyrank(const Slice& key, int32_t count = parsed_zsets_meta_value.count(); int32_t version = parsed_zsets_meta_value.version(); int32_t start_index = start >= 0 ? start : count + start; - int32_t stop_index = stop >= 0 ? stop : count + stop; + int32_t stop_index = stop >= 0 ? stop : count + stop; start_index = start_index <= 0 ? 0 : start_index; stop_index = stop_index >= count ? count - 1 : stop_index; if (start_index > stop_index || start_index >= count) { return s; } - ZSetsScoreKey zsets_score_key(key, version, - std::numeric_limits::lowest(), Slice()); - rocksdb::Iterator* iter = - db_->NewIterator(default_read_options_, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && cur_index <= stop_index; - iter->Next(), ++cur_index) { + ZSetsScoreKey zsets_score_key(key, version, std::numeric_limits::lowest(), Slice()); + rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[2]); + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { if (cur_index >= start_index) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); - ZSetsMemberKey zsets_member_key(key, version, - parsed_zsets_score_key.member()); + ZSetsMemberKey zsets_member_key(key, version, parsed_zsets_score_key.member()); batch.Delete(handles_[1], zsets_member_key.Encode()); batch.Delete(handles_[2], iter->key()); del_cnt++; @@ -867,11 +775,7 @@ Status RedisZSets::ZRemrangebyrank(const Slice& key, return s; } -Status RedisZSets::ZRemrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, +Status RedisZSets::ZRemrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret) { *ret = 0; uint32_t statistic = 0; @@ -892,31 +796,27 @@ Status RedisZSets::ZRemrangebyscore(const Slice& key, int32_t stop_index = parsed_zsets_meta_value.count() - 1; int32_t version = parsed_zsets_meta_value.version(); ZSetsScoreKey zsets_score_key(key, version, min, Slice()); - rocksdb::Iterator* iter = - db_->NewIterator(default_read_options_, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && cur_index <= stop_index; - iter->Next(), ++cur_index) { + rocksdb::Iterator* iter = db_->NewIterator(default_read_options_, handles_[2]); + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { bool left_pass = false; bool right_pass = false; ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); if (parsed_zsets_score_key.key() != key) { - break; + break; } if (parsed_zsets_score_key.version() != version) { - break; + break; } - if ((left_close && min <= parsed_zsets_score_key.score()) - || (!left_close && min < parsed_zsets_score_key.score())) { + if ((left_close && min <= parsed_zsets_score_key.score()) || + (!left_close && min < parsed_zsets_score_key.score())) { left_pass = true; } - if ((right_close && parsed_zsets_score_key.score() <= max) - || (!right_close && parsed_zsets_score_key.score() < max)) { + if ((right_close && parsed_zsets_score_key.score() <= max) || + (!right_close && parsed_zsets_score_key.score() < max)) { right_pass = true; } if (left_pass && right_pass) { - ZSetsMemberKey zsets_member_key(key, version, - parsed_zsets_score_key.member()); + ZSetsMemberKey zsets_member_key(key, version, parsed_zsets_score_key.member()); batch.Delete(handles_[1], zsets_member_key.Encode()); batch.Delete(handles_[2], iter->key()); del_cnt++; @@ -939,10 +839,7 @@ Status RedisZSets::ZRemrangebyscore(const Slice& key, return s; } -Status RedisZSets::ZRevrange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members) { +Status RedisZSets::ZRevrange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members) { score_members->clear(); rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -962,21 +859,17 @@ Status RedisZSets::ZRevrange(const Slice& key, int32_t count = parsed_zsets_meta_value.count(); int32_t version = parsed_zsets_meta_value.version(); int32_t start_index = stop >= 0 ? count - stop - 1 : -stop - 1; - int32_t stop_index = start >= 0 ? count- start - 1 : -start - 1; + int32_t stop_index = start >= 0 ? count - start - 1 : -start - 1; start_index = start_index <= 0 ? 0 : start_index; stop_index = stop_index >= count ? count - 1 : stop_index; - if (start_index > stop_index - || start_index >= count - || stop_index < 0) { + if (start_index > stop_index || start_index >= count || stop_index < 0) { return s; } int32_t cur_index = count - 1; ScoreMember score_member; - ZSetsScoreKey zsets_score_key(key, version, - std::numeric_limits::max(), Slice()); + ZSetsScoreKey zsets_score_key(key, version, std::numeric_limits::max(), Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->SeekForPrev(zsets_score_key.Encode()); - iter->Valid() && cur_index >= start_index; + for (iter->SeekForPrev(zsets_score_key.Encode()); iter->Valid() && cur_index >= start_index; iter->Prev(), --cur_index) { if (cur_index <= stop_index) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); @@ -991,14 +884,8 @@ Status RedisZSets::ZRevrange(const Slice& key, return s; } -Status RedisZSets::ZRevrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members) { +Status RedisZSets::ZRevrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, + int64_t count, int64_t offset, std::vector* score_members) { score_members->clear(); rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -1013,17 +900,14 @@ Status RedisZSets::ZRevrangebyscore(const Slice& key, return Status::NotFound("Stale"); } else if (parsed_zsets_meta_value.count() == 0) { return Status::NotFound(); - } else if (offset >= 0 && count != 0 ) { + } else if (offset >= 0 && count != 0) { int32_t version = parsed_zsets_meta_value.version(); int32_t left = parsed_zsets_meta_value.count(); int64_t skipped = 0; ScoreMember score_member; - ZSetsScoreKey zsets_score_key(key, version, - std::nextafter(max, std::numeric_limits::max()), Slice()); + ZSetsScoreKey zsets_score_key(key, version, std::nextafter(max, std::numeric_limits::max()), Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->SeekForPrev(zsets_score_key.Encode()); - iter->Valid() && left > 0; - iter->Prev(), --left) { + for (iter->SeekForPrev(zsets_score_key.Encode()); iter->Valid() && left > 0; iter->Prev(), --left) { bool left_pass = false; bool right_pass = false; ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); @@ -1033,12 +917,12 @@ Status RedisZSets::ZRevrangebyscore(const Slice& key, if (parsed_zsets_score_key.version() != version) { break; } - if ((left_close && min <= parsed_zsets_score_key.score()) - || (!left_close && min < parsed_zsets_score_key.score())) { + if ((left_close && min <= parsed_zsets_score_key.score()) || + (!left_close && min < parsed_zsets_score_key.score())) { left_pass = true; } - if ((right_close && parsed_zsets_score_key.score() <= max) - || (!right_close && parsed_zsets_score_key.score() < max)) { + if ((right_close && parsed_zsets_score_key.score() <= max) || + (!right_close && parsed_zsets_score_key.score() < max)) { right_pass = true; } if (left_pass && right_pass) { @@ -1064,9 +948,7 @@ Status RedisZSets::ZRevrangebyscore(const Slice& key, return s; } -Status RedisZSets::ZRevrank(const Slice& key, - const Slice& member, - int32_t* rank) { +Status RedisZSets::ZRevrank(const Slice& key, const Slice& member, int32_t* rank) { *rank = -1; rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -1087,12 +969,9 @@ Status RedisZSets::ZRevrank(const Slice& key, int32_t rev_index = 0; int32_t left = parsed_zsets_meta_value.count(); int32_t version = parsed_zsets_meta_value.version(); - ZSetsScoreKey zsets_score_key(key, version, - std::numeric_limits::max(), Slice()); + ZSetsScoreKey zsets_score_key(key, version, std::numeric_limits::max(), Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->SeekForPrev(zsets_score_key.Encode()); - iter->Valid() && left >= 0; - iter->Prev(), --left, ++rev_index) { + for (iter->SeekForPrev(zsets_score_key.Encode()); iter->Valid() && left >= 0; iter->Prev(), --left, ++rev_index) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); if (!parsed_zsets_score_key.member().compare(member)) { found = true; @@ -1110,9 +989,7 @@ Status RedisZSets::ZRevrank(const Slice& key, return s; } -Status RedisZSets::ZScore(const Slice& key, - const Slice& member, - double* score) { +Status RedisZSets::ZScore(const Slice& key, const Slice& member, double* score) { *score = 0; rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot = nullptr; @@ -1132,8 +1009,7 @@ Status RedisZSets::ZScore(const Slice& key, } else { std::string data_value; ZSetsMemberKey zsets_member_key(key, version, member); - s = db_->Get(read_options, handles_[1], - zsets_member_key.Encode(), &data_value); + s = db_->Get(read_options, handles_[1], zsets_member_key.Encode(), &data_value); if (s.ok()) { uint64_t tmp = DecodeFixed64(data_value.data()); const void* ptr_tmp = reinterpret_cast(&tmp); @@ -1148,11 +1024,8 @@ Status RedisZSets::ZScore(const Slice& key, return s; } -Status RedisZSets::ZUnionstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret) { +Status RedisZSets::ZUnionstore(const Slice& destination, const std::vector& keys, + const std::vector& weights, const AGGREGATE agg, int32_t* ret) { *ret = 0; uint32_t statistic = 0; rocksdb::WriteBatch batch; @@ -1172,18 +1045,15 @@ Status RedisZSets::ZUnionstore(const Slice& destination, s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (!parsed_zsets_meta_value.IsStale() - && parsed_zsets_meta_value.count() != 0) { + if (!parsed_zsets_meta_value.IsStale() && parsed_zsets_meta_value.count() != 0) { int32_t cur_index = 0; int32_t stop_index = parsed_zsets_meta_value.count() - 1; double score = 0; double weight = idx < weights.size() ? weights[idx] : 1; version = parsed_zsets_meta_value.version(); - ZSetsScoreKey zsets_score_key(keys[idx], version, - std::numeric_limits::lowest(), Slice()); + ZSetsScoreKey zsets_score_key(keys[idx], version, std::numeric_limits::lowest(), Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && cur_index <= stop_index; + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); sm.score = parsed_zsets_score_key.score(); @@ -1194,9 +1064,15 @@ Status RedisZSets::ZUnionstore(const Slice& destination, } else { score = member_score_map[sm.member]; switch (agg) { - case SUM: score += weight * sm.score; break; - case MIN: score = std::min(score, weight * sm.score); break; - case MAX: score = std::max(score, weight * sm.score); break; + case SUM: + score += weight * sm.score; + break; + case MIN: + score = std::min(score, weight * sm.score); + break; + case MAX: + score = std::max(score, weight * sm.score); + break; } member_score_map[sm.member] = (score == -0.0) ? 0 : score; } @@ -1229,8 +1105,7 @@ Status RedisZSets::ZUnionstore(const Slice& destination, const void* ptr_score = reinterpret_cast(&sm.second); EncodeFixed64(score_buf, *reinterpret_cast(ptr_score)); - batch.Put(handles_[1], zsets_member_key.Encode(), - Slice(score_buf, sizeof(uint64_t))); + batch.Put(handles_[1], zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); ZSetsScoreKey zsets_score_key(destination, version, sm.second, sm.first); batch.Put(handles_[2], zsets_score_key.Encode(), Slice()); @@ -1241,11 +1116,8 @@ Status RedisZSets::ZUnionstore(const Slice& destination, return s; } -Status RedisZSets::ZInterstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret) { +Status RedisZSets::ZInterstore(const Slice& destination, const std::vector& keys, + const std::vector& weights, const AGGREGATE agg, int32_t* ret) { if (keys.size() <= 0) { return Status::Corruption("ZInterstore invalid parameter, no keys"); } @@ -1274,8 +1146,7 @@ Status RedisZSets::ZInterstore(const Slice& destination, s = db_->Get(read_options, handles_[0], keys[idx], &meta_value); if (s.ok()) { ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { have_invalid_zsets = true; } else { vaild_zsets.push_back({keys[idx], parsed_zsets_meta_value.version()}); @@ -1291,12 +1162,10 @@ Status RedisZSets::ZInterstore(const Slice& destination, } if (!have_invalid_zsets) { - ZSetsScoreKey zsets_score_key(vaild_zsets[0].key, vaild_zsets[0].version, - std::numeric_limits::lowest(), Slice()); + ZSetsScoreKey zsets_score_key(vaild_zsets[0].key, vaild_zsets[0].version, std::numeric_limits::lowest(), + Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[2]); - for (iter->Seek(zsets_score_key.Encode()); - iter->Valid() && cur_index <= stop_index; - iter->Next(), ++cur_index) { + for (iter->Seek(zsets_score_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { ParsedZSetsScoreKey parsed_zsets_score_key(iter->key()); double score = parsed_zsets_score_key.score(); std::string member = parsed_zsets_score_key.member().ToString(); @@ -1311,18 +1180,22 @@ Status RedisZSets::ZInterstore(const Slice& destination, item.score = sm.score * (weights.size() > 0 ? weights[0] : 1); for (size_t idx = 1; idx < vaild_zsets.size(); ++idx) { double weight = idx < weights.size() ? weights[idx] : 1; - ZSetsMemberKey zsets_member_key(vaild_zsets[idx].key, - vaild_zsets[idx].version, item.member); - s = db_->Get(read_options, handles_[1], - zsets_member_key.Encode(), &data_value); + ZSetsMemberKey zsets_member_key(vaild_zsets[idx].key, vaild_zsets[idx].version, item.member); + s = db_->Get(read_options, handles_[1], zsets_member_key.Encode(), &data_value); if (s.ok()) { uint64_t tmp = DecodeFixed64(data_value.data()); const void* ptr_tmp = reinterpret_cast(&tmp); double score = *reinterpret_cast(ptr_tmp); switch (agg) { - case SUM: item.score += weight * score; break; - case MIN: item.score = std::min(item.score, weight * score); break; - case MAX: item.score = std::max(item.score, weight * score); break; + case SUM: + item.score += weight * score; + break; + case MIN: + item.score = std::min(item.score, weight * score); + break; + case MAX: + item.score = std::max(item.score, weight * score); + break; } } else if (s.IsNotFound()) { reliable = false; @@ -1357,8 +1230,7 @@ Status RedisZSets::ZInterstore(const Slice& destination, const void* ptr_score = reinterpret_cast(&sm.score); EncodeFixed64(score_buf, *reinterpret_cast(ptr_score)); - batch.Put(handles_[1], - zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); + batch.Put(handles_[1], zsets_member_key.Encode(), Slice(score_buf, sizeof(uint64_t))); ZSetsScoreKey zsets_score_key(destination, version, sm.score, sm.member); batch.Put(handles_[2], zsets_score_key.Encode(), Slice()); @@ -1369,11 +1241,7 @@ Status RedisZSets::ZInterstore(const Slice& destination, return s; } -Status RedisZSets::ZRangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, +Status RedisZSets::ZRangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, std::vector* members) { members->clear(); rocksdb::ReadOptions read_options; @@ -1389,8 +1257,7 @@ Status RedisZSets::ZRangebylex(const Slice& key, Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { return Status::NotFound(); } else { int32_t version = parsed_zsets_meta_value.version(); @@ -1398,21 +1265,15 @@ Status RedisZSets::ZRangebylex(const Slice& key, int32_t stop_index = parsed_zsets_meta_value.count() - 1; ZSetsMemberKey zsets_member_key(key, version, Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(zsets_member_key.Encode()); - iter->Valid() && cur_index <= stop_index; - iter->Next(), ++cur_index) { + for (iter->Seek(zsets_member_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { bool left_pass = false; bool right_pass = false; ParsedZSetsMemberKey parsed_zsets_member_key(iter->key()); Slice member = parsed_zsets_member_key.member(); - if (left_no_limit - || (left_close && min.compare(member) <= 0) - || (!left_close && min.compare(member) < 0)) { + if (left_no_limit || (left_close && min.compare(member) <= 0) || (!left_close && min.compare(member) < 0)) { left_pass = true; } - if (right_not_limit - || (right_close && max.compare(member) >= 0) - || (!right_close && max.compare(member) > 0)) { + if (right_not_limit || (right_close && max.compare(member) >= 0) || (!right_close && max.compare(member) > 0)) { right_pass = true; } if (left_pass && right_pass) { @@ -1428,11 +1289,7 @@ Status RedisZSets::ZRangebylex(const Slice& key, return s; } -Status RedisZSets::ZLexcount(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, +Status RedisZSets::ZLexcount(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, int32_t* ret) { std::vector members; Status s = ZRangebylex(key, min, max, left_close, right_close, &members); @@ -1440,12 +1297,8 @@ Status RedisZSets::ZLexcount(const Slice& key, return s; } -Status RedisZSets::ZRemrangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, - int32_t* ret) { +Status RedisZSets::ZRemrangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, + bool right_close, int32_t* ret) { *ret = 0; uint32_t statistic = 0; rocksdb::WriteBatch batch; @@ -1464,8 +1317,7 @@ Status RedisZSets::ZRemrangebylex(const Slice& key, Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { return Status::NotFound(); } else { int32_t version = parsed_zsets_meta_value.version(); @@ -1473,21 +1325,15 @@ Status RedisZSets::ZRemrangebylex(const Slice& key, int32_t stop_index = parsed_zsets_meta_value.count() - 1; ZSetsMemberKey zsets_member_key(key, version, Slice()); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(zsets_member_key.Encode()); - iter->Valid() && cur_index <= stop_index; - iter->Next(), ++cur_index) { + for (iter->Seek(zsets_member_key.Encode()); iter->Valid() && cur_index <= stop_index; iter->Next(), ++cur_index) { bool left_pass = false; bool right_pass = false; ParsedZSetsMemberKey parsed_zsets_member_key(iter->key()); Slice member = parsed_zsets_member_key.member(); - if (left_no_limit - || (left_close && min.compare(member) <= 0) - || (!left_close && min.compare(member) < 0)) { + if (left_no_limit || (left_close && min.compare(member) <= 0) || (!left_close && min.compare(member) < 0)) { left_pass = true; } - if (right_not_limit - || (right_close && max.compare(member) >= 0) - || (!right_close && max.compare(member) > 0)) { + if (right_not_limit || (right_close && max.compare(member) >= 0) || (!right_close && max.compare(member) > 0)) { right_pass = true; } if (left_pass && right_pass) { @@ -1562,11 +1408,8 @@ Status RedisZSets::Del(const Slice& key) { return s; } -bool RedisZSets::Scan(const std::string& start_key, - const std::string& pattern, - std::vector* keys, - int64_t* count, - std::string* next_key) { +bool RedisZSets::Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, + int64_t* count, std::string* next_key) { std::string meta_key; bool is_finish = true; rocksdb::ReadOptions iterator_options; @@ -1580,14 +1423,12 @@ bool RedisZSets::Scan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*count) > 0) { ParsedZSetsMetaValue parsed_zsets_meta_value(it->value()); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { it->Next(); continue; } else { meta_key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - meta_key.data(), meta_key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), meta_key.data(), meta_key.size(), 0)) { keys->push_back(meta_key); } (*count)--; @@ -1595,10 +1436,8 @@ bool RedisZSets::Scan(const std::string& start_key, } } - std::string prefix = isTailWildcard(pattern) ? - pattern.substr(0, pattern.size() - 1) : ""; - if (it->Valid() - && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { + std::string prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; + if (it->Valid() && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { *next_key = it->key().ToString(); is_finish = false; } else { @@ -1608,11 +1447,8 @@ bool RedisZSets::Scan(const std::string& start_key, return is_finish; } -bool RedisZSets::PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) { +bool RedisZSets::PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) { bool is_finish = true; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; @@ -1624,13 +1460,11 @@ bool RedisZSets::PKExpireScan(const std::string& start_key, it->Seek(start_key); while (it->Valid() && (*leftover_visits) > 0) { ParsedZSetsMetaValue parsed_zsets_meta_value(it->value()); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { it->Next(); continue; } else { - if (min_timestamp < parsed_zsets_meta_value.timestamp() - && parsed_zsets_meta_value.timestamp() < max_timestamp) { + if (min_timestamp < parsed_zsets_meta_value.timestamp() && parsed_zsets_meta_value.timestamp() < max_timestamp) { keys->push_back(it->key().ToString()); } (*leftover_visits)--; @@ -1648,7 +1482,6 @@ bool RedisZSets::PKExpireScan(const std::string& start_key, return is_finish; } - Status RedisZSets::Expireat(const Slice& key, int32_t timestamp) { std::string meta_value; ScopeRecordLock l(lock_mgr_, key); @@ -1671,12 +1504,8 @@ Status RedisZSets::Expireat(const Slice& key, int32_t timestamp) { return s; } -Status RedisZSets::ZScan(const Slice& key, - int64_t cursor, - const std::string& pattern, - int64_t count, - std::vector* score_members, - int64_t* next_cursor) { +Status RedisZSets::ZScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* score_members, int64_t* next_cursor) { *next_cursor = 0; score_members->clear(); if (cursor < 0) { @@ -1695,8 +1524,7 @@ Status RedisZSets::ZScan(const Slice& key, Status s = db_->Get(read_options, handles_[0], key, &meta_value); if (s.ok()) { ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { *next_cursor = 0; return Status::NotFound(); } else { @@ -1718,13 +1546,11 @@ Status RedisZSets::ZScan(const Slice& key, ZSetsMemberKey zsets_member_key(key, version, start_point); std::string prefix = zsets_member_prefix.Encode().ToString(); rocksdb::Iterator* iter = db_->NewIterator(read_options, handles_[1]); - for (iter->Seek(zsets_member_key.Encode()); - iter->Valid() && rest > 0 && iter->key().starts_with(prefix); + for (iter->Seek(zsets_member_key.Encode()); iter->Valid() && rest > 0 && iter->key().starts_with(prefix); iter->Next()) { ParsedZSetsMemberKey parsed_zsets_member_key(iter->key()); std::string member = parsed_zsets_member_key.member().ToString(); - if (StringMatch(pattern.data(), - pattern.size(), member.data(), member.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), member.data(), member.size(), 0)) { uint64_t tmp = DecodeFixed64(iter->value().data()); const void* ptr_tmp = reinterpret_cast(&tmp); double score = *reinterpret_cast(ptr_tmp); @@ -1733,9 +1559,7 @@ Status RedisZSets::ZScan(const Slice& key, rest--; } - if (iter->Valid() - && (iter->key().compare(prefix) <= 0 - || iter->key().starts_with(prefix))) { + if (iter->Valid() && (iter->key().compare(prefix) <= 0 || iter->key().starts_with(prefix))) { *next_cursor = cursor + step_length; ParsedZSetsMemberKey parsed_zsets_member_key(iter->key()); std::string next_member = parsed_zsets_member_key.member().ToString(); @@ -1752,12 +1576,8 @@ Status RedisZSets::ZScan(const Slice& key, return Status::OK(); } -Status RedisZSets::PKScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +Status RedisZSets::PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1771,9 +1591,7 @@ Status RedisZSets::PKScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) > 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) > 0)) { return Status::InvalidArgument("error in given range"); } @@ -1784,16 +1602,13 @@ Status RedisZSets::PKScanRange(const Slice& key_start, it->Seek(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedZSetsMetaValue parsed_zsets_meta_value(it->value()); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { it->Next(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1801,11 +1616,9 @@ Status RedisZSets::PKScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) <= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedZSetsMetaValue parsed_zsets_meta_value(it->value()); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { it->Next(); } else { *next_key = it->key().ToString(); @@ -1816,12 +1629,8 @@ Status RedisZSets::PKScanRange(const Slice& key_start, return Status::OK(); } -Status RedisZSets::PKRScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key) { +Status RedisZSets::PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key) { next_key->clear(); std::string key; @@ -1835,9 +1644,7 @@ Status RedisZSets::PKRScanRange(const Slice& key_start, bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); - if (!start_no_limit - && !end_no_limit - && (key_start.compare(key_end) < 0)) { + if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) < 0)) { return Status::InvalidArgument("error in given range"); } @@ -1848,16 +1655,13 @@ Status RedisZSets::PKRScanRange(const Slice& key_start, it->SeekForPrev(key_start); } - while (it->Valid() && remain > 0 - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedZSetsMetaValue parsed_zsets_meta_value(it->value()); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { it->Prev(); } else { key = it->key().ToString(); - if (StringMatch(pattern.data(), pattern.size(), - key.data(), key.size(), 0)) { + if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } remain--; @@ -1865,11 +1669,9 @@ Status RedisZSets::PKRScanRange(const Slice& key_start, } } - while (it->Valid() - && (end_no_limit || it->key().compare(key_end) >= 0)) { + while (it->Valid() && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedZSetsMetaValue parsed_zsets_meta_value(it->value()); - if (parsed_zsets_meta_value.IsStale() - || parsed_zsets_meta_value.count() == 0) { + if (parsed_zsets_meta_value.IsStale() || parsed_zsets_meta_value.count() == 0) { it->Prev(); } else { *next_key = it->key().ToString(); @@ -1940,30 +1742,24 @@ void RedisZSets::ScanDatabase() { printf("\n***************ZSets Meta Data***************\n"); auto meta_iter = db_->NewIterator(iterator_options, handles_[0]); - for (meta_iter->SeekToFirst(); - meta_iter->Valid(); - meta_iter->Next()) { + for (meta_iter->SeekToFirst(); meta_iter->Valid(); meta_iter->Next()) { ParsedZSetsMetaValue parsed_zsets_meta_value(meta_iter->value()); int32_t survival_time = 0; if (parsed_zsets_meta_value.timestamp() != 0) { - survival_time = parsed_zsets_meta_value.timestamp() - current_time > 0 ? - parsed_zsets_meta_value.timestamp() - current_time : -1; + survival_time = parsed_zsets_meta_value.timestamp() - current_time > 0 + ? parsed_zsets_meta_value.timestamp() - current_time + : -1; } printf("[key : %-30s] [count : %-10d] [timestamp : %-10d] [version : %d] [survival_time : %d]\n", - meta_iter->key().ToString().c_str(), - parsed_zsets_meta_value.count(), - parsed_zsets_meta_value.timestamp(), - parsed_zsets_meta_value.version(), - survival_time); + meta_iter->key().ToString().c_str(), parsed_zsets_meta_value.count(), parsed_zsets_meta_value.timestamp(), + parsed_zsets_meta_value.version(), survival_time); } delete meta_iter; printf("\n***************ZSets Member To Score Data***************\n"); auto member_iter = db_->NewIterator(iterator_options, handles_[1]); - for (member_iter->SeekToFirst(); - member_iter->Valid(); - member_iter->Next()) { + for (member_iter->SeekToFirst(); member_iter->Valid(); member_iter->Next()) { ParsedZSetsMemberKey parsed_zsets_member_key(member_iter->key()); uint64_t tmp = DecodeFixed64(member_iter->value().data()); @@ -1971,24 +1767,18 @@ void RedisZSets::ScanDatabase() { double score = *reinterpret_cast(ptr_tmp); printf("[key : %-30s] [member : %-20s] [score : %-20lf] [version : %d]\n", - parsed_zsets_member_key.key().ToString().c_str(), - parsed_zsets_member_key.member().ToString().c_str(), - score, + parsed_zsets_member_key.key().ToString().c_str(), parsed_zsets_member_key.member().ToString().c_str(), score, parsed_zsets_member_key.version()); } delete member_iter; printf("\n***************ZSets Score To Member Data***************\n"); auto score_iter = db_->NewIterator(iterator_options, handles_[2]); - for (score_iter->SeekToFirst(); - score_iter->Valid(); - score_iter->Next()) { + for (score_iter->SeekToFirst(); score_iter->Valid(); score_iter->Next()) { ParsedZSetsScoreKey parsed_zsets_score_key(score_iter->key()); printf("[key : %-30s] [score : %-20lf] [member : %-20s] [version : %d]\n", - parsed_zsets_score_key.key().ToString().c_str(), - parsed_zsets_score_key.score(), - parsed_zsets_score_key.member().ToString().c_str(), - parsed_zsets_score_key.version()); + parsed_zsets_score_key.key().ToString().c_str(), parsed_zsets_score_key.score(), + parsed_zsets_score_key.member().ToString().c_str(), parsed_zsets_score_key.version()); } delete score_iter; } diff --git a/src/storage/src/redis_zsets.h b/src/storage/src/redis_zsets.h index c756d14dc0..b40cc0d80a 100644 --- a/src/storage/src/redis_zsets.h +++ b/src/storage/src/redis_zsets.h @@ -7,11 +7,11 @@ #define SRC_REDIS_ZSETS_h #include -#include #include +#include -#include "src/redis.h" #include "src/custom_comparator.h" +#include "src/redis.h" namespace storage { @@ -21,140 +21,57 @@ class RedisZSets : public Redis { ~RedisZSets() = default; // Common Commands - Status Open(const StorageOptions& storage_options, - const std::string& db_path) override; - Status CompactRange(const rocksdb::Slice* begin, - const rocksdb::Slice* end, + Status Open(const StorageOptions& storage_options, const std::string& db_path) override; + Status CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type = kMetaAndData) override; Status GetProperty(const std::string& property, uint64_t* out) override; Status ScanKeyNum(KeyInfo* key_info) override; - Status ScanKeys(const std::string& pattern, - std::vector* keys) override; + Status ScanKeys(const std::string& pattern, std::vector* keys) override; Status PKPatternMatchDel(const std::string& pattern, int32_t* ret) override; // ZSets Commands - Status ZAdd(const Slice& key, - const std::vector& score_members, - int32_t* ret); + Status ZAdd(const Slice& key, const std::vector& score_members, int32_t* ret); Status ZCard(const Slice& key, int32_t* card); - Status ZCount(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int32_t* ret); - Status ZIncrby(const Slice& key, - const Slice& member, - double increment, - double* ret); - Status ZRange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members); - Status ZRangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members); - Status ZRank(const Slice& key, - const Slice& member, - int32_t* rank); - Status ZRem(const Slice& key, - std::vector members, - int32_t* ret); - Status ZRemrangebyrank(const Slice& key, - int32_t start, - int32_t stop, - int32_t* ret); - Status ZRemrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int32_t* ret); - Status ZRevrange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members); - Status ZRevrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members); - Status ZRevrank(const Slice& key, - const Slice& member, - int32_t* rank); + Status ZCount(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret); + Status ZIncrby(const Slice& key, const Slice& member, double increment, double* ret); + Status ZRange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members); + Status ZRangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int64_t count, + int64_t offset, std::vector* score_members); + Status ZRank(const Slice& key, const Slice& member, int32_t* rank); + Status ZRem(const Slice& key, std::vector members, int32_t* ret); + Status ZRemrangebyrank(const Slice& key, int32_t start, int32_t stop, int32_t* ret); + Status ZRemrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret); + Status ZRevrange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members); + Status ZRevrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int64_t count, + int64_t offset, std::vector* score_members); + Status ZRevrank(const Slice& key, const Slice& member, int32_t* rank); Status ZScore(const Slice& key, const Slice& member, double* score); - Status ZUnionstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret); - Status ZInterstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret); - Status ZRangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, + Status ZUnionstore(const Slice& destination, const std::vector& keys, const std::vector& weights, + const AGGREGATE agg, int32_t* ret); + Status ZInterstore(const Slice& destination, const std::vector& keys, const std::vector& weights, + const AGGREGATE agg, int32_t* ret); + Status ZRangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, std::vector* members); - Status ZLexcount(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, + Status ZLexcount(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, int32_t* ret); - Status ZRemrangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, + Status ZRemrangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, int32_t* ret); - Status ZScan(const Slice& key, - int64_t cursor, - const std::string& pattern, - int64_t count, - std::vector* score_members, - int64_t* next_cursor); - Status PKScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key); - Status PKRScanRange(const Slice& key_start, - const Slice& key_end, - const Slice& pattern, - int32_t limit, - std::vector* keys, - std::string* next_key); - Status ZPopMax(const Slice& key, - const int64_t count, - std::vector* score_members); - Status ZPopMin(const Slice& key, - const int64_t count, - std::vector* score_members); + Status ZScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* score_members, int64_t* next_cursor); + Status PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key); + Status PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, + std::vector* keys, std::string* next_key); + Status ZPopMax(const Slice& key, const int64_t count, std::vector* score_members); + Status ZPopMin(const Slice& key, const int64_t count, std::vector* score_members); // Keys Commands Status Expire(const Slice& key, int32_t ttl) override; Status Del(const Slice& key) override; - bool Scan(const std::string& start_key, const std::string& pattern, - std::vector* keys, - int64_t* count, std::string* next_key) override; - bool PKExpireScan(const std::string& start_key, - int32_t min_timestamp, int32_t max_timestamp, - std::vector* keys, - int64_t* leftover_visits, - std::string* next_key) override; + bool Scan(const std::string& start_key, const std::string& pattern, std::vector* keys, int64_t* count, + std::string* next_key) override; + bool PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, + std::vector* keys, int64_t* leftover_visits, std::string* next_key) override; Status Expireat(const Slice& key, int32_t timestamp) override; Status Persist(const Slice& key) override; Status TTL(const Slice& key, int64_t* timestamp) override; diff --git a/src/storage/src/scope_record_lock.h b/src/storage/src/scope_record_lock.h index e51b9e8127..aa8c9dc7eb 100644 --- a/src/storage/src/scope_record_lock.h +++ b/src/storage/src/scope_record_lock.h @@ -6,22 +6,19 @@ #ifndef SRC_SCOPE_RECORD_LOCK_H_ #define SRC_SCOPE_RECORD_LOCK_H_ -#include -#include #include +#include +#include #include "src/lock_mgr.h" namespace storage { class ScopeRecordLock { public: - ScopeRecordLock(LockMgr* lock_mgr, const Slice& key) : - lock_mgr_(lock_mgr), key_(key) { + ScopeRecordLock(LockMgr* lock_mgr, const Slice& key) : lock_mgr_(lock_mgr), key_(key) { lock_mgr_->TryLock(key_.ToString()); } - ~ScopeRecordLock() { - lock_mgr_->UnLock(key_.ToString()); - } + ~ScopeRecordLock() { lock_mgr_->UnLock(key_.ToString()); } private: LockMgr* const lock_mgr_; @@ -32,14 +29,10 @@ class ScopeRecordLock { class MultiScopeRecordLock { public: - MultiScopeRecordLock(LockMgr* lock_mgr, - const std::vector& keys) : - lock_mgr_(lock_mgr), - keys_(keys) { + MultiScopeRecordLock(LockMgr* lock_mgr, const std::vector& keys) : lock_mgr_(lock_mgr), keys_(keys) { std::string pre_key; std::sort(keys_.begin(), keys_.end()); - if (!keys_.empty() && - keys_[0].empty()) { + if (!keys_.empty() && keys_[0].empty()) { lock_mgr_->TryLock(pre_key); } @@ -52,8 +45,7 @@ class MultiScopeRecordLock { } ~MultiScopeRecordLock() { std::string pre_key; - if (!keys_.empty() && - keys_[0].empty()) { + if (!keys_.empty() && keys_[0].empty()) { lock_mgr_->UnLock(pre_key); } diff --git a/src/storage/src/scope_snapshot.h b/src/storage/src/scope_snapshot.h index 4d61b116cd..a50d520516 100644 --- a/src/storage/src/scope_snapshot.h +++ b/src/storage/src/scope_snapshot.h @@ -11,13 +11,11 @@ namespace storage { class ScopeSnapshot { public: - ScopeSnapshot(rocksdb::DB* db, const rocksdb::Snapshot** snapshot) : - db_(db), snapshot_(snapshot) { + ScopeSnapshot(rocksdb::DB* db, const rocksdb::Snapshot** snapshot) : db_(db), snapshot_(snapshot) { *snapshot_ = db_->GetSnapshot(); } - ~ScopeSnapshot() { - db_->ReleaseSnapshot(*snapshot_); - } + ~ScopeSnapshot() { db_->ReleaseSnapshot(*snapshot_); } + private: rocksdb::DB* const db_; const rocksdb::Snapshot** snapshot_; diff --git a/src/storage/src/storage.cc b/src/storage/src/storage.cc index 1289d69f96..ec4d0d08a5 100644 --- a/src/storage/src/storage.cc +++ b/src/storage/src/storage.cc @@ -6,20 +6,20 @@ #include "storage/storage.h" #include "storage/util.h" -#include "src/options_helper.h" +#include "src/lru_cache.h" #include "src/mutex_impl.h" -#include "src/redis_strings.h" +#include "src/options_helper.h" #include "src/redis_hashes.h" -#include "src/redis_sets.h" +#include "src/redis_hyperloglog.h" #include "src/redis_lists.h" +#include "src/redis_sets.h" +#include "src/redis_strings.h" #include "src/redis_zsets.h" -#include "src/redis_hyperloglog.h" -#include "src/lru_cache.h" namespace storage { Status StorageOptions::ResetOptions(const OptionType& option_type, - const std::unordered_map& options_map) { + const std::unordered_map& options_map) { std::unordered_map& options_member_type_info = mutable_cf_options_member_type_info; char* opt = reinterpret_cast(static_cast(&options)); if (option_type == OptionType::kDB) { @@ -44,24 +44,23 @@ Status StorageOptions::ResetOptions(const OptionType& option_type, return Status::OK(); } -Storage::Storage() : - strings_db_(nullptr), - hashes_db_(nullptr), - sets_db_(nullptr), - zsets_db_(nullptr), - lists_db_(nullptr), - is_opened_(false), - bg_tasks_cond_var_(&bg_tasks_mutex_), - current_task_type_(kNone), - bg_tasks_should_exit_(false), - scan_keynum_exit_(false) { +Storage::Storage() + : strings_db_(nullptr), + hashes_db_(nullptr), + sets_db_(nullptr), + zsets_db_(nullptr), + lists_db_(nullptr), + is_opened_(false), + bg_tasks_cond_var_(&bg_tasks_mutex_), + current_task_type_(kNone), + bg_tasks_should_exit_(false), + scan_keynum_exit_(false) { cursors_store_ = new LRUCache(); cursors_store_->SetCapacity(5000); Status s = StartBGThread(); if (!s.ok()) { - fprintf(stderr, - "[FATAL] start bg thread failed, %s\n", s.ToString().c_str()); + fprintf(stderr, "[FATAL] start bg thread failed, %s\n", s.ToString().c_str()); exit(-1); } } @@ -91,8 +90,7 @@ Storage::~Storage() { delete cursors_store_; } -static std::string AppendSubDirectory(const std::string& db_path, - const std::string& sub_db) { +static std::string AppendSubDirectory(const std::string& db_path, const std::string& sub_db) { if (db_path.back() == '/') { return db_path + sub_db; } else { @@ -100,48 +98,41 @@ static std::string AppendSubDirectory(const std::string& db_path, } } -Status Storage::Open(const StorageOptions& storage_options, - const std::string& db_path) { +Status Storage::Open(const StorageOptions& storage_options, const std::string& db_path) { mkpath(db_path.c_str(), 0755); strings_db_ = new RedisStrings(this, kStrings); - Status s = strings_db_->Open( - storage_options, AppendSubDirectory(db_path, "strings")); + Status s = strings_db_->Open(storage_options, AppendSubDirectory(db_path, "strings")); if (!s.ok()) { - fprintf(stderr, - "[FATAL] open kv db failed, %s\n", s.ToString().c_str()); + fprintf(stderr, "[FATAL] open kv db failed, %s\n", s.ToString().c_str()); exit(-1); } hashes_db_ = new RedisHashes(this, kHashes); s = hashes_db_->Open(storage_options, AppendSubDirectory(db_path, "hashes")); if (!s.ok()) { - fprintf(stderr, - "[FATAL] open hashes db failed, %s\n", s.ToString().c_str()); + fprintf(stderr, "[FATAL] open hashes db failed, %s\n", s.ToString().c_str()); exit(-1); } sets_db_ = new RedisSets(this, kSets); s = sets_db_->Open(storage_options, AppendSubDirectory(db_path, "sets")); if (!s.ok()) { - fprintf(stderr, - "[FATAL] open set db failed, %s\n", s.ToString().c_str()); + fprintf(stderr, "[FATAL] open set db failed, %s\n", s.ToString().c_str()); exit(-1); } lists_db_ = new RedisLists(this, kLists); s = lists_db_->Open(storage_options, AppendSubDirectory(db_path, "lists")); if (!s.ok()) { - fprintf(stderr, - "[FATAL] open list db failed, %s\n", s.ToString().c_str()); + fprintf(stderr, "[FATAL] open list db failed, %s\n", s.ToString().c_str()); exit(-1); } zsets_db_ = new RedisZSets(this, kZSets); s = zsets_db_->Open(storage_options, AppendSubDirectory(db_path, "zsets")); if (!s.ok()) { - fprintf(stderr, - "[FATAL] open zset db failed, %s\n", s.ToString().c_str()); + fprintf(stderr, "[FATAL] open zset db failed, %s\n", s.ToString().c_str()); exit(-1); } is_opened_.store(true); @@ -153,65 +144,43 @@ Status Storage::GetStartKey(const DataType& dtype, int64_t cursor, std::string* return cursors_store_->Lookup(index_key, start_key); } -Status Storage::StoreCursorStartKey(const DataType& dtype, int64_t cursor, - const std::string& next_key) { +Status Storage::StoreCursorStartKey(const DataType& dtype, int64_t cursor, const std::string& next_key) { std::string index_key = DataTypeTag[dtype] + std::to_string(cursor); return cursors_store_->Insert(index_key, next_key); } // Strings Commands -Status Storage::Set(const Slice& key, - const Slice& value) { - return strings_db_->Set(key, value); -} +Status Storage::Set(const Slice& key, const Slice& value) { return strings_db_->Set(key, value); } -Status Storage::Setxx(const Slice& key, - const Slice& value, - int32_t* ret, - const int32_t ttl) { +Status Storage::Setxx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { return strings_db_->Setxx(key, value, ret, ttl); } -Status Storage::Get(const Slice& key, std::string* value) { - return strings_db_->Get(key, value); -} +Status Storage::Get(const Slice& key, std::string* value) { return strings_db_->Get(key, value); } -Status Storage::GetSet(const Slice& key, const Slice& value, - std::string* old_value) { +Status Storage::GetSet(const Slice& key, const Slice& value, std::string* old_value) { return strings_db_->GetSet(key, value, old_value); } -Status Storage::SetBit(const Slice& key, int64_t offset, - int32_t value, int32_t* ret) { +Status Storage::SetBit(const Slice& key, int64_t offset, int32_t value, int32_t* ret) { return strings_db_->SetBit(key, offset, value, ret); } -Status Storage::GetBit(const Slice& key, int64_t offset, int32_t* ret) { - return strings_db_->GetBit(key, offset, ret); -} +Status Storage::GetBit(const Slice& key, int64_t offset, int32_t* ret) { return strings_db_->GetBit(key, offset, ret); } -Status Storage::MSet(const std::vector& kvs) { - return strings_db_->MSet(kvs); -} +Status Storage::MSet(const std::vector& kvs) { return strings_db_->MSet(kvs); } -Status Storage::MGet(const std::vector& keys, - std::vector* vss) { +Status Storage::MGet(const std::vector& keys, std::vector* vss) { return strings_db_->MGet(keys, vss); } -Status Storage::Setnx(const Slice& key, const Slice& value, - int32_t* ret, const int32_t ttl) { +Status Storage::Setnx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { return strings_db_->Setnx(key, value, ret, ttl); } -Status Storage::MSetnx(const std::vector& kvs, - int32_t* ret) { - return strings_db_->MSetnx(kvs, ret); -} +Status Storage::MSetnx(const std::vector& kvs, int32_t* ret) { return strings_db_->MSetnx(kvs, ret); } -Status Storage::Setvx(const Slice& key, const Slice& value, - const Slice& new_value, int32_t* ret, - const int32_t ttl) { +Status Storage::Setvx(const Slice& key, const Slice& value, const Slice& new_value, int32_t* ret, const int32_t ttl) { return strings_db_->Setvx(key, value, new_value, ret, ttl); } @@ -219,13 +188,11 @@ Status Storage::Delvx(const Slice& key, const Slice& value, int32_t* ret) { return strings_db_->Delvx(key, value, ret); } -Status Storage::Setrange(const Slice& key, int64_t start_offset, - const Slice& value, int32_t* ret) { +Status Storage::Setrange(const Slice& key, int64_t start_offset, const Slice& value, int32_t* ret) { return strings_db_->Setrange(key, start_offset, value, ret); } -Status Storage::Getrange(const Slice& key, int64_t start_offset, - int64_t end_offset, std::string* ret) { +Status Storage::Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, std::string* ret) { return strings_db_->Getrange(key, start_offset, end_offset, ret); } @@ -233,210 +200,140 @@ Status Storage::Append(const Slice& key, const Slice& value, int32_t* ret) { return strings_db_->Append(key, value, ret); } -Status Storage::BitCount(const Slice& key, int64_t start_offset, - int64_t end_offset, int32_t *ret, bool have_range) { +Status Storage::BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, int32_t* ret, bool have_range) { return strings_db_->BitCount(key, start_offset, end_offset, ret, have_range); } -Status Storage::BitOp(BitOpType op, const std::string& dest_key, - const std::vector& src_keys, - int64_t* ret) { +Status Storage::BitOp(BitOpType op, const std::string& dest_key, const std::vector& src_keys, + int64_t* ret) { return strings_db_->BitOp(op, dest_key, src_keys, ret); } -Status Storage::BitPos(const Slice& key, int32_t bit, - int64_t* ret) { - return strings_db_->BitPos(key, bit, ret); -} +Status Storage::BitPos(const Slice& key, int32_t bit, int64_t* ret) { return strings_db_->BitPos(key, bit, ret); } -Status Storage::BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t* ret) { +Status Storage::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t* ret) { return strings_db_->BitPos(key, bit, start_offset, ret); } -Status Storage::BitPos(const Slice& key, int32_t bit, - int64_t start_offset, int64_t end_offset, - int64_t* ret) { +Status Storage::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t end_offset, int64_t* ret) { return strings_db_->BitPos(key, bit, start_offset, end_offset, ret); } -Status Storage::Decrby(const Slice& key, int64_t value, int64_t* ret) { - return strings_db_->Decrby(key, value, ret); -} +Status Storage::Decrby(const Slice& key, int64_t value, int64_t* ret) { return strings_db_->Decrby(key, value, ret); } -Status Storage::Incrby(const Slice& key, int64_t value, int64_t* ret) { - return strings_db_->Incrby(key, value, ret); -} +Status Storage::Incrby(const Slice& key, int64_t value, int64_t* ret) { return strings_db_->Incrby(key, value, ret); } -Status Storage::Incrbyfloat(const Slice& key, const Slice& value, - std::string* ret) { +Status Storage::Incrbyfloat(const Slice& key, const Slice& value, std::string* ret) { return strings_db_->Incrbyfloat(key, value, ret); } -Status Storage::Setex(const Slice& key, const Slice& value, int32_t ttl) { - return strings_db_->Setex(key, value, ttl); -} +Status Storage::Setex(const Slice& key, const Slice& value, int32_t ttl) { return strings_db_->Setex(key, value, ttl); } -Status Storage::Strlen(const Slice& key, int32_t* len) { - return strings_db_->Strlen(key, len); -} +Status Storage::Strlen(const Slice& key, int32_t* len) { return strings_db_->Strlen(key, len); } -Status Storage::PKSetexAt(const Slice& key, - const Slice& value, - int32_t timestamp) { +Status Storage::PKSetexAt(const Slice& key, const Slice& value, int32_t timestamp) { return strings_db_->PKSetexAt(key, value, timestamp); } // Hashes Commands -Status Storage::HSet(const Slice& key, const Slice& field, - const Slice& value, int32_t* res) { +Status Storage::HSet(const Slice& key, const Slice& field, const Slice& value, int32_t* res) { return hashes_db_->HSet(key, field, value, res); } -Status Storage::HGet(const Slice& key, const Slice& field, - std::string* value) { +Status Storage::HGet(const Slice& key, const Slice& field, std::string* value) { return hashes_db_->HGet(key, field, value); } -Status Storage::HMSet(const Slice& key, - const std::vector& fvs) { - return hashes_db_->HMSet(key, fvs); -} +Status Storage::HMSet(const Slice& key, const std::vector& fvs) { return hashes_db_->HMSet(key, fvs); } -Status Storage::HMGet(const Slice& key, - const std::vector& fields, - std::vector* vss) { +Status Storage::HMGet(const Slice& key, const std::vector& fields, std::vector* vss) { return hashes_db_->HMGet(key, fields, vss); } -Status Storage::HGetall(const Slice& key, - std::vector* fvs) { - return hashes_db_->HGetall(key, fvs); -} +Status Storage::HGetall(const Slice& key, std::vector* fvs) { return hashes_db_->HGetall(key, fvs); } -Status Storage::HKeys(const Slice& key, - std::vector* fields) { - return hashes_db_->HKeys(key, fields); -} +Status Storage::HKeys(const Slice& key, std::vector* fields) { return hashes_db_->HKeys(key, fields); } -Status Storage::HVals(const Slice& key, - std::vector* values) { - return hashes_db_->HVals(key, values); -} +Status Storage::HVals(const Slice& key, std::vector* values) { return hashes_db_->HVals(key, values); } -Status Storage::HSetnx(const Slice& key, const Slice& field, - const Slice& value, int32_t* ret) { +Status Storage::HSetnx(const Slice& key, const Slice& field, const Slice& value, int32_t* ret) { return hashes_db_->HSetnx(key, field, value, ret); } -Status Storage::HLen(const Slice& key, int32_t* ret) { - return hashes_db_->HLen(key, ret); -} +Status Storage::HLen(const Slice& key, int32_t* ret) { return hashes_db_->HLen(key, ret); } Status Storage::HStrlen(const Slice& key, const Slice& field, int32_t* len) { return hashes_db_->HStrlen(key, field, len); } -Status Storage::HExists(const Slice& key, const Slice& field) { - return hashes_db_->HExists(key, field); -} +Status Storage::HExists(const Slice& key, const Slice& field) { return hashes_db_->HExists(key, field); } -Status Storage::HIncrby(const Slice& key, const Slice& field, int64_t value, - int64_t* ret) { +Status Storage::HIncrby(const Slice& key, const Slice& field, int64_t value, int64_t* ret) { return hashes_db_->HIncrby(key, field, value, ret); } -Status Storage::HIncrbyfloat(const Slice& key, const Slice& field, - const Slice& by, std::string* new_value) { +Status Storage::HIncrbyfloat(const Slice& key, const Slice& field, const Slice& by, std::string* new_value) { return hashes_db_->HIncrbyfloat(key, field, by, new_value); } -Status Storage::HDel(const Slice& key, - const std::vector& fields, - int32_t* ret) { +Status Storage::HDel(const Slice& key, const std::vector& fields, int32_t* ret) { return hashes_db_->HDel(key, fields, ret); } -Status Storage::HScan(const Slice& key, int64_t cursor, - const std::string& pattern, int64_t count, - std::vector* field_values, - int64_t* next_cursor) { - return hashes_db_->HScan(key, cursor, - pattern, count, field_values, next_cursor); +Status Storage::HScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* field_values, int64_t* next_cursor) { + return hashes_db_->HScan(key, cursor, pattern, count, field_values, next_cursor); } -Status Storage::HScanx(const Slice& key, const std::string start_field, - const std::string& pattern, int64_t count, - std::vector* field_values, - std::string* next_field) { - return hashes_db_->HScanx(key, start_field, - pattern, count, field_values, next_field); +Status Storage::HScanx(const Slice& key, const std::string start_field, const std::string& pattern, int64_t count, + std::vector* field_values, std::string* next_field) { + return hashes_db_->HScanx(key, start_field, pattern, count, field_values, next_field); } -Status Storage::PKHScanRange(const Slice& key, const Slice& field_start, - const std::string& field_end, - const Slice& pattern, int32_t limit, - std::vector* field_values, - std::string* next_field) { - return hashes_db_->PKHScanRange(key, field_start, - field_end, pattern, limit, field_values, next_field); +Status Storage::PKHScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, + const Slice& pattern, int32_t limit, std::vector* field_values, + std::string* next_field) { + return hashes_db_->PKHScanRange(key, field_start, field_end, pattern, limit, field_values, next_field); } -Status Storage::PKHRScanRange(const Slice& key, const Slice& field_start, - const std::string& field_end, - const Slice& pattern, int32_t limit, - std::vector* field_values, - std::string* next_field) { - return hashes_db_->PKHRScanRange(key, field_start, - field_end, pattern, limit, field_values, next_field); +Status Storage::PKHRScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, + const Slice& pattern, int32_t limit, std::vector* field_values, + std::string* next_field) { + return hashes_db_->PKHRScanRange(key, field_start, field_end, pattern, limit, field_values, next_field); } // Sets Commands -Status Storage::SAdd(const Slice& key, - const std::vector& members, - int32_t* ret) { +Status Storage::SAdd(const Slice& key, const std::vector& members, int32_t* ret) { return sets_db_->SAdd(key, members, ret); } -Status Storage::SCard(const Slice& key, - int32_t* ret) { - return sets_db_->SCard(key, ret); -} +Status Storage::SCard(const Slice& key, int32_t* ret) { return sets_db_->SCard(key, ret); } -Status Storage::SDiff(const std::vector& keys, - std::vector* members) { +Status Storage::SDiff(const std::vector& keys, std::vector* members) { return sets_db_->SDiff(keys, members); } -Status Storage::SDiffstore(const Slice& destination, - const std::vector& keys, - int32_t* ret) { +Status Storage::SDiffstore(const Slice& destination, const std::vector& keys, int32_t* ret) { return sets_db_->SDiffstore(destination, keys, ret); } -Status Storage::SInter(const std::vector& keys, - std::vector* members) { +Status Storage::SInter(const std::vector& keys, std::vector* members) { return sets_db_->SInter(keys, members); } -Status Storage::SInterstore(const Slice& destination, - const std::vector& keys, - int32_t* ret) { +Status Storage::SInterstore(const Slice& destination, const std::vector& keys, int32_t* ret) { return sets_db_->SInterstore(destination, keys, ret); } -Status Storage::SIsmember(const Slice& key, const Slice& member, - int32_t* ret) { +Status Storage::SIsmember(const Slice& key, const Slice& member, int32_t* ret) { return sets_db_->SIsmember(key, member, ret); } -Status Storage::SMembers(const Slice& key, - std::vector* members) { +Status Storage::SMembers(const Slice& key, std::vector* members) { return sets_db_->SMembers(key, members); } -Status Storage::SMove(const Slice& source, const Slice& destination, - const Slice& member, int32_t* ret) { +Status Storage::SMove(const Slice& source, const Slice& destination, const Slice& member, int32_t* ret) { return sets_db_->SMove(source, destination, member, ret); } @@ -449,79 +346,53 @@ Status Storage::SPop(const Slice& key, std::string* member) { return status; } -Status Storage::SRandmember(const Slice& key, int32_t count, - std::vector* members) { +Status Storage::SRandmember(const Slice& key, int32_t count, std::vector* members) { return sets_db_->SRandmember(key, count, members); } -Status Storage::SRem(const Slice& key, - const std::vector& members, - int32_t* ret) { +Status Storage::SRem(const Slice& key, const std::vector& members, int32_t* ret) { return sets_db_->SRem(key, members, ret); } -Status Storage::SUnion(const std::vector& keys, - std::vector* members) { +Status Storage::SUnion(const std::vector& keys, std::vector* members) { return sets_db_->SUnion(keys, members); } -Status Storage::SUnionstore(const Slice& destination, - const std::vector& keys, - int32_t* ret) { +Status Storage::SUnionstore(const Slice& destination, const std::vector& keys, int32_t* ret) { return sets_db_->SUnionstore(destination, keys, ret); } -Status Storage::SScan(const Slice& key, int64_t cursor, - const std::string& pattern, int64_t count, - std::vector* members, - int64_t* next_cursor) { +Status Storage::SScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* members, int64_t* next_cursor) { return sets_db_->SScan(key, cursor, pattern, count, members, next_cursor); } -Status Storage::LPush(const Slice& key, - const std::vector& values, - uint64_t* ret) { +Status Storage::LPush(const Slice& key, const std::vector& values, uint64_t* ret) { return lists_db_->LPush(key, values, ret); } -Status Storage::RPush(const Slice& key, - const std::vector& values, - uint64_t* ret) { +Status Storage::RPush(const Slice& key, const std::vector& values, uint64_t* ret) { return lists_db_->RPush(key, values, ret); } -Status Storage::LRange(const Slice& key, int64_t start, int64_t stop, - std::vector* ret) { +Status Storage::LRange(const Slice& key, int64_t start, int64_t stop, std::vector* ret) { return lists_db_->LRange(key, start, stop, ret); } -Status Storage::LTrim(const Slice& key, int64_t start, int64_t stop) { - return lists_db_->LTrim(key, start, stop); -} +Status Storage::LTrim(const Slice& key, int64_t start, int64_t stop) { return lists_db_->LTrim(key, start, stop); } -Status Storage::LLen(const Slice& key, uint64_t* len) { - return lists_db_->LLen(key, len); -} +Status Storage::LLen(const Slice& key, uint64_t* len) { return lists_db_->LLen(key, len); } -Status Storage::LPop(const Slice& key, std::string* element) { - return lists_db_->LPop(key, element); -} +Status Storage::LPop(const Slice& key, std::string* element) { return lists_db_->LPop(key, element); } -Status Storage::RPop(const Slice& key, std::string* element) { - return lists_db_->RPop(key, element); -} +Status Storage::RPop(const Slice& key, std::string* element) { return lists_db_->RPop(key, element); } -Status Storage::LIndex(const Slice& key, - int64_t index, - std::string* element) { +Status Storage::LIndex(const Slice& key, int64_t index, std::string* element) { return lists_db_->LIndex(key, index, element); } -Status Storage::LInsert(const Slice& key, - const BeforeOrAfter& before_or_after, - const std::string& pivot, - const std::string& value, - int64_t* ret) { +Status Storage::LInsert(const Slice& key, const BeforeOrAfter& before_or_after, const std::string& pivot, + const std::string& value, int64_t* ret) { return lists_db_->LInsert(key, before_or_after, pivot, value, ret); } @@ -533,217 +404,127 @@ Status Storage::RPushx(const Slice& key, const Slice& value, uint64_t* len) { return lists_db_->RPushx(key, value, len); } -Status Storage::LRem(const Slice& key, int64_t count, - const Slice& value, uint64_t* ret) { +Status Storage::LRem(const Slice& key, int64_t count, const Slice& value, uint64_t* ret) { return lists_db_->LRem(key, count, value, ret); } -Status Storage::LSet(const Slice& key, int64_t index, const Slice& value) { - return lists_db_->LSet(key, index, value); -} +Status Storage::LSet(const Slice& key, int64_t index, const Slice& value) { return lists_db_->LSet(key, index, value); } -Status Storage::RPoplpush(const Slice& source, - const Slice& destination, - std::string* element) { +Status Storage::RPoplpush(const Slice& source, const Slice& destination, std::string* element) { return lists_db_->RPoplpush(source, destination, element); } -Status Storage::ZPopMax(const Slice& key, - const int64_t count, - std::vector* score_members){ +Status Storage::ZPopMax(const Slice& key, const int64_t count, std::vector* score_members) { return zsets_db_->ZPopMax(key, count, score_members); } -Status Storage::ZPopMin(const Slice& key, - const int64_t count, - std::vector* score_members){ +Status Storage::ZPopMin(const Slice& key, const int64_t count, std::vector* score_members) { return zsets_db_->ZPopMin(key, count, score_members); } -Status Storage::ZAdd(const Slice& key, - const std::vector& score_members, - int32_t* ret) { +Status Storage::ZAdd(const Slice& key, const std::vector& score_members, int32_t* ret) { return zsets_db_->ZAdd(key, score_members, ret); } -Status Storage::ZCard(const Slice& key, - int32_t* ret) { - return zsets_db_->ZCard(key, ret); -} +Status Storage::ZCard(const Slice& key, int32_t* ret) { return zsets_db_->ZCard(key, ret); } -Status Storage::ZCount(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int32_t* ret) { +Status Storage::ZCount(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret) { return zsets_db_->ZCount(key, min, max, left_close, right_close, ret); } -Status Storage::ZIncrby(const Slice& key, - const Slice& member, - double increment, - double* ret) { +Status Storage::ZIncrby(const Slice& key, const Slice& member, double increment, double* ret) { return zsets_db_->ZIncrby(key, member, increment, ret); } -Status Storage::ZRange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members) { +Status Storage::ZRange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members) { return zsets_db_->ZRange(key, start, stop, score_members); } -Status Storage::ZRangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - std::vector* score_members) { +Status Storage::ZRangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, + std::vector* score_members) { // maximum number of zset is std::numeric_limits::max() - return zsets_db_->ZRangebyscore(key, min, max, - left_close, right_close, std::numeric_limits::max(), 0, score_members); + return zsets_db_->ZRangebyscore(key, min, max, left_close, right_close, std::numeric_limits::max(), 0, + score_members); } -Status Storage::ZRangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members) { - return zsets_db_->ZRangebyscore(key, min, max, - left_close, right_close, count, offset, score_members); +Status Storage::ZRangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, + int64_t count, int64_t offset, std::vector* score_members) { + return zsets_db_->ZRangebyscore(key, min, max, left_close, right_close, count, offset, score_members); } -Status Storage::ZRank(const Slice& key, - const Slice& member, - int32_t* rank) { +Status Storage::ZRank(const Slice& key, const Slice& member, int32_t* rank) { return zsets_db_->ZRank(key, member, rank); } -Status Storage::ZRem(const Slice& key, - std::vector members, - int32_t* ret) { +Status Storage::ZRem(const Slice& key, std::vector members, int32_t* ret) { return zsets_db_->ZRem(key, members, ret); } -Status Storage::ZRemrangebyrank(const Slice& key, - int32_t start, - int32_t stop, - int32_t* ret) { +Status Storage::ZRemrangebyrank(const Slice& key, int32_t start, int32_t stop, int32_t* ret) { return zsets_db_->ZRemrangebyrank(key, start, stop, ret); } -Status Storage::ZRemrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int32_t* ret) { - return zsets_db_->ZRemrangebyscore(key, min, max, - left_close, right_close, ret); -} - -Status Storage::ZRevrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - int64_t count, - int64_t offset, - std::vector* score_members) { - return zsets_db_->ZRevrangebyscore(key, min, max, - left_close, right_close, count, offset, score_members); -} - -Status Storage::ZRevrange(const Slice& key, - int32_t start, - int32_t stop, - std::vector* score_members) { +Status Storage::ZRemrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, + int32_t* ret) { + return zsets_db_->ZRemrangebyscore(key, min, max, left_close, right_close, ret); +} + +Status Storage::ZRevrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, + int64_t count, int64_t offset, std::vector* score_members) { + return zsets_db_->ZRevrangebyscore(key, min, max, left_close, right_close, count, offset, score_members); +} + +Status Storage::ZRevrange(const Slice& key, int32_t start, int32_t stop, std::vector* score_members) { return zsets_db_->ZRevrange(key, start, stop, score_members); } -Status Storage::ZRevrangebyscore(const Slice& key, - double min, - double max, - bool left_close, - bool right_close, - std::vector* score_members) { +Status Storage::ZRevrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, + std::vector* score_members) { // maximum number of zset is std::numeric_limits::max() - return zsets_db_->ZRevrangebyscore(key, min, max, - left_close, right_close, std::numeric_limits::max(), 0, score_members); + return zsets_db_->ZRevrangebyscore(key, min, max, left_close, right_close, std::numeric_limits::max(), 0, + score_members); } -Status Storage::ZRevrank(const Slice& key, - const Slice& member, - int32_t* rank) { +Status Storage::ZRevrank(const Slice& key, const Slice& member, int32_t* rank) { return zsets_db_->ZRevrank(key, member, rank); } -Status Storage::ZScore(const Slice& key, - const Slice& member, - double* ret) { +Status Storage::ZScore(const Slice& key, const Slice& member, double* ret) { return zsets_db_->ZScore(key, member, ret); } -Status Storage::ZUnionstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret) { +Status Storage::ZUnionstore(const Slice& destination, const std::vector& keys, + const std::vector& weights, const AGGREGATE agg, int32_t* ret) { return zsets_db_->ZUnionstore(destination, keys, weights, agg, ret); } -Status Storage::ZInterstore(const Slice& destination, - const std::vector& keys, - const std::vector& weights, - const AGGREGATE agg, - int32_t* ret) { +Status Storage::ZInterstore(const Slice& destination, const std::vector& keys, + const std::vector& weights, const AGGREGATE agg, int32_t* ret) { return zsets_db_->ZInterstore(destination, keys, weights, agg, ret); } -Status Storage::ZRangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, - std::vector* members) { - return zsets_db_->ZRangebylex(key, min, max, - left_close, right_close, members); +Status Storage::ZRangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, + std::vector* members) { + return zsets_db_->ZRangebylex(key, min, max, left_close, right_close, members); } -Status Storage::ZLexcount(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, - int32_t* ret) { +Status Storage::ZLexcount(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, + int32_t* ret) { return zsets_db_->ZLexcount(key, min, max, left_close, right_close, ret); } -Status Storage::ZRemrangebylex(const Slice& key, - const Slice& min, - const Slice& max, - bool left_close, - bool right_close, - int32_t* ret) { +Status Storage::ZRemrangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, + int32_t* ret) { return zsets_db_->ZRemrangebylex(key, min, max, left_close, right_close, ret); } -Status Storage::ZScan(const Slice& key, int64_t cursor, - const std::string& pattern, int64_t count, - std::vector* score_members, - int64_t* next_cursor) { - return zsets_db_->ZScan(key, cursor, - pattern, count, score_members, next_cursor); +Status Storage::ZScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* score_members, int64_t* next_cursor) { + return zsets_db_->ZScan(key, cursor, pattern, count, score_members, next_cursor); } - // Keys Commands -int32_t Storage::Expire(const Slice& key, int32_t ttl, - std::map* type_status) { +int32_t Storage::Expire(const Slice& key, int32_t ttl, std::map* type_status) { int32_t ret = 0; bool is_corruption = false; @@ -799,8 +580,7 @@ int32_t Storage::Expire(const Slice& key, int32_t ttl, } } -int64_t Storage::Del(const std::vector& keys, - std::map* type_status) { +int64_t Storage::Del(const std::vector& keys, std::map* type_status) { Status s; int64_t count = 0; bool is_corruption = false; @@ -859,8 +639,7 @@ int64_t Storage::Del(const std::vector& keys, } } -int64_t Storage::DelByType(const std::vector& keys, - const DataType& type) { +int64_t Storage::DelByType(const std::vector& keys, const DataType& type) { Status s; int64_t count = 0; bool is_corruption = false; @@ -868,8 +647,7 @@ int64_t Storage::DelByType(const std::vector& keys, for (const auto& key : keys) { switch (type) { // Strings - case DataType::kStrings: - { + case DataType::kStrings: { s = strings_db_->Del(key); if (s.ok()) { count++; @@ -879,8 +657,7 @@ int64_t Storage::DelByType(const std::vector& keys, break; } // Hashes - case DataType::kHashes: - { + case DataType::kHashes: { s = hashes_db_->Del(key); if (s.ok()) { count++; @@ -890,8 +667,7 @@ int64_t Storage::DelByType(const std::vector& keys, break; } // Sets - case DataType::kSets: - { + case DataType::kSets: { s = sets_db_->Del(key); if (s.ok()) { count++; @@ -901,8 +677,7 @@ int64_t Storage::DelByType(const std::vector& keys, break; } // Lists - case DataType::kLists: - { + case DataType::kLists: { s = lists_db_->Del(key); if (s.ok()) { count++; @@ -912,8 +687,7 @@ int64_t Storage::DelByType(const std::vector& keys, break; } // ZSets - case DataType::kZSets: - { + case DataType::kZSets: { s = zsets_db_->Del(key); if (s.ok()) { count++; @@ -922,8 +696,7 @@ int64_t Storage::DelByType(const std::vector& keys, } break; } - case DataType::kAll: - { + case DataType::kAll: { return -1; } } @@ -936,9 +709,7 @@ int64_t Storage::DelByType(const std::vector& keys, } } - -int64_t Storage::Exists(const std::vector& keys, - std::map* type_status) { +int64_t Storage::Exists(const std::vector& keys, std::map* type_status) { int64_t count = 0; int32_t ret; uint64_t llen; @@ -995,17 +766,15 @@ int64_t Storage::Exists(const std::vector& keys, } } -int64_t Storage::Scan(const DataType& dtype, int64_t cursor, - const std::string& pattern, int64_t count, - std::vector* keys) { +int64_t Storage::Scan(const DataType& dtype, int64_t cursor, const std::string& pattern, int64_t count, + std::vector* keys) { keys->clear(); bool is_finish; int64_t leftover_visits = count; int64_t step_length = count, cursor_ret = 0; std::string start_key, next_key, prefix; - prefix = isTailWildcard(pattern) ? - pattern.substr(0, pattern.size() - 1) : ""; + prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; if (cursor < 0) { return cursor_ret; @@ -1013,8 +782,7 @@ int64_t Storage::Scan(const DataType& dtype, int64_t cursor, Status s = GetStartKey(dtype, cursor, &start_key); if (s.IsNotFound()) { // If want to scan all the databases, we start with the strings database - start_key = (dtype == DataType::kAll - ? DataTypeTag[kStrings] : DataTypeTag[dtype]) + prefix; + start_key = (dtype == DataType::kAll ? DataTypeTag[kStrings] : DataTypeTag[dtype]) + prefix; cursor = 0; } } @@ -1023,8 +791,7 @@ int64_t Storage::Scan(const DataType& dtype, int64_t cursor, start_key.erase(start_key.begin()); switch (key_type) { case 'k': - is_finish = strings_db_->Scan(start_key, pattern, - keys, &leftover_visits, &next_key); + is_finish = strings_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("k") + next_key); @@ -1041,8 +808,7 @@ int64_t Storage::Scan(const DataType& dtype, int64_t cursor, } start_key = prefix; case 'h': - is_finish = hashes_db_->Scan(start_key, pattern, - keys, &leftover_visits, &next_key); + is_finish = hashes_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("h") + next_key); @@ -1059,8 +825,7 @@ int64_t Storage::Scan(const DataType& dtype, int64_t cursor, } start_key = prefix; case 's': - is_finish = sets_db_->Scan(start_key, pattern, - keys, &leftover_visits, &next_key); + is_finish = sets_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("s") + next_key); @@ -1077,8 +842,7 @@ int64_t Storage::Scan(const DataType& dtype, int64_t cursor, } start_key = prefix; case 'l': - is_finish = lists_db_->Scan(start_key, pattern, - keys, &leftover_visits, &next_key); + is_finish = lists_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("l") + next_key); @@ -1095,8 +859,7 @@ int64_t Storage::Scan(const DataType& dtype, int64_t cursor, } start_key = prefix; case 'z': - is_finish = zsets_db_->Scan(start_key, pattern, - keys, &leftover_visits, &next_key); + is_finish = zsets_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("z") + next_key); @@ -1109,9 +872,8 @@ int64_t Storage::Scan(const DataType& dtype, int64_t cursor, return cursor_ret; } -int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, - int32_t min_ttl, int32_t max_ttl, - int64_t count, std::vector* keys) { +int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, int32_t min_ttl, int32_t max_ttl, int64_t count, + std::vector* keys) { keys->clear(); bool is_finish; int64_t leftover_visits = count; @@ -1127,8 +889,7 @@ int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, Status s = GetStartKey(dtype, cursor, &start_key); if (s.IsNotFound()) { // If want to scan all the databases, we start with the strings database - start_key = std::string(1, dtype == DataType::kAll - ? DataTypeTag[kStrings] : DataTypeTag[dtype]); + start_key = std::string(1, dtype == DataType::kAll ? DataTypeTag[kStrings] : DataTypeTag[dtype]); cursor = 0; } } @@ -1137,8 +898,8 @@ int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, start_key.erase(start_key.begin()); switch (key_type) { case 'k': - is_finish = strings_db_->PKExpireScan(start_key, curtime + min_ttl, - curtime + max_ttl, keys, &leftover_visits, &next_key); + is_finish = + strings_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("k") + next_key); @@ -1155,8 +916,8 @@ int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, } start_key = ""; case 'h': - is_finish = hashes_db_->PKExpireScan(start_key, curtime + min_ttl, - curtime + max_ttl, keys, &leftover_visits, &next_key); + is_finish = + hashes_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("h") + next_key); @@ -1173,8 +934,8 @@ int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, } start_key = ""; case 's': - is_finish = sets_db_->PKExpireScan(start_key, curtime + min_ttl, - curtime + max_ttl, keys, &leftover_visits, &next_key); + is_finish = + sets_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("s") + next_key); @@ -1191,8 +952,8 @@ int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, } start_key = ""; case 'l': - is_finish = lists_db_->PKExpireScan(start_key, curtime + min_ttl, - curtime + max_ttl, keys, &leftover_visits, &next_key); + is_finish = + lists_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("l") + next_key); @@ -1209,8 +970,8 @@ int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, } start_key = ""; case 'z': - is_finish = zsets_db_->PKExpireScan(start_key, curtime + min_ttl, - curtime + max_ttl, keys, &leftover_visits, &next_key); + is_finish = + zsets_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("z") + next_key); @@ -1223,37 +984,27 @@ int64_t Storage::PKExpireScan(const DataType& dtype, int64_t cursor, return cursor_ret; } - - -Status Storage::PKScanRange(const DataType& data_type, - const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, - std::vector* keys, - std::vector* kvs, - std::string* next_key) { +Status Storage::PKScanRange(const DataType& data_type, const Slice& key_start, const Slice& key_end, + const Slice& pattern, int32_t limit, std::vector* keys, + std::vector* kvs, std::string* next_key) { Status s; keys->clear(); next_key->clear(); switch (data_type) { case DataType::kStrings: - s = strings_db_->PKScanRange(key_start, key_end, - pattern, limit, kvs, next_key); + s = strings_db_->PKScanRange(key_start, key_end, pattern, limit, kvs, next_key); break; case DataType::kHashes: - s = hashes_db_->PKScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = hashes_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kLists: - s = lists_db_->PKScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = lists_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kZSets: - s = zsets_db_->PKScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = zsets_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kSets: - s = sets_db_->PKScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = sets_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; default: s = Status::Corruption("Unsupported data types"); @@ -1262,35 +1013,27 @@ Status Storage::PKScanRange(const DataType& data_type, return s; } -Status Storage::PKRScanRange(const DataType& data_type, - const Slice& key_start, const Slice& key_end, - const Slice& pattern, int32_t limit, - std::vector* keys, - std::vector* kvs, - std::string* next_key) { +Status Storage::PKRScanRange(const DataType& data_type, const Slice& key_start, const Slice& key_end, + const Slice& pattern, int32_t limit, std::vector* keys, + std::vector* kvs, std::string* next_key) { Status s; keys->clear(); next_key->clear(); switch (data_type) { case DataType::kStrings: - s = strings_db_->PKRScanRange(key_start, key_end, - pattern, limit, kvs, next_key); + s = strings_db_->PKRScanRange(key_start, key_end, pattern, limit, kvs, next_key); break; case DataType::kHashes: - s = hashes_db_->PKRScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = hashes_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kLists: - s = lists_db_->PKRScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = lists_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kZSets: - s = zsets_db_->PKRScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = zsets_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kSets: - s = sets_db_->PKRScanRange(key_start, key_end, - pattern, limit, keys, next_key); + s = sets_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; default: s = Status::Corruption("Unsupported data types"); @@ -1299,9 +1042,7 @@ Status Storage::PKRScanRange(const DataType& data_type, return s; } -Status Storage::PKPatternMatchDel(const DataType& data_type, - const std::string& pattern, - int32_t* ret) { +Status Storage::PKPatternMatchDel(const DataType& data_type, const std::string& pattern, int32_t* ret) { Status s; switch (data_type) { case DataType::kStrings: @@ -1326,12 +1067,8 @@ Status Storage::PKPatternMatchDel(const DataType& data_type, return s; } -Status Storage::Scanx(const DataType& data_type, - const std::string& start_key, - const std::string& pattern, - int64_t count, - std::vector* keys, - std::string* next_key) { +Status Storage::Scanx(const DataType& data_type, const std::string& start_key, const std::string& pattern, + int64_t count, std::vector* keys, std::string* next_key) { Status s; keys->clear(); next_key->clear(); @@ -1358,8 +1095,7 @@ Status Storage::Scanx(const DataType& data_type, return s; } -int32_t Storage::Expireat(const Slice& key, int32_t timestamp, - std::map* type_status) { +int32_t Storage::Expireat(const Slice& key, int32_t timestamp, std::map* type_status) { Status s; int32_t count = 0; bool is_corruption = false; @@ -1411,8 +1147,7 @@ int32_t Storage::Expireat(const Slice& key, int32_t timestamp, } } -int32_t Storage::Persist(const Slice& key, - std::map* type_status) { +int32_t Storage::Persist(const Slice& key, std::map* type_status) { Status s; int32_t count = 0; bool is_corruption = false; @@ -1464,8 +1199,7 @@ int32_t Storage::Persist(const Slice& key, } } -std::map Storage::TTL(const Slice& key, - std::map* type_status) { +std::map Storage::TTL(const Slice& key, std::map* type_status) { Status s; std::map ret; int64_t timestamp = 0; @@ -1513,7 +1247,7 @@ std::map Storage::TTL(const Slice& key, } // the sequence is kv, hash, list, zset, set -Status Storage::Type(const std::string &key, std::string* type) { +Status Storage::Type(const std::string& key, std::string* type) { type->clear(); Status s; @@ -1566,9 +1300,7 @@ Status Storage::Type(const std::string &key, std::string* type) { return Status::OK(); } -Status Storage::Keys(const DataType& data_type, - const std::string& pattern, - std::vector* keys) { +Status Storage::Keys(const DataType& data_type, const std::string& pattern, std::vector* keys) { Status s; if (data_type == DataType::kStrings) { s = strings_db_->ScanKeys(pattern, keys); @@ -1603,34 +1335,32 @@ Status Storage::Keys(const DataType& data_type, void Storage::ScanDatabase(const DataType& type) { switch (type) { case kStrings: - strings_db_->ScanDatabase(); - break; + strings_db_->ScanDatabase(); + break; case kHashes: - hashes_db_->ScanDatabase(); - break; + hashes_db_->ScanDatabase(); + break; case kSets: - sets_db_->ScanDatabase(); - break; + sets_db_->ScanDatabase(); + break; case kZSets: - zsets_db_->ScanDatabase(); - break; + zsets_db_->ScanDatabase(); + break; case kLists: - lists_db_->ScanDatabase(); - break; + lists_db_->ScanDatabase(); + break; case kAll: - strings_db_->ScanDatabase(); - hashes_db_->ScanDatabase(); - sets_db_->ScanDatabase(); - zsets_db_->ScanDatabase(); - lists_db_->ScanDatabase(); - break; + strings_db_->ScanDatabase(); + hashes_db_->ScanDatabase(); + sets_db_->ScanDatabase(); + zsets_db_->ScanDatabase(); + lists_db_->ScanDatabase(); + break; } } // HyperLogLog -Status Storage::PfAdd(const Slice& key, - const std::vector& values, - bool* update) { +Status Storage::PfAdd(const Slice& key, const std::vector& values, bool* update) { *update = false; if (values.size() >= kMaxKeys) { return Status::InvalidArgument("Invalid the number of key"); @@ -1659,8 +1389,7 @@ Status Storage::PfAdd(const Slice& key, return s; } -Status Storage::PfCount(const std::vector& keys, - int64_t* result) { +Status Storage::PfCount(const std::vector& keys, int64_t* result) { if (keys.size() >= kMaxKeys || keys.size() <= 0) { return Status::InvalidArgument("Invalid the number of key"); } @@ -1731,8 +1460,7 @@ static void* StartBGThreadWrapper(void* arg) { } Status Storage::StartBGThread() { - int result = pthread_create(&bg_tasks_thread_id_, - NULL, StartBGThreadWrapper, this); + int result = pthread_create(&bg_tasks_thread_id_, NULL, StartBGThreadWrapper, this); if (result != 0) { char msg[128]; snprintf(msg, sizeof(msg), "pthread create: %s", strerror(result)); @@ -1792,12 +1520,7 @@ Status Storage::Compact(const DataType& type, bool sync) { } Status Storage::DoCompact(const DataType& type) { - if (type != kAll - && type != kStrings - && type != kHashes - && type != kSets - && type != kZSets - && type != kLists) { + if (type != kAll && type != kStrings && type != kHashes && type != kSets && type != kZSets && type != kLists) { return Status::InvalidArgument(""); } @@ -1896,19 +1619,17 @@ Status Storage::GetUsage(const std::string& property, uint64_t* const result) { return Status::OK(); } -Status Storage::GetUsage(const std::string& property, - std::map* const type_result) { +Status Storage::GetUsage(const std::string& property, std::map* const type_result) { type_result->clear(); (*type_result)[STRINGS_DB] = GetProperty(STRINGS_DB, property); - (*type_result)[HASHES_DB] = GetProperty(HASHES_DB, property); - (*type_result)[LISTS_DB] = GetProperty(LISTS_DB, property); - (*type_result)[ZSETS_DB] = GetProperty(ZSETS_DB, property); - (*type_result)[SETS_DB] = GetProperty(SETS_DB, property); + (*type_result)[HASHES_DB] = GetProperty(HASHES_DB, property); + (*type_result)[LISTS_DB] = GetProperty(LISTS_DB, property); + (*type_result)[ZSETS_DB] = GetProperty(ZSETS_DB, property); + (*type_result)[SETS_DB] = GetProperty(SETS_DB, property); return Status::OK(); } -uint64_t Storage::GetProperty(const std::string& db_type, - const std::string& property) { +uint64_t Storage::GetProperty(const std::string& db_type, const std::string& property) { uint64_t out = 0, result = 0; if (db_type == ALL_DB || db_type == STRINGS_DB) { strings_db_->GetProperty(property, &out); @@ -1936,8 +1657,7 @@ uint64_t Storage::GetProperty(const std::string& db_type, Status Storage::GetKeyNum(std::vector* key_infos) { KeyInfo key_info; // NOTE: keep the db order with string, hash, list, zset, set - std::vector dbs = {strings_db_, hashes_db_, - lists_db_, zsets_db_, sets_db_}; + std::vector dbs = {strings_db_, hashes_db_, lists_db_, zsets_db_, sets_db_}; for (const auto& db : dbs) { // check the scanner was stopped or not, before scanning the next db if (scan_keynum_exit_) { @@ -1975,7 +1695,7 @@ rocksdb::DB* Storage::GetDBByType(const std::string& type) { } Status Storage::SetOptions(const OptionType& option_type, const std::string& db_type, - const std::unordered_map& options) { + const std::unordered_map& options) { Status s; if (db_type == ALL_DB || db_type == STRINGS_DB) { s = strings_db_->SetOptions(option_type, options); diff --git a/src/storage/src/storage_murmur3.h b/src/storage/src/storage_murmur3.h index dfcbda2dea..25f95175c9 100644 --- a/src/storage/src/storage_murmur3.h +++ b/src/storage/src/storage_murmur3.h @@ -25,47 +25,40 @@ typedef unsigned __int64 uint64_t; // Other compilers -#else // defined(_MSC_VER) +#else // defined(_MSC_VER) -#include +# include -#endif // !defined(_MSC_VER) +#endif // !defined(_MSC_VER) #define FORCE_INLINE __attribute__((always_inline)) -inline uint32_t rotl32 ( uint32_t x, uint8_t r ) -{ - return (x << r) | (x >> (32 - r)); -} +inline uint32_t rotl32(uint32_t x, uint8_t r) { return (x << r) | (x >> (32 - r)); } -#define ROTL32(x,y) rotl32(x,y) +#define ROTL32(x, y) rotl32(x, y) #define BIG_CONSTANT(x) (x##LLU) /* NO-OP for little-endian platforms */ #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) -# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ -# define BYTESWAP(x) (x) -# endif +# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define BYTESWAP(x) (x) +# endif /* if __BYTE_ORDER__ is not predefined (like FreeBSD), use arch */ -#elif defined(__i386) || defined(__x86_64) \ -|| defined(__alpha) || defined(__vax) +#elif defined(__i386) || defined(__x86_64) || defined(__alpha) || defined(__vax) -# define BYTESWAP(x) (x) +# define BYTESWAP(x) (x) /* use __builtin_bswap32 if available */ #elif defined(__GNUC__) || defined(__clang__) -#ifdef __has_builtin -#if __has_builtin(__builtin_bswap32) -#define BYTESWAP(x) __builtin_bswap32(x) -#endif // __has_builtin(__builtin_bswap32) -#endif // __has_builtin -#endif // defined(__GNUC__) || defined(__clang__) +# ifdef __has_builtin +# if __has_builtin(__builtin_bswap32) +# define BYTESWAP(x) __builtin_bswap32(x) +# endif // __has_builtin(__builtin_bswap32) +# endif // __has_builtin +#endif // defined(__GNUC__) || defined(__clang__) /* last resort (big-endian w/o __builtin_bswap) */ #ifndef BYTESWAP -# define BYTESWAP(x) ((((x)&0xFF)<<24) \ -|(((x)>>24)&0xFF) \ -|(((x)&0x0000FF00)<<8) \ -|(((x)&0x00FF0000)>>8) ) +# define BYTESWAP(x) ((((x)&0xFF) << 24) | (((x) >> 24) & 0xFF) | (((x)&0x0000FF00) << 8) | (((x)&0x00FF0000) >> 8)) #endif //----------------------------------------------------------------------------- @@ -77,15 +70,14 @@ inline uint32_t rotl32 ( uint32_t x, uint8_t r ) //----------------------------------------------------------------------------- // Finalization mix - force all bits of a hash block to avalanche -uint32_t fmix32( uint32_t h ) -{ - h ^= h >> 16; - h *= 0x85ebca6b; - h ^= h >> 13; - h *= 0xc2b2ae35; - h ^= h >> 16; - - return h; +uint32_t fmix32(uint32_t h) { + h ^= h >> 16; + h *= 0x85ebca6b; + h ^= h >> 13; + h *= 0xc2b2ae35; + h ^= h >> 16; + + return h; } //----------------------------------------------------------------------------- @@ -95,62 +87,65 @@ extern "C" #else extern #endif -void MurmurHash3_x86_32( const void * key, int len, uint32_t seed, void * out ) -{ - const uint8_t * data = (const uint8_t*)key; - const int nblocks = len / 4; - int i; - - uint32_t h1 = seed; - - uint32_t c1 = 0xcc9e2d51; - uint32_t c2 = 0x1b873593; - - //---------- - // body - - const uint32_t * blocks = (const uint32_t *)(data + nblocks*4); - - for(i = -nblocks; i; i++) - { - uint32_t k1 = getblock(blocks,i); - + void + MurmurHash3_x86_32(const void* key, int len, uint32_t seed, void* out) { + const uint8_t* data = (const uint8_t*)key; + const int nblocks = len / 4; + int i; + + uint32_t h1 = seed; + + uint32_t c1 = 0xcc9e2d51; + uint32_t c2 = 0x1b873593; + + //---------- + // body + + const uint32_t* blocks = (const uint32_t*)(data + nblocks * 4); + + for (i = -nblocks; i; i++) { + uint32_t k1 = getblock(blocks, i); + + k1 *= c1; + k1 = ROTL32(k1, 15); + k1 *= c2; + + h1 ^= k1; + h1 = ROTL32(h1, 13); + h1 = h1 * 5 + 0xe6546b64; + } + + //---------- + // tail + { + const uint8_t* tail = (const uint8_t*)(data + nblocks * 4); + + uint32_t k1 = 0; + + switch (len & 3) { + case 3: + k1 ^= tail[2] << 16; + case 2: + k1 ^= tail[1] << 8; + case 1: + k1 ^= tail[0]; k1 *= c1; - k1 = ROTL32(k1,15); + k1 = ROTL32(k1, 15); k1 *= c2; - h1 ^= k1; - h1 = ROTL32(h1,13); - h1 = h1*5+0xe6546b64; - } - - //---------- - // tail - { - const uint8_t * tail = (const uint8_t*)(data + nblocks*4); - - uint32_t k1 = 0; - - switch(len & 3) - { - case 3: k1 ^= tail[2] << 16; - case 2: k1 ^= tail[1] << 8; - case 1: k1 ^= tail[0]; - k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; - }; - } - - //---------- - // finalization - - h1 ^= len; - - h1 = fmix32(h1); - - *(uint32_t*)out = h1; + }; + } + + //---------- + // finalization + + h1 ^= len; + + h1 = fmix32(h1); + + *(uint32_t*)out = h1; } -} // end namespace nemo +} // namespace storage #endif - diff --git a/src/storage/src/strings_filter.h b/src/storage/src/strings_filter.h index dc6fa92253..a7d89e1c43 100644 --- a/src/storage/src/strings_filter.h +++ b/src/storage/src/strings_filter.h @@ -6,38 +6,33 @@ #ifndef SRC_STRINGS_FILTER_H_ #define SRC_STRINGS_FILTER_H_ -#include #include +#include -#include "src/strings_value_format.h" #include "rocksdb/compaction_filter.h" #include "src/debug.h" +#include "src/strings_value_format.h" namespace storage { class StringsFilter : public rocksdb::CompactionFilter { public: StringsFilter() = default; - bool Filter(int level, const rocksdb::Slice& key, - const rocksdb::Slice& value, - std::string* new_value, bool* value_changed) const override { + bool Filter(int level, const rocksdb::Slice& key, const rocksdb::Slice& value, std::string* new_value, + bool* value_changed) const override { int64_t unix_time; rocksdb::Env::Default()->GetCurrentTime(&unix_time); int32_t cur_time = static_cast(unix_time); ParsedStringsValue parsed_strings_value(value); - Trace("==========================START=========================="); - Trace("[StringsFilter], key: %s, value = %s, timestamp: %d, cur_time: %d", - key.ToString().c_str(), - parsed_strings_value.value().ToString().c_str(), - parsed_strings_value.timestamp(), - cur_time); - - if (parsed_strings_value.timestamp() != 0 - && parsed_strings_value.timestamp() < cur_time) { - Trace("Drop[Stale]"); + TRACE("==========================START=========================="); + TRACE("[StringsFilter], key: %s, value = %s, timestamp: %d, cur_time: %d", key.ToString().c_str(), + parsed_strings_value.value().ToString().c_str(), parsed_strings_value.timestamp(), cur_time); + + if (parsed_strings_value.timestamp() != 0 && parsed_strings_value.timestamp() < cur_time) { + TRACE("Drop[Stale]"); return true; } else { - Trace("Reserve"); + TRACE("Reserve"); return false; } } @@ -49,12 +44,10 @@ class StringsFilterFactory : public rocksdb::CompactionFilterFactory { public: StringsFilterFactory() = default; std::unique_ptr CreateCompactionFilter( - const rocksdb::CompactionFilter::Context& context) override { + const rocksdb::CompactionFilter::Context& context) override { return std::unique_ptr(new StringsFilter()); } - const char* Name() const override { - return "StringsFilterFactory"; - } + const char* Name() const override { return "StringsFilterFactory"; } }; } // namespace storage diff --git a/src/storage/src/strings_value_format.h b/src/storage/src/strings_value_format.h index 0f3ab27cbe..f1e68da161 100644 --- a/src/storage/src/strings_value_format.h +++ b/src/storage/src/strings_value_format.h @@ -14,9 +14,7 @@ namespace storage { class StringsValue : public InternalValue { public: - explicit StringsValue(const Slice& user_value) : - InternalValue(user_value) { - } + explicit StringsValue(const rocksdb::Slice& user_value) : InternalValue(user_value) {} size_t AppendTimestampAndVersion() override { size_t usize = user_value_.size(); char* dst = start_; @@ -30,49 +28,38 @@ class StringsValue : public InternalValue { class ParsedStringsValue : public ParsedInternalValue { public: // Use this constructor after rocksdb::DB::Get(); - explicit ParsedStringsValue(std::string* internal_value_str) : - ParsedInternalValue(internal_value_str) { + explicit ParsedStringsValue(std::string* internal_value_str) : ParsedInternalValue(internal_value_str) { if (internal_value_str->size() >= kStringsValueSuffixLength) { - user_value_ = Slice(internal_value_str->data(), - internal_value_str->size() - kStringsValueSuffixLength); - timestamp_ = DecodeFixed32(internal_value_str->data() + - internal_value_str->size() - kStringsValueSuffixLength); + user_value_ = rocksdb::Slice(internal_value_str->data(), internal_value_str->size() - kStringsValueSuffixLength); + timestamp_ = DecodeFixed32(internal_value_str->data() + internal_value_str->size() - kStringsValueSuffixLength); } } // Use this constructor in rocksdb::CompactionFilter::Filter(); - explicit ParsedStringsValue(const Slice& internal_value_slice) : - ParsedInternalValue(internal_value_slice) { + explicit ParsedStringsValue(const rocksdb::Slice& internal_value_slice) : ParsedInternalValue(internal_value_slice) { if (internal_value_slice.size() >= kStringsValueSuffixLength) { - user_value_ = Slice(internal_value_slice.data(), - internal_value_slice.size() - kStringsValueSuffixLength); - timestamp_ = DecodeFixed32(internal_value_slice.data() + - internal_value_slice.size() - kStringsValueSuffixLength); + user_value_ = rocksdb::Slice(internal_value_slice.data(), internal_value_slice.size() - kStringsValueSuffixLength); + timestamp_ = DecodeFixed32(internal_value_slice.data() + internal_value_slice.size() - kStringsValueSuffixLength); } } void StripSuffix() override { if (value_ != nullptr) { - value_->erase(value_->size() - kStringsValueSuffixLength, - kStringsValueSuffixLength); + value_->erase(value_->size() - kStringsValueSuffixLength, kStringsValueSuffixLength); } } // Strings type do not have version field; - void SetVersionToValue() override { - } + void SetVersionToValue() override {} void SetTimestampToValue() override { if (value_ != nullptr) { - char* dst = const_cast(value_->data()) + value_->size() - - kStringsValueSuffixLength; + char* dst = const_cast(value_->data()) + value_->size() - kStringsValueSuffixLength; EncodeFixed32(dst, timestamp_); } } - Slice value() { - return user_value_; - } + rocksdb::Slice value() { return user_value_; } static const size_t kStringsValueSuffixLength = sizeof(int32_t); }; diff --git a/src/storage/src/util.cc b/src/storage/src/util.cc index b55b8d7c90..cbccb24ca3 100644 --- a/src/storage/src/util.cc +++ b/src/storage/src/util.cc @@ -4,8 +4,8 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include #include #include "src/coding.h" @@ -22,8 +22,7 @@ uint32_t Digits10(uint64_t v) { if (v < 1000000000000UL) { if (v < 100000000UL) { if (v < 1000000) { - if (v < 10000) - return 4; + if (v < 10000) return 4; return 5 + (v >= 100000); } return 7 + (v >= 10000000UL); @@ -48,137 +47,137 @@ uint32_t Digits10(uint64_t v) { * Modified in order to handle signed integers since the original code was * designed for unsigned integers. */ int Int64ToStr(char* dst, size_t dstlen, int64_t svalue) { - static const char digits[201] = - "0001020304050607080910111213141516171819" - "2021222324252627282930313233343536373839" - "4041424344454647484950515253545556575859" - "6061626364656667686970717273747576777879" - "8081828384858687888990919293949596979899"; - int negative; - uint64_t value; - - /* The main loop works with 64bit unsigned integers for simplicity, so - * we convert the number here and remember if it is negative. */ - if (svalue < 0) { - if (svalue != LLONG_MIN) { - value = -svalue; - } else { - value = ((uint64_t) LLONG_MAX)+1; - } - negative = 1; + static const char digits[201] = + "0001020304050607080910111213141516171819" + "2021222324252627282930313233343536373839" + "4041424344454647484950515253545556575859" + "6061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"; + int negative; + uint64_t value; + + /* The main loop works with 64bit unsigned integers for simplicity, so + * we convert the number here and remember if it is negative. */ + if (svalue < 0) { + if (svalue != LLONG_MIN) { + value = -svalue; } else { - value = svalue; - negative = 0; + value = ((uint64_t)LLONG_MAX) + 1; } + negative = 1; + } else { + value = svalue; + negative = 0; + } - /* Check length. */ - uint32_t const length = Digits10(value)+negative; - if (length >= dstlen) return 0; - - /* Null term. */ - uint32_t next = length; - dst[next] = '\0'; - next--; - while (value >= 100) { - int const i = (value % 100) * 2; - value /= 100; - dst[next] = digits[i + 1]; - dst[next - 1] = digits[i]; - next -= 2; - } + /* Check length. */ + uint32_t const length = Digits10(value) + negative; + if (length >= dstlen) return 0; + + /* Null term. */ + uint32_t next = length; + dst[next] = '\0'; + next--; + while (value >= 100) { + int const i = (value % 100) * 2; + value /= 100; + dst[next] = digits[i + 1]; + dst[next - 1] = digits[i]; + next -= 2; + } - /* Handle last 1-2 digits. */ - if (value < 10) { - dst[next] = '0' + (uint32_t) value; - } else { - int i = (uint32_t) value * 2; - dst[next] = digits[i + 1]; - dst[next - 1] = digits[i]; - } + /* Handle last 1-2 digits. */ + if (value < 10) { + dst[next] = '0' + (uint32_t)value; + } else { + int i = (uint32_t)value * 2; + dst[next] = digits[i + 1]; + dst[next - 1] = digits[i]; + } - /* Add sign. */ - if (negative) dst[0] = '-'; - return length; + /* Add sign. */ + if (negative) dst[0] = '-'; + return length; } /* Convert a string into a long long. Returns 1 if the string could be parsed * into a (non-overflowing) long long, 0 otherwise. The value will be set to * the parsed value when appropriate. */ -int StrToInt64(const char *s, size_t slen, int64_t *value) { - const char *p = s; - size_t plen = 0; - int negative = 0; - uint64_t v; - - if (plen == slen) - return 0; - - /* Special case: first and only digit is 0. */ - if (slen == 1 && p[0] == '0') { - if (value != NULL) *value = 0; - return 1; - } +int StrToInt64(const char* s, size_t slen, int64_t* value) { + const char* p = s; + size_t plen = 0; + int negative = 0; + uint64_t v; - if (p[0] == '-') { - negative = 1; - p++; plen++; + if (plen == slen) return 0; - /* Abort on only a negative sign. */ - if (plen == slen) - return 0; - } + /* Special case: first and only digit is 0. */ + if (slen == 1 && p[0] == '0') { + if (value != NULL) *value = 0; + return 1; + } - while (plen < slen && p[0] == '0') { - p++; plen++; - } + if (p[0] == '-') { + negative = 1; + p++; + plen++; - if (plen == slen) { - if (value != NULL) *value = 0; - return 1; - } + /* Abort on only a negative sign. */ + if (plen == slen) return 0; + } - /* First digit should be 1-9, otherwise the string should just be 0. */ - if (p[0] >= '1' && p[0] <= '9') { - v = p[0]-'0'; - p++; plen++; - } else if (p[0] == '0' && slen == 1) { - *value = 0; - return 1; - } else { - return 0; - } + while (plen < slen && p[0] == '0') { + p++; + plen++; + } + + if (plen == slen) { + if (value != NULL) *value = 0; + return 1; + } + + /* First digit should be 1-9, otherwise the string should just be 0. */ + if (p[0] >= '1' && p[0] <= '9') { + v = p[0] - '0'; + p++; + plen++; + } else if (p[0] == '0' && slen == 1) { + *value = 0; + return 1; + } else { + return 0; + } - while (plen < slen && p[0] >= '0' && p[0] <= '9') { - if (v > (ULLONG_MAX / 10)) /* Overflow. */ - return 0; - v *= 10; + while (plen < slen && p[0] >= '0' && p[0] <= '9') { + if (v > (ULLONG_MAX / 10)) /* Overflow. */ + return 0; + v *= 10; - if (v > (ULLONG_MAX - (p[0]-'0'))) /* Overflow. */ - return 0; - v += p[0]-'0'; + if (v > (ULLONG_MAX - (p[0] - '0'))) /* Overflow. */ + return 0; + v += p[0] - '0'; - p++; plen++; - } + p++; + plen++; + } - /* Return if not all bytes were used. */ - if (plen < slen) - return 0; + /* Return if not all bytes were used. */ + if (plen < slen) return 0; - if (negative) { - if (v > ((uint64_t)(-(LLONG_MIN+1))+1)) /* Overflow. */ - return 0; - if (value != NULL) *value = -v; - } else { - if (v > LLONG_MAX) /* Overflow. */ - return 0; - if (value != NULL) *value = v; - } - return 1; + if (negative) { + if (v > ((uint64_t)(-(LLONG_MIN + 1)) + 1)) /* Overflow. */ + return 0; + if (value != NULL) *value = -v; + } else { + if (v > LLONG_MAX) /* Overflow. */ + return 0; + if (value != NULL) *value = v; + } + return 1; } /* Glob-style pattern matching. */ -int StringMatch(const char *pattern, int pattern_len, const char* str, - int string_len, int nocase) { +int StringMatch(const char* pattern, int pattern_len, const char* str, int string_len, int nocase) { while (pattern_len) { switch (pattern[0]) { case '*': @@ -186,25 +185,20 @@ int StringMatch(const char *pattern, int pattern_len, const char* str, pattern++; pattern_len--; } - if (pattern_len == 1) - return 1; /* match */ + if (pattern_len == 1) return 1; /* match */ while (string_len) { - if (StringMatch(pattern+1, pattern_len-1, - str, string_len, nocase)) - return 1; /* match */ + if (StringMatch(pattern + 1, pattern_len - 1, str, string_len, nocase)) return 1; /* match */ str++; string_len--; } return 0; /* no match */ break; case '?': - if (string_len == 0) - return 0; /* no match */ + if (string_len == 0) return 0; /* no match */ str++; string_len--; break; - case '[': - { + case '[': { int not_flag, match; pattern++; pattern_len--; @@ -218,53 +212,46 @@ int StringMatch(const char *pattern, int pattern_len, const char* str, if (pattern[0] == '\\') { pattern++; pattern_len--; - if (pattern[0] == str[0]) - match = 1; - } else if (pattern[0] == ']') { - break; - } else if (pattern_len == 0) { - pattern--; - pattern_len++; - break; - } else if (pattern[1] == '-' && pattern_len >= 3) { - int start = pattern[0]; - int end = pattern[2]; - int c = str[0]; - if (start > end) { - int t = start; - start = end; - end = t; - } - if (nocase) { - start = tolower(start); - end = tolower(end); - c = tolower(c); - } - pattern += 2; - pattern_len -= 2; - if (c >= start && c <= end) - match = 1; - } else { - if (!nocase) { - if (pattern[0] == str[0]) - match = 1; - } else { - if (tolower(static_cast(pattern[0])) == - tolower(static_cast(str[0]))) - match = 1; - } - } - pattern++; - pattern_len--; - } - if (not_flag) - match = !match; - if (!match) - return 0; /* no match */ - str++; - string_len--; + if (pattern[0] == str[0]) match = 1; + } else if (pattern[0] == ']') { break; + } else if (pattern_len == 0) { + pattern--; + pattern_len++; + break; + } else if (pattern[1] == '-' && pattern_len >= 3) { + int start = pattern[0]; + int end = pattern[2]; + int c = str[0]; + if (start > end) { + int t = start; + start = end; + end = t; + } + if (nocase) { + start = tolower(start); + end = tolower(end); + c = tolower(c); + } + pattern += 2; + pattern_len -= 2; + if (c >= start && c <= end) match = 1; + } else { + if (!nocase) { + if (pattern[0] == str[0]) match = 1; + } else { + if (tolower(static_cast(pattern[0])) == tolower(static_cast(str[0]))) match = 1; + } + } + pattern++; + pattern_len--; } + if (not_flag) match = !match; + if (!match) return 0; /* no match */ + str++; + string_len--; + break; + } case '\\': if (pattern_len >= 2) { pattern++; @@ -273,92 +260,86 @@ int StringMatch(const char *pattern, int pattern_len, const char* str, /* fall through */ default: if (!nocase) { - if (pattern[0] != str[0]) - return 0; /* no match */ + if (pattern[0] != str[0]) return 0; /* no match */ } else { - if (tolower(static_cast(pattern[0])) != - tolower(static_cast(str[0]))) - return 0; /* no match */ + if (tolower(static_cast(pattern[0])) != tolower(static_cast(str[0]))) return 0; /* no match */ } str++; string_len--; break; + } + pattern++; + pattern_len--; + if (string_len == 0) { + while (*pattern == '*') { + pattern++; + pattern_len--; } - pattern++; - pattern_len--; - if (string_len == 0) { - while (*pattern == '*') { - pattern++; - pattern_len--; - } - break; - } + break; } - if (pattern_len == 0 && string_len == 0) - return 1; - return 0; + } + if (pattern_len == 0 && string_len == 0) return 1; + return 0; } int StrToLongDouble(const char* s, size_t slen, long double* ldval) { - char *pEnd; - std::string t(s, slen); - if (t.find(" ") != std::string::npos) { - return -1; - } - long double d = strtold(s, &pEnd); - if (pEnd != s + slen) - return -1; + char* pEnd; + std::string t(s, slen); + if (t.find(" ") != std::string::npos) { + return -1; + } + long double d = strtold(s, &pEnd); + if (pEnd != s + slen) return -1; - if (ldval != NULL) *ldval = d; - return 0; + if (ldval != NULL) *ldval = d; + return 0; } int LongDoubleToStr(long double ldval, std::string* value) { - char buf[256]; - int len; - if (std::isnan(ldval)) { - return -1; - } else if (std::isinf(ldval)) { - /* Libc in odd systems (Hi Solaris!) will format infinite in a - * different way, so better to handle it in an explicit way. */ - if (ldval > 0) { - memcpy(buf, "inf", 3); - len = 3; - } else { - memcpy(buf, "-inf", 4); - len = 4; - } - return -1; + char buf[256]; + int len; + if (std::isnan(ldval)) { + return -1; + } else if (std::isinf(ldval)) { + /* Libc in odd systems (Hi Solaris!) will format infinite in a + * different way, so better to handle it in an explicit way. */ + if (ldval > 0) { + memcpy(buf, "inf", 3); + len = 3; } else { - /* We use 17 digits precision since with 128 bit floats that precision - * after rounding is able to represent most small decimal numbers in a - * way that is "non surprising" for the user (that is, most small - * decimal numbers will be represented in a way that when converted - * back into a string are exactly the same as what the user typed.) */ - len = snprintf(buf, sizeof(buf), "%.17Lf", ldval); - /* Now remove trailing zeroes after the '.' */ - if (strchr(buf, '.') != NULL) { - char *p = buf+len-1; - while (*p == '0') { - p--; - len--; - } - if (*p == '.') len--; + memcpy(buf, "-inf", 4); + len = 4; + } + return -1; + } else { + /* We use 17 digits precision since with 128 bit floats that precision + * after rounding is able to represent most small decimal numbers in a + * way that is "non surprising" for the user (that is, most small + * decimal numbers will be represented in a way that when converted + * back into a string are exactly the same as what the user typed.) */ + len = snprintf(buf, sizeof(buf), "%.17Lf", ldval); + /* Now remove trailing zeroes after the '.' */ + if (strchr(buf, '.') != NULL) { + char* p = buf + len - 1; + while (*p == '0') { + p--; + len--; } - value->assign(buf, len); - return 0; + if (*p == '.') len--; } + value->assign(buf, len); + return 0; + } } -int do_mkdir(const char *path, mode_t mode) { +int do_mkdir(const char* path, mode_t mode) { struct stat st; int status = 0; if (stat(path, &st) != 0) { /* Directory does not exist. EEXIST for race * condition */ - if (mkdir(path, mode) != 0 && errno != EEXIST) - status = -1; + if (mkdir(path, mode) != 0 && errno != EEXIST) status = -1; } else if (!S_ISDIR(st.st_mode)) { errno = ENOTDIR; status = -1; @@ -373,11 +354,11 @@ int do_mkdir(const char *path, mode_t mode) { ** each directory in path exists, rather than optimistically creating ** the last element and working backwards. */ -int mkpath(const char *path, mode_t mode) { - char *pp; - char *sp; - int status; - char *copypath = strdup(path); +int mkpath(const char* path, mode_t mode) { + char* pp; + char* sp; + int status; + char* copypath = strdup(path); status = 0; pp = copypath; @@ -390,72 +371,69 @@ int mkpath(const char *path, mode_t mode) { } pp = sp + 1; } - if (status == 0) - status = do_mkdir(path, mode); + if (status == 0) status = do_mkdir(path, mode); free(copypath); return (status); } int delete_dir(const char* dirname) { - char chBuf[256]; - DIR * dir = NULL; - struct dirent *ptr; - int ret = 0; - dir = opendir(dirname); - if (NULL == dir) { - return -1; + char chBuf[256]; + DIR* dir = NULL; + struct dirent* ptr; + int ret = 0; + dir = opendir(dirname); + if (NULL == dir) { + return -1; + } + while ((ptr = readdir(dir)) != NULL) { + ret = strcmp(ptr->d_name, "."); + if (0 == ret) { + continue; } - while ((ptr = readdir(dir)) != NULL) { - ret = strcmp(ptr->d_name, "."); - if (0 == ret) { - continue; - } - ret = strcmp(ptr->d_name, ".."); - if (0 == ret) { - continue; - } - snprintf(chBuf, sizeof(256), "%s/%s", dirname, ptr->d_name); - ret = is_dir(chBuf); - if (0 == ret) { - // is dir - ret = delete_dir(chBuf); - if (0 != ret) { - return -1; - } - } else if (1 == ret) { - // is file - ret = remove(chBuf); - if (0 != ret) { - return -1; - } - } + ret = strcmp(ptr->d_name, ".."); + if (0 == ret) { + continue; } - (void)closedir(dir); - ret = remove(dirname); - if (0 != ret) { + snprintf(chBuf, sizeof(256), "%s/%s", dirname, ptr->d_name); + ret = is_dir(chBuf); + if (0 == ret) { + // is dir + ret = delete_dir(chBuf); + if (0 != ret) { return -1; + } + } else if (1 == ret) { + // is file + ret = remove(chBuf); + if (0 != ret) { + return -1; + } } - return 0; + } + (void)closedir(dir); + ret = remove(dirname); + if (0 != ret) { + return -1; + } + return 0; } int is_dir(const char* filename) { - struct stat buf; - int ret = stat(filename, &buf); - if (0 == ret) { - if (buf.st_mode & S_IFDIR) { - // folder - return 0; - } else { - // file - return 1; - } + struct stat buf; + int ret = stat(filename, &buf); + if (0 == ret) { + if (buf.st_mode & S_IFDIR) { + // folder + return 0; + } else { + // file + return 1; } - return -1; + } + return -1; } -int CalculateMetaStartAndEndKey(const std::string& key, - std::string* meta_start_key, - std::string* meta_end_key) { +int CalculateMetaStartAndEndKey(const std::string& key, std::string* meta_start_key, std::string* meta_end_key) { size_t needed = key.size() + 1; char* dst = new char[needed]; const char* start = dst; @@ -468,9 +446,7 @@ int CalculateMetaStartAndEndKey(const std::string& key, return 0; } -int CalculateDataStartAndEndKey(const std::string& key, - std::string* data_start_key, - std::string* data_end_key) { +int CalculateDataStartAndEndKey(const std::string& key, std::string* data_start_key, std::string* data_end_key) { size_t needed = sizeof(int32_t) + key.size() + 1; char* dst = new char[needed]; const char* start = dst; @@ -493,8 +469,7 @@ bool isTailWildcard(const std::string& pattern) { return false; } else { for (uint32_t idx = 0; idx < pattern.size() - 1; ++idx) { - if (pattern[idx] == '*' || pattern[idx] == '?' - || pattern[idx] == '[' || pattern[idx] == ']') { + if (pattern[idx] == '*' || pattern[idx] == '?' || pattern[idx] == '[' || pattern[idx] == ']') { return false; } } @@ -503,41 +478,35 @@ bool isTailWildcard(const std::string& pattern) { return true; } -void GetFilepath(const char *path, const char *filename, char *filepath) -{ - strcpy(filepath, path); - if(filepath[strlen(path) - 1] != '/') - strcat(filepath, "/"); - strcat(filepath, filename); +void GetFilepath(const char* path, const char* filename, char* filepath) { + strcpy(filepath, path); + if (filepath[strlen(path) - 1] != '/') strcat(filepath, "/"); + strcat(filepath, filename); } -bool DeleteFiles(const char* path) -{ - DIR *dir; - struct dirent *dirinfo; - struct stat statbuf; - char filepath[256] = {0}; - lstat(path, &statbuf); - - if (S_ISREG(statbuf.st_mode))//判断是否是常规文件 - { - remove(path); - } - else if (S_ISDIR(statbuf.st_mode))//判断是否是目录 - { - if ((dir = opendir(path)) == NULL) - return 1; - while ((dirinfo = readdir(dir)) != NULL) - { - GetFilepath(path, dirinfo->d_name, filepath); - if (strcmp(dirinfo->d_name, ".") == 0 || strcmp(dirinfo->d_name, "..") == 0)//判断是否是特殊目录 - continue; - DeleteFiles(filepath); - rmdir(filepath); - } - closedir(dir); +bool DeleteFiles(const char* path) { + DIR* dir; + struct dirent* dirinfo; + struct stat statbuf; + char filepath[256] = {0}; + lstat(path, &statbuf); + + if (S_ISREG(statbuf.st_mode)) // 判断是否是常规文件 + { + remove(path); + } else if (S_ISDIR(statbuf.st_mode)) // 判断是否是目录 + { + if ((dir = opendir(path)) == NULL) return 1; + while ((dirinfo = readdir(dir)) != NULL) { + GetFilepath(path, dirinfo->d_name, filepath); + if (strcmp(dirinfo->d_name, ".") == 0 || strcmp(dirinfo->d_name, "..") == 0) // 判断是否是特殊目录 + continue; + DeleteFiles(filepath); + rmdir(filepath); } - return 0; + closedir(dir); + } + return 0; } } // namespace storage diff --git a/src/storage/src/zsets_data_key_format.h b/src/storage/src/zsets_data_key_format.h index 78d50c0c8e..62be99d809 100644 --- a/src/storage/src/zsets_data_key_format.h +++ b/src/storage/src/zsets_data_key_format.h @@ -14,11 +14,8 @@ namespace storage { */ class ZSetsScoreKey { public: - ZSetsScoreKey(const Slice& key, int32_t version, - double score, const Slice& member) : - start_(nullptr), key_(key), - version_(version), score_(score), - member_(member) {} + ZSetsScoreKey(const Slice& key, int32_t version, double score, const Slice& member) + : start_(nullptr), key_(key), version_(version), score_(score), member_(member) {} ~ZSetsScoreKey() { if (start_ != space_) { @@ -27,8 +24,7 @@ class ZSetsScoreKey { } const Slice Encode() { - size_t needed = key_.size() + member_.size() - + sizeof(int32_t) * 2 + sizeof(uint64_t); + size_t needed = key_.size() + member_.size() + sizeof(int32_t) * 2 + sizeof(uint64_t); char* dst = nullptr; if (needed <= sizeof(space_)) { dst = space_; @@ -63,7 +59,6 @@ class ZSetsScoreKey { Slice member_; }; - class ParsedZSetsScoreKey { public: explicit ParsedZSetsScoreKey(const std::string* key) { @@ -79,8 +74,7 @@ class ParsedZSetsScoreKey { const void* ptr_tmp = reinterpret_cast(&tmp); score_ = *reinterpret_cast(ptr_tmp); ptr += sizeof(uint64_t); - member_ = Slice(ptr, key->size() - key_len - - 2 * sizeof(int32_t) - sizeof(uint64_t)); + member_ = Slice(ptr, key->size() - key_len - 2 * sizeof(int32_t) - sizeof(uint64_t)); } explicit ParsedZSetsScoreKey(const Slice& key) { @@ -96,22 +90,13 @@ class ParsedZSetsScoreKey { const void* ptr_tmp = reinterpret_cast(&tmp); score_ = *reinterpret_cast(ptr_tmp); ptr += sizeof(uint64_t); - member_ = Slice(ptr, key.size() - key_len - - 2 * sizeof(int32_t) - sizeof(uint64_t)); + member_ = Slice(ptr, key.size() - key_len - 2 * sizeof(int32_t) - sizeof(uint64_t)); } - Slice key() { - return key_; - } - int32_t version() const { - return version_; - } - double score() const { - return score_; - } - Slice member() { - return member_; - } + Slice key() { return key_; } + int32_t version() const { return version_; } + double score() const { return score_; } + Slice member() { return member_; } private: Slice key_; diff --git a/src/storage/src/zsets_filter.h b/src/storage/src/zsets_filter.h index 4a2d2c1d5d..d8a520d7bb 100644 --- a/src/storage/src/zsets_filter.h +++ b/src/storage/src/zsets_filter.h @@ -6,9 +6,9 @@ #ifndef SRC_ZSETS_FILTER_H_ #define SRC_ZSETS_FILTER_H_ +#include #include #include -#include #include "rocksdb/compaction_filter.h" @@ -16,30 +16,20 @@ #include "base_meta_value_format.h" #include "zsets_data_key_format.h" - namespace storage { class ZSetsScoreFilter : public rocksdb::CompactionFilter { public: - ZSetsScoreFilter(rocksdb::DB* db, - std::vector* handles_ptr) : - db_(db), - cf_handles_ptr_(handles_ptr), - meta_not_found_(false), - cur_meta_version_(0), - cur_meta_timestamp_(0) {} - - bool Filter(int level, const rocksdb::Slice& key, - const rocksdb::Slice& value, - std::string* new_value, + ZSetsScoreFilter(rocksdb::DB* db, std::vector* handles_ptr) + : db_(db), cf_handles_ptr_(handles_ptr), meta_not_found_(false), cur_meta_version_(0), cur_meta_timestamp_(0) {} + + bool Filter(int level, const rocksdb::Slice& key, const rocksdb::Slice& value, std::string* new_value, bool* value_changed) const override { ParsedZSetsScoreKey parsed_zsets_score_key(key); - Trace("==========================START=========================="); - Trace("[ScoreFilter], key: %s, score = %lf, member = %s, version = %d", - parsed_zsets_score_key.key().ToString().c_str(), - parsed_zsets_score_key.score(), - parsed_zsets_score_key.member().ToString().c_str(), - parsed_zsets_score_key.version()); + TRACE("==========================START=========================="); + TRACE("[ScoreFilter], key: %s, score = %lf, member = %s, version = %d", + parsed_zsets_score_key.key().ToString().c_str(), parsed_zsets_score_key.score(), + parsed_zsets_score_key.member().ToString().c_str(), parsed_zsets_score_key.version()); if (parsed_zsets_score_key.key().ToString() != cur_key_) { cur_key_ = parsed_zsets_score_key.key().ToString(); @@ -48,8 +38,7 @@ class ZSetsScoreFilter : public rocksdb::CompactionFilter { if (cf_handles_ptr_->size() == 0) { return false; } - Status s = db_->Get(default_read_options_, - (*cf_handles_ptr_)[0], cur_key_, &meta_value); + Status s = db_->Get(default_read_options_, (*cf_handles_ptr_)[0], cur_key_, &meta_value); if (s.ok()) { meta_not_found_ = false; ParsedZSetsMetaValue parsed_zsets_meta_value(&meta_value); @@ -59,33 +48,32 @@ class ZSetsScoreFilter : public rocksdb::CompactionFilter { meta_not_found_ = true; } else { cur_key_ = ""; - Trace("Reserve[Get meta_key faild]"); + TRACE("Reserve[Get meta_key faild]"); return false; } } if (meta_not_found_) { - Trace("Drop[Meta key not exist]"); + TRACE("Drop[Meta key not exist]"); return true; } int64_t unix_time; rocksdb::Env::Default()->GetCurrentTime(&unix_time); - if (cur_meta_timestamp_ != 0 && - cur_meta_timestamp_ < static_cast(unix_time)) { - Trace("Drop[Timeout]"); + if (cur_meta_timestamp_ != 0 && cur_meta_timestamp_ < static_cast(unix_time)) { + TRACE("Drop[Timeout]"); return true; } if (cur_meta_version_ > parsed_zsets_score_key.version()) { - Trace("Drop[score_key_version < cur_meta_version]"); + TRACE("Drop[score_key_version < cur_meta_version]"); return true; } else { - Trace("Reserve[score_key_version == cur_meta_version]"); + TRACE("Reserve[score_key_version == cur_meta_version]"); return false; } } - const char* Name() const override { return "ZSetsScoreFilter";} + const char* Name() const override { return "ZSetsScoreFilter"; } private: rocksdb::DB* db_; @@ -99,19 +87,15 @@ class ZSetsScoreFilter : public rocksdb::CompactionFilter { class ZSetsScoreFilterFactory : public rocksdb::CompactionFilterFactory { public: - ZSetsScoreFilterFactory(rocksdb::DB** db_ptr, - std::vector* handles_ptr) - : db_ptr_(db_ptr), cf_handles_ptr_(handles_ptr) {} + ZSetsScoreFilterFactory(rocksdb::DB** db_ptr, std::vector* handles_ptr) + : db_ptr_(db_ptr), cf_handles_ptr_(handles_ptr) {} std::unique_ptr CreateCompactionFilter( const rocksdb::CompactionFilter::Context& context) override { - return std::unique_ptr( - new ZSetsScoreFilter(*db_ptr_, cf_handles_ptr_)); + return std::unique_ptr(new ZSetsScoreFilter(*db_ptr_, cf_handles_ptr_)); } - const char* Name() const override { - return "ZSetsScoreFilterFactory"; - } + const char* Name() const override { return "ZSetsScoreFilterFactory"; } private: rocksdb::DB** db_ptr_; diff --git a/src/storage/tests/custom_comparator_test.cc b/src/storage/tests/custom_comparator_test.cc index 3c8b450252..9661d2619b 100644 --- a/src/storage/tests/custom_comparator_test.cc +++ b/src/storage/tests/custom_comparator_test.cc @@ -4,11 +4,11 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include -#include "src/redis.h" #include "src/custom_comparator.h" +#include "src/redis.h" #include "src/zsets_data_key_format.h" #include "storage/storage.h" @@ -16,23 +16,21 @@ using namespace storage; // FindShortestSeparator TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { - ZSetsScoreKeyComparatorImpl impl; // ***************** Group 1 Test ***************** - ZSetsScoreKey zsets_score_key_start_1("Axlgrep", 1557212501, 3.1415, "abc"); + ZSetsScoreKey zsets_score_key_start_1("Axlgrep", 1557212501, 3.1415, "abc"); ZSetsScoreKey zsets_score_key_limit_1("Axlgreq", 1557212501, 3.1415, "abc"); std::string start_1 = zsets_score_key_start_1.Encode().ToString(); std::string limit_1 = zsets_score_key_limit_1.Encode().ToString(); std::string change_start_1 = start_1; impl.FindShortestSeparator(&change_start_1, Slice(limit_1)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_1); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_1); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_1); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_1); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_1); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_1); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_1, start_1) >= 0); - ASSERT_TRUE(impl.Compare(change_start_1, limit_1) < 0); - + ASSERT_TRUE(impl.Compare(change_start_1, limit_1) < 0); // ***************** Group 2 Test ***************** ZSetsScoreKey zsets_score_key_start_2("Axlgrep", 1557212501, 3.1314, "abc"); @@ -41,13 +39,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_2 = zsets_score_key_limit_2.Encode().ToString(); std::string change_start_2 = start_2; impl.FindShortestSeparator(&change_start_2, Slice(limit_2)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_2); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_2); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_2); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_2); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_2); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_2); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_2, start_2) >= 0); - ASSERT_TRUE(impl.Compare(change_start_2, limit_2) < 0); - + ASSERT_TRUE(impl.Compare(change_start_2, limit_2) < 0); // ***************** Group 3 Test ***************** ZSetsScoreKey zsets_score_key_start_3("Axlgrep", 1557212501, 3.1415, "abc"); @@ -56,13 +53,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_3 = zsets_score_key_limit_3.Encode().ToString(); std::string change_start_3 = start_3; impl.FindShortestSeparator(&change_start_3, Slice(limit_3)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_3); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_3); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_3); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_3); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_3); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_3); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_3, start_3) >= 0); - ASSERT_TRUE(impl.Compare(change_start_3, limit_3) < 0); - + ASSERT_TRUE(impl.Compare(change_start_3, limit_3) < 0); // ***************** Group 4 Test ***************** ZSetsScoreKey zsets_score_key_start_4("Axlgrep", 1557212501, 3.1415, "abc"); @@ -71,13 +67,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_4 = zsets_score_key_limit_4.Encode().ToString(); std::string change_start_4 = start_4; impl.FindShortestSeparator(&change_start_4, Slice(limit_4)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_4); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_4); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_4); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_4); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_4); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_4); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_4, start_4) >= 0); - ASSERT_TRUE(impl.Compare(change_start_4, limit_4) < 0); - + ASSERT_TRUE(impl.Compare(change_start_4, limit_4) < 0); // ***************** Group 5 Test ***************** ZSetsScoreKey zsets_score_key_start_5("Axlgrep", 1557212501, 3.1415, "abc"); @@ -86,13 +81,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_5 = zsets_score_key_limit_5.Encode().ToString(); std::string change_start_5 = start_5; impl.FindShortestSeparator(&change_start_5, Slice(limit_5)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_5); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_5); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_5); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_5); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_5); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_5); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_5, start_5) >= 0); - ASSERT_TRUE(impl.Compare(change_start_5, limit_5) < 0); - + ASSERT_TRUE(impl.Compare(change_start_5, limit_5) < 0); // ***************** Group 6 Test ***************** ZSetsScoreKey zsets_score_key_start_6("Axlgrep", 1557212501, 3.1415, "abccccccc"); @@ -101,13 +95,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_6 = zsets_score_key_limit_6.Encode().ToString(); std::string change_start_6 = start_6; impl.FindShortestSeparator(&change_start_6, Slice(limit_6)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_6); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_6); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_6); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_6); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_6); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_6); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_6, start_6) >= 0); - ASSERT_TRUE(impl.Compare(change_start_6, limit_6) < 0); - + ASSERT_TRUE(impl.Compare(change_start_6, limit_6) < 0); // ***************** Group 7 Test ***************** ZSetsScoreKey zsets_score_key_start_7("Axlgrep", 1557212501, 3.1415, "abcccaccc"); @@ -116,13 +109,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_7 = zsets_score_key_limit_7.Encode().ToString(); std::string change_start_7 = start_7; impl.FindShortestSeparator(&change_start_7, Slice(limit_7)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_7); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_7); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_7); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_7); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_7); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_7); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_7, start_7) >= 0); - ASSERT_TRUE(impl.Compare(change_start_7, limit_7) < 0); - + ASSERT_TRUE(impl.Compare(change_start_7, limit_7) < 0); // ***************** Group 8 Test ***************** ZSetsScoreKey zsets_score_key_start_8("Axlgrep", 1557212501, 3.1415, ""); @@ -131,13 +123,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_8 = zsets_score_key_limit_8.Encode().ToString(); std::string change_start_8 = start_8; impl.FindShortestSeparator(&change_start_8, Slice(limit_8)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_8); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_8); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_8); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_8); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_8); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_8); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_8, start_8) >= 0); - ASSERT_TRUE(impl.Compare(change_start_8, limit_8) < 0); - + ASSERT_TRUE(impl.Compare(change_start_8, limit_8) < 0); // ***************** Group 9 Test ***************** ZSetsScoreKey zsets_score_key_start_9("Axlgrep", 1557212501, 3.1415, "aaaa"); @@ -146,12 +137,12 @@ TEST(ZSetScoreKeyComparator, FindShortestSeparatorTest) { std::string limit_9 = zsets_score_key_limit_9.Encode().ToString(); std::string change_start_9 = start_9; impl.FindShortestSeparator(&change_start_9, Slice(limit_9)); - //impl.ParseAndPrintZSetsScoreKey("origin start : ", start_9); - //impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_9); - //impl.ParseAndPrintZSetsScoreKey("limit : ", limit_9); - //printf("**********************************************************************\n"); + // impl.ParseAndPrintZSetsScoreKey("origin start : ", start_9); + // impl.ParseAndPrintZSetsScoreKey("changed start : ", change_start_9); + // impl.ParseAndPrintZSetsScoreKey("limit : ", limit_9); + // printf("**********************************************************************\n"); ASSERT_TRUE(impl.Compare(change_start_9, start_9) >= 0); - ASSERT_TRUE(impl.Compare(change_start_9, limit_9) < 0); + ASSERT_TRUE(impl.Compare(change_start_9, limit_9) < 0); } int main(int argc, char** argv) { diff --git a/src/storage/tests/hashes_filter_test.cc b/src/storage/tests/hashes_filter_test.cc index 10ca4d3ce7..b3fe587504 100644 --- a/src/storage/tests/hashes_filter_test.cc +++ b/src/storage/tests/hashes_filter_test.cc @@ -97,7 +97,6 @@ // ASSERT_EQ(filter_result, true); // delete hashes_meta_filter; - // /*************** TEST DATA FILTER ***************/ // // No timeout is set, version not outmoded. diff --git a/src/storage/tests/hashes_test.cc b/src/storage/tests/hashes_test.cc index c728264ae2..74dcd6a991 100644 --- a/src/storage/tests/hashes_test.cc +++ b/src/storage/tests/hashes_test.cc @@ -5,10 +5,10 @@ #include #include +#include +#include #include #include -#include -#include #include "storage/storage.h" #include "storage/util.h" @@ -32,18 +32,17 @@ class HashesTest : public ::testing::Test { void TearDown() { std::string path = "./db/hashes"; DeleteFiles(path.c_str()); -} + } - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Storage db; storage::Status s; }; -static bool field_value_match(storage::Storage *const db, - const Slice& key, +static bool field_value_match(storage::Storage* const db, const Slice& key, const std::vector& expect_field_value) { std::vector field_value_out; Status s = db->HGetall(key, &field_value_out); @@ -77,9 +76,7 @@ static bool field_value_match(const std::vector& field_value_out, return true; } -static bool size_match(storage::Storage *const db, - const Slice& key, - int32_t expect_size) { +static bool size_match(storage::Storage* const db, const Slice& key, int32_t expect_size) { int32_t size = 0; Status s = db->HLen(key, &size); if (!s.ok() && !s.IsNotFound()) { @@ -91,8 +88,7 @@ static bool size_match(storage::Storage *const db, return size == expect_size; } -static bool make_expired(storage::Storage *const db, - const Slice& key) { +static bool make_expired(storage::Storage* const db, const Slice& key) { std::map type_status; int ret = db->Expire(key, 1, &type_status); if (!ret || !type_status[storage::DataType::kHashes].ok()) { @@ -114,8 +110,7 @@ TEST_F(HashesTest, HDel) { s = db.HMSet("HDEL_KEY", fvs); ASSERT_TRUE(s.ok()); - std::vector fields {"TEST_FIELD1", "TEST_FIELD2", - "TEST_FIELD3", "TEST_FIElD2", "TEST_NOT_EXIST_FIELD"}; + std::vector fields{"TEST_FIELD1", "TEST_FIELD2", "TEST_FIELD3", "TEST_FIElD2", "TEST_NOT_EXIST_FIELD"}; s = db.HDel("HDEL_KEY", fields, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -261,7 +256,7 @@ TEST_F(HashesTest, HIncrby) { std::string str_value; // ***************** Group 1 Test ***************** - s = db.HSet("GP1_HINCRBY_KEY", "GP1_HINCRBY_FIELD" , "1", &ret); + s = db.HSet("GP1_HINCRBY_KEY", "GP1_HINCRBY_FIELD", "1", &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -269,9 +264,8 @@ TEST_F(HashesTest, HIncrby) { ASSERT_TRUE(s.ok()); ASSERT_EQ(value, 2); - // ***************** Group 2 Test ***************** - s = db.HSet("GP2_HINCRBY_KEY", "GP2_HINCRBY_FIELD" , " 1", &ret); + s = db.HSet("GP2_HINCRBY_KEY", "GP2_HINCRBY_FIELD", " 1", &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -279,9 +273,8 @@ TEST_F(HashesTest, HIncrby) { ASSERT_TRUE(s.IsCorruption()); ASSERT_EQ(value, 0); - // ***************** Group 3 Test ***************** - s = db.HSet("GP3_HINCRBY_KEY", "GP3_HINCRBY_FIELD" , "1 ", &ret); + s = db.HSet("GP3_HINCRBY_KEY", "GP3_HINCRBY_FIELD", "1 ", &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -298,7 +291,6 @@ TEST_F(HashesTest, HIncrby) { ASSERT_TRUE(s.ok()); ASSERT_EQ(atoll(str_value.data()), 1000); - // If the hash field contains a string that can not be // represented as integer s = db.HSet("HINCRBY_KEY", "HINCRBY_STR_FIELD", "HINCRBY_VALEU", &ret); @@ -337,15 +329,13 @@ TEST_F(HashesTest, HIncrby) { // Larger than the maximum number 9223372036854775807 s = db.HSet("HINCRBY_KEY", "HINCRBY_NUM_FIELD", "10", &ret); ASSERT_TRUE(s.ok()); - s = db.HIncrby("HINCRBY_KEY", "HINCRBY_NUM_FIELD", - 9223372036854775807, &value); + s = db.HIncrby("HINCRBY_KEY", "HINCRBY_NUM_FIELD", 9223372036854775807, &value); ASSERT_TRUE(s.IsInvalidArgument()); // Less than the minimum number -9223372036854775808 s = db.HSet("HINCRBY_KEY", "HINCRBY_NUM_FIELD", "-10", &ret); ASSERT_TRUE(s.ok()); - s = db.HIncrby("HINCRBY_KEY", "HINCRBY_NUM_FIELD", - -9223372036854775807, &value); + s = db.HIncrby("HINCRBY_KEY", "HINCRBY_NUM_FIELD", -9223372036854775807, &value); ASSERT_TRUE(s.IsInvalidArgument()); } @@ -355,7 +345,7 @@ TEST_F(HashesTest, HIncrbyfloat) { std::string new_value; // ***************** Group 1 Test ***************** - s = db.HSet("GP1_HINCRBYFLOAT_KEY", "GP1_HINCRBYFLOAT_FIELD" , "1.234", &ret); + s = db.HSet("GP1_HINCRBYFLOAT_KEY", "GP1_HINCRBYFLOAT_FIELD", "1.234", &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -363,9 +353,8 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "2.468"); - // ***************** Group 2 Test ***************** - s = db.HSet("GP2_HINCRBYFLOAT_KEY", "GP2_HINCRBYFLOAT_FIELD" , " 1.234", &ret); + s = db.HSet("GP2_HINCRBYFLOAT_KEY", "GP2_HINCRBYFLOAT_FIELD", " 1.234", &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -373,9 +362,8 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_TRUE(s.IsCorruption()); ASSERT_EQ(new_value, ""); - // ***************** Group 3 Test ***************** - s = db.HSet("GP3_HINCRBYFLOAT_KEY", "GP3_HINCRBYFLOAT_FIELD" , "1.234 ", &ret); + s = db.HSet("GP3_HINCRBYFLOAT_KEY", "GP3_HINCRBYFLOAT_FIELD", "1.234 ", &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -385,16 +373,14 @@ TEST_F(HashesTest, HIncrbyfloat) { // If the specified increment are not parsable as a double precision // floating point number - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", - "HINCRBYFLOAT_FIELD", "HINCRBYFLOAT_BY", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_FIELD", "HINCRBYFLOAT_BY", &new_value); ASSERT_TRUE(s.IsCorruption()); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_FIELD", &new_value); ASSERT_TRUE(s.IsNotFound()); // If key does not exist the value is set to 0 before the // operation is performed - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_FIELD", - "12.3456", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_FIELD", "12.3456", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "12.3456"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_FIELD", &new_value); @@ -406,11 +392,9 @@ TEST_F(HashesTest, HIncrbyfloat) { // If the current field content are not parsable as a double precision // floating point number - s = db.HSet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_STR_FIELD", - "HINCRBYFLOAT_VALUE", &ret); + s = db.HSet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_STR_FIELD", "HINCRBYFLOAT_VALUE", &ret); ASSERT_TRUE(s.ok()); - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_STR_FIELD", - "123.456", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_STR_FIELD", "123.456", &new_value); ASSERT_TRUE(s.IsCorruption()); s = db.HLen("HINCRBYFLOAT_KEY", &ret); ASSERT_TRUE(s.ok()); @@ -418,8 +402,7 @@ TEST_F(HashesTest, HIncrbyfloat) { // If field does not exist the value is set to 0 before the // operation is performed - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NOT_EXIST_FIELD", - "65.4321000", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NOT_EXIST_FIELD", "65.4321000", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "65.4321"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NOT_EXIST_FIELD", &new_value); @@ -433,8 +416,7 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_TRUE(s.ok()); // Positive test - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NUM_FIELD", - "+123.456789", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NUM_FIELD", "+123.456789", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "1123.456789"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NUM_FIELD", &new_value); @@ -442,8 +424,7 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "1123.456789"); // Negative test - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NUM_FIELD", - "-123.456789", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NUM_FIELD", "-123.456789", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "1000"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_NUM_FIELD", &new_value); @@ -456,8 +437,7 @@ TEST_F(HashesTest, HIncrbyfloat) { // ***** Special test ***** // case 1 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD1", - "2.0e2", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD1", "2.0e2", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "200"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD1", &new_value); @@ -465,12 +445,10 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "200"); // case2 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD2", - "5.0e3", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD2", "5.0e3", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "5000"); - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD2", - "2.0e2", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD2", "2.0e2", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "5200"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD2", &new_value); @@ -478,12 +456,10 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "5200"); // case 3 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD3", - "5.0e3", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD3", "5.0e3", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "5000"); - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD3", - "-2.0e2", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD3", "-2.0e2", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "4800"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD3", &new_value); @@ -491,8 +467,7 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "4800"); // case 4 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD4", - ".456789", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD4", ".456789", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "0.456789"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD4", &new_value); @@ -500,8 +475,7 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "0.456789"); // case5 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD5", - "-.456789", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD5", "-.456789", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "-0.456789"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD5", &new_value); @@ -509,8 +483,7 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "-0.456789"); // case6 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD6", - "+.456789", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD6", "+.456789", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "0.456789"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD6", &new_value); @@ -518,12 +491,10 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "0.456789"); // case7 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD7", - "+.456789", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD7", "+.456789", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "0.456789"); - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD7", - "-.456789", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD7", "-.456789", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "0"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD7", &new_value); @@ -531,8 +502,7 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "0"); // case8 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD8", - "-00000.456789000", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD8", "-00000.456789000", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "-0.456789"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD8", &new_value); @@ -540,8 +510,7 @@ TEST_F(HashesTest, HIncrbyfloat) { ASSERT_EQ(new_value, "-0.456789"); // case9 - s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD9", - "+00000.456789000", &new_value); + s = db.HIncrbyfloat("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD9", "+00000.456789000", &new_value); ASSERT_TRUE(s.ok()); ASSERT_EQ(new_value, "0.456789"); s = db.HGet("HINCRBYFLOAT_KEY", "HINCRBYFLOAT_SP_FIELD9", &new_value); @@ -676,8 +645,7 @@ TEST_F(HashesTest, HMGetTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector fields1 {"TEST_FIELD1", - "TEST_FIELD2", "TEST_FIELD3", "TEST_NOT_EXIST_FIELD"}; + std::vector fields1{"TEST_FIELD1", "TEST_FIELD2", "TEST_FIELD3", "TEST_NOT_EXIST_FIELD"}; s = db.HMGet("GP1_HMGET_KEY", fields1, &vss); ASSERT_TRUE(s.ok()); ASSERT_EQ(vss.size(), 4); @@ -691,7 +659,6 @@ TEST_F(HashesTest, HMGetTest) { ASSERT_TRUE(vss[3].status.IsNotFound()); ASSERT_EQ(vss[3].value, ""); - // ***************** Group 2 Test ***************** std::vector fvs2; fvs2.push_back({"TEST_FIELD1", "TEST_VALUE1"}); @@ -704,8 +671,7 @@ TEST_F(HashesTest, HMGetTest) { ASSERT_EQ(ret, 2); vss.clear(); - std::vector fields2 {"TEST_FIELD1", - "TEST_FIELD2", "TEST_NOT_EXIST_FIELD"}; + std::vector fields2{"TEST_FIELD1", "TEST_FIELD2", "TEST_NOT_EXIST_FIELD"}; s = db.HMGet("GP2_HMGET_KEY", fields2, &vss); ASSERT_TRUE(s.ok()); ASSERT_EQ(vss.size(), 3); @@ -717,11 +683,9 @@ TEST_F(HashesTest, HMGetTest) { ASSERT_TRUE(vss[2].status.IsNotFound()); ASSERT_EQ(vss[2].value, ""); - // ***************** Group 3 Test ***************** vss.clear(); - std::vector fields3 {"TEST_FIELD1", - "TEST_FIELD2", "TEST_FIELD3"}; + std::vector fields3{"TEST_FIELD1", "TEST_FIELD2", "TEST_FIELD3"}; s = db.HMGet("GP3_HMGET_KEY", fields3, &vss); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(vss.size(), 3); @@ -733,7 +697,6 @@ TEST_F(HashesTest, HMGetTest) { ASSERT_TRUE(vss[2].status.IsNotFound()); ASSERT_EQ(vss[2].value, ""); - // ***************** Group 4 Test ***************** std::vector fvs4; fvs4.push_back({"TEST_FIELD1", "TEST_VALUE1"}); @@ -746,8 +709,7 @@ TEST_F(HashesTest, HMGetTest) { ASSERT_TRUE(make_expired(&db, "GP4_HMGET_KEY")); vss.clear(); - std::vector fields4 {"TEST_FIELD1", - "TEST_FIELD2", "TEST_FIELD3"}; + std::vector fields4{"TEST_FIELD1", "TEST_FIELD2", "TEST_FIELD3"}; s = db.HMGet("GP4_HMGET_KEY", fields4, &vss); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(vss.size(), 3); @@ -788,11 +750,10 @@ TEST_F(HashesTest, HMSetTest) { ASSERT_EQ(ret, 4); std::vector vss1; - std::vector fields1 {"TEST_FIELD1", - "TEST_FIELD2", "TEST_FIELD3", "TEST_FIELD4"}; + std::vector fields1{"TEST_FIELD1", "TEST_FIELD2", "TEST_FIELD3", "TEST_FIELD4"}; s = db.HMGet("HMSET_KEY", fields1, &vss1); ASSERT_TRUE(s.ok()); - ASSERT_EQ(vss1.size(), 4); + ASSERT_EQ(vss1.size(), 4); ASSERT_EQ(vss1[0].value, "TEST_VALUE1"); ASSERT_EQ(vss1[1].value, "TEST_VALUE2"); @@ -817,11 +778,10 @@ TEST_F(HashesTest, HMSetTest) { ASSERT_EQ(ret, 3); std::vector vss2; - std::vector fields2 {"TEST_FIELD3", - "TEST_FIELD4", "TEST_FIELD5"}; + std::vector fields2{"TEST_FIELD3", "TEST_FIELD4", "TEST_FIELD5"}; s = db.HMGet("HMSET_KEY", fields2, &vss2); ASSERT_TRUE(s.ok()); - ASSERT_EQ(vss2.size(), 3); + ASSERT_EQ(vss2.size(), 3); ASSERT_EQ(vss2[0].value, "TEST_VALUE3"); ASSERT_EQ(vss2[1].value, "TEST_VALUE4"); @@ -867,7 +827,6 @@ TEST_F(HashesTest, HSetTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(value, "HSET_TEST_NEW_VALUE"); - // ***************** Group 2 Test ***************** s = db.HSet("GP2_HSET_KEY", "HSET_TEST_FIELD", "HSET_TEST_VALUE", &ret); ASSERT_TRUE(s.ok()); @@ -891,7 +850,6 @@ TEST_F(HashesTest, HSetTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(value, "HSET_TEST_VALUE"); - // ***************** Group 3 Test ***************** s = db.HSet("GP3_HSET_KEY", "HSET_TEST_FIELD", "HSET_TEST_NEW_VALUE", &ret); ASSERT_TRUE(s.ok()); @@ -929,8 +887,7 @@ TEST_F(HashesTest, HSetnxTest) { ASSERT_EQ(value, "HSETNX_TEST_VALUE"); // If field already exists, this operation has no effect. - s = db.HSetnx("HSETNX_KEY", "HSETNX_TEST_FIELD", - "HSETNX_TEST_NEW_VALUE", &ret); + s = db.HSetnx("HSETNX_KEY", "HSETNX_TEST_FIELD", "HSETNX_TEST_NEW_VALUE", &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); s = db.HGet("HSETNX_KEY", "HSETNX_TEST_FIELD", &value); @@ -1011,12 +968,12 @@ TEST_F(HashesTest, HStrlenTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); - s = db.HStrlen("HSTRLEN_KEY", "HSTRLEN_TEST_FIELD", &len); + s = db.HStrlen("HSTRLEN_KEY", "HSTRLEN_TEST_FIELD", &len); ASSERT_TRUE(s.ok()); ASSERT_EQ(len, 18); // If the key or the field do not exist, 0 is returned - s = db.HStrlen("HSTRLEN_KEY", "HSTRLEN_NOT_EXIST_FIELD", &len); + s = db.HStrlen("HSTRLEN_KEY", "HSTRLEN_NOT_EXIST_FIELD", &len); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(len, 0); } @@ -1029,9 +986,8 @@ TEST_F(HashesTest, HScanTest) { // ***************** Group 1 Test ***************** // {a,v} {b,v} {c,v} {d,v} {e,v} {f,v} {g,v} {h,v} // 0 1 2 3 4 5 6 7 - std::vector gp1_field_value {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}}; + std::vector gp1_field_value{{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, + {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}}; s = db.HMSet("GP1_HSCAN_KEY", gp1_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP1_HSCAN_KEY", 8)); @@ -1058,13 +1014,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {{"g", "v"}, {"h", "v"}})); - // ***************** Group 2 Test ***************** // {a,v} {b,v} {c,v} {d,v} {e,v} {f,v} {g,v} {h,v} // 0 1 2 3 4 5 6 7 - std::vector gp2_field_value {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}}; + std::vector gp2_field_value{{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, + {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}}; s = db.HMSet("GP2_HSCAN_KEY", gp2_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP2_HSCAN_KEY", 8)); @@ -1133,13 +1087,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {{"h", "v"}})); - // ***************** Group 3 Test ***************** // {a,v} {b,v} {c,v} {d,v} {e,v} {f,v} {g,v} {h,v} // 0 1 2 3 4 5 6 7 - std::vector gp3_field_value {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}}; + std::vector gp3_field_value{{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, + {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}}; s = db.HMSet("GP3_HSCAN_KEY", gp3_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP3_HSCAN_KEY", 8)); @@ -1150,8 +1102,7 @@ TEST_F(HashesTest, HScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(field_value_out.size(), 5); ASSERT_EQ(next_cursor, 5); - ASSERT_TRUE(field_value_match(field_value_out, {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}})); + ASSERT_TRUE(field_value_match(field_value_out, {{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, {"e", "v"}})); field_value_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -1161,13 +1112,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {{"f", "v"}, {"g", "v"}, {"h", "v"}})); - // ***************** Group 4 Test ***************** // {a,v} {b,v} {c,v} {d,v} {e,v} {f,v} {g,v} {h,v} // 0 1 2 3 4 5 6 7 - std::vector gp4_field_value {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}}; + std::vector gp4_field_value{{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, + {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}}; s = db.HMSet("GP4_HSCAN_KEY", gp4_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP4_HSCAN_KEY", 8)); @@ -1178,17 +1127,15 @@ TEST_F(HashesTest, HScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(field_value_out.size(), 8); ASSERT_EQ(next_cursor, 0); - ASSERT_TRUE(field_value_match(field_value_out, {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}})); - + ASSERT_TRUE(field_value_match( + field_value_out, + {{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}})); // ***************** Group 5 Test ***************** // {a_1_,v} {a_2_,v} {a_3_,v} {b_1_,v} {b_2_,v} {b_3_,v} {c_1_,v} {c_2_,v} {c_3_,v} // 0 1 2 3 4 5 6 7 8 - std::vector gp5_field_value {{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, - {"b_1_", "v"}, {"b_2_", "v"}, {"b_3_", "v"}, - {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; + std::vector gp5_field_value{{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, {"b_1_", "v"}, {"b_2_", "v"}, + {"b_3_", "v"}, {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; s = db.HMSet("GP5_HSCAN_KEY", gp5_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP5_HSCAN_KEY", 9)); @@ -1217,13 +1164,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {{"c_1_", "v"}})); - // ***************** Group 6 Test ***************** // {a_1_,v} {a_2_,v} {a_3_,v} {b_1_,v} {b_2_,v} {b_3_,v} {c_1_,v} {c_2_,v} {c_3_,v} // 0 1 2 3 4 5 6 7 8 - std::vector gp6_field_value {{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, - {"b_1_", "v"}, {"b_2_", "v"}, {"b_3_", "v"}, - {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; + std::vector gp6_field_value{{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, {"b_1_", "v"}, {"b_2_", "v"}, + {"b_3_", "v"}, {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; s = db.HMSet("GP6_HSCAN_KEY", gp6_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP6_HSCAN_KEY", 9)); @@ -1276,13 +1221,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {{"a_3_", "v"}})); - // ***************** Group 7 Test ***************** // {a_1_,v} {a_2_,v} {a_3_,v} {b_1_,v} {b_2_,v} {b_3_,v} {c_1_,v} {c_2_,v} {c_3_,v} // 0 1 2 3 4 5 6 7 8 - std::vector gp7_field_value {{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, - {"b_1_", "v"}, {"b_2_", "v"}, {"b_3_", "v"}, - {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; + std::vector gp7_field_value{{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, {"b_1_", "v"}, {"b_2_", "v"}, + {"b_3_", "v"}, {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; s = db.HMSet("GP7_HSCAN_KEY", gp7_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP7_HSCAN_KEY", 9)); @@ -1335,13 +1278,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {{"b_3_", "v"}})); - // ***************** Group 8 Test ***************** // {a_1_,v} {a_2_,v} {a_3_,v} {b_1_,v} {b_2_,v} {b_3_,v} {c_1_,v} {c_2_,v} {c_3_,v} // 0 1 2 3 4 5 6 7 8 - std::vector gp8_field_value {{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, - {"b_1_", "v"}, {"b_2_", "v"}, {"b_3_", "v"}, - {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; + std::vector gp8_field_value{{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, {"b_1_", "v"}, {"b_2_", "v"}, + {"b_3_", "v"}, {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; s = db.HMSet("GP8_HSCAN_KEY", gp8_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP8_HSCAN_KEY", 9)); @@ -1394,13 +1335,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {{"c_3_", "v"}})); - // ***************** Group 9 Test ***************** // {a_1_,v} {a_2_,v} {a_3_,v} {b_1_,v} {b_2_,v} {b_3_,v} {c_1_,v} {c_2_,v} {c_3_,v} // 0 1 2 3 4 5 6 7 8 - std::vector gp9_field_value {{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, - {"b_1_", "v"}, {"b_2_", "v"}, {"b_3_", "v"}, - {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; + std::vector gp9_field_value{{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, {"b_1_", "v"}, {"b_2_", "v"}, + {"b_3_", "v"}, {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; s = db.HMSet("GP9_HSCAN_KEY", gp9_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP9_HSCAN_KEY", 9)); @@ -1413,13 +1352,11 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 10 Test ***************** // {a_1_,v} {a_2_,v} {a_3_,v} {b_1_,v} {b_2_,v} {b_3_,v} {c_1_,v} {c_2_,v} {c_3_,v} // 0 1 2 3 4 5 6 7 8 - std::vector gp10_field_value {{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, - {"b_1_", "v"}, {"b_2_", "v"}, {"b_3_", "v"}, - {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; + std::vector gp10_field_value{{"a_1_", "v"}, {"a_2_", "v"}, {"a_3_", "v"}, {"b_1_", "v"}, {"b_2_", "v"}, + {"b_3_", "v"}, {"c_1_", "v"}, {"c_2_", "v"}, {"c_3_", "v"}}; s = db.HMSet("GP10_HSCAN_KEY", gp10_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP10_HSCAN_KEY", 9)); @@ -1433,7 +1370,6 @@ TEST_F(HashesTest, HScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 11 Test ***************** // HScan Not Exist Key field_value_out.clear(); @@ -1454,9 +1390,8 @@ TEST_F(HashesTest, HScanxTest) { // ***************** Group 1 Test ***************** // {a,v} {b,v} {c,v} {d,v} {e,v} {f,v} {g,v} {h,v} // 0 1 2 3 4 5 6 7 - std::vector gp1_field_value {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}}; + std::vector gp1_field_value{{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, + {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}}; s = db.HMSet("GP1_HSCANX_KEY", gp1_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP1_HSCANX_KEY", 8)); @@ -1483,13 +1418,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {{"g", "v"}, {"h", "v"}})); - // ***************** Group 2 Test ***************** // {a,v} {b,v} {c,v} {d,v} {e,v} {f,v} {g,v} {h,v} // 0 1 2 3 4 5 6 7 - std::vector gp2_field_value {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}}; + std::vector gp2_field_value{{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, + {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}}; s = db.HMSet("GP2_HSCANX_KEY", gp2_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP2_HSCANX_KEY", 8)); @@ -1516,13 +1449,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {{"g", "v"}, {"h", "v"}})); - // ***************** Group 3 Test ***************** // {a,v} {b,v} {c,v} {d,v} {e,v} {f,v} {g,v} {h,v} // 0 1 2 3 4 5 6 7 - std::vector gp3_field_value {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}}; + std::vector gp3_field_value{{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, + {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}}; s = db.HMSet("GP3_HSCANX_KEY", gp3_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP3_HSCANX_KEY", 8)); @@ -1532,17 +1463,15 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(field_value_out.size(), 8); ASSERT_EQ(next_field, ""); - ASSERT_TRUE(field_value_match(field_value_out, {{"a", "v"}, {"b", "v"}, {"c", "v"}, - {"d", "v"}, {"e", "v"}, {"f", "v"}, - {"g", "v"}, {"h", "v"}})); - + ASSERT_TRUE(field_value_match( + field_value_out, + {{"a", "v"}, {"b", "v"}, {"c", "v"}, {"d", "v"}, {"e", "v"}, {"f", "v"}, {"g", "v"}, {"h", "v"}})); // ***************** Group 4 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp4_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp4_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP4_HSCANX_KEY", gp4_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP4_HSCANX_KEY", 9)); @@ -1575,13 +1504,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 5 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp5_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp5_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP5_HSCANX_KEY", gp5_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP5_HSCANX_KEY", 9)); @@ -1614,13 +1541,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 6 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp6_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp6_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP6_HSCANX_KEY", gp6_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP6_HSCANX_KEY", 9)); @@ -1653,13 +1578,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 7 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp7_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp7_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP7_HSCANX_KEY", gp7_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP7_HSCANX_KEY", 9)); @@ -1687,13 +1610,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {{"c_f2", "v"}})); - // ***************** Group 8 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp8_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp8_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP8_HSCANX_KEY", gp8_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP8_HSCANX_KEY", 9)); @@ -1721,13 +1642,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 9 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp9_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp9_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP9_HSCANX_KEY", gp9_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP9_HSCANX_KEY", 9)); @@ -1741,13 +1660,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 10 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp10_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp10_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; field_value_out.clear(); s = db.HScanx("GP10_HSCANX_KEY", "", "*", 10, &field_value_out, &next_field); @@ -1756,16 +1673,12 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 11 Test ***************** // {a_f1,v} {a_f2,v} {a_f3,v} {b_f1,v} {b_f2,v} {b_f3,v} {c_f1,v} {c_f2,v}, {c_f3, v} // 0 1 2 3 4 5 6 7 8 - std::vector gp11_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; - std::vector gp11_del_field {"a_f1", "a_f2", "a_f3", - "b_f1", "b_f2", "b_f3", - "c_f1", "c_f2", "c_f3"}; + std::vector gp11_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp11_del_field{"a_f1", "a_f2", "a_f3", "b_f1", "b_f2", "b_f3", "c_f1", "c_f2", "c_f3"}; s = db.HMSet("GP11_HSCANX_KEY", gp9_field_value); ASSERT_TRUE(s.ok()); @@ -1783,14 +1696,11 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {})); - // ***************** Group 12 Test ***************** // {aaa,v} {aab,v} {aac,v} {aad,v} {aaf,v} {aba,v} {abb,v} {abc,v}, {abd, v}, {abf, v} // 0 1 2 3 4 5 6 7 8 9 - std::vector gp12_field_value {{"aaa", "v"}, {"aab", "v"}, {"aac", "v"}, - {"aad", "v"}, {"aaf", "v"}, {"aba", "v"}, - {"abb", "v"}, {"abc", "v"}, {"abd", "v"}, - {"abf", "v"}}; + std::vector gp12_field_value{{"aaa", "v"}, {"aab", "v"}, {"aac", "v"}, {"aad", "v"}, {"aaf", "v"}, + {"aba", "v"}, {"abb", "v"}, {"abc", "v"}, {"abd", "v"}, {"abf", "v"}}; s = db.HMSet("GP12_HSCANX_KEY", gp12_field_value); ASSERT_TRUE(s.ok()); @@ -1824,7 +1734,6 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_EQ(next_field, ""); ASSERT_TRUE(field_value_match(field_value_out, {{"abf", "v"}})); - field_value_out.clear(); s = db.HScanx("GP12_HSCANX_KEY", "aa", "ab*", 5, &field_value_out, &next_field); ASSERT_TRUE(s.ok()); @@ -1837,7 +1746,8 @@ TEST_F(HashesTest, HScanxTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(field_value_out.size(), 5); ASSERT_EQ(next_field, ""); - ASSERT_TRUE(field_value_match(field_value_out, {{"aba", "v"}, {"abb", "v"}, {"abc", "v"}, {"abd", "v"}, {"abf", "v"}})); + ASSERT_TRUE( + field_value_match(field_value_out, {{"aba", "v"}, {"abb", "v"}, {"abc", "v"}, {"abd", "v"}, {"abf", "v"}})); } // PKHScanRange @@ -1853,10 +1763,8 @@ TEST_F(HashesTest, PKHScanRangeTest) { // a c e g i k m o q s // ^ ^ // field_start field_end/next_field - std::vector gp1_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp1_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP1_PKHSCANRANGE_KEY", gp1_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP1_PKHSCANRANGE_KEY", 10)); @@ -1871,16 +1779,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_start field_end/next_field - std::vector gp2_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp2_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP2_PKHSCANRANGE_KEY", gp2_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP2_PKHSCANRANGE_KEY", 10)); @@ -1895,16 +1800,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_start field_end - std::vector gp3_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp3_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP3_PKHSCANRANGE_KEY", gp3_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP3_PKHSCANRANGE_KEY", 10)); @@ -1919,16 +1821,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_start field_end - std::vector gp4_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp4_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP4_PKHSCANRANGE_KEY", gp4_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP4_PKHSCANRANGE_KEY", 10)); @@ -1943,16 +1842,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_start field_end - std::vector gp5_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp5_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP5_PKHSCANRANGE_KEY", gp5_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP5_PKHSCANRANGE_KEY", 10)); @@ -1967,16 +1863,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_start field_end - std::vector gp6_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp6_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP6_PKHSCANRANGE_KEY", gp6_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP6_PKHSCANRANGE_KEY", 10)); @@ -1991,16 +1884,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ // field_start/field_end - std::vector gp7_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp7_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP7_PKHSCANRANGE_KEY", gp7_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP7_PKHSCANRANGE_KEY", 10)); @@ -2015,16 +1905,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_end field_start - std::vector gp8_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp8_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP8_PKHSCANRANGE_KEY", gp8_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP8_PKHSCANRANGE_KEY", 10)); @@ -2036,16 +1923,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ ^ // field_start next_field field_end - std::vector gp9_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp9_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP9_PKHSCANRANGE_KEY", gp9_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP9_PKHSCANRANGE_KEY", 10)); @@ -2060,16 +1944,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "m"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ ^ ^ // field_start deleted next_field field_end - std::vector gp10_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp10_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP10_PKHSCANRANGE_KEY", gp10_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP10_PKHSCANRANGE_KEY", 10)); @@ -2088,15 +1969,13 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "o"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 // a_f1 a_f2 a_f3 b_f1 b_f2 b_f3 c_f1 c_f2 c_f3 // ^ ^ ^ // field_start next_field field_end - std::vector gp11_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp11_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP11_PKHSCANRANGE_KEY", gp11_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP11_PKHSCANRANGE_KEY", 9)); @@ -2114,21 +1993,17 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "b_f1"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 // a c e g i k m o q s // ^ ^ ^ // field_start next_field field_end - std::vector gp12_field_value_a {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp12_field_value_b {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp12_field_value_c {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp12_field_value_a{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp12_field_value_b{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp12_field_value_c{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP12_PKHSCANRANGE_KEY_A", gp12_field_value_a); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP12_PKHSCANRANGE_KEY_A", 9)); @@ -2149,21 +2024,17 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "m"); - // ************************** Group 13 Test ************************** // 0 1 2 3 4 5 6 7 8 // c e g i k m o q s // ^ ^ ^ // field_start next_field field_end - std::vector gp13_field_value_a {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp13_field_value_b {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp13_field_value_c {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp13_field_value_a{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp13_field_value_b{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp13_field_value_c{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP13_PKHSCANRANGE_KEY_A", gp13_field_value_a); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP13_PKHSCANRANGE_KEY_A", 9)); @@ -2184,21 +2055,17 @@ TEST_F(HashesTest, PKHScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "o"); - // ************************** Group 14 Test ************************** // 0 1 2 3 4 5 6 7 8 // c e g i k m o q s u // ^ ^ // field_start next_field/field_end - std::vector gp14_field_value_a {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp14_field_value_b {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp14_field_value_c {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp14_field_value_a{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp14_field_value_b{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp14_field_value_c{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP14_PKHSCANRANGE_KEY_A", gp14_field_value_a); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP14_PKHSCANRANGE_KEY_A", 9)); @@ -2230,10 +2097,8 @@ TEST_F(HashesTest, PKHRScanRangeTest) { // a c e g i k m o q s // ^ ^ // field_end/next_field field_start - std::vector gp1_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp1_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP1_PKHRSCANRANGE_KEY", gp1_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP1_PKHRSCANRANGE_KEY", 10)); @@ -2248,16 +2113,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_end field_start - std::vector gp2_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp2_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP2_PKHRSCANRANGE_KEY", gp2_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP2_PKHRSCANRANGE_KEY", 10)); @@ -2272,16 +2134,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_end/next_field field_start - std::vector gp3_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp3_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP3_PKHRSCANRANGE_KEY", gp3_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP3_PKHRSCANRANGE_KEY", 10)); @@ -2296,16 +2155,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_end field_start - std::vector gp4_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp4_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP4_PKHRSCANRANGE_KEY", gp4_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP4_PKHRSCANRANGE_KEY", 10)); @@ -2320,16 +2176,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_end field_start - std::vector gp5_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp5_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP5_PKHRSCANRANGE_KEY", gp5_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP5_PKHRSCANRANGE_KEY", 10)); @@ -2344,16 +2197,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_end field_start - std::vector gp6_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp6_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP6_PKHRSCANRANGE_KEY", gp6_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP6_PKHRSCANRANGE_KEY", 10)); @@ -2368,16 +2218,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ // field_start/field_end - std::vector gp7_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp7_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP7_PKHRSCANRANGE_KEY", gp7_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP7_PKHRSCANRANGE_KEY", 10)); @@ -2392,16 +2239,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ // field_start field_end - std::vector gp8_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp8_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP8_PKHRSCANRANGE_KEY", gp8_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP8_PKHRSCANRANGE_KEY", 10)); @@ -2413,16 +2257,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ ^ // field_end next_field field_start - std::vector gp9_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp9_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP9_PKHRSCANRANGE_KEY", gp9_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP9_PKHRSCANRANGE_KEY", 10)); @@ -2437,16 +2278,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "g"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // a c e g i k m o q s // ^ ^ ^ ^ // field_end next_field deleted field_start - std::vector gp10_field_value {{"a", "v"}, {"c", "v"}, {"e", "v"}, - {"g", "v"}, {"i", "v"}, {"k", "v"}, - {"m", "v"}, {"o", "v"}, {"q", "v"}, - {"s", "v"}}; + std::vector gp10_field_value{{"a", "v"}, {"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, + {"k", "v"}, {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP10_PKHRSCANRANGE_KEY", gp10_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP10_PKHRSCANRANGE_KEY", 10)); @@ -2465,15 +2303,13 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "e"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 // a_f1 a_f2 a_f3 b_f1 b_f2 b_f3 c_f1 c_f2 c_f3 // ^ ^ ^ // field_end next_field field_start - std::vector gp11_field_value {{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, - {"b_f1", "v"}, {"b_f2", "v"}, {"b_f3", "v"}, - {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; + std::vector gp11_field_value{{"a_f1", "v"}, {"a_f2", "v"}, {"a_f3", "v"}, {"b_f1", "v"}, {"b_f2", "v"}, + {"b_f3", "v"}, {"c_f1", "v"}, {"c_f2", "v"}, {"c_f3", "v"}}; s = db.HMSet("GP11_PKHRSCANRANGE_KEY", gp11_field_value); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP11_PKHRSCANRANGE_KEY", 9)); @@ -2491,21 +2327,17 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "b_f3"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 // a c e g i k m o q s // ^ ^ // field_end/next_field field_start - std::vector gp12_field_value_a {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp12_field_value_b {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp12_field_value_c {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp12_field_value_a{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp12_field_value_b{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp12_field_value_c{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP12_PKHRSCANRANGE_KEY_A", gp12_field_value_a); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP12_PKHRSCANRANGE_KEY_A", 9)); @@ -2523,21 +2355,17 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, ""); - // ************************** Group 13 Test ************************** // 0 1 2 3 4 5 6 7 8 // c e g i k m o q s // ^ ^ ^ // field_end next_field field_start - std::vector gp13_field_value_a {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp13_field_value_b {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp13_field_value_c {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp13_field_value_a{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp13_field_value_b{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp13_field_value_c{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP13_PKHRSCANRANGE_KEY_A", gp13_field_value_a); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP13_PKHRSCANRANGE_KEY_A", 9)); @@ -2558,21 +2386,17 @@ TEST_F(HashesTest, PKHRScanRangeTest) { ASSERT_TRUE(field_value_match(field_value_out, expect_field_value)); ASSERT_EQ(next_field, "e"); - // ************************** Group 14 Test ************************** // 0 1 2 3 4 5 6 7 8 // c e g i k m o q s u // ^ ^ ^ // field_end next_field field_start - std::vector gp14_field_value_a {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp14_field_value_b {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; - std::vector gp14_field_value_c {{"c", "v"}, {"e", "v"}, {"g", "v"}, - {"i", "v"}, {"k", "v"}, {"m", "v"}, - {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp14_field_value_a{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp14_field_value_b{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; + std::vector gp14_field_value_c{{"c", "v"}, {"e", "v"}, {"g", "v"}, {"i", "v"}, {"k", "v"}, + {"m", "v"}, {"o", "v"}, {"q", "v"}, {"s", "v"}}; s = db.HMSet("GP14_PKHRSCANRANGE_KEY_A", gp14_field_value_a); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP14_PKHRSCANRANGE_KEY_A", 9)); @@ -2598,4 +2422,3 @@ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - diff --git a/src/storage/tests/hyperloglog_test.cc b/src/storage/tests/hyperloglog_test.cc index 1b5a46e822..ebc2e52bcf 100644 --- a/src/storage/tests/hyperloglog_test.cc +++ b/src/storage/tests/hyperloglog_test.cc @@ -4,8 +4,8 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include #include "storage/storage.h" #include "storage/util.h" @@ -14,8 +14,8 @@ using namespace storage; class HyperLogLogTest : public ::testing::Test { public: - HyperLogLogTest() { } - virtual ~HyperLogLogTest() { } + HyperLogLogTest() {} + virtual ~HyperLogLogTest() {} void SetUp() { std::string path = "./db/hyperloglog"; @@ -31,8 +31,8 @@ class HyperLogLogTest : public ::testing::Test { DeleteFiles(path.c_str()); } - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Storage db; @@ -47,7 +47,7 @@ TEST_F(HyperLogLogTest, PfaddTest) { s = db.PfAdd("HLL", values, &update); ASSERT_TRUE(s.ok()); ASSERT_TRUE(update); - std::vector keys {"HLL"}; + std::vector keys{"HLL"}; int64_t nums = db.Exists(keys, &type_status); ASSERT_EQ(nums, 1); @@ -105,7 +105,7 @@ TEST_F(HyperLogLogTest, PfCountTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(update); - std::vector keys {"HLL"}; + std::vector keys{"HLL"}; int64_t result; s = db.PfCount(keys, &result); ASSERT_TRUE(s.ok()); @@ -130,22 +130,22 @@ TEST_F(HyperLogLogTest, PfCountTest) { TEST_F(HyperLogLogTest, PfMergeTest) { // PFMERGE results on the cardinality of union of sets bool update; - std::vector values1 {"A", "B", "C"}; + std::vector values1{"A", "B", "C"}; s = db.PfAdd("HLL1", values1, &update); ASSERT_TRUE(s.ok()); ASSERT_TRUE(update); - std::vector values2 {"B", "C", "D"}; + std::vector values2{"B", "C", "D"}; s = db.PfAdd("HLL2", values2, &update); ASSERT_TRUE(s.ok()); ASSERT_TRUE(update); - std::vector values3 {"C", "D", "E"}; + std::vector values3{"C", "D", "E"}; s = db.PfAdd("HLL3", values3, &update); ASSERT_TRUE(s.ok()); ASSERT_TRUE(update); - std::vector keys {"HLL1", "HLL2", "HLL3"}; + std::vector keys{"HLL1", "HLL2", "HLL3"}; s = db.PfMerge(keys); ASSERT_TRUE(s.ok()); int64_t result; @@ -161,9 +161,9 @@ TEST_F(HyperLogLogTest, MultipleKeysTest) { // PFCOUNT multiple-keys merge returns cardinality of union bool update; for (int32_t i = 1; i <= 10000; i++) { - std::vector hll1_value {"FOO" + std::to_string(i)}; - std::vector hll2_value {"BAR" + std::to_string(i)}; - std::vector hll3_value {"ZAP" + std::to_string(i)}; + std::vector hll1_value{"FOO" + std::to_string(i)}; + std::vector hll2_value{"BAR" + std::to_string(i)}; + std::vector hll3_value{"ZAP" + std::to_string(i)}; s = db.PfAdd("HLL1", hll1_value, &update); ASSERT_TRUE(s.ok()); @@ -173,16 +173,15 @@ TEST_F(HyperLogLogTest, MultipleKeysTest) { s = db.PfAdd("HLL3", hll3_value, &update); ASSERT_TRUE(s.ok()); } - std::vector keys {"HLL1", "HLL2", "HLL3"}; + std::vector keys{"HLL1", "HLL2", "HLL3"}; int64_t result; s = db.PfCount(keys, &result); ASSERT_TRUE(s.ok()); int32_t ratio_nums = abs(10000 * 3 - result); - ASSERT_LT(ratio_nums, static_cast(result/100)*5); + ASSERT_LT(ratio_nums, static_cast(result / 100) * 5); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - diff --git a/src/storage/tests/keys_test.cc b/src/storage/tests/keys_test.cc index caed5357b0..3bf455dc2a 100644 --- a/src/storage/tests/keys_test.cc +++ b/src/storage/tests/keys_test.cc @@ -4,8 +4,8 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include #include "storage/storage.h" #include "storage/util.h" @@ -14,8 +14,8 @@ using namespace storage; class KeysTest : public ::testing::Test { public: - KeysTest() { } - virtual ~KeysTest() { } + KeysTest() {} + virtual ~KeysTest() {} void SetUp() { std::string path = "./db/keys"; @@ -31,16 +31,15 @@ class KeysTest : public ::testing::Test { DeleteFiles(path.c_str()); } - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Storage db; storage::Status s; }; -static bool make_expired(storage::Storage *const db, - const Slice& key) { +static bool make_expired(storage::Storage* const db, const Slice& key) { std::map type_status; int ret = db->Expire(key, 1, &type_status); if (!ret || !type_status[storage::DataType::kStrings].ok()) { @@ -50,32 +49,29 @@ static bool make_expired(storage::Storage *const db, return true; } -static bool set_timeout(storage::Storage *const db, - const Slice& key, int32_t ttl) { +static bool set_timeout(storage::Storage* const db, const Slice& key, int32_t ttl) { std::map type_status; int ret = db->Expire(key, ttl, &type_status); if (!ret || !type_status[storage::DataType::kStrings].ok()) { - return false; + return false; } return true; } -static bool key_value_match(const std::vector& key_value_out, - const std::vector& expect_key_value) { +static bool key_value_match(const std::vector& key_value_out, const std::vector& expect_key_value) { if (key_value_out.size() != expect_key_value.size()) { return false; } for (int32_t idx = 0; idx < key_value_out.size(); ++idx) { - if (key_value_out[idx].key != expect_key_value[idx].key - || key_value_out[idx].value != expect_key_value[idx].value) { + if (key_value_out[idx].key != expect_key_value[idx].key || + key_value_out[idx].value != expect_key_value[idx].value) { return false; } } return true; } -static bool key_match(const std::vector& keys_out, - const std::vector& expect_keys) { +static bool key_match(const std::vector& keys_out, const std::vector& expect_keys) { if (keys_out.size() != expect_keys.size()) { return false; } @@ -100,16 +96,10 @@ TEST_F(KeysTest, PKScanRangeTest) { std::map type_status; std::vector kvs_out; std::vector expect_kvs; - std::vector kvs {{"PKSCANRANGE_A", "VALUE"}, - {"PKSCANRANGE_C", "VALUE"}, - {"PKSCANRANGE_E", "VALUE"}, - {"PKSCANRANGE_G", "VALUE"}, - {"PKSCANRANGE_I", "VALUE"}, - {"PKSCANRANGE_K", "VALUE"}, - {"PKSCANRANGE_M", "VALUE"}, - {"PKSCANRANGE_O", "VALUE"}, - {"PKSCANRANGE_Q", "VALUE"}, - {"PKSCANRANGE_S", "VALUE"}}; + std::vector kvs{{"PKSCANRANGE_A", "VALUE"}, {"PKSCANRANGE_C", "VALUE"}, {"PKSCANRANGE_E", "VALUE"}, + {"PKSCANRANGE_G", "VALUE"}, {"PKSCANRANGE_I", "VALUE"}, {"PKSCANRANGE_K", "VALUE"}, + {"PKSCANRANGE_M", "VALUE"}, {"PKSCANRANGE_O", "VALUE"}, {"PKSCANRANGE_Q", "VALUE"}, + {"PKSCANRANGE_S", "VALUE"}}; for (const auto& kv : kvs) { keys_del.push_back(kv.key); } @@ -118,7 +108,6 @@ TEST_F(KeysTest, PKScanRangeTest) { s = db.MSet(kvs); ASSERT_TRUE(s.ok()); - // ************************** Group 1 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -134,7 +123,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -150,7 +138,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -166,7 +153,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -182,7 +168,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -198,7 +183,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -214,7 +198,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -230,7 +213,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -243,7 +225,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -259,7 +240,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, "PKSCANRANGE_M"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -278,7 +258,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, "PKSCANRANGE_O"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -294,14 +273,11 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, "PKSCANRANGE_I"); - - //=============================== Sets =============================== for (const auto& kv : kvs) { s = db.SAdd(kv.key, {"MEMBER"}, &ret); } - // ************************** Group 1 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -317,7 +293,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -333,7 +308,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -349,7 +323,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -365,7 +338,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -381,7 +353,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -397,7 +368,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -413,7 +383,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -426,7 +395,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -442,7 +410,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_M"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -461,7 +428,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_O"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -479,7 +445,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_I"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -498,13 +463,11 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_K"); - //=============================== Hashes =============================== for (const auto& kv : kvs) { s = db.HMSet(kv.key, {{"FIELD", "VALUE"}}); } - // ************************** Group 1 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -520,7 +483,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -536,7 +498,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -552,7 +513,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -568,7 +528,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -584,7 +543,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -600,7 +558,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -616,7 +573,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -629,7 +585,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -645,7 +600,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_M"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -664,7 +618,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_O"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -680,7 +633,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_I"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -697,13 +649,11 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_K"); - //=============================== ZSets =============================== for (const auto& kv : kvs) { s = db.ZAdd(kv.key, {{1, "MEMBER"}}, &ret); } - // ************************** Group 1 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -719,7 +669,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -735,7 +684,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -751,7 +699,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -767,7 +714,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -783,7 +729,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -799,7 +744,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -815,7 +759,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -828,7 +771,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -844,7 +786,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_M"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -863,7 +804,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_O"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -879,7 +819,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_I"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -898,13 +837,11 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_K"); - //=============================== Lists =============================== for (const auto& kv : kvs) { s = db.LPush(kv.key, {"NODE"}, &ret_u64); } - // ************************** Group 1 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -920,7 +857,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -936,7 +872,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -952,7 +887,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -968,7 +902,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -984,7 +917,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1000,7 +932,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1016,7 +947,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1029,7 +959,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1045,7 +974,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_M"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1064,7 +992,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_O"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1080,7 +1007,6 @@ TEST_F(KeysTest, PKScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKSCANRANGE_I"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1118,16 +1044,11 @@ TEST_F(KeysTest, PKRScanRangeTest) { std::map type_status; std::vector kvs_out; std::vector expect_kvs; - std::vector kvs {{"PKRSCANRANGE_A", "VALUE"}, - {"PKRSCANRANGE_C", "VALUE"}, - {"PKRSCANRANGE_E", "VALUE"}, - {"PKRSCANRANGE_G", "VALUE"}, - {"PKRSCANRANGE_I", "VALUE"}, - {"PKRSCANRANGE_K", "VALUE"}, - {"PKRSCANRANGE_M", "VALUE"}, - {"PKRSCANRANGE_O", "VALUE"}, - {"PKRSCANRANGE_Q", "VALUE"}, - {"PKRSCANRANGE_S", "VALUE"}}; + std::vector kvs{{"PKRSCANRANGE_A", "VALUE"}, {"PKRSCANRANGE_C", "VALUE"}, + {"PKRSCANRANGE_E", "VALUE"}, {"PKRSCANRANGE_G", "VALUE"}, + {"PKRSCANRANGE_I", "VALUE"}, {"PKRSCANRANGE_K", "VALUE"}, + {"PKRSCANRANGE_M", "VALUE"}, {"PKRSCANRANGE_O", "VALUE"}, + {"PKRSCANRANGE_Q", "VALUE"}, {"PKRSCANRANGE_S", "VALUE"}}; for (const auto& kv : kvs) { keys_del.push_back(kv.key); } @@ -1136,12 +1057,11 @@ TEST_F(KeysTest, PKRScanRangeTest) { s = db.MSet(kvs); ASSERT_TRUE(s.ok()); - // ************************** Group 1 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start kvs_out.clear(); expect_kvs.clear(); s = db.PKRScanRange(DataType::kStrings, "", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1152,7 +1072,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1168,12 +1087,11 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start kvs_out.clear(); expect_kvs.clear(); s = db.PKRScanRange(DataType::kStrings, "PKRSCANRANGE_R", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1184,7 +1102,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1200,7 +1117,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1216,7 +1132,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1232,7 +1147,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1248,7 +1162,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1261,7 +1174,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1277,7 +1189,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1296,7 +1207,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1312,7 +1222,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_value_match(kvs_out, expect_kvs)); ASSERT_EQ(next_key, "PKRSCANRANGE_K"); - //=============================== Sets =============================== for (const auto& kv : kvs) { s = db.SAdd(kv.key, {"MEMBER"}, &ret); @@ -1322,7 +1231,7 @@ TEST_F(KeysTest, PKRScanRangeTest) { // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kSets, "", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1333,7 +1242,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1349,12 +1257,11 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kSets, "PKRSCANRANGE_R", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1365,7 +1272,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1381,7 +1287,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1397,7 +1302,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1413,7 +1317,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1429,7 +1332,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1442,7 +1344,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1458,7 +1359,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1477,7 +1377,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1497,7 +1396,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1513,7 +1411,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_K"); - // ************************** Group 13 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1531,7 +1428,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - //=============================== Hashes =============================== for (const auto& kv : kvs) { s = db.HMSet(kv.key, {{"FIELD", "VALUE"}}); @@ -1541,7 +1437,7 @@ TEST_F(KeysTest, PKRScanRangeTest) { // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kHashes, "", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1552,7 +1448,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1568,12 +1463,11 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kHashes, "PKRSCANRANGE_R", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1584,7 +1478,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1600,7 +1493,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1616,7 +1508,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1632,7 +1523,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1648,7 +1538,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1661,7 +1550,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1677,7 +1565,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1696,7 +1583,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1716,7 +1602,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1732,7 +1617,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_K"); - // ************************** Group 13 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1750,7 +1634,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - //=============================== ZSets =============================== for (const auto& kv : kvs) { s = db.ZAdd(kv.key, {{1, "MEMBER"}}, &ret); @@ -1760,7 +1643,7 @@ TEST_F(KeysTest, PKRScanRangeTest) { // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kZSets, "", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1771,7 +1654,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1787,12 +1669,11 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kZSets, "PKRSCANRANGE_R", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1803,7 +1684,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1819,7 +1699,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1835,7 +1714,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1851,7 +1729,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1867,7 +1744,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1880,7 +1756,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1896,7 +1771,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1915,7 +1789,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1935,7 +1808,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1951,7 +1823,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_K"); - // ************************** Group 13 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -1969,7 +1840,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - //=============================== Lists =============================== for (const auto& kv : kvs) { s = db.LPush(kv.key, {"NODE"}, &ret_u64); @@ -1979,7 +1849,7 @@ TEST_F(KeysTest, PKRScanRangeTest) { // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kLists, "", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -1990,7 +1860,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 2 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2006,12 +1875,11 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 3 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S // ^ ^ - //key_end/next_key key_start + // key_end/next_key key_start keys_out.clear(); expect_keys.clear(); s = db.PKRScanRange(DataType::kLists, "PKRSCANRANGE_R", "", "*", 10, &keys_out, &kvs_out, &next_key); @@ -2022,7 +1890,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 4 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2038,7 +1905,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 5 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2054,7 +1920,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 6 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2070,7 +1935,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 7 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2086,7 +1950,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 8 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2099,7 +1962,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, ""); - // ************************** Group 9 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2115,7 +1977,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_G"); - // ************************** Group 10 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2134,7 +1995,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 11 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2143,7 +2003,7 @@ TEST_F(KeysTest, PKRScanRangeTest) { keys_out.clear(); expect_keys.clear(); std::string element; - s = db.LPop("PKRSCANRANGE_I",&element); + s = db.LPop("PKRSCANRANGE_I", &element); ASSERT_TRUE(s.ok()); s = db.PKRScanRange(DataType::kLists, "PKRSCANRANGE_Q", "PKRSCANRANGE_C", "*", 4, &keys_out, &kvs_out, &next_key); ASSERT_TRUE(s.ok()); @@ -2155,7 +2015,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_E"); - // ************************** Group 12 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2171,7 +2030,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { ASSERT_TRUE(key_match(keys_out, expect_keys)); ASSERT_EQ(next_key, "PKRSCANRANGE_K"); - // ************************** Group 13 Test ************************** // 0 1 2 3 4 5 6 7 8 9 // A C E G I K M O Q S @@ -2218,7 +2076,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kStrings, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 2 Test ***************** // db.Set("GP2_PKPATTERNMATCHDEL_STRING_KEY1", "VALUE"); // db.Set("GP2_PKPATTERNMATCHDEL_STRING_KEY2", "VALUE"); @@ -2236,7 +2093,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kStrings, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 3 Test ***************** // db.Set("GP3_PKPATTERNMATCHDEL_STRING_KEY1_0xxx0", "VALUE"); // db.Set("GP3_PKPATTERNMATCHDEL_STRING_KEY2_0ooo0", "VALUE"); @@ -2256,7 +2112,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 4 Test ***************** // db.Set("GP4_PKPATTERNMATCHDEL_STRING_KEY1", "VALUE"); // db.Set("GP4_PKPATTERNMATCHDEL_STRING_KEY2_0ooo0", "VALUE"); @@ -2274,7 +2129,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kStrings, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 5 Test ***************** // size_t gp5_total_kv = 23333; // for (size_t idx = 0; idx < gp5_total_kv; ++idx) { @@ -2287,7 +2141,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kStrings, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // //=============================== Set =============================== // // ***************** Group 1 Test ***************** @@ -2304,7 +2157,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 2 Test ***************** // db.SAdd("GP2_PKPATTERNMATCHDEL_SET_KEY1", {"M1"}, &ret); // db.SAdd("GP2_PKPATTERNMATCHDEL_SET_KEY2", {"M1"}, &ret); @@ -2322,7 +2174,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 3 Test ***************** // db.SAdd("GP3_PKPATTERNMATCHDEL_SET_KEY1_0xxx0", {"M1"}, &ret); // db.SAdd("GP3_PKPATTERNMATCHDEL_SET_KEY2_0ooo0", {"M1"}, &ret); @@ -2342,7 +2193,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 4 Test ***************** // db.SAdd("GP4_PKPATTERNMATCHDEL_SET_KEY1", {"M1"}, &ret); // db.SAdd("GP4_PKPATTERNMATCHDEL_SET_KEY2", {"M1"}, &ret); @@ -2360,7 +2210,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 5 Test ***************** // db.SAdd("GP5_PKPATTERNMATCHDEL_SET_KEY1_0ooo0", {"M1"}, &ret); // db.SAdd("GP5_PKPATTERNMATCHDEL_SET_KEY2_0xxx0", {"M1"}, &ret); @@ -2385,7 +2234,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 6 Test ***************** // size_t gp6_total_set = 23333; // for (size_t idx = 0; idx < gp6_total_set; ++idx) { @@ -2398,7 +2246,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // //=============================== Hashes =============================== // // ***************** Group 1 Test ***************** @@ -2415,7 +2262,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kHashes, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 2 Test ***************** // db.HSet("GP2_PKPATTERNMATCHDEL_HASH_KEY1", "FIELD", "VALUE", &ret); // db.HSet("GP2_PKPATTERNMATCHDEL_HASH_KEY2", "FIELD", "VALUE", &ret); @@ -2433,7 +2279,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kHashes, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 3 Test ***************** // db.HSet("GP3_PKPATTERNMATCHDEL_HASH_KEY1_0xxx0", "FIELD", "VALUE", &ret); // db.HSet("GP3_PKPATTERNMATCHDEL_HASH_KEY2_0ooo0", "FIELD", "VALUE", &ret); @@ -2453,7 +2298,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 4 Test ***************** // db.HSet("GP4_PKPATTERNMATCHDEL_HASH_KEY1", "FIELD", "VALUE", &ret); // db.HSet("GP4_PKPATTERNMATCHDEL_HASH_KEY2", "FIELD", "VALUE", &ret); @@ -2471,7 +2315,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kHashes, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 5 Test ***************** // db.HSet("GP5_PKPATTERNMATCHDEL_HASH_KEY1_0ooo0", "FIELD", "VALUE", &ret); // db.HSet("GP5_PKPATTERNMATCHDEL_HASH_KEY2_0xxx0", "FIELD", "VALUE", &ret); @@ -2496,7 +2339,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 6 Test ***************** // size_t gp6_total_hash = 23333; // for (size_t idx = 0; idx < gp6_total_hash; ++idx) { @@ -2509,7 +2351,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kHashes, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // //=============================== ZSets =============================== // // ***************** Group 1 Test ***************** @@ -2526,7 +2367,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kZSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 2 Test ***************** // db.ZAdd("GP2_PKPATTERNMATCHDEL_ZSET_KEY1", {{1, "M"}}, &ret); // db.ZAdd("GP2_PKPATTERNMATCHDEL_ZSET_KEY2", {{1, "M"}}, &ret); @@ -2544,7 +2384,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kZSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 3 Test ***************** // db.ZAdd("GP3_PKPATTERNMATCHDEL_ZSET_KEY1_0xxx0", {{1, "M"}}, &ret); // db.ZAdd("GP3_PKPATTERNMATCHDEL_ZSET_KEY2_0ooo0", {{1, "M"}}, &ret); @@ -2564,7 +2403,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 4 Test ***************** // db.ZAdd("GP4_PKPATTERNMATCHDEL_ZSET_KEY1", {{1, "M"}}, &ret); // db.ZAdd("GP4_PKPATTERNMATCHDEL_ZSET_KEY2", {{1, "M"}}, &ret); @@ -2582,7 +2420,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kZSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 5 Test ***************** // db.ZAdd("GP5_PKPATTERNMATCHDEL_ZSET_KEY1_0ooo0", {{1, "M"}}, &ret); // db.ZAdd("GP5_PKPATTERNMATCHDEL_ZSET_KEY2_0xxx0", {{1, "M"}}, &ret); @@ -2607,7 +2444,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 6 Test ***************** // size_t gp6_total_zset = 23333; // for (size_t idx = 0; idx < gp6_total_zset; ++idx) { @@ -2620,8 +2456,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kZSets, "*", &keys); // ASSERT_EQ(keys.size(), 0); - - // //=============================== List =============================== // // ***************** Group 1 Test ***************** @@ -2638,7 +2472,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kLists, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 2 Test ***************** // db.LPush("GP2_PKPATTERNMATCHDEL_LIST_KEY1", {"VALUE"}, &ret64); // db.LPush("GP2_PKPATTERNMATCHDEL_LIST_KEY2", {"VALUE"}, &ret64); @@ -2656,7 +2489,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kLists, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 3 Test ***************** // db.LPush("GP3_PKPATTERNMATCHDEL_LIST_KEY1_0xxx0", {"VALUE"}, &ret64); // db.LPush("GP3_PKPATTERNMATCHDEL_LIST_KEY2_0ooo0", {"VALUE"}, &ret64); @@ -2676,7 +2508,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 4 Test ***************** // db.LPush("GP4_PKPATTERNMATCHDEL_LIST_KEY1", {"VALUE"}, &ret64); // db.LPush("GP4_PKPATTERNMATCHDEL_LIST_KEY2", {"VALUE"}, &ret64); @@ -2694,7 +2525,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // db.Keys(DataType::kLists, "*", &keys); // ASSERT_EQ(keys.size(), 0); - // // ***************** Group 5 Test ***************** // db.LPush("GP5_PKPATTERNMATCHDEL_LIST_KEY1_0ooo0", {"VALUE"}, &ret64); // db.LPush("GP5_PKPATTERNMATCHDEL_LIST_KEY2_0xxx0", {"VALUE"}, &ret64); @@ -2719,7 +2549,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // type_status.clear(); // db.Del(keys, &type_status); - // // ***************** Group 6 Test ***************** // size_t gp6_total_list = 23333; // for (size_t idx = 0; idx < gp6_total_list; ++idx) { @@ -2740,7 +2569,6 @@ TEST_F(KeysTest, PKRScanRangeTest) { // Note: This test needs to execute at first because all of the data is // predetermined. TEST_F(KeysTest, ScanCaseAllTest) { - int64_t cursor; int64_t next_cursor; int64_t del_num; @@ -2752,32 +2580,35 @@ TEST_F(KeysTest, ScanCaseAllTest) { std::map type_status; // ***************** Group 1 Test ***************** - //String + // String s = db.Set("GP1_SCAN_CASE_ALL_STRING_KEY1", "GP1_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP1_SCAN_CASE_ALL_STRING_KEY2", "GP1_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP1_SCAN_CASE_ALL_STRING_KEY3", "GP1_SCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP1_SCAN_CASE_ALL_HASH_KEY1", "GP1_SCAN_CASE_ALL_HASH_FIELD1", "GP1_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP1_SCAN_CASE_ALL_HASH_KEY2", "GP1_SCAN_CASE_ALL_HASH_FIELD2", "GP1_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP1_SCAN_CASE_ALL_HASH_KEY3", "GP1_SCAN_CASE_ALL_HASH_FIELD3", "GP1_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP1_SCAN_CASE_ALL_HASH_KEY1", "GP1_SCAN_CASE_ALL_HASH_FIELD1", "GP1_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP1_SCAN_CASE_ALL_HASH_KEY2", "GP1_SCAN_CASE_ALL_HASH_FIELD2", "GP1_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP1_SCAN_CASE_ALL_HASH_KEY3", "GP1_SCAN_CASE_ALL_HASH_FIELD3", "GP1_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); - //Set + // Set s = db.SAdd("GP1_SCAN_CASE_ALL_SET_KEY1", {"GP1_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP1_SCAN_CASE_ALL_SET_KEY2", {"GP1_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP1_SCAN_CASE_ALL_SET_KEY3", {"GP1_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP1_SCAN_CASE_ALL_LIST_KEY1", {"GP1_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP1_SCAN_CASE_ALL_LIST_KEY2", {"GP1_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP1_SCAN_CASE_ALL_LIST_KEY3", {"GP1_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP1_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP1_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP1_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP1_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP1_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP1_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); - //Scan + // Scan delete_keys.clear(); keys.clear(); cursor = db.Scan(DataType::kAll, 0, "*", 3, &keys); @@ -2829,34 +2660,36 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 2 Test ***************** - //String + // String s = db.Set("GP2_SCAN_CASE_ALL_STRING_KEY1", "GP2_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP2_SCAN_CASE_ALL_STRING_KEY2", "GP2_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP2_SCAN_CASE_ALL_STRING_KEY3", "GP2_SCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP2_SCAN_CASE_ALL_HASH_KEY1", "GP2_SCAN_CASE_ALL_HASH_FIELD1", "GP2_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP2_SCAN_CASE_ALL_HASH_KEY2", "GP2_SCAN_CASE_ALL_HASH_FIELD2", "GP2_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP2_SCAN_CASE_ALL_HASH_KEY3", "GP2_SCAN_CASE_ALL_HASH_FIELD3", "GP2_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP2_SCAN_CASE_ALL_HASH_KEY1", "GP2_SCAN_CASE_ALL_HASH_FIELD1", "GP2_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP2_SCAN_CASE_ALL_HASH_KEY2", "GP2_SCAN_CASE_ALL_HASH_FIELD2", "GP2_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP2_SCAN_CASE_ALL_HASH_KEY3", "GP2_SCAN_CASE_ALL_HASH_FIELD3", "GP2_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); - //Set + // Set s = db.SAdd("GP2_SCAN_CASE_ALL_SET_KEY1", {"GP2_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP2_SCAN_CASE_ALL_SET_KEY2", {"GP2_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP2_SCAN_CASE_ALL_SET_KEY3", {"GP2_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP2_SCAN_CASE_ALL_LIST_KEY1", {"GP2_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP2_SCAN_CASE_ALL_LIST_KEY2", {"GP2_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP2_SCAN_CASE_ALL_LIST_KEY3", {"GP2_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP2_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP2_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP2_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP2_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP2_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP2_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); - //Scan + // Scan delete_keys.clear(); keys.clear(); cursor = db.Scan(DataType::kAll, 0, "*", 2, &keys); @@ -2926,34 +2759,36 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 3 Test ***************** - //String + // String s = db.Set("GP3_SCAN_CASE_ALL_STRING_KEY1", "GP3_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP3_SCAN_CASE_ALL_STRING_KEY2", "GP3_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP3_SCAN_CASE_ALL_STRING_KEY3", "GP3_SCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP3_SCAN_CASE_ALL_HASH_KEY1", "GP3_SCAN_CASE_ALL_HASH_FIELD1", "GP3_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP3_SCAN_CASE_ALL_HASH_KEY2", "GP3_SCAN_CASE_ALL_HASH_FIELD2", "GP3_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP3_SCAN_CASE_ALL_HASH_KEY3", "GP3_SCAN_CASE_ALL_HASH_FIELD3", "GP3_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP3_SCAN_CASE_ALL_HASH_KEY1", "GP3_SCAN_CASE_ALL_HASH_FIELD1", "GP3_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP3_SCAN_CASE_ALL_HASH_KEY2", "GP3_SCAN_CASE_ALL_HASH_FIELD2", "GP3_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP3_SCAN_CASE_ALL_HASH_KEY3", "GP3_SCAN_CASE_ALL_HASH_FIELD3", "GP3_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); - //Set + // Set s = db.SAdd("GP3_SCAN_CASE_ALL_SET_KEY1", {"GP3_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP3_SCAN_CASE_ALL_SET_KEY2", {"GP3_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP3_SCAN_CASE_ALL_SET_KEY3", {"GP3_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP3_SCAN_CASE_ALL_LIST_KEY1", {"GP3_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP3_SCAN_CASE_ALL_LIST_KEY2", {"GP3_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP3_SCAN_CASE_ALL_LIST_KEY3", {"GP3_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP3_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP3_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP3_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP3_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP3_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP3_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); - //Scan + // Scan delete_keys.clear(); keys.clear(); cursor = db.Scan(DataType::kAll, 0, "*", 5, &keys); @@ -2993,29 +2828,31 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 4 Test ***************** - //String + // String s = db.Set("GP4_SCAN_CASE_ALL_STRING_KEY1", "GP4_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP4_SCAN_CASE_ALL_STRING_KEY2", "GP4_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP4_SCAN_CASE_ALL_STRING_KEY3", "GP4_SCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP4_SCAN_CASE_ALL_HASH_KEY1", "GP4_SCAN_CASE_ALL_HASH_FIELD1", "GP4_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP4_SCAN_CASE_ALL_HASH_KEY2", "GP4_SCAN_CASE_ALL_HASH_FIELD2", "GP4_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP4_SCAN_CASE_ALL_HASH_KEY3", "GP4_SCAN_CASE_ALL_HASH_FIELD3", "GP4_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP4_SCAN_CASE_ALL_HASH_KEY1", "GP4_SCAN_CASE_ALL_HASH_FIELD1", "GP4_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP4_SCAN_CASE_ALL_HASH_KEY2", "GP4_SCAN_CASE_ALL_HASH_FIELD2", "GP4_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP4_SCAN_CASE_ALL_HASH_KEY3", "GP4_SCAN_CASE_ALL_HASH_FIELD3", "GP4_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); - //Set + // Set s = db.SAdd("GP4_SCAN_CASE_ALL_SET_KEY1", {"GP4_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP4_SCAN_CASE_ALL_SET_KEY2", {"GP4_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP4_SCAN_CASE_ALL_SET_KEY3", {"GP4_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP4_SCAN_CASE_ALL_LIST_KEY1", {"GP4_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP4_SCAN_CASE_ALL_LIST_KEY2", {"GP4_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP4_SCAN_CASE_ALL_LIST_KEY3", {"GP4_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP4_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP4_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP4_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP4_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP4_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP4_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3047,10 +2884,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 5 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP5_SCAN_CASE_ALL_STRING_KEY1", "GP5_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP5_SCAN_CASE_ALL_STRING_KEY2", "GP5_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP5_SCAN_CASE_ALL_STRING_KEY3", "GP5_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3058,15 +2894,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP5_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP5_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP5_SCAN_CASE_ALL_HASH_KEY1", "GP5_SCAN_CASE_ALL_HASH_FIELD1", "GP5_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP5_SCAN_CASE_ALL_HASH_KEY2", "GP5_SCAN_CASE_ALL_HASH_FIELD2", "GP5_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP5_SCAN_CASE_ALL_HASH_KEY3", "GP5_SCAN_CASE_ALL_HASH_FIELD3", "GP5_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP5_SCAN_CASE_ALL_HASH_KEY1", "GP5_SCAN_CASE_ALL_HASH_FIELD1", "GP5_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP5_SCAN_CASE_ALL_HASH_KEY2", "GP5_SCAN_CASE_ALL_HASH_FIELD2", "GP5_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP5_SCAN_CASE_ALL_HASH_KEY3", "GP5_SCAN_CASE_ALL_HASH_FIELD3", "GP5_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP5_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP5_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP5_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP5_SCAN_CASE_ALL_SET_KEY1", {"GP5_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP5_SCAN_CASE_ALL_SET_KEY2", {"GP5_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP5_SCAN_CASE_ALL_SET_KEY3", {"GP5_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3074,7 +2913,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP5_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP5_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP5_SCAN_CASE_ALL_LIST_KEY1", {"GP5_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP5_SCAN_CASE_ALL_LIST_KEY2", {"GP5_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP5_SCAN_CASE_ALL_LIST_KEY3", {"GP5_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3082,7 +2921,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP5_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP5_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP5_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP5_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP5_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP5_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP5_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP5_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3108,10 +2947,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 6 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP6_SCAN_CASE_ALL_STRING_KEY1", "GP6_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP6_SCAN_CASE_ALL_STRING_KEY2", "GP6_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP6_SCAN_CASE_ALL_STRING_KEY3", "GP6_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3119,15 +2957,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP6_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP6_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP6_SCAN_CASE_ALL_HASH_KEY1", "GP6_SCAN_CASE_ALL_HASH_FIELD1", "GP6_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP6_SCAN_CASE_ALL_HASH_KEY2", "GP6_SCAN_CASE_ALL_HASH_FIELD2", "GP6_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP6_SCAN_CASE_ALL_HASH_KEY3", "GP6_SCAN_CASE_ALL_HASH_FIELD3", "GP6_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP6_SCAN_CASE_ALL_HASH_KEY1", "GP6_SCAN_CASE_ALL_HASH_FIELD1", "GP6_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP6_SCAN_CASE_ALL_HASH_KEY2", "GP6_SCAN_CASE_ALL_HASH_FIELD2", "GP6_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP6_SCAN_CASE_ALL_HASH_KEY3", "GP6_SCAN_CASE_ALL_HASH_FIELD3", "GP6_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP6_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP6_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP6_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP6_SCAN_CASE_ALL_SET_KEY1", {"GP6_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP6_SCAN_CASE_ALL_SET_KEY2", {"GP6_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP6_SCAN_CASE_ALL_SET_KEY3", {"GP6_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3135,7 +2976,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP6_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP6_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP6_SCAN_CASE_ALL_LIST_KEY1", {"GP6_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP6_SCAN_CASE_ALL_LIST_KEY2", {"GP6_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP6_SCAN_CASE_ALL_LIST_KEY3", {"GP6_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3143,7 +2984,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP6_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP6_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP6_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP6_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP6_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP6_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP6_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP6_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3171,10 +3012,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 7 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP7_SCAN_CASE_ALL_STRING_KEY1", "GP7_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP7_SCAN_CASE_ALL_STRING_KEY2", "GP7_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP7_SCAN_CASE_ALL_STRING_KEY3", "GP7_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3182,15 +3022,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP7_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP7_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP7_SCAN_CASE_ALL_HASH_KEY1", "GP7_SCAN_CASE_ALL_HASH_FIELD1", "GP7_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP7_SCAN_CASE_ALL_HASH_KEY2", "GP7_SCAN_CASE_ALL_HASH_FIELD2", "GP7_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP7_SCAN_CASE_ALL_HASH_KEY3", "GP7_SCAN_CASE_ALL_HASH_FIELD3", "GP7_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP7_SCAN_CASE_ALL_HASH_KEY1", "GP7_SCAN_CASE_ALL_HASH_FIELD1", "GP7_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP7_SCAN_CASE_ALL_HASH_KEY2", "GP7_SCAN_CASE_ALL_HASH_FIELD2", "GP7_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP7_SCAN_CASE_ALL_HASH_KEY3", "GP7_SCAN_CASE_ALL_HASH_FIELD3", "GP7_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP7_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP7_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP7_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP7_SCAN_CASE_ALL_SET_KEY1", {"GP7_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP7_SCAN_CASE_ALL_SET_KEY2", {"GP7_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP7_SCAN_CASE_ALL_SET_KEY3", {"GP7_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3198,7 +3041,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP7_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP7_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP7_SCAN_CASE_ALL_LIST_KEY1", {"GP7_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP7_SCAN_CASE_ALL_LIST_KEY2", {"GP7_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP7_SCAN_CASE_ALL_LIST_KEY3", {"GP7_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3206,7 +3049,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP7_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP7_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP7_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP7_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP7_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP7_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP7_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP7_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3234,10 +3077,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 8 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP8_SCAN_CASE_ALL_STRING_KEY1", "GP8_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP8_SCAN_CASE_ALL_STRING_KEY2", "GP8_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP8_SCAN_CASE_ALL_STRING_KEY3", "GP8_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3245,15 +3087,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP8_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP8_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP8_SCAN_CASE_ALL_HASH_KEY1", "GP8_SCAN_CASE_ALL_HASH_FIELD1", "GP8_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP8_SCAN_CASE_ALL_HASH_KEY2", "GP8_SCAN_CASE_ALL_HASH_FIELD2", "GP8_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP8_SCAN_CASE_ALL_HASH_KEY3", "GP8_SCAN_CASE_ALL_HASH_FIELD3", "GP8_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP8_SCAN_CASE_ALL_HASH_KEY1", "GP8_SCAN_CASE_ALL_HASH_FIELD1", "GP8_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP8_SCAN_CASE_ALL_HASH_KEY2", "GP8_SCAN_CASE_ALL_HASH_FIELD2", "GP8_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP8_SCAN_CASE_ALL_HASH_KEY3", "GP8_SCAN_CASE_ALL_HASH_FIELD3", "GP8_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP8_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP8_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP8_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP8_SCAN_CASE_ALL_SET_KEY1", {"GP8_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP8_SCAN_CASE_ALL_SET_KEY2", {"GP8_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP8_SCAN_CASE_ALL_SET_KEY3", {"GP8_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3261,7 +3106,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP8_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP8_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP8_SCAN_CASE_ALL_LIST_KEY1", {"GP8_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP8_SCAN_CASE_ALL_LIST_KEY2", {"GP8_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP8_SCAN_CASE_ALL_LIST_KEY3", {"GP8_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3269,7 +3114,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP8_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP8_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP8_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP8_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP8_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP8_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP8_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP8_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3297,10 +3142,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 9 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP9_SCAN_CASE_ALL_STRING_KEY1", "GP9_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP9_SCAN_CASE_ALL_STRING_KEY2", "GP9_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP9_SCAN_CASE_ALL_STRING_KEY3", "GP9_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3308,15 +3152,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP9_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP9_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP9_SCAN_CASE_ALL_HASH_KEY1", "GP9_SCAN_CASE_ALL_HASH_FIELD1", "GP9_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP9_SCAN_CASE_ALL_HASH_KEY2", "GP9_SCAN_CASE_ALL_HASH_FIELD2", "GP9_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP9_SCAN_CASE_ALL_HASH_KEY3", "GP9_SCAN_CASE_ALL_HASH_FIELD3", "GP9_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP9_SCAN_CASE_ALL_HASH_KEY1", "GP9_SCAN_CASE_ALL_HASH_FIELD1", "GP9_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP9_SCAN_CASE_ALL_HASH_KEY2", "GP9_SCAN_CASE_ALL_HASH_FIELD2", "GP9_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP9_SCAN_CASE_ALL_HASH_KEY3", "GP9_SCAN_CASE_ALL_HASH_FIELD3", "GP9_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP9_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP9_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP9_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP9_SCAN_CASE_ALL_SET_KEY1", {"GP9_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP9_SCAN_CASE_ALL_SET_KEY2", {"GP9_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP9_SCAN_CASE_ALL_SET_KEY3", {"GP9_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3324,7 +3171,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP9_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP9_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP9_SCAN_CASE_ALL_LIST_KEY1", {"GP9_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP9_SCAN_CASE_ALL_LIST_KEY2", {"GP9_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP9_SCAN_CASE_ALL_LIST_KEY3", {"GP9_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3332,7 +3179,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP9_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP9_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP9_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP9_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP9_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP9_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP9_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP9_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3370,10 +3217,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 10 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP10_SCAN_CASE_ALL_STRING_KEY1", "GP10_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP10_SCAN_CASE_ALL_STRING_KEY2", "GP10_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP10_SCAN_CASE_ALL_STRING_KEY3", "GP10_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3381,15 +3227,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP10_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP10_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP10_SCAN_CASE_ALL_HASH_KEY1", "GP10_SCAN_CASE_ALL_HASH_FIELD1", "GP10_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP10_SCAN_CASE_ALL_HASH_KEY2", "GP10_SCAN_CASE_ALL_HASH_FIELD2", "GP10_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP10_SCAN_CASE_ALL_HASH_KEY3", "GP10_SCAN_CASE_ALL_HASH_FIELD3", "GP10_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP10_SCAN_CASE_ALL_HASH_KEY1", "GP10_SCAN_CASE_ALL_HASH_FIELD1", "GP10_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP10_SCAN_CASE_ALL_HASH_KEY2", "GP10_SCAN_CASE_ALL_HASH_FIELD2", "GP10_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP10_SCAN_CASE_ALL_HASH_KEY3", "GP10_SCAN_CASE_ALL_HASH_FIELD3", "GP10_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP10_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP10_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP10_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP10_SCAN_CASE_ALL_SET_KEY1", {"GP10_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP10_SCAN_CASE_ALL_SET_KEY2", {"GP10_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP10_SCAN_CASE_ALL_SET_KEY3", {"GP10_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3397,7 +3246,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP10_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP10_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP10_SCAN_CASE_ALL_LIST_KEY1", {"GP10_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP10_SCAN_CASE_ALL_LIST_KEY2", {"GP10_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP10_SCAN_CASE_ALL_LIST_KEY3", {"GP10_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3405,7 +3254,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP10_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP10_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP10_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP10_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP10_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP10_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP10_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP10_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3431,10 +3280,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 11 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP11_SCAN_CASE_ALL_STRING_KEY1", "GP11_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP11_SCAN_CASE_ALL_STRING_KEY2", "GP11_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP11_SCAN_CASE_ALL_STRING_KEY3", "GP11_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3442,15 +3290,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP11_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP11_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP11_SCAN_CASE_ALL_HASH_KEY1", "GP11_SCAN_CASE_ALL_HASH_FIELD1", "GP11_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP11_SCAN_CASE_ALL_HASH_KEY2", "GP11_SCAN_CASE_ALL_HASH_FIELD2", "GP11_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP11_SCAN_CASE_ALL_HASH_KEY3", "GP11_SCAN_CASE_ALL_HASH_FIELD3", "GP11_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP11_SCAN_CASE_ALL_HASH_KEY1", "GP11_SCAN_CASE_ALL_HASH_FIELD1", "GP11_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP11_SCAN_CASE_ALL_HASH_KEY2", "GP11_SCAN_CASE_ALL_HASH_FIELD2", "GP11_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP11_SCAN_CASE_ALL_HASH_KEY3", "GP11_SCAN_CASE_ALL_HASH_FIELD3", "GP11_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP11_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP11_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP11_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP11_SCAN_CASE_ALL_SET_KEY1", {"GP11_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP11_SCAN_CASE_ALL_SET_KEY2", {"GP11_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP11_SCAN_CASE_ALL_SET_KEY3", {"GP11_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3458,7 +3309,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP11_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP11_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP11_SCAN_CASE_ALL_LIST_KEY1", {"GP11_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP11_SCAN_CASE_ALL_LIST_KEY2", {"GP11_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP11_SCAN_CASE_ALL_LIST_KEY3", {"GP11_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3466,7 +3317,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP11_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP11_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP11_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP11_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP11_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP11_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP11_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP11_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3492,10 +3343,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 12 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP12_SCAN_CASE_ALL_STRING_KEY1", "GP12_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP12_SCAN_CASE_ALL_STRING_KEY2", "GP12_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP12_SCAN_CASE_ALL_STRING_KEY3", "GP12_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3503,15 +3353,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP12_SCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP12_SCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP12_SCAN_CASE_ALL_HASH_KEY1", "GP12_SCAN_CASE_ALL_HASH_FIELD1", "GP12_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP12_SCAN_CASE_ALL_HASH_KEY2", "GP12_SCAN_CASE_ALL_HASH_FIELD2", "GP12_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP12_SCAN_CASE_ALL_HASH_KEY3", "GP12_SCAN_CASE_ALL_HASH_FIELD3", "GP12_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP12_SCAN_CASE_ALL_HASH_KEY1", "GP12_SCAN_CASE_ALL_HASH_FIELD1", "GP12_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP12_SCAN_CASE_ALL_HASH_KEY2", "GP12_SCAN_CASE_ALL_HASH_FIELD2", "GP12_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP12_SCAN_CASE_ALL_HASH_KEY3", "GP12_SCAN_CASE_ALL_HASH_FIELD3", "GP12_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP12_SCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP12_SCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP12_SCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP12_SCAN_CASE_ALL_SET_KEY1", {"GP12_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP12_SCAN_CASE_ALL_SET_KEY2", {"GP12_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP12_SCAN_CASE_ALL_SET_KEY3", {"GP12_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3519,7 +3372,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP12_SCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP12_SCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP12_SCAN_CASE_ALL_LIST_KEY1", {"GP12_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP12_SCAN_CASE_ALL_LIST_KEY2", {"GP12_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP12_SCAN_CASE_ALL_LIST_KEY3", {"GP12_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3527,7 +3380,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP12_SCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP12_SCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP12_SCAN_CASE_ALL_ZSET_KEY1", {{1, "GP12_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP12_SCAN_CASE_ALL_ZSET_KEY2", {{1, "GP12_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP12_SCAN_CASE_ALL_ZSET_KEY3", {{1, "GP12_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3553,10 +3406,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 13 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP13_KEY1_SCAN_CASE_ALL_STRING", "GP13_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP13_KEY2_SCAN_CASE_ALL_STRING", "GP13_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP13_KEY3_SCAN_CASE_ALL_STRING", "GP13_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3564,15 +3416,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP13_KEY2_SCAN_CASE_ALL_STRING"); delete_keys.push_back("GP13_KEY3_SCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP13_KEY1_SCAN_CASE_ALL_HASH", "GP13_SCAN_CASE_ALL_HASH_FIELD1", "GP13_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP13_KEY2_SCAN_CASE_ALL_HASH", "GP13_SCAN_CASE_ALL_HASH_FIELD2", "GP13_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP13_KEY3_SCAN_CASE_ALL_HASH", "GP13_SCAN_CASE_ALL_HASH_FIELD3", "GP13_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP13_KEY1_SCAN_CASE_ALL_HASH", "GP13_SCAN_CASE_ALL_HASH_FIELD1", "GP13_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP13_KEY2_SCAN_CASE_ALL_HASH", "GP13_SCAN_CASE_ALL_HASH_FIELD2", "GP13_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP13_KEY3_SCAN_CASE_ALL_HASH", "GP13_SCAN_CASE_ALL_HASH_FIELD3", "GP13_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP13_KEY1_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP13_KEY2_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP13_KEY3_SCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP13_KEY1_SCAN_CASE_ALL_SET", {"GP13_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP13_KEY2_SCAN_CASE_ALL_SET", {"GP13_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP13_KEY3_SCAN_CASE_ALL_SET", {"GP13_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3580,7 +3435,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP13_KEY2_SCAN_CASE_ALL_SET"); delete_keys.push_back("GP13_KEY3_SCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP13_KEY1_SCAN_CASE_ALL_LIST", {"GP13_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP13_KEY2_SCAN_CASE_ALL_LIST", {"GP13_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP13_KEY3_SCAN_CASE_ALL_LIST", {"GP13_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3588,7 +3443,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP13_KEY2_SCAN_CASE_ALL_LIST"); delete_keys.push_back("GP13_KEY3_SCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP13_KEY1_SCAN_CASE_ALL_ZSET", {{1, "GP13_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP13_KEY2_SCAN_CASE_ALL_ZSET", {{1, "GP13_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP13_KEY3_SCAN_CASE_ALL_ZSET", {{1, "GP13_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3616,10 +3471,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 14 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP14_KEY1_SCAN_CASE_ALL_STRING", "GP14_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP14_KEY2_SCAN_CASE_ALL_STRING", "GP14_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP14_KEY3_SCAN_CASE_ALL_STRING", "GP14_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3627,15 +3481,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP14_KEY2_SCAN_CASE_ALL_STRING"); delete_keys.push_back("GP14_KEY3_SCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP14_KEY1_SCAN_CASE_ALL_HASH", "GP14_SCAN_CASE_ALL_HASH_FIELD1", "GP14_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP14_KEY2_SCAN_CASE_ALL_HASH", "GP14_SCAN_CASE_ALL_HASH_FIELD2", "GP14_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP14_KEY3_SCAN_CASE_ALL_HASH", "GP14_SCAN_CASE_ALL_HASH_FIELD3", "GP14_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP14_KEY1_SCAN_CASE_ALL_HASH", "GP14_SCAN_CASE_ALL_HASH_FIELD1", "GP14_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP14_KEY2_SCAN_CASE_ALL_HASH", "GP14_SCAN_CASE_ALL_HASH_FIELD2", "GP14_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP14_KEY3_SCAN_CASE_ALL_HASH", "GP14_SCAN_CASE_ALL_HASH_FIELD3", "GP14_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP14_KEY1_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP14_KEY2_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP14_KEY3_SCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP14_KEY1_SCAN_CASE_ALL_SET", {"GP14_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP14_KEY2_SCAN_CASE_ALL_SET", {"GP14_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP14_KEY3_SCAN_CASE_ALL_SET", {"GP14_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3643,7 +3500,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP14_KEY2_SCAN_CASE_ALL_SET"); delete_keys.push_back("GP14_KEY3_SCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP14_KEY1_SCAN_CASE_ALL_LIST", {"GP14_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP14_KEY2_SCAN_CASE_ALL_LIST", {"GP14_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP14_KEY3_SCAN_CASE_ALL_LIST", {"GP14_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3651,7 +3508,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP14_KEY2_SCAN_CASE_ALL_LIST"); delete_keys.push_back("GP14_KEY3_SCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP14_KEY1_SCAN_CASE_ALL_ZSET", {{1, "GP14_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP14_KEY2_SCAN_CASE_ALL_ZSET", {{1, "GP14_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP14_KEY3_SCAN_CASE_ALL_ZSET", {{1, "GP14_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3679,10 +3536,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 15 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP15_KEY1_SCAN_CASE_ALL_STRING", "GP15_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP15_KEY2_SCAN_CASE_ALL_STRING", "GP15_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP15_KEY3_SCAN_CASE_ALL_STRING", "GP15_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3690,15 +3546,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP15_KEY2_SCAN_CASE_ALL_STRING"); delete_keys.push_back("GP15_KEY3_SCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP15_KEY1_SCAN_CASE_ALL_HASH", "GP15_SCAN_CASE_ALL_HASH_FIELD1", "GP15_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP15_KEY2_SCAN_CASE_ALL_HASH", "GP15_SCAN_CASE_ALL_HASH_FIELD2", "GP15_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP15_KEY3_SCAN_CASE_ALL_HASH", "GP15_SCAN_CASE_ALL_HASH_FIELD3", "GP15_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP15_KEY1_SCAN_CASE_ALL_HASH", "GP15_SCAN_CASE_ALL_HASH_FIELD1", "GP15_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP15_KEY2_SCAN_CASE_ALL_HASH", "GP15_SCAN_CASE_ALL_HASH_FIELD2", "GP15_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP15_KEY3_SCAN_CASE_ALL_HASH", "GP15_SCAN_CASE_ALL_HASH_FIELD3", "GP15_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP15_KEY1_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP15_KEY2_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP15_KEY3_SCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP15_KEY1_SCAN_CASE_ALL_SET", {"GP15_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP15_KEY2_SCAN_CASE_ALL_SET", {"GP15_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP15_KEY3_SCAN_CASE_ALL_SET", {"GP15_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3706,7 +3565,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP15_KEY2_SCAN_CASE_ALL_SET"); delete_keys.push_back("GP15_KEY3_SCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP15_KEY1_SCAN_CASE_ALL_LIST", {"GP15_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP15_KEY2_SCAN_CASE_ALL_LIST", {"GP15_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP15_KEY3_SCAN_CASE_ALL_LIST", {"GP15_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3714,7 +3573,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP15_KEY2_SCAN_CASE_ALL_LIST"); delete_keys.push_back("GP15_KEY3_SCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP15_KEY1_SCAN_CASE_ALL_ZSET", {{1, "GP15_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP15_KEY2_SCAN_CASE_ALL_ZSET", {{1, "GP15_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP15_KEY3_SCAN_CASE_ALL_ZSET", {{1, "GP15_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3742,10 +3601,9 @@ TEST_F(KeysTest, ScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 16 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP16_KEY1_SCAN_CASE_ALL_STRING", "GP16_SCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP16_KEY2_SCAN_CASE_ALL_STRING", "GP16_SCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP16_KEY3_SCAN_CASE_ALL_STRING", "GP16_SCAN_CASE_ALL_STRING_VALUE3"); @@ -3753,15 +3611,18 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP16_KEY2_SCAN_CASE_ALL_STRING"); delete_keys.push_back("GP16_KEY3_SCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP16_KEY1_SCAN_CASE_ALL_HASH", "GP16_SCAN_CASE_ALL_HASH_FIELD1", "GP16_SCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP16_KEY2_SCAN_CASE_ALL_HASH", "GP16_SCAN_CASE_ALL_HASH_FIELD2", "GP16_SCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP16_KEY3_SCAN_CASE_ALL_HASH", "GP16_SCAN_CASE_ALL_HASH_FIELD3", "GP16_SCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP16_KEY1_SCAN_CASE_ALL_HASH", "GP16_SCAN_CASE_ALL_HASH_FIELD1", "GP16_SCAN_CASE_ALL_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP16_KEY2_SCAN_CASE_ALL_HASH", "GP16_SCAN_CASE_ALL_HASH_FIELD2", "GP16_SCAN_CASE_ALL_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP16_KEY3_SCAN_CASE_ALL_HASH", "GP16_SCAN_CASE_ALL_HASH_FIELD3", "GP16_SCAN_CASE_ALL_HASH_VALUE3", + &int32_ret); delete_keys.push_back("GP16_KEY1_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP16_KEY2_SCAN_CASE_ALL_HASH"); delete_keys.push_back("GP16_KEY3_SCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP16_KEY1_SCAN_CASE_ALL_SET", {"GP16_SCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP16_KEY2_SCAN_CASE_ALL_SET", {"GP16_SCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP16_KEY3_SCAN_CASE_ALL_SET", {"GP16_SCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -3769,7 +3630,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP16_KEY2_SCAN_CASE_ALL_SET"); delete_keys.push_back("GP16_KEY3_SCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP16_KEY1_SCAN_CASE_ALL_LIST", {"GP16_SCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP16_KEY2_SCAN_CASE_ALL_LIST", {"GP16_SCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP16_KEY3_SCAN_CASE_ALL_LIST", {"GP16_SCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -3777,7 +3638,7 @@ TEST_F(KeysTest, ScanCaseAllTest) { delete_keys.push_back("GP16_KEY2_SCAN_CASE_ALL_LIST"); delete_keys.push_back("GP16_KEY3_SCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP16_KEY1_SCAN_CASE_ALL_ZSET", {{1, "GP16_SCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP16_KEY2_SCAN_CASE_ALL_ZSET", {{1, "GP16_SCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP16_KEY3_SCAN_CASE_ALL_ZSET", {{1, "GP16_SCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -3810,7 +3671,6 @@ TEST_F(KeysTest, ScanCaseAllTest) { // Note: This test needs to execute at first because all of the data is // predetermined. TEST_F(KeysTest, ScanCaseSingleTest) { - int64_t cursor; int64_t next_cursor; int64_t del_num; @@ -3823,7 +3683,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { // ***************** Group 1 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP1_KEY1_SCAN_CASE_SINGLE_STRING", "GP1_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP1_KEY2_SCAN_CASE_SINGLE_STRING", "GP1_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP1_KEY3_SCAN_CASE_SINGLE_STRING", "GP1_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -3837,13 +3697,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP1_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP1_KEY1_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD1", "GP1_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP1_KEY2_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD2", "GP1_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP1_KEY3_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD3", "GP1_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP1_KEY4_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD4", "GP1_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP1_KEY5_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD5", "GP1_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP1_KEY6_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD6", "GP1_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP1_KEY1_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD1", "GP1_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP1_KEY2_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD2", "GP1_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP1_KEY3_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD3", "GP1_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP1_KEY4_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD4", "GP1_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP1_KEY5_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD5", "GP1_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP1_KEY6_SCAN_CASE_SINGLE_HASH", "GP1_SCAN_CASE_SINGLE_HASH_FIELD6", "GP1_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP1_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP1_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP1_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -3851,7 +3717,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP1_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP1_KEY1_SCAN_CASE_SINGLE_SET", {"GP1_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP1_KEY2_SCAN_CASE_SINGLE_SET", {"GP1_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP1_KEY3_SCAN_CASE_SINGLE_SET", {"GP1_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -3865,7 +3731,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP1_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP1_KEY1_SCAN_CASE_SINGLE_LIST", {"GP1_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP1_KEY2_SCAN_CASE_SINGLE_LIST", {"GP1_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP1_KEY3_SCAN_CASE_SINGLE_LIST", {"GP1_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -3879,7 +3745,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP1_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP1_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP1_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP1_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP1_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP1_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP1_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -3920,10 +3786,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 2 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP2_KEY1_SCAN_CASE_SINGLE_STRING", "GP2_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP2_KEY2_SCAN_CASE_SINGLE_STRING", "GP2_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP2_KEY3_SCAN_CASE_SINGLE_STRING", "GP2_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -3937,13 +3802,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP2_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP2_KEY1_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD1", "GP2_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP2_KEY2_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD2", "GP2_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP2_KEY3_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD3", "GP2_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP2_KEY4_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD4", "GP2_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP2_KEY5_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD5", "GP2_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP2_KEY6_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD6", "GP2_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP2_KEY1_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD1", "GP2_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP2_KEY2_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD2", "GP2_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP2_KEY3_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD3", "GP2_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP2_KEY4_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD4", "GP2_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP2_KEY5_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD5", "GP2_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP2_KEY6_SCAN_CASE_SINGLE_HASH", "GP2_SCAN_CASE_SINGLE_HASH_FIELD6", "GP2_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP2_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP2_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP2_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -3951,7 +3822,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP2_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP2_KEY1_SCAN_CASE_SINGLE_SET", {"GP2_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP2_KEY2_SCAN_CASE_SINGLE_SET", {"GP2_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP2_KEY3_SCAN_CASE_SINGLE_SET", {"GP2_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -3965,7 +3836,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP2_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP2_KEY1_SCAN_CASE_SINGLE_LIST", {"GP2_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP2_KEY2_SCAN_CASE_SINGLE_LIST", {"GP2_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP2_KEY3_SCAN_CASE_SINGLE_LIST", {"GP2_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -3979,7 +3850,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP2_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP2_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP2_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP2_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP2_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP2_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP2_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4015,10 +3886,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 3 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP3_KEY1_SCAN_CASE_SINGLE_STRING", "GP3_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP3_KEY2_SCAN_CASE_SINGLE_STRING", "GP3_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP3_KEY3_SCAN_CASE_SINGLE_STRING", "GP3_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4032,13 +3902,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP3_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP3_KEY1_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD1", "GP3_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP3_KEY2_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD2", "GP3_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP3_KEY3_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD3", "GP3_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP3_KEY4_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD4", "GP3_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP3_KEY5_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD5", "GP3_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP3_KEY6_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD6", "GP3_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP3_KEY1_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD1", "GP3_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP3_KEY2_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD2", "GP3_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP3_KEY3_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD3", "GP3_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP3_KEY4_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD4", "GP3_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP3_KEY5_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD5", "GP3_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP3_KEY6_SCAN_CASE_SINGLE_HASH", "GP3_SCAN_CASE_SINGLE_HASH_FIELD6", "GP3_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP3_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP3_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP3_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4046,7 +3922,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP3_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP3_KEY1_SCAN_CASE_SINGLE_SET", {"GP3_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP3_KEY2_SCAN_CASE_SINGLE_SET", {"GP3_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP3_KEY3_SCAN_CASE_SINGLE_SET", {"GP3_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4060,7 +3936,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP3_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP3_KEY1_SCAN_CASE_SINGLE_LIST", {"GP3_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP3_KEY2_SCAN_CASE_SINGLE_LIST", {"GP3_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP3_KEY3_SCAN_CASE_SINGLE_LIST", {"GP3_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4074,7 +3950,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP3_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP3_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP3_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP3_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP3_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP3_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP3_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4105,10 +3981,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 4 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP4_KEY1_SCAN_CASE_SINGLE_STRING", "GP4_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP4_KEY2_SCAN_CASE_SINGLE_STRING", "GP4_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP4_KEY3_SCAN_CASE_SINGLE_STRING", "GP4_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4122,13 +3997,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP4_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP4_KEY1_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD1", "GP4_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP4_KEY2_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD2", "GP4_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP4_KEY3_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD3", "GP4_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP4_KEY4_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD4", "GP4_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP4_KEY5_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD5", "GP4_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP4_KEY6_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD6", "GP4_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP4_KEY1_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD1", "GP4_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP4_KEY2_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD2", "GP4_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP4_KEY3_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD3", "GP4_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP4_KEY4_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD4", "GP4_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP4_KEY5_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD5", "GP4_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP4_KEY6_SCAN_CASE_SINGLE_HASH", "GP4_SCAN_CASE_SINGLE_HASH_FIELD6", "GP4_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP4_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP4_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP4_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4136,7 +4017,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP4_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP4_KEY1_SCAN_CASE_SINGLE_SET", {"GP4_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP4_KEY2_SCAN_CASE_SINGLE_SET", {"GP4_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP4_KEY3_SCAN_CASE_SINGLE_SET", {"GP4_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4150,7 +4031,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP4_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP4_KEY1_SCAN_CASE_SINGLE_LIST", {"GP4_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP4_KEY2_SCAN_CASE_SINGLE_LIST", {"GP4_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP4_KEY3_SCAN_CASE_SINGLE_LIST", {"GP4_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4164,7 +4045,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP4_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP4_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP4_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP4_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP4_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP4_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP4_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4195,10 +4076,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 5 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP5_KEY1_SCAN_CASE_SINGLE_STRING", "GP5_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP5_KEY2_SCAN_CASE_SINGLE_STRING", "GP5_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP5_KEY3_SCAN_CASE_SINGLE_STRING", "GP5_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4212,13 +4092,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP5_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP5_KEY1_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD1", "GP5_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP5_KEY2_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD2", "GP5_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP5_KEY3_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD3", "GP5_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP5_KEY4_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD4", "GP5_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP5_KEY5_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD5", "GP5_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP5_KEY6_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD6", "GP5_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP5_KEY1_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD1", "GP5_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP5_KEY2_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD2", "GP5_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP5_KEY3_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD3", "GP5_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP5_KEY4_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD4", "GP5_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP5_KEY5_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD5", "GP5_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP5_KEY6_SCAN_CASE_SINGLE_HASH", "GP5_SCAN_CASE_SINGLE_HASH_FIELD6", "GP5_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP5_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP5_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP5_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4226,7 +4112,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP5_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP5_KEY1_SCAN_CASE_SINGLE_SET", {"GP5_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP5_KEY2_SCAN_CASE_SINGLE_SET", {"GP5_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP5_KEY3_SCAN_CASE_SINGLE_SET", {"GP5_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4240,7 +4126,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP5_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP5_KEY1_SCAN_CASE_SINGLE_LIST", {"GP5_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP5_KEY2_SCAN_CASE_SINGLE_LIST", {"GP5_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP5_KEY3_SCAN_CASE_SINGLE_LIST", {"GP5_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4254,7 +4140,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP5_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP5_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP5_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP5_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP5_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP5_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP5_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4295,10 +4181,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 6 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP6_KEY1_SCAN_CASE_SINGLE_STRING", "GP6_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP6_KEY2_SCAN_CASE_SINGLE_STRING", "GP6_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP6_KEY3_SCAN_CASE_SINGLE_STRING", "GP6_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4312,13 +4197,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP6_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP6_KEY1_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD1", "GP6_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP6_KEY2_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD2", "GP6_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP6_KEY3_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD3", "GP6_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP6_KEY4_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD4", "GP6_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP6_KEY5_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD5", "GP6_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP6_KEY6_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD6", "GP6_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP6_KEY1_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD1", "GP6_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP6_KEY2_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD2", "GP6_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP6_KEY3_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD3", "GP6_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP6_KEY4_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD4", "GP6_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP6_KEY5_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD5", "GP6_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP6_KEY6_SCAN_CASE_SINGLE_HASH", "GP6_SCAN_CASE_SINGLE_HASH_FIELD6", "GP6_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP6_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP6_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP6_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4326,7 +4217,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP6_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP6_KEY1_SCAN_CASE_SINGLE_SET", {"GP6_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP6_KEY2_SCAN_CASE_SINGLE_SET", {"GP6_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP6_KEY3_SCAN_CASE_SINGLE_SET", {"GP6_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4340,7 +4231,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP6_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP6_KEY1_SCAN_CASE_SINGLE_LIST", {"GP6_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP6_KEY2_SCAN_CASE_SINGLE_LIST", {"GP6_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP6_KEY3_SCAN_CASE_SINGLE_LIST", {"GP6_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4354,7 +4245,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP6_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP6_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP6_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP6_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP6_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP6_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP6_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4390,10 +4281,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 7 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP7_KEY1_SCAN_CASE_SINGLE_STRING", "GP7_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP7_KEY2_SCAN_CASE_SINGLE_STRING", "GP7_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP7_KEY3_SCAN_CASE_SINGLE_STRING", "GP7_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4407,13 +4297,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP7_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP7_KEY1_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD1", "GP7_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP7_KEY2_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD2", "GP7_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP7_KEY3_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD3", "GP7_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP7_KEY4_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD4", "GP7_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP7_KEY5_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD5", "GP7_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP7_KEY6_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD6", "GP7_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP7_KEY1_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD1", "GP7_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP7_KEY2_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD2", "GP7_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP7_KEY3_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD3", "GP7_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP7_KEY4_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD4", "GP7_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP7_KEY5_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD5", "GP7_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP7_KEY6_SCAN_CASE_SINGLE_HASH", "GP7_SCAN_CASE_SINGLE_HASH_FIELD6", "GP7_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP7_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP7_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP7_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4421,7 +4317,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP7_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP7_KEY1_SCAN_CASE_SINGLE_SET", {"GP7_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP7_KEY2_SCAN_CASE_SINGLE_SET", {"GP7_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP7_KEY3_SCAN_CASE_SINGLE_SET", {"GP7_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4435,7 +4331,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP7_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP7_KEY1_SCAN_CASE_SINGLE_LIST", {"GP7_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP7_KEY2_SCAN_CASE_SINGLE_LIST", {"GP7_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP7_KEY3_SCAN_CASE_SINGLE_LIST", {"GP7_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4449,7 +4345,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP7_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP7_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP7_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP7_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP7_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP7_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP7_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4480,10 +4376,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 8 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP8_KEY1_SCAN_CASE_SINGLE_STRING", "GP8_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP8_KEY2_SCAN_CASE_SINGLE_STRING", "GP8_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP8_KEY3_SCAN_CASE_SINGLE_STRING", "GP8_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4497,13 +4392,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP8_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP8_KEY1_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD1", "GP8_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP8_KEY2_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD2", "GP8_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP8_KEY3_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD3", "GP8_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP8_KEY4_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD4", "GP8_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP8_KEY5_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD5", "GP8_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP8_KEY6_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD6", "GP8_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP8_KEY1_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD1", "GP8_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP8_KEY2_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD2", "GP8_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP8_KEY3_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD3", "GP8_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP8_KEY4_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD4", "GP8_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP8_KEY5_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD5", "GP8_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP8_KEY6_SCAN_CASE_SINGLE_HASH", "GP8_SCAN_CASE_SINGLE_HASH_FIELD6", "GP8_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP8_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP8_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP8_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4511,7 +4412,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP8_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP8_KEY1_SCAN_CASE_SINGLE_SET", {"GP8_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP8_KEY2_SCAN_CASE_SINGLE_SET", {"GP8_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP8_KEY3_SCAN_CASE_SINGLE_SET", {"GP8_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4525,7 +4426,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP8_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP8_KEY1_SCAN_CASE_SINGLE_LIST", {"GP8_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP8_KEY2_SCAN_CASE_SINGLE_LIST", {"GP8_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP8_KEY3_SCAN_CASE_SINGLE_LIST", {"GP8_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4539,7 +4440,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP8_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP8_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP8_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP8_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP8_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP8_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP8_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4570,10 +4471,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 9 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP9_KEY1_SCAN_CASE_SINGLE_STRING", "GP9_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP9_KEY2_SCAN_CASE_SINGLE_STRING", "GP9_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP9_KEY3_SCAN_CASE_SINGLE_STRING", "GP9_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4587,13 +4487,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP9_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP9_KEY1_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD1", "GP9_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP9_KEY2_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD2", "GP9_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP9_KEY3_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD3", "GP9_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP9_KEY4_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD4", "GP9_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP9_KEY5_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD5", "GP9_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP9_KEY6_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD6", "GP9_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP9_KEY1_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD1", "GP9_SCAN_CASE_SINGLE_HASH_VALUE1", + &int32_ret); + s = db.HSet("GP9_KEY2_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD2", "GP9_SCAN_CASE_SINGLE_HASH_VALUE2", + &int32_ret); + s = db.HSet("GP9_KEY3_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD3", "GP9_SCAN_CASE_SINGLE_HASH_VALUE3", + &int32_ret); + s = db.HSet("GP9_KEY4_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD4", "GP9_SCAN_CASE_SINGLE_HASH_VALUE4", + &int32_ret); + s = db.HSet("GP9_KEY5_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD5", "GP9_SCAN_CASE_SINGLE_HASH_VALUE5", + &int32_ret); + s = db.HSet("GP9_KEY6_SCAN_CASE_SINGLE_HASH", "GP9_SCAN_CASE_SINGLE_HASH_FIELD6", "GP9_SCAN_CASE_SINGLE_HASH_VALUE6", + &int32_ret); delete_keys.push_back("GP9_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP9_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP9_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4601,7 +4507,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP9_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP9_KEY1_SCAN_CASE_SINGLE_SET", {"GP9_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP9_KEY2_SCAN_CASE_SINGLE_SET", {"GP9_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP9_KEY3_SCAN_CASE_SINGLE_SET", {"GP9_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4615,7 +4521,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP9_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP9_KEY1_SCAN_CASE_SINGLE_LIST", {"GP9_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP9_KEY2_SCAN_CASE_SINGLE_LIST", {"GP9_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP9_KEY3_SCAN_CASE_SINGLE_LIST", {"GP9_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4629,7 +4535,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP9_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP9_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP9_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP9_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP9_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP9_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP9_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4670,10 +4576,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 10 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP10_KEY1_SCAN_CASE_SINGLE_STRING", "GP10_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP10_KEY2_SCAN_CASE_SINGLE_STRING", "GP10_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP10_KEY3_SCAN_CASE_SINGLE_STRING", "GP10_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4687,13 +4592,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP10_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP10_KEY1_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD1", "GP10_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP10_KEY2_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD2", "GP10_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP10_KEY3_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD3", "GP10_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP10_KEY4_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD4", "GP10_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP10_KEY5_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD5", "GP10_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP10_KEY6_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD6", "GP10_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP10_KEY1_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD1", + "GP10_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP10_KEY2_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD2", + "GP10_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP10_KEY3_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD3", + "GP10_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP10_KEY4_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD4", + "GP10_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP10_KEY5_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD5", + "GP10_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP10_KEY6_SCAN_CASE_SINGLE_HASH", "GP10_SCAN_CASE_SINGLE_HASH_FIELD6", + "GP10_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP10_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP10_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP10_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4701,7 +4612,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP10_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP10_KEY1_SCAN_CASE_SINGLE_SET", {"GP10_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP10_KEY2_SCAN_CASE_SINGLE_SET", {"GP10_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP10_KEY3_SCAN_CASE_SINGLE_SET", {"GP10_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4715,7 +4626,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP10_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP10_KEY1_SCAN_CASE_SINGLE_LIST", {"GP10_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP10_KEY2_SCAN_CASE_SINGLE_LIST", {"GP10_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP10_KEY3_SCAN_CASE_SINGLE_LIST", {"GP10_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4729,7 +4640,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP10_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP10_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP10_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP10_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP10_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP10_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP10_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4765,10 +4676,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 11 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP11_KEY1_SCAN_CASE_SINGLE_STRING", "GP11_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP11_KEY2_SCAN_CASE_SINGLE_STRING", "GP11_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP11_KEY3_SCAN_CASE_SINGLE_STRING", "GP11_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4782,13 +4692,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP11_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP11_KEY1_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD1", "GP11_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP11_KEY2_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD2", "GP11_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP11_KEY3_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD3", "GP11_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP11_KEY4_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD4", "GP11_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP11_KEY5_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD5", "GP11_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP11_KEY6_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD6", "GP11_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP11_KEY1_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD1", + "GP11_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP11_KEY2_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD2", + "GP11_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP11_KEY3_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD3", + "GP11_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP11_KEY4_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD4", + "GP11_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP11_KEY5_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD5", + "GP11_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP11_KEY6_SCAN_CASE_SINGLE_HASH", "GP11_SCAN_CASE_SINGLE_HASH_FIELD6", + "GP11_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP11_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP11_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP11_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4796,7 +4712,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP11_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP11_KEY1_SCAN_CASE_SINGLE_SET", {"GP11_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP11_KEY2_SCAN_CASE_SINGLE_SET", {"GP11_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP11_KEY3_SCAN_CASE_SINGLE_SET", {"GP11_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4810,7 +4726,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP11_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP11_KEY1_SCAN_CASE_SINGLE_LIST", {"GP11_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP11_KEY2_SCAN_CASE_SINGLE_LIST", {"GP11_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP11_KEY3_SCAN_CASE_SINGLE_LIST", {"GP11_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4824,7 +4740,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP11_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP11_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP11_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP11_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP11_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP11_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP11_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4855,10 +4771,9 @@ TEST_F(KeysTest, ScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 12 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP12_KEY1_SCAN_CASE_SINGLE_STRING", "GP12_SCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP12_KEY2_SCAN_CASE_SINGLE_STRING", "GP12_SCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP12_KEY3_SCAN_CASE_SINGLE_STRING", "GP12_SCAN_CASE_SINGLE_STRING_VALUE3"); @@ -4872,13 +4787,19 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_SCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP12_KEY6_SCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP12_KEY1_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD1", "GP12_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP12_KEY2_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD2", "GP12_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP12_KEY3_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD3", "GP12_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP12_KEY4_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD4", "GP12_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP12_KEY5_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD5", "GP12_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP12_KEY6_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD6", "GP12_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP12_KEY1_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD1", + "GP12_SCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP12_KEY2_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD2", + "GP12_SCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP12_KEY3_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD3", + "GP12_SCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP12_KEY4_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD4", + "GP12_SCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP12_KEY5_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD5", + "GP12_SCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP12_KEY6_SCAN_CASE_SINGLE_HASH", "GP12_SCAN_CASE_SINGLE_HASH_FIELD6", + "GP12_SCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP12_KEY1_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP12_KEY2_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP12_KEY3_SCAN_CASE_SINGLE_HASH"); @@ -4886,7 +4807,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_SCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP12_KEY6_SCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP12_KEY1_SCAN_CASE_SINGLE_SET", {"GP12_SCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP12_KEY2_SCAN_CASE_SINGLE_SET", {"GP12_SCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP12_KEY3_SCAN_CASE_SINGLE_SET", {"GP12_SCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -4900,7 +4821,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_SCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP12_KEY6_SCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP12_KEY1_SCAN_CASE_SINGLE_LIST", {"GP12_SCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP12_KEY2_SCAN_CASE_SINGLE_LIST", {"GP12_SCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP12_KEY3_SCAN_CASE_SINGLE_LIST", {"GP12_SCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -4914,7 +4835,7 @@ TEST_F(KeysTest, ScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_SCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP12_KEY6_SCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP12_KEY1_SCAN_CASE_SINGLE_ZSET", {{1, "GP12_SCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP12_KEY2_SCAN_CASE_SINGLE_ZSET", {{1, "GP12_SCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP12_KEY3_SCAN_CASE_SINGLE_ZSET", {{1, "GP12_SCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -4947,7 +4868,6 @@ TEST_F(KeysTest, ScanCaseSingleTest) { } TEST_F(KeysTest, PKExpireScanCaseAllTest) { - int64_t cursor; int64_t next_cursor; int64_t del_num; @@ -4959,27 +4879,30 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { std::map type_status; // ***************** Group 1 Test ***************** - //String + // String s = db.Set("GP1_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP1_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP1_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP1_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP1_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP1_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP1_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP1_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP1_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP1_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP1_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP1_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP1_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP1_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP1_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP1_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); - //Set + // Set s = db.SAdd("GP1_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP1_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP1_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP1_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP1_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP1_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP1_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP1_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP1_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP1_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP1_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP1_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP1_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP1_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP1_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP1_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP1_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP1_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5004,7 +4927,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { ASSERT_TRUE(set_timeout(&db, "GP1_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", 28)); ASSERT_TRUE(set_timeout(&db, "GP1_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", 30)); - //PKExpireScan + // PKExpireScan delete_keys.clear(); keys.clear(); cursor = db.PKExpireScan(DataType::kAll, 0, 0, 100, 3, &keys); @@ -5056,29 +4979,31 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 2 Test ***************** - //String + // String s = db.Set("GP2_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP2_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP2_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP2_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP2_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP2_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP2_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP2_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP2_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP2_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP2_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP2_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP2_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP2_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP2_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP2_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); - //Set + // Set s = db.SAdd("GP2_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP2_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP2_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP2_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP2_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP2_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP2_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP2_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP2_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP2_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP2_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP2_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP2_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP2_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP2_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP2_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP2_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP2_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5103,7 +5028,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { ASSERT_TRUE(set_timeout(&db, "GP2_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", 28)); ASSERT_TRUE(set_timeout(&db, "GP2_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", 30)); - //PKExpireScan + // PKExpireScan delete_keys.clear(); keys.clear(); cursor = db.PKExpireScan(DataType::kAll, 0, 0, 100, 2, &keys); @@ -5173,29 +5098,31 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 3 Test ***************** - //String + // String s = db.Set("GP3_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP3_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP3_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP3_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP3_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP3_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP3_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP3_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP3_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP3_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP3_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP3_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP3_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP3_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP3_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP3_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); - //Set + // Set s = db.SAdd("GP3_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP3_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP3_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP3_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP3_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP3_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP3_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP3_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP3_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP3_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP3_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP3_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP3_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP3_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP3_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP3_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP3_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP3_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5220,7 +5147,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { ASSERT_TRUE(set_timeout(&db, "GP3_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", 28)); ASSERT_TRUE(set_timeout(&db, "GP3_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", 30)); - //PKExpireScan + // PKExpireScan delete_keys.clear(); keys.clear(); cursor = db.PKExpireScan(DataType::kAll, 0, 0, 100, 5, &keys); @@ -5260,29 +5187,31 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 4 Test ***************** - //String + // String s = db.Set("GP4_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP4_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP4_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP4_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP4_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP4_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); - //Hash - s = db.HSet("GP4_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP4_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP4_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP4_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP4_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP4_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP4_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP4_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP4_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP4_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); - //Set + // Set s = db.SAdd("GP4_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP4_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP4_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP4_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP4_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP4_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); - //List + // List s = db.LPush("GP4_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP4_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP4_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP4_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP4_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP4_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); - //ZSet + // ZSet s = db.ZAdd("GP4_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP4_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP4_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP4_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP4_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP4_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5334,10 +5263,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 5 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP5_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP5_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP5_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP5_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP5_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP5_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5345,15 +5273,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP5_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP5_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP5_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP5_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP5_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP5_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP5_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP5_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP5_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP5_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5361,7 +5292,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP5_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP5_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP5_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP5_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP5_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP5_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5369,7 +5300,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP5_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP5_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP5_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP5_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP5_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP5_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP5_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5415,10 +5346,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 6 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP6_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP6_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP6_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP6_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP6_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP6_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5426,15 +5356,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP6_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP6_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP6_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP6_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP6_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP6_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP6_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP6_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP6_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP6_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5442,7 +5375,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP6_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP6_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP6_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP6_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP6_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP6_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5450,7 +5383,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP6_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP6_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP6_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP6_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP6_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP6_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP6_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5498,10 +5431,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 7 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP7_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP7_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP7_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP7_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP7_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP7_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5509,15 +5441,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP7_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP7_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP7_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP7_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP7_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP7_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP7_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP7_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP7_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP7_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5525,7 +5460,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP7_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP7_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP7_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP7_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP7_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP7_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5533,7 +5468,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP7_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP7_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP7_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP7_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP7_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP7_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP7_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5581,10 +5516,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 8 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP8_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP8_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP8_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP8_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP8_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP8_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5592,15 +5526,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP8_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP8_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP8_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP8_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP8_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP8_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP8_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP8_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP8_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP8_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5608,7 +5545,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP8_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP8_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP8_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP8_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP8_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP8_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5616,7 +5553,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP8_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP8_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP8_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP8_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP8_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP8_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP8_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5664,10 +5601,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 9 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP9_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP9_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP9_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5675,15 +5611,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP9_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP9_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP9_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP9_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP9_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP9_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP9_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5691,7 +5630,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP9_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP9_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP9_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5699,7 +5638,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP9_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP9_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP9_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP9_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP9_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP9_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5736,16 +5675,16 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { cursor = next_cursor; } while (cursor); ASSERT_EQ(total_keys.size(), 15); - ASSERT_EQ(total_keys[0], "GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY1"); - ASSERT_EQ(total_keys[1], "GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); - ASSERT_EQ(total_keys[2], "GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - ASSERT_EQ(total_keys[3], "GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); - ASSERT_EQ(total_keys[4], "GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); - ASSERT_EQ(total_keys[5], "GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - ASSERT_EQ(total_keys[6], "GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY1"); - ASSERT_EQ(total_keys[7], "GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); - ASSERT_EQ(total_keys[8], "GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - ASSERT_EQ(total_keys[9], "GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY1"); + ASSERT_EQ(total_keys[0], "GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY1"); + ASSERT_EQ(total_keys[1], "GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); + ASSERT_EQ(total_keys[2], "GP9_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); + ASSERT_EQ(total_keys[3], "GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); + ASSERT_EQ(total_keys[4], "GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); + ASSERT_EQ(total_keys[5], "GP9_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); + ASSERT_EQ(total_keys[6], "GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY1"); + ASSERT_EQ(total_keys[7], "GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); + ASSERT_EQ(total_keys[8], "GP9_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); + ASSERT_EQ(total_keys[9], "GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY1"); ASSERT_EQ(total_keys[10], "GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); ASSERT_EQ(total_keys[11], "GP9_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); ASSERT_EQ(total_keys[12], "GP9_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1"); @@ -5757,10 +5696,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 10 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP10_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP10_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP10_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP10_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP10_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP10_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5768,15 +5706,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP10_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP10_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP10_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP10_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP10_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP10_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP10_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP10_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP10_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP10_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5784,7 +5725,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP10_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP10_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP10_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP10_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP10_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP10_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5792,7 +5733,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP10_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP10_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP10_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP10_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP10_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP10_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP10_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5838,10 +5779,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 11 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP11_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP11_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP11_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP11_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP11_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP11_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5849,15 +5789,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP11_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP11_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP11_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP11_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP11_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP11_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP11_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP11_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP11_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP11_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5865,7 +5808,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP11_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP11_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP11_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP11_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP11_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP11_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5873,7 +5816,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP11_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP11_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP11_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP11_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP11_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP11_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP11_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -5919,10 +5862,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 12 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP12_PKEXPIRESCAN_CASE_ALL_STRING_KEY1", "GP12_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP12_PKEXPIRESCAN_CASE_ALL_STRING_KEY2", "GP12_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP12_PKEXPIRESCAN_CASE_ALL_STRING_KEY3", "GP12_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -5930,15 +5872,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_STRING_KEY2"); delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_STRING_KEY3"); - //Hash - s = db.HSet("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY1", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP12_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY2", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP12_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY3", "GP12_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP12_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY1"); delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY2"); delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_HASH_KEY3"); - //Set + // Set s = db.SAdd("GP12_PKEXPIRESCAN_CASE_ALL_SET_KEY1", {"GP12_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP12_PKEXPIRESCAN_CASE_ALL_SET_KEY2", {"GP12_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP12_PKEXPIRESCAN_CASE_ALL_SET_KEY3", {"GP12_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -5946,7 +5891,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_SET_KEY2"); delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_SET_KEY3"); - //List + // List s = db.LPush("GP12_PKEXPIRESCAN_CASE_ALL_LIST_KEY1", {"GP12_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP12_PKEXPIRESCAN_CASE_ALL_LIST_KEY2", {"GP12_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP12_PKEXPIRESCAN_CASE_ALL_LIST_KEY3", {"GP12_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -5954,7 +5899,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_LIST_KEY2"); delete_keys.push_back("GP12_PKEXPIRESCAN_CASE_ALL_LIST_KEY3"); - //ZSet + // ZSet s = db.ZAdd("GP12_PKEXPIRESCAN_CASE_ALL_ZSET_KEY1", {{1, "GP12_PKEXPIRESCAN_CASE_ALL_ZSET_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP12_PKEXPIRESCAN_CASE_ALL_ZSET_KEY2", {{1, "GP12_PKEXPIRESCAN_CASE_ALL_ZSET_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP12_PKEXPIRESCAN_CASE_ALL_ZSET_KEY3", {{1, "GP12_PKEXPIRESCAN_CASE_ALL_ZSET_MEMBER3"}}, &int32_ret); @@ -6000,10 +5945,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 13 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP13_KEY1_PKEXPIRESCAN_CASE_ALL_STRING", "GP13_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_STRING", "GP13_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_STRING", "GP13_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -6011,15 +5955,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_STRING"); delete_keys.push_back("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP13_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP13_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP13_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP13_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP13_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP13_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP13_KEY1_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP13_KEY1_PKEXPIRESCAN_CASE_ALL_SET", {"GP13_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_SET", {"GP13_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_SET", {"GP13_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -6027,7 +5974,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_SET"); delete_keys.push_back("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP13_KEY1_PKEXPIRESCAN_CASE_ALL_LIST", {"GP13_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_LIST", {"GP13_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_LIST", {"GP13_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -6035,7 +5982,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_LIST"); delete_keys.push_back("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP13_KEY1_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP13_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP13_KEY2_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP13_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP13_KEY3_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP13_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -6083,10 +6030,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 14 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP14_KEY1_PKEXPIRESCAN_CASE_ALL_STRING", "GP14_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_STRING", "GP14_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_STRING", "GP14_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -6094,15 +6040,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_STRING"); delete_keys.push_back("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP14_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP14_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP14_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP14_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP14_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP14_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP14_KEY1_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP14_KEY1_PKEXPIRESCAN_CASE_ALL_SET", {"GP14_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_SET", {"GP14_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_SET", {"GP14_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -6110,7 +6059,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_SET"); delete_keys.push_back("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP14_KEY1_PKEXPIRESCAN_CASE_ALL_LIST", {"GP14_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_LIST", {"GP14_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_LIST", {"GP14_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -6118,7 +6067,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_LIST"); delete_keys.push_back("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP14_KEY1_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP14_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP14_KEY2_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP14_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP14_KEY3_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP14_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -6166,10 +6115,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 15 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP15_KEY1_PKEXPIRESCAN_CASE_ALL_STRING", "GP15_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_STRING", "GP15_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_STRING", "GP15_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -6177,15 +6125,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_STRING"); delete_keys.push_back("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP15_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP15_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP15_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP15_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP15_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP15_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP15_KEY1_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP15_KEY1_PKEXPIRESCAN_CASE_ALL_SET", {"GP15_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_SET", {"GP15_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_SET", {"GP15_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -6193,7 +6144,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_SET"); delete_keys.push_back("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP15_KEY1_PKEXPIRESCAN_CASE_ALL_LIST", {"GP15_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_LIST", {"GP15_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_LIST", {"GP15_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -6201,7 +6152,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_LIST"); delete_keys.push_back("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP15_KEY1_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP15_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP15_KEY2_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP15_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP15_KEY3_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP15_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -6249,10 +6200,9 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 16 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP16_KEY1_PKEXPIRESCAN_CASE_ALL_STRING", "GP16_PKEXPIRESCAN_CASE_ALL_STRING_VALUE1"); s = db.Set("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_STRING", "GP16_PKEXPIRESCAN_CASE_ALL_STRING_VALUE2"); s = db.Set("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_STRING", "GP16_PKEXPIRESCAN_CASE_ALL_STRING_VALUE3"); @@ -6260,15 +6210,18 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_STRING"); delete_keys.push_back("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_STRING"); - //Hash - s = db.HSet("GP16_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); - s = db.HSet("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); - s = db.HSet("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); + // Hash + s = db.HSet("GP16_KEY1_PKEXPIRESCAN_CASE_ALL_HASH", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_FIELD1", + "GP16_PKEXPIRESCAN_CASE_ALL_HASH_VALUE1", &int32_ret); + s = db.HSet("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_HASH", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_FIELD2", + "GP16_PKEXPIRESCAN_CASE_ALL_HASH_VALUE2", &int32_ret); + s = db.HSet("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_HASH", "GP16_PKEXPIRESCAN_CASE_ALL_HASH_FIELD3", + "GP16_PKEXPIRESCAN_CASE_ALL_HASH_VALUE3", &int32_ret); delete_keys.push_back("GP16_KEY1_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_HASH"); delete_keys.push_back("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_HASH"); - //Set + // Set s = db.SAdd("GP16_KEY1_PKEXPIRESCAN_CASE_ALL_SET", {"GP16_PKEXPIRESCAN_CASE_ALL_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_SET", {"GP16_PKEXPIRESCAN_CASE_ALL_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_SET", {"GP16_PKEXPIRESCAN_CASE_ALL_SET_MEMBER3"}, &int32_ret); @@ -6276,7 +6229,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_SET"); delete_keys.push_back("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_SET"); - //List + // List s = db.LPush("GP16_KEY1_PKEXPIRESCAN_CASE_ALL_LIST", {"GP16_PKEXPIRESCAN_CASE_ALL_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_LIST", {"GP16_PKEXPIRESCAN_CASE_ALL_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_LIST", {"GP16_PKEXPIRESCAN_CASE_ALL_LIST_NODE3"}, &uint64_ret); @@ -6284,7 +6237,7 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { delete_keys.push_back("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_LIST"); delete_keys.push_back("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP16_KEY1_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP16_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP16_KEY2_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP16_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP16_KEY3_PKEXPIRESCAN_CASE_ALL_ZSET", {{1, "GP16_PKEXPIRESCAN_CASE_ALL_LIST_MEMBER3"}}, &int32_ret); @@ -6334,7 +6287,6 @@ TEST_F(KeysTest, PKExpireScanCaseAllTest) { } TEST_F(KeysTest, PKExpireScanCaseSingleTest) { - int64_t cursor; int64_t next_cursor; int64_t del_num; @@ -6347,7 +6299,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { // ***************** Group 1 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP1_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP1_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP1_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP1_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP1_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP1_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -6361,13 +6313,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP1_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP1_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP1_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP1_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP1_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP1_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP1_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP1_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP1_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP1_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP1_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP1_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP1_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP1_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP1_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP1_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP1_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -6375,7 +6333,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP1_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP1_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP1_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP1_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP1_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP1_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP1_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -6389,7 +6347,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP1_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP1_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP1_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP1_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP1_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP1_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP1_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -6403,7 +6361,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP1_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP1_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP1_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP1_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP1_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP1_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP1_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP1_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -6451,10 +6409,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 2 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP2_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP2_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP2_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP2_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP2_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP2_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -6468,13 +6425,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP2_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP2_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP2_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP2_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP2_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP2_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP2_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP2_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP2_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP2_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP2_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP2_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP2_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP2_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP2_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP2_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP2_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -6482,7 +6445,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP2_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP2_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP2_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP2_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP2_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP2_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP2_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -6496,7 +6459,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP2_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP2_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP2_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP2_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP2_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP2_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP2_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -6510,7 +6473,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP2_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP2_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP2_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP2_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP2_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP2_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP2_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP2_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -6553,10 +6516,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 3 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP3_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP3_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP3_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP3_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP3_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP3_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -6570,13 +6532,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP3_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP3_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP3_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP3_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP3_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP3_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP3_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP3_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP3_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP3_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP3_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP3_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP3_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP3_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP3_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP3_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP3_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -6584,7 +6552,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP3_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP3_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP3_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP3_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP3_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP3_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP3_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -6598,7 +6566,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP3_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP3_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP3_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP3_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP3_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP3_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP3_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -6612,7 +6580,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP3_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP3_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP3_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP3_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP3_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP3_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP3_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP3_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -6650,10 +6618,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 4 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP4_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP4_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP4_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP4_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP4_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP4_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -6667,13 +6634,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP4_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP4_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP4_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP4_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP4_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP4_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP4_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP4_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP4_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP4_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP4_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP4_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP4_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP4_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP4_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP4_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP4_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -6681,7 +6654,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP4_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP4_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP4_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP4_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP4_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP4_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP4_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -6695,7 +6668,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP4_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP4_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP4_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP4_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP4_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP4_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP4_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -6709,7 +6682,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP4_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP4_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP4_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP4_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP4_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP4_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP4_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP4_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -6747,10 +6720,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 5 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP5_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP5_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP5_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP5_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP5_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP5_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -6764,13 +6736,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP5_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP5_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP5_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP5_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP5_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP5_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP5_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP5_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP5_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP5_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP5_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP5_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP5_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP5_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP5_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP5_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP5_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -6778,7 +6756,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP5_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP5_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP5_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP5_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP5_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP5_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP5_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -6792,7 +6770,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP5_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP5_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP5_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP5_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP5_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP5_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP5_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -6806,7 +6784,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP5_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP5_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP5_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP5_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP5_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP5_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP5_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP5_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -6854,10 +6832,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 6 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP6_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP6_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP6_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP6_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP6_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP6_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -6871,13 +6848,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP6_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP6_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP6_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP6_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP6_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP6_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP6_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP6_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP6_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP6_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP6_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP6_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP6_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP6_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP6_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP6_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP6_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -6885,7 +6868,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP6_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP6_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP6_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP6_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP6_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP6_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP6_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -6899,7 +6882,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP6_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP6_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP6_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP6_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP6_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP6_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP6_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -6913,7 +6896,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP6_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP6_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP6_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP6_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP6_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP6_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP6_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP6_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -6956,10 +6939,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 7 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP7_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP7_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP7_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP7_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP7_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP7_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -6973,13 +6955,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP7_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP7_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP7_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP7_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP7_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP7_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP7_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP7_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP7_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP7_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP7_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP7_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP7_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP7_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP7_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP7_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP7_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -6987,7 +6975,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP7_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP7_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP7_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP7_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP7_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP7_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP7_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -7001,7 +6989,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP7_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP7_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP7_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP7_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP7_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP7_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP7_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -7015,7 +7003,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP7_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP7_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP7_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP7_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP7_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP7_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP7_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP7_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -7053,10 +7041,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 8 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP8_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP8_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP8_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP8_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP8_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP8_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -7070,13 +7057,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP8_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP8_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP8_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP8_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP8_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP8_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP8_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP8_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP8_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP8_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP8_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP8_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP8_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP8_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP8_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP8_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP8_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -7084,7 +7077,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP8_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP8_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP8_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP8_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP8_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP8_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP8_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -7098,7 +7091,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP8_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP8_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP8_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP8_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP8_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP8_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP8_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -7112,7 +7105,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP8_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP8_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP8_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP8_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP8_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP8_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP8_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP8_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -7150,10 +7143,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 9 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP9_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP9_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP9_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP9_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP9_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP9_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -7167,13 +7159,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP9_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP9_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP9_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP9_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP9_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP9_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP9_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP9_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP9_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP9_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP9_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP9_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP9_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP9_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP9_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP9_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP9_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -7181,7 +7179,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP9_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP9_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP9_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP9_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP9_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP9_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP9_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -7195,7 +7193,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP9_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP9_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP9_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP9_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP9_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP9_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP9_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -7209,7 +7207,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP9_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP9_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet + // ZSet s = db.ZAdd("GP9_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP9_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); s = db.ZAdd("GP9_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP9_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); s = db.ZAdd("GP9_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP9_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); @@ -7257,10 +7255,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 10 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP10_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP10_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP10_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -7274,13 +7271,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP10_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP10_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP10_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -7288,7 +7291,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP10_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP10_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP10_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -7302,7 +7305,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -7316,13 +7319,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet - s = db.ZAdd("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); - s = db.ZAdd("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); - s = db.ZAdd("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); - s = db.ZAdd("GP10_KEY4_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER4"}}, &int32_ret); - s = db.ZAdd("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER5"}}, &int32_ret); - s = db.ZAdd("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER6"}}, &int32_ret); + // ZSet + s = db.ZAdd("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, + &int32_ret); + s = db.ZAdd("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, + &int32_ret); + s = db.ZAdd("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, + &int32_ret); + s = db.ZAdd("GP10_KEY4_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER4"}}, + &int32_ret); + s = db.ZAdd("GP10_KEY5_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER5"}}, + &int32_ret); + s = db.ZAdd("GP10_KEY6_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP10_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER6"}}, + &int32_ret); delete_keys.push_back("GP10_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET"); delete_keys.push_back("GP10_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET"); delete_keys.push_back("GP10_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET"); @@ -7359,10 +7368,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 11 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP11_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP11_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP11_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -7376,13 +7384,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP11_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP11_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP11_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -7390,7 +7404,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP11_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP11_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP11_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -7404,7 +7418,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -7418,13 +7432,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet - s = db.ZAdd("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); - s = db.ZAdd("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); - s = db.ZAdd("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); - s = db.ZAdd("GP11_KEY4_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER4"}}, &int32_ret); - s = db.ZAdd("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER5"}}, &int32_ret); - s = db.ZAdd("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER6"}}, &int32_ret); + // ZSet + s = db.ZAdd("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, + &int32_ret); + s = db.ZAdd("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, + &int32_ret); + s = db.ZAdd("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, + &int32_ret); + s = db.ZAdd("GP11_KEY4_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER4"}}, + &int32_ret); + s = db.ZAdd("GP11_KEY5_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER5"}}, + &int32_ret); + s = db.ZAdd("GP11_KEY6_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP11_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER6"}}, + &int32_ret); delete_keys.push_back("GP11_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET"); delete_keys.push_back("GP11_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET"); delete_keys.push_back("GP11_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET"); @@ -7456,10 +7476,9 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { sleep(2); db.Compact(DataType::kAll, true); - // ***************** Group 12 Test ***************** delete_keys.clear(); - //String + // String s = db.Set("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP12_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE1"); s = db.Set("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP12_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE2"); s = db.Set("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_STRING", "GP12_PKEXPIRESCAN_CASE_SINGLE_STRING_VALUE3"); @@ -7473,13 +7492,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_STRING"); delete_keys.push_back("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_STRING"); - //Hash - s = db.HSet("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); - s = db.HSet("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); - s = db.HSet("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); - s = db.HSet("GP12_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); - s = db.HSet("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); - s = db.HSet("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); + // Hash + s = db.HSet("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD1", + "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE1", &int32_ret); + s = db.HSet("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD2", + "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE2", &int32_ret); + s = db.HSet("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD3", + "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE3", &int32_ret); + s = db.HSet("GP12_KEY4_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD4", + "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE4", &int32_ret); + s = db.HSet("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD5", + "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE5", &int32_ret); + s = db.HSet("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH", "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_FIELD6", + "GP12_PKEXPIRESCAN_CASE_SINGLE_HASH_VALUE6", &int32_ret); delete_keys.push_back("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_HASH"); @@ -7487,7 +7512,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_HASH"); delete_keys.push_back("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_HASH"); - //Set + // Set s = db.SAdd("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP12_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER1"}, &int32_ret); s = db.SAdd("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP12_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER2"}, &int32_ret); s = db.SAdd("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_SET", {"GP12_PKEXPIRESCAN_CASE_SINGLE_SET_MEMBER3"}, &int32_ret); @@ -7501,7 +7526,7 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_SET"); delete_keys.push_back("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_SET"); - //List + // List s = db.LPush("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE1"}, &uint64_ret); s = db.LPush("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE2"}, &uint64_ret); s = db.LPush("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_LIST", {"GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_NODE3"}, &uint64_ret); @@ -7515,13 +7540,19 @@ TEST_F(KeysTest, PKExpireScanCaseSingleTest) { delete_keys.push_back("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_LIST"); delete_keys.push_back("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_LIST"); - //ZSet - s = db.ZAdd("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, &int32_ret); - s = db.ZAdd("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, &int32_ret); - s = db.ZAdd("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, &int32_ret); - s = db.ZAdd("GP12_KEY4_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER4"}}, &int32_ret); - s = db.ZAdd("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER5"}}, &int32_ret); - s = db.ZAdd("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER6"}}, &int32_ret); + // ZSet + s = db.ZAdd("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER1"}}, + &int32_ret); + s = db.ZAdd("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER2"}}, + &int32_ret); + s = db.ZAdd("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER3"}}, + &int32_ret); + s = db.ZAdd("GP12_KEY4_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER4"}}, + &int32_ret); + s = db.ZAdd("GP12_KEY5_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER5"}}, + &int32_ret); + s = db.ZAdd("GP12_KEY6_PKEXPIRESCAN_CASE_SINGLE_ZSET", {{1, "GP12_PKEXPIRESCAN_CASE_SINGLE_LIST_MEMBER6"}}, + &int32_ret); delete_keys.push_back("GP12_KEY1_PKEXPIRESCAN_CASE_SINGLE_ZSET"); delete_keys.push_back("GP12_KEY2_PKEXPIRESCAN_CASE_SINGLE_ZSET"); delete_keys.push_back("GP12_KEY3_PKEXPIRESCAN_CASE_SINGLE_ZSET"); @@ -7606,7 +7637,6 @@ TEST_F(KeysTest, ExpireTest) { s = db.ZCard("GP1_EXPIRE_KEY", &ret); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 2 Test ***************** // Strings s = db.Set("GP2_EXPIRE_STRING_KEY", "VALUE"); @@ -7653,7 +7683,6 @@ TEST_F(KeysTest, ExpireTest) { ret = db.Expire("GP2_EXPIRE_ZSETS_KEY", 1, &type_status); ASSERT_EQ(ret, 0); - // ***************** Group 3 Test ***************** // Strings s = db.Set("GP3_EXPIRE_STRING_KEY", "VALUE"); @@ -7712,7 +7741,7 @@ TEST_F(KeysTest, DelTest) { int32_t ret; std::string value; std::map type_status; - std::vector keys {"DEL_KEY"}; + std::vector keys{"DEL_KEY"}; // Strings s = db.Set("DEL_KEY", "VALUE"); @@ -7764,7 +7793,7 @@ TEST_F(KeysTest, ExistsTest) { int32_t ret; uint64_t llen; std::map type_status; - std::vector keys {"EXISTS_KEY"}; + std::vector keys{"EXISTS_KEY"}; // Strings s = db.Set("EXISTS_KEY", "VALUE"); @@ -7862,7 +7891,6 @@ TEST_F(KeysTest, ExpireatTest) { s = db.ZAdd("EXPIREAT_KEY", {{1, "MEMBER"}}, &ret); ASSERT_TRUE(s.ok()); - ret = db.Expireat("EXPIREAT_KEY", 0, &type_status); ASSERT_EQ(ret, 5); @@ -7990,4 +8018,3 @@ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - diff --git a/src/storage/tests/lists_filter_test.cc b/src/storage/tests/lists_filter_test.cc index 3c11b675ee..01231d1b14 100644 --- a/src/storage/tests/lists_filter_test.cc +++ b/src/storage/tests/lists_filter_test.cc @@ -4,12 +4,12 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include -#include "storage/storage.h" -#include "src/redis.h" #include "src/lists_filter.h" +#include "src/redis.h" +#include "storage/storage.h" using namespace storage; @@ -25,8 +25,7 @@ class ListsFilterTest : public ::testing::Test { if (s.ok()) { // create column family rocksdb::ColumnFamilyHandle* cf; - s = meta_db->CreateColumnFamily(rocksdb::ColumnFamilyOptions(), - "data_cf", &cf); + s = meta_db->CreateColumnFamily(rocksdb::ColumnFamilyOptions(), "data_cf", &cf); delete cf; delete meta_db; } @@ -35,18 +34,15 @@ class ListsFilterTest : public ::testing::Test { rocksdb::ColumnFamilyOptions data_cf_ops(options); // Meta CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor(rocksdb::kDefaultColumnFamilyName, meta_cf_ops)); // Data CF - column_families.push_back(rocksdb::ColumnFamilyDescriptor( - "data_cf", data_cf_ops)); + column_families.push_back(rocksdb::ColumnFamilyDescriptor("data_cf", data_cf_ops)); - s = rocksdb::DB::Open(options, db_path, column_families, - &handles, &meta_db); + s = rocksdb::DB::Open(options, db_path, column_families, &handles, &meta_db); } - virtual ~ListsFilterTest() { } + virtual ~ListsFilterTest() {} - virtual void SetUp() { } + virtual void SetUp() {} virtual void TearDown() { for (auto handle : handles) { delete handle; @@ -59,7 +55,7 @@ class ListsFilterTest : public ::testing::Test { storage::Status s; std::vector column_families; - std::vector handles; + std::vector handles; }; // Meta Filter @@ -79,8 +75,8 @@ TEST_F(ListsFilterTest, MetaFilterTest) { ListsMetaValue lists_meta_value1(std::string(str, sizeof(uint64_t))); lists_meta_value1.UpdateVersion(); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - filter_result = lists_meta_filter->Filter(0, "FILTER_TEST_KEY", - lists_meta_value1.Encode(), &new_value, &value_changed); + filter_result = + lists_meta_filter->Filter(0, "FILTER_TEST_KEY", lists_meta_value1.Encode(), &new_value, &value_changed); ASSERT_EQ(filter_result, true); // Timeout timestamp is not set, it's not an empty list. @@ -88,8 +84,8 @@ TEST_F(ListsFilterTest, MetaFilterTest) { ListsMetaValue lists_meta_value2(std::string(str, sizeof(uint64_t))); lists_meta_value2.UpdateVersion(); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - filter_result = lists_meta_filter->Filter(0, "FILTER_TEST_KEY", - lists_meta_value2.Encode(), &new_value, &value_changed); + filter_result = + lists_meta_filter->Filter(0, "FILTER_TEST_KEY", lists_meta_value2.Encode(), &new_value, &value_changed); ASSERT_EQ(filter_result, false); // Timeout timestamp is set, but not expired. @@ -98,8 +94,8 @@ TEST_F(ListsFilterTest, MetaFilterTest) { lists_meta_value3.UpdateVersion(); lists_meta_value3.SetRelativeTimestamp(3); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); - filter_result = lists_meta_filter->Filter(0, "FILTER_TEST_KEY", - lists_meta_value3.Encode(), &new_value, &value_changed); + filter_result = + lists_meta_filter->Filter(0, "FILTER_TEST_KEY", lists_meta_value3.Encode(), &new_value, &value_changed); ASSERT_EQ(filter_result, false); // Timeout timestamp is set, already expired. @@ -109,9 +105,8 @@ TEST_F(ListsFilterTest, MetaFilterTest) { lists_meta_value4.SetRelativeTimestamp(1); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); ParsedListsMetaValue parsed_meta_value(lists_meta_value4.Encode()); - filter_result = lists_meta_filter->Filter(0, "FILTER_TEST_KEY", - lists_meta_value4.Encode(), - &new_value, &value_changed); + filter_result = + lists_meta_filter->Filter(0, "FILTER_TEST_KEY", lists_meta_value4.Encode(), &new_value, &value_changed); ASSERT_EQ(filter_result, true); delete lists_meta_filter; } @@ -131,16 +126,14 @@ TEST_F(ListsFilterTest, DataFilterTest) { EncodeFixed64(str, 1); ListsMetaValue lists_meta_value1(std::string(str, sizeof(uint64_t))); version = lists_meta_value1.UpdateVersion(); - s = meta_db->Put(rocksdb::WriteOptions(), handles[0], - "FILTER_TEST_KEY", lists_meta_value1.Encode()); + s = meta_db->Put(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY", lists_meta_value1.Encode()); ASSERT_TRUE(s.ok()); ListsDataKey lists_data_key1("FILTER_TEST_KEY", version, 1); - filter_result = lists_data_filter1->Filter(0, lists_data_key1.Encode(), - "FILTER_TEST_VALUE", &new_value, &value_changed); + filter_result = + lists_data_filter1->Filter(0, lists_data_key1.Encode(), "FILTER_TEST_VALUE", &new_value, &value_changed); ASSERT_EQ(filter_result, false); - s = meta_db->Delete(rocksdb::WriteOptions(), - handles[0], "FILTER_TEST_KEY"); + s = meta_db->Delete(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY"); ASSERT_TRUE(s.ok()); delete lists_data_filter1; @@ -152,15 +145,13 @@ TEST_F(ListsFilterTest, DataFilterTest) { ListsMetaValue lists_meta_value2(std::string(str, sizeof(uint64_t))); version = lists_meta_value2.UpdateVersion(); lists_meta_value2.SetRelativeTimestamp(1); - s = meta_db->Put(rocksdb::WriteOptions(), handles[0], - "FILTER_TEST_KEY", lists_meta_value2.Encode()); + s = meta_db->Put(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY", lists_meta_value2.Encode()); ASSERT_TRUE(s.ok()); ListsDataKey lists_data_key2("FILTER_TEST_KEY", version, 1); - filter_result = lists_data_filter2->Filter(0, lists_data_key2.Encode(), - "FILTER_TEST_VALUE", &new_value, &value_changed); + filter_result = + lists_data_filter2->Filter(0, lists_data_key2.Encode(), "FILTER_TEST_VALUE", &new_value, &value_changed); ASSERT_EQ(filter_result, false); - s = meta_db->Delete(rocksdb::WriteOptions(), - handles[0], "FILTER_TEST_KEY"); + s = meta_db->Delete(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY"); ASSERT_TRUE(s.ok()); delete lists_data_filter2; @@ -172,16 +163,14 @@ TEST_F(ListsFilterTest, DataFilterTest) { ListsMetaValue lists_meta_value3(std::string(str, sizeof(uint64_t))); version = lists_meta_value3.UpdateVersion(); lists_meta_value3.SetRelativeTimestamp(1); - s = meta_db->Put(rocksdb::WriteOptions(), handles[0], - "FILTER_TEST_KEY", lists_meta_value3.Encode()); + s = meta_db->Put(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY", lists_meta_value3.Encode()); ASSERT_TRUE(s.ok()); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); ListsDataKey lists_data_key3("FILTER_TEST_KEY", version, 1); - filter_result = lists_data_filter3->Filter(0, lists_data_key3.Encode(), - "FILTER_TEST_VALUE", &new_value, &value_changed); + filter_result = + lists_data_filter3->Filter(0, lists_data_key3.Encode(), "FILTER_TEST_VALUE", &new_value, &value_changed); ASSERT_EQ(filter_result, true); - s = meta_db->Delete(rocksdb::WriteOptions(), - handles[0], "FILTER_TEST_KEY"); + s = meta_db->Delete(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY"); ASSERT_TRUE(s.ok()); delete lists_data_filter3; @@ -192,19 +181,16 @@ TEST_F(ListsFilterTest, DataFilterTest) { EncodeFixed64(str, 1); ListsMetaValue lists_meta_value4(std::string(str, sizeof(uint64_t))); version = lists_meta_value4.UpdateVersion(); - s = meta_db->Put(rocksdb::WriteOptions(), handles[0], - "FILTER_TEST_KEY", lists_meta_value4.Encode()); + s = meta_db->Put(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY", lists_meta_value4.Encode()); ASSERT_TRUE(s.ok()); ListsDataKey lists_data_key4("FILTER_TEST_KEY", version, 1); version = lists_meta_value4.UpdateVersion(); - s = meta_db->Put(rocksdb::WriteOptions(), handles[0], - "FILTER_TEST_KEY", lists_meta_value4.Encode()); + s = meta_db->Put(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY", lists_meta_value4.Encode()); ASSERT_TRUE(s.ok()); - filter_result = lists_data_filter4->Filter(0, lists_data_key4.Encode(), - "FILTER_TEST_VALUE", &new_value, &value_changed); + filter_result = + lists_data_filter4->Filter(0, lists_data_key4.Encode(), "FILTER_TEST_VALUE", &new_value, &value_changed); ASSERT_EQ(filter_result, true); - s = meta_db->Delete(rocksdb::WriteOptions(), - handles[0], "FILTER_TEST_KEY"); + s = meta_db->Delete(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY"); ASSERT_TRUE(s.ok()); delete lists_data_filter4; @@ -215,15 +201,13 @@ TEST_F(ListsFilterTest, DataFilterTest) { EncodeFixed64(str, 1); ListsMetaValue lists_meta_value5(std::string(str, sizeof(uint64_t))); version = lists_meta_value5.UpdateVersion(); - s = meta_db->Put(rocksdb::WriteOptions(), handles[0], - "FILTER_TEST_KEY", lists_meta_value5.Encode()); + s = meta_db->Put(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY", lists_meta_value5.Encode()); ASSERT_TRUE(s.ok()); ListsDataKey lists_data_value5("FILTER_TEST_KEY", version, 1); - s = meta_db->Delete(rocksdb::WriteOptions(), handles[0], - "FILTER_TEST_KEY"); + s = meta_db->Delete(rocksdb::WriteOptions(), handles[0], "FILTER_TEST_KEY"); ASSERT_TRUE(s.ok()); - filter_result = lists_data_filter5->Filter(0, lists_data_value5.Encode(), - "FILTER_TEST_VALUE", &new_value, &value_changed); + filter_result = + lists_data_filter5->Filter(0, lists_data_value5.Encode(), "FILTER_TEST_VALUE", &new_value, &value_changed); ASSERT_EQ(filter_result, true); delete lists_data_filter5; } diff --git a/src/storage/tests/lists_test.cc b/src/storage/tests/lists_test.cc index 003c2901f0..e4410f8d28 100644 --- a/src/storage/tests/lists_test.cc +++ b/src/storage/tests/lists_test.cc @@ -4,16 +4,15 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include #include "storage/storage.h" #include "storage/util.h" using namespace storage; -static bool elements_match(storage::Storage *const db, - const Slice& key, +static bool elements_match(storage::Storage* const db, const Slice& key, const std::vector& expect_elements) { std::vector elements_out; Status s = db->LRange(key, 0, -1, &elements_out); @@ -47,9 +46,7 @@ static bool elements_match(const std::vector& elements_out, return true; } -static bool len_match(storage::Storage *const db, - const Slice& key, - uint64_t expect_len) { +static bool len_match(storage::Storage* const db, const Slice& key, uint64_t expect_len) { uint64_t len = 0; Status s = db->LLen(key, &len); if (!s.ok() && !s.IsNotFound()) { @@ -61,8 +58,7 @@ static bool len_match(storage::Storage *const db, return len == expect_len; } -static bool make_expired(storage::Storage *const db, - const Slice& key) { +static bool make_expired(storage::Storage* const db, const Slice& key) { std::map type_status; int ret = db->Expire(key, 1, &type_status); if (!ret || !type_status[storage::DataType::kLists].ok()) { @@ -74,8 +70,8 @@ static bool make_expired(storage::Storage *const db, class ListsTest : public ::testing::Test { public: - ListsTest() { } - virtual ~ListsTest() { } + ListsTest() {} + virtual ~ListsTest() {} void SetUp() { std::string path = "./db/lists"; @@ -95,8 +91,8 @@ class ListsTest : public ::testing::Test { DeleteFiles(path.c_str()); } - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Storage db; @@ -112,7 +108,7 @@ TEST_F(ListsTest, LIndexTest) { // "z" -> "e" -> "p" -> "p" -> "l" -> "i" -> "n" // 0 1 2 3 4 5 6 // -7 -6 -5 -4 -3 -2 -1 - std::vector gp1_nodes {"n", "i", "l", "p", "p", "e", "z"}; + std::vector gp1_nodes{"n", "i", "l", "p", "p", "e", "z"}; s = db.LPush("GP1_LINDEX_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); @@ -149,13 +145,12 @@ TEST_F(ListsTest, LIndexTest) { s = db.LIndex("GP1_LINDEX_KEY", -10000, &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 2 Test ***************** // "b" -> "a" -> "t" -> "t" -> "l" -> "e" // 0 1 2 3 4 5 // -6 -5 -4 -3 -2 -1 // LIndex time out list - std::vector gp2_nodes {"b", "a", "t", "t", "l", "e"}; + std::vector gp2_nodes{"b", "a", "t", "t", "l", "e"}; s = db.RPush("GP2_LINDEX_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -168,13 +163,12 @@ TEST_F(ListsTest, LIndexTest) { s = db.LIndex("GP2_LINDEX_KEY", 0, &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 3 Test ***************** // "m" -> "i" -> "s" -> "t" -> "y" // 0 1 2 3 4 // -5 -4 -3 -2 -1 // LIndex the key that has been deleted - std::vector gp3_nodes {"m", "i", "s", "t", "y"}; + std::vector gp3_nodes{"m", "i", "s", "t", "y"}; s = db.RPush("GP3_LINDEX_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -191,13 +185,11 @@ TEST_F(ListsTest, LIndexTest) { s = db.LIndex("GP3_LINDEX_KEY", 0, &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 4 Test ***************** // LIndex not exist key s = db.LIndex("GP4_LINDEX_KEY", 0, &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 5 Test ***************** // "m" -> "i" -> "s" -> "t" -> "y" // 0 1 2 3 4 @@ -207,7 +199,7 @@ TEST_F(ListsTest, LIndexTest) { // "i" -> "s" -> "t" -> "y" // 0 1 2 3 // -4 -3 -2 -1 - std::vector gp5_nodes {"m", "i", "s", "t", "y"}; + std::vector gp5_nodes{"m", "i", "s", "t", "y"}; s = db.RPush("GP5_LINDEX_KEY", gp5_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes.size(), num); @@ -221,7 +213,6 @@ TEST_F(ListsTest, LIndexTest) { s = db.LIndex("GP5_LINDEX_KEY", -5, &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 6 Test ***************** // "m" -> "i" -> "s" -> "t" -> "y" // 0 1 2 3 4 @@ -231,7 +222,7 @@ TEST_F(ListsTest, LIndexTest) { // "m" -> "i" -> "s" -> "t" // 0 1 2 3 // -4 -3 -2 -1 - std::vector gp6_nodes {"m", "i", "s", "t", "y"}; + std::vector gp6_nodes{"m", "i", "s", "t", "y"}; s = db.RPush("GP6_LINDEX_KEY", gp6_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp6_nodes.size(), num); @@ -245,7 +236,6 @@ TEST_F(ListsTest, LIndexTest) { s = db.LIndex("GP6_LINDEX_KEY", 4, &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 7 Test ***************** // "m" -> "i" -> "s" -> "t" -> "y" // 0 1 2 3 4 @@ -255,7 +245,7 @@ TEST_F(ListsTest, LIndexTest) { // "i" -> "s" -> "t" // 0 1 2 // -3 -2 -1 - std::vector gp7_nodes {"m", "i", "s", "t", "y"}; + std::vector gp7_nodes{"m", "i", "s", "t", "y"}; s = db.RPush("GP7_LINDEX_KEY", gp7_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp7_nodes.size(), num); @@ -283,11 +273,10 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - // ***************** Group 2 Test ***************** // "w" -> "e" -> "r" -> "u" -> "n" // LInsert not exist pivot value - std::vector gp2_nodes {"w", "e", "r", "u", "n"}; + std::vector gp2_nodes{"w", "e", "r", "u", "n"}; s = db.RPush("GP2_LINSERT_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -298,11 +287,10 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, -1); - // ***************** Group 3 Test ***************** // "a" -> "p" -> "p" -> "l" -> "e" // LInsert expire list - std::vector gp3_nodes {"a", "p", "p", "l", "e"}; + std::vector gp3_nodes{"a", "p", "p", "l", "e"}; s = db.RPush("GP3_LINSERT_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -318,10 +306,9 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - // ***************** Group 4 Test ***************** // "a" - std::vector gp4_nodes {"a"}; + std::vector gp4_nodes{"a"}; s = db.RPush("GP4_LINSERT_KEY", gp4_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes.size(), num); @@ -335,10 +322,9 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(len_match(&db, "GP4_LINSERT_KEY", 2)); ASSERT_TRUE(elements_match(&db, "GP4_LINSERT_KEY", {"x", "a"})); - // ***************** Group 5 Test ***************** // "a" - std::vector gp5_nodes {"a"}; + std::vector gp5_nodes{"a"}; s = db.RPush("GP5_LINSERT_KEY", gp5_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes.size(), num); @@ -352,10 +338,9 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(len_match(&db, "GP5_LINSERT_KEY", 2)); ASSERT_TRUE(elements_match(&db, "GP5_LINSERT_KEY", {"a", "x"})); - // ***************** Group 6 Test ***************** // "a" -> "b" - std::vector gp6_nodes {"a", "b"}; + std::vector gp6_nodes{"a", "b"}; s = db.RPush("GP6_LINSERT_KEY", gp6_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp6_nodes.size(), num); @@ -369,10 +354,9 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(len_match(&db, "GP6_LINSERT_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP6_LINSERT_KEY", {"x", "a", "b"})); - // ***************** Group 7 Test ***************** // "a" -> "b" - std::vector gp7_nodes {"a", "b"}; + std::vector gp7_nodes{"a", "b"}; s = db.RPush("GP7_LINSERT_KEY", gp7_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp7_nodes.size(), num); @@ -386,10 +370,9 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(len_match(&db, "GP7_LINSERT_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP7_LINSERT_KEY", {"a", "x", "b"})); - // ***************** Group 8 Test ***************** // "a" -> "b" - std::vector gp8_nodes {"a", "b"}; + std::vector gp8_nodes{"a", "b"}; s = db.RPush("GP8_LINSERT_KEY", gp8_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp8_nodes.size(), num); @@ -403,10 +386,9 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(len_match(&db, "GP8_LINSERT_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP8_LINSERT_KEY", {"a", "x", "b"})); - // ***************** Group 9 Test ***************** // "a" -> "b" - std::vector gp9_nodes {"a", "b"}; + std::vector gp9_nodes{"a", "b"}; s = db.RPush("GP9_LINSERT_KEY", gp9_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp9_nodes.size(), num); @@ -420,10 +402,9 @@ TEST_F(ListsTest, LInsertTest) { ASSERT_TRUE(len_match(&db, "GP9_LINSERT_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP9_LINSERT_KEY", {"a", "b", "x"})); - // ***************** Group 10 Test ***************** // "1" -> "2" -> "3" - std::vector gp10_nodes {"1", "2", "3"}; + std::vector gp10_nodes{"1", "2", "3"}; s = db.RPush("GP10_LINSERT_KEY", gp10_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp10_nodes.size(), num); @@ -479,7 +460,7 @@ TEST_F(ListsTest, LLenTest) { // ***************** Group 1 Test ***************** // "l" -> "x" -> "a" - std::vector gp1_nodes {"a", "x", "l"}; + std::vector gp1_nodes{"a", "x", "l"}; s = db.LPush("GP1_LLEN_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); @@ -489,10 +470,9 @@ TEST_F(ListsTest, LLenTest) { ASSERT_TRUE(make_expired(&db, "GP1_LLEN_KEY")); ASSERT_TRUE(len_match(&db, "GP1_LLEN_KEY", 0)); - // ***************** Group 1 Test ***************** // "p" -> "e" -> "r" -> "g" - std::vector gp2_nodes {"g", "r", "e", "p"}; + std::vector gp2_nodes{"g", "r", "e", "p"}; s = db.LPush("GP2_LLEN_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -515,7 +495,7 @@ TEST_F(ListsTest, LPopTest) { // ***************** Group 1 Test ***************** // "l" -> "x" -> "a" - std::vector gp1_nodes {"a", "x", "l"}; + std::vector gp1_nodes{"a", "x", "l"}; s = db.LPush("GP1_LPOP_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); @@ -543,10 +523,9 @@ TEST_F(ListsTest, LPopTest) { s = db.LPop("GP1_LPOP_KEY", &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 2 Test ***************** // "p" -> "e" -> "r" -> "g" - std::vector gp2_nodes {"g", "r", "e", "p"}; + std::vector gp2_nodes{"g", "r", "e", "p"}; s = db.LPush("GP2_LPOP_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -559,10 +538,9 @@ TEST_F(ListsTest, LPopTest) { ASSERT_TRUE(len_match(&db, "GP2_LPOP_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP2_LPOP_KEY", {})); - // ***************** Group 3 Test ***************** // "p" -> "o" -> "m" -> "e" -> "i" -> "i" - std::vector gp3_nodes {"i", "i", "e", "m", "o", "p"}; + std::vector gp3_nodes{"i", "i", "e", "m", "o", "p"}; s = db.LPush("GP3_LPOP_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -591,17 +569,16 @@ TEST_F(ListsTest, LPushTest) { // ***************** Group 1 Test ***************** // "s" -> "l" -> "a" -> "s" -> "h" - std::vector gp1_nodes {"h", "s", "a", "l", "s"}; + std::vector gp1_nodes{"h", "s", "a", "l", "s"}; s = db.LPush("GP1_LPUSH_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); ASSERT_TRUE(len_match(&db, "GP1_LPUSH_KEY", gp1_nodes.size())); ASSERT_TRUE(elements_match(&db, "GP1_LPUSH_KEY", {"s", "l", "a", "s", "h"})); - // ***************** Group 2 Test ***************** // "a" -> "x" -> "l" - std::vector gp2_nodes1 {"l", "x", "a"}; + std::vector gp2_nodes1{"l", "x", "a"}; s = db.LPush("GP2_LPUSH_KEY", gp2_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes1.size(), num); @@ -609,7 +586,7 @@ TEST_F(ListsTest, LPushTest) { ASSERT_TRUE(elements_match(&db, "GP2_LPUSH_KEY", {"a", "x", "l"})); // "r" -> "o" -> "s" -> "e" - std::vector gp2_nodes2 {"e", "s", "o", "r"}; + std::vector gp2_nodes2{"e", "s", "o", "r"}; ASSERT_TRUE(make_expired(&db, "GP2_LPUSH_KEY")); s = db.LPush("GP2_LPUSH_KEY", gp2_nodes2, &num); ASSERT_TRUE(s.ok()); @@ -617,10 +594,9 @@ TEST_F(ListsTest, LPushTest) { ASSERT_TRUE(len_match(&db, "GP2_LPUSH_KEY", gp2_nodes2.size())); ASSERT_TRUE(elements_match(&db, "GP2_LPUSH_KEY", {"r", "o", "s", "e"})); - // ***************** Group 3 Test ***************** // "d" -> "a" -> "v" -> "i" -> "d" - std::vector gp3_nodes1 {"d", "i", "v", "a", "d"}; + std::vector gp3_nodes1{"d", "i", "v", "a", "d"}; s = db.LPush("GP3_LPUSH_KEY", gp3_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes1.size(), num); @@ -634,17 +610,16 @@ TEST_F(ListsTest, LPushTest) { ASSERT_TRUE(type_status[storage::DataType::kLists].ok()); // "g" -> "i" -> "l" -> "m" -> "o" -> "u" -> "r" - std::vector gp3_nodes2 {"r", "u", "o", "m", "l", "i", "g"}; + std::vector gp3_nodes2{"r", "u", "o", "m", "l", "i", "g"}; s = db.LPush("GP3_LPUSH_KEY", gp3_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes2.size(), num); ASSERT_TRUE(len_match(&db, "GP3_LPUSH_KEY", gp3_nodes2.size())); ASSERT_TRUE(elements_match(&db, "GP3_LPUSH_KEY", {"g", "i", "l", "m", "o", "u", "r"})); - // ***************** Group 4 Test ***************** // "b" -> "l" -> "u" -> "e" - std::vector gp4_nodes1 {"e", "u", "l", "b"}; + std::vector gp4_nodes1{"e", "u", "l", "b"}; s = db.LPush("GP4_LPUSH_KEY", gp4_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes1.size(), num); @@ -652,17 +627,16 @@ TEST_F(ListsTest, LPushTest) { ASSERT_TRUE(elements_match(&db, "GP4_LPUSH_KEY", {"b", "l", "u", "e"})); // "t" -> "h" -> "e" -> " " -> "b" -> "l" -> "u" -> "e" - std::vector gp4_nodes2 {" ", "e", "h", "t"}; + std::vector gp4_nodes2{" ", "e", "h", "t"}; s = db.LPush("GP4_LPUSH_KEY", gp4_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(8, num); ASSERT_TRUE(len_match(&db, "GP4_LPUSH_KEY", 8)); ASSERT_TRUE(elements_match(&db, "GP4_LPUSH_KEY", {"t", "h", "e", " ", "b", "l", "u", "e"})); - // ***************** Group 5 Test ***************** // "b" -> "l" -> "u" -> "e" - std::vector gp5_nodes1 {"e", "u", "l", "b"}; + std::vector gp5_nodes1{"e", "u", "l", "b"}; s = db.LPush("GP5_LPUSH_KEY", gp5_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes1.size(), num); @@ -672,17 +646,16 @@ TEST_F(ListsTest, LPushTest) { ASSERT_TRUE(make_expired(&db, "GP5_LPUSH_KEY")); // "t" -> "h" -> "e" -> " "; - std::vector gp5_nodes2 {" ", "e", "h", "t"}; + std::vector gp5_nodes2{" ", "e", "h", "t"}; s = db.LPush("GP5_LPUSH_KEY", gp5_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, num); ASSERT_TRUE(len_match(&db, "GP5_LPUSH_KEY", 4)); ASSERT_TRUE(elements_match(&db, "GP5_LPUSH_KEY", {"t", "h", "e", " "})); - // ***************** Group 6 Test ***************** // "b" -> "l" -> "u" -> "e" - std::vector gp6_nodes1 {"e", "u", "l", "b"}; + std::vector gp6_nodes1{"e", "u", "l", "b"}; s = db.LPush("GP6_LPUSH_KEY", gp6_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp6_nodes1.size(), num); @@ -711,7 +684,7 @@ TEST_F(ListsTest, LPushTest) { ASSERT_TRUE(elements_match(&db, "GP6_LPUSH_KEY", {})); // "t" -> "h" -> "e" -> " "; - std::vector gp6_nodes2 {" ", "e", "h", "t"}; + std::vector gp6_nodes2{" ", "e", "h", "t"}; s = db.LPush("GP6_LPUSH_KEY", gp6_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, num); @@ -730,7 +703,7 @@ TEST_F(ListsTest, LPushxTest) { // ***************** Group 1 Test ***************** // "o" -> "o" -> "o" - std::vector gp1_nodes1 {"o", "o", "o"}; + std::vector gp1_nodes1{"o", "o", "o"}; s = db.RPush("GP1_LPUSHX_KEY", gp1_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes1.size(), num); @@ -745,7 +718,7 @@ TEST_F(ListsTest, LPushxTest) { ASSERT_TRUE(elements_match(&db, "GP1_LPUSHX_KEY", {"x", "o", "o", "o"})); // "o" -> "o" -> "x" -> "o" -> "o" -> "o" - std::vector gp1_nodes2 {"o", "o"}; + std::vector gp1_nodes2{"o", "o"}; s = db.LPush("GP1_LPUSHX_KEY", gp1_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(num, 6); @@ -759,7 +732,6 @@ TEST_F(ListsTest, LPushxTest) { ASSERT_TRUE(len_match(&db, "GP1_LPUSHX_KEY", 7)); ASSERT_TRUE(elements_match(&db, "GP1_LPUSHX_KEY", {"x", "o", "o", "x", "o", "o", "o"})); - // ***************** Group 2 Test ***************** // LPushx not exist key s = db.LPushx("GP2_LPUSHX_KEY", "x", &num); @@ -767,11 +739,10 @@ TEST_F(ListsTest, LPushxTest) { ASSERT_TRUE(len_match(&db, "GP2_LPUSHX_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP2_LPUSHX_KEY", {})); - // ***************** Group 3 Test ***************** // "o" -> "o" -> "o" // LPushx timeout key - std::vector gp3_nodes {"o", "o", "o"}; + std::vector gp3_nodes{"o", "o", "o"}; s = db.RPush("GP3_LPUSHX_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -784,10 +755,9 @@ TEST_F(ListsTest, LPushxTest) { ASSERT_TRUE(len_match(&db, "GP3_LPUSHX_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP3_LPUSHX_KEY", {})); - // ***************** Group 4 Test ***************** // LPushx has been deleted key - std::vector gp4_nodes {"o", "o", "o"}; + std::vector gp4_nodes{"o", "o", "o"}; s = db.RPush("GP4_LPUSHX_KEY", gp4_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes.size(), num); @@ -812,7 +782,7 @@ TEST_F(ListsTest, LRangeTest) { // ***************** Group 1 Test ***************** // " " -> "a" -> "t" -> " " - std::vector gp1_nodes1 {" ", "a", "t", " "}; + std::vector gp1_nodes1{" ", "a", "t", " "}; s = db.RPush("GP1_LRANGE_KEY", gp1_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes1.size(), num); @@ -820,7 +790,7 @@ TEST_F(ListsTest, LRangeTest) { ASSERT_TRUE(elements_match(&db, "GP1_LRANGE_KEY", {" ", "a", "t", " "})); // "l" -> "i" -> "v" -> "e" -> " " -> "a" -> "t" -> " " - std::vector gp1_nodes2 {"e", "v", "i", "l"}; + std::vector gp1_nodes2{"e", "v", "i", "l"}; s = db.LPush("GP1_LRANGE_KEY", gp1_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes1.size() + gp1_nodes2.size(), num); @@ -830,37 +800,43 @@ TEST_F(ListsTest, LRangeTest) { // "l" -> "i" -> "v" -> "e" -> " " -> "a" -> "t" -> " " -> "p" -> "o" -> "m" -> "p" -> "e" -> "i" -> "i" // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp1_nodes3 {"p", "o", "m", "p", "e", "i", "i"}; + std::vector gp1_nodes3{"p", "o", "m", "p", "e", "i", "i"}; s = db.RPush("GP1_LRANGE_KEY", gp1_nodes3, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes1.size() + gp1_nodes2.size() + gp1_nodes3.size(), num); ASSERT_TRUE(len_match(&db, "GP1_LRANGE_KEY", gp1_nodes1.size() + gp1_nodes2.size() + gp1_nodes3.size())); - ASSERT_TRUE(elements_match(&db, "GP1_LRANGE_KEY", {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); + ASSERT_TRUE(elements_match(&db, "GP1_LRANGE_KEY", + {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); std::vector gp1_range_nodes; s = db.LRange("GP1_LRANGE_KEY", 0, -1, &gp1_range_nodes); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); + ASSERT_TRUE( + elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); gp1_range_nodes.clear(); s = db.LRange("GP1_LRANGE_KEY", 0, 14, &gp1_range_nodes); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); + ASSERT_TRUE( + elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); gp1_range_nodes.clear(); s = db.LRange("GP1_LRANGE_KEY", -15, -1, &gp1_range_nodes); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); + ASSERT_TRUE( + elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); gp1_range_nodes.clear(); s = db.LRange("GP1_LRANGE_KEY", 0, 100, &gp1_range_nodes); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); + ASSERT_TRUE( + elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); gp1_range_nodes.clear(); s = db.LRange("GP1_LRANGE_KEY", -100, -1, &gp1_range_nodes); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); + ASSERT_TRUE( + elements_match(gp1_range_nodes, {"l", "i", "v", "e", " ", "a", "t", " ", "p", "o", "m", "p", "e", "i", "i"})); gp1_range_nodes.clear(); s = db.LRange("GP1_LRANGE_KEY", 5, 6, &gp1_range_nodes); @@ -942,12 +918,11 @@ TEST_F(ListsTest, LRangeTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(elements_match(gp1_range_nodes, {"i"})); - // ***************** Group 2 Test ***************** // "a" // 0 // -1 - std::vector gp2_nodes {"a"}; + std::vector gp2_nodes{"a"}; s = db.RPush("GP2_LRANGE_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -1004,7 +979,6 @@ TEST_F(ListsTest, LRangeTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(elements_match(gp2_range_nodes, {})); - // ***************** Group 3 Test ***************** // LRange not exist key std::vector gp3_range_nodes; @@ -1012,13 +986,12 @@ TEST_F(ListsTest, LRangeTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(elements_match(gp3_range_nodes, {})); - // ***************** Group 4 Test ***************** // "n" -> "o" -> "w" // 0 1 2 // -3 -2 -1 // LRange timeout key - std::vector gp4_nodes {"n", "o", "w"}; + std::vector gp4_nodes{"n", "o", "w"}; s = db.RPush("GP4_LRANGE_KEY", gp4_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes.size(), num); @@ -1031,13 +1004,12 @@ TEST_F(ListsTest, LRangeTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(elements_match(gp4_range_nodes, {})); - // ***************** Group 5 Test ***************** // "t" -> "o" -> "u" -> "r" // 0 1 2 3 // -4 -3 -2 -1 // LRange has been deleted key - std::vector gp5_nodes {"t", "o", "u", "r"}; + std::vector gp5_nodes{"t", "o", "u", "r"}; s = db.RPush("GP5_LRANGE_KEY", gp5_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes.size(), num); @@ -1066,7 +1038,7 @@ TEST_F(ListsTest, LRemTest) { // "o" // 0 // -1 - std::vector gp1_nodes {"o"}; + std::vector gp1_nodes{"o"}; s = db.RPush("GP1_LREM_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); @@ -1097,12 +1069,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP1_LREM_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP1_LREM_KEY", {})); - // ***************** Group 2 Test ***************** // "o" // 0 // -1 - std::vector gp2_nodes {"o"}; + std::vector gp2_nodes{"o"}; s = db.RPush("GP2_LREM_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -1115,12 +1086,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP2_LREM_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP2_LREM_KEY", {})); - // ***************** Group 3 Test ***************** // "o" // 0 // -1 - std::vector gp3_nodes {"o"}; + std::vector gp3_nodes{"o"}; s = db.RPush("GP3_LREM_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -1133,12 +1103,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP3_LREM_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP3_LREM_KEY", {})); - // ***************** Group 4 Test ***************** // "o" -> "x" // 0 1 // -2 -1 - std::vector gp4_nodes {"o", "x"}; + std::vector gp4_nodes{"o", "x"}; s = db.RPush("GP4_LREM_KEY", gp4_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes.size(), num); @@ -1151,12 +1120,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP4_LREM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP4_LREM_KEY", {"o"})); - // ***************** Group 5 Test ***************** // "o" -> "x" // 0 1 // -2 -1 - std::vector gp5_nodes {"o", "x"}; + std::vector gp5_nodes{"o", "x"}; s = db.RPush("GP5_LREM_KEY", gp5_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes.size(), num); @@ -1169,12 +1137,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP5_LREM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP5_LREM_KEY", {"o"})); - // ***************** Group 6 Test ***************** // "o" -> "x" // 0 1 // -2 -1 - std::vector gp6_nodes {"o", "x"}; + std::vector gp6_nodes{"o", "x"}; s = db.RPush("GP6_LREM_KEY", gp6_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp6_nodes.size(), num); @@ -1187,12 +1154,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP6_LREM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP6_LREM_KEY", {"o"})); - // ***************** Group 7 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp7_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp7_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP7_LREM_KEY", gp7_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp7_nodes.size(), num); @@ -1205,12 +1171,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP7_LREM_KEY", 6)); ASSERT_TRUE(elements_match(&db, "GP7_LREM_KEY", {"o", "o", "o", "o", "o", "o"})); - // ***************** Group 8 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp8_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp8_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP8_LREM_KEY", gp8_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp8_nodes.size(), num); @@ -1223,12 +1188,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP8_LREM_KEY", 6)); ASSERT_TRUE(elements_match(&db, "GP8_LREM_KEY", {"o", "o", "o", "o", "o", "o"})); - // ***************** Group 9 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp9_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp9_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP9_LREM_KEY", gp9_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp9_nodes.size(), num); @@ -1241,12 +1205,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP9_LREM_KEY", 6)); ASSERT_TRUE(elements_match(&db, "GP9_LREM_KEY", {"o", "o", "o", "o", "o", "o"})); - // ***************** Group 10 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp10_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp10_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP10_LREM_KEY", gp10_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp10_nodes.size(), num); @@ -1259,12 +1222,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP10_LREM_KEY", 9)); ASSERT_TRUE(elements_match(&db, "GP10_LREM_KEY", {"o", "o", "o", "x", "o", "x", "o", "o", "x"})); - // ***************** Group 11 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp11_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp11_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP11_LREM_KEY", gp11_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp11_nodes.size(), num); @@ -1277,12 +1239,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP11_LREM_KEY", 7)); ASSERT_TRUE(elements_match(&db, "GP11_LREM_KEY", {"o", "o", "o", "o", "o", "o", "x"})); - // ***************** Group 12 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp12_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp12_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP12_LREM_KEY", gp12_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp12_nodes.size(), num); @@ -1295,12 +1256,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP12_LREM_KEY", 6)); ASSERT_TRUE(elements_match(&db, "GP12_LREM_KEY", {"o", "o", "o", "o", "o", "o"})); - // ***************** Group 13 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp13_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp13_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP13_LREM_KEY", gp13_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp13_nodes.size(), num); @@ -1313,12 +1273,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP13_LREM_KEY", 9)); ASSERT_TRUE(elements_match(&db, "GP13_LREM_KEY", {"o", "x", "o", "o", "x", "o", "x", "o", "o"})); - // ***************** Group 14 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp14_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp14_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP14_LREM_KEY", gp14_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp14_nodes.size(), num); @@ -1331,12 +1290,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP14_LREM_KEY", 8)); ASSERT_TRUE(elements_match(&db, "GP14_LREM_KEY", {"o", "x", "o", "o", "x", "o", "o", "o"})); - // ***************** Group 15 Test ***************** // "o" -> "x" -> "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" -> "x" // 0 1 2 3 4 5 6 7 8 9 // -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 - std::vector gp15_nodes {"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; + std::vector gp15_nodes{"o", "x", "o", "o", "x", "o", "x", "o", "o", "x"}; s = db.RPush("GP15_LREM_KEY", gp15_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp15_nodes.size(), num); @@ -1349,12 +1307,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP15_LREM_KEY", 7)); ASSERT_TRUE(elements_match(&db, "GP15_LREM_KEY", {"o", "x", "o", "o", "o", "o", "o"})); - // ***************** Group 16 Test ***************** // "o" -> "x" -> "x" -> "x" -> "x" -> "o" // 0 1 2 3 4 5 // -6 -5 -4 -3 -2 -1 - std::vector gp16_nodes {"o", "x", "x", "x", "x", "o"}; + std::vector gp16_nodes{"o", "x", "x", "x", "x", "o"}; s = db.RPush("GP16_LREM_KEY", gp16_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp16_nodes.size(), num); @@ -1367,12 +1324,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP16_LREM_KEY", 4)); ASSERT_TRUE(elements_match(&db, "GP16_LREM_KEY", {"o", "x", "x", "o"})); - // ***************** Group 17 Test ***************** // "o" -> "x" -> "x" -> "x" -> "x" -> "o" // 0 1 2 3 4 5 // -6 -5 -4 -3 -2 -1 - std::vector gp17_nodes {"o", "x", "x", "x", "x", "o"}; + std::vector gp17_nodes{"o", "x", "x", "x", "x", "o"}; s = db.RPush("GP17_LREM_KEY", gp17_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp17_nodes.size(), num); @@ -1385,12 +1341,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP17_LREM_KEY", 4)); ASSERT_TRUE(elements_match(&db, "GP17_LREM_KEY", {"o", "x", "x", "o"})); - // ***************** Group 18 Test ***************** // "o" -> "x" -> "x" -> "x" -> "x" -> "o" // 0 1 2 3 4 5 // -6 -5 -4 -3 -2 -1 - std::vector gp18_nodes {"o", "x", "x", "x", "x", "o"}; + std::vector gp18_nodes{"o", "x", "x", "x", "x", "o"}; s = db.RPush("GP18_LREM_KEY", gp18_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp18_nodes.size(), num); @@ -1403,12 +1358,11 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP18_LREM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP18_LREM_KEY", {"o", "x", "o"})); - // ***************** Group 19 Test ***************** // "o" -> "x" -> "x" -> "x" -> "x" -> "o" // 0 1 2 3 4 5 // -6 -5 -4 -3 -2 -1 - std::vector gp19_nodes {"o", "x", "x", "x", "x", "o"}; + std::vector gp19_nodes{"o", "x", "x", "x", "x", "o"}; s = db.RPush("GP19_LREM_KEY", gp19_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp19_nodes.size(), num); @@ -1421,11 +1375,10 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP19_LREM_KEY", 2)); ASSERT_TRUE(elements_match(&db, "GP19_LREM_KEY", {"o", "o"})); - // ***************** Group 20 Test ***************** // "o" -> "x" -> "o" // LRem timeout key - std::vector gp20_nodes {"o", "o", "o"}; + std::vector gp20_nodes{"o", "o", "o"}; s = db.RPush("GP20_LREM_KEY", gp20_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp20_nodes.size(), num); @@ -1439,7 +1392,6 @@ TEST_F(ListsTest, LRemTest) { ASSERT_TRUE(len_match(&db, "GP20_LREM_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP20_LREM_KEY", {})); - // ***************** Group 21 Test ***************** // LRem not exist key s = db.LRem("GP21_LREM_KEY", 0, "x", &num); @@ -1458,7 +1410,7 @@ TEST_F(ListsTest, LSetTest) { // "o" -> "o" -> "o" -> "o" -> "o" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp1_nodes1 {"o", "o", "o", "o", "o"}; + std::vector gp1_nodes1{"o", "o", "o", "o", "o"}; s = db.LPush("GP1_LSET_KEY", gp1_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes1.size(), num); @@ -1489,11 +1441,10 @@ TEST_F(ListsTest, LSetTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(elements_match(&db, "GP1_LSET_KEY", {"o", "o", "x", "o", "x"})); - // "o" -> "o" -> "x" -> "o" -> "x" -> "o" -> "o" // 0 1 2 3 4 5 6 // -7 -6 -5 -4 -3 -2 -1 - std::vector gp1_nodes2 {"o", "o"}; + std::vector gp1_nodes2{"o", "o"}; s = db.RPush("GP1_LSET_KEY", gp1_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes1.size() + gp1_nodes2.size(), num); @@ -1508,10 +1459,9 @@ TEST_F(ListsTest, LSetTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(elements_match(&db, "GP1_LSET_KEY", {"x", "o", "x", "o", "x", "x", "o"})); - // ***************** Group 2 Test ***************** // LSet expire key - std::vector gp2_nodes {"o", "o", "o"}; + std::vector gp2_nodes{"o", "o", "o"}; s = db.LPush("GP2_LSET_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -1522,15 +1472,13 @@ TEST_F(ListsTest, LSetTest) { s = db.LSet("GP2_LSET_KEY", 0, "x"); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 3 Test ***************** // LSet not exist key s = db.LSet("GP3_LSET_KEY", 0, "x"); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 4 Test ***************** - std::vector gp4_nodes {"o"}; + std::vector gp4_nodes{"o"}; s = db.LPush("GP4_LSET_KEY", gp4_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes.size(), num); @@ -1552,13 +1500,12 @@ TEST_F(ListsTest, LSetTest) { // LTrim TEST_F(ListsTest, LTrimTest) { - uint64_t num; // ***************** Group 1 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp1_nodes {"a", "b", "c", "d", "e"}; + std::vector gp1_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP1_LTRIM_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); @@ -1585,12 +1532,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP1_LTRIM_KEY", gp1_nodes.size())); ASSERT_TRUE(elements_match(&db, "GP1_LTRIM_KEY", {"a", "b", "c", "d", "e"})); - // ***************** Group 2 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp2_nodes {"a", "b", "c", "d", "e"}; + std::vector gp2_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP2_LTRIM_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -1602,12 +1548,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP2_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP2_LTRIM_KEY", {"a", "b", "c"})); - // ***************** Group 3 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp3_nodes {"a", "b", "c", "d", "e"}; + std::vector gp3_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP3_LTRIM_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -1619,12 +1564,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP3_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP3_LTRIM_KEY", {"a", "b", "c"})); - // ***************** Group 4 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp4_nodes {"a", "b", "c", "d", "e"}; + std::vector gp4_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP4_LTRIM_KEY", gp4_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes.size(), num); @@ -1636,12 +1580,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP4_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP4_LTRIM_KEY", {"a", "b", "c"})); - // ***************** Group 5 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp5_nodes {"a", "b", "c", "d", "e"}; + std::vector gp5_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP5_LTRIM_KEY", gp5_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes.size(), num); @@ -1653,12 +1596,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP5_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP5_LTRIM_KEY", {"a", "b", "c"})); - // ***************** Group 6 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp6_nodes {"a", "b", "c", "d", "e"}; + std::vector gp6_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP6_LTRIM_KEY", gp6_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp6_nodes.size(), num); @@ -1670,12 +1612,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP6_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP6_LTRIM_KEY", {"a", "b", "c"})); - // ***************** Group 7 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp7_nodes {"a", "b", "c", "d", "e"}; + std::vector gp7_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP7_LTRIM_KEY", gp7_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp7_nodes.size(), num); @@ -1687,12 +1628,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP7_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP7_LTRIM_KEY", {"a", "b", "c"})); - // ***************** Group 8 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp8_nodes {"a", "b", "c", "d", "e"}; + std::vector gp8_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP8_LTRIM_KEY", gp8_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp8_nodes.size(), num); @@ -1704,12 +1644,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP8_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP8_LTRIM_KEY", {"b", "c", "d"})); - // ***************** Group 9 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp9_nodes {"a", "b", "c", "d", "e"}; + std::vector gp9_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP9_LTRIM_KEY", gp9_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp9_nodes.size(), num); @@ -1721,12 +1660,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP9_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP9_LTRIM_KEY", {"b", "c", "d"})); - // ***************** Group 10 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp10_nodes {"a", "b", "c", "d", "e"}; + std::vector gp10_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP10_LTRIM_KEY", gp10_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp10_nodes.size(), num); @@ -1738,12 +1676,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP10_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP10_LTRIM_KEY", {"b", "c", "d"})); - // ***************** Group 11 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp11_nodes {"a", "b", "c", "d", "e"}; + std::vector gp11_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP11_LTRIM_KEY", gp11_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp11_nodes.size(), num); @@ -1755,12 +1692,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP11_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP11_LTRIM_KEY", {"b", "c", "d"})); - // ***************** Group 12 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp12_nodes {"a", "b", "c", "d", "e"}; + std::vector gp12_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP12_LTRIM_KEY", gp12_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp12_nodes.size(), num); @@ -1772,12 +1708,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP12_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP12_LTRIM_KEY", {"c"})); - // ***************** Group 13 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp13_nodes {"a", "b", "c", "d", "e"}; + std::vector gp13_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP13_LTRIM_KEY", gp13_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp13_nodes.size(), num); @@ -1789,12 +1724,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP13_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP13_LTRIM_KEY", {"c"})); - // ***************** Group 14 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp14_nodes {"a", "b", "c", "d", "e"}; + std::vector gp14_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP14_LTRIM_KEY", gp14_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp14_nodes.size(), num); @@ -1806,12 +1740,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP14_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP14_LTRIM_KEY", {"c"})); - // ***************** Group 15 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp15_nodes {"a", "b", "c", "d", "e"}; + std::vector gp15_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP15_LTRIM_KEY", gp15_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp15_nodes.size(), num); @@ -1823,12 +1756,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP15_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP15_LTRIM_KEY", {"c", "d", "e"})); - // ***************** Group 16 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp16_nodes {"a", "b", "c", "d", "e"}; + std::vector gp16_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP16_LTRIM_KEY", gp16_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp16_nodes.size(), num); @@ -1840,12 +1772,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP16_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP16_LTRIM_KEY", {"c", "d", "e"})); - // ***************** Group 17 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp17_nodes {"a", "b", "c", "d", "e"}; + std::vector gp17_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP17_LTRIM_KEY", gp17_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp17_nodes.size(), num); @@ -1857,12 +1788,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP17_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP17_LTRIM_KEY", {"c", "d", "e"})); - // ***************** Group 18 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp18_nodes {"a", "b", "c", "d", "e"}; + std::vector gp18_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP18_LTRIM_KEY", gp18_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp18_nodes.size(), num); @@ -1874,12 +1804,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP18_LTRIM_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP18_LTRIM_KEY", {"c", "d", "e"})); - // ***************** Group 19 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp19_nodes {"a", "b", "c", "d", "e"}; + std::vector gp19_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP19_LTRIM_KEY", gp19_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp19_nodes.size(), num); @@ -1891,12 +1820,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP19_LTRIM_KEY", 5)); ASSERT_TRUE(elements_match(&db, "GP19_LTRIM_KEY", {"a", "b", "c", "d", "e"})); - // ***************** Group 20 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp20_nodes {"a", "b", "c", "d", "e"}; + std::vector gp20_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP20_LTRIM_KEY", gp20_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp20_nodes.size(), num); @@ -1908,12 +1836,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP20_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP20_LTRIM_KEY", {"a"})); - // ***************** Group 21 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp21_nodes {"a", "b", "c", "d", "e"}; + std::vector gp21_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP21_LTRIM_KEY", gp21_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp21_nodes.size(), num); @@ -1925,12 +1852,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP21_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP21_LTRIM_KEY", {"a"})); - // ***************** Group 22 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp22_nodes {"a", "b", "c", "d", "e"}; + std::vector gp22_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP22_LTRIM_KEY", gp22_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp22_nodes.size(), num); @@ -1942,12 +1868,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP22_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP22_LTRIM_KEY", {"a"})); - // ***************** Group 23 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp23_nodes {"a", "b", "c", "d", "e"}; + std::vector gp23_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP23_LTRIM_KEY", gp23_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp23_nodes.size(), num); @@ -1959,12 +1884,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP23_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP23_LTRIM_KEY", {"a"})); - // ***************** Group 24 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp24_nodes {"a", "b", "c", "d", "e"}; + std::vector gp24_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP24_LTRIM_KEY", gp24_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp24_nodes.size(), num); @@ -1976,12 +1900,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP24_LTRIM_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP24_LTRIM_KEY", {})); - // ***************** Group 25 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp25_nodes {"a", "b", "c", "d", "e"}; + std::vector gp25_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP25_LTRIM_KEY", gp25_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp25_nodes.size(), num); @@ -1993,12 +1916,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP25_LTRIM_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP25_LTRIM_KEY", {})); - // ***************** Group 26 Test ***************** // "a" -> "b" -> "c" -> "d" -> "e" // 0 1 2 3 4 // -5 -4 -3 -2 -1 - std::vector gp26_nodes {"a", "b", "c", "d", "e"}; + std::vector gp26_nodes{"a", "b", "c", "d", "e"}; s = db.RPush("GP26_LTRIM_KEY", gp26_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp26_nodes.size(), num); @@ -2010,12 +1932,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP26_LTRIM_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP26_LTRIM_KEY", {})); - // ***************** Group 27 Test ***************** // "a" -> "b" // 0 1 // -2 -1 - std::vector gp27_nodes {"a", "b"}; + std::vector gp27_nodes{"a", "b"}; s = db.RPush("GP27_LTRIM_KEY", gp27_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp27_nodes.size(), num); @@ -2027,12 +1948,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP27_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP27_LTRIM_KEY", {"a"})); - // ***************** Group 28 Test ***************** // "a" -> "b" // 0 1 // -2 -1 - std::vector gp28_nodes {"a", "b"}; + std::vector gp28_nodes{"a", "b"}; s = db.RPush("GP28_LTRIM_KEY", gp28_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp28_nodes.size(), num); @@ -2044,12 +1964,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP28_LTRIM_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP28_LTRIM_KEY", {"b"})); - // ***************** Group 29 Test ***************** // "a" -> "b" // 0 1 // -2 -1 - std::vector gp29_nodes {"a", "b"}; + std::vector gp29_nodes{"a", "b"}; s = db.RPush("GP29_LTRIM_KEY", gp29_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp29_nodes.size(), num); @@ -2061,12 +1980,11 @@ TEST_F(ListsTest, LTrimTest) { ASSERT_TRUE(len_match(&db, "GP29_LTRIM_KEY", 2)); ASSERT_TRUE(elements_match(&db, "GP29_LTRIM_KEY", {"a", "b"})); - // ***************** Group 30 Test ***************** // "a" -> "b" // 0 1 // -2 -1 - std::vector gp30_nodes {"a", "b"}; + std::vector gp30_nodes{"a", "b"}; s = db.RPush("GP30_LTRIM_KEY", gp30_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp30_nodes.size(), num); @@ -2085,7 +2003,7 @@ TEST_F(ListsTest, RPopTest) { // ***************** Group 1 Test ***************** // "a" -> "x" -> "l" - std::vector gp1_nodes {"l", "x", "a"}; + std::vector gp1_nodes{"l", "x", "a"}; s = db.LPush("GP1_RPOP_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); @@ -2113,10 +2031,9 @@ TEST_F(ListsTest, RPopTest) { s = db.LPop("GP1_RPOP_KEY", &element); ASSERT_TRUE(s.IsNotFound()); - // ***************** Group 2 Test ***************** // "g" -> "r" -> "e" -> "p" - std::vector gp2_nodes {"p", "e", "r", "g"}; + std::vector gp2_nodes{"p", "e", "r", "g"}; s = db.LPush("GP2_RPOP_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -2129,10 +2046,9 @@ TEST_F(ListsTest, RPopTest) { ASSERT_TRUE(len_match(&db, "GP2_RPOP_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP2_RPOP_KEY", {})); - // ***************** Group 3 Test ***************** // "p" -> "o" -> "m" -> "e" -> "i" -> "i" - std::vector gp3_nodes {"i", "i", "e", "m", "o", "p"}; + std::vector gp3_nodes{"i", "i", "e", "m", "o", "p"}; s = db.LPush("GP3_RPOP_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -2166,7 +2082,7 @@ TEST_F(ListsTest, RPoplpushTest) { // source // destination "o" // - std::vector gp1_nodes {"o"}; + std::vector gp1_nodes{"o"}; s = db.RPush("GP1_RPOPLPUSH_SOURCE_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); @@ -2181,7 +2097,6 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP1_RPOPLPUSH_DESTINATION_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP1_RPOPLPUSH_DESTINATION_KEY", {"o"})); - // ***************** Group 2 Test ***************** // source // destination "o" @@ -2189,7 +2104,7 @@ TEST_F(ListsTest, RPoplpushTest) { // source // destination "o" // - std::vector gp2_nodes {"o"}; + std::vector gp2_nodes{"o"}; s = db.RPush("GP2_RPOPLPUSH_DESTINATION_KEY", gp2_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes.size(), num); @@ -2204,7 +2119,6 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP2_RPOPLPUSH_DESTINATION_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP2_RPOPLPUSH_DESTINATION_KEY", {"o"})); - // ***************** Group 3 Test ***************** // source "a" -> "b" -> "c" -> "o" // destination "a" -> "b" -> "c" @@ -2221,13 +2135,13 @@ TEST_F(ListsTest, RPoplpushTest) { // source // destination "a" -> "b" -> "c" -> "o" -> "a" -> "b" -> "c" // - std::vector gp3_nodes1 {"a", "b", "c", "o"}; - std::vector gp3_nodes2 {"a", "b", "c"}; + std::vector gp3_nodes1{"a", "b", "c", "o"}; + std::vector gp3_nodes2{"a", "b", "c"}; s = db.RPush("GP3_RPOPLPUSH_SOURCE_KEY", gp3_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes1.size(), num); ASSERT_TRUE(len_match(&db, "GP3_RPOPLPUSH_SOURCE_KEY", gp3_nodes1.size())); - ASSERT_TRUE(elements_match(&db, "GP3_RPOPLPUSH_SOURCE_KEY", {"a", "b","c", "o"})); + ASSERT_TRUE(elements_match(&db, "GP3_RPOPLPUSH_SOURCE_KEY", {"a", "b", "c", "o"})); s = db.RPush("GP3_RPOPLPUSH_DESTINATION_KEY", gp3_nodes2, &num); ASSERT_TRUE(s.ok()); @@ -2270,7 +2184,6 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP3_RPOPLPUSH_DESTINATION_KEY", 7)); ASSERT_TRUE(elements_match(&db, "GP3_RPOPLPUSH_DESTINATION_KEY", {"a", "b", "c", "o", "a", "b", "c"})); - // ***************** Group 4 Test ***************** // source (empty list); // destination "a" -> "b" -> "c" @@ -2278,8 +2191,8 @@ TEST_F(ListsTest, RPoplpushTest) { // source (empty list); // destination "a" -> "b" -> "c" // - std::vector gp4_nodes1 {"o"}; - std::vector gp4_nodes2 {"a", "b", "c"}; + std::vector gp4_nodes1{"o"}; + std::vector gp4_nodes2{"a", "b", "c"}; s = db.RPush("GP4_RPOPLPUSH_SOURCE_KEY", gp4_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes1.size(), num); @@ -2305,7 +2218,6 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP4_RPOPLPUSH_DESTINATION_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP4_RPOPLPUSH_DESTINATION_KEY", {"a", "b", "c"})); - // ***************** Group 5 Test ***************** // source "a" -> "b" -> "c" // destination (empty list); @@ -2313,8 +2225,8 @@ TEST_F(ListsTest, RPoplpushTest) { // source "a" -> "b" // destination "c" // - std::vector gp5_nodes1 {"a", "b", "c"}; - std::vector gp5_nodes2 {"o"}; + std::vector gp5_nodes1{"a", "b", "c"}; + std::vector gp5_nodes2{"o"}; s = db.RPush("GP5_RPOPLPUSH_SOURCE_KEY", gp5_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes1.size(), num); @@ -2340,7 +2252,6 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP5_RPOPLPUSH_DESTINATION_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP5_RPOPLPUSH_DESTINATION_KEY", {"c"})); - // ***************** Group 6 Test ***************** // source "a" -> "b" -> "c" (timeout list); // destination "x" -> "y" -> "z" @@ -2348,8 +2259,8 @@ TEST_F(ListsTest, RPoplpushTest) { // source "a" -> "b" -> "c" (timeout list); // destination "x" -> "y" -> "z" // - std::vector gp6_nodes1 {"a", "b", "c"}; - std::vector gp6_nodes2 {"x", "y", "z"}; + std::vector gp6_nodes1{"a", "b", "c"}; + std::vector gp6_nodes2{"x", "y", "z"}; s = db.RPush("GP6_RPOPLPUSH_SOURCE_KEY", gp6_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp6_nodes1.size(), num); @@ -2371,7 +2282,6 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP6_RPOPLPUSH_DESTINATION_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP6_RPOPLPUSH_DESTINATION_KEY", {"x", "y", "z"})); - // ***************** Group 7 Test ***************** // source "a" -> "b" -> "c" // destination "x" -> "y" -> "z" (timeout list); @@ -2379,8 +2289,8 @@ TEST_F(ListsTest, RPoplpushTest) { // source "a" -> "b" // destination "c" // - std::vector gp7_nodes1 {"a", "b", "c"}; - std::vector gp7_nodes2 {"x", "y", "z"}; + std::vector gp7_nodes1{"a", "b", "c"}; + std::vector gp7_nodes2{"x", "y", "z"}; s = db.RPush("GP7_RPOPLPUSH_SOURCE_KEY", gp7_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp7_nodes1.size(), num); @@ -2402,13 +2312,12 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP7_RPOPLPUSH_DESTINATION_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP7_RPOPLPUSH_DESTINATION_KEY", {"c"})); - // ***************** Group 8 Test ***************** // source "a" -> "b" -> "c" // ----------------after rpoplpush----------------- // source "c" -> "a" -> "b" // - std::vector gp8_nodes {"a", "b", "c"}; + std::vector gp8_nodes{"a", "b", "c"}; s = db.RPush("GP8_RPOPLPUSH_SOURCE_KEY", gp8_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp8_nodes.size(), num); @@ -2421,13 +2330,12 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP8_RPOPLPUSH_SOURCE_KEY", 3)); ASSERT_TRUE(elements_match(&db, "GP8_RPOPLPUSH_SOURCE_KEY", {"c", "a", "b"})); - // ***************** Group 9 Test ***************** // source "a" -> "b" -> "c" (timeout list) // ----------------after rpoplpush----------------- // source "a" -> "b" -> "c" (timeout list) // - std::vector gp9_nodes {"a", "b", "c"}; + std::vector gp9_nodes{"a", "b", "c"}; s = db.RPush("GP9_RPOPLPUSH_SOURCE_KEY", gp9_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp9_nodes.size(), num); @@ -2443,13 +2351,12 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP9_RPOPLPUSH_SOURCE_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP9_RPOPLPUSH_SOURCE_KEY", {})); - // ***************** Group 10 Test ***************** // source "o" // ----------------after rpoplpush----------------- // source "o" // - std::vector gp10_nodes {"o"}; + std::vector gp10_nodes{"o"}; s = db.RPush("GP10_RPOPLPUSH_SOURCE_KEY", gp10_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp10_nodes.size(), num); @@ -2462,7 +2369,6 @@ TEST_F(ListsTest, RPoplpushTest) { ASSERT_TRUE(len_match(&db, "GP10_RPOPLPUSH_SOURCE_KEY", 1)); ASSERT_TRUE(elements_match(&db, "GP10_RPOPLPUSH_SOURCE_KEY", {"o"})); - // ***************** Group 11 Test ***************** // source "a" -> "b" -> "c" // destination "x" -> "y" -> "z" (TTL 100); @@ -2472,8 +2378,8 @@ TEST_F(ListsTest, RPoplpushTest) { // source "a" -> "b" // destination "c" (TTL -1) // - std::vector gp11_nodes1 {"a", "b", "c"}; - std::vector gp11_nodes2 {"x", "y", "z"}; + std::vector gp11_nodes1{"a", "b", "c"}; + std::vector gp11_nodes2{"x", "y", "z"}; s = db.RPush("GP11_RPOPLPUSH_SOURCE_KEY", gp11_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp11_nodes1.size(), num); @@ -2523,17 +2429,16 @@ TEST_F(ListsTest, RPushTest) { // ***************** Group 1 Test ***************** // "s" -> "l" -> "a" -> "s" -> "h" - std::vector gp1_nodes {"s", "l", "a", "s", "h"}; + std::vector gp1_nodes{"s", "l", "a", "s", "h"}; s = db.RPush("GP1_RPUSH_KEY", gp1_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes.size(), num); ASSERT_TRUE(len_match(&db, "GP1_RPUSH_KEY", gp1_nodes.size())); ASSERT_TRUE(elements_match(&db, "GP1_RPUSH_KEY", {"s", "l", "a", "s", "h"})); - // ***************** Group 2 Test ***************** // "a" -> "x" -> "l" - std::vector gp2_nodes1 {"a", "x", "l"}; + std::vector gp2_nodes1{"a", "x", "l"}; s = db.RPush("GP2_RPUSH_KEY", gp2_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp2_nodes1.size(), num); @@ -2541,7 +2446,7 @@ TEST_F(ListsTest, RPushTest) { ASSERT_TRUE(elements_match(&db, "GP2_RPUSH_KEY", {"a", "x", "l"})); // "r" -> "o" -> "s" -> "e" - std::vector gp2_nodes2 {"r", "o", "s", "e"}; + std::vector gp2_nodes2{"r", "o", "s", "e"}; ASSERT_TRUE(make_expired(&db, "GP2_RPUSH_KEY")); s = db.RPush("GP2_RPUSH_KEY", gp2_nodes2, &num); ASSERT_TRUE(s.ok()); @@ -2549,10 +2454,9 @@ TEST_F(ListsTest, RPushTest) { ASSERT_TRUE(len_match(&db, "GP2_RPUSH_KEY", gp2_nodes2.size())); ASSERT_TRUE(elements_match(&db, "GP2_RPUSH_KEY", {"r", "o", "s", "e"})); - // ***************** Group 3 Test ***************** // "d" -> "a" -> "v" -> "i" -> "d" - std::vector gp3_nodes1 {"d", "a", "v", "i", "d"}; + std::vector gp3_nodes1{"d", "a", "v", "i", "d"}; s = db.RPush("GP3_RPUSH_KEY", gp3_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes1.size(), num); @@ -2566,17 +2470,16 @@ TEST_F(ListsTest, RPushTest) { ASSERT_TRUE(type_status[storage::DataType::kLists].ok()); // "g" -> "i" -> "l" -> "m" -> "o" -> "u" -> "r" - std::vector gp3_nodes2 {"g", "i", "l", "m", "o", "u", "r"}; + std::vector gp3_nodes2{"g", "i", "l", "m", "o", "u", "r"}; s = db.RPush("GP3_RPUSH_KEY", gp3_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes2.size(), num); ASSERT_TRUE(len_match(&db, "GP3_RPUSH_KEY", gp3_nodes2.size())); ASSERT_TRUE(elements_match(&db, "GP3_RPUSH_KEY", {"g", "i", "l", "m", "o", "u", "r"})); - // ***************** Group 4 Test ***************** // "t" -> "h" -> "e" -> " " - std::vector gp4_nodes1 {"t", "h", "e", " "}; + std::vector gp4_nodes1{"t", "h", "e", " "}; s = db.RPush("GP4_RPUSH_KEY", gp4_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes1.size(), num); @@ -2584,17 +2487,16 @@ TEST_F(ListsTest, RPushTest) { ASSERT_TRUE(elements_match(&db, "GP4_RPUSH_KEY", {"t", "h", "e", " "})); // "t" -> "h" -> "e" -> " " -> "b" -> "l" -> "u" -> "e" - std::vector gp4_nodes2 {"b", "l", "u", "e"}; + std::vector gp4_nodes2{"b", "l", "u", "e"}; s = db.RPush("GP4_RPUSH_KEY", gp4_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(8, num); ASSERT_TRUE(len_match(&db, "GP4_RPUSH_KEY", 8)); ASSERT_TRUE(elements_match(&db, "GP4_RPUSH_KEY", {"t", "h", "e", " ", "b", "l", "u", "e"})); - // ***************** Group 5 Test ***************** // "t" -> "h" -> "e" - std::vector gp5_nodes1 {"t", "h", "e"}; + std::vector gp5_nodes1{"t", "h", "e"}; s = db.RPush("GP5_RPUSH_KEY", gp5_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp5_nodes1.size(), num); @@ -2604,17 +2506,16 @@ TEST_F(ListsTest, RPushTest) { ASSERT_TRUE(make_expired(&db, "GP5_RPUSH_KEY")); // "b" -> "l" -> "u" -> "e" - std::vector gp5_nodes2 {"b", "l", "u", "e"}; + std::vector gp5_nodes2{"b", "l", "u", "e"}; s = db.RPush("GP5_RPUSH_KEY", gp5_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, num); ASSERT_TRUE(len_match(&db, "GP5_RPUSH_KEY", 4)); ASSERT_TRUE(elements_match(&db, "GP5_RPUSH_KEY", {"b", "l", "u", "e"})); - // ***************** Group 6 Test ***************** // "b" -> "l" -> "u" -> "e" - std::vector gp6_nodes1 {"b", "l", "u", "e"}; + std::vector gp6_nodes1{"b", "l", "u", "e"}; s = db.RPush("GP6_RPUSH_KEY", gp6_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp6_nodes1.size(), num); @@ -2643,7 +2544,7 @@ TEST_F(ListsTest, RPushTest) { ASSERT_TRUE(elements_match(&db, "GP6_RPUSH_KEY", {})); // "t" -> "h" -> "e" - std::vector gp6_nodes2 {"t", "h", "e"}; + std::vector gp6_nodes2{"t", "h", "e"}; s = db.RPush("GP6_RPUSH_KEY", gp6_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, num); @@ -2662,7 +2563,7 @@ TEST_F(ListsTest, RPushxTest) { // ***************** Group 1 Test ***************** // "o" -> "o" -> "o" - std::vector gp1_nodes1 {"o", "o", "o"}; + std::vector gp1_nodes1{"o", "o", "o"}; s = db.LPush("GP1_RPUSHX_KEY", gp1_nodes1, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp1_nodes1.size(), num); @@ -2677,7 +2578,7 @@ TEST_F(ListsTest, RPushxTest) { ASSERT_TRUE(elements_match(&db, "GP1_RPUSHX_KEY", {"o", "o", "o", "x"})); // "o" -> "o" -> "o" -> "x" -> "o" -> "o" - std::vector gp1_nodes2 {"o", "o"}; + std::vector gp1_nodes2{"o", "o"}; s = db.RPush("GP1_RPUSHX_KEY", gp1_nodes2, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(num, 6); @@ -2690,7 +2591,6 @@ TEST_F(ListsTest, RPushxTest) { ASSERT_TRUE(len_match(&db, "GP1_RPUSHX_KEY", 7)); ASSERT_TRUE(elements_match(&db, "GP1_RPUSHX_KEY", {"o", "o", "o", "x", "o", "o", "x"})); - // ***************** Group 2 Test ***************** // RPushx not exist key s = db.RPushx("GP2_RPUSHX_KEY", "x", &num); @@ -2698,11 +2598,10 @@ TEST_F(ListsTest, RPushxTest) { ASSERT_TRUE(len_match(&db, "GP2_RPUSHX_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP2_RPUSHX_KEY", {})); - // ***************** Group 3 Test ***************** // "o" -> "o" -> "o" // RPushx timeout key - std::vector gp3_nodes {"o", "o", "o"}; + std::vector gp3_nodes{"o", "o", "o"}; s = db.RPush("GP3_RPUSHX_KEY", gp3_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp3_nodes.size(), num); @@ -2715,10 +2614,9 @@ TEST_F(ListsTest, RPushxTest) { ASSERT_TRUE(len_match(&db, "GP3_RPUSHX_KEY", 0)); ASSERT_TRUE(elements_match(&db, "GP3_RPUSHX_KEY", {})); - // ***************** Group 4 Test ***************** // RPushx has been deleted key - std::vector gp4_nodes {"o", "o", "o"}; + std::vector gp4_nodes{"o", "o", "o"}; s = db.RPush("GP4_RPUSHX_KEY", gp4_nodes, &num); ASSERT_TRUE(s.ok()); ASSERT_EQ(gp4_nodes.size(), num); diff --git a/src/storage/tests/lru_cache_test.cc b/src/storage/tests/lru_cache_test.cc index 19ef159be6..82d3e0e1ae 100644 --- a/src/storage/tests/lru_cache_test.cc +++ b/src/storage/tests/lru_cache_test.cc @@ -5,8 +5,8 @@ #include -#include "storage/storage.h" #include "src/lru_cache.h" +#include "storage/storage.h" using namespace storage; @@ -120,7 +120,6 @@ TEST(LRUCacheTest, TestLookupCase1) { ASSERT_TRUE(lru_cache.LRUAsExpected({{"k5", "v5"}, {"k4", "v4"}, {"k1", "v1"}, {"k3", "v3"}, {"k2", "v2"}})); } - TEST(LRUCacheTest, TestInsertCase1) { Status s; storage::LRUCache lru_cache; @@ -146,7 +145,7 @@ TEST(LRUCacheTest, TestInsertCase1) { // ***************** Step 3 ***************** // (k3, v3) -> (k2, v2) -> (k1, v1) - s = lru_cache.Insert("k3","v3"); + s = lru_cache.Insert("k3", "v3"); ASSERT_TRUE(s.ok()); ASSERT_EQ(lru_cache.Size(), 3); ASSERT_EQ(lru_cache.TotalCharge(), 3); @@ -305,7 +304,6 @@ TEST(LRUCacheTest, TestInsertCase3) { ASSERT_TRUE(lru_cache.LRUAsExpected({{"k6", "v6"}})); } - TEST(LRUCacheTest, TestInsertCase4) { Status s; storage::LRUCache lru_cache; diff --git a/src/storage/tests/options_test.cc b/src/storage/tests/options_test.cc index 6e5e22b5c0..1c030726ef 100644 --- a/src/storage/tests/options_test.cc +++ b/src/storage/tests/options_test.cc @@ -11,13 +11,13 @@ using namespace storage; -class StorageOptionsTest: public ::testing::Test { - public: +class StorageOptionsTest : public ::testing::Test { + public: StorageOptionsTest() = default; virtual ~StorageOptionsTest() = default; - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Status s; @@ -25,29 +25,29 @@ class StorageOptionsTest: public ::testing::Test { // ResetOptions TEST_F(StorageOptionsTest, ResetOptionsTest) { - std::unordered_map cf_options_map {{"write_buffer_size", "4096"}, - {"max_write_buffer_number", "10"}}; + std::unordered_map cf_options_map{{"write_buffer_size", "4096"}, + {"max_write_buffer_number", "10"}}; s = storage_options.ResetOptions(OptionType::kColumnFamily, cf_options_map); ASSERT_TRUE(s.ok()); ASSERT_EQ(storage_options.options.write_buffer_size, 4096); ASSERT_EQ(storage_options.options.max_write_buffer_number, 10); - std::unordered_map invalid_cf_options_map {{"write_buffer_size", "abc"}, - {"max_write_buffer_number", "0x33"}}; + std::unordered_map invalid_cf_options_map{{"write_buffer_size", "abc"}, + {"max_write_buffer_number", "0x33"}}; s = storage_options.ResetOptions(OptionType::kColumnFamily, invalid_cf_options_map); ASSERT_FALSE(s.ok()); ASSERT_EQ(storage_options.options.write_buffer_size, 4096); ASSERT_EQ(storage_options.options.max_write_buffer_number, 10); - std::unordered_map db_options_map {{"max_open_files", "16"}, - {"max_background_compactions", "32"}}; + std::unordered_map db_options_map{{"max_open_files", "16"}, + {"max_background_compactions", "32"}}; s = storage_options.ResetOptions(OptionType::kDB, db_options_map); ASSERT_TRUE(s.ok()); ASSERT_EQ(storage_options.options.max_open_files, 16); ASSERT_EQ(storage_options.options.max_background_compactions, 32); - std::unordered_map invalid_db_options_map {{"max_open_files", "a"}, - {"max_background_compactions", "bac"}}; + std::unordered_map invalid_db_options_map{{"max_open_files", "a"}, + {"max_background_compactions", "bac"}}; s = storage_options.ResetOptions(OptionType::kDB, invalid_db_options_map); ASSERT_FALSE(s.ok()); ASSERT_EQ(storage_options.options.max_open_files, 16); diff --git a/src/storage/tests/sets_test.cc b/src/storage/tests/sets_test.cc index 72adbc8ca0..0867d4d3d4 100644 --- a/src/storage/tests/sets_test.cc +++ b/src/storage/tests/sets_test.cc @@ -4,8 +4,8 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include #include "storage/storage.h" #include "storage/util.h" @@ -14,8 +14,8 @@ using namespace storage; class SetsTest : public ::testing::Test { public: - SetsTest() { } - virtual ~SetsTest() { } + SetsTest() {} + virtual ~SetsTest() {} void SetUp() override { std::string path = "./db/sets"; @@ -31,16 +31,15 @@ class SetsTest : public ::testing::Test { DeleteFiles(path.c_str()); } - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Storage db; storage::Status s; }; -static bool members_match(storage::Storage *const db, - const Slice& key, +static bool members_match(storage::Storage* const db, const Slice& key, const std::vector& expect_members) { std::vector mm_out; Status s = db->SMembers(key, &mm_out); @@ -61,8 +60,7 @@ static bool members_match(storage::Storage *const db, return true; } -static bool members_match(const std::vector& mm_out, - const std::vector& expect_members) { +static bool members_match(const std::vector& mm_out, const std::vector& expect_members) { if (mm_out.size() != expect_members.size()) { return false; } @@ -74,11 +72,9 @@ static bool members_match(const std::vector& mm_out, return true; } -static bool members_contains(const std::vector& mm_out, - const std::vector& total_members) { +static bool members_contains(const std::vector& mm_out, const std::vector& total_members) { for (const auto& member : mm_out) { - if (find(total_members.begin(), total_members.end(), member) - == total_members.end()) { + if (find(total_members.begin(), total_members.end(), member) == total_members.end()) { return false; } } @@ -96,9 +92,7 @@ static bool members_uniquen(const std::vector& members) { return true; } -static bool size_match(storage::Storage *const db, - const Slice& key, - int32_t expect_size) { +static bool size_match(storage::Storage* const db, const Slice& key, int32_t expect_size) { int32_t size = 0; Status s = db->SCard(key, &size); if (!s.ok() && !s.IsNotFound()) { @@ -110,8 +104,7 @@ static bool size_match(storage::Storage *const db, return size == expect_size; } -static bool make_expired(storage::Storage *const db, - const Slice& key) { +static bool make_expired(storage::Storage* const db, const Slice& key) { std::map type_status; int ret = db->Expire(key, 1, &type_status); if (!ret || !type_status[storage::DataType::kSets].ok()) { @@ -124,14 +117,14 @@ static bool make_expired(storage::Storage *const db, // SAdd TEST_F(SetsTest, SAddTest) { int32_t ret = 0; - std::vector members1 {"a", "b", "c", "b"}; + std::vector members1{"a", "b", "c", "b"}; s = db.SAdd("SADD_KEY", members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "SADD_KEY", 3)); ASSERT_TRUE(members_match(&db, "SADD_KEY", {"a", "b", "c"})); - std::vector members2 {"d", "e"}; + std::vector members2{"d", "e"}; s = db.SAdd("SADD_KEY", members2, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); @@ -142,7 +135,7 @@ TEST_F(SetsTest, SAddTest) { ASSERT_TRUE(make_expired(&db, "SADD_KEY")); ASSERT_TRUE(size_match(&db, "SADD_KEY", 0)); - std::vector members3 {"a", "b"}; + std::vector members3{"a", "b"}; s = db.SAdd("SADD_KEY", members3, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); @@ -157,14 +150,14 @@ TEST_F(SetsTest, SAddTest) { ASSERT_TRUE(size_match(&db, "SADD_KEY", 0)); ASSERT_TRUE(members_match(&db, "SADD_KEY", {})); - std::vector members4 {"a", "x", "l"}; + std::vector members4{"a", "x", "l"}; s = db.SAdd("SADD_KEY", members4, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "SADD_KEY", 3)); ASSERT_TRUE(members_match(&db, "SADD_KEY", {"a", "x", "l"})); - std::vector members5 {"a", "x", "l", "z"}; + std::vector members5{"a", "x", "l", "z"}; s = db.SAdd("SADD_KEY", members5, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -175,7 +168,7 @@ TEST_F(SetsTest, SAddTest) { // SCard TEST_F(SetsTest, SCardTest) { int32_t ret = 0; - std::vector members {"MM1", "MM2", "MM3"}; + std::vector members{"MM1", "MM2", "MM3"}; s = db.SAdd("SCARD_KEY", members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -193,9 +186,9 @@ TEST_F(SetsTest, SDiffTest) { // key2 = {c} // key3 = {a, c, e} // SDIFF key1 key2 key3 = {b, d} - std::vector gp1_members1 {"a", "b", "c", "d"}; - std::vector gp1_members2 {"c"}; - std::vector gp1_members3 {"a", "c", "e"}; + std::vector gp1_members1{"a", "b", "c", "d"}; + std::vector gp1_members2{"c"}; + std::vector gp1_members3{"a", "c", "e"}; s = db.SAdd("GP1_SDIFF_KEY1", gp1_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -206,8 +199,7 @@ TEST_F(SetsTest, SDiffTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp1_keys {"GP1_SDIFF_KEY1", - "GP1_SDIFF_KEY2", "GP1_SDIFF_KEY3"}; + std::vector gp1_keys{"GP1_SDIFF_KEY1", "GP1_SDIFF_KEY2", "GP1_SDIFF_KEY3"}; std::vector gp1_members_out; s = db.SDiff(gp1_keys, &gp1_members_out); ASSERT_TRUE(s.ok()); @@ -238,15 +230,14 @@ TEST_F(SetsTest, SDiffTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp1_members_out, {"a", "b", "d"})); - // ***************** Group 2 Test ***************** // key1 = {} // key2 = {c} // key3 = {a, c, e} // SDIFF key1 key2 key3 = {} - std::vector gp2_members1 {}; - std::vector gp2_members2 {"c"}; - std::vector gp2_members3 {"a", "c", "e"}; + std::vector gp2_members1{}; + std::vector gp2_members2{"c"}; + std::vector gp2_members3{"a", "c", "e"}; s = db.SAdd("GP2_SDIFF_KEY1", gp2_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); @@ -257,37 +248,34 @@ TEST_F(SetsTest, SDiffTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp2_keys {"GP2_SDIFF_KEY1", - "GP2_SDIFF_KEY2", "GP2_SDIFF_KEY3"}; + std::vector gp2_keys{"GP2_SDIFF_KEY1", "GP2_SDIFF_KEY2", "GP2_SDIFF_KEY3"}; std::vector gp2_members_out; s = db.SDiff(gp2_keys, &gp2_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp2_members_out, {})); - // ***************** Group 3 Test ***************** // key1 = {a, b, c, d} // SDIFF key1 = {a, b, c, d} - std::vector gp3_members1 {"a", "b", "c", "d"}; + std::vector gp3_members1{"a", "b", "c", "d"}; s = db.SAdd("GP3_SDIFF_KEY1", gp3_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); - std::vector gp3_keys {"GP3_SDIFF_KEY1"}; + std::vector gp3_keys{"GP3_SDIFF_KEY1"}; std::vector gp3_members_out; s = db.SDiff(gp3_keys, &gp3_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp3_members_out, {"a", "b", "c", "d"})); - // ***************** Group 4 Test ***************** // key1 = {a, b, c, d} (expire key); // key2 = {c} // key3 = {a, c, e} // SDIFF key1 key2 key3 = {} - std::vector gp4_members1 {"a", "b", "c", "d"}; - std::vector gp4_members2 {"c"}; - std::vector gp4_members3 {"a", "c", "e"}; + std::vector gp4_members1{"a", "b", "c", "d"}; + std::vector gp4_members2{"c"}; + std::vector gp4_members3{"a", "c", "e"}; s = db.SAdd("GP4_SDIFF_KEY1", gp4_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -300,22 +288,20 @@ TEST_F(SetsTest, SDiffTest) { ASSERT_TRUE(make_expired(&db, "GP4_SDIFF_KEY1")); - std::vector gp4_keys {"GP4_SDIFF_KEY1", - "GP4_SDIFF_KEY2", "GP4_SDIFF_KEY3"}; + std::vector gp4_keys{"GP4_SDIFF_KEY1", "GP4_SDIFF_KEY2", "GP4_SDIFF_KEY3"}; std::vector gp4_members_out; s = db.SDiff(gp4_keys, &gp4_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp4_members_out, {})); - // ***************** Group 5 Test ***************** // key1 = {a, b, c, d} (key1 is empty key) // key2 = {c} // key3 = {a, c, e} // SDIFF key1 key2 key3 = {b, d} - std::vector gp5_members1 {"a", "b", "c", "d"}; - std::vector gp5_members2 {"c"}; - std::vector gp5_members3 {"a", "c", "e"}; + std::vector gp5_members1{"a", "b", "c", "d"}; + std::vector gp5_members2{"c"}; + std::vector gp5_members3{"a", "c", "e"}; s = db.SAdd("", gp5_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -326,8 +312,7 @@ TEST_F(SetsTest, SDiffTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - - std::vector gp5_keys {"", "GP5_SDIFF_KEY2", "GP5_SDIFF_KEY3"}; + std::vector gp5_keys{"", "GP5_SDIFF_KEY2", "GP5_SDIFF_KEY3"}; std::vector gp5_members_out; s = db.SDiff(gp5_keys, &gp5_members_out); ASSERT_TRUE(s.ok()); @@ -340,7 +325,6 @@ TEST_F(SetsTest, SDiffTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp5_members_out, {"b", "d"})); - // ***************** Group 6 Test ***************** // empty keys std::vector gp6_keys; @@ -361,9 +345,9 @@ TEST_F(SetsTest, SDiffstoreTest) { // key3 = {a, c, e} // SDIFFSTORE destination key1 key2 key3 // destination = {b, d} - std::vector gp1_members1 {"a", "b", "c", "d"}; - std::vector gp1_members2 {"c"}; - std::vector gp1_members3 {"a", "c", "e"}; + std::vector gp1_members1{"a", "b", "c", "d"}; + std::vector gp1_members2{"c"}; + std::vector gp1_members3{"a", "c", "e"}; s = db.SAdd("GP1_SDIFFSTORE_KEY1", gp1_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -375,8 +359,7 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_EQ(ret, 3); std::vector gp1_members_out; - std::vector gp1_keys {"GP1_SDIFFSTORE_KEY1", - "GP1_SDIFFSTORE_KEY2", "GP1_SDIFFSTORE_KEY3"}; + std::vector gp1_keys{"GP1_SDIFFSTORE_KEY1", "GP1_SDIFFSTORE_KEY2", "GP1_SDIFFSTORE_KEY3"}; s = db.SDiffstore("GP1_SDIFFSTORE_DESTINATION1", gp1_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); @@ -399,8 +382,7 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP1_SDIFFSTORE_DESTINATION2", 3)); - ASSERT_TRUE(members_match(&db, "GP1_SDIFFSTORE_DESTINATION2", - {"a", "b", "d"})); + ASSERT_TRUE(members_match(&db, "GP1_SDIFFSTORE_DESTINATION2", {"a", "b", "d"})); // destination = {}; // key1 = {a, b, c, d} @@ -415,9 +397,7 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP1_SDIFFSTORE_DESTINATION3", 3)); - ASSERT_TRUE(members_match(&db, "GP1_SDIFFSTORE_DESTINATION3", - {"a", "b", "d"})); - + ASSERT_TRUE(members_match(&db, "GP1_SDIFFSTORE_DESTINATION3", {"a", "b", "d"})); // ***************** Group 2 Test ***************** // destination = {}; @@ -426,9 +406,9 @@ TEST_F(SetsTest, SDiffstoreTest) { // key3 = {a, c, e} // SDIFFSTORE destination key1 key2 key3 // destination = {} - std::vector gp2_members1 {}; - std::vector gp2_members2 {"c"}; - std::vector gp2_members3 {"a", "c", "e"}; + std::vector gp2_members1{}; + std::vector gp2_members2{"c"}; + std::vector gp2_members3{"a", "c", "e"}; s = db.SAdd("GP2_SDIFFSTORE_KEY1", gp2_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); @@ -439,8 +419,7 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp2_keys {"GP2_SDIFFSTORE_KEY1", - "GP2_SDIFFSTORE_KEY2", "GP2_SDIFFSTORE_KEY3"}; + std::vector gp2_keys{"GP2_SDIFFSTORE_KEY1", "GP2_SDIFFSTORE_KEY2", "GP2_SDIFFSTORE_KEY3"}; std::vector gp2_members_out; s = db.SDiffstore("GP2_SDIFFSTORE_DESTINATION1", gp2_keys, &ret); ASSERT_TRUE(s.ok()); @@ -448,26 +427,23 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(size_match(&db, "GP2_SDIFFSTORE_DESTINATION1", 0)); ASSERT_TRUE(members_match(&db, "GP2_SDIFFSTORE_DESTINATION1", {})); - // ***************** Group 3 Test ***************** // destination = {}; // key1 = {a, b, c, d} // SDIFFSTORE destination key1 // destination = {a, b, c, d} - std::vector gp3_members1 {"a", "b", "c", "d"}; + std::vector gp3_members1{"a", "b", "c", "d"}; s = db.SAdd("GP3_SDIFFSTORE_KEY1", gp3_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); - std::vector gp3_keys {"GP3_SDIFFSTORE_KEY1"}; + std::vector gp3_keys{"GP3_SDIFFSTORE_KEY1"}; std::vector gp3_members_out; s = db.SDiffstore("GP3_SDIFFSTORE_DESTINATION1", gp3_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(size_match(&db, "GP3_SDIFFSTORE_DESTINATION1", 4)); - ASSERT_TRUE(members_match(&db, "GP3_SDIFFSTORE_DESTINATION1", - {"a", "b", "c", "d"})); - + ASSERT_TRUE(members_match(&db, "GP3_SDIFFSTORE_DESTINATION1", {"a", "b", "c", "d"})); // ***************** Group 4 Test ***************** // destination = {}; @@ -476,9 +452,9 @@ TEST_F(SetsTest, SDiffstoreTest) { // key3 = {a, c, e} // SDIFFSTORE destination key1 key2 key3 // destination = {} - std::vector gp4_members1 {"a", "b", "c", "d"}; - std::vector gp4_members2 {"c"}; - std::vector gp4_members3 {"a", "c", "e"}; + std::vector gp4_members1{"a", "b", "c", "d"}; + std::vector gp4_members2{"c"}; + std::vector gp4_members3{"a", "c", "e"}; s = db.SAdd("GP4_SDIFFSTORE_KEY1", gp4_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -491,8 +467,7 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(make_expired(&db, "GP4_SDIFFSTORE_KEY1")); - std::vector gp4_keys {"GP4_SDIFFSTORE_KEY1", - "GP4_SDIFFSTORE_KEY2", "GP4_SDIFFSTORE_KEY3"}; + std::vector gp4_keys{"GP4_SDIFFSTORE_KEY1", "GP4_SDIFFSTORE_KEY2", "GP4_SDIFFSTORE_KEY3"}; std::vector gp4_members_out; s = db.SDiffstore("GP4_SDIFFSTORE_DESTINATION1", gp4_keys, &ret); ASSERT_TRUE(s.ok()); @@ -500,7 +475,6 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(size_match(&db, "GP4_SDIFFSTORE_DESTINATION1", 0)); ASSERT_TRUE(members_match(&db, "GP4_SDIFFSTORE_DESTINATION1", {})); - // ***************** Group 5 Test ***************** // the destination already exists, it is overwritten // destination = {a, x, l} @@ -509,10 +483,10 @@ TEST_F(SetsTest, SDiffstoreTest) { // key3 = {a, c, e} // SDIFFSTORE destination key1 key2 key3 // destination = {b, d} - std::vector gp5_destination_members {"a", "x", "l"}; - std::vector gp5_members1 {"a", "b", "c", "d"}; - std::vector gp5_members2 {"c"}; - std::vector gp5_members3 {"a", "c", "e"}; + std::vector gp5_destination_members{"a", "x", "l"}; + std::vector gp5_members1{"a", "b", "c", "d"}; + std::vector gp5_members2{"c"}; + std::vector gp5_members3{"a", "c", "e"}; s = db.SAdd("GP5_SDIFFSTORE_DESTINATION1", gp5_destination_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -526,15 +500,13 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp5_keys {"GP5_SDIFFSTORE_KEY1", - "GP5_SDIFFSTORE_KEY2", "GP5_SDIFFSTORE_KEY3"}; + std::vector gp5_keys{"GP5_SDIFFSTORE_KEY1", "GP5_SDIFFSTORE_KEY2", "GP5_SDIFFSTORE_KEY3"}; s = db.SDiffstore("GP5_SDIFFSTORE_DESTINATION1", gp5_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); ASSERT_TRUE(size_match(&db, "GP5_SDIFFSTORE_DESTINATION1", 2)); ASSERT_TRUE(members_match(&db, "GP5_SDIFFSTORE_DESTINATION1", {"b", "d"})); - // ***************** Group 6 Test ***************** // test destination equal key1 (the destination already exists, it is // overwritten) @@ -543,9 +515,9 @@ TEST_F(SetsTest, SDiffstoreTest) { // key3 = {a, c, e} // SDIFFSTORE destination destination key2 key3 // destination = {b, d} - std::vector gp6_destination_members {"a", "b", "c", "d"}; - std::vector gp6_members2 {"c"}; - std::vector gp6_members3 {"a", "c", "e"}; + std::vector gp6_destination_members{"a", "b", "c", "d"}; + std::vector gp6_members2{"c"}; + std::vector gp6_members3{"a", "c", "e"}; s = db.SAdd("GP6_SDIFFSTORE_DESTINATION1", gp6_destination_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -556,15 +528,13 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp6_keys {"GP6_SDIFFSTORE_DESTINATION1", - "GP6_SDIFFSTORE_KEY2", "GP6_SDIFFSTORE_KEY3"}; + std::vector gp6_keys{"GP6_SDIFFSTORE_DESTINATION1", "GP6_SDIFFSTORE_KEY2", "GP6_SDIFFSTORE_KEY3"}; s = db.SDiffstore("GP6_SDIFFSTORE_DESTINATION1", gp6_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); ASSERT_TRUE(size_match(&db, "GP6_SDIFFSTORE_DESTINATION1", 2)); ASSERT_TRUE(members_match(&db, "GP6_SDIFFSTORE_DESTINATION1", {"b", "d"})); - // ***************** Group 7 Test ***************** // test destination exist but timeout (the destination already exists, it is // overwritten) @@ -574,10 +544,10 @@ TEST_F(SetsTest, SDiffstoreTest) { // key3 = {a, c, e} // SDIFFSTORE destination key1 key2 key3 // destination = {b, d} - std::vector gp7_destination_members {"a", "x", "l"}; - std::vector gp7_members1 {"a", "b", "c", "d"}; - std::vector gp7_members2 {"c"}; - std::vector gp7_members3 {"a", "c", "e"}; + std::vector gp7_destination_members{"a", "x", "l"}; + std::vector gp7_members1{"a", "b", "c", "d"}; + std::vector gp7_members2{"c"}; + std::vector gp7_members3{"a", "c", "e"}; s = db.SAdd("GP7_SDIFFSTORE_DESTINATION1", gp7_destination_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -593,8 +563,7 @@ TEST_F(SetsTest, SDiffstoreTest) { ASSERT_TRUE(make_expired(&db, "GP7_SDIFFSTORE_DESTINATION1")); - std::vector gp7_keys {"GP7_SDIFFSTORE_KEY1", - "GP7_SDIFFSTORE_KEY2", "GP7_SDIFFSTORE_KEY3"}; + std::vector gp7_keys{"GP7_SDIFFSTORE_KEY1", "GP7_SDIFFSTORE_KEY2", "GP7_SDIFFSTORE_KEY3"}; s = db.SDiffstore("GP7_SDIFFSTORE_DESTINATION1", gp7_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); @@ -611,9 +580,9 @@ TEST_F(SetsTest, SInterTest) { // key2 = {a, c} // key3 = {a, c, e} // SINTER key1 key2 key3 = {a, c} - std::vector gp1_members1 {"a", "b", "c", "d"}; - std::vector gp1_members2 {"a", "c"}; - std::vector gp1_members3 {"a", "c", "e"}; + std::vector gp1_members1{"a", "b", "c", "d"}; + std::vector gp1_members2{"a", "c"}; + std::vector gp1_members3{"a", "c", "e"}; s = db.SAdd("GP1_SINTER_KEY1", gp1_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -624,8 +593,7 @@ TEST_F(SetsTest, SInterTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp1_keys {"GP1_SINTER_KEY1", - "GP1_SINTER_KEY2", "GP1_SINTER_KEY3"}; + std::vector gp1_keys{"GP1_SINTER_KEY1", "GP1_SINTER_KEY2", "GP1_SINTER_KEY3"}; std::vector gp1_members_out; s = db.SInter(gp1_keys, &gp1_members_out); ASSERT_TRUE(s.ok()); @@ -642,15 +610,14 @@ TEST_F(SetsTest, SInterTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp1_members_out, {})); - // ***************** Group 2 Test ***************** // key1 = {a, b, c, d} // key2 = {c} // key3 = {a, c, e} // SINTER key1 key2 key3 not_exist_key = {} - std::vector gp2_members1 {"a", "b", "c", "d"}; - std::vector gp2_members2 {"c"}; - std::vector gp2_members3 {"a", "c", "e"}; + std::vector gp2_members1{"a", "b", "c", "d"}; + std::vector gp2_members2{"c"}; + std::vector gp2_members3{"a", "c", "e"}; s = db.SAdd("GP2_SINTER_KEY1", gp2_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -661,22 +628,20 @@ TEST_F(SetsTest, SInterTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp2_keys {"GP2_SINTER_KEY1", - "GP2_SINTER_KEY2", "GP2_SINTER_KEY3", "NOT_EXIST_KEY"}; + std::vector gp2_keys{"GP2_SINTER_KEY1", "GP2_SINTER_KEY2", "GP2_SINTER_KEY3", "NOT_EXIST_KEY"}; std::vector gp2_members_out; s = db.SInter(gp2_keys, &gp2_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp2_members_out, {})); - // ***************** Group 3 Test ***************** // key1 = {a, b, c, d} // key2 = {a, c} // key3 = {} // SINTER key1 key2 key3 = {} - std::vector gp3_members1 {"a", "b", "c", "d"}; - std::vector gp3_members2 {"a", "c"}; - std::vector gp3_members3 {"a", "b", "c"}; + std::vector gp3_members1{"a", "b", "c", "d"}; + std::vector gp3_members2{"a", "c"}; + std::vector gp3_members3{"a", "b", "c"}; s = db.SAdd("GP3_SINTER_KEY1", gp3_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -699,21 +664,19 @@ TEST_F(SetsTest, SInterTest) { ASSERT_TRUE(members_match(gp3_members_out, {})); gp3_members_out.clear(); - std::vector gp3_keys {"GP3_SINTER_KEY1", - "GP3_SINTER_KEY2", "GP3_SINTER_KEY3"}; + std::vector gp3_keys{"GP3_SINTER_KEY1", "GP3_SINTER_KEY2", "GP3_SINTER_KEY3"}; s = db.SInter(gp3_keys, &gp3_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp3_members_out, {})); - // ***************** Group 4 Test ***************** // key1 = {} // key2 = {a, c} // key3 = {a, b, c, d} // SINTER key1 key2 key3 = {} - std::vector gp4_members1 {"a", "b", "c", "d"}; - std::vector gp4_members2 {"a", "c"}; - std::vector gp4_members3 {"a", "b", "c", "d"}; + std::vector gp4_members1{"a", "b", "c", "d"}; + std::vector gp4_members2{"a", "c"}; + std::vector gp4_members3{"a", "b", "c", "d"}; s = db.SAdd("GP4_SINTER_KEY1", gp4_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -736,21 +699,19 @@ TEST_F(SetsTest, SInterTest) { ASSERT_EQ(gp4_members_out.size(), 0); gp4_members_out.clear(); - std::vector gp4_keys {"GP4_SINTER_KEY1", - "GP4_SINTER_KEY2", "GP4_SINTER_KEY3"}; + std::vector gp4_keys{"GP4_SINTER_KEY1", "GP4_SINTER_KEY2", "GP4_SINTER_KEY3"}; s = db.SInter(gp4_keys, &gp4_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp4_members_out, {})); - // ***************** Group 5 Test ***************** // key1 = {a, b, c, d} // key2 = {a, c} // key3 = {a, b, c} // SINTER key1 key2 key2 key3 = {a, c} - std::vector gp5_members1 {"a", "b", "c", "d"}; - std::vector gp5_members2 {"a", "c"}; - std::vector gp5_members3 {"a", "b", "c"}; + std::vector gp5_members1{"a", "b", "c", "d"}; + std::vector gp5_members2{"a", "c"}; + std::vector gp5_members3{"a", "b", "c"}; s = db.SAdd("GP5_SINTER_KEY1", gp5_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -762,8 +723,7 @@ TEST_F(SetsTest, SInterTest) { ASSERT_EQ(ret, 3); std::vector gp5_members_out; - std::vector gp5_keys {"GP5_SINTER_KEY1", - "GP5_SINTER_KEY2", "GP5_SINTER_KEY2", "GP5_SINTER_KEY3"}; + std::vector gp5_keys{"GP5_SINTER_KEY1", "GP5_SINTER_KEY2", "GP5_SINTER_KEY2", "GP5_SINTER_KEY3"}; s = db.SInter(gp5_keys, &gp5_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp5_members_out, {"a", "c"})); @@ -780,9 +740,9 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, c, e} // SINTERSTORE destination key1 key2 key3 // destination = {a, c} - std::vector gp1_members1 {"a", "b", "c", "d"}; - std::vector gp1_members2 {"a", "c"}; - std::vector gp1_members3 {"a", "c", "e"}; + std::vector gp1_members1{"a", "b", "c", "d"}; + std::vector gp1_members2{"a", "c"}; + std::vector gp1_members3{"a", "c", "e"}; s = db.SAdd("GP1_SINTERSTORE_KEY1", gp1_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -793,15 +753,13 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp1_keys {"GP1_SINTERSTORE_KEY1", - "GP1_SINTERSTORE_KEY2", "GP1_SINTERSTORE_KEY3"}; + std::vector gp1_keys{"GP1_SINTERSTORE_KEY1", "GP1_SINTERSTORE_KEY2", "GP1_SINTERSTORE_KEY3"}; s = db.SInterstore("GP1_SINTERSTORE_DESTINATION1", gp1_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); ASSERT_TRUE(size_match(&db, "GP1_SINTERSTORE_DESTINATION1", 2)); ASSERT_TRUE(members_match(&db, "GP1_SINTERSTORE_DESTINATION1", {"a", "c"})); - // ***************** Group 2 Test ***************** // the destination already exists, it is overwritten. // destination = {a, x, l} @@ -810,10 +768,10 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, c, e} // SINTERSTORE destination key1 key2 key3 // destination = {a, c} - std::vector gp2_destination_members {"a", "x", "l"}; - std::vector gp2_members1 {"a", "b", "c", "d"}; - std::vector gp2_members2 {"a", "c"}; - std::vector gp2_members3 {"a", "c", "e"}; + std::vector gp2_destination_members{"a", "x", "l"}; + std::vector gp2_members1{"a", "b", "c", "d"}; + std::vector gp2_members2{"a", "c"}; + std::vector gp2_members3{"a", "c", "e"}; s = db.SAdd("GP2_SINTERSTORE_DESTINATION1", gp2_destination_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -827,15 +785,13 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp2_keys {"GP2_SINTERSTORE_KEY1", - "GP2_SINTERSTORE_KEY2", "GP2_SINTERSTORE_KEY3"}; + std::vector gp2_keys{"GP2_SINTERSTORE_KEY1", "GP2_SINTERSTORE_KEY2", "GP2_SINTERSTORE_KEY3"}; s = db.SInterstore("GP2_SINTERSTORE_DESTINATION1", gp2_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); ASSERT_TRUE(size_match(&db, "GP2_SINTERSTORE_DESTINATION1", 2)); ASSERT_TRUE(members_match(&db, "GP2_SINTERSTORE_DESTINATION1", {"a", "c"})); - // ***************** Group 3 Test ***************** // destination = {} // key1 = {a, b, c, d} @@ -843,9 +799,9 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, c, e} // SINTERSTORE destination key1 key2 key3 not_exist_key // destination = {} - std::vector gp3_members1 {"a", "b", "c", "d"}; - std::vector gp3_members2 {"a", "c"}; - std::vector gp3_members3 {"a", "c", "e"}; + std::vector gp3_members1{"a", "b", "c", "d"}; + std::vector gp3_members2{"a", "c"}; + std::vector gp3_members3{"a", "c", "e"}; s = db.SAdd("GP3_SINTERSTORE_KEY1", gp3_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -856,16 +812,14 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp3_keys {"GP3_SINTERSTORE_KEY1", - "GP3_SINTERSTORE_KEY2", "GP3_SINTERSTORE_KEY3", - "GP3_SINTERSTORE_NOT_EXIST_KEY"}; + std::vector gp3_keys{"GP3_SINTERSTORE_KEY1", "GP3_SINTERSTORE_KEY2", "GP3_SINTERSTORE_KEY3", + "GP3_SINTERSTORE_NOT_EXIST_KEY"}; s = db.SInterstore("GP3_SINTERSTORE_DESTINATION1", gp3_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP3_SINTERSTORE_DESTINATION1", 0)); ASSERT_TRUE(members_match(&db, "GP3_SINTERSTORE_DESTINATION1", {})); - // ***************** Group 4 Test ***************** // destination = {} // key1 = {a, b, c, d} @@ -873,9 +827,9 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, c, e} // SINTERSTORE destination key1 key2 key3 // destination = {} - std::vector gp4_members1 {"a", "b", "c", "d"}; - std::vector gp4_members2 {"a", "c"}; - std::vector gp4_members3 {"a", "c", "e"}; + std::vector gp4_members1{"a", "b", "c", "d"}; + std::vector gp4_members2{"a", "c"}; + std::vector gp4_members3{"a", "c", "e"}; s = db.SAdd("GP4_SINTERSTORE_KEY1", gp4_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -888,15 +842,13 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(make_expired(&db, "GP4_SINTERSTORE_KEY2")); - std::vector gp4_keys {"GP4_SINTERSTORE_KEY1", - "GP4_SINTERSTORE_KEY2", "GP4_SINTERSTORE_KEY3"}; + std::vector gp4_keys{"GP4_SINTERSTORE_KEY1", "GP4_SINTERSTORE_KEY2", "GP4_SINTERSTORE_KEY3"}; s = db.SInterstore("GP4_SINTERSTORE_DESTINATION1", gp4_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP4_SINTERSTORE_DESTINATION1", 0)); ASSERT_TRUE(members_match(&db, "GP4_SINTERSTORE_DESTINATION1", {})); - // ***************** Group 5 Test ***************** // destination = {} // key1 = {a, b, c, d} (expire key); @@ -904,9 +856,9 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, c, e} // SINTERSTORE destination key1 key2 key3 // destination = {} - std::vector gp5_members1 {"a", "b", "c", "d"}; - std::vector gp5_members2 {"a", "c"}; - std::vector gp5_members3 {"a", "c", "e"}; + std::vector gp5_members1{"a", "b", "c", "d"}; + std::vector gp5_members2{"a", "c"}; + std::vector gp5_members3{"a", "c", "e"}; s = db.SAdd("GP5_SINTERSTORE_KEY1", gp5_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -919,15 +871,13 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(make_expired(&db, "GP5_SINTERSTORE_KEY1")); - std::vector gp5_keys {"GP5_SINTERSTORE_KEY1", - "GP5_SINTERSTORE_KEY2", "GP5_SINTERSTORE_KEY3"}; + std::vector gp5_keys{"GP5_SINTERSTORE_KEY1", "GP5_SINTERSTORE_KEY2", "GP5_SINTERSTORE_KEY3"}; s = db.SInterstore("GP5_SINTERSTORE_DESTINATION1", gp5_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP5_SINTERSTORE_DESTINATION1", 0)); ASSERT_TRUE(members_match(&db, "GP5_SINTERSTORE_DESTINATION1", {})); - // ***************** Group 6 Test ***************** // destination = {} // key1 = {} @@ -935,9 +885,9 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, c, e} // SINTERSTORE destination key1 key2 key3 // destination = {} - std::vector gp6_members1 {"a", "b", "c", "d"}; - std::vector gp6_members2 {"a", "c"}; - std::vector gp6_members3 {"a", "c", "e"}; + std::vector gp6_members1{"a", "b", "c", "d"}; + std::vector gp6_members2{"a", "c"}; + std::vector gp6_members3{"a", "c", "e"}; s = db.SAdd("GP6_SINTERSTORE_KEY1", gp6_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -955,15 +905,13 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - std::vector gp6_keys {"GP6_SINTERSTORE_KEY1", - "GP6_SINTERSTORE_KEY2", "GP6_SINTERSTORE_KEY3"}; + std::vector gp6_keys{"GP6_SINTERSTORE_KEY1", "GP6_SINTERSTORE_KEY2", "GP6_SINTERSTORE_KEY3"}; s = db.SInterstore("GP6_SINTERSTORE_DESTINATION1", gp6_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP6_SINTERSTORE_DESTINATION1", 0)); ASSERT_TRUE(members_match(&db, "GP6_SINTERSTORE_DESTINATION1", {})); - // ***************** Group 7 Test ***************** // destination = {} // key1 = {a, b, c, d} @@ -971,9 +919,9 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, c, e} // SINTERSTORE destination not_exist_key key1 key2 key3 // destination = {} - std::vector gp7_members1 {"a", "b", "c", "d"}; - std::vector gp7_members2 {"a", "c"}; - std::vector gp7_members3 {"a", "c", "e"}; + std::vector gp7_members1{"a", "b", "c", "d"}; + std::vector gp7_members2{"a", "c"}; + std::vector gp7_members3{"a", "c", "e"}; s = db.SAdd("GP7_SINTERSTORE_KEY1", gp7_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -984,15 +932,14 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp7_keys {"GP7_SINTERSTORE_NOT_EXIST_KEY", - "GP7_SINTERSTORE_KEY1", "GP7_SINTERSTORE_KEY2", "GP7_SINTERSTORE_KEY3"}; + std::vector gp7_keys{"GP7_SINTERSTORE_NOT_EXIST_KEY", "GP7_SINTERSTORE_KEY1", "GP7_SINTERSTORE_KEY2", + "GP7_SINTERSTORE_KEY3"}; s = db.SInterstore("GP7_SINTERSTORE_DESTINATION1", gp7_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP7_SINTERSTORE_DESTINATION1", 0)); ASSERT_TRUE(members_match(&db, "GP7_SINTERSTORE_DESTINATION1", {})); - // ***************** Group 8 Test ***************** // destination = {} // key1 = {a, b, c, d} @@ -1000,9 +947,9 @@ TEST_F(SetsTest, SInterstoreTest) { // key3 = {a, b, c, d} // SINTERSTORE destination key1 key2 key3 // destination = {a, b, c, d} - std::vector gp8_members1 {"a", "b", "c", "d"}; - std::vector gp8_members2 {"a", "b", "c", "d"}; - std::vector gp8_members3 {"a", "b", "c", "d"}; + std::vector gp8_members1{"a", "b", "c", "d"}; + std::vector gp8_members2{"a", "b", "c", "d"}; + std::vector gp8_members3{"a", "b", "c", "d"}; s = db.SAdd("GP8_SINTERSTORE_KEY1", gp8_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1013,22 +960,23 @@ TEST_F(SetsTest, SInterstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); - std::vector gp8_keys {"GP8_SINTERSTORE_KEY1", - "GP8_SINTERSTORE_KEY2", "GP8_SINTERSTORE_KEY3", }; + std::vector gp8_keys{ + "GP8_SINTERSTORE_KEY1", + "GP8_SINTERSTORE_KEY2", + "GP8_SINTERSTORE_KEY3", + }; std::vector gp8_members_out; s = db.SInterstore("GP8_SINTERSTORE_DESTINATION1", gp8_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(size_match(&db, "GP8_SINTERSTORE_DESTINATION1", 4)); - ASSERT_TRUE(members_match(&db, "GP8_SINTERSTORE_DESTINATION1", - {"a", "b", "c", "d"})); + ASSERT_TRUE(members_match(&db, "GP8_SINTERSTORE_DESTINATION1", {"a", "b", "c", "d"})); } - // SIsmember TEST_F(SetsTest, SIsmemberTest) { int32_t ret = 0; - std::vector members {"MEMBER"}; + std::vector members{"MEMBER"}; s = db.SAdd("SISMEMBER_KEY", members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); @@ -1116,8 +1064,8 @@ TEST_F(SetsTest, SMoveTest) { // SMove source destination d // source = {a, b, c} // destination = {a, c, d} - std::vector gp1_source {"a", "b", "c", "d"}; - std::vector gp1_destination {"a", "c"}; + std::vector gp1_source{"a", "b", "c", "d"}; + std::vector gp1_destination{"a", "c"}; s = db.SAdd("GP1_SMOVE_SOURCE", gp1_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1134,15 +1082,14 @@ TEST_F(SetsTest, SMoveTest) { ASSERT_TRUE(size_match(&db, "GP1_SMOVE_DESTINATION", 3)); ASSERT_TRUE(members_match(&db, "GP1_SMOVE_DESTINATION", {"a", "c", "d"})); - // ***************** Group 2 Test ***************** // source = {a, b, c, d} // destination = {a, c} (expire key); // SMove source destination d // source = {a, b, c} // destination = {d} - std::vector gp2_source {"a", "b", "c", "d"}; - std::vector gp2_destination {"a", "c"}; + std::vector gp2_source{"a", "b", "c", "d"}; + std::vector gp2_destination{"a", "c"}; s = db.SAdd("GP2_SMOVE_SOURCE", gp2_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1161,15 +1108,14 @@ TEST_F(SetsTest, SMoveTest) { ASSERT_TRUE(size_match(&db, "GP2_SMOVE_DESTINATION", 1)); ASSERT_TRUE(members_match(&db, "GP2_SMOVE_DESTINATION", {"d"})); - // ***************** Group 3 Test ***************** // source = {a, x, l} // destination = {} // SMove source destination x // source = {a, l} // destination = {x} - std::vector gp3_source {"a", "x", "l"}; - std::vector gp3_destination {"a", "b"}; + std::vector gp3_source{"a", "x", "l"}; + std::vector gp3_destination{"a", "b"}; s = db.SAdd("GP3_SMOVE_SOURCE", gp3_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -1193,13 +1139,12 @@ TEST_F(SetsTest, SMoveTest) { ASSERT_TRUE(size_match(&db, "GP3_SMOVE_DESTINATION", 1)); ASSERT_TRUE(members_match(&db, "GP3_SMOVE_DESTINATION", {"x"})); - // ***************** Group 4 Test ***************** // source = {a, x, l} // SMove source not_exist_key x // source = {a, l} // not_exist_key = {x} - std::vector gp4_source {"a", "x", "l"}; + std::vector gp4_source{"a", "x", "l"}; s = db.SAdd("GP4_SMOVE_SOURCE", gp4_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -1213,15 +1158,14 @@ TEST_F(SetsTest, SMoveTest) { ASSERT_TRUE(size_match(&db, "GP4_SMOVE_NOT_EXIST_KEY", 1)); ASSERT_TRUE(members_match(&db, "GP4_SMOVE_NOT_EXIST_KEY", {"x"})); - // ***************** Group 5 Test ***************** // source = {} // destination = {a, x, l} // SMove source destination x // source = {} // destination = {a, x, l} - std::vector gp5_source {"a", "b"}; - std::vector gp5_destination {"a", "x", "l"}; + std::vector gp5_source{"a", "b"}; + std::vector gp5_destination{"a", "x", "l"}; s = db.SAdd("GP5_SMOVE_SOURCE", gp5_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); @@ -1245,15 +1189,14 @@ TEST_F(SetsTest, SMoveTest) { ASSERT_TRUE(size_match(&db, "GP5_SMOVE_DESTINATION", 3)); ASSERT_TRUE(members_match(&db, "GP5_SMOVE_DESTINATION", {"a", "x", "l"})); - // ***************** Group 6 Test ***************** // source = {a, b, c, d} (expire key); // destination = {a, c} // SMove source destination d // source = {} // destination = {d} - std::vector gp6_source {"a", "b", "c", "d"}; - std::vector gp6_destination {"a", "c"}; + std::vector gp6_source{"a", "b", "c", "d"}; + std::vector gp6_destination{"a", "c"}; s = db.SAdd("GP6_SMOVE_SOURCE", gp6_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1272,15 +1215,14 @@ TEST_F(SetsTest, SMoveTest) { ASSERT_TRUE(size_match(&db, "GP6_SMOVE_DESTINATION", 2)); ASSERT_TRUE(members_match(&db, "GP6_SMOVE_DESTINATION", {"a", "c"})); - // ***************** Group 7 Test ***************** // source = {a, b, c, d} // destination = {a, c} // SMove source destination x // source = {a, b, c, d} // destination = {a, c} - std::vector gp7_source {"a", "b", "c", "d"}; - std::vector gp7_destination {"a", "c"}; + std::vector gp7_source{"a", "b", "c", "d"}; + std::vector gp7_destination{"a", "c"}; s = db.SAdd("GP7_SMOVE_SOURCE", gp7_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1297,15 +1239,14 @@ TEST_F(SetsTest, SMoveTest) { ASSERT_TRUE(size_match(&db, "GP7_SMOVE_DESTINATION", 2)); ASSERT_TRUE(members_match(&db, "GP7_SMOVE_DESTINATION", {"a", "c"})); - // ***************** Group 8 Test ***************** // source = {a, b, c, d} // destination = {a, c, d} // SMove source destination d // source = {a, b, c} // destination = {a, c, d} - std::vector gp8_source {"a", "b", "c", "d"}; - std::vector gp8_destination {"a", "c", "d"}; + std::vector gp8_source{"a", "b", "c", "d"}; + std::vector gp8_destination{"a", "c", "d"}; s = db.SAdd("GP8_SMOVE_SOURCE", gp8_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1326,7 +1267,7 @@ TEST_F(SetsTest, SMoveTest) { // source = {a, b, c, d} // SMove source source d // source = {a, b, c, d} - std::vector gp9_source {"a", "b", "c", "d"}; + std::vector gp9_source{"a", "b", "c", "d"}; s = db.SAdd("GP9_SMOVE_SOURCE", gp8_source, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1345,7 +1286,7 @@ TEST_F(SetsTest, SPopTest) { std::string member; // ***************** Group 1 Test ***************** - std::vector gp1_members {"gp1_aa", "gp1_bb", "gp1_cc"}; + std::vector gp1_members{"gp1_aa", "gp1_bb", "gp1_cc"}; s = db.SAdd("GP1_SPOP_KEY", gp1_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -1370,7 +1311,6 @@ TEST_F(SetsTest, SPopTest) { ASSERT_TRUE(members_match(&db, "GP1_SPOP_KEY", {})); ASSERT_TRUE(members_match(gp1_out_all, gp1_members)); - // ***************** Group 2 Test ***************** std::vector gp2_members; for (int32_t idx = 1; idx <= 1; ++idx) { @@ -1392,7 +1332,6 @@ TEST_F(SetsTest, SPopTest) { ASSERT_TRUE(members_match(&db, "GP2_SPOP_KEY", {})); ASSERT_TRUE(members_match(gp2_out_all, gp2_members)); - // ***************** Group 3 Test ***************** std::vector gp3_members; for (int32_t idx = 1; idx <= 100; ++idx) { @@ -1414,7 +1353,6 @@ TEST_F(SetsTest, SPopTest) { ASSERT_TRUE(members_match(&db, "GP3_SPOP_KEY", {})); ASSERT_TRUE(members_match(gp3_out_all, gp3_members)); - // ***************** Group 4 Test ***************** std::vector gp4_members; for (int32_t idx = 1; idx <= 10000; ++idx) { @@ -1436,9 +1374,8 @@ TEST_F(SetsTest, SPopTest) { ASSERT_TRUE(members_match(&db, "GP4_SPOP_KEY", {})); ASSERT_TRUE(members_match(gp4_out_all, gp4_members)); - // ***************** Group 5 Test ***************** - std::vector gp5_members {"gp5_aa", "gp5_bb", "gp5_cc"}; + std::vector gp5_members{"gp5_aa", "gp5_bb", "gp5_cc"}; s = db.SAdd("GP5_SPOP_KEY", gp5_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -1450,9 +1387,8 @@ TEST_F(SetsTest, SPopTest) { ASSERT_TRUE(size_match(&db, "GP5_SPOP_KEY", 0)); ASSERT_TRUE(members_match(&db, "GP5_SPOP_KEY", {})); - // ***************** Group 6 Test ***************** - std::vector gp6_members {"gp6_aa", "gp6_bb", "gp6_cc"}; + std::vector gp6_members{"gp6_aa", "gp6_bb", "gp6_cc"}; s = db.SAdd("GP6_SPOP_KEY", gp6_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); @@ -1467,7 +1403,6 @@ TEST_F(SetsTest, SPopTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(size_match(&db, "GP6_SPOP_KEY", 0)); ASSERT_TRUE(members_match(&db, "GP6_SPOP_KEY", {})); - } // SRandmember @@ -1475,9 +1410,7 @@ TEST_F(SetsTest, SRanmemberTest) { int32_t ret = 0; // ***************** Group 1 Test ***************** - std::vector gp1_members {"gp1_aa", "gp1_bb", "gp1_cc", - "gp1_dd", "gp1_ee", "gp1_ff", - "gp1_gg", "gp1_hh"}; + std::vector gp1_members{"gp1_aa", "gp1_bb", "gp1_cc", "gp1_dd", "gp1_ee", "gp1_ff", "gp1_gg", "gp1_hh"}; s = db.SAdd("GP1_SRANDMEMBER_KEY", gp1_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 8); @@ -1539,7 +1472,6 @@ TEST_F(SetsTest, SRanmemberTest) { ASSERT_EQ(gp1_out.size(), 10); ASSERT_TRUE(members_contains(gp1_out, gp1_members)); - // ***************** Group 2 Test ***************** s = db.SAdd("GP2_SRANDMEMBER_KEY", {"MM"}, &ret); ASSERT_TRUE(s.ok()); @@ -1566,11 +1498,8 @@ TEST_F(SetsTest, SRanmemberTest) { ASSERT_EQ(gp2_out.size(), 3); ASSERT_TRUE(members_match(gp2_out, {"MM", "MM", "MM"})); - // ***************** Group 3 Test ***************** - std::vector gp3_members {"gp1_aa", "gp1_bb", "gp1_cc", - "gp1_dd", "gp1_ee", "gp1_ff", - "gp1_gg", "gp1_hh"}; + std::vector gp3_members{"gp1_aa", "gp1_bb", "gp1_cc", "gp1_dd", "gp1_ee", "gp1_ff", "gp1_gg", "gp1_hh"}; s = db.SAdd("GP3_SRANDMEMBER_KEY", gp3_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 8); @@ -1583,18 +1512,17 @@ TEST_F(SetsTest, SRanmemberTest) { ASSERT_TRUE(members_match(gp3_out, {})); } - // SRem TEST_F(SetsTest, SRemTest) { int32_t ret = 0; // ***************** Group 1 Test ***************** - std::vector gp1_members {"a", "b", "c", "d"}; + std::vector gp1_members{"a", "b", "c", "d"}; s = db.SAdd("GP1_SREM_KEY", gp1_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); - std::vector gp1_del_members {"a", "b"}; + std::vector gp1_del_members{"a", "b"}; s = db.SRem("GP1_SREM_KEY", gp1_del_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); @@ -1602,15 +1530,14 @@ TEST_F(SetsTest, SRemTest) { ASSERT_TRUE(size_match(&db, "GP1_SREM_KEY", 2)); ASSERT_TRUE(members_match(&db, "GP1_SREM_KEY", {"c", "d"})); - // ***************** Group 2 Test ***************** // srem not exist members - std::vector gp2_members {"a", "b", "c", "d"}; + std::vector gp2_members{"a", "b", "c", "d"}; s = db.SAdd("GP2_SREM_KEY", gp2_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); - std::vector gp2_del_members {"e", "f"}; + std::vector gp2_del_members{"e", "f"}; s = db.SRem("GP2_SREM_KEY", gp2_del_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); @@ -1618,7 +1545,6 @@ TEST_F(SetsTest, SRemTest) { ASSERT_TRUE(size_match(&db, "GP2_SREM_KEY", 4)); ASSERT_TRUE(members_match(&db, "GP2_SREM_KEY", {"a", "b", "c", "d"})); - // ***************** Group 3 Test ***************** // srem not exist key std::vector gp3_del_members{"a", "b", "c"}; @@ -1626,17 +1552,16 @@ TEST_F(SetsTest, SRemTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - // ***************** Group 4 Test ***************** // srem timeout key - std::vector gp4_members {"a", "b", "c", "d"}; + std::vector gp4_members{"a", "b", "c", "d"}; s = db.SAdd("GP4_SREM_KEY", gp4_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(make_expired(&db, "GP4_SREM_KEY")); - std::vector gp4_del_members {"a", "b"}; + std::vector gp4_del_members{"a", "b"}; s = db.SRem("GP4_SREM_KEY", gp4_del_members, &ret); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); @@ -1654,9 +1579,9 @@ TEST_F(SetsTest, SUnionTest) { // key2 = {a, c} // key3 = {a, c, e} // SUNION key1 key2 key3 = {a, b, c, d, e} - std::vector gp1_members1 {"a", "b", "c", "d"}; - std::vector gp1_members2 {"a", "c"}; - std::vector gp1_members3 {"a", "c", "e"}; + std::vector gp1_members1{"a", "b", "c", "d"}; + std::vector gp1_members2{"a", "c"}; + std::vector gp1_members3{"a", "c", "e"}; s = db.SAdd("GP1_SUNION_KEY1", gp1_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1667,8 +1592,7 @@ TEST_F(SetsTest, SUnionTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp1_keys {"GP1_SUNION_KEY1", - "GP1_SUNION_KEY2", "GP1_SUNION_KEY3"}; + std::vector gp1_keys{"GP1_SUNION_KEY1", "GP1_SUNION_KEY2", "GP1_SUNION_KEY3"}; std::vector gp1_members_out; s = db.SUnion(gp1_keys, &gp1_members_out); ASSERT_TRUE(s.ok()); @@ -1688,15 +1612,14 @@ TEST_F(SetsTest, SUnionTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp1_members_out, {"a", "b", "c", "d"})); - // ***************** Group 2 Test ***************** // key1 = {a, b, c, d} // key2 = {a, c} // key3 = {a, c, e} // SUNION key1 key2 key3 not_exist_key = {a, b, c, d, e} - std::vector gp2_members1 {"a", "b", "c", "d"}; - std::vector gp2_members2 {"a", "c"}; - std::vector gp2_members3 {"a", "c", "e"}; + std::vector gp2_members1{"a", "b", "c", "d"}; + std::vector gp2_members2{"a", "c"}; + std::vector gp2_members3{"a", "c", "e"}; s = db.SAdd("GP2_SUNION_KEY1", gp2_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1707,22 +1630,20 @@ TEST_F(SetsTest, SUnionTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp2_keys {"GP2_SUNION_KEY1", - "GP2_SUNION_KEY2", "GP2_SUNION_KEY3", "GP2_NOT_EXIST_KEY"}; + std::vector gp2_keys{"GP2_SUNION_KEY1", "GP2_SUNION_KEY2", "GP2_SUNION_KEY3", "GP2_NOT_EXIST_KEY"}; std::vector gp2_members_out; s = db.SUnion(gp2_keys, &gp2_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp2_members_out, {"a", "b", "c", "d", "e"})); - // ***************** Group 3 Test ***************** // key1 = {a, b, c, d} // key2 = {a, c} // key3 = {} // SUNION key1 key2 key3 = {a, b, c, d} - std::vector gp3_members1 {"a", "b", "c", "d"}; - std::vector gp3_members2 {"a", "c"}; - std::vector gp3_members3 {"a", "c", "e", "f", "g"}; + std::vector gp3_members1{"a", "b", "c", "d"}; + std::vector gp3_members2{"a", "c"}; + std::vector gp3_members3{"a", "c", "e", "f", "g"}; s = db.SAdd("GP3_SUNION_KEY1", gp3_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1744,23 +1665,21 @@ TEST_F(SetsTest, SUnionTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(gp3_members_out.size(), 0); - std::vector gp3_keys {"GP3_SUNION_KEY1", - "GP3_SUNION_KEY2", "GP3_SUNION_KEY3"}; + std::vector gp3_keys{"GP3_SUNION_KEY1", "GP3_SUNION_KEY2", "GP3_SUNION_KEY3"}; gp3_members_out.clear(); s = db.SUnion(gp3_keys, &gp3_members_out); ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(gp3_members_out, {"a", "b", "c", "d"})); - // ***************** Group 4 Test ***************** // key1 = {a, b, c, d} // SUNION key1 = {a, b, c, d} - std::vector gp4_members1 {"a", "b", "c", "d"}; + std::vector gp4_members1{"a", "b", "c", "d"}; s = db.SAdd("GP4_SUNION_KEY1", gp4_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); - std::vector gp4_keys {"GP4_SUNION_KEY1"}; + std::vector gp4_keys{"GP4_SUNION_KEY1"}; std::vector gp4_members_out; s = db.SUnion(gp4_keys, &gp4_members_out); ASSERT_TRUE(s.ok()); @@ -1778,9 +1697,9 @@ TEST_F(SetsTest, SUnionstoreTest) { // key3 = {a, c, e} // SUNIONSTORE destination key1 key2 key3 // destination = {a, b, c, d, e} - std::vector gp1_members1 {"a", "b", "c", "d"}; - std::vector gp1_members2 {"a", "c"}; - std::vector gp1_members3 {"a", "c", "e"}; + std::vector gp1_members1{"a", "b", "c", "d"}; + std::vector gp1_members2{"a", "c"}; + std::vector gp1_members3{"a", "c", "e"}; s = db.SAdd("GP1_SUNIONSTORE_KEY1", gp1_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1791,14 +1710,12 @@ TEST_F(SetsTest, SUnionstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp1_keys {"GP1_SUNIONSTORE_KEY1", - "GP1_SUNIONSTORE_KEY2", "GP1_SUNIONSTORE_KEY3"}; + std::vector gp1_keys{"GP1_SUNIONSTORE_KEY1", "GP1_SUNIONSTORE_KEY2", "GP1_SUNIONSTORE_KEY3"}; s = db.SUnionstore("GP1_SUNIONSTORE_DESTINATION1", gp1_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 5); ASSERT_TRUE(size_match(&db, "GP1_SUNIONSTORE_DESTINATION1", 5)); - ASSERT_TRUE(members_match(&db, "GP1_SUNIONSTORE_DESTINATION1", - {"a", "b", "c", "d", "e"})); + ASSERT_TRUE(members_match(&db, "GP1_SUNIONSTORE_DESTINATION1", {"a", "b", "c", "d", "e"})); // destination = {} // key1 = {a, b, c, d} @@ -1812,9 +1729,7 @@ TEST_F(SetsTest, SUnionstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(size_match(&db, "GP1_SUNIONSTORE_DESTINATION1", 4)); - ASSERT_TRUE(members_match(&db, "GP1_SUNIONSTORE_DESTINATION1", - {"a", "b", "c", "d"})); - + ASSERT_TRUE(members_match(&db, "GP1_SUNIONSTORE_DESTINATION1", {"a", "b", "c", "d"})); // ***************** Group 2 Test ***************** // destination already exists, it is overwritten. @@ -1824,9 +1739,9 @@ TEST_F(SetsTest, SUnionstoreTest) { // key3 = {a, c, e} // SUNIONSTORE destination key1 key2 key3 // destination = {a, b, c, d, e} - std::vector gp2_members1 {"a", "b", "c", "d"}; - std::vector gp2_members2 {"a", "c"}; - std::vector gp2_members3 {"a", "c", "e"}; + std::vector gp2_members1{"a", "b", "c", "d"}; + std::vector gp2_members2{"a", "c"}; + std::vector gp2_members3{"a", "c", "e"}; s = db.SAdd("GP2_SUNIONSTORE_KEY1", gp2_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1837,15 +1752,12 @@ TEST_F(SetsTest, SUnionstoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp2_keys {"GP2_SUNIONSTORE_KEY1", - "GP2_SUNIONSTORE_KEY2", "GP2_SUNIONSTORE_KEY3"}; + std::vector gp2_keys{"GP2_SUNIONSTORE_KEY1", "GP2_SUNIONSTORE_KEY2", "GP2_SUNIONSTORE_KEY3"}; s = db.SUnionstore("GP2_SUNIONSTORE_DESTINATION1", gp2_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 5); ASSERT_TRUE(size_match(&db, "GP2_SUNIONSTORE_DESTINATION1", 5)); - ASSERT_TRUE(members_match(&db, "GP2_SUNIONSTORE_DESTINATION1", - {"a", "b", "c", "d", "e"})); - + ASSERT_TRUE(members_match(&db, "GP2_SUNIONSTORE_DESTINATION1", {"a", "b", "c", "d", "e"})); // ***************** Group 3 Test ***************** // destination = {} @@ -1854,9 +1766,9 @@ TEST_F(SetsTest, SUnionstoreTest) { // key3 = {} // SUNIONSTORE destination key1 key2 key3 // destination = {a, b, c, d} - std::vector gp3_members1 {"a", "b", "c", "d"}; - std::vector gp3_members2 {"a", "c"}; - std::vector gp3_members3 {"a", "x", "l"}; + std::vector gp3_members1{"a", "b", "c", "d"}; + std::vector gp3_members2{"a", "c"}; + std::vector gp3_members3{"a", "x", "l"}; s = db.SAdd("GP3_SUNIONSTORE_KEY1", gp3_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); @@ -1873,47 +1785,41 @@ TEST_F(SetsTest, SUnionstoreTest) { ASSERT_TRUE(size_match(&db, "GP3_SUNIONSTORE_KEY3", 0)); ASSERT_TRUE(members_match(&db, "GP3_SUNIONSTORE_KEY3", {})); - std::vector gp3_keys {"GP3_SUNIONSTORE_KEY1", - "GP3_SUNIONSTORE_KEY2", "GP3_SUNIONSTORE_KEY3"}; + std::vector gp3_keys{"GP3_SUNIONSTORE_KEY1", "GP3_SUNIONSTORE_KEY2", "GP3_SUNIONSTORE_KEY3"}; s = db.SUnionstore("GP3_SUNIONSTORE_DESTINATION1", gp3_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(size_match(&db, "GP3_SUNIONSTORE_DESTINATION1", 4)); - ASSERT_TRUE(members_match(&db, "GP3_SUNIONSTORE_DESTINATION1", - {"a", "b", "c", "d"})); - + ASSERT_TRUE(members_match(&db, "GP3_SUNIONSTORE_DESTINATION1", {"a", "b", "c", "d"})); // ***************** Group 4 Test ***************** // destination = {} // key1 = {a, x, l} // SUNIONSTORE destination key1 not_exist_key // destination = {a, x, l} - std::vector gp4_members1 {"a", "x", "l"}; + std::vector gp4_members1{"a", "x", "l"}; s = db.SAdd("GP4_SUNIONSTORE_KEY1", gp4_members1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); - std::vector gp4_keys {"GP4_SUNIONSTORE_KEY1", - "GP4_SUNIONSTORE_NOT_EXIST_KEY"}; + std::vector gp4_keys{"GP4_SUNIONSTORE_KEY1", "GP4_SUNIONSTORE_NOT_EXIST_KEY"}; std::vector gp4_members_out; s = db.SUnionstore("GP4_SUNIONSTORE_DESTINATION1", gp4_keys, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP4_SUNIONSTORE_DESTINATION1", 3)); - ASSERT_TRUE(members_match(&db, "GP4_SUNIONSTORE_DESTINATION1", - {"a", "x", "l"})); + ASSERT_TRUE(members_match(&db, "GP4_SUNIONSTORE_DESTINATION1", {"a", "x", "l"})); } // SScan TEST_F(SetsTest, SScanTest) { - int32_t ret = 0; int64_t cursor = 0, next_cursor = 0; std::vector member_out; // ***************** Group 1 Test ***************** // a b c d e f g h // 0 1 2 3 4 5 6 7 - std::vector gp1_members {"a", "b", "c", "d", "e", "f", "g", "h"}; + std::vector gp1_members{"a", "b", "c", "d", "e", "f", "g", "h"}; s = db.SAdd("GP1_SSCAN_KEY", gp1_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 8); @@ -1940,11 +1846,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"g", "h"})); - // ***************** Group 2 Test ***************** // a b c d e f g h // 0 1 2 3 4 5 6 7 - std::vector gp2_members {"a", "b", "c", "d", "e", "f", "g", "h"}; + std::vector gp2_members{"a", "b", "c", "d", "e", "f", "g", "h"}; s = db.SAdd("GP2_SSCAN_KEY", gp2_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 8); @@ -2013,11 +1918,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"h"})); - // ***************** Group 3 Test ***************** // a b c d e f g h // 0 1 2 3 4 5 6 7 - std::vector gp3_members {"a", "b", "c", "d", "e", "f", "g", "h"}; + std::vector gp3_members{"a", "b", "c", "d", "e", "f", "g", "h"}; s = db.SAdd("GP3_SSCAN_KEY", gp3_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 8); @@ -2038,11 +1942,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"f", "g", "h"})); - // ***************** Group 4 Test ***************** // a b c d e f g h // 0 1 2 3 4 5 6 7 - std::vector gp4_members {"a", "b", "c", "d", "e", "f", "g", "h"}; + std::vector gp4_members{"a", "b", "c", "d", "e", "f", "g", "h"}; s = db.SAdd("GP4_SSCAN_KEY", gp4_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 8); @@ -2055,11 +1958,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"a", "b", "c", "d", "e", "f", "g", "h"})); - // ***************** Group 5 Test ***************** // a_1_ a_2_ a_3_ b_1_ b_2_ b_3_ c_1_ c_2_ c_3 - // 0 1 2 3 4 5 6 7 8 - std::vector gp5_members {"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; + // 0 1 2 3 4 5 6 7 8 + std::vector gp5_members{"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; s = db.SAdd("GP5_SSCAN_KEY", gp5_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -2088,11 +1990,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"c_1_"})); - // ***************** Group 6 Test ***************** // a_1_ a_2_ a_3_ b_1_ b_2_ b_3_ c_1_ c_2_ c_3_ // 0 1 2 3 4 5 6 7 8 - std::vector gp6_members {"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; + std::vector gp6_members{"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; s = db.SAdd("GP6_SSCAN_KEY", gp6_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -2145,11 +2046,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"a_3_"})); - // ***************** Group 7 Test ***************** // a_1_ a_2_ a_3_ b_1_ b_2_ b_3_ c_1_ c_2_ c_3 // 0 1 2 3 4 5 6 7 8 - std::vector gp7_members {"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; + std::vector gp7_members{"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; s = db.SAdd("GP7_SSCAN_KEY", gp7_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -2202,11 +2102,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"b_3_"})); - // ***************** Group 8 Test ***************** // a_1_ a_2_ a_3_ b_1_ b_2_ b_3_ c_1_ c_2_ c_3 // 0 1 2 3 4 5 6 7 8 - std::vector gp8_members {"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; + std::vector gp8_members{"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; s = db.SAdd("GP8_SSCAN_KEY", gp8_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -2259,11 +2158,10 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {"c_3_"})); - // ***************** Group 9 Test ***************** // a_1_ a_2_ a_3_ b_1_ b_2_ b_3_ c_1_ c_2_ c_3 // 0 1 2 3 4 5 6 7 8 - std::vector gp9_members {"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; + std::vector gp9_members{"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; s = db.SAdd("GP9_SSCAN_KEY", gp9_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -2276,12 +2174,11 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {})); - // ***************** Group 10 Test ***************** // a_1_ a_2_ a_3_ b_1_ b_2_ b_3_ c_1_ c_2_ c_3 // 0 1 2 3 4 5 6 7 8 // SScan Expired Key - std::vector gp10_members {"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; + std::vector gp10_members{"a_1_", "a_2_", "a_3_", "b_1_", "b_2_", "b_3_", "c_1_", "c_2_", "c_3_"}; s = db.SAdd("GP10_SSCAN_KEY", gp10_members, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -2295,7 +2192,6 @@ TEST_F(SetsTest, SScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(members_match(member_out, {})); - // ***************** Group 11 Test ***************** // SScan Not Exist Key member_out.clear(); @@ -2307,7 +2203,6 @@ TEST_F(SetsTest, SScanTest) { ASSERT_TRUE(members_match(member_out, {})); } - int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/src/storage/tests/strings_filter_test.cc b/src/storage/tests/strings_filter_test.cc index 6b872b5707..c4d95dcc48 100644 --- a/src/storage/tests/strings_filter_test.cc +++ b/src/storage/tests/strings_filter_test.cc @@ -4,11 +4,11 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include -#include "storage/storage.h" #include "src/strings_filter.h" +#include "storage/storage.h" using namespace storage; @@ -21,12 +21,10 @@ TEST(StringsFilterTest, FilterTest) { int32_t ttl = 1; StringsValue strings_value("FILTER_VALUE"); strings_value.SetRelativeTimestamp(ttl); - is_stale = filter->Filter(0, "FILTER_KEY", - strings_value.Encode(), &new_value, &value_changed); + is_stale = filter->Filter(0, "FILTER_KEY", strings_value.Encode(), &new_value, &value_changed); ASSERT_FALSE(is_stale); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); - is_stale = filter->Filter(0, "FILTER_KEY", - strings_value.Encode(), &new_value, &value_changed); + is_stale = filter->Filter(0, "FILTER_KEY", strings_value.Encode(), &new_value, &value_changed); ASSERT_TRUE(is_stale); delete filter; @@ -36,4 +34,3 @@ int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } - diff --git a/src/storage/tests/strings_test.cc b/src/storage/tests/strings_test.cc index ca47f33246..da161d1225 100644 --- a/src/storage/tests/strings_test.cc +++ b/src/storage/tests/strings_test.cc @@ -4,8 +4,8 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include #include "storage/storage.h" #include "storage/util.h" @@ -14,8 +14,8 @@ using namespace storage; class StringsTest : public ::testing::Test { public: - StringsTest() { } - virtual ~StringsTest() { } + StringsTest() {} + virtual ~StringsTest() {} void SetUp() override { std::string path = "./db/strings"; @@ -31,16 +31,15 @@ class StringsTest : public ::testing::Test { DeleteFiles(path.c_str()); } - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Storage db; storage::Status s; }; -static bool make_expired(storage::Storage *const db, - const Slice& key) { +static bool make_expired(storage::Storage* const db, const Slice& key) { std::map type_status; int ret = db->Expire(key, 1, &type_status); if (!ret || !type_status[storage::DataType::kStrings].ok()) { @@ -50,14 +49,12 @@ static bool make_expired(storage::Storage *const db, return true; } -static bool string_ttl(storage::Storage *const db, - const Slice& key, int32_t* ttl) { +static bool string_ttl(storage::Storage* const db, const Slice& key, int32_t* ttl) { std::map type_ttl; std::map type_status; type_ttl = db->TTL(key, &type_status); for (const auto& item : type_status) { - if (item.second != Status::OK() - && item.second != Status::NotFound()) { + if (item.second != Status::OK() && item.second != Status::NotFound()) { return false; } } @@ -88,7 +85,6 @@ TEST_F(StringsTest, AppendTest) { s = db.Get("GP1_APPEND_KEY", &value); ASSERT_STREQ(value.c_str(), "HELLO WORLD"); - // ***************** Group 2 Test ***************** s = db.Set("GP2_APPEND_KEY", "VALUE"); ASSERT_TRUE(s.ok()); @@ -110,7 +106,6 @@ TEST_F(StringsTest, AppendTest) { ASSERT_LE(type_ttl[kStrings], 100); ASSERT_GE(type_ttl[kStrings], 0); - // ***************** Group 3 Test ***************** s = db.Set("GP3_APPEND_KEY", "VALUE"); ASSERT_TRUE(s.ok()); @@ -225,7 +220,6 @@ TEST_F(StringsTest, DecrbyTest) { s = db.Decrby("GP1_DECRBY_KEY", 9223372036854775807, &ret); ASSERT_TRUE(s.IsInvalidArgument()); - // ***************** Group 2 Test ***************** s = db.Set("GP2_DECRBY_KEY", "10"); ASSERT_TRUE(s.ok()); @@ -246,7 +240,6 @@ TEST_F(StringsTest, DecrbyTest) { ASSERT_LE(type_ttl[kStrings], 100); ASSERT_GE(type_ttl[kStrings], 0); - // ***************** Group 3 Test ***************** s = db.Set("GP3_DECRBY_KEY", "10"); ASSERT_TRUE(s.ok()); @@ -262,7 +255,6 @@ TEST_F(StringsTest, DecrbyTest) { type_ttl = db.TTL("GP3_DECRBY_KEY", &type_status); ASSERT_EQ(type_ttl[kStrings], -1); - // ***************** Group 4 Test ***************** s = db.Set("GP4_DECRBY_KEY", "100000"); ASSERT_TRUE(s.ok()); @@ -378,7 +370,6 @@ TEST_F(StringsTest, IncrbyTest) { s = db.Incrby("GP1_INCRBY_KEY", 9223372036854775807, &ret); ASSERT_TRUE(s.IsInvalidArgument()); - // ***************** Group 2 Test ***************** s = db.Set("GP2_INCRBY_KEY", "10"); ASSERT_TRUE(s.ok()); @@ -399,7 +390,6 @@ TEST_F(StringsTest, IncrbyTest) { ASSERT_LE(type_ttl[kStrings], 100); ASSERT_GE(type_ttl[kStrings], 0); - // ***************** Group 3 Test ***************** s = db.Set("GP3_INCRBY_KEY", "10"); ASSERT_TRUE(s.ok()); @@ -415,7 +405,6 @@ TEST_F(StringsTest, IncrbyTest) { type_ttl = db.TTL("GP3_INCRBY_KEY", &type_status); ASSERT_EQ(type_ttl[kStrings], -1); - // ***************** Group 4 Test ***************** s = db.Set("GP4_INCRBY_KEY", "50000"); ASSERT_TRUE(s.ok()); @@ -425,7 +414,6 @@ TEST_F(StringsTest, IncrbyTest) { ASSERT_EQ(ret, 100000); s = db.Get("GP4_INCRBY_KEY", &value); ASSERT_EQ(value, "100000"); - } // Incrbyfloat @@ -451,7 +439,6 @@ TEST_F(StringsTest, IncrbyfloatTest) { s = db.Incrbyfloat("GP1_INCRBYFLOAT_KEY", "5", &value); ASSERT_TRUE(s.IsCorruption()); - // ***************** Group 2 Test ***************** s = db.Set("GP2_INCRBYFLOAT_KEY", "10.11111"); ASSERT_TRUE(s.ok()); @@ -472,7 +459,6 @@ TEST_F(StringsTest, IncrbyfloatTest) { ASSERT_LE(type_ttl[kStrings], 100); ASSERT_GE(type_ttl[kStrings], 0); - // ***************** Group 3 Test ***************** s = db.Set("GP3_INCRBYFLOAT_KEY", "10"); ASSERT_TRUE(s.ok()); @@ -488,7 +474,6 @@ TEST_F(StringsTest, IncrbyfloatTest) { type_ttl = db.TTL("GP3_INCRBYFLOAT_KEY", &type_status); ASSERT_EQ(type_ttl[kStrings], -1); - // ***************** Group 4 Test ***************** s = db.Set("GP4_INCRBYFLOAT_KEY", "100.001"); ASSERT_TRUE(s.ok()); @@ -505,16 +490,11 @@ TEST_F(StringsTest, MGetTest) { std::vector vss; // ***************** Group 1 Test ***************** - std::vector kvs1 {{"GP1_MGET_KEY1", "VALUE1"}, - {"GP1_MGET_KEY2", "VALUE2"}, - {"GP1_MGET_KEY3", "VALUE3"}}; + std::vector kvs1{ + {"GP1_MGET_KEY1", "VALUE1"}, {"GP1_MGET_KEY2", "VALUE2"}, {"GP1_MGET_KEY3", "VALUE3"}}; s = db.MSet(kvs1); ASSERT_TRUE(s.ok()); - std::vector keys1 {"", - "GP1_MGET_KEY1", - "GP1_MGET_KEY2", - "GP1_MGET_KEY3", - "GP1_MGET_NOT_EXIST_KEY"}; + std::vector keys1{"", "GP1_MGET_KEY1", "GP1_MGET_KEY2", "GP1_MGET_KEY3", "GP1_MGET_NOT_EXIST_KEY"}; vss.clear(); s = db.MGet(keys1, &vss); ASSERT_TRUE(s.ok()); @@ -530,17 +510,11 @@ TEST_F(StringsTest, MGetTest) { ASSERT_TRUE(vss[4].status.IsNotFound()); ASSERT_EQ(vss[4].value, ""); - // ***************** Group 2 Test ***************** - std::vector kvs2 {{"GP2_MGET_KEY1", "VALUE1"}, - {"GP2_MGET_KEY2", "VALUE2"}, - {"GP2_MGET_KEY3", ""}}; + std::vector kvs2{{"GP2_MGET_KEY1", "VALUE1"}, {"GP2_MGET_KEY2", "VALUE2"}, {"GP2_MGET_KEY3", ""}}; s = db.MSet(kvs2); ASSERT_TRUE(s.ok()); - std::vector keys2 {"GP2_MGET_KEY1", - "GP2_MGET_KEY2", - "GP2_MGET_KEY3", - "GP2_MGET_NOT_EXIST_KEY"}; + std::vector keys2{"GP2_MGET_KEY1", "GP2_MGET_KEY2", "GP2_MGET_KEY3", "GP2_MGET_NOT_EXIST_KEY"}; ASSERT_TRUE(make_expired(&db, "GP2_MGET_KEY2")); vss.clear(); @@ -626,7 +600,6 @@ TEST_F(StringsTest, SetBitTest) { ASSERT_TRUE(s.ok()); ASSERT_STREQ(value.c_str(), "\x00"); - // ***************** Group 2 Test ***************** s = db.SetBit("GP2_SETBIT_KEY", 10081, 1, &ret); ASSERT_TRUE(s.ok()); @@ -644,7 +617,6 @@ TEST_F(StringsTest, SetBitTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); - // ***************** Group 3 Test ***************** s = db.SetBit("GP3_SETBIT_KEY", 1, 1, &ret); ASSERT_TRUE(s.ok()); @@ -662,7 +634,6 @@ TEST_F(StringsTest, SetBitTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); - // ***************** Group 4 Test ***************** s = db.SetBit("GP4_SETBIT_KEY", 1, 1, &ret); ASSERT_TRUE(s.ok()); @@ -673,7 +644,6 @@ TEST_F(StringsTest, SetBitTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); - // ***************** Group 5 Test ***************** // The offset argument is less than 0 s = db.SetBit("GP5_SETBIT_KEY", -1, 0, &ret); @@ -721,7 +691,6 @@ TEST_F(StringsTest, SetnxTest) { // Setvx TEST_F(StringsTest, SetvxTest) { - int32_t ret, ttl; std::string value; // ***************** Group 1 Test ***************** @@ -736,7 +705,6 @@ TEST_F(StringsTest, SetvxTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(value, "GP1_SETVX_NEW_VALUE"); - // ***************** Group 2 Test ***************** s = db.Setvx("GP2_SETVX_KEY", "GP2_SETVX_VALUE", "GP2_SETVX_NEW_VALUE", &ret); ASSERT_TRUE(s.ok()); @@ -746,7 +714,6 @@ TEST_F(StringsTest, SetvxTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(value, ""); - // ***************** Group 3 Test ***************** s = db.Set("GP3_SETVX_KEY", "GP3_SETVX_VALUE"); ASSERT_TRUE(s.ok()); @@ -759,7 +726,6 @@ TEST_F(StringsTest, SetvxTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(value, "GP3_SETVX_VALUE"); - // ***************** Group 4 Test ***************** s = db.Set("GP4_SETVX_KEY", "GP4_SETVX_VALUE"); ASSERT_TRUE(s.ok()); @@ -773,7 +739,6 @@ TEST_F(StringsTest, SetvxTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(value, ""); - // ***************** Group 5 Test ***************** s = db.Set("GP5_SETVX_KEY", "GP5_SETVX_VALUE"); ASSERT_TRUE(s.ok()); @@ -790,7 +755,6 @@ TEST_F(StringsTest, SetvxTest) { ASSERT_LE(0, ttl); ASSERT_GE(10, ttl); - // ***************** Group 6 Test ***************** s = db.Set("GP6_SETVX_KEY", "GP6_SETVX_VALUE"); ASSERT_TRUE(s.ok()); @@ -820,7 +784,6 @@ TEST_F(StringsTest, SetvxTest) { // Delvx TEST_F(StringsTest, DelvxTest) { - int32_t ret, ttl; std::string value; // ***************** Group 1 Test ***************** @@ -835,7 +798,6 @@ TEST_F(StringsTest, DelvxTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(value, ""); - // ***************** Group 2 Test ***************** s = db.Delvx("GP2_DELVX_KEY", "GP2_DELVX_VALUE", &ret); ASSERT_TRUE(s.IsNotFound()); @@ -845,7 +807,6 @@ TEST_F(StringsTest, DelvxTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(value, ""); - // ***************** Group 3 Test ***************** s = db.Set("GP3_DELVX_KEY", "GP3_DELVX_VALUE"); ASSERT_TRUE(s.ok()); @@ -858,7 +819,6 @@ TEST_F(StringsTest, DelvxTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(value, "GP3_DELVX_VALUE"); - // ***************** Group 4 Test ***************** s = db.Set("GP4_DELVX_KEY", "GP4_DELVX_VALUE"); ASSERT_TRUE(s.ok()); @@ -885,7 +845,7 @@ TEST_F(StringsTest, SetrangeTest) { s = db.Get("SETRANGE_KEY", &value); ASSERT_STREQ(value.c_str(), "HELLO REDIS"); - std::vector keys {"SETRANGE_KEY"}; + std::vector keys{"SETRANGE_KEY"}; std::map type_status; ret = db.Del(keys, &type_status); ASSERT_EQ(ret, 1); @@ -991,7 +951,6 @@ TEST_F(StringsTest, PKSetexAtTest) { ASSERT_LE(ttl_ret[DataType::kStrings], 100); ASSERT_GE(ttl_ret[DataType::kStrings], 90); - // ***************** Group 2 Test ***************** s = db.Set("GP2_PKSETEX_KEY", "VALUE"); ASSERT_TRUE(s.ok()); @@ -1004,7 +963,6 @@ TEST_F(StringsTest, PKSetexAtTest) { ASSERT_LE(ttl_ret[DataType::kStrings], 100); ASSERT_GE(ttl_ret[DataType::kStrings], 90); - // ***************** Group 3 Test ***************** s = db.PKSetexAt("GP3_PKSETEX_KEY", "VALUE", unix_time - 100); ASSERT_TRUE(s.ok()); @@ -1013,7 +971,6 @@ TEST_F(StringsTest, PKSetexAtTest) { ttl_ret = db.TTL("GP3_PKSETEX_KEY", &type_status); ASSERT_EQ(ttl_ret[DataType::kStrings], -2); - // ***************** Group 4 Test ***************** s = db.Set("GP4_PKSETEX_KEY", "VALUE"); ASSERT_TRUE(s.ok()); @@ -1024,7 +981,6 @@ TEST_F(StringsTest, PKSetexAtTest) { ttl_ret = db.TTL("GP4_PKSETEX_KEY", &type_status); ASSERT_EQ(ttl_ret[DataType::kStrings], -2); - // ***************** Group 5 Test ***************** s = db.PKSetexAt("GP5_PKSETEX_KEY", "VALUE", -unix_time); ASSERT_TRUE(s.ok()); @@ -1033,7 +989,6 @@ TEST_F(StringsTest, PKSetexAtTest) { ttl_ret = db.TTL("GP5_PKSETEX_KEY", &type_status); ASSERT_EQ(ttl_ret[DataType::kStrings], -2); - // ***************** Group 6 Test ***************** s = db.Set("GP6_PKSETEX_KEY", "VALUE"); ASSERT_TRUE(s.ok()); diff --git a/src/storage/tests/zsets_test.cc b/src/storage/tests/zsets_test.cc index 6f8e5235b9..a8adf98e1f 100644 --- a/src/storage/tests/zsets_test.cc +++ b/src/storage/tests/zsets_test.cc @@ -4,8 +4,8 @@ // of patent rights can be found in the PATENTS file in the same directory. #include -#include #include +#include #include "storage/storage.h" #include "storage/util.h" @@ -14,8 +14,8 @@ using namespace storage; class ZSetsTest : public ::testing::Test { public: - ZSetsTest() { } - virtual ~ZSetsTest() { } + ZSetsTest() {} + virtual ~ZSetsTest() {} void SetUp() override { std::string path = "./db/zsets"; @@ -35,16 +35,15 @@ class ZSetsTest : public ::testing::Test { DeleteFiles(path.c_str()); } - static void SetUpTestCase() { } - static void TearDownTestCase() { } + static void SetUpTestCase() {} + static void TearDownTestCase() {} StorageOptions storage_options; storage::Storage db; storage::Status s; }; -static bool members_match(const std::vector& mm_out, - const std::vector& expect_members) { +static bool members_match(const std::vector& mm_out, const std::vector& expect_members) { if (mm_out.size() != expect_members.size()) { return false; } @@ -56,8 +55,7 @@ static bool members_match(const std::vector& mm_out, return true; } -static bool score_members_match(storage::Storage *const db, - const Slice& key, +static bool score_members_match(storage::Storage* const db, const Slice& key, const std::vector& expect_sm) { std::vector sm_out; Status s = db->ZRange(key, 0, -1, &sm_out); @@ -71,8 +69,7 @@ static bool score_members_match(storage::Storage *const db, return true; } for (int idx = 0; idx < sm_out.size(); ++idx) { - if (expect_sm[idx].score != sm_out[idx].score - || expect_sm[idx].member != sm_out[idx].member) { + if (expect_sm[idx].score != sm_out[idx].score || expect_sm[idx].member != sm_out[idx].member) { return false; } } @@ -85,17 +82,14 @@ static bool score_members_match(const std::vector& sm_out, return false; } for (int idx = 0; idx < sm_out.size(); ++idx) { - if (expect_sm[idx].score != sm_out[idx].score - || expect_sm[idx].member != sm_out[idx].member) { + if (expect_sm[idx].score != sm_out[idx].score || expect_sm[idx].member != sm_out[idx].member) { return false; } } return true; } -static bool size_match(storage::Storage *const db, - const Slice& key, - int32_t expect_size) { +static bool size_match(storage::Storage* const db, const Slice& key, int32_t expect_size) { int32_t size = 0; Status s = db->ZCard(key, &size); if (!s.ok() && !s.IsNotFound()) { @@ -107,8 +101,7 @@ static bool size_match(storage::Storage *const db, return size == expect_size; } -static bool make_expired(storage::Storage *const db, - const Slice& key) { +static bool make_expired(storage::Storage* const db, const Slice& key) { std::map type_status; int ret = db->Expire(key, 1, &type_status); if (!ret || !type_status[storage::DataType::kZSets].ok()) { @@ -118,16 +111,15 @@ static bool make_expired(storage::Storage *const db, return true; } -static bool delete_key(storage::Storage *const db, - const Slice& key) { +static bool delete_key(storage::Storage* const db, const Slice& key) { std::vector del_keys = {key.ToString()}; std::map type_status; db->Del(del_keys, &type_status); return type_status[storage::DataType::kZSets].ok(); } -//ZPopMax -TEST_F(ZSetsTest, ZPopMaxTest){ +// ZPopMax +TEST_F(ZSetsTest, ZPopMaxTest) { int32_t ret; std::map type_ttl; std::map type_status; @@ -137,16 +129,17 @@ TEST_F(ZSetsTest, ZPopMaxTest){ // [0, MM2] // [3.23, MM1] // [8.0004, MM3] - std::vector gp1_sm {{3.23, "MM1"}, {0, "MM2"}, {8.0004, "MM3"}, {-0.54, "MM4"}}; + std::vector gp1_sm{{3.23, "MM1"}, {0, "MM2"}, {8.0004, "MM3"}, {-0.54, "MM4"}}; Status s = db.ZAdd("GP1_ZPOPMAX_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); ASSERT_TRUE(size_match(&db, "GP1_ZPOPMAX_KEY", 4)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZPOPMAX_KEY", {{-0.54, "MM4"}, {0, "MM2"}, {3.23, "MM1"}, {8.0004, "MM3"}})); + ASSERT_TRUE( + score_members_match(&db, "GP1_ZPOPMAX_KEY", {{-0.54, "MM4"}, {0, "MM2"}, {3.23, "MM1"}, {8.0004, "MM3"}})); std::vector score_members; s = db.ZPopMax("GP1_ZPOPMAX_KEY", 1, &score_members); - - // [-0.54, MM4] ret: [8.0004, MM3] + + // [-0.54, MM4] ret: [8.0004, MM3] // [0, MM2] // [3.23, MM1] ASSERT_TRUE(s.ok()); @@ -155,8 +148,8 @@ TEST_F(ZSetsTest, ZPopMaxTest){ ASSERT_TRUE(score_members_match(&db, "GP1_ZPOPMAX_KEY", {{-0.54, "MM4"}, {0, "MM2"}, {3.23, "MM1"}})); ASSERT_TRUE(size_match(&db, "GP1_ZPOPMAX_KEY", 3)); s = db.ZPopMax("GP1_ZPOPMAX_KEY", 3, &score_members); - - // ret: [3.23, MM1] + + // ret: [3.23, MM1] // [0, MM2] // [-0.54, MM4] ASSERT_TRUE(s.ok()); @@ -166,18 +159,17 @@ TEST_F(ZSetsTest, ZPopMaxTest){ ASSERT_TRUE(score_members_match(&db, "GP1_ZPOPMAX_KEY", {})); s = db.ZPopMax("GP1_ZPOPMAX_KEY", 1, &score_members); - // ret: + // ret: ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, score_members.size()); ASSERT_TRUE(size_match(&db, "GP1_ZPOPMAX_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP1_ZPOPMAX_KEY", {})); - - + // ***************** Group 2 Test ***************** - // [0, MM1] + // [0, MM1] // [0, MM2] // [0, MM3] - std::vector gp2_sm {{0, "MM1"}, {0, "MM2"}, {0, "MM3"}}; + std::vector gp2_sm{{0, "MM1"}, {0, "MM2"}, {0, "MM3"}}; s = db.ZAdd("GP2_ZPOPMAX_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); @@ -189,7 +181,7 @@ TEST_F(ZSetsTest, ZPopMaxTest){ // [0, MM2] ASSERT_TRUE(s.ok()); ASSERT_EQ(1, score_members.size()); - ASSERT_TRUE(size_match(&db, "GP2_ZPOPMAX_KEY", 2)); + ASSERT_TRUE(size_match(&db, "GP2_ZPOPMAX_KEY", 2)); ASSERT_TRUE(score_members_match(score_members, {{0, "MM3"}})); ASSERT_TRUE(score_members_match(&db, "GP2_ZPOPMAX_KEY", {{0, "MM1"}, {0, "MM2"}})); s = db.ZPopMax("GP2_ZPOPMAX_KEY", 3, &score_members); @@ -198,11 +190,10 @@ TEST_F(ZSetsTest, ZPopMaxTest){ // [0, MM1] ASSERT_TRUE(s.ok()); ASSERT_EQ(2, score_members.size()); - ASSERT_TRUE(size_match(&db, "GP2_ZPOPMAX_KEY", 0)); + ASSERT_TRUE(size_match(&db, "GP2_ZPOPMAX_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {{0, "MM2"}, {0, "MM1"}})); ASSERT_TRUE(score_members_match(&db, "GP2_ZPOPMAX_KEY", {})); - // ***************** Group 3 Test ***************** // [-1, MM3] // [-1, MM4] @@ -214,34 +205,24 @@ TEST_F(ZSetsTest, ZPopMaxTest){ // [1, MM2] // [2e5 + 3.98, MM10] // [2e5 + 3.98, MM9] - std::vector gp3_sm { - {1, "MM1"}, - {1, "MM2"}, - {-1, "MM3"}, - {-1, "MM4"}, - {1/6.0, "MM5"}, - {1/6.0, "MM6"}, - {0.532445, "MM7"}, - {0.532445, "MM8"}, - {2e5 + 3.98, "MM9"}, - {2e5 + 3.98, "MM10"} - }; + std::vector gp3_sm{ + {1, "MM1"}, {1, "MM2"}, {-1, "MM3"}, {-1, "MM4"}, {1 / 6.0, "MM5"}, + {1 / 6.0, "MM6"}, {0.532445, "MM7"}, {0.532445, "MM8"}, {2e5 + 3.98, "MM9"}, {2e5 + 3.98, "MM10"}}; s = db.ZAdd("GP3_ZPOPMAX_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(10, ret); ASSERT_TRUE(size_match(&db, "GP3_ZPOPMAX_KEY", 10)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZPOPMAX_KEY", { - {-1, "MM3"}, - {-1, "MM4"}, - {1/6.0, "MM5"}, - {1/6.0, "MM6"}, - {0.532445, "MM7"}, - {0.532445, "MM8"}, - {1, "MM1"}, - {1, "MM2"}, - {2e5 + 3.98, "MM10"}, - {2e5 + 3.98, "MM9"} - })); + ASSERT_TRUE(score_members_match(&db, "GP3_ZPOPMAX_KEY", + {{-1, "MM3"}, + {-1, "MM4"}, + {1 / 6.0, "MM5"}, + {1 / 6.0, "MM6"}, + {0.532445, "MM7"}, + {0.532445, "MM8"}, + {1, "MM1"}, + {1, "MM2"}, + {2e5 + 3.98, "MM10"}, + {2e5 + 3.98, "MM9"}})); s = db.ZPopMax("GP3_ZPOPMAX_KEY", 5, &score_members); // [-1, MM3] ret: [2e5 + 3.98, MM9] @@ -252,56 +233,57 @@ TEST_F(ZSetsTest, ZPopMaxTest){ ASSERT_TRUE(s.ok()); ASSERT_EQ(5, score_members.size()); ASSERT_TRUE(size_match(&db, "GP3_ZPOPMAX_KEY", 5)); - ASSERT_TRUE(score_members_match(score_members, {{2e5 + 3.98, "MM9"}, {2e5 + 3.98, "MM10"}, {1, "MM2"}, {1, "MM1"}, {0.532445, "MM8"}})); - ASSERT_TRUE(score_members_match(&db, "GP3_ZPOPMAX_KEY", {{-1, "MM3"}, {-1, "MM4"}, {1/6.0, "MM5"}, {1/6.0, "MM6"}, {0.532445, "MM7"}})); - + ASSERT_TRUE(score_members_match( + score_members, {{2e5 + 3.98, "MM9"}, {2e5 + 3.98, "MM10"}, {1, "MM2"}, {1, "MM1"}, {0.532445, "MM8"}})); + ASSERT_TRUE(score_members_match(&db, "GP3_ZPOPMAX_KEY", + {{-1, "MM3"}, {-1, "MM4"}, {1 / 6.0, "MM5"}, {1 / 6.0, "MM6"}, {0.532445, "MM7"}})); // ***************** Group 4 Test ***************** // s = db.ZPopMax("GP4_ZPOPMAX_KEY", 1, &score_members); - // ret: + // ret: ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, score_members.size()); - // ***************** Group 5 Test ***************** // [-1, MM1] // [0, MM2] // [1, MM3] - std::vector gp5_sm1 {{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}}; + std::vector gp5_sm1{{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}}; s = db.ZAdd("GP5_ZPOPMAX_KEY", gp5_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); - ASSERT_TRUE(size_match(&db, "GP5_ZPOPMAX_KEY", 3)); + ASSERT_TRUE(size_match(&db, "GP5_ZPOPMAX_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP5_ZPOPMAX_KEY", {{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}})); ASSERT_TRUE(make_expired(&db, "GP5_ZPOPMAX_KEY")); ASSERT_TRUE(size_match(&db, "GP5_ZPOPMAX_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP5_ZPOPMAX_KEY", {})); s = db.ZPopMax("GP5_ZPOPMAX_KEY", 1, &score_members); - // ret: + // ret: ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, score_members.size()); -} +} -//ZPopMin -TEST_F(ZSetsTest, ZPopMinTest) { +// ZPopMin +TEST_F(ZSetsTest, ZPopMinTest) { int32_t ret; std::map type_ttl; std::map type_status; // ***************** Group 1 Test ***************** - // [-0.54, MM4] + // [-0.54, MM4] // [0, MM2] // [3.23, MM1] // [8.0004, MM3] - std::vector gp1_sm {{3.23, "MM1"}, {0, "MM2"}, {8.0004, "MM3"}, {-0.54, "MM4"}}; - Status s = db.ZAdd("GP1_ZPOPMIN_KEY", gp1_sm, &ret); - ASSERT_TRUE(s.ok()); + std::vector gp1_sm{{3.23, "MM1"}, {0, "MM2"}, {8.0004, "MM3"}, {-0.54, "MM4"}}; + Status s = db.ZAdd("GP1_ZPOPMIN_KEY", gp1_sm, &ret); + ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); ASSERT_TRUE(size_match(&db, "GP1_ZPOPMIN_KEY", 4)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZPOPMIN_KEY", {{-0.54, "MM4"}, {0, "MM2"}, {3.23, "MM1"}, {8.0004, "MM3"}})); + ASSERT_TRUE( + score_members_match(&db, "GP1_ZPOPMIN_KEY", {{-0.54, "MM4"}, {0, "MM2"}, {3.23, "MM1"}, {8.0004, "MM3"}})); std::vector score_members; s = db.ZPopMin("GP1_ZPOPMIN_KEY", 1, &score_members); @@ -325,18 +307,17 @@ TEST_F(ZSetsTest, ZPopMinTest) { ASSERT_TRUE(score_members_match(&db, "GP1_ZPOPMIN_KEY", {})); s = db.ZPopMin("GP1_ZPOPMIN_KEY", 1, &score_members); - // ret: + // ret: ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, score_members.size()); ASSERT_TRUE(size_match(&db, "GP1_ZPOPMIN_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP1_ZPOPMIN_KEY", {})); - - + // ***************** Group 2 Test ***************** // [0, MM1] // [0, MM2] // [0, MM3] - std::vector gp2_sm {{0, "MM1"}, {0, "MM2"}, {0, "MM3"}}; + std::vector gp2_sm{{0, "MM1"}, {0, "MM2"}, {0, "MM3"}}; s = db.ZAdd("GP2_ZPOPMIN_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); @@ -345,22 +326,21 @@ TEST_F(ZSetsTest, ZPopMinTest) { s = db.ZPopMin("GP2_ZPOPMIN_KEY", 1, &score_members); // [0, MM2] ret: [0, MM1] - // [0, MM3] + // [0, MM3] ASSERT_TRUE(s.ok()); ASSERT_EQ(1, score_members.size()); - ASSERT_TRUE(size_match(&db, "GP2_ZPOPMIN_KEY", 2)); + ASSERT_TRUE(size_match(&db, "GP2_ZPOPMIN_KEY", 2)); ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}})); - ASSERT_TRUE(score_members_match(&db,"GP2_ZPOPMIN_KEY",{{0, "MM2"}, {0, "MM3"}})); + ASSERT_TRUE(score_members_match(&db, "GP2_ZPOPMIN_KEY", {{0, "MM2"}, {0, "MM3"}})); s = db.ZPopMin("GP2_ZPOPMIN_KEY", 3, &score_members); // ret: [0, MM2] - // [0, MM3] + // [0, MM3] ASSERT_TRUE(s.ok()); ASSERT_EQ(score_members.size(), 2); - ASSERT_TRUE(size_match(&db, "GP2_ZPOPMIN_KEY", 0)); + ASSERT_TRUE(size_match(&db, "GP2_ZPOPMIN_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {{0, "MM2"}, {0, "MM3"}})); - ASSERT_TRUE(score_members_match(&db,"GP2_ZPOPMIN_KEY", {})); - + ASSERT_TRUE(score_members_match(&db, "GP2_ZPOPMIN_KEY", {})); // ***************** Group 3 Test ***************** // [-1, MM3] @@ -373,34 +353,24 @@ TEST_F(ZSetsTest, ZPopMinTest) { // [1, MM2] // [2e5 + 3.98, MM10] // [2e5 + 3.98, MM9] - std::vector gp3_sm { - {1, "MM1"}, - {1, "MM2"}, - {-1, "MM3"}, - {-1, "MM4"}, - {1/6.0, "MM5"}, - {1/6.0, "MM6"}, - {0.532445, "MM7"}, - {0.532445, "MM8"}, - {2e5 + 3.98, "MM9"}, - {2e5 + 3.98, "MM10"} - }; - s = db.ZAdd("GP3_ZPOPMIN_KEY", gp3_sm, &ret); + std::vector gp3_sm{ + {1, "MM1"}, {1, "MM2"}, {-1, "MM3"}, {-1, "MM4"}, {1 / 6.0, "MM5"}, + {1 / 6.0, "MM6"}, {0.532445, "MM7"}, {0.532445, "MM8"}, {2e5 + 3.98, "MM9"}, {2e5 + 3.98, "MM10"}}; + s = db.ZAdd("GP3_ZPOPMIN_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(10, ret); ASSERT_TRUE(size_match(&db, "GP3_ZPOPMIN_KEY", 10)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZPOPMIN_KEY", { - {-1, "MM3"}, - {-1, "MM4"}, - {1/6.0, "MM5"}, - {1/6.0, "MM6"}, - {0.532445, "MM7"}, - {0.532445, "MM8"}, - {1, "MM1"}, - {1, "MM2"}, - {2e5 + 3.98, "MM10"}, - {2e5 + 3.98, "MM9"} - })); + ASSERT_TRUE(score_members_match(&db, "GP3_ZPOPMIN_KEY", + {{-1, "MM3"}, + {-1, "MM4"}, + {1 / 6.0, "MM5"}, + {1 / 6.0, "MM6"}, + {0.532445, "MM7"}, + {0.532445, "MM8"}, + {1, "MM1"}, + {1, "MM2"}, + {2e5 + 3.98, "MM10"}, + {2e5 + 3.98, "MM9"}})); s = db.ZPopMin("GP3_ZPOPMIN_KEY", 5, &score_members); // [0.532445, MM8] ret: [-1, MM3] @@ -411,38 +381,38 @@ TEST_F(ZSetsTest, ZPopMinTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(5, score_members.size()); ASSERT_TRUE(size_match(&db, "GP3_ZPOPMIN_KEY", 5)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZPOPMIN_KEY", {{0.532445, "MM8"}, {1, "MM1"}, {1, "MM2"}, {2e5 + 3.98, "MM10"}, {2e5 + 3.98, "MM9"}})); - ASSERT_TRUE(score_members_match(score_members,{{-1, "MM3"}, {-1, "MM4"}, {1/6.0, "MM5"}, {1/6.0, "MM6"}, {0.532445, "MM7"}})); - + ASSERT_TRUE(score_members_match( + &db, "GP3_ZPOPMIN_KEY", {{0.532445, "MM8"}, {1, "MM1"}, {1, "MM2"}, {2e5 + 3.98, "MM10"}, {2e5 + 3.98, "MM9"}})); + ASSERT_TRUE(score_members_match(score_members, + {{-1, "MM3"}, {-1, "MM4"}, {1 / 6.0, "MM5"}, {1 / 6.0, "MM6"}, {0.532445, "MM7"}})); // ***************** Group 4 Test ***************** // s = db.ZPopMin("GP4_ZPOPMIN_KEY", 1, &score_members); - // ret: + // ret: ASSERT_TRUE(s.IsNotFound()); - ASSERT_EQ(0, score_members.size()); - + ASSERT_EQ(0, score_members.size()); // ***************** Group 5 Test ***************** // [-1, MM1] // [0, MM2] // [1, MM3] - std::vector gp5_sm1 {{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}}; + std::vector gp5_sm1{{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}}; s = db.ZAdd("GP5_ZPOPMIN_KEY", gp5_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); - ASSERT_TRUE(size_match(&db, "GP5_ZPOPMIN_KEY", 3)); + ASSERT_TRUE(size_match(&db, "GP5_ZPOPMIN_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP5_ZPOPMIN_KEY", {{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}})); ASSERT_TRUE(make_expired(&db, "GP5_ZPOPMIN_KEY")); ASSERT_TRUE(size_match(&db, "GP5_ZPOPMIN_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP5_ZPOPMIN_KEY", {})); s = db.ZPopMin("GP5_ZPOPMIN_KEY", 1, &score_members); - - // ret: + + // ret: ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, score_members.size()); -} +} // ZAdd TEST_F(ZSetsTest, ZAddTest) { @@ -451,40 +421,38 @@ TEST_F(ZSetsTest, ZAddTest) { std::map type_status; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{3.23, "MM1"}, {0, "MM2"}, {8.0004, "MM3"}, {-0.54, "MM4"}}; + std::vector gp1_sm{{3.23, "MM1"}, {0, "MM2"}, {8.0004, "MM3"}, {-0.54, "MM4"}}; s = db.ZAdd("GP1_ZADD_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); ASSERT_TRUE(size_match(&db, "GP1_ZADD_KEY", 4)); ASSERT_TRUE(score_members_match(&db, "GP1_ZADD_KEY", {{-0.54, "MM4"}, {0, "MM2"}, {3.23, "MM1"}, {8.0004, "MM3"}})); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{0, "MM1"}, {0, "MM1"}, {0, "MM2"}, {0, "MM3"}}; + std::vector gp2_sm{{0, "MM1"}, {0, "MM1"}, {0, "MM2"}, {0, "MM3"}}; s = db.ZAdd("GP2_ZADD_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP2_ZADD_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP2_ZADD_KEY", {{0, "MM1"}, {0, "MM2"}, {0, "MM3"}})); - // ***************** Group 3 Test ***************** - std::vector gp3_sm {{1/1.0, "MM1"}, {1/3.0, "MM2"}, {1/6.0, "MM3"}, {1/7.0, "MM4"}}; + std::vector gp3_sm{{1 / 1.0, "MM1"}, {1 / 3.0, "MM2"}, {1 / 6.0, "MM3"}, {1 / 7.0, "MM4"}}; s = db.ZAdd("GP3_ZADD_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); ASSERT_TRUE(size_match(&db, "GP3_ZADD_KEY", 4)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZADD_KEY", {{1/7.0, "MM4"}, {1/6.0, "MM3"}, {1/3.0, "MM2"}, {1/1.0, "MM1"}})); - + ASSERT_TRUE(score_members_match(&db, "GP3_ZADD_KEY", + {{1 / 7.0, "MM4"}, {1 / 6.0, "MM3"}, {1 / 3.0, "MM2"}, {1 / 1.0, "MM1"}})); // ***************** Group 4 Test ***************** - std::vector gp4_sm {{-1/1.0, "MM1"}, {-1/3.0, "MM2"}, {-1/6.0, "MM3"}, {-1/7.0, "MM4"}}; + std::vector gp4_sm{{-1 / 1.0, "MM1"}, {-1 / 3.0, "MM2"}, {-1 / 6.0, "MM3"}, {-1 / 7.0, "MM4"}}; s = db.ZAdd("GP4_ZADD_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); ASSERT_TRUE(size_match(&db, "GP4_ZADD_KEY", 4)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZADD_KEY", {{-1/1.0, "MM1"}, {-1/3.0, "MM2"}, {-1/6.0, "MM3"}, {-1/7.0, "MM4"}})); - + ASSERT_TRUE(score_members_match(&db, "GP4_ZADD_KEY", + {{-1 / 1.0, "MM1"}, {-1 / 3.0, "MM2"}, {-1 / 6.0, "MM3"}, {-1 / 7.0, "MM4"}})); // ***************** Group 5 Test ***************** // [0, MM1] @@ -509,8 +477,7 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 3)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-0.5333, "MM2"}, {0, "MM1"}, {1.79769e+308, "MM3"}})); + ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", {{-0.5333, "MM2"}, {0, "MM1"}, {1.79769e+308, "MM3"}})); // [-0.5333, MM2] // [0, MM1] @@ -520,8 +487,8 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 4)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-0.5333, "MM2"}, {0, "MM1"}, {50000, "MM4"}, {1.79769e+308, "MM3"}})); + ASSERT_TRUE( + score_members_match(&db, "GP5_ZADD_KEY", {{-0.5333, "MM2"}, {0, "MM1"}, {50000, "MM4"}, {1.79769e+308, "MM3"}})); // [-1.79769e+308, MM5] // [-0.5333, MM2] @@ -532,9 +499,9 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 5)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {0, "MM1"}, - {50000, "MM4"}, {1.79769e+308, "MM3"}})); + ASSERT_TRUE(score_members_match( + &db, "GP5_ZADD_KEY", + {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {0, "MM1"}, {50000, "MM4"}, {1.79769e+308, "MM3"}})); // [-1.79769e+308, MM5] // [-0.5333, MM2] @@ -546,9 +513,9 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {0, "MM1"}, - {0, "MM6"}, {50000, "MM4"}, {1.79769e+308, "MM3"}})); + ASSERT_TRUE(score_members_match( + &db, "GP5_ZADD_KEY", + {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {0, "MM1"}, {0, "MM6"}, {50000, "MM4"}, {1.79769e+308, "MM3"}})); // [-1.79769e+308, MM5] // [-0.5333, MM2] @@ -560,9 +527,9 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(0, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {0, "MM1"}, - {50000, "MM4"}, {100000, "MM6"}, {1.79769e+308, "MM3"}})); + ASSERT_TRUE(score_members_match( + &db, "GP5_ZADD_KEY", + {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {0, "MM1"}, {50000, "MM4"}, {100000, "MM6"}, {1.79769e+308, "MM3"}})); // [-1.79769e+308, MM5] // [-0.5333, MM2] @@ -576,9 +543,13 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 7)); ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {-0.5333, "MM7"}, - {0, "MM1"}, {50000, "MM4"}, {100000, "MM6"}, - {1.79769e+308, "MM3"}})); + {{-1.79769e+308, "MM5"}, + {-0.5333, "MM2"}, + {-0.5333, "MM7"}, + {0, "MM1"}, + {50000, "MM4"}, + {100000, "MM6"}, + {1.79769e+308, "MM3"}})); // [-1.79769e+308, MM5] // [-0.5333, MM2] @@ -588,14 +559,19 @@ TEST_F(ZSetsTest, ZAddTest) { // [50000, MM4] // [100000, MM6] // [1.79769e+308, MM3] - s = db.ZAdd("GP5_ZADD_KEY", {{-1/3.0, "MM8"}}, &ret); + s = db.ZAdd("GP5_ZADD_KEY", {{-1 / 3.0, "MM8"}}, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 8)); ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {-0.5333, "MM7"}, - {-1/3.0, "MM8"}, {0, "MM1"}, {50000, "MM4"}, - {100000, "MM6"}, {1.79769e+308, "MM3"}})); + {{-1.79769e+308, "MM5"}, + {-0.5333, "MM2"}, + {-0.5333, "MM7"}, + {-1 / 3.0, "MM8"}, + {0, "MM1"}, + {50000, "MM4"}, + {100000, "MM6"}, + {1.79769e+308, "MM3"}})); // [-1.79769e+308, MM5] // [-0.5333, MM2] @@ -606,14 +582,20 @@ TEST_F(ZSetsTest, ZAddTest) { // [50000, MM4] // [100000, MM6] // [1.79769e+308, MM3] - s = db.ZAdd("GP5_ZADD_KEY", {{1/3.0, "MM9"}}, &ret); + s = db.ZAdd("GP5_ZADD_KEY", {{1 / 3.0, "MM9"}}, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 9)); ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{-1.79769e+308, "MM5"}, {-0.5333, "MM2"}, {-0.5333, "MM7"}, - {-1/3.0, "MM8"}, {0, "MM1"}, {1/3.0, "MM9"}, - {50000, "MM4"}, {100000, "MM6"}, {1.79769e+308, "MM3"}})); + {{-1.79769e+308, "MM5"}, + {-0.5333, "MM2"}, + {-0.5333, "MM7"}, + {-1 / 3.0, "MM8"}, + {0, "MM1"}, + {1 / 3.0, "MM9"}, + {50000, "MM4"}, + {100000, "MM6"}, + {1.79769e+308, "MM3"}})); // [0, MM1] // [0, MM2] @@ -624,20 +606,19 @@ TEST_F(ZSetsTest, ZAddTest) { // [0, MM7] // [0, MM8] // [0, MM9] - s = db.ZAdd("GP5_ZADD_KEY", {{0, "MM1"}, {0, "MM2"}, {0, "MM3"}, - {0, "MM4"}, {0, "MM5"}, {0, "MM6"}, - {0, "MM7"}, {0, "MM8"}, {0, "MM9"}}, &ret); + s = db.ZAdd( + "GP5_ZADD_KEY", + {{0, "MM1"}, {0, "MM2"}, {0, "MM3"}, {0, "MM4"}, {0, "MM5"}, {0, "MM6"}, {0, "MM7"}, {0, "MM8"}, {0, "MM9"}}, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(0, ret); ASSERT_TRUE(size_match(&db, "GP5_ZADD_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZADD_KEY", - {{0, "MM1"}, {0, "MM2"}, {0, "MM3"}, - {0, "MM4"}, {0, "MM5"}, {0, "MM6"}, - {0, "MM7"}, {0, "MM8"}, {0, "MM9"}})); - + ASSERT_TRUE(score_members_match( + &db, "GP5_ZADD_KEY", + {{0, "MM1"}, {0, "MM2"}, {0, "MM3"}, {0, "MM4"}, {0, "MM5"}, {0, "MM6"}, {0, "MM7"}, {0, "MM8"}, {0, "MM9"}})); // ***************** Group 6 Test ***************** - std::vector gp6_sm1 {{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}}; + std::vector gp6_sm1{{-1, "MM1"}, {0, "MM2"}, {1, "MM3"}}; s = db.ZAdd("GP6_ZADD_KEY", gp6_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); @@ -647,16 +628,15 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(size_match(&db, "GP6_ZADD_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP6_ZADD_KEY", {})); - std::vector gp6_sm2 {{-100, "MM1"}, {0, "MM2"}, {100, "MM3"}}; + std::vector gp6_sm2{{-100, "MM1"}, {0, "MM2"}, {100, "MM3"}}; s = db.ZAdd("GP6_ZADD_KEY", gp6_sm2, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP6_ZADD_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP6_ZADD_KEY", {{-100, "MM1"}, {0, "MM2"}, {100, "MM3"}})); - // ***************** Group 7 Test ***************** - std::vector gp7_sm1 {{-0.123456789, "MM1"}, {0, "MM2"}, {0.123456789, "MM3"}}; + std::vector gp7_sm1{{-0.123456789, "MM1"}, {0, "MM2"}, {0.123456789, "MM3"}}; s = db.ZAdd("GP7_ZADD_KEY", gp7_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); @@ -666,7 +646,7 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(size_match(&db, "GP7_ZADD_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP7_ZADD_KEY", {})); - std::vector gp7_sm2 {{-1234.56789, "MM1"}, {0, "MM2"}, {1234.56789, "MM3"}}; + std::vector gp7_sm2{{-1234.56789, "MM1"}, {0, "MM2"}, {1234.56789, "MM3"}}; s = db.ZAdd("GP7_ZADD_KEY", gp7_sm2, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); @@ -679,10 +659,9 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_TRUE(size_match(&db, "GP7_ZADD_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP7_ZADD_KEY", {{0, "MM2"}, {1234.56789, "MM1"}, {1234.56789, "MM3"}})); - // ***************** Group 8 Test ***************** - std::vector gp8_sm1 {{1, "MM1"}}; - std::vector gp8_sm2 {{2, "MM2"}}; + std::vector gp8_sm1{{1, "MM1"}}; + std::vector gp8_sm2{{2, "MM2"}}; s = db.ZAdd("GP8_ZADD_KEY", gp8_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); @@ -714,14 +693,13 @@ TEST_F(ZSetsTest, ZAddTest) { ASSERT_EQ(type_ttl[kZSets], -1); } - // ZCard TEST_F(ZSetsTest, ZCardTest) { int32_t ret; double score; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{-1, "MM1"}, {-2, "MM2"}, {-3, "MM3"}, {-4, "MM4"}}; + std::vector gp1_sm{{-1, "MM1"}, {-2, "MM2"}, {-3, "MM3"}, {-4, "MM4"}}; s = db.ZAdd("GP1_ZCARD_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); @@ -731,9 +709,8 @@ TEST_F(ZSetsTest, ZCardTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}}; + std::vector gp2_sm{{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}}; s = db.ZAdd("GP2_ZCARD_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(5, ret); @@ -743,9 +720,8 @@ TEST_F(ZSetsTest, ZCardTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(5, ret); - // ***************** Group 3 Test ***************** - std::vector gp3_sm {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}}; + std::vector gp3_sm{{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}}; s = db.ZAdd("GP3_ZCARD_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(5, ret); @@ -756,29 +732,30 @@ TEST_F(ZSetsTest, ZCardTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, ret); - // ***************** Group 4 Test ***************** s = db.ZCard("GP4_ZCARD_KEY", &ret); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, ret); } - // ZCount TEST_F(ZSetsTest, ZCountTest) { int32_t ret; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{101010.1010101, "MM1"}, {101010.0101010, "MM2"}, - {-100.000000001, "MM3"}, {-100.000000002, "MM4"}, - {-100.000000001, "MM5"}, {-100.000000002, "MM6"}}; + std::vector gp1_sm{{101010.1010101, "MM1"}, {101010.0101010, "MM2"}, {-100.000000001, "MM3"}, + {-100.000000002, "MM4"}, {-100.000000001, "MM5"}, {-100.000000002, "MM6"}}; s = db.ZAdd("GP1_ZCOUNT_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP1_ZCOUNT_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZCOUNT_KEY", {{-100.000000002, "MM4"}, {-100.000000002, "MM6"}, - {-100.000000001, "MM3"}, {-100.000000001, "MM5"}, - {101010.0101010, "MM2"}, {101010.1010101, "MM1"}})); + ASSERT_TRUE(score_members_match(&db, "GP1_ZCOUNT_KEY", + {{-100.000000002, "MM4"}, + {-100.000000002, "MM6"}, + {-100.000000001, "MM3"}, + {-100.000000001, "MM5"}, + {101010.0101010, "MM2"}, + {101010.1010101, "MM1"}})); s = db.ZCount("GP1_ZCOUNT_KEY", -100.000000002, 101010.1010101, true, true, &ret); ASSERT_TRUE(s.ok()); @@ -832,41 +809,36 @@ TEST_F(ZSetsTest, ZCountTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp2_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP2_ZCOUNT_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP2_ZCOUNT_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZCOUNT_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP2_ZCOUNT_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); ASSERT_TRUE(make_expired(&db, "GP2_ZCOUNT_KEY")); s = db.ZCount("GP2_ZCOUNT_KEY", -100000000, 100000000, true, true, &ret); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - // ***************** Group 3 Test ***************** s = db.ZCount("GP3_ZCOUNT_KEY", -100000000, 100000000, true, true, &ret); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - // ***************** Group 4 Test ***************** - std::vector gp4_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp4_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP4_ZCOUNT_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP4_ZCOUNT_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZCOUNT_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP4_ZCOUNT_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZCount("GP4_ZCOUNT_KEY", -100, -50, true, true, &ret); ASSERT_TRUE(s.ok()); @@ -961,12 +933,12 @@ TEST_F(ZSetsTest, ZIncrbyTest) { std::map type_status; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{101010.1010101, "MM1"}, {101010.0101010, "MM2"}}; + std::vector gp1_sm{{101010.1010101, "MM1"}, {101010.0101010, "MM2"}}; s = db.ZAdd("GP1_ZINCRBY_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(2, ret); ASSERT_TRUE(size_match(&db, "GP1_ZINCRBY_KEY", 2)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZINCRBY_KEY",{{101010.0101010, "MM2"}, {101010.1010101, "MM1"}})); + ASSERT_TRUE(score_members_match(&db, "GP1_ZINCRBY_KEY", {{101010.0101010, "MM2"}, {101010.1010101, "MM1"}})); s = db.ZIncrby("GP1_ZINCRBY_KEY", "MM1", -0.1010101, &score); ASSERT_TRUE(s.ok()); @@ -983,14 +955,13 @@ TEST_F(ZSetsTest, ZIncrbyTest) { ASSERT_TRUE(size_match(&db, "GP1_ZINCRBY_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP1_ZINCRBY_KEY", {{101010, "MM1"}, {101010, "MM2"}, {101010, "MM3"}})); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{101010.1010101010, "MM1"}}; + std::vector gp2_sm{{101010.1010101010, "MM1"}}; s = db.ZAdd("GP2_ZINCRBY_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP2_ZINCRBY_KEY", 1)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZINCRBY_KEY",{{101010.1010101010, "MM1"}})); + ASSERT_TRUE(score_members_match(&db, "GP2_ZINCRBY_KEY", {{101010.1010101010, "MM1"}})); s = db.ZIncrby("GP2_ZINCRBY_KEY", "MM1", 0.0101010101, &score); ASSERT_TRUE(s.ok()); @@ -1011,14 +982,13 @@ TEST_F(ZSetsTest, ZIncrbyTest) { ASSERT_TRUE(size_match(&db, "GP2_ZINCRBY_KEY", 1)); ASSERT_TRUE(score_members_match(&db, "GP2_ZINCRBY_KEY", {{202020, "MM1"}})); - // ***************** Group 3 Test ***************** - std::vector gp3_sm {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}}; + std::vector gp3_sm{{1, "MM1"}, {2, "MM2"}, {3, "MM3"}}; s = db.ZAdd("GP3_ZINCRBY_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP3_ZINCRBY_KEY", 3)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZINCRBY_KEY",{{1, "MM1"}, {2, "MM2"}, {3, "MM3"}})); + ASSERT_TRUE(score_members_match(&db, "GP3_ZINCRBY_KEY", {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}})); ASSERT_TRUE(make_expired(&db, "GP3_ZINCRBY_KEY")); ASSERT_TRUE(size_match(&db, "GP3_ZINCRBY_KEY", 0)); @@ -1040,14 +1010,15 @@ TEST_F(ZSetsTest, ZIncrbyTest) { ASSERT_TRUE(s.ok()); ASSERT_DOUBLE_EQ(score, 303030.030303); ASSERT_TRUE(size_match(&db, "GP3_ZINCRBY_KEY", 3)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZINCRBY_KEY", {{101010.010101, "MM1"}, {202020.020202, "MM2"}, {303030.030303, "MM3"}})); + ASSERT_TRUE(score_members_match(&db, "GP3_ZINCRBY_KEY", + {{101010.010101, "MM1"}, {202020.020202, "MM2"}, {303030.030303, "MM3"}})); s = db.ZIncrby("GP3_ZINCRBY_KEY", "MM1", 303030.030303, &score); ASSERT_TRUE(s.ok()); ASSERT_DOUBLE_EQ(score, 404040.040404); ASSERT_TRUE(size_match(&db, "GP3_ZINCRBY_KEY", 3)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZINCRBY_KEY", {{202020.020202, "MM2"}, {303030.030303, "MM3"}, {404040.040404, "MM1"}})); - + ASSERT_TRUE(score_members_match(&db, "GP3_ZINCRBY_KEY", + {{202020.020202, "MM2"}, {303030.030303, "MM3"}, {404040.040404, "MM1"}})); // ***************** Group 4 Test ***************** s = db.ZIncrby("GP4_ZINCRBY_KEY", "MM1", -101010.010101, &score); @@ -1062,7 +1033,6 @@ TEST_F(ZSetsTest, ZIncrbyTest) { ASSERT_TRUE(size_match(&db, "GP4_ZINCRBY_KEY", 2)); ASSERT_TRUE(score_members_match(&db, "GP4_ZINCRBY_KEY", {{-101010.010101, "MM1"}, {101010.010101, "MM2"}})); - // ***************** Group 5 Test ***************** s = db.ZAdd("GP5_ZINCRBY_KEY", {{1, "MM1"}}, &ret); ASSERT_TRUE(s.ok()); @@ -1075,7 +1045,6 @@ TEST_F(ZSetsTest, ZIncrbyTest) { ASSERT_TRUE(size_match(&db, "GP5_ZINCRBY_KEY", 1)); ASSERT_TRUE(score_members_match(&db, "GP5_ZINCRBY_KEY", {{2, "MM2"}})); - // ***************** Group 6 Test ***************** s = db.ZAdd("GP6_ZINCRBY_KEY", {{1, "MM1"}}, &ret); ASSERT_TRUE(s.ok()); @@ -1112,7 +1081,7 @@ TEST_F(ZSetsTest, ZRangeTest) { std::vector score_members; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{0, "MM1"}}; + std::vector gp1_sm{{0, "MM1"}}; s = db.ZAdd("GP1_ZRANGE_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); @@ -1123,65 +1092,62 @@ TEST_F(ZSetsTest, ZRangeTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}})); - // ***************** Group 2 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp2_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp2_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP2_ZRANGE_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP2_ZRANGE_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZRANGE_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP2_ZRANGE_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", 0, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", -9, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", 0, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", -9, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE(score_members_match( + score_members, + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", -100, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", 0, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", -100, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", 0, 0, &score_members); ASSERT_TRUE(s.ok()); @@ -1201,33 +1167,33 @@ TEST_F(ZSetsTest, ZRangeTest) { s = db.ZRange("GP2_ZRANGE_KEY", 0, 5, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); + ASSERT_TRUE( + score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); s = db.ZRange("GP2_ZRANGE_KEY", 0, -4, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); + ASSERT_TRUE( + score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); s = db.ZRange("GP2_ZRANGE_KEY", -9, -4, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); + ASSERT_TRUE( + score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); s = db.ZRange("GP2_ZRANGE_KEY", -9, 5, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); + ASSERT_TRUE( + score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); s = db.ZRange("GP2_ZRANGE_KEY", -100, 5, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); + ASSERT_TRUE( + score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); s = db.ZRange("GP2_ZRANGE_KEY", -100, -4, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); + ASSERT_TRUE( + score_members_match(score_members, {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}})); s = db.ZRange("GP2_ZRANGE_KEY", 3, 5, &score_members); ASSERT_TRUE(s.ok()); @@ -1247,37 +1213,36 @@ TEST_F(ZSetsTest, ZRangeTest) { s = db.ZRange("GP2_ZRANGE_KEY", 3, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE( + score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", -6, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE( + score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", 3, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE( + score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", -6, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE( + score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", -6, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE( + score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRange("GP2_ZRANGE_KEY", 3, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE( + score_members_match(score_members, {{3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); // ***************** Group 3 Test ***************** - std::vector gp3_sm {{0, "MM1"}}; + std::vector gp3_sm{{0, "MM1"}}; s = db.ZAdd("GP3_ZRANGE_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); @@ -1289,7 +1254,6 @@ TEST_F(ZSetsTest, ZRangeTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 4 Test ***************** s = db.ZRange("GP4_ZRANGE_KEY", 0, -1, &score_members); ASSERT_TRUE(s.IsNotFound()); @@ -1302,153 +1266,295 @@ TEST_F(ZSetsTest, ZRangebyscoreTest) { std::vector score_members; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp1_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP1_ZRANGEBYSCORE_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // count = max offset = 0 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, std::numeric_limits::max(), 0, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, std::numeric_limits::max(), 0, + &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // count = 18 offset = 0 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 18, 0, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 18, 0, &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // count = 10 offset = 0 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 0, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 10, 0, &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, {-100.0000000000001, "MM10"}})); // count = 10 offset = 1 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 1, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, { {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}})); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 10, 1, &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}})); // count = 10 offset = 17 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 17, &score_members); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 10, 17, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(score_members, {{987654321.0000001, "MM18"}})); // count = 10 offset = 18 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 18, &score_members); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 10, 18, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {})); // count = 10 offset = 19 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 19, &score_members); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 10, 19, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {})); // count = 10000 offset = 1 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10000, 1, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, { {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 10000, 1, &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // count = 10000 offset = 10000 - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10000, 10000, &score_members); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, 10000, 10000, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {})); - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, true, true, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }})); - - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, true, false, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }})); - - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), true, true, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), false, true, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, true, true, + &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}})); + + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, true, false, + &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}})); + + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), true, true, + &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); + + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), false, true, + &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -987654321.0000001, 987654321.0000001, true, true, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -987654321.0000001, 987654321.0000001, false, false, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, { {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"} })); - - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -999999999, -1000.000000000001 , true, true, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }})); - - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -999999999, -1000.000000000001 , true, false, &score_members); - ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }})); + ASSERT_TRUE(score_members_match(score_members, {{-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}})); + + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -999999999, -1000.000000000001, true, true, &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}})); + + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -999999999, -1000.000000000001, true, false, &score_members); + ASSERT_TRUE(s.ok()); + ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -654321.0000000001, -4321.000000000001, true, true, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }})); + ASSERT_TRUE(score_members_match( + score_members, {{-654321.0000000001, "MM4"}, {-54321.00000000001, "MM5"}, {-4321.000000000001, "MM6"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -654321.0000000001, -4321.000000000001, false, false, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-54321.00000000001, "MM5" }})); + ASSERT_TRUE(score_members_match(score_members, {{-54321.00000000001, "MM5"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", 0, 0, true, true, &score_members); ASSERT_TRUE(s.ok()); @@ -1460,77 +1566,106 @@ TEST_F(ZSetsTest, ZRangebyscoreTest) { s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, true, true, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{ 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(score_members, {{4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, false, true, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, { { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(score_members, {{54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, false, false, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, { { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, })); + ASSERT_TRUE(score_members_match(score_members, { + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + })); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -1000.000000000001, 987654321.0000001, true, true, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(score_members, {{-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", -1000.000000000001, 987654321.0000001, false, true, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(score_members, {{-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); - s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", 999999999, std::numeric_limits::max(), true, true, &score_members); + s = db.ZRangebyscore("GP1_ZRANGEBYSCORE_KEY", 999999999, std::numeric_limits::max(), true, true, + &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, - {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, - {5, "MM6"}}; + std::vector gp2_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP2_ZRANGEBYSCORE_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); ASSERT_TRUE(make_expired(&db, "GP2_ZRANGEBYSCORE_KEY")); - s = db.ZRangebyscore("GP2_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &score_members); + s = db.ZRangebyscore("GP2_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, &score_members); ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 3 Test ***************** - s = db.ZRangebyscore("GP3_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &score_members); + s = db.ZRangebyscore("GP3_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, &score_members); ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 4 Test ***************** - std::vector gp4_sm {{std::numeric_limits::lowest(), "MM0"}, - {0, "MM1"}, - {std::numeric_limits::max(), "MM2"}}; + std::vector gp4_sm{ + {std::numeric_limits::lowest(), "MM0"}, {0, "MM1"}, {std::numeric_limits::max(), "MM2"}}; s = db.ZAdd("GP4_ZRANGEBYSCORE_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); - s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &score_members); + s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{std::numeric_limits::lowest(), "MM0"}, {0, "MM1"}, {std::numeric_limits::max(), "MM2"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{std::numeric_limits::lowest(), "MM0"}, {0, "MM1"}, {std::numeric_limits::max(), "MM2"}})); - s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), false, false, &score_members); + s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), false, false, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}})); - s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, false, &score_members); + s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, false, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{std::numeric_limits::lowest(), "MM0"}, {0, "MM1"}})); - s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), false, true, &score_members); + s = db.ZRangebyscore("GP4_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), false, true, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}, {std::numeric_limits::max(), "MM2"}})); } @@ -1543,10 +1678,8 @@ TEST_F(ZSetsTest, ZRangebyscoreTest) { // // ***************** Group 1 Test ***************** // // {-5, MM0} {-3, MM1} {-1, MM2} {0, MM3} {1, MM4} {3, MM5} {5, MM6} // // 0 1 2 3 4 5 6 -// std::vector gp1_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; -// s = db.ZAdd("GP1_ZRANK_KEY", gp1_sm, &ret); -// ASSERT_TRUE(s.ok()); -// ASSERT_EQ(7, ret); +// std::vector gp1_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, +// "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP1_ZRANK_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); // s = db.ZRank("GP1_ZRANK_KEY", "MM0", &rank); // ASSERT_TRUE(s.ok()); @@ -1568,19 +1701,15 @@ TEST_F(ZSetsTest, ZRangebyscoreTest) { // ASSERT_TRUE(s.IsNotFound()); // ASSERT_EQ(rank, -1); - // // ***************** Group 2 Test ***************** -// std::vector gp2_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; -// s = db.ZAdd("GP2_ZRANK_KEY", gp2_sm, &ret); -// ASSERT_TRUE(s.ok()); -// ASSERT_EQ(7, ret); +// std::vector gp2_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, +// "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP2_ZRANK_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); // ASSERT_TRUE(make_expired(&db, "GP2_ZRANGE_KEY")); // s = db.ZRank("GP2_ZRANGE_KEY", "MM0", &rank); // ASSERT_TRUE(s.IsNotFound()); // ASSERT_EQ(-1, rank); - // // ***************** Group 3 Test ***************** // s = db.ZRank("GP3_ZRANGE_KEY", "MM0", &rank); // ASSERT_TRUE(s.IsNotFound()); @@ -1594,12 +1723,14 @@ TEST_F(ZSetsTest, ZRemTest) { // ***************** Group 1 Test ***************** // {-5, MM0} {-3, MM1} {-1, MM2} {0, MM3} {1, MM4} {3, MM5} {5, MM6} // 0 1 2 3 4 5 6 - std::vector gp1_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; + std::vector gp1_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP1_ZREM_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); ASSERT_TRUE(size_match(&db, "GP1_ZREM_KEY", 7)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); + ASSERT_TRUE(score_members_match( + &db, "GP1_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); s = db.ZRem("GP1_ZREM_KEY", {"MM1", "MM3", "MM5"}, &ret); ASSERT_TRUE(s.ok()); @@ -1607,16 +1738,17 @@ TEST_F(ZSetsTest, ZRemTest) { ASSERT_TRUE(size_match(&db, "GP1_ZREM_KEY", 4)); ASSERT_TRUE(score_members_match(&db, "GP1_ZREM_KEY", {{-5, "MM0"}, {-1, "MM2"}, {1, "MM4"}, {5, "MM6"}})); - // ***************** Group 2 Test ***************** // {-5, MM0} {-3, MM1} {-1, MM2} {0, MM3} {1, MM4} {3, MM5} {5, MM6} // 0 1 2 3 4 5 6 - std::vector gp2_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; + std::vector gp2_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP2_ZREM_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); ASSERT_TRUE(size_match(&db, "GP2_ZREM_KEY", 7)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); + ASSERT_TRUE(score_members_match( + &db, "GP2_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); s = db.ZRem("GP2_ZREM_KEY", {"MM0", "MM1", "MM2", "MM3", "MM4", "MM5", "MM6"}, &ret); ASSERT_TRUE(s.ok()); @@ -1630,16 +1762,17 @@ TEST_F(ZSetsTest, ZRemTest) { ASSERT_TRUE(size_match(&db, "GP2_ZREM_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP2_ZREM_KEY", {})); - // ***************** Group 3 Test ***************** // {-5, MM0} {-3, MM1} {-1, MM2} {0, MM3} {1, MM4} {3, MM5} {5, MM6} // 0 1 2 3 4 5 6 - std::vector gp3_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; + std::vector gp3_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP3_ZREM_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); ASSERT_TRUE(size_match(&db, "GP3_ZREM_KEY", 7)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); + ASSERT_TRUE(score_members_match( + &db, "GP3_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); s = db.ZRem("GP3_ZREM_KEY", {"MM0", "MM0", "MM1", "MM1", "MM2", "MM2"}, &ret); ASSERT_TRUE(s.ok()); @@ -1647,33 +1780,36 @@ TEST_F(ZSetsTest, ZRemTest) { ASSERT_TRUE(size_match(&db, "GP3_ZREM_KEY", 4)); ASSERT_TRUE(score_members_match(&db, "GP3_ZREM_KEY", {{0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); - // ***************** Group 4 Test ***************** // {-5, MM0} {-3, MM1} {-1, MM2} {0, MM3} {1, MM4} {3, MM5} {5, MM6} // 0 1 2 3 4 5 6 - std::vector gp4_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; + std::vector gp4_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP4_ZREM_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); ASSERT_TRUE(size_match(&db, "GP4_ZREM_KEY", 7)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); + ASSERT_TRUE(score_members_match( + &db, "GP4_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); s = db.ZRem("GP4_ZREM_KEY", {"MM", "YY", "CC"}, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(0, ret); ASSERT_TRUE(size_match(&db, "GP4_ZREM_KEY", 7)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); - + ASSERT_TRUE(score_members_match( + &db, "GP4_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); // ***************** Group 5 Test ***************** // {-5, MM0} {-3, MM1} {-1, MM2} {0, MM3} {1, MM4} {3, MM5} {5, MM6} // 0 1 2 3 4 5 6 - std::vector gp5_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; + std::vector gp5_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP5_ZREM_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); ASSERT_TRUE(size_match(&db, "GP5_ZREM_KEY", 7)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); + ASSERT_TRUE(score_members_match( + &db, "GP5_ZREM_KEY", {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}})); ASSERT_TRUE(make_expired(&db, "GP5_ZREM_KEY")); s = db.ZRem("GP5_ZREM_KEY", {"MM0", "MM1", "MM2"}, &ret); @@ -1682,7 +1818,6 @@ TEST_F(ZSetsTest, ZRemTest) { ASSERT_TRUE(size_match(&db, "GP5_ZREM_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP5_ZREM_KEY", {})); - // ***************** Group 5 Test ***************** // Not exist ZSet s = db.ZRem("GP6_ZREM_KEY", {"MM0", "MM1", "MM2"}, &ret); @@ -1690,7 +1825,6 @@ TEST_F(ZSetsTest, ZRemTest) { ASSERT_EQ(0, ret); ASSERT_TRUE(size_match(&db, "GP6_ZREM_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP6_ZREM_KEY", {})); - } // ZRemrangebyrank @@ -1699,7 +1833,7 @@ TEST_F(ZSetsTest, ZRemrangebyrankTest) { std::vector score_members; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{0, "MM1"}}; + std::vector gp1_sm{{0, "MM1"}}; s = db.ZAdd("GP1_ZREMMRANGEBYRANK_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); @@ -1711,22 +1845,20 @@ TEST_F(ZSetsTest, ZRemrangebyrankTest) { ASSERT_EQ(1, ret); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 2 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp2_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp2_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP2_ZREMRANGEBYRANK_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP2_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP2_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP2_ZREMRANGEBYRANK_KEY", 0, 8, &ret); ASSERT_TRUE(s.ok()); @@ -1734,22 +1866,20 @@ TEST_F(ZSetsTest, ZRemrangebyrankTest) { ASSERT_TRUE(size_match(&db, "GP2_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 3 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp3_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp3_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP3_ZREMRANGEBYRANK_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP3_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP3_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP3_ZREMRANGEBYRANK_KEY", -9, -1, &ret); ASSERT_TRUE(s.ok()); @@ -1757,584 +1887,532 @@ TEST_F(ZSetsTest, ZRemrangebyrankTest) { ASSERT_TRUE(size_match(&db, "GP3_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 4 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp4_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp4_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP4_ZREMRANGEBYRANK_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP4_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP4_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP4_ZREMRANGEBYRANK_KEY", 0, -1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP4_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 5 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp5_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp5_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP5_ZREMRANGEBYRANK_KEY", gp5_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP5_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP5_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP5_ZREMRANGEBYRANK_KEY", -9, 8, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP5_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 6 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp6_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp6_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP6_ZREMRANGEBYRANK_KEY", gp6_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP6_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP6_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP6_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP6_ZREMRANGEBYRANK_KEY", -100, 8, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP6_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 7 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp7_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp7_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP7_ZREMRANGEBYRANK_KEY", gp7_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP7_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP7_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP7_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP7_ZREMRANGEBYRANK_KEY", 0, 100, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP7_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 8 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp8_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp8_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP8_ZREMRANGEBYRANK_KEY", gp8_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP8_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP8_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP8_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP8_ZREMRANGEBYRANK_KEY", -100, 100, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP8_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 9 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp9_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp9_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP9_ZREMRANGEBYRANK_KEY", gp9_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP9_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP9_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP9_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP9_ZREMRANGEBYRANK_KEY", 0, 0, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP9_ZREMRANGEBYRANK_KEY", 8)); - ASSERT_TRUE(score_members_match(&db, "GP9_ZREMRANGEBYRANK_KEY", {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, - {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, - {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE(score_members_match( + &db, "GP9_ZREMRANGEBYRANK_KEY", + {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); // ***************** Group 10 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp10_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp10_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP10_ZREMRANGEBYRANK_KEY", gp10_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP10_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP10_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP10_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP10_ZREMRANGEBYRANK_KEY", -9, -9, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP10_ZREMRANGEBYRANK_KEY", 8)); - ASSERT_TRUE(score_members_match(&db, "GP10_ZREMRANGEBYRANK_KEY", {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, - {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, - {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE(score_members_match( + &db, "GP10_ZREMRANGEBYRANK_KEY", + {{1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); // ***************** Group 11 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp11_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp11_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP11_ZREMRANGEBYRANK_KEY", gp11_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP11_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP11_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP11_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP11_ZREMRANGEBYRANK_KEY", 8, 8, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP11_ZREMRANGEBYRANK_KEY", 8)); - ASSERT_TRUE(score_members_match(&db, "GP11_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}})); - + ASSERT_TRUE(score_members_match( + &db, "GP11_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}})); // ***************** Group 12 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp12_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp12_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP12_ZREMRANGEBYRANK_KEY", gp12_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP12_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP12_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP12_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP12_ZREMRANGEBYRANK_KEY", -1, -1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP12_ZREMRANGEBYRANK_KEY", 8)); - ASSERT_TRUE(score_members_match(&db, "GP12_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}})); - + ASSERT_TRUE(score_members_match( + &db, "GP12_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}})); // ***************** Group 13 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp13_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp13_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP13_ZREMRANGEBYRANK_KEY", gp13_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP13_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP13_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP13_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP13_ZREMRANGEBYRANK_KEY", 0, 5, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP13_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP13_ZREMRANGEBYRANK_KEY", {{6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - // ***************** Group 14 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp14_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp14_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP14_ZREMRANGEBYRANK_KEY", gp14_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP14_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP14_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP14_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP14_ZREMRANGEBYRANK_KEY", 0, -4, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP14_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP14_ZREMRANGEBYRANK_KEY", {{6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - // ***************** Group 15 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp15_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp15_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP15_ZREMRANGEBYRANK_KEY", gp15_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP15_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP15_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP15_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP15_ZREMRANGEBYRANK_KEY", -9, -4, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP15_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP15_ZREMRANGEBYRANK_KEY", {{6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - // ***************** Group 16 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp16_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp16_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP16_ZREMRANGEBYRANK_KEY", gp16_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP16_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP16_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP16_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP16_ZREMRANGEBYRANK_KEY", -9, 5, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP16_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP16_ZREMRANGEBYRANK_KEY", {{6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - // ***************** Group 17 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp17_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp17_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP17_ZREMRANGEBYRANK_KEY", gp17_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP17_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP17_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP17_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP17_ZREMRANGEBYRANK_KEY", -100, 5, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP17_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP17_ZREMRANGEBYRANK_KEY", {{6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - // ***************** Group 18 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp18_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp18_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP18_ZREMRANGEBYRANK_KEY", gp18_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP18_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP18_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP18_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP18_ZREMRANGEBYRANK_KEY", -100, -4, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP18_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP18_ZREMRANGEBYRANK_KEY", {{6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - // ***************** Group 19 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp19_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp19_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP19_ZREMRANGEBYRANK_KEY", gp19_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP19_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP19_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP19_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP19_ZREMRANGEBYRANK_KEY", 3, 5, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP19_ZREMRANGEBYRANK_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP19_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE(score_members_match(&db, "GP19_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); // ***************** Group 20 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp20_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp20_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP20_ZREMRANGEBYRANK_KEY", gp20_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP20_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP20_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP20_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP20_ZREMRANGEBYRANK_KEY", -6, -4, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP20_ZREMRANGEBYRANK_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP20_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE(score_members_match(&db, "GP20_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); // ***************** Group 21 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp21_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp21_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP21_ZREMRANGEBYRANK_KEY", gp21_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP21_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP21_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP21_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP21_ZREMRANGEBYRANK_KEY", 3, -4, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP21_ZREMRANGEBYRANK_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP21_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE(score_members_match(&db, "GP21_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); // ***************** Group 22 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp22_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp22_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP22_ZREMRANGEBYRANK_KEY", gp22_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP22_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP22_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP22_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP22_ZREMRANGEBYRANK_KEY", -6, 5, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP22_ZREMRANGEBYRANK_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP22_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); - + ASSERT_TRUE(score_members_match(&db, "GP22_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); // ***************** Group 23 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp23_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp23_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP23_ZREMRANGEBYRANK_KEY", gp23_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP23_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP23_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP23_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP23_ZREMRANGEBYRANK_KEY", 3, 8, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP23_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP23_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}})); - // ***************** Group 24 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp24_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp24_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP24_ZREMRANGEBYRANK_KEY", gp24_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP24_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP24_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP24_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP24_ZREMRANGEBYRANK_KEY", -6, -1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP24_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP24_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}})); - // ***************** Group 25 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp25_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp25_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP25_ZREMRANGEBYRANK_KEY", gp25_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP25_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP25_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP25_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP25_ZREMRANGEBYRANK_KEY", 3, -1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP25_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP25_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}})); - // ***************** Group 26 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp26_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp26_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP26_ZREMRANGEBYRANK_KEY", gp26_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP26_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP26_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP26_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP26_ZREMRANGEBYRANK_KEY", -6, 8, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP26_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP26_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}})); - // ***************** Group 27 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp27_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp27_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP27_ZREMRANGEBYRANK_KEY", gp27_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP27_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP27_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP27_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP27_ZREMRANGEBYRANK_KEY", -6, 100, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP27_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP27_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}})); - // ***************** Group 28 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp28_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp28_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP28_ZREMRANGEBYRANK_KEY", gp28_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP28_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP28_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP28_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRemrangebyrank("GP28_ZREMRANGEBYRANK_KEY", 3, 100, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP28_ZREMRANGEBYRANK_KEY", 3)); ASSERT_TRUE(score_members_match(&db, "GP28_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}})); - // ***************** Group 29 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 0 1 2 3 4 5 6 7 8 // -9 -8 -7 -6 -5 -4 -3 -2 -1 - std::vector gp29_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp29_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP29_ZREMRANGEBYRANK_KEY", gp29_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP29_ZREMRANGEBYRANK_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP29_ZREMRANGEBYRANK_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP29_ZREMRANGEBYRANK_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); ASSERT_TRUE(make_expired(&db, "GP29_ZREMRANGEBYRANK_KEY")); s = db.ZRemrangebyrank("GP29_ZREMRANGEBYRANK_KEY", 0, 0, &ret); ASSERT_TRUE(s.IsNotFound()); @@ -2342,7 +2420,6 @@ TEST_F(ZSetsTest, ZRemrangebyrankTest) { ASSERT_TRUE(size_match(&db, "GP29_ZREMRANGEBYRANK_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP29_ZREMRANGEBYRANK_KEY", {})); - // ***************** Group 30 Test ***************** s = db.ZRemrangebyrank("GP30_ZREMRANGEBYRANK_KEY", 0, 0, &ret); ASSERT_TRUE(s.IsNotFound()); @@ -2356,31 +2433,55 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { int32_t ret; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp1_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP1_ZREMRANGEBYSCORE_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); - s = db.ZRemrangebyscore("GP1_ZREMRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &ret); + s = db.ZRemrangebyscore("GP1_ZREMRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); ASSERT_TRUE(size_match(&db, "GP1_ZREMRANGEBYSCORE_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP1_ZREMRANGEBYSCORE_KEY", {})); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp2_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP2_ZREMRANGEBYSCORE_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2389,64 +2490,130 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(0, ret); ASSERT_TRUE(size_match(&db, "GP2_ZREMRANGEBYSCORE_KEY", 18)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + ASSERT_TRUE(score_members_match(&db, "GP2_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 3 Test ***************** - std::vector gp3_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp3_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP3_ZREMRANGEBYSCORE_KEY", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); - s = db.ZRemrangebyscore("GP3_ZREMRANGEBYSCORE_KEY",-987654321.0000001, -7654321.000000001, true, true, &ret); + s = db.ZRemrangebyscore("GP3_ZREMRANGEBYSCORE_KEY", -987654321.0000001, -7654321.000000001, true, true, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP3_ZREMRANGEBYSCORE_KEY", 15)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZREMRANGEBYSCORE_KEY",{{-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + ASSERT_TRUE(score_members_match(&db, "GP3_ZREMRANGEBYSCORE_KEY", + {{-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 4 Test ***************** - std::vector gp4_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp4_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP4_ZREMRANGEBYSCORE_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); - s = db.ZRemrangebyscore("GP4_ZREMRANGEBYSCORE_KEY",-999999999, -4321.000000000001, true, true, &ret); + s = db.ZRemrangebyscore("GP4_ZREMRANGEBYSCORE_KEY", -999999999, -4321.000000000001, true, true, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP4_ZREMRANGEBYSCORE_KEY", 12)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZREMRANGEBYSCORE_KEY",{{-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + ASSERT_TRUE(score_members_match(&db, "GP4_ZREMRANGEBYSCORE_KEY", + {{-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 5 Test ***************** - std::vector gp5_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp5_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP5_ZREMRANGEBYSCORE_KEY", gp5_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2455,20 +2622,42 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP5_ZREMRANGEBYSCORE_KEY", 15)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + ASSERT_TRUE(score_members_match(&db, "GP5_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 6 Test ***************** - std::vector gp6_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp6_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP6_ZREMRANGEBYSCORE_KEY", gp6_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2477,20 +2666,42 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP6_ZREMRANGEBYSCORE_KEY", 15)); - ASSERT_TRUE(score_members_match(&db, "GP6_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + ASSERT_TRUE(score_members_match(&db, "GP6_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 7 Test ***************** - std::vector gp7_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp7_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP7_ZREMRANGEBYSCORE_KEY", gp7_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2499,21 +2710,44 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP7_ZREMRANGEBYSCORE_KEY", 17)); - ASSERT_TRUE(score_members_match(&db, "GP7_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + ASSERT_TRUE(score_members_match(&db, "GP7_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 8 Test ***************** - std::vector gp8_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp8_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP8_ZREMRANGEBYSCORE_KEY", gp8_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2522,20 +2756,42 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(3, ret); ASSERT_TRUE(size_match(&db, "GP8_ZREMRANGEBYSCORE_KEY", 15)); - ASSERT_TRUE(score_members_match(&db, "GP8_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); - + ASSERT_TRUE(score_members_match(&db, "GP8_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 9 Test ***************** - std::vector gp9_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp9_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP9_ZREMRANGEBYSCORE_KEY", gp9_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2544,19 +2800,39 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP9_ZREMRANGEBYSCORE_KEY", 12)); - ASSERT_TRUE(score_members_match(&db, "GP9_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}})); - + ASSERT_TRUE(score_members_match(&db, "GP9_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}})); // ***************** Group 10 Test ***************** - std::vector gp10_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp10_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP10_ZREMRANGEBYSCORE_KEY", gp10_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2565,43 +2841,66 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP10_ZREMRANGEBYSCORE_KEY", 17)); - ASSERT_TRUE(score_members_match(&db, "GP10_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}})); - + ASSERT_TRUE(score_members_match(&db, "GP10_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}})); // ***************** Group 11 Test ***************** - std::vector gp11_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp11_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP11_ZREMRANGEBYSCORE_KEY", gp11_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); ASSERT_TRUE(make_expired(&db, "GP11_ZREMRANGEBYSCORE_KEY")); - s = db.ZRemrangebyscore("GP11_ZREMRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &ret); + s = db.ZRemrangebyscore("GP11_ZREMRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, &ret); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, ret); ASSERT_TRUE(size_match(&db, "GP11_ZREMRANGEBYSCORE_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP11_ZREMRANGEBYSCORE_KEY", {})); - // ***************** Group 12 Test ***************** - s = db.ZRemrangebyscore("GP12_ZREMRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &ret); + s = db.ZRemrangebyscore("GP12_ZREMRANGEBYSCORE_KEY", std::numeric_limits::lowest(), + std::numeric_limits::max(), true, true, &ret); ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(0, ret); ASSERT_TRUE(size_match(&db, "GP12_ZREMRANGEBYSCORE_KEY", 0)); - // ***************** Group 13 Test ***************** - std::vector gp13_sm {{0, "MM0"}}; + std::vector gp13_sm{{0, "MM0"}}; s = db.ZAdd("GP13_ZREMRANGEBYSCORE_KEY", gp13_sm, &ret); ASSERT_TRUE(s.ok()); @@ -2613,72 +2912,141 @@ TEST_F(ZSetsTest, ZRemrangebyscoreTest) { ASSERT_TRUE(size_match(&db, "GP13_ZREMRANGEBYSCORE_KEY", 0)); ASSERT_TRUE(score_members_match(&db, "GP13_ZREMRANGEBYSCORE_KEY", {})); - // ***************** Group 14 Test ***************** - std::vector gp14_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp14_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP14_ZREMRANGEBYSCORE_KEY", gp14_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); - s = db.ZRemrangebyscore("GP14_ZREMRANGEBYSCORE_KEY",-987654321.0000001, -7654321.000000001, false, false, &ret); + s = db.ZRemrangebyscore("GP14_ZREMRANGEBYSCORE_KEY", -987654321.0000001, -7654321.000000001, false, false, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); ASSERT_TRUE(size_match(&db, "GP14_ZREMRANGEBYSCORE_KEY", 17)); - ASSERT_TRUE(score_members_match(&db, "GP14_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(&db, "GP14_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 15 Test ***************** - std::vector gp15_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp15_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP15_ZREMRANGEBYSCORE_KEY", gp15_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); - s = db.ZRemrangebyscore("GP15_ZREMRANGEBYSCORE_KEY",-987654321.0000001, -7654321.000000001, true, false, &ret); + s = db.ZRemrangebyscore("GP15_ZREMRANGEBYSCORE_KEY", -987654321.0000001, -7654321.000000001, true, false, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(2, ret); ASSERT_TRUE(size_match(&db, "GP15_ZREMRANGEBYSCORE_KEY", 16)); - ASSERT_TRUE(score_members_match(&db, "GP15_ZREMRANGEBYSCORE_KEY", { {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(&db, "GP15_ZREMRANGEBYSCORE_KEY", + {{-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); // ***************** Group 16 Test ***************** - std::vector gp16_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; + std::vector gp16_sm{{-987654321.0000001, "MM1"}, + {-87654321.00000001, "MM2"}, + {-7654321.000000001, "MM3"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}}; s = db.ZAdd("GP16_ZREMRANGEBYSCORE_KEY", gp16_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(18, ret); - s = db.ZRemrangebyscore("GP16_ZREMRANGEBYSCORE_KEY",-987654321.0000001, -7654321.000000001, false, true, &ret); + s = db.ZRemrangebyscore("GP16_ZREMRANGEBYSCORE_KEY", -987654321.0000001, -7654321.000000001, false, true, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(2, ret); ASSERT_TRUE(size_match(&db, "GP16_ZREMRANGEBYSCORE_KEY", 16)); - ASSERT_TRUE(score_members_match(&db, "GP16_ZREMRANGEBYSCORE_KEY",{{-987654321.0000001, "MM1" }, - {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, - {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, - {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, - { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, - { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}})); + ASSERT_TRUE(score_members_match(&db, "GP16_ZREMRANGEBYSCORE_KEY", + {{-987654321.0000001, "MM1"}, + {-654321.0000000001, "MM4"}, + {-54321.00000000001, "MM5"}, + {-4321.000000000001, "MM6"}, + {-1000.000000000001, "MM7"}, + {-1000.000000000001, "MM8"}, + {-1000.000000000001, "MM9"}, + {-100.0000000000001, "MM10"}, + {0, "MM11"}, + {100.0000000000001, "MM12"}, + {4321.000000000001, "MM13"}, + {54321.00000000001, "MM14"}, + {654321.0000000001, "MM15"}, + {7654321.000000001, "MM16"}, + {87654321.00000001, "MM17"}, + {987654321.0000001, "MM18"}})); } // ZRevrange @@ -2687,7 +3055,7 @@ TEST_F(ZSetsTest, ZRevrangeTest) { std::vector score_members; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{0, "MM1"}}; + std::vector gp1_sm{{0, "MM1"}}; s = db.ZAdd("GP1_ZREVRANGE_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); @@ -2706,65 +3074,62 @@ TEST_F(ZSetsTest, ZRevrangeTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}})); - // ***************** Group 2 Test ***************** // // {0, MM0} {1, MM1} {2, MM2} {3, MM3} {4, MM4} {5, MM5} {6, MM6} {7, MM7} {8, MM8} // 8 7 6 5 4 3 2 1 0 // -1 -2 -3 -4 -5 -6 -7 -8 -9 - std::vector gp2_sm {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; + std::vector gp2_sm{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, + {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}}; s = db.ZAdd("GP2_ZREVRANGE_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(9, ret); ASSERT_TRUE(size_match(&db, "GP2_ZREVRANGE_KEY", 9)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZREVRANGE_KEY", {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, - {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, - {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); + ASSERT_TRUE(score_members_match( + &db, "GP2_ZREVRANGE_KEY", + {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}, {3, "MM3"}, {4, "MM4"}, {5, "MM5"}, {6, "MM6"}, {7, "MM7"}, {8, "MM8"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 0, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -9, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 0, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -9, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); - + ASSERT_TRUE(score_members_match( + score_members, + {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -100, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 0, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -100, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE(score_members_match( + score_members, + {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 0, 0, &score_members); ASSERT_TRUE(s.ok()); @@ -2784,36 +3149,33 @@ TEST_F(ZSetsTest, ZRevrangeTest) { s = db.ZRevrange("GP2_ZREVRANGE_KEY", 0, 5, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); + ASSERT_TRUE( + score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 0, -4, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); + ASSERT_TRUE( + score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -9, -4, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); + ASSERT_TRUE( + score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -9, 5, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); - + ASSERT_TRUE( + score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -100, 5, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); - + ASSERT_TRUE( + score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -100, -4, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, - {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); - + ASSERT_TRUE( + score_members_match(score_members, {{8, "MM8"}, {7, "MM7"}, {6, "MM6"}, {5, "MM5"}, {4, "MM4"}, {3, "MM3"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 3, 5, &score_members); ASSERT_TRUE(s.ok()); @@ -2833,39 +3195,38 @@ TEST_F(ZSetsTest, ZRevrangeTest) { s = db.ZRevrange("GP2_ZREVRANGE_KEY", 3, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE( + score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -6, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE( + score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 3, -1, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE( + score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -6, 8, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE( + score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", -6, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); + ASSERT_TRUE( + score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); s = db.ZRevrange("GP2_ZREVRANGE_KEY", 3, 100, &score_members); ASSERT_TRUE(s.ok()); - ASSERT_TRUE(score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, - {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); - + ASSERT_TRUE( + score_members_match(score_members, {{5, "MM5"}, {4, "MM4"}, {3, "MM3"}, {2, "MM2"}, {1, "MM1"}, {0, "MM0"}})); // ***************** Group 3 Test ***************** - std::vector gp3_sm1 {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}}; - std::vector gp3_sm2 {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}}; - std::vector gp3_sm3 {{0, "MM0"}, {1, "MM1"}, {2, "MM2"}}; + std::vector gp3_sm1{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}}; + std::vector gp3_sm2{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}}; + std::vector gp3_sm3{{0, "MM0"}, {1, "MM1"}, {2, "MM2"}}; s = db.ZAdd("GP3_ZREVRANGE_KEY1", gp3_sm1, &ret); ASSERT_TRUE(s.ok()); s = db.ZAdd("GP3_ZREVRANGE_KEY2", gp3_sm2, &ret); @@ -2889,9 +3250,8 @@ TEST_F(ZSetsTest, ZRevrangeTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{1, "MM1"}})); - // ***************** Group 4 Test ***************** - std::vector gp4_sm {{0, "MM1"}}; + std::vector gp4_sm{{0, "MM1"}}; s = db.ZAdd("GP4_ZREVRANGE_KEY", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(1, ret); @@ -2903,7 +3263,6 @@ TEST_F(ZSetsTest, ZRevrangeTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(score_members_match(score_members, {})); - // ***************** Group 5 Test ***************** s = db.ZRevrange("GP5_ZREVRANGE_KEY", 0, -1, &score_members); ASSERT_TRUE(s.IsNotFound()); @@ -2917,160 +3276,210 @@ TEST_F(ZSetsTest, ZRevrangeTest) { // std::vector score_members; // // ***************** Group 1 Test ***************** -// std::vector gp1_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, {-7654321.000000001, "MM3" }, -// {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, {-4321.000000000001, "MM6" }, -// {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM9" }, -// {-100.0000000000001, "MM10"}, { 0, "MM11"}, { 100.0000000000001, "MM12"}, -// { 4321.000000000001, "MM13"}, { 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, -// { 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { 987654321.0000001, "MM18"}}; +// std::vector gp1_sm {{-987654321.0000001, "MM1" }, {-87654321.00000001, "MM2" }, +// {-7654321.000000001, "MM3" }, +// {-654321.0000000001, "MM4" }, {-54321.00000000001, "MM5" }, +// {-4321.000000000001, "MM6" }, +// {-1000.000000000001, "MM7" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM9" }, +// {-100.0000000000001, "MM10"}, { 0, "MM11"}, { +// 100.0000000000001, "MM12"}, { 4321.000000000001, "MM13"}, { +// 54321.00000000001, "MM14"}, { 654321.0000000001, "MM15"}, { +// 7654321.000000001, "MM16"}, { 87654321.00000001, "MM17"}, { +// 987654321.0000001, "MM18"}}; // s = db.ZAdd("GP1_ZREVRANGEBYSCORE_KEY", gp1_sm, &ret); // ASSERT_TRUE(s.ok()); // ASSERT_EQ(18, ret); -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, &score_members); ASSERT_TRUE(s.ok()); +// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { +// 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); // // count = max offset = 0 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, std::numeric_limits::max(), 0, &score_members); +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, std::numeric_limits::max(), 0, &score_members); // ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); +// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { +// 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); // // count = 18 offset = 0 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 18, 0, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 18, 0, &score_members); ASSERT_TRUE(s.ok()); +// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { +// 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); // // count = 10 offset = 0 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 0, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10, 0, &score_members); ASSERT_TRUE(s.ok()); +// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { +// 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, // {-1000.000000000001, "MM9" }})); // // count = 10 offset = 1 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 1, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10, 1, &score_members); ASSERT_TRUE(s.ok()); +// ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, "MM17"}, { +// 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, // {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }})); // // count = 10 offset = 2 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 2, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, { { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }})); +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10, 2, &score_members); ASSERT_TRUE(s.ok()); +// ASSERT_TRUE(score_members_match(score_members, { { +// 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }})); // // count = 10 offset = 17 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 17, &score_members); -// ASSERT_TRUE(s.ok()); +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10, 17, &score_members); ASSERT_TRUE(s.ok()); // ASSERT_TRUE(score_members_match(score_members, {{-987654321.0000001, "MM1" }})); // // count = 10 offset = 18 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 18, &score_members); -// ASSERT_TRUE(s.ok()); +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10, 18, &score_members); ASSERT_TRUE(s.ok()); // ASSERT_TRUE(score_members_match(score_members, {})); // // count = 10 offset = 19 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10, 19, &score_members); -// ASSERT_TRUE(s.ok()); +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10, 19, &score_members); ASSERT_TRUE(s.ok()); // ASSERT_TRUE(score_members_match(score_members, {})); // // count = 10000 offset = 1 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10000, 1, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); - +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10000, 1, &score_members); ASSERT_TRUE(s.ok()); +// ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, "MM17"}, { +// 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); // // count = 10000 offset = 10000 -// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, 10000, 10000, &score_members); -// ASSERT_TRUE(s.ok()); +// s = db.ZRevrangebyscore("GP1_ZRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, 10000, 10000, &score_members); ASSERT_TRUE(s.ok()); // ASSERT_TRUE(score_members_match(score_members, {})); -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, true, false, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), false, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -987654321.0000001, 987654321.0000001, true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -987654321.0000001, 987654321.0000001, false, false, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, })); +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, +// true, true, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, +// {{-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), -1000.000000000001, +// true, false, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, +// {{-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), true, +// true, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, +// "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, std::numeric_limits::max(), false, +// true, &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, +// "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -987654321.0000001, 987654321.0000001, true, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, +// { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -987654321.0000001, 987654321.0000001, false, false, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, +// "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, })); // s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -999999999, -1000.000000000001 , true, true, &score_members); // ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }, -// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); +// ASSERT_TRUE(score_members_match(score_members, {{-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }, +// {-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); // s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -999999999, -1000.000000000001 , true, false, &score_members); // ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }, -// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, {-987654321.0000001, "MM1" }})); +// ASSERT_TRUE(score_members_match(score_members, {{-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, +// {-654321.0000000001, "MM4" }, +// {-7654321.000000001, "MM3" }, {-87654321.00000001, "MM2" }, +// {-987654321.0000001, "MM1" }})); -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -654321.0000000001, -4321.000000000001, true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{-4321.000000000001, "MM6" }, {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }})); +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -654321.0000000001, -4321.000000000001, true, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{-4321.000000000001, "MM6" }, +// {-54321.00000000001, "MM5" }, {-654321.0000000001, "MM4" }})); -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -654321.0000000001, -4321.000000000001, false, false, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{-54321.00000000001, "MM5" }})); +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -654321.0000000001, -4321.000000000001, false, false, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{-54321.00000000001, "MM5" +// }})); // s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 0, 0, true, true, &score_members); // ASSERT_TRUE(s.ok()); @@ -3080,38 +3489,40 @@ TEST_F(ZSetsTest, ZRevrangeTest) { // ASSERT_TRUE(s.ok()); // ASSERT_TRUE(score_members_match(score_members, {})); -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, false, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, })); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, false, false, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, })); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, 987654321.0000001, true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}, -// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, {-1000.000000000001, "MM7" }})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, 987654321.0000001, false, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, -// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { 4321.000000000001, "MM13"}, -// { 100.0000000000001, "MM12"}, { 0, "MM11"}, {-100.0000000000001, "MM10"}})); - -// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 999999999, std::numeric_limits::max(), true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {})); - +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, true, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, +// { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, false, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, +// { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, })); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 4321.000000000001, 987654321.0000001, false, false, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, { { 87654321.00000001, +// "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, })); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, 987654321.0000001, true, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, +// { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}, +// {-1000.000000000001, "MM9" }, {-1000.000000000001, "MM8" }, +// {-1000.000000000001, "MM7" }})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", -1000.000000000001, 987654321.0000001, false, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{ 987654321.0000001, "MM18"}, +// { 87654321.00000001, "MM17"}, { 7654321.000000001, "MM16"}, +// { 654321.0000000001, "MM15"}, { 54321.00000000001, "MM14"}, { +// 4321.000000000001, "MM13"}, { 100.0000000000001, "MM12"}, { 0, +// "MM11"}, {-100.0000000000001, "MM10"}})); + +// s = db.ZRevrangebyscore("GP1_ZREVRANGEBYSCORE_KEY", 999999999, std::numeric_limits::max(), true, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {})); // // ***************** Group 2 Test ***************** // std::vector gp2_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, @@ -3121,17 +3532,15 @@ TEST_F(ZSetsTest, ZRevrangeTest) { // ASSERT_TRUE(s.ok()); // ASSERT_EQ(7, ret); // ASSERT_TRUE(make_expired(&db, "GP2_ZREVRANGEBYSCORE_KEY")); -// s = db.ZRevrangebyscore("GP2_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &score_members); -// ASSERT_TRUE(s.IsNotFound()); +// s = db.ZRevrangebyscore("GP2_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, &score_members); ASSERT_TRUE(s.IsNotFound()); // ASSERT_TRUE(score_members_match(score_members, {})); - // // ***************** Group 3 Test ***************** -// s = db.ZRevrangebyscore("GP3_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), std::numeric_limits::max(), true, true, &score_members); -// ASSERT_TRUE(s.IsNotFound()); +// s = db.ZRevrangebyscore("GP3_ZREVRANGEBYSCORE_KEY", std::numeric_limits::lowest(), +// std::numeric_limits::max(), true, true, &score_members); ASSERT_TRUE(s.IsNotFound()); // ASSERT_TRUE(score_members_match(score_members, {})); - // // ***************** Group 4 Test ***************** // std::vector gp4_sm {{-1000000000.0000000001, "MM0"}, // {0, "MM1"}, @@ -3140,21 +3549,20 @@ TEST_F(ZSetsTest, ZRevrangeTest) { // ASSERT_TRUE(s.ok()); // ASSERT_EQ(3, ret); -// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, true, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{1000000000.0000000001, "MM2"}, {0, "MM1"}, {-1000000000.0000000001, "MM0"}})); +// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, true, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{1000000000.0000000001, +// "MM2"}, {0, "MM1"}, {-1000000000.0000000001, "MM0"}})); -// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, false, false, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}})); +// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, false, false, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}})); -// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, true, false, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}, {-1000000000.0000000001, "MM0"}})); +// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, true, false, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{0, "MM1"}, +// {-1000000000.0000000001, "MM0"}})); -// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, false, true, &score_members); -// ASSERT_TRUE(s.ok()); -// ASSERT_TRUE(score_members_match(score_members, {{1000000000.0000000001, "MM2"}, {0, "MM1"}})); +// s = db.ZRevrangebyscore("GP4_ZREVRANGEBYSCORE_KEY", -1000000000.0000000001, 1000000000.0000000001, false, true, +// &score_members); ASSERT_TRUE(s.ok()); ASSERT_TRUE(score_members_match(score_members, {{1000000000.0000000001, +// "MM2"}, {0, "MM1"}})); // } // ZRevrank @@ -3164,7 +3572,8 @@ TEST_F(ZSetsTest, ZRevrankTest) { // ***************** Group 1 Test ***************** // {-5, MM0} {-3, MM1} {-1, MM2} {0, MM3} {1, MM4} {3, MM5} {5, MM6} // 6 5 4 3 2 1 0 - std::vector gp1_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; + std::vector gp1_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP1_ZREVRANK_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); @@ -3189,9 +3598,9 @@ TEST_F(ZSetsTest, ZRevrankTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(rank, -1); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; + std::vector gp2_sm{{-5, "MM0"}, {-3, "MM1"}, {-1, "MM2"}, {0, "MM3"}, + {1, "MM4"}, {3, "MM5"}, {5, "MM6"}}; s = db.ZAdd("GP2_ZREVRANK_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(7, ret); @@ -3201,7 +3610,6 @@ TEST_F(ZSetsTest, ZRevrankTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(-1, rank); - // ***************** Group 3 Test ***************** s = db.ZRevrank("GP3_ZREVRANK_KEY", "MM0", &rank); ASSERT_TRUE(s.IsNotFound()); @@ -3214,16 +3622,19 @@ TEST_F(ZSetsTest, ZScoreTest) { double score; // ***************** Group 1 Test ***************** - std::vector gp1_sm {{54354.497895352, "MM1"}, {100.987654321, "MM2"}, - {-100.000000001, "MM3"}, {-100.000000002, "MM4"}, - {-100.000000001, "MM5"}, {-100.000000002, "MM6"}}; + std::vector gp1_sm{{54354.497895352, "MM1"}, {100.987654321, "MM2"}, {-100.000000001, "MM3"}, + {-100.000000002, "MM4"}, {-100.000000001, "MM5"}, {-100.000000002, "MM6"}}; s = db.ZAdd("GP1_ZSCORE_KEY", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(6, ret); ASSERT_TRUE(size_match(&db, "GP1_ZSCORE_KEY", 6)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZSCORE_KEY", {{-100.000000002, "MM4"}, {-100.000000002, "MM6"}, - {-100.000000001, "MM3"}, {-100.000000001, "MM5"}, - {100.987654321, "MM2"}, {54354.497895352,"MM1"}})); + ASSERT_TRUE(score_members_match(&db, "GP1_ZSCORE_KEY", + {{-100.000000002, "MM4"}, + {-100.000000002, "MM6"}, + {-100.000000001, "MM3"}, + {-100.000000001, "MM5"}, + {100.987654321, "MM2"}, + {54354.497895352, "MM1"}})); s = db.ZScore("GP1_ZSCORE_KEY", "MM1", &score); ASSERT_TRUE(s.ok()); ASSERT_DOUBLE_EQ(54354.497895352, score); @@ -3252,20 +3663,18 @@ TEST_F(ZSetsTest, ZScoreTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_DOUBLE_EQ(0, score); - // ***************** Group 2 Test ***************** - std::vector gp2_sm {{4, "MM1"}, {3, "MM2"}, {2, "MM3"}, {1, "MM4"}}; + std::vector gp2_sm{{4, "MM1"}, {3, "MM2"}, {2, "MM3"}, {1, "MM4"}}; s = db.ZAdd("GP2_ZSCORE_KEY", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(4, ret); ASSERT_TRUE(size_match(&db, "GP2_ZSCORE_KEY", 4)); - ASSERT_TRUE(score_members_match(&db, "GP2_ZSCORE_KEY", {{1,"MM4"}, {2,"MM3"}, {3, "MM2"}, {4, "MM1"}})); + ASSERT_TRUE(score_members_match(&db, "GP2_ZSCORE_KEY", {{1, "MM4"}, {2, "MM3"}, {3, "MM2"}, {4, "MM1"}})); ASSERT_TRUE(make_expired(&db, "GP2_ZSCORE_KEY")); s = db.ZScore("GP2_ZSCORE_KEY", "MM1", &score); ASSERT_TRUE(s.IsNotFound()); ASSERT_DOUBLE_EQ(0, score); - // ***************** Group 3 Test ***************** s = db.ZScore("GP3_ZSCORE_KEY", "MM1", &score); ASSERT_TRUE(s.IsNotFound()); @@ -3283,18 +3692,20 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {1001001, MM1} {10010010, MM2} {100100100, MM3} // - std::vector gp1_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp1_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp1_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp1_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp1_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp1_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP1_ZUNIONSTORE_SM1", gp1_sm1, &ret); s = db.ZAdd("GP1_ZUNIONSTORE_SM2", gp1_sm2, &ret); s = db.ZAdd("GP1_ZUNIONSTORE_SM3", gp1_sm3, &ret); - s = db.ZUnionstore("GP1_ZUNIONSTORE_DESTINATION", {"GP1_ZUNIONSTORE_SM1", "GP1_ZUNIONSTORE_SM2", "GP1_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::SUM, &ret); + s = db.ZUnionstore("GP1_ZUNIONSTORE_DESTINATION", + {"GP1_ZUNIONSTORE_SM1", "GP1_ZUNIONSTORE_SM2", "GP1_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP1_ZUNIONSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZUNIONSTORE_DESTINATION", {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP1_ZUNIONSTORE_DESTINATION", + {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); // ***************** Group 2 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3303,19 +3714,20 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // { 1, MM1} { 10, MM2} { 100, MM3} // - std::vector gp2_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp2_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp2_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp2_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp2_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp2_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP2_ZUNIONSTORE_SM1", gp2_sm1, &ret); s = db.ZAdd("GP2_ZUNIONSTORE_SM2", gp2_sm2, &ret); s = db.ZAdd("GP2_ZUNIONSTORE_SM3", gp2_sm3, &ret); - s = db.ZUnionstore("GP2_ZUNIONSTORE_DESTINATION", {"GP2_ZUNIONSTORE_SM1", "GP2_ZUNIONSTORE_SM2", "GP2_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::MIN, &ret); + s = db.ZUnionstore("GP2_ZUNIONSTORE_DESTINATION", + {"GP2_ZUNIONSTORE_SM1", "GP2_ZUNIONSTORE_SM2", "GP2_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::MIN, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP2_ZUNIONSTORE_DESTINATION", 3)); ASSERT_TRUE(score_members_match(&db, "GP2_ZUNIONSTORE_DESTINATION", {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}})); - // ***************** Group 3 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 // { 1000, MM1} { 10000, MM2} { 100000, MM3} weight 1 @@ -3323,18 +3735,20 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {1000000, MM1} {10000000, MM2} {100000000, MM3} // - std::vector gp3_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp3_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp3_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp3_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp3_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp3_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP3_ZUNIONSTORE_SM1", gp3_sm1, &ret); s = db.ZAdd("GP3_ZUNIONSTORE_SM2", gp3_sm2, &ret); s = db.ZAdd("GP3_ZUNIONSTORE_SM3", gp3_sm3, &ret); - s = db.ZUnionstore("GP3_ZUNIONSTORE_DESTINATION", {"GP3_ZUNIONSTORE_SM1", "GP3_ZUNIONSTORE_SM2", "GP3_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::MAX, &ret); + s = db.ZUnionstore("GP3_ZUNIONSTORE_DESTINATION", + {"GP3_ZUNIONSTORE_SM1", "GP3_ZUNIONSTORE_SM2", "GP3_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::MAX, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP3_ZUNIONSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZUNIONSTORE_DESTINATION", {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP3_ZUNIONSTORE_DESTINATION", + {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}})); // ***************** Group 4 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3343,18 +3757,20 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {3002001, MM1} {30020010, MM2} {300200100, MM3} // - std::vector gp4_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp4_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp4_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp4_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp4_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp4_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP4_ZUNIONSTORE_SM1", gp4_sm1, &ret); s = db.ZAdd("GP4_ZUNIONSTORE_SM2", gp4_sm2, &ret); s = db.ZAdd("GP4_ZUNIONSTORE_SM3", gp4_sm3, &ret); - s = db.ZUnionstore("GP4_ZUNIONSTORE_DESTINATION", {"GP4_ZUNIONSTORE_SM1", "GP4_ZUNIONSTORE_SM2", "GP4_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZUnionstore("GP4_ZUNIONSTORE_DESTINATION", + {"GP4_ZUNIONSTORE_SM1", "GP4_ZUNIONSTORE_SM2", "GP4_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP4_ZUNIONSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZUNIONSTORE_DESTINATION", {{3002001, "MM1"}, {30020010, "MM2"}, {300200100, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP4_ZUNIONSTORE_DESTINATION", + {{3002001, "MM1"}, {30020010, "MM2"}, {300200100, "MM3"}})); // ***************** Group 5 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3363,18 +3779,20 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {3002001, MM1} { 20010, MM2} {300200100, MM3} // - std::vector gp5_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp5_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp5_sm3 {{1000000, "MM1"}, {100000000, "MM3"}}; + std::vector gp5_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp5_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp5_sm3{{1000000, "MM1"}, {100000000, "MM3"}}; s = db.ZAdd("GP5_ZUNIONSTORE_SM1", gp5_sm1, &ret); s = db.ZAdd("GP5_ZUNIONSTORE_SM2", gp5_sm2, &ret); s = db.ZAdd("GP5_ZUNIONSTORE_SM3", gp5_sm3, &ret); - s = db.ZUnionstore("GP5_ZUNIONSTORE_DESTINATION", {"GP5_ZUNIONSTORE_SM1", "GP5_ZUNIONSTORE_SM2", "GP5_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZUnionstore("GP5_ZUNIONSTORE_DESTINATION", + {"GP5_ZUNIONSTORE_SM1", "GP5_ZUNIONSTORE_SM2", "GP5_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP5_ZUNIONSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP5_ZUNIONSTORE_DESTINATION", {{20010, "MM2"}, {3002001, "MM1"}, {300200100, "MM3"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP5_ZUNIONSTORE_DESTINATION", {{20010, "MM2"}, {3002001, "MM1"}, {300200100, "MM3"}})); // ***************** Group 6 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3383,19 +3801,21 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {3000001, MM1} { 10, MM2} {300000100, MM3} // - std::vector gp6_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp6_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp6_sm3 {{1000000, "MM1"}, {100000000, "MM3"}}; + std::vector gp6_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp6_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp6_sm3{{1000000, "MM1"}, {100000000, "MM3"}}; s = db.ZAdd("GP6_ZUNIONSTORE_SM1", gp6_sm1, &ret); s = db.ZAdd("GP6_ZUNIONSTORE_SM2", gp6_sm2, &ret); s = db.ZAdd("GP6_ZUNIONSTORE_SM3", gp6_sm3, &ret); ASSERT_TRUE(make_expired(&db, "GP6_ZUNIONSTORE_SM2")); - s = db.ZUnionstore("GP6_ZUNIONSTORE_DESTINATION", {"GP6_ZUNIONSTORE_SM1", "GP6_ZUNIONSTORE_SM2", "GP6_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZUnionstore("GP6_ZUNIONSTORE_DESTINATION", + {"GP6_ZUNIONSTORE_SM1", "GP6_ZUNIONSTORE_SM2", "GP6_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP6_ZUNIONSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP6_ZUNIONSTORE_DESTINATION", {{10, "MM2"}, {3000001, "MM1"}, {300000100, "MM3"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP6_ZUNIONSTORE_DESTINATION", {{10, "MM2"}, {3000001, "MM1"}, {300000100, "MM3"}})); // ***************** Group 7 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3404,19 +3824,21 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // { 1, MM1} { 10, MM2} { 100, MM3} {3000, MM4} // - std::vector gp7_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp7_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp7_sm3 { {1000, "MM4"}}; + std::vector gp7_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp7_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp7_sm3{{1000, "MM4"}}; s = db.ZAdd("GP7_ZUNIONSTORE_SM1", gp7_sm1, &ret); s = db.ZAdd("GP7_ZUNIONSTORE_SM2", gp7_sm2, &ret); s = db.ZAdd("GP7_ZUNIONSTORE_SM3", gp7_sm3, &ret); ASSERT_TRUE(make_expired(&db, "GP7_ZUNIONSTORE_SM2")); - s = db.ZUnionstore("GP7_ZUNIONSTORE_DESTINATION", {"GP7_ZUNIONSTORE_SM1", "GP7_ZUNIONSTORE_SM2", "GP7_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZUnionstore("GP7_ZUNIONSTORE_DESTINATION", + {"GP7_ZUNIONSTORE_SM1", "GP7_ZUNIONSTORE_SM2", "GP7_ZUNIONSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(size_match(&db, "GP7_ZUNIONSTORE_DESTINATION", 4)); - ASSERT_TRUE(score_members_match(&db, "GP7_ZUNIONSTORE_DESTINATION", {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}, {3000, "MM4"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP7_ZUNIONSTORE_DESTINATION", {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}, {3000, "MM4"}})); // ***************** Group 8 Test ***************** // {1, MM1} weight 1 @@ -3425,19 +3847,20 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {1, MM1} {1, MM2} {1, MM3} // - std::vector gp8_sm1 {{1, "MM1"}}; - std::vector gp8_sm2 {{1, "MM2"}}; - std::vector gp8_sm3 {{1, "MM3"}}; + std::vector gp8_sm1{{1, "MM1"}}; + std::vector gp8_sm2{{1, "MM2"}}; + std::vector gp8_sm3{{1, "MM3"}}; s = db.ZAdd("GP8_ZUNIONSTORE_SM1", gp8_sm1, &ret); s = db.ZAdd("GP8_ZUNIONSTORE_SM2", gp8_sm2, &ret); s = db.ZAdd("GP8_ZUNIONSTORE_SM3", gp8_sm3, &ret); - s = db.ZUnionstore("GP8_ZUNIONSTORE_DESTINATION", {"GP8_ZUNIONSTORE_SM1", "GP8_ZUNIONSTORE_SM2", "GP8_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::MIN, &ret); + s = db.ZUnionstore("GP8_ZUNIONSTORE_DESTINATION", + {"GP8_ZUNIONSTORE_SM1", "GP8_ZUNIONSTORE_SM2", "GP8_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::MIN, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP8_ZUNIONSTORE_DESTINATION", 3)); ASSERT_TRUE(score_members_match(&db, "GP8_ZUNIONSTORE_DESTINATION", {{1, "MM1"}, {1, "MM2"}, {1, "MM3"}})); - // ***************** Group 9 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 // { 1000, MM1} { 10000, MM2} { 100000, MM3} weight 1 @@ -3445,10 +3868,10 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {1001001, MM1} {10010010, MM2} {100100100, MM3} // - std::vector gp9_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp9_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp9_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; - std::vector gp9_destination {{1, "MM1"}}; + std::vector gp9_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp9_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp9_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp9_destination{{1, "MM1"}}; s = db.ZAdd("GP9_ZUNIONSTORE_SM1", gp9_sm1, &ret); s = db.ZAdd("GP9_ZUNIONSTORE_SM2", gp9_sm2, &ret); s = db.ZAdd("GP9_ZUNIONSTORE_SM3", gp9_sm3, &ret); @@ -3458,12 +3881,14 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { ASSERT_TRUE(size_match(&db, "GP9_ZUNIONSTORE_DESTINATION", 1)); ASSERT_TRUE(score_members_match(&db, "GP9_ZUNIONSTORE_DESTINATION", {{1, "MM1"}})); - s = db.ZUnionstore("GP9_ZUNIONSTORE_DESTINATION", {"GP9_ZUNIONSTORE_SM1", "GP9_ZUNIONSTORE_SM2", "GP9_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::SUM, &ret); + s = db.ZUnionstore("GP9_ZUNIONSTORE_DESTINATION", + {"GP9_ZUNIONSTORE_SM1", "GP9_ZUNIONSTORE_SM2", "GP9_ZUNIONSTORE_SM3"}, {1, 1, 1}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP9_ZUNIONSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP9_ZUNIONSTORE_DESTINATION", {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP9_ZUNIONSTORE_DESTINATION", + {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); // ***************** Group 10 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3472,26 +3897,27 @@ TEST_F(ZSetsTest, ZUnionstoreTest) { // // {1001001, MM1} {10010010, MM2} {100100100, MM3} // - std::vector gp10_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp10_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp10_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp10_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp10_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp10_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP10_ZUNIONSTORE_SM1", gp10_sm1, &ret); s = db.ZAdd("GP10_ZUNIONSTORE_SM2", gp10_sm2, &ret); s = db.ZAdd("GP10_ZUNIONSTORE_SM3", gp10_sm3, &ret); s = db.ZUnionstore("GP10_ZUNIONSTORE_DESTINATION", - {"GP10_ZUNIONSTORE_SM1", "GP10_ZUNIONSTORE_SM2", "GP10_ZUNIONSTORE_SM3","GP10_ZUNIONSTORE_SM4"}, {1, 1, 1, 1}, storage::SUM, &ret); + {"GP10_ZUNIONSTORE_SM1", "GP10_ZUNIONSTORE_SM2", "GP10_ZUNIONSTORE_SM3", "GP10_ZUNIONSTORE_SM4"}, + {1, 1, 1, 1}, storage::SUM, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP10_ZUNIONSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP10_ZUNIONSTORE_DESTINATION", {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP10_ZUNIONSTORE_DESTINATION", + {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); // ***************** Group 11 Test ***************** // {-999999999, MM1} weight 0 // // { 0, MM1} // - std::vector gp11_sm1 {{-999999999, "MM1"}}; + std::vector gp11_sm1{{-999999999, "MM1"}}; s = db.ZAdd("GP11_ZUNIONSTORE_SM1", gp11_sm1, &ret); s = db.ZUnionstore("GP11_ZUNIONSTORE_DESTINATION", {"GP11_ZUNIONSTORE_SM1"}, {0}, storage::SUM, &ret); ASSERT_TRUE(s.ok()); @@ -3511,18 +3937,20 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {1001001, MM1} {10010010, MM2} {100100100, MM3} // - std::vector gp1_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp1_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp1_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp1_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp1_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp1_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP1_ZINTERSTORE_SM1", gp1_sm1, &ret); s = db.ZAdd("GP1_ZINTERSTORE_SM2", gp1_sm2, &ret); s = db.ZAdd("GP1_ZINTERSTORE_SM3", gp1_sm3, &ret); - s = db.ZInterstore("GP1_ZINTERSTORE_DESTINATION", {"GP1_ZINTERSTORE_SM1", "GP1_ZINTERSTORE_SM2", "GP1_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::SUM, &ret); + s = db.ZInterstore("GP1_ZINTERSTORE_DESTINATION", + {"GP1_ZINTERSTORE_SM1", "GP1_ZINTERSTORE_SM2", "GP1_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP1_ZINTERSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP1_ZINTERSTORE_DESTINATION", {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP1_ZINTERSTORE_DESTINATION", + {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); // ***************** Group 2 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3531,19 +3959,20 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // { 1, MM1} { 10, MM2} { 100, MM3} // - std::vector gp2_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp2_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp2_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp2_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp2_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp2_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP2_ZINTERSTORE_SM1", gp2_sm1, &ret); s = db.ZAdd("GP2_ZINTERSTORE_SM2", gp2_sm2, &ret); s = db.ZAdd("GP2_ZINTERSTORE_SM3", gp2_sm3, &ret); - s = db.ZInterstore("GP2_ZINTERSTORE_DESTINATION", {"GP2_ZINTERSTORE_SM1", "GP2_ZINTERSTORE_SM2", "GP2_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::MIN, &ret); + s = db.ZInterstore("GP2_ZINTERSTORE_DESTINATION", + {"GP2_ZINTERSTORE_SM1", "GP2_ZINTERSTORE_SM2", "GP2_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::MIN, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP2_ZINTERSTORE_DESTINATION", 3)); ASSERT_TRUE(score_members_match(&db, "GP2_ZINTERSTORE_DESTINATION", {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}})); - // ***************** Group 3 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 // { 1000, MM1} { 10000, MM2} { 100000, MM3} weight 1 @@ -3551,18 +3980,20 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {1000000, MM1} {10000000, MM2} {100000000, MM3} // - std::vector gp3_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp3_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp3_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp3_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp3_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp3_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP3_ZINTERSTORE_SM1", gp3_sm1, &ret); s = db.ZAdd("GP3_ZINTERSTORE_SM2", gp3_sm2, &ret); s = db.ZAdd("GP3_ZINTERSTORE_SM3", gp3_sm3, &ret); - s = db.ZInterstore("GP3_ZINTERSTORE_DESTINATION", {"GP3_ZINTERSTORE_SM1", "GP3_ZINTERSTORE_SM2", "GP3_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::MAX, &ret); + s = db.ZInterstore("GP3_ZINTERSTORE_DESTINATION", + {"GP3_ZINTERSTORE_SM1", "GP3_ZINTERSTORE_SM2", "GP3_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::MAX, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP3_ZINTERSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP3_ZINTERSTORE_DESTINATION", {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP3_ZINTERSTORE_DESTINATION", + {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}})); // ***************** Group 4 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3571,18 +4002,20 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {3002001, MM1} {30020010, MM2} {300200100, MM3} // - std::vector gp4_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp4_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp4_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp4_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp4_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp4_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP4_ZINTERSTORE_SM1", gp4_sm1, &ret); s = db.ZAdd("GP4_ZINTERSTORE_SM2", gp4_sm2, &ret); s = db.ZAdd("GP4_ZINTERSTORE_SM3", gp4_sm3, &ret); - s = db.ZInterstore("GP4_ZINTERSTORE_DESTINATION", {"GP4_ZINTERSTORE_SM1", "GP4_ZINTERSTORE_SM2", "GP4_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZInterstore("GP4_ZINTERSTORE_DESTINATION", + {"GP4_ZINTERSTORE_SM1", "GP4_ZINTERSTORE_SM2", "GP4_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP4_ZINTERSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP4_ZINTERSTORE_DESTINATION", {{3002001, "MM1"}, {30020010, "MM2"}, {300200100, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP4_ZINTERSTORE_DESTINATION", + {{3002001, "MM1"}, {30020010, "MM2"}, {300200100, "MM3"}})); // ***************** Group 5 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3591,19 +4024,20 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {3002001, MM1} {300200100, MM3} // - std::vector gp5_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp5_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp5_sm3 {{1000000, "MM1"}, {100000000, "MM3"}}; + std::vector gp5_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp5_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp5_sm3{{1000000, "MM1"}, {100000000, "MM3"}}; s = db.ZAdd("GP5_ZINTERSTORE_SM1", gp5_sm1, &ret); s = db.ZAdd("GP5_ZINTERSTORE_SM2", gp5_sm2, &ret); s = db.ZAdd("GP5_ZINTERSTORE_SM3", gp5_sm3, &ret); - s = db.ZInterstore("GP5_ZINTERSTORE_DESTINATION", {"GP5_ZINTERSTORE_SM1", "GP5_ZINTERSTORE_SM2", "GP5_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZInterstore("GP5_ZINTERSTORE_DESTINATION", + {"GP5_ZINTERSTORE_SM1", "GP5_ZINTERSTORE_SM2", "GP5_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); ASSERT_TRUE(size_match(&db, "GP5_ZINTERSTORE_DESTINATION", 2)); ASSERT_TRUE(score_members_match(&db, "GP5_ZINTERSTORE_DESTINATION", {{3002001, "MM1"}, {300200100, "MM3"}})); - // ***************** Group 6 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 // { 1000, MM1} { 10000, MM2} { 100000, MM3} weight 2 (expire) @@ -3611,20 +4045,21 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {3000001, MM1} { 10, MM2} {300000100, MM3} // - std::vector gp6_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp6_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp6_sm3 {{1000000, "MM1"}, {100000000, "MM3"}}; + std::vector gp6_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp6_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp6_sm3{{1000000, "MM1"}, {100000000, "MM3"}}; s = db.ZAdd("GP6_ZINTERSTORE_SM1", gp6_sm1, &ret); s = db.ZAdd("GP6_ZINTERSTORE_SM2", gp6_sm2, &ret); s = db.ZAdd("GP6_ZINTERSTORE_SM3", gp6_sm3, &ret); ASSERT_TRUE(make_expired(&db, "GP6_ZINTERSTORE_SM2")); - s = db.ZInterstore("GP6_ZINTERSTORE_DESTINATION", {"GP6_ZINTERSTORE_SM1", "GP6_ZINTERSTORE_SM2", "GP6_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZInterstore("GP6_ZINTERSTORE_DESTINATION", + {"GP6_ZINTERSTORE_SM1", "GP6_ZINTERSTORE_SM2", "GP6_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP6_ZINTERSTORE_DESTINATION", 0)); ASSERT_TRUE(score_members_match(&db, "GP6_ZINTERSTORE_DESTINATION", {})); - // ***************** Group 7 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 // {1000, MM1} {10000, MM2} {100000, MM3} weight 2 (expire) @@ -3632,20 +4067,21 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // { 1, MM1} { 10, MM2} { 100, MM3} {3000, MM4} // - std::vector gp7_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp7_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp7_sm3 { {1000, "MM4"}}; + std::vector gp7_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp7_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp7_sm3{{1000, "MM4"}}; s = db.ZAdd("GP7_ZINTERSTORE_SM1", gp7_sm1, &ret); s = db.ZAdd("GP7_ZINTERSTORE_SM2", gp7_sm2, &ret); s = db.ZAdd("GP7_ZINTERSTORE_SM3", gp7_sm3, &ret); ASSERT_TRUE(make_expired(&db, "GP7_ZINTERSTORE_SM2")); - s = db.ZInterstore("GP7_ZINTERSTORE_DESTINATION", {"GP7_ZINTERSTORE_SM1", "GP7_ZINTERSTORE_SM2", "GP7_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, &ret); + s = db.ZInterstore("GP7_ZINTERSTORE_DESTINATION", + {"GP7_ZINTERSTORE_SM1", "GP7_ZINTERSTORE_SM2", "GP7_ZINTERSTORE_SM3"}, {1, 2, 3}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP7_ZINTERSTORE_DESTINATION", 0)); ASSERT_TRUE(score_members_match(&db, "GP7_ZINTERSTORE_DESTINATION", {})); - // ***************** Group 8 Test ***************** // {1, MM1} weight 1 // {1, MM2} weight 1 @@ -3653,19 +4089,20 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {1, MM1} {1, MM2} {1, MM3} // - std::vector gp8_sm1 {{1, "MM1"}}; - std::vector gp8_sm2 {{1, "MM2"}}; - std::vector gp8_sm3 {{1, "MM3"}}; + std::vector gp8_sm1{{1, "MM1"}}; + std::vector gp8_sm2{{1, "MM2"}}; + std::vector gp8_sm3{{1, "MM3"}}; s = db.ZAdd("GP8_ZINTERSTORE_SM1", gp8_sm1, &ret); s = db.ZAdd("GP8_ZINTERSTORE_SM2", gp8_sm2, &ret); s = db.ZAdd("GP8_ZINTERSTORE_SM3", gp8_sm3, &ret); - s = db.ZInterstore("GP8_ZINTERSTORE_DESTINATION", {"GP8_ZINTERSTORE_SM1", "GP8_ZINTERSTORE_SM2", "GP8_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::MIN, &ret); + s = db.ZInterstore("GP8_ZINTERSTORE_DESTINATION", + {"GP8_ZINTERSTORE_SM1", "GP8_ZINTERSTORE_SM2", "GP8_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::MIN, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP8_ZINTERSTORE_DESTINATION", 0)); ASSERT_TRUE(score_members_match(&db, "GP8_ZINTERSTORE_DESTINATION", {})); - // ***************** Group 9 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 // { 1000, MM1} { 10000, MM2} { 100000, MM3} weight 1 @@ -3673,10 +4110,10 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {1001001, MM1} {10010010, MM2} {100100100, MM3} // - std::vector gp9_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp9_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp9_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; - std::vector gp9_destination {{1, "MM1"}}; + std::vector gp9_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp9_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp9_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp9_destination{{1, "MM1"}}; s = db.ZAdd("GP9_ZINTERSTORE_SM1", gp9_sm1, &ret); s = db.ZAdd("GP9_ZINTERSTORE_SM2", gp9_sm2, &ret); s = db.ZAdd("GP9_ZINTERSTORE_SM3", gp9_sm3, &ret); @@ -3686,12 +4123,14 @@ TEST_F(ZSetsTest, ZInterstoreTest) { ASSERT_TRUE(size_match(&db, "GP9_ZINTERSTORE_DESTINATION", 1)); ASSERT_TRUE(score_members_match(&db, "GP9_ZINTERSTORE_DESTINATION", {{1, "MM1"}})); - s = db.ZInterstore("GP9_ZINTERSTORE_DESTINATION", {"GP9_ZINTERSTORE_SM1", "GP9_ZINTERSTORE_SM2", "GP9_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::SUM, &ret); + s = db.ZInterstore("GP9_ZINTERSTORE_DESTINATION", + {"GP9_ZINTERSTORE_SM1", "GP9_ZINTERSTORE_SM2", "GP9_ZINTERSTORE_SM3"}, {1, 1, 1}, storage::SUM, + &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP9_ZINTERSTORE_DESTINATION", 3)); - ASSERT_TRUE(score_members_match(&db, "GP9_ZINTERSTORE_DESTINATION", {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); - + ASSERT_TRUE(score_members_match(&db, "GP9_ZINTERSTORE_DESTINATION", + {{1001001, "MM1"}, {10010010, "MM2"}, {100100100, "MM3"}})); // ***************** Group 10 Test ***************** // { 1, MM1} { 10, MM2} { 100, MM3} weight 1 @@ -3700,14 +4139,15 @@ TEST_F(ZSetsTest, ZInterstoreTest) { // // {1001001, MM1} {10010010, MM2} {100100100, MM3} // - std::vector gp10_sm1 {{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; - std::vector gp10_sm2 {{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; - std::vector gp10_sm3 {{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; + std::vector gp10_sm1{{1, "MM1"}, {10, "MM2"}, {100, "MM3"}}; + std::vector gp10_sm2{{1000, "MM1"}, {10000, "MM2"}, {100000, "MM3"}}; + std::vector gp10_sm3{{1000000, "MM1"}, {10000000, "MM2"}, {100000000, "MM3"}}; s = db.ZAdd("GP10_ZINTERSTORE_SM1", gp10_sm1, &ret); s = db.ZAdd("GP10_ZINTERSTORE_SM2", gp10_sm2, &ret); s = db.ZAdd("GP10_ZINTERSTORE_SM3", gp10_sm3, &ret); s = db.ZInterstore("GP10_ZINTERSTORE_DESTINATION", - {"GP10_ZINTERSTORE_SM1", "GP10_ZINTERSTORE_SM2", "GP10_ZINTERSTORE_SM3", "GP10_ZINTERSTORE_SM4"}, {1, 1, 1, 1}, storage::SUM, &ret); + {"GP10_ZINTERSTORE_SM1", "GP10_ZINTERSTORE_SM2", "GP10_ZINTERSTORE_SM3", "GP10_ZINTERSTORE_SM4"}, + {1, 1, 1, 1}, storage::SUM, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP10_ZINTERSTORE_DESTINATION", 0)); @@ -3722,9 +4162,8 @@ TEST_F(ZSetsTest, ZRangebylexTest) { // ***************** Group 1 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp1_sm1 {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp1_sm1{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP1_ZRANGEBYLEX", gp1_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -3825,13 +4264,11 @@ TEST_F(ZSetsTest, ZRangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_TRUE(members_match(members, {})); - // ***************** Group 2 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} (expire) // - std::vector gp2_sm1 {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp2_sm1{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP2_ZRANGEBYLEX", gp1_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -3841,7 +4278,6 @@ TEST_F(ZSetsTest, ZRangebylexTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_TRUE(members_match(members, {})); - // ***************** Group 3 Test ***************** s = db.ZRangebylex("GP3_ZRANGEBYLEX", "-", "+", true, true, &members); ASSERT_TRUE(s.IsNotFound()); @@ -3856,9 +4292,8 @@ TEST_F(ZSetsTest, ZLexcountTest) { // ***************** Group 1 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp1_sm1 {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp1_sm1{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP1_ZLEXCOUNT", gp1_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -3959,13 +4394,11 @@ TEST_F(ZSetsTest, ZLexcountTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); - // ***************** Group 2 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} (expire) // - std::vector gp2_sm1 {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp2_sm1{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP2_ZLEXCOUNT", gp1_sm1, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -3975,7 +4408,6 @@ TEST_F(ZSetsTest, ZLexcountTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - // ***************** Group 3 Test ***************** s = db.ZLexcount("GP3_ZLEXCOUNT", "-", "+", true, true, &ret); ASSERT_TRUE(s.IsNotFound()); @@ -3990,9 +4422,8 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { // ***************** Group 1 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp1_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp1_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP1_ZREMRANGEBYLEX", gp1_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4006,9 +4437,8 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { // ***************** Group 2 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp2_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp2_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP2_ZREMRANGEBYLEX", gp2_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4019,13 +4449,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP2_ZREMRANGEBYLEX", 0)); ASSERT_TRUE(score_members_match(&db, "GP2_ZREMRANGEBYLEX", {})); - // ***************** Group 3 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp3_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp3_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP3_ZREMRANGEBYLEX", gp3_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4036,13 +4464,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP3_ZREMRANGEBYLEX", 1)); ASSERT_TRUE(score_members_match(&db, "GP3_ZREMRANGEBYLEX", {{1, "m"}})); - // ***************** Group 4 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp4_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp4_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP4_ZREMRANGEBYLEX", gp4_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4053,13 +4479,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP4_ZREMRANGEBYLEX", 1)); ASSERT_TRUE(score_members_match(&db, "GP4_ZREMRANGEBYLEX", {{1, "e"}})); - // ***************** Group 5 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp5_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp5_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP5_ZREMRANGEBYLEX", gp5_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4070,13 +4494,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP5_ZREMRANGEBYLEX", 2)); ASSERT_TRUE(score_members_match(&db, "GP5_ZREMRANGEBYLEX", {{1, "e"}, {1, "m"}})); - // ***************** Group 6 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp6_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp6_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP6_ZREMRANGEBYLEX", gp6_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4085,16 +4507,14 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 3); ASSERT_TRUE(size_match(&db, "GP6_ZREMRANGEBYLEX", 6)); - ASSERT_TRUE(score_members_match(&db, "GP6_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "k"}, {1, "l"}, {1, "m"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP6_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 7 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp7_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp7_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP7_ZREMRANGEBYLEX", gp7_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4103,17 +4523,14 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 2); ASSERT_TRUE(size_match(&db, "GP7_ZREMRANGEBYLEX", 7)); - ASSERT_TRUE(score_members_match(&db, "GP7_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "j"}, {1, "k"}, {1, "l"}, - {1, "m"}})); - + ASSERT_TRUE(score_members_match(&db, "GP7_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 8 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp8_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp8_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP8_ZREMRANGEBYLEX", gp8_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4122,17 +4539,14 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); ASSERT_TRUE(size_match(&db, "GP8_ZREMRANGEBYLEX", 8)); - ASSERT_TRUE(score_members_match(&db, "GP8_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "j"}, {1, "k"}, - {1, "l"}, {1, "m"}})); - + ASSERT_TRUE(score_members_match(&db, "GP8_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 9 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp9_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp9_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP9_ZREMRANGEBYLEX", gp9_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4141,17 +4555,14 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); ASSERT_TRUE(size_match(&db, "GP9_ZREMRANGEBYLEX", 8)); - ASSERT_TRUE(score_members_match(&db, "GP9_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "j"}, {1, "k"}, - {1, "l"}, {1, "m"}})); - + ASSERT_TRUE(score_members_match(&db, "GP9_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 10 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp10_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp10_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP10_ZREMRANGEBYLEX", gp10_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4160,17 +4571,15 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP10_ZREMRANGEBYLEX", 9)); - ASSERT_TRUE(score_members_match(&db, "GP10_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP10_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 11 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp11_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp11_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP11_ZREMRANGEBYLEX", gp11_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4179,17 +4588,15 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP11_ZREMRANGEBYLEX", 9)); - ASSERT_TRUE(score_members_match(&db, "GP11_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP11_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 12 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp12_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp12_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP12_ZREMRANGEBYLEX", gp12_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4198,17 +4605,15 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP12_ZREMRANGEBYLEX", 9)); - ASSERT_TRUE(score_members_match(&db, "GP12_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP12_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 13 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp13_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp13_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP13_ZREMRANGEBYLEX", gp13_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4219,13 +4624,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP13_ZREMRANGEBYLEX", 0)); ASSERT_TRUE(score_members_match(&db, "GP13_ZREMRANGEBYLEX", {})); - // ***************** Group 14 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp14_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp14_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP14_ZREMRANGEBYLEX", gp14_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4236,13 +4639,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP14_ZREMRANGEBYLEX", 0)); ASSERT_TRUE(score_members_match(&db, "GP14_ZREMRANGEBYLEX", {})); - // ***************** Group 15 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp15_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp15_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP15_ZREMRANGEBYLEX", gp15_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4253,13 +4654,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP15_ZREMRANGEBYLEX", 0)); ASSERT_TRUE(score_members_match(&db, "GP15_ZREMRANGEBYLEX", {})); - // ***************** Group 16 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp16_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp16_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP16_ZREMRANGEBYLEX", gp16_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4270,13 +4669,11 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(size_match(&db, "GP16_ZREMRANGEBYLEX", 0)); ASSERT_TRUE(score_members_match(&db, "GP16_ZREMRANGEBYLEX", {})); - // ***************** Group 17 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp17_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp17_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP17_ZREMRANGEBYLEX", gp17_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4285,16 +4682,13 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 5); ASSERT_TRUE(size_match(&db, "GP17_ZREMRANGEBYLEX", 4)); - ASSERT_TRUE(score_members_match(&db, "GP17_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}})); - + ASSERT_TRUE(score_members_match(&db, "GP17_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}})); // ***************** Group 18 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp18_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp18_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP18_ZREMRANGEBYLEX", gp18_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4303,16 +4697,13 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(size_match(&db, "GP18_ZREMRANGEBYLEX", 5)); - ASSERT_TRUE(score_members_match(&db, "GP18_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}})); - + ASSERT_TRUE(score_members_match(&db, "GP18_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}})); // ***************** Group 19 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp19_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp19_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP19_ZREMRANGEBYLEX", gp19_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4321,16 +4712,13 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 5); ASSERT_TRUE(size_match(&db, "GP19_ZREMRANGEBYLEX", 4)); - ASSERT_TRUE(score_members_match(&db, "GP19_ZREMRANGEBYLEX", {{1, "j"}, {1, "k"}, {1, "l"}, - {1, "m"}})); - + ASSERT_TRUE(score_members_match(&db, "GP19_ZREMRANGEBYLEX", {{1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 20 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp20_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp20_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP20_ZREMRANGEBYLEX", gp20_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4339,16 +4727,13 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 4); ASSERT_TRUE(size_match(&db, "GP20_ZREMRANGEBYLEX", 5)); - ASSERT_TRUE(score_members_match(&db, "GP20_ZREMRANGEBYLEX", {{1, "i"}, {1, "j"}, {1, "k"}, - {1, "l"}, {1, "m"}})); - + ASSERT_TRUE(score_members_match(&db, "GP20_ZREMRANGEBYLEX", {{1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 21 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp21_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp21_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP21_ZREMRANGEBYLEX", gp21_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4357,17 +4742,14 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); ASSERT_TRUE(size_match(&db, "GP21_ZREMRANGEBYLEX", 8)); - ASSERT_TRUE(score_members_match(&db, "GP21_ZREMRANGEBYLEX", {{1, "f"}, {1, "g"}, {1, "h"}, - {1, "i"}, {1, "j"}, {1, "k"}, - {1, "l"}, {1, "m"}})); - + ASSERT_TRUE(score_members_match(&db, "GP21_ZREMRANGEBYLEX", + {{1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 22 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp22_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp22_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP22_ZREMRANGEBYLEX", gp22_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4376,17 +4758,15 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP22_ZREMRANGEBYLEX", 9)); - ASSERT_TRUE(score_members_match(&db, "GP22_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP22_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 23 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp23_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp23_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP23_ZREMRANGEBYLEX", gp23_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4395,17 +4775,14 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 1); ASSERT_TRUE(size_match(&db, "GP23_ZREMRANGEBYLEX", 8)); - ASSERT_TRUE(score_members_match(&db, "GP23_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}})); - + ASSERT_TRUE(score_members_match(&db, "GP23_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}})); // ***************** Group 24 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} // - std::vector gp24_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp24_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP24_ZREMRANGEBYLEX", gp24_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4414,17 +4791,15 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 0); ASSERT_TRUE(size_match(&db, "GP24_ZREMRANGEBYLEX", 9)); - ASSERT_TRUE(score_members_match(&db, "GP24_ZREMRANGEBYLEX", {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}})); - + ASSERT_TRUE( + score_members_match(&db, "GP24_ZREMRANGEBYLEX", + {{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}})); // ***************** Group 25 Test ***************** // {1, e} {1, f} {1, g} {1, h} {1, i} {1, j} {1, k} {1, l} {1, m} (expire) // - std::vector gp25_sm {{1, "e"}, {1, "f"}, {1, "g"}, - {1, "h"}, {1, "i"}, {1, "j"}, - {1, "k"}, {1, "l"}, {1, "m"}}; + std::vector gp25_sm{{1, "e"}, {1, "f"}, {1, "g"}, {1, "h"}, {1, "i"}, + {1, "j"}, {1, "k"}, {1, "l"}, {1, "m"}}; s = db.ZAdd("GP25_ZREMRANGEBYLEX", gp25_sm, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4434,7 +4809,6 @@ TEST_F(ZSetsTest, ZRemrangebylexTest) { ASSERT_TRUE(s.IsNotFound()); ASSERT_EQ(ret, 0); - // ***************** Group 26 Test ***************** s = db.ZRemrangebylex("GP26_ZREMRANGEBYLEX", "-", "+", true, true, &ret); ASSERT_TRUE(s.IsNotFound()); @@ -4450,9 +4824,8 @@ TEST_F(ZSetsTest, ZScanTest) { // ***************** Group 1 Test ***************** // {0,a} {0,b} {0,c} {0,d} {0,e} {0,f} {0,g} {0,h} // 0 1 2 3 4 5 6 7 - std::vector gp1_score_member {{0, "a"}, {0, "b"}, {0, "c"}, - {0, "d"}, {0, "e"}, {0, "f"}, - {0, "g"}, {0, "h"}}; + std::vector gp1_score_member{{0, "a"}, {0, "b"}, {0, "c"}, {0, "d"}, + {0, "e"}, {0, "f"}, {0, "g"}, {0, "h"}}; s = db.ZAdd("GP1_ZSCAN_KEY", gp1_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP1_ZSCAN_KEY", 8)); @@ -4461,7 +4834,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 3); ASSERT_EQ(next_cursor, 3); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"a"}, {0,"b"}, {0, "c"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "a"}, {0, "b"}, {0, "c"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4469,7 +4842,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 3); ASSERT_EQ(next_cursor, 6); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"d"}, {0,"e"}, {0, "f"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "d"}, {0, "e"}, {0, "f"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4477,15 +4850,13 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 2); ASSERT_EQ(next_cursor, 0); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"g"}, {0,"h"}})); - + ASSERT_TRUE(score_members_match(score_member_out, {{0, "g"}, {0, "h"}})); // ***************** Group 2 Test ***************** // {0,a} {0,b} {0,c} {0,d} {0,e} {0,f} {0,g} {0,h} // 0 1 2 3 4 5 6 7 - std::vector gp2_score_member {{0, "a"}, {0, "b"}, {0, "c"}, - {0, "d"}, {0, "e"}, {0, "f"}, - {0, "g"}, {0, "h"}}; + std::vector gp2_score_member{{0, "a"}, {0, "b"}, {0, "c"}, {0, "d"}, + {0, "e"}, {0, "f"}, {0, "g"}, {0, "h"}}; s = db.ZAdd("GP2_ZSCAN_KEY", gp2_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP2_ZSCAN_KEY", 8)); @@ -4494,7 +4865,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 1); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"a"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "a"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4502,7 +4873,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 2); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"b"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "b"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4510,7 +4881,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 3); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"c"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "c"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4518,7 +4889,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 4); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"d"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "d"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4526,7 +4897,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 5); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"e"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "e"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4534,7 +4905,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 6); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"f"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "f"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4542,7 +4913,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 7); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"g"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "g"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4550,15 +4921,13 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 1); ASSERT_EQ(next_cursor, 0); - ASSERT_TRUE(score_members_match(score_member_out, {{0,"h"}})); - + ASSERT_TRUE(score_members_match(score_member_out, {{0, "h"}})); // ***************** Group 3 Test ***************** // {0,a} {0,b} {0,c} {0,d} {0,e} {0,f} {0,g} {0,h} // 0 1 2 3 4 5 6 7 - std::vector gp3_score_member {{0, "a"}, {0, "b"}, {0, "c"}, - {0, "d"}, {0, "e"}, {0, "f"}, - {0, "g"}, {0, "h"}}; + std::vector gp3_score_member{{0, "a"}, {0, "b"}, {0, "c"}, {0, "d"}, + {0, "e"}, {0, "f"}, {0, "g"}, {0, "h"}}; s = db.ZAdd("GP3_ZSCAN_KEY", gp3_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP3_ZSCAN_KEY", 8)); @@ -4569,8 +4938,7 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 5); ASSERT_EQ(next_cursor, 5); - ASSERT_TRUE(score_members_match(score_member_out, {{0, "a"}, {0, "b"}, {0, "c"}, - {0, "d"}, {0, "e"}})); + ASSERT_TRUE(score_members_match(score_member_out, {{0, "a"}, {0, "b"}, {0, "c"}, {0, "d"}, {0, "e"}})); score_member_out.clear(); cursor = next_cursor, next_cursor = 0; @@ -4580,13 +4948,11 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(score_members_match(score_member_out, {{0, "f"}, {0, "g"}, {0, "h"}})); - // ***************** Group 4 Test ***************** // {0,a} {0,b} {0,c} {0,d} {0,e} {0,f} {0,g} {0,h} // 0 1 2 3 4 5 6 7 - std::vector gp4_score_member {{0, "a"}, {0, "b"}, {0, "c"}, - {0, "d"}, {0, "e"}, {0, "f"}, - {0, "g"}, {0, "h"}}; + std::vector gp4_score_member{{0, "a"}, {0, "b"}, {0, "c"}, {0, "d"}, + {0, "e"}, {0, "f"}, {0, "g"}, {0, "h"}}; s = db.ZAdd("GP4_ZSCAN_KEY", gp4_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_TRUE(size_match(&db, "GP4_ZSCAN_KEY", 8)); @@ -4597,17 +4963,14 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(s.ok()); ASSERT_EQ(score_member_out.size(), 8); ASSERT_EQ(next_cursor, 0); - ASSERT_TRUE(score_members_match(score_member_out, {{0, "a"}, {0, "b"}, {0, "c"}, - {0, "d"}, {0, "e"}, {0, "f"}, - {0, "g"}, {0, "h"}})); - + ASSERT_TRUE(score_members_match(score_member_out, + {{0, "a"}, {0, "b"}, {0, "c"}, {0, "d"}, {0, "e"}, {0, "f"}, {0, "g"}, {0, "h"}})); // ***************** Group 5 Test ***************** // {0,a_1_} {0,a_2_} {0,a_3_} {0,b_1_} {0,b_2_} {0,b_3_} {0,c_1_} {0,c_2_} {0,c_3_} // 0 1 2 3 4 5 6 7 8 - std::vector gp5_score_member {{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, - {0, "b_1_"}, {0, "b_2_"}, {0, "b_3_"}, - {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; + std::vector gp5_score_member{{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, {0, "b_1_"}, {0, "b_2_"}, + {0, "b_3_"}, {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; s = db.ZAdd("GP5_ZSCAN_KEY", gp5_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4637,13 +5000,11 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(score_members_match(score_member_out, {{0, "c_1_"}})); - // ***************** Group 6 Test ***************** // {0,a_1_} {0,a_2_} {0,a_3_} {0,b_1_} {0,b_2_} {0,b_3_} {0,c_1_} {0,c_2_} {0,c_3_} // 0 1 2 3 4 5 6 7 8 - std::vector gp6_score_member {{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, - {0, "b_1_"}, {0, "b_2_"}, {0, "b_3_"}, - {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; + std::vector gp6_score_member{{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, {0, "b_1_"}, {0, "b_2_"}, + {0, "b_3_"}, {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; s = db.ZAdd("GP6_ZSCAN_KEY", gp6_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4697,14 +5058,11 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(score_members_match(score_member_out, {{0, "a_3_"}})); - - // ***************** Group 7 Test ***************** // {0,a_1_} {0,a_2_} {0,a_3_} {0,b_1_} {0,b_2_} {0,b_3_} {0,c_1_} {0,c_2_} {0,c_3_} // 0 1 2 3 4 5 6 7 8 - std::vector gp7_score_member {{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, - {0, "b_1_"}, {0, "b_2_"}, {0, "b_3_"}, - {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; + std::vector gp7_score_member{{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, {0, "b_1_"}, {0, "b_2_"}, + {0, "b_3_"}, {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; s = db.ZAdd("GP7_ZSCAN_KEY", gp7_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4758,14 +5116,11 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(score_members_match(score_member_out, {{0, "b_3_"}})); - - // ***************** Group 8 Test ***************** // {0,a_1_} {0,a_2_} {0,a_3_} {0,b_1_} {0,b_2_} {0,b_3_} {0,c_1_} {0,c_2_} {0,c_3_} // 0 1 2 3 4 5 6 7 8 - std::vector gp8_score_member {{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, - {0, "b_1_"}, {0, "b_2_"}, {0, "b_3_"}, - {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; + std::vector gp8_score_member{{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, {0, "b_1_"}, {0, "b_2_"}, + {0, "b_3_"}, {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; s = db.ZAdd("GP8_ZSCAN_KEY", gp8_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4819,13 +5174,11 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(score_members_match(score_member_out, {{0, "c_3_"}})); - // ***************** Group 9 Test ***************** // {0,a_1_} {0,a_2_} {0,a_3_} {0,b_1_} {0,b_2_} {0,b_3_} {0,c_1_} {0,c_2_} {0,c_3_} // 0 1 2 3 4 5 6 7 8 - std::vector gp9_score_member {{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, - {0, "b_1_"}, {0, "b_2_"}, {0, "b_3_"}, - {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; + std::vector gp9_score_member{{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, {0, "b_1_"}, {0, "b_2_"}, + {0, "b_3_"}, {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; s = db.ZAdd("GP9_ZSCAN_KEY", gp9_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4839,13 +5192,11 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(score_members_match(score_member_out, {})); - // ***************** Group 10 Test ***************** // {0,a_1_} {0,a_2_} {0,a_3_} {0,b_1_} {0,b_2_} {0,b_3_} {0,c_1_} {0,c_2_} {0,c_3_} // 0 1 2 3 4 5 6 7 8 - std::vector gp10_score_member {{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, - {0, "b_1_"}, {0, "b_2_"}, {0, "b_3_"}, - {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; + std::vector gp10_score_member{{0, "a_1_"}, {0, "a_2_"}, {0, "a_3_"}, {0, "b_1_"}, {0, "b_2_"}, + {0, "b_3_"}, {0, "c_1_"}, {0, "c_2_"}, {0, "c_3_"}}; s = db.ZAdd("GP10_ZSCAN_KEY", gp10_score_member, &ret); ASSERT_TRUE(s.ok()); ASSERT_EQ(ret, 9); @@ -4860,7 +5211,6 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_EQ(next_cursor, 0); ASSERT_TRUE(score_members_match(score_member_out, {})); - // ***************** Group 11 Test ***************** // ZScan Not Exist Key score_member_out.clear(); @@ -4872,7 +5222,6 @@ TEST_F(ZSetsTest, ZScanTest) { ASSERT_TRUE(score_members_match(score_member_out, {})); } - int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS();