diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..33bf2a3b9 --- /dev/null +++ b/.clang-format @@ -0,0 +1,137 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveMacros: false +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: true +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + - Regex: '.*' + Priority: 1 + SortPriority: 0 +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentCaseLabels: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +Standard: Latest +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseCRLF: false +UseTab: Never +... + diff --git a/.gitignore b/.gitignore index 67e45bd1e..8fccd3208 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ *.swp bazel-* compile_commands.json +build +.vscode +tmp \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 6071a4ec8..5c2f51b33 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.6) +cmake_minimum_required(VERSION 3.0) project(muduo C CXX) diff --git a/muduo/base/AsyncLogging.cc b/muduo/base/AsyncLogging.cc index 0f82444d0..e18b734c2 100644 --- a/muduo/base/AsyncLogging.cc +++ b/muduo/base/AsyncLogging.cc @@ -11,43 +11,28 @@ using namespace muduo; -AsyncLogging::AsyncLogging(const string& basename, - off_t rollSize, +AsyncLogging::AsyncLogging(const string &basename, off_t rollSize, int flushInterval) - : flushInterval_(flushInterval), - running_(false), - basename_(basename), - rollSize_(rollSize), - thread_(std::bind(&AsyncLogging::threadFunc, this), "Logging"), - latch_(1), - mutex_(), - cond_(mutex_), - currentBuffer_(new Buffer), - nextBuffer_(new Buffer), - buffers_() -{ + : flushInterval_(flushInterval), running_(false), basename_(basename), + rollSize_(rollSize), + thread_(std::bind(&AsyncLogging::threadFunc, this), "Logging"), latch_(1), + mutex_(), cond_(mutex_), currentBuffer_(new Buffer), + nextBuffer_(new Buffer), buffers_() { currentBuffer_->bzero(); nextBuffer_->bzero(); buffers_.reserve(16); } -void AsyncLogging::append(const char* logline, int len) -{ +void AsyncLogging::append(const char *logline, int len) { muduo::MutexLockGuard lock(mutex_); - if (currentBuffer_->avail() > len) - { + if (currentBuffer_->avail() > len) { currentBuffer_->append(logline, len); - } - else - { + } else { buffers_.push_back(std::move(currentBuffer_)); - if (nextBuffer_) - { + if (nextBuffer_) { currentBuffer_ = std::move(nextBuffer_); - } - else - { + } else { currentBuffer_.reset(new Buffer); // Rarely happens } currentBuffer_->append(logline, len); @@ -55,8 +40,7 @@ void AsyncLogging::append(const char* logline, int len) } } -void AsyncLogging::threadFunc() -{ +void AsyncLogging::threadFunc() { assert(running_ == true); latch_.countDown(); LogFile output(basename_, rollSize_, false); @@ -66,62 +50,56 @@ void AsyncLogging::threadFunc() newBuffer2->bzero(); BufferVector buffersToWrite; buffersToWrite.reserve(16); - while (running_) - { + while (running_) { assert(newBuffer1 && newBuffer1->length() == 0); assert(newBuffer2 && newBuffer2->length() == 0); assert(buffersToWrite.empty()); { muduo::MutexLockGuard lock(mutex_); - if (buffers_.empty()) // unusual usage! + if (buffers_.empty()) // unusual usage! { cond_.waitForSeconds(flushInterval_); } buffers_.push_back(std::move(currentBuffer_)); currentBuffer_ = std::move(newBuffer1); buffersToWrite.swap(buffers_); - if (!nextBuffer_) - { + if (!nextBuffer_) { nextBuffer_ = std::move(newBuffer2); } } assert(!buffersToWrite.empty()); - if (buffersToWrite.size() > 25) - { + if (buffersToWrite.size() > 25) { char buf[256]; - snprintf(buf, sizeof buf, "Dropped log messages at %s, %zd larger buffers\n", + snprintf(buf, sizeof buf, + "Dropped log messages at %s, %zd larger buffers\n", Timestamp::now().toFormattedString().c_str(), - buffersToWrite.size()-2); + buffersToWrite.size() - 2); fputs(buf, stderr); output.append(buf, static_cast(strlen(buf))); - buffersToWrite.erase(buffersToWrite.begin()+2, buffersToWrite.end()); + buffersToWrite.erase(buffersToWrite.begin() + 2, buffersToWrite.end()); } - for (const auto& buffer : buffersToWrite) - { + for (const auto &buffer : buffersToWrite) { // FIXME: use unbuffered stdio FILE ? or use ::writev ? output.append(buffer->data(), buffer->length()); } - if (buffersToWrite.size() > 2) - { + if (buffersToWrite.size() > 2) { // drop non-bzero-ed buffers, avoid trashing buffersToWrite.resize(2); } - if (!newBuffer1) - { + if (!newBuffer1) { assert(!buffersToWrite.empty()); newBuffer1 = std::move(buffersToWrite.back()); buffersToWrite.pop_back(); newBuffer1->reset(); } - if (!newBuffer2) - { + if (!newBuffer2) { assert(!buffersToWrite.empty()); newBuffer2 = std::move(buffersToWrite.back()); buffersToWrite.pop_back(); @@ -133,4 +111,3 @@ void AsyncLogging::threadFunc() } output.flush(); } - diff --git a/muduo/base/AsyncLogging.h b/muduo/base/AsyncLogging.h index 46e77dd9f..a2603de6c 100644 --- a/muduo/base/AsyncLogging.h +++ b/muduo/base/AsyncLogging.h @@ -9,50 +9,40 @@ #include "muduo/base/BlockingQueue.h" #include "muduo/base/BoundedBlockingQueue.h" #include "muduo/base/CountDownLatch.h" +#include "muduo/base/LogStream.h" #include "muduo/base/Mutex.h" #include "muduo/base/Thread.h" -#include "muduo/base/LogStream.h" #include #include -namespace muduo -{ +namespace muduo { -class AsyncLogging : noncopyable -{ - public: +class AsyncLogging : noncopyable { +public: + AsyncLogging(const string &basename, off_t rollSize, int flushInterval = 3); - AsyncLogging(const string& basename, - off_t rollSize, - int flushInterval = 3); - - ~AsyncLogging() - { - if (running_) - { + ~AsyncLogging() { + if (running_) { stop(); } } - void append(const char* logline, int len); + void append(const char *logline, int len); - void start() - { + void start() { running_ = true; thread_.start(); latch_.wait(); } - void stop() NO_THREAD_SAFETY_ANALYSIS - { + void stop() NO_THREAD_SAFETY_ANALYSIS { running_ = false; cond_.notify(); thread_.join(); } - private: - +private: void threadFunc(); typedef muduo::detail::FixedBuffer Buffer; @@ -72,6 +62,6 @@ class AsyncLogging : noncopyable BufferVector buffers_ GUARDED_BY(mutex_); }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_ASYNCLOGGING_H +#endif // MUDUO_BASE_ASYNCLOGGING_H diff --git a/muduo/base/Atomic.h b/muduo/base/Atomic.h index 6158fac08..dc4ee3f1e 100644 --- a/muduo/base/Atomic.h +++ b/muduo/base/Atomic.h @@ -10,19 +10,12 @@ #include -namespace muduo -{ - -namespace detail -{ -template -class AtomicIntegerT : noncopyable -{ - public: - AtomicIntegerT() - : value_(0) - { - } +namespace muduo { + +namespace detail { +template class AtomicIntegerT : noncopyable { +public: + AtomicIntegerT() : value_(0) {} // uncomment if you need copying and assignment // @@ -36,62 +29,42 @@ class AtomicIntegerT : noncopyable // return *this; // } - T get() - { + T get() { // in gcc >= 4.7: __atomic_load_n(&value_, __ATOMIC_SEQ_CST) return __sync_val_compare_and_swap(&value_, 0, 0); } - T getAndAdd(T x) - { + T getAndAdd(T x) { // in gcc >= 4.7: __atomic_fetch_add(&value_, x, __ATOMIC_SEQ_CST) return __sync_fetch_and_add(&value_, x); } - T addAndGet(T x) - { - return getAndAdd(x) + x; - } + T addAndGet(T x) { return getAndAdd(x) + x; } - T incrementAndGet() - { - return addAndGet(1); - } + T incrementAndGet() { return addAndGet(1); } - T decrementAndGet() - { - return addAndGet(-1); - } + T decrementAndGet() { return addAndGet(-1); } - void add(T x) - { - getAndAdd(x); - } + void add(T x) { getAndAdd(x); } - void increment() - { - incrementAndGet(); - } + void increment() { incrementAndGet(); } - void decrement() - { - decrementAndGet(); - } + void decrement() { decrementAndGet(); } - T getAndSet(T newValue) - { - // in gcc >= 4.7: __atomic_exchange_n(&value_, newValue, __ATOMIC_SEQ_CST) + T getAndSet(T newValue) { + // in gcc >= 4.7: __atomic_exchange_n(&value_, newValue, + // __ATOMIC_SEQ_CST) return __sync_lock_test_and_set(&value_, newValue); } - private: +private: volatile T value_; }; -} // namespace detail +} // namespace detail typedef detail::AtomicIntegerT AtomicInt32; typedef detail::AtomicIntegerT AtomicInt64; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_ATOMIC_H +#endif // MUDUO_BASE_ATOMIC_H diff --git a/muduo/base/BlockingQueue.h b/muduo/base/BlockingQueue.h index adf92bcd4..8bf2534e3 100644 --- a/muduo/base/BlockingQueue.h +++ b/muduo/base/BlockingQueue.h @@ -9,46 +9,34 @@ #include "muduo/base/Condition.h" #include "muduo/base/Mutex.h" -#include #include +#include -namespace muduo -{ +namespace muduo { -template -class BlockingQueue : noncopyable -{ - public: +template class BlockingQueue : noncopyable { +public: using queue_type = std::deque; - BlockingQueue() - : mutex_(), - notEmpty_(mutex_), - queue_() - { - } + BlockingQueue() : mutex_(), notEmpty_(mutex_), queue_() {} - void put(const T& x) - { + void put(const T &x) { MutexLockGuard lock(mutex_); queue_.push_back(x); notEmpty_.notify(); // wait morphing saves us // http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/ } - void put(T&& x) - { + void put(T &&x) { MutexLockGuard lock(mutex_); queue_.push_back(std::move(x)); notEmpty_.notify(); } - T take() - { + T take() { MutexLockGuard lock(mutex_); // always use a while-loop, due to spurious wakeup - while (queue_.empty()) - { + while (queue_.empty()) { notEmpty_.wait(); } assert(!queue_.empty()); @@ -57,8 +45,7 @@ class BlockingQueue : noncopyable return front; } - queue_type drain() - { + queue_type drain() { std::deque queue; { MutexLockGuard lock(mutex_); @@ -68,18 +55,17 @@ class BlockingQueue : noncopyable return queue; } - size_t size() const - { + size_t size() const { MutexLockGuard lock(mutex_); return queue_.size(); } - private: +private: mutable MutexLock mutex_; - Condition notEmpty_ GUARDED_BY(mutex_); - queue_type queue_ GUARDED_BY(mutex_); -}; // __attribute__ ((aligned (64))); + Condition notEmpty_ GUARDED_BY(mutex_); + queue_type queue_ GUARDED_BY(mutex_); +}; // __attribute__ ((aligned (64))); -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_BLOCKINGQUEUE_H +#endif // MUDUO_BASE_BLOCKINGQUEUE_H diff --git a/muduo/base/BoundedBlockingQueue.h b/muduo/base/BoundedBlockingQueue.h index cfb4d3bae..18ce49c25 100644 --- a/muduo/base/BoundedBlockingQueue.h +++ b/muduo/base/BoundedBlockingQueue.h @@ -9,29 +9,19 @@ #include "muduo/base/Condition.h" #include "muduo/base/Mutex.h" -#include #include +#include -namespace muduo -{ +namespace muduo { -template -class BoundedBlockingQueue : noncopyable -{ - public: +template class BoundedBlockingQueue : noncopyable { +public: explicit BoundedBlockingQueue(int maxSize) - : mutex_(), - notEmpty_(mutex_), - notFull_(mutex_), - queue_(maxSize) - { - } + : mutex_(), notEmpty_(mutex_), notFull_(mutex_), queue_(maxSize) {} - void put(const T& x) - { + void put(const T &x) { MutexLockGuard lock(mutex_); - while (queue_.full()) - { + while (queue_.full()) { notFull_.wait(); } assert(!queue_.full()); @@ -39,11 +29,9 @@ class BoundedBlockingQueue : noncopyable notEmpty_.notify(); } - void put(T&& x) - { + void put(T &&x) { MutexLockGuard lock(mutex_); - while (queue_.full()) - { + while (queue_.full()) { notFull_.wait(); } assert(!queue_.full()); @@ -51,11 +39,9 @@ class BoundedBlockingQueue : noncopyable notEmpty_.notify(); } - T take() - { + T take() { MutexLockGuard lock(mutex_); - while (queue_.empty()) - { + while (queue_.empty()) { notEmpty_.wait(); } assert(!queue_.empty()); @@ -65,37 +51,33 @@ class BoundedBlockingQueue : noncopyable return front; } - bool empty() const - { + bool empty() const { MutexLockGuard lock(mutex_); return queue_.empty(); } - bool full() const - { + bool full() const { MutexLockGuard lock(mutex_); return queue_.full(); } - size_t size() const - { + size_t size() const { MutexLockGuard lock(mutex_); return queue_.size(); } - size_t capacity() const - { + size_t capacity() const { MutexLockGuard lock(mutex_); return queue_.capacity(); } - private: - mutable MutexLock mutex_; - Condition notEmpty_ GUARDED_BY(mutex_); - Condition notFull_ GUARDED_BY(mutex_); - boost::circular_buffer queue_ GUARDED_BY(mutex_); +private: + mutable MutexLock mutex_; + Condition notEmpty_ GUARDED_BY(mutex_); + Condition notFull_ GUARDED_BY(mutex_); + boost::circular_buffer queue_ GUARDED_BY(mutex_); }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H +#endif // MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H diff --git a/muduo/base/Condition.cc b/muduo/base/Condition.cc index 47e9d23a9..846ae2e84 100644 --- a/muduo/base/Condition.cc +++ b/muduo/base/Condition.cc @@ -8,8 +8,7 @@ #include // returns true if time out, false otherwise. -bool muduo::Condition::waitForSeconds(double seconds) -{ +bool muduo::Condition::waitForSeconds(double seconds) { struct timespec abstime; // FIXME: use CLOCK_MONOTONIC or CLOCK_MONOTONIC_RAW to prevent time rewind. clock_gettime(CLOCK_REALTIME, &abstime); @@ -17,10 +16,12 @@ bool muduo::Condition::waitForSeconds(double seconds) const int64_t kNanoSecondsPerSecond = 1000000000; int64_t nanoseconds = static_cast(seconds * kNanoSecondsPerSecond); - abstime.tv_sec += static_cast((abstime.tv_nsec + nanoseconds) / kNanoSecondsPerSecond); - abstime.tv_nsec = static_cast((abstime.tv_nsec + nanoseconds) % kNanoSecondsPerSecond); + abstime.tv_sec += static_cast((abstime.tv_nsec + nanoseconds) / + kNanoSecondsPerSecond); + abstime.tv_nsec = static_cast((abstime.tv_nsec + nanoseconds) % + kNanoSecondsPerSecond); MutexLock::UnassignGuard ug(mutex_); - return ETIMEDOUT == pthread_cond_timedwait(&pcond_, mutex_.getPthreadMutex(), &abstime); + return ETIMEDOUT == + pthread_cond_timedwait(&pcond_, mutex_.getPthreadMutex(), &abstime); } - diff --git a/muduo/base/Condition.h b/muduo/base/Condition.h index 0181550b7..13acfb00a 100644 --- a/muduo/base/Condition.h +++ b/muduo/base/Condition.h @@ -10,25 +10,17 @@ #include -namespace muduo -{ - -class Condition : noncopyable -{ - public: - explicit Condition(MutexLock& mutex) - : mutex_(mutex) - { +namespace muduo { + +class Condition : noncopyable { +public: + explicit Condition(MutexLock &mutex) : mutex_(mutex) { MCHECK(pthread_cond_init(&pcond_, NULL)); } - ~Condition() - { - MCHECK(pthread_cond_destroy(&pcond_)); - } + ~Condition() { MCHECK(pthread_cond_destroy(&pcond_)); } - void wait() - { + void wait() { MutexLock::UnassignGuard ug(mutex_); MCHECK(pthread_cond_wait(&pcond_, mutex_.getPthreadMutex())); } @@ -36,21 +28,15 @@ class Condition : noncopyable // returns true if time out, false otherwise. bool waitForSeconds(double seconds); - void notify() - { - MCHECK(pthread_cond_signal(&pcond_)); - } + void notify() { MCHECK(pthread_cond_signal(&pcond_)); } - void notifyAll() - { - MCHECK(pthread_cond_broadcast(&pcond_)); - } + void notifyAll() { MCHECK(pthread_cond_broadcast(&pcond_)); } - private: - MutexLock& mutex_; +private: + MutexLock &mutex_; pthread_cond_t pcond_; }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_CONDITION_H +#endif // MUDUO_BASE_CONDITION_H diff --git a/muduo/base/CountDownLatch.cc b/muduo/base/CountDownLatch.cc index 72d26cced..db2b963b6 100644 --- a/muduo/base/CountDownLatch.cc +++ b/muduo/base/CountDownLatch.cc @@ -8,34 +8,24 @@ using namespace muduo; CountDownLatch::CountDownLatch(int count) - : mutex_(), - condition_(mutex_), - count_(count) -{ -} + : mutex_(), condition_(mutex_), count_(count) {} -void CountDownLatch::wait() -{ +void CountDownLatch::wait() { MutexLockGuard lock(mutex_); - while (count_ > 0) - { + while (count_ > 0) { condition_.wait(); } } -void CountDownLatch::countDown() -{ +void CountDownLatch::countDown() { MutexLockGuard lock(mutex_); --count_; - if (count_ == 0) - { + if (count_ == 0) { condition_.notifyAll(); } } -int CountDownLatch::getCount() const -{ +int CountDownLatch::getCount() const { MutexLockGuard lock(mutex_); return count_; } - diff --git a/muduo/base/CountDownLatch.h b/muduo/base/CountDownLatch.h index 9919aeff0..add7121c3 100644 --- a/muduo/base/CountDownLatch.h +++ b/muduo/base/CountDownLatch.h @@ -9,13 +9,10 @@ #include "muduo/base/Condition.h" #include "muduo/base/Mutex.h" -namespace muduo -{ - -class CountDownLatch : noncopyable -{ - public: +namespace muduo { +class CountDownLatch : noncopyable { +public: explicit CountDownLatch(int count); void wait(); @@ -24,11 +21,11 @@ class CountDownLatch : noncopyable int getCount() const; - private: +private: mutable MutexLock mutex_; Condition condition_ GUARDED_BY(mutex_); int count_ GUARDED_BY(mutex_); }; -} // namespace muduo -#endif // MUDUO_BASE_COUNTDOWNLATCH_H +} // namespace muduo +#endif // MUDUO_BASE_COUNTDOWNLATCH_H diff --git a/muduo/base/CurrentThread.cc b/muduo/base/CurrentThread.cc index 15edff0b5..01b71929a 100644 --- a/muduo/base/CurrentThread.cc +++ b/muduo/base/CurrentThread.cc @@ -9,53 +9,46 @@ #include #include -namespace muduo -{ -namespace CurrentThread -{ +namespace muduo { +namespace CurrentThread { __thread int t_cachedTid = 0; __thread char t_tidString[32]; __thread int t_tidStringLength = 6; -__thread const char* t_threadName = "unknown"; +__thread const char *t_threadName = "unknown"; static_assert(std::is_same::value, "pid_t should be int"); -string stackTrace(bool demangle) -{ +string stackTrace(bool demangle) { string stack; const int max_frames = 200; - void* frame[max_frames]; + void *frame[max_frames]; int nptrs = ::backtrace(frame, max_frames); - char** strings = ::backtrace_symbols(frame, nptrs); - if (strings) - { + char **strings = ::backtrace_symbols(frame, nptrs); + if (strings) { size_t len = 256; - char* demangled = demangle ? static_cast(::malloc(len)) : nullptr; - for (int i = 1; i < nptrs; ++i) // skipping the 0-th, which is this function + char *demangled = demangle ? static_cast(::malloc(len)) : nullptr; + for (int i = 1; i < nptrs; ++i) // skipping the 0-th, which is this function { - if (demangle) - { + if (demangle) { // https://panthema.net/2008/0901-stacktrace-demangled/ // bin/exception_test(_ZN3Bar4testEv+0x79) [0x401909] - char* left_par = nullptr; - char* plus = nullptr; - for (char* p = strings[i]; *p; ++p) - { + char *left_par = nullptr; + char *plus = nullptr; + for (char *p = strings[i]; *p; ++p) { if (*p == '(') left_par = p; else if (*p == '+') plus = p; } - if (left_par && plus) - { + if (left_par && plus) { *plus = '\0'; int status = 0; - char* ret = abi::__cxa_demangle(left_par+1, demangled, &len, &status); + char *ret = + abi::__cxa_demangle(left_par + 1, demangled, &len, &status); *plus = '+'; - if (status == 0) - { - demangled = ret; // ret could be realloc() - stack.append(strings[i], left_par+1); + if (status == 0) { + demangled = ret; // ret could be realloc() + stack.append(strings[i], left_par + 1); stack.append(demangled); stack.append(plus); stack.push_back('\n'); @@ -73,5 +66,5 @@ string stackTrace(bool demangle) return stack; } -} // namespace CurrentThread -} // namespace muduo +} // namespace CurrentThread +} // namespace muduo diff --git a/muduo/base/CurrentThread.h b/muduo/base/CurrentThread.h index 33fd8c0ae..193e8707d 100644 --- a/muduo/base/CurrentThread.h +++ b/muduo/base/CurrentThread.h @@ -8,47 +8,40 @@ #include "muduo/base/Types.h" -namespace muduo -{ -namespace CurrentThread -{ - // internal - extern __thread int t_cachedTid; - extern __thread char t_tidString[32]; - extern __thread int t_tidStringLength; - extern __thread const char* t_threadName; - void cacheTid(); - - inline int tid() - { - if (__builtin_expect(t_cachedTid == 0, 0)) - { - cacheTid(); - } - return t_cachedTid; +namespace muduo { +namespace CurrentThread { +// internal +extern __thread int t_cachedTid; +extern __thread char t_tidString[32]; +extern __thread int t_tidStringLength; +extern __thread const char *t_threadName; +void cacheTid(); + +inline int tid() { + if (__builtin_expect(t_cachedTid == 0, 0)) { + cacheTid(); } + return t_cachedTid; +} - inline const char* tidString() // for logging - { - return t_tidString; - } +inline const char *tidString() // for logging +{ + return t_tidString; +} - inline int tidStringLength() // for logging - { - return t_tidStringLength; - } +inline int tidStringLength() // for logging +{ + return t_tidStringLength; +} - inline const char* name() - { - return t_threadName; - } +inline const char *name() { return t_threadName; } - bool isMainThread(); +bool isMainThread(); - void sleepUsec(int64_t usec); // for testing +void sleepUsec(int64_t usec); // for testing - string stackTrace(bool demangle); -} // namespace CurrentThread -} // namespace muduo +string stackTrace(bool demangle); +} // namespace CurrentThread +} // namespace muduo -#endif // MUDUO_BASE_CURRENTTHREAD_H +#endif // MUDUO_BASE_CURRENTTHREAD_H diff --git a/muduo/base/Date.cc b/muduo/base/Date.cc index 86b60715d..317104944 100644 --- a/muduo/base/Date.cc +++ b/muduo/base/Date.cc @@ -4,13 +4,11 @@ // Author: Shuo Chen (chenshuo at chenshuo dot com) #include "muduo/base/Date.h" -#include // snprintf +#include // snprintf #include // struct tm -namespace muduo -{ -namespace detail -{ +namespace muduo { +namespace detail { char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1]; @@ -18,17 +16,15 @@ char require_32_bit_integer_at_least[sizeof(int) >= sizeof(int32_t) ? 1 : -1]; // http://www.faqs.org/faqs/calendars/faq/part2/ // http://blog.csdn.net/Solstice -int getJulianDayNumber(int year, int month, int day) -{ - (void) require_32_bit_integer_at_least; // no warning please +int getJulianDayNumber(int year, int month, int day) { + (void)require_32_bit_integer_at_least; // no warning please int a = (14 - month) / 12; int y = year + 4800 - a; int m = month + 12 * a - 3; - return day + (153*m + 2) / 5 + y*365 + y/4 - y/100 + y/400 - 32045; + return day + (153 * m + 2) / 5 + y * 365 + y / 4 - y / 100 + y / 400 - 32045; } -struct Date::YearMonthDay getYearMonthDay(int julianDayNumber) -{ +struct Date::YearMonthDay getYearMonthDay(int julianDayNumber) { int a = julianDayNumber + 32044; int b = (4 * a + 3) / 146097; int c = a - ((b * 146097) / 4); @@ -41,36 +37,27 @@ struct Date::YearMonthDay getYearMonthDay(int julianDayNumber) ymd.year = b * 100 + d - 4800 + (m / 10); return ymd; } -} // namespace detail +} // namespace detail const int Date::kJulianDayOf1970_01_01 = detail::getJulianDayNumber(1970, 1, 1); -} // namespace muduo +} // namespace muduo using namespace muduo; using namespace muduo::detail; Date::Date(int y, int m, int d) - : julianDayNumber_(getJulianDayNumber(y, m, d)) -{ -} + : julianDayNumber_(getJulianDayNumber(y, m, d)) {} -Date::Date(const struct tm& t) - : julianDayNumber_(getJulianDayNumber( - t.tm_year+1900, - t.tm_mon+1, - t.tm_mday)) -{ -} +Date::Date(const struct tm &t) + : julianDayNumber_( + getJulianDayNumber(t.tm_year + 1900, t.tm_mon + 1, t.tm_mday)) {} -string Date::toIsoString() const -{ +string Date::toIsoString() const { char buf[32]; YearMonthDay ymd(yearMonthDay()); snprintf(buf, sizeof buf, "%4d-%02d-%02d", ymd.year, ymd.month, ymd.day); return buf; } -Date::YearMonthDay Date::yearMonthDay() const -{ +Date::YearMonthDay Date::yearMonthDay() const { return getYearMonthDay(julianDayNumber_); } - diff --git a/muduo/base/Date.h b/muduo/base/Date.h index 2e27b19cd..3dd6eb65b 100644 --- a/muduo/base/Date.h +++ b/muduo/base/Date.h @@ -6,13 +6,12 @@ #ifndef MUDUO_BASE_DATE_H #define MUDUO_BASE_DATE_H -#include "muduo/base/copyable.h" #include "muduo/base/Types.h" +#include "muduo/base/copyable.h" struct tm; -namespace muduo -{ +namespace muduo { /// /// Date in Gregorian calendar. @@ -21,16 +20,14 @@ namespace muduo /// It's recommended to pass it by value, since it's passed in register on x64. /// class Date : public muduo::copyable - // public boost::less_than_comparable, - // public boost::equality_comparable +// public boost::less_than_comparable, +// public boost::equality_comparable { - public: - - struct YearMonthDay - { - int year; // [1900..2500] - int month; // [1..12] - int day; // [1..31] +public: + struct YearMonthDay { + int year; // [1900..2500] + int month; // [1..12] + int day; // [1..31] }; static const int kDaysPerWeek = 7; @@ -39,9 +36,7 @@ class Date : public muduo::copyable /// /// Constucts an invalid Date. /// - Date() - : julianDayNumber_(0) - {} + Date() : julianDayNumber_(0) {} /// /// Constucts a yyyy-mm-dd Date. @@ -52,21 +47,16 @@ class Date : public muduo::copyable /// /// Constucts a Date from Julian Day Number. /// - explicit Date(int julianDayNum) - : julianDayNumber_(julianDayNum) - {} + explicit Date(int julianDayNum) : julianDayNumber_(julianDayNum) {} /// /// Constucts a Date from struct tm /// - explicit Date(const struct tm&); + explicit Date(const struct tm &); // default copy/assignment/dtor are Okay - void swap(Date& that) - { - std::swap(julianDayNumber_, that.julianDayNumber_); - } + void swap(Date &that) { std::swap(julianDayNumber_, that.julianDayNumber_); } bool valid() const { return julianDayNumber_ > 0; } @@ -77,43 +67,29 @@ class Date : public muduo::copyable struct YearMonthDay yearMonthDay() const; - int year() const - { - return yearMonthDay().year; - } + int year() const { return yearMonthDay().year; } - int month() const - { - return yearMonthDay().month; - } + int month() const { return yearMonthDay().month; } - int day() const - { - return yearMonthDay().day; - } + int day() const { return yearMonthDay().day; } // [0, 1, ..., 6] => [Sunday, Monday, ..., Saturday ] - int weekDay() const - { - return (julianDayNumber_+1) % kDaysPerWeek; - } + int weekDay() const { return (julianDayNumber_ + 1) % kDaysPerWeek; } int julianDayNumber() const { return julianDayNumber_; } - private: +private: int julianDayNumber_; }; -inline bool operator<(Date x, Date y) -{ +inline bool operator<(Date x, Date y) { return x.julianDayNumber() < y.julianDayNumber(); } -inline bool operator==(Date x, Date y) -{ +inline bool operator==(Date x, Date y) { return x.julianDayNumber() == y.julianDayNumber(); } -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_DATE_H +#endif // MUDUO_BASE_DATE_H diff --git a/muduo/base/Exception.cc b/muduo/base/Exception.cc index 6e2afbe8c..933f3154e 100644 --- a/muduo/base/Exception.cc +++ b/muduo/base/Exception.cc @@ -6,13 +6,10 @@ #include "muduo/base/Exception.h" #include "muduo/base/CurrentThread.h" -namespace muduo -{ +namespace muduo { Exception::Exception(string msg) - : message_(std::move(msg)), - stack_(CurrentThread::stackTrace(/*demangle=*/false)) -{ -} + : message_(std::move(msg)), + stack_(CurrentThread::stackTrace(/*demangle=*/false)) {} -} // namespace muduo +} // namespace muduo diff --git a/muduo/base/Exception.h b/muduo/base/Exception.h index 2a7462213..d408ee590 100644 --- a/muduo/base/Exception.h +++ b/muduo/base/Exception.h @@ -9,32 +9,24 @@ #include "muduo/base/Types.h" #include -namespace muduo -{ +namespace muduo { -class Exception : public std::exception -{ - public: +class Exception : public std::exception { +public: Exception(string what); ~Exception() noexcept override = default; // default copy-ctor and operator= are okay. - const char* what() const noexcept override - { - return message_.c_str(); - } + const char *what() const noexcept override { return message_.c_str(); } - const char* stackTrace() const noexcept - { - return stack_.c_str(); - } + const char *stackTrace() const noexcept { return stack_.c_str(); } - private: +private: string message_; string stack_; }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_EXCEPTION_H +#endif // MUDUO_BASE_EXCEPTION_H diff --git a/muduo/base/FileUtil.cc b/muduo/base/FileUtil.cc index 2f7c24b15..875c896f0 100644 --- a/muduo/base/FileUtil.cc +++ b/muduo/base/FileUtil.cc @@ -16,32 +16,24 @@ using namespace muduo; FileUtil::AppendFile::AppendFile(StringArg filename) - : fp_(::fopen(filename.c_str(), "ae")), // 'e' for O_CLOEXEC - writtenBytes_(0) -{ + : fp_(::fopen(filename.c_str(), "ae")), // 'e' for O_CLOEXEC + writtenBytes_(0) { assert(fp_); ::setbuffer(fp_, buffer_, sizeof buffer_); // posix_fadvise POSIX_FADV_DONTNEED ? } -FileUtil::AppendFile::~AppendFile() -{ - ::fclose(fp_); -} +FileUtil::AppendFile::~AppendFile() { ::fclose(fp_); } -void FileUtil::AppendFile::append(const char* logline, const size_t len) -{ +void FileUtil::AppendFile::append(const char *logline, const size_t len) { size_t written = 0; - while (written != len) - { + while (written != len) { size_t remain = len - written; size_t n = write(logline + written, remain); - if (n != remain) - { + if (n != remain) { int err = ferror(fp_); - if (err) - { + if (err) { fprintf(stderr, "AppendFile::append() failed %s\n", strerror_tl(err)); break; } @@ -52,92 +44,68 @@ void FileUtil::AppendFile::append(const char* logline, const size_t len) writtenBytes_ += written; } -void FileUtil::AppendFile::flush() -{ - ::fflush(fp_); -} +void FileUtil::AppendFile::flush() { ::fflush(fp_); } -size_t FileUtil::AppendFile::write(const char* logline, size_t len) -{ +size_t FileUtil::AppendFile::write(const char *logline, size_t len) { // #undef fwrite_unlocked return ::fwrite_unlocked(logline, 1, len, fp_); } FileUtil::ReadSmallFile::ReadSmallFile(StringArg filename) - : fd_(::open(filename.c_str(), O_RDONLY | O_CLOEXEC)), - err_(0) -{ + : fd_(::open(filename.c_str(), O_RDONLY | O_CLOEXEC)), err_(0) { buf_[0] = '\0'; - if (fd_ < 0) - { + if (fd_ < 0) { err_ = errno; } } -FileUtil::ReadSmallFile::~ReadSmallFile() -{ - if (fd_ >= 0) - { +FileUtil::ReadSmallFile::~ReadSmallFile() { + if (fd_ >= 0) { ::close(fd_); // FIXME: check EINTR } } // return errno -template -int FileUtil::ReadSmallFile::readToString(int maxSize, - String* content, - int64_t* fileSize, - int64_t* modifyTime, - int64_t* createTime) -{ +template +int FileUtil::ReadSmallFile::readToString(int maxSize, String *content, + int64_t *fileSize, + int64_t *modifyTime, + int64_t *createTime) { static_assert(sizeof(off_t) == 8, "_FILE_OFFSET_BITS = 64"); assert(content != NULL); int err = err_; - if (fd_ >= 0) - { + if (fd_ >= 0) { content->clear(); - if (fileSize) - { + if (fileSize) { struct stat statbuf; - if (::fstat(fd_, &statbuf) == 0) - { - if (S_ISREG(statbuf.st_mode)) - { + if (::fstat(fd_, &statbuf) == 0) { + if (S_ISREG(statbuf.st_mode)) { *fileSize = statbuf.st_size; - content->reserve(static_cast(std::min(implicit_cast(maxSize), *fileSize))); - } - else if (S_ISDIR(statbuf.st_mode)) - { + content->reserve(static_cast( + std::min(implicit_cast(maxSize), *fileSize))); + } else if (S_ISDIR(statbuf.st_mode)) { err = EISDIR; } - if (modifyTime) - { + if (modifyTime) { *modifyTime = statbuf.st_mtime; } - if (createTime) - { + if (createTime) { *createTime = statbuf.st_ctime; } - } - else - { + } else { err = errno; } } - while (content->size() < implicit_cast(maxSize)) - { - size_t toRead = std::min(implicit_cast(maxSize) - content->size(), sizeof(buf_)); + while (content->size() < implicit_cast(maxSize)) { + size_t toRead = std::min(implicit_cast(maxSize) - content->size(), + sizeof(buf_)); ssize_t n = ::read(fd_, buf_, toRead); - if (n > 0) - { + if (n > 0) { content->append(buf_, n); - } - else - { - if (n < 0) - { + } else { + if (n < 0) { err = errno; } break; @@ -147,35 +115,26 @@ int FileUtil::ReadSmallFile::readToString(int maxSize, return err; } -int FileUtil::ReadSmallFile::readToBuffer(int* size) -{ +int FileUtil::ReadSmallFile::readToBuffer(int *size) { int err = err_; - if (fd_ >= 0) - { - ssize_t n = ::pread(fd_, buf_, sizeof(buf_)-1, 0); - if (n >= 0) - { - if (size) - { + if (fd_ >= 0) { + ssize_t n = ::pread(fd_, buf_, sizeof(buf_) - 1, 0); + if (n >= 0) { + if (size) { *size = static_cast(n); } buf_[n] = '\0'; - } - else - { + } else { err = errno; } } return err; } -template int FileUtil::readFile(StringArg filename, - int maxSize, - string* content, - int64_t*, int64_t*, int64_t*); - -template int FileUtil::ReadSmallFile::readToString( - int maxSize, - string* content, - int64_t*, int64_t*, int64_t*); +template int FileUtil::readFile(StringArg filename, int maxSize, + string *content, int64_t *, int64_t *, + int64_t *); +template int FileUtil::ReadSmallFile::readToString(int maxSize, string *content, + int64_t *, int64_t *, + int64_t *); diff --git a/muduo/base/FileUtil.h b/muduo/base/FileUtil.h index 62ddebcac..ba86de3c1 100644 --- a/muduo/base/FileUtil.h +++ b/muduo/base/FileUtil.h @@ -8,82 +8,69 @@ #ifndef MUDUO_BASE_FILEUTIL_H #define MUDUO_BASE_FILEUTIL_H -#include "muduo/base/noncopyable.h" #include "muduo/base/StringPiece.h" -#include // for off_t +#include "muduo/base/noncopyable.h" +#include // for off_t -namespace muduo -{ -namespace FileUtil -{ +namespace muduo { +namespace FileUtil { // read small file < 64KB -class ReadSmallFile : noncopyable -{ - public: +class ReadSmallFile : noncopyable { +public: ReadSmallFile(StringArg filename); ~ReadSmallFile(); // return errno - template - int readToString(int maxSize, - String* content, - int64_t* fileSize, - int64_t* modifyTime, - int64_t* createTime); + template + int readToString(int maxSize, String *content, int64_t *fileSize, + int64_t *modifyTime, int64_t *createTime); /// Read at maxium kBufferSize into buf_ // return errno - int readToBuffer(int* size); + int readToBuffer(int *size); - const char* buffer() const { return buf_; } + const char *buffer() const { return buf_; } - static const int kBufferSize = 64*1024; + static const int kBufferSize = 64 * 1024; - private: +private: int fd_; int err_; char buf_[kBufferSize]; }; // read the file content, returns errno if error happens. -template -int readFile(StringArg filename, - int maxSize, - String* content, - int64_t* fileSize = NULL, - int64_t* modifyTime = NULL, - int64_t* createTime = NULL) -{ +template +int readFile(StringArg filename, int maxSize, String *content, + int64_t *fileSize = NULL, int64_t *modifyTime = NULL, + int64_t *createTime = NULL) { ReadSmallFile file(filename); return file.readToString(maxSize, content, fileSize, modifyTime, createTime); } // not thread safe -class AppendFile : noncopyable -{ - public: +class AppendFile : noncopyable { +public: explicit AppendFile(StringArg filename); ~AppendFile(); - void append(const char* logline, size_t len); + void append(const char *logline, size_t len); void flush(); off_t writtenBytes() const { return writtenBytes_; } - private: +private: + size_t write(const char *logline, size_t len); - size_t write(const char* logline, size_t len); - - FILE* fp_; - char buffer_[64*1024]; + FILE *fp_; + char buffer_[64 * 1024]; off_t writtenBytes_; }; -} // namespace FileUtil -} // namespace muduo - -#endif // MUDUO_BASE_FILEUTIL_H +} // namespace FileUtil +} // namespace muduo +#endif // MUDUO_BASE_FILEUTIL_H diff --git a/muduo/base/GzipFile.h b/muduo/base/GzipFile.h index 68a538c4d..258817028 100644 --- a/muduo/base/GzipFile.h +++ b/muduo/base/GzipFile.h @@ -9,43 +9,37 @@ #include "muduo/base/noncopyable.h" #include -namespace muduo -{ - -class GzipFile : noncopyable -{ - public: - GzipFile(GzipFile&& rhs) noexcept - : file_(rhs.file_) - { - rhs.file_ = NULL; - } +namespace muduo { + +class GzipFile : noncopyable { +public: + GzipFile(GzipFile &&rhs) noexcept : file_(rhs.file_) { rhs.file_ = NULL; } - ~GzipFile() - { - if (file_) - { + ~GzipFile() { + if (file_) { ::gzclose(file_); } } - GzipFile& operator=(GzipFile&& rhs) noexcept - { + GzipFile &operator=(GzipFile &&rhs) noexcept { swap(rhs); return *this; } bool valid() const { return file_ != NULL; } - void swap(GzipFile& rhs) { std::swap(file_, rhs.file_); } + void swap(GzipFile &rhs) { std::swap(file_, rhs.file_); } #if ZLIB_VERNUM >= 0x1240 bool setBuffer(int size) { return ::gzbuffer(file_, size) == 0; } #endif - // return the number of uncompressed bytes actually read, 0 for eof, -1 for error - int read(void* buf, int len) { return ::gzread(file_, buf, len); } + // return the number of uncompressed bytes actually read, 0 for eof, -1 for + // error + int read(void *buf, int len) { return ::gzread(file_, buf, len); } // return the number of uncompressed bytes actually written - int write(StringPiece buf) { return ::gzwrite(file_, buf.data(), buf.size()); } + int write(StringPiece buf) { + return ::gzwrite(file_, buf.data(), buf.size()); + } // number of uncompressed bytes off_t tell() const { return ::gztell(file_); } @@ -57,33 +51,26 @@ class GzipFile : noncopyable // int flush(int f) { return ::gzflush(file_, f); } - static GzipFile openForRead(StringArg filename) - { + static GzipFile openForRead(StringArg filename) { return GzipFile(::gzopen(filename.c_str(), "rbe")); } - static GzipFile openForAppend(StringArg filename) - { + static GzipFile openForAppend(StringArg filename) { return GzipFile(::gzopen(filename.c_str(), "abe")); } - static GzipFile openForWriteExclusive(StringArg filename) - { + static GzipFile openForWriteExclusive(StringArg filename) { return GzipFile(::gzopen(filename.c_str(), "wbxe")); } - static GzipFile openForWriteTruncate(StringArg filename) - { + static GzipFile openForWriteTruncate(StringArg filename) { return GzipFile(::gzopen(filename.c_str(), "wbe")); } - private: - explicit GzipFile(gzFile file) - : file_(file) - { - } +private: + explicit GzipFile(gzFile file) : file_(file) {} gzFile file_; }; -} // namespace muduo +} // namespace muduo diff --git a/muduo/base/LogFile.cc b/muduo/base/LogFile.cc index 2a12abe40..188d8442f 100644 --- a/muduo/base/LogFile.cc +++ b/muduo/base/LogFile.cc @@ -14,75 +14,50 @@ using namespace muduo; -LogFile::LogFile(const string& basename, - off_t rollSize, - bool threadSafe, - int flushInterval, - int checkEveryN) - : basename_(basename), - rollSize_(rollSize), - flushInterval_(flushInterval), - checkEveryN_(checkEveryN), - count_(0), - mutex_(threadSafe ? new MutexLock : NULL), - startOfPeriod_(0), - lastRoll_(0), - lastFlush_(0) -{ +LogFile::LogFile(const string &basename, off_t rollSize, bool threadSafe, + int flushInterval, int checkEveryN) + : basename_(basename), rollSize_(rollSize), flushInterval_(flushInterval), + checkEveryN_(checkEveryN), count_(0), + mutex_(threadSafe ? new MutexLock : NULL), startOfPeriod_(0), + lastRoll_(0), lastFlush_(0) { assert(basename.find('/') == string::npos); rollFile(); } LogFile::~LogFile() = default; -void LogFile::append(const char* logline, int len) -{ - if (mutex_) - { +void LogFile::append(const char *logline, int len) { + if (mutex_) { MutexLockGuard lock(*mutex_); append_unlocked(logline, len); - } - else - { + } else { append_unlocked(logline, len); } } -void LogFile::flush() -{ - if (mutex_) - { +void LogFile::flush() { + if (mutex_) { MutexLockGuard lock(*mutex_); file_->flush(); - } - else - { + } else { file_->flush(); } } -void LogFile::append_unlocked(const char* logline, int len) -{ +void LogFile::append_unlocked(const char *logline, int len) { file_->append(logline, len); - if (file_->writtenBytes() > rollSize_) - { + if (file_->writtenBytes() > rollSize_) { rollFile(); - } - else - { + } else { ++count_; - if (count_ >= checkEveryN_) - { + if (count_ >= checkEveryN_) { count_ = 0; time_t now = ::time(NULL); time_t thisPeriod_ = now / kRollPerSeconds_ * kRollPerSeconds_; - if (thisPeriod_ != startOfPeriod_) - { + if (thisPeriod_ != startOfPeriod_) { rollFile(); - } - else if (now - lastFlush_ > flushInterval_) - { + } else if (now - lastFlush_ > flushInterval_) { lastFlush_ = now; file_->flush(); } @@ -90,14 +65,12 @@ void LogFile::append_unlocked(const char* logline, int len) } } -bool LogFile::rollFile() -{ +bool LogFile::rollFile() { time_t now = 0; string filename = getLogFileName(basename_, &now); time_t start = now / kRollPerSeconds_ * kRollPerSeconds_; - if (now > lastRoll_) - { + if (now > lastRoll_) { lastRoll_ = now; lastFlush_ = now; startOfPeriod_ = start; @@ -107,8 +80,7 @@ bool LogFile::rollFile() return false; } -string LogFile::getLogFileName(const string& basename, time_t* now) -{ +string LogFile::getLogFileName(const string &basename, time_t *now) { string filename; filename.reserve(basename.size() + 64); filename = basename; @@ -130,4 +102,3 @@ string LogFile::getLogFileName(const string& basename, time_t* now) return filename; } - diff --git a/muduo/base/LogFile.h b/muduo/base/LogFile.h index 7abd583d3..f78c8090a 100644 --- a/muduo/base/LogFile.h +++ b/muduo/base/LogFile.h @@ -11,32 +11,26 @@ #include -namespace muduo -{ +namespace muduo { -namespace FileUtil -{ +namespace FileUtil { class AppendFile; } -class LogFile : noncopyable -{ - public: - LogFile(const string& basename, - off_t rollSize, - bool threadSafe = true, - int flushInterval = 3, - int checkEveryN = 1024); +class LogFile : noncopyable { +public: + LogFile(const string &basename, off_t rollSize, bool threadSafe = true, + int flushInterval = 3, int checkEveryN = 1024); ~LogFile(); - void append(const char* logline, int len); + void append(const char *logline, int len); void flush(); bool rollFile(); - private: - void append_unlocked(const char* logline, int len); +private: + void append_unlocked(const char *logline, int len); - static string getLogFileName(const string& basename, time_t* now); + static string getLogFileName(const string &basename, time_t *now); const string basename_; const off_t rollSize_; @@ -51,8 +45,8 @@ class LogFile : noncopyable time_t lastFlush_; std::unique_ptr file_; - const static int kRollPerSeconds_ = 60*60*24; + const static int kRollPerSeconds_ = 60 * 60 * 24; }; -} // namespace muduo -#endif // MUDUO_BASE_LOGFILE_H +} // namespace muduo +#endif // MUDUO_BASE_LOGFILE_H diff --git a/muduo/base/LogStream.cc b/muduo/base/LogStream.cc index cafd5b8a1..6e8dd6440 100644 --- a/muduo/base/LogStream.cc +++ b/muduo/base/LogStream.cc @@ -6,12 +6,12 @@ #include "muduo/base/LogStream.h" #include -#include -#include #include -#include +#include #include #include +#include +#include #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS @@ -19,7 +19,6 @@ #include - using namespace muduo; using namespace muduo::detail; @@ -30,34 +29,28 @@ using namespace muduo::detail; #pragma GCC diagnostic ignored "-Wtype-limits" #endif -namespace muduo -{ -namespace detail -{ +namespace muduo { +namespace detail { const char digits[] = "9876543210123456789"; -const char* zero = digits + 9; +const char *zero = digits + 9; static_assert(sizeof(digits) == 20, "wrong number of digits"); const char digitsHex[] = "0123456789ABCDEF"; static_assert(sizeof digitsHex == 17, "wrong number of digitsHex"); // Efficient Integer to String Conversions, by Matthew Wilson. -template -size_t convert(char buf[], T value) -{ +template size_t convert(char buf[], T value) { T i = value; - char* p = buf; + char *p = buf; - do - { + do { int lsd = static_cast(i % 10); i /= 10; *p++ = zero[lsd]; } while (i != 0); - if (value < 0) - { + if (value < 0) { *p++ = '-'; } *p = '\0'; @@ -66,13 +59,11 @@ size_t convert(char buf[], T value) return p - buf; } -size_t convertHex(char buf[], uintptr_t value) -{ +size_t convertHex(char buf[], uintptr_t value) { uintptr_t i = value; - char* p = buf; + char *p = buf; - do - { + do { int lsd = static_cast(i % 16); i /= 16; *p++ = digitsHex[lsd]; @@ -87,7 +78,7 @@ size_t convertHex(char buf[], uintptr_t value) template class FixedBuffer; template class FixedBuffer; -} // namespace detail +} // namespace detail /* Format a number with 5 characters, including SI units. @@ -99,44 +90,43 @@ template class FixedBuffer; [1.00P, 999P] [1.00E, inf) */ -std::string formatSI(int64_t s) -{ +std::string formatSI(int64_t s) { double n = static_cast(s); char buf[64]; if (s < 1000) snprintf(buf, sizeof(buf), "%" PRId64, s); else if (s < 9995) - snprintf(buf, sizeof(buf), "%.2fk", n/1e3); + snprintf(buf, sizeof(buf), "%.2fk", n / 1e3); else if (s < 99950) - snprintf(buf, sizeof(buf), "%.1fk", n/1e3); + snprintf(buf, sizeof(buf), "%.1fk", n / 1e3); else if (s < 999500) - snprintf(buf, sizeof(buf), "%.0fk", n/1e3); + snprintf(buf, sizeof(buf), "%.0fk", n / 1e3); else if (s < 9995000) - snprintf(buf, sizeof(buf), "%.2fM", n/1e6); + snprintf(buf, sizeof(buf), "%.2fM", n / 1e6); else if (s < 99950000) - snprintf(buf, sizeof(buf), "%.1fM", n/1e6); + snprintf(buf, sizeof(buf), "%.1fM", n / 1e6); else if (s < 999500000) - snprintf(buf, sizeof(buf), "%.0fM", n/1e6); + snprintf(buf, sizeof(buf), "%.0fM", n / 1e6); else if (s < 9995000000) - snprintf(buf, sizeof(buf), "%.2fG", n/1e9); + snprintf(buf, sizeof(buf), "%.2fG", n / 1e9); else if (s < 99950000000) - snprintf(buf, sizeof(buf), "%.1fG", n/1e9); + snprintf(buf, sizeof(buf), "%.1fG", n / 1e9); else if (s < 999500000000) - snprintf(buf, sizeof(buf), "%.0fG", n/1e9); + snprintf(buf, sizeof(buf), "%.0fG", n / 1e9); else if (s < 9995000000000) - snprintf(buf, sizeof(buf), "%.2fT", n/1e12); + snprintf(buf, sizeof(buf), "%.2fT", n / 1e12); else if (s < 99950000000000) - snprintf(buf, sizeof(buf), "%.1fT", n/1e12); + snprintf(buf, sizeof(buf), "%.1fT", n / 1e12); else if (s < 999500000000000) - snprintf(buf, sizeof(buf), "%.0fT", n/1e12); + snprintf(buf, sizeof(buf), "%.0fT", n / 1e12); else if (s < 9995000000000000) - snprintf(buf, sizeof(buf), "%.2fP", n/1e15); + snprintf(buf, sizeof(buf), "%.2fP", n / 1e15); else if (s < 99950000000000000) - snprintf(buf, sizeof(buf), "%.1fP", n/1e15); + snprintf(buf, sizeof(buf), "%.1fP", n / 1e15); else if (s < 999500000000000000) - snprintf(buf, sizeof(buf), "%.0fP", n/1e15); + snprintf(buf, sizeof(buf), "%.0fP", n / 1e15); else - snprintf(buf, sizeof(buf), "%.2fE", n/1e18); + snprintf(buf, sizeof(buf), "%.2fE", n / 1e18); return buf; } @@ -147,8 +137,7 @@ std::string formatSI(int64_t s) [ 100Ki, 1023Ki] [1.00Mi, 9.99Mi] */ -std::string formatIEC(int64_t s) -{ +std::string formatIEC(int64_t s) { double n = static_cast(s); char buf[64]; const double Ki = 1024.0; @@ -160,72 +149,64 @@ std::string formatIEC(int64_t s) if (n < Ki) snprintf(buf, sizeof buf, "%" PRId64, s); - else if (n < Ki*9.995) + else if (n < Ki * 9.995) snprintf(buf, sizeof buf, "%.2fKi", n / Ki); - else if (n < Ki*99.95) + else if (n < Ki * 99.95) snprintf(buf, sizeof buf, "%.1fKi", n / Ki); - else if (n < Ki*1023.5) + else if (n < Ki * 1023.5) snprintf(buf, sizeof buf, "%.0fKi", n / Ki); - else if (n < Mi*9.995) + else if (n < Mi * 9.995) snprintf(buf, sizeof buf, "%.2fMi", n / Mi); - else if (n < Mi*99.95) + else if (n < Mi * 99.95) snprintf(buf, sizeof buf, "%.1fMi", n / Mi); - else if (n < Mi*1023.5) + else if (n < Mi * 1023.5) snprintf(buf, sizeof buf, "%.0fMi", n / Mi); - else if (n < Gi*9.995) + else if (n < Gi * 9.995) snprintf(buf, sizeof buf, "%.2fGi", n / Gi); - else if (n < Gi*99.95) + else if (n < Gi * 99.95) snprintf(buf, sizeof buf, "%.1fGi", n / Gi); - else if (n < Gi*1023.5) + else if (n < Gi * 1023.5) snprintf(buf, sizeof buf, "%.0fGi", n / Gi); - else if (n < Ti*9.995) + else if (n < Ti * 9.995) snprintf(buf, sizeof buf, "%.2fTi", n / Ti); - else if (n < Ti*99.95) + else if (n < Ti * 99.95) snprintf(buf, sizeof buf, "%.1fTi", n / Ti); - else if (n < Ti*1023.5) + else if (n < Ti * 1023.5) snprintf(buf, sizeof buf, "%.0fTi", n / Ti); - else if (n < Pi*9.995) + else if (n < Pi * 9.995) snprintf(buf, sizeof buf, "%.2fPi", n / Pi); - else if (n < Pi*99.95) + else if (n < Pi * 99.95) snprintf(buf, sizeof buf, "%.1fPi", n / Pi); - else if (n < Pi*1023.5) + else if (n < Pi * 1023.5) snprintf(buf, sizeof buf, "%.0fPi", n / Pi); - else if (n < Ei*9.995) - snprintf(buf, sizeof buf, "%.2fEi", n / Ei ); + else if (n < Ei * 9.995) + snprintf(buf, sizeof buf, "%.2fEi", n / Ei); else - snprintf(buf, sizeof buf, "%.1fEi", n / Ei ); + snprintf(buf, sizeof buf, "%.1fEi", n / Ei); return buf; } -} // namespace muduo +} // namespace muduo -template -const char* FixedBuffer::debugString() -{ +template const char *FixedBuffer::debugString() { *cur_ = '\0'; return data_; } -template -void FixedBuffer::cookieStart() -{ -} +template void FixedBuffer::cookieStart() {} -template -void FixedBuffer::cookieEnd() -{ -} +template void FixedBuffer::cookieEnd() {} -void LogStream::staticCheck() -{ +void LogStream::staticCheck() { static_assert(kMaxNumericSize - 10 > std::numeric_limits::digits10, "kMaxNumericSize is large enough"); - static_assert(kMaxNumericSize - 10 > std::numeric_limits::digits10, + static_assert(kMaxNumericSize - 10 > + std::numeric_limits::digits10, "kMaxNumericSize is large enough"); static_assert(kMaxNumericSize - 10 > std::numeric_limits::digits10, "kMaxNumericSize is large enough"); @@ -233,93 +214,77 @@ void LogStream::staticCheck() "kMaxNumericSize is large enough"); } -template -void LogStream::formatInteger(T v) -{ - if (buffer_.avail() >= kMaxNumericSize) - { +template void LogStream::formatInteger(T v) { + if (buffer_.avail() >= kMaxNumericSize) { size_t len = convert(buffer_.current(), v); buffer_.add(len); } } -LogStream& LogStream::operator<<(short v) -{ +LogStream &LogStream::operator<<(short v) { *this << static_cast(v); return *this; } -LogStream& LogStream::operator<<(unsigned short v) -{ +LogStream &LogStream::operator<<(unsigned short v) { *this << static_cast(v); return *this; } -LogStream& LogStream::operator<<(int v) -{ +LogStream &LogStream::operator<<(int v) { formatInteger(v); return *this; } -LogStream& LogStream::operator<<(unsigned int v) -{ +LogStream &LogStream::operator<<(unsigned int v) { formatInteger(v); return *this; } -LogStream& LogStream::operator<<(long v) -{ +LogStream &LogStream::operator<<(long v) { formatInteger(v); return *this; } -LogStream& LogStream::operator<<(unsigned long v) -{ +LogStream &LogStream::operator<<(unsigned long v) { formatInteger(v); return *this; } -LogStream& LogStream::operator<<(long long v) -{ +LogStream &LogStream::operator<<(long long v) { formatInteger(v); return *this; } -LogStream& LogStream::operator<<(unsigned long long v) -{ +LogStream &LogStream::operator<<(unsigned long long v) { formatInteger(v); return *this; } -LogStream& LogStream::operator<<(const void* p) -{ +LogStream &LogStream::operator<<(const void *p) { uintptr_t v = reinterpret_cast(p); - if (buffer_.avail() >= kMaxNumericSize) - { - char* buf = buffer_.current(); + if (buffer_.avail() >= kMaxNumericSize) { + char *buf = buffer_.current(); buf[0] = '0'; buf[1] = 'x'; - size_t len = convertHex(buf+2, v); - buffer_.add(len+2); + size_t len = convertHex(buf + 2, v); + buffer_.add(len + 2); } return *this; } // FIXME: replace this with Grisu3 by Florian Loitsch. -LogStream& LogStream::operator<<(double v) -{ - if (buffer_.avail() >= kMaxNumericSize) - { +LogStream &LogStream::operator<<(double v) { + if (buffer_.avail() >= kMaxNumericSize) { int len = snprintf(buffer_.current(), kMaxNumericSize, "%.12g", v); buffer_.add(len); } return *this; } -template -Fmt::Fmt(const char* fmt, T val) -{ - static_assert(std::is_arithmetic::value == true, "Must be arithmetic type"); +template Fmt::Fmt(const char *fmt, T val) { + static_assert(std::is_arithmetic::value == true, + "Must be arithmetic type"); length_ = snprintf(buf_, sizeof buf_, fmt, val); assert(static_cast(length_) < sizeof buf_); @@ -327,16 +292,16 @@ Fmt::Fmt(const char* fmt, T val) // Explicit instantiations -template Fmt::Fmt(const char* fmt, char); +template Fmt::Fmt(const char *fmt, char); -template Fmt::Fmt(const char* fmt, short); -template Fmt::Fmt(const char* fmt, unsigned short); -template Fmt::Fmt(const char* fmt, int); -template Fmt::Fmt(const char* fmt, unsigned int); -template Fmt::Fmt(const char* fmt, long); -template Fmt::Fmt(const char* fmt, unsigned long); -template Fmt::Fmt(const char* fmt, long long); -template Fmt::Fmt(const char* fmt, unsigned long long); +template Fmt::Fmt(const char *fmt, short); +template Fmt::Fmt(const char *fmt, unsigned short); +template Fmt::Fmt(const char *fmt, int); +template Fmt::Fmt(const char *fmt, unsigned int); +template Fmt::Fmt(const char *fmt, long); +template Fmt::Fmt(const char *fmt, unsigned long); +template Fmt::Fmt(const char *fmt, long long); +template Fmt::Fmt(const char *fmt, unsigned long long); -template Fmt::Fmt(const char* fmt, float); -template Fmt::Fmt(const char* fmt, double); +template Fmt::Fmt(const char *fmt, float); +template Fmt::Fmt(const char *fmt, double); diff --git a/muduo/base/LogStream.h b/muduo/base/LogStream.h index 442b4689d..13259efa3 100644 --- a/muduo/base/LogStream.h +++ b/muduo/base/LogStream.h @@ -6,51 +6,38 @@ #ifndef MUDUO_BASE_LOGSTREAM_H #define MUDUO_BASE_LOGSTREAM_H -#include "muduo/base/noncopyable.h" #include "muduo/base/StringPiece.h" #include "muduo/base/Types.h" +#include "muduo/base/noncopyable.h" #include #include // memcpy -namespace muduo -{ +namespace muduo { -namespace detail -{ +namespace detail { const int kSmallBuffer = 4000; -const int kLargeBuffer = 4000*1000; +const int kLargeBuffer = 4000 * 1000; -template -class FixedBuffer : noncopyable -{ - public: - FixedBuffer() - : cur_(data_) - { - setCookie(cookieStart); - } +template class FixedBuffer : noncopyable { +public: + FixedBuffer() : cur_(data_) { setCookie(cookieStart); } - ~FixedBuffer() - { - setCookie(cookieEnd); - } + ~FixedBuffer() { setCookie(cookieEnd); } - void append(const char* /*restrict*/ buf, size_t len) - { + void append(const char * /*restrict*/ buf, size_t len) { // FIXME: append partially - if (implicit_cast(avail()) > len) - { + if (implicit_cast(avail()) > len) { memcpy(cur_, buf, len); cur_ += len; } } - const char* data() const { return data_; } + const char *data() const { return data_; } int length() const { return static_cast(cur_ - data_); } // write to data_ directly - char* current() { return cur_; } + char *current() { return cur_; } int avail() const { return static_cast(end() - cur_); } void add(size_t len) { cur_ += len; } @@ -58,58 +45,55 @@ class FixedBuffer : noncopyable void bzero() { memZero(data_, sizeof data_); } // for used by GDB - const char* debugString(); + const char *debugString(); void setCookie(void (*cookie)()) { cookie_ = cookie; } // for used by unit test string toString() const { return string(data_, length()); } StringPiece toStringPiece() const { return StringPiece(data_, length()); } - private: - const char* end() const { return data_ + sizeof data_; } +private: + const char *end() const { return data_ + sizeof data_; } // Must be outline function for cookies. static void cookieStart(); static void cookieEnd(); void (*cookie_)(); char data_[SIZE]; - char* cur_; + char *cur_; }; -} // namespace detail +} // namespace detail -class LogStream : noncopyable -{ +class LogStream : noncopyable { typedef LogStream self; - public: + +public: typedef detail::FixedBuffer Buffer; - self& operator<<(bool v) - { + self &operator<<(bool v) { buffer_.append(v ? "1" : "0", 1); return *this; } - self& operator<<(short); - self& operator<<(unsigned short); - self& operator<<(int); - self& operator<<(unsigned int); - self& operator<<(long); - self& operator<<(unsigned long); - self& operator<<(long long); - self& operator<<(unsigned long long); + self &operator<<(short); + self &operator<<(unsigned short); + self &operator<<(int); + self &operator<<(unsigned int); + self &operator<<(long); + self &operator<<(unsigned long); + self &operator<<(long long); + self &operator<<(unsigned long long); - self& operator<<(const void*); + self &operator<<(const void *); - self& operator<<(float v) - { + self &operator<<(float v) { *this << static_cast(v); return *this; } - self& operator<<(double); + self &operator<<(double); // self& operator<<(long double); - self& operator<<(char v) - { + self &operator<<(char v) { buffer_.append(&v, 1); return *this; } @@ -117,51 +101,42 @@ class LogStream : noncopyable // self& operator<<(signed char); // self& operator<<(unsigned char); - self& operator<<(const char* str) - { - if (str) - { + self &operator<<(const char *str) { + if (str) { buffer_.append(str, strlen(str)); - } - else - { + } else { buffer_.append("(null)", 6); } return *this; } - self& operator<<(const unsigned char* str) - { - return operator<<(reinterpret_cast(str)); + self &operator<<(const unsigned char *str) { + return operator<<(reinterpret_cast(str)); } - self& operator<<(const string& v) - { + self &operator<<(const string &v) { buffer_.append(v.c_str(), v.size()); return *this; } - self& operator<<(const StringPiece& v) - { + self &operator<<(const StringPiece &v) { buffer_.append(v.data(), v.size()); return *this; } - self& operator<<(const Buffer& v) - { + self &operator<<(const Buffer &v) { *this << v.toStringPiece(); return *this; } - void append(const char* data, int len) { buffer_.append(data, len); } - const Buffer& buffer() const { return buffer_; } + void append(const char *data, int len) { buffer_.append(data, len); } + const Buffer &buffer() const { return buffer_; } void resetBuffer() { buffer_.reset(); } - private: +private: void staticCheck(); - template - void formatInteger(T); + template void formatInteger(T); Buffer buffer_; @@ -170,20 +145,18 @@ class LogStream : noncopyable class Fmt // : noncopyable { - public: - template - Fmt(const char* fmt, T val); +public: + template Fmt(const char *fmt, T val); - const char* data() const { return buf_; } + const char *data() const { return buf_; } int length() const { return length_; } - private: +private: char buf_[32]; int length_; }; -inline LogStream& operator<<(LogStream& s, const Fmt& fmt) -{ +inline LogStream &operator<<(LogStream &s, const Fmt &fmt) { s.append(fmt.data(), fmt.length()); return s; } @@ -198,6 +171,6 @@ string formatSI(int64_t n); // Requires n >= 0 string formatIEC(int64_t n); -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_LOGSTREAM_H +#endif // MUDUO_BASE_LOGSTREAM_H diff --git a/muduo/base/Logging.cc b/muduo/base/Logging.cc index c09a8ce4c..3d4177019 100644 --- a/muduo/base/Logging.cc +++ b/muduo/base/Logging.cc @@ -6,8 +6,8 @@ #include "muduo/base/Logging.h" #include "muduo/base/CurrentThread.h" -#include "muduo/base/Timestamp.h" #include "muduo/base/TimeZone.h" +#include "muduo/base/Timestamp.h" #include #include @@ -15,8 +15,7 @@ #include -namespace muduo -{ +namespace muduo { /* class LoggerImpl @@ -39,13 +38,11 @@ __thread char t_errnobuf[512]; __thread char t_time[64]; __thread time_t t_lastSecond; -const char* strerror_tl(int savedErrno) -{ +const char *strerror_tl(int savedErrno) { return strerror_r(savedErrno, t_errnobuf, sizeof t_errnobuf); } -Logger::LogLevel initLogLevel() -{ +Logger::LogLevel initLogLevel() { if (::getenv("MUDUO_LOG_TRACE")) return Logger::TRACE; else if (::getenv("MUDUO_LOG_DEBUG")) @@ -56,172 +53,125 @@ Logger::LogLevel initLogLevel() Logger::LogLevel g_logLevel = initLogLevel(); -const char* LogLevelName[Logger::NUM_LOG_LEVELS] = -{ - "TRACE ", - "DEBUG ", - "INFO ", - "WARN ", - "ERROR ", - "FATAL ", +const char *LogLevelName[Logger::NUM_LOG_LEVELS] = { + "TRACE ", "DEBUG ", "INFO ", "WARN ", "ERROR ", "FATAL ", }; // helper class for known string length at compile time -class T -{ - public: - T(const char* str, unsigned len) - :str_(str), - len_(len) - { +class T { +public: + T(const char *str, unsigned len) : str_(str), len_(len) { assert(strlen(str) == len_); } - const char* str_; + const char *str_; const unsigned len_; }; -inline LogStream& operator<<(LogStream& s, T v) -{ +inline LogStream &operator<<(LogStream &s, T v) { s.append(v.str_, v.len_); return s; } -inline LogStream& operator<<(LogStream& s, const Logger::SourceFile& v) -{ +inline LogStream &operator<<(LogStream &s, const Logger::SourceFile &v) { s.append(v.data_, v.size_); return s; } -void defaultOutput(const char* msg, int len) -{ +void defaultOutput(const char *msg, int len) { size_t n = fwrite(msg, 1, len, stdout); - //FIXME check n + // FIXME check n (void)n; } -void defaultFlush() -{ - fflush(stdout); -} +void defaultFlush() { fflush(stdout); } Logger::OutputFunc g_output = defaultOutput; Logger::FlushFunc g_flush = defaultFlush; TimeZone g_logTimeZone; -} // namespace muduo +} // namespace muduo using namespace muduo; -Logger::Impl::Impl(LogLevel level, int savedErrno, const SourceFile& file, int line) - : time_(Timestamp::now()), - stream_(), - level_(level), - line_(line), - basename_(file) -{ +Logger::Impl::Impl(LogLevel level, int savedErrno, const SourceFile &file, + int line) + : time_(Timestamp::now()), stream_(), level_(level), line_(line), + basename_(file) { formatTime(); CurrentThread::tid(); stream_ << T(CurrentThread::tidString(), CurrentThread::tidStringLength()); stream_ << T(LogLevelName[level], 6); - if (savedErrno != 0) - { + if (savedErrno != 0) { stream_ << strerror_tl(savedErrno) << " (errno=" << savedErrno << ") "; } } -void Logger::Impl::formatTime() -{ +void Logger::Impl::formatTime() { int64_t microSecondsSinceEpoch = time_.microSecondsSinceEpoch(); - time_t seconds = static_cast(microSecondsSinceEpoch / Timestamp::kMicroSecondsPerSecond); - int microseconds = static_cast(microSecondsSinceEpoch % Timestamp::kMicroSecondsPerSecond); - if (seconds != t_lastSecond) - { + time_t seconds = static_cast(microSecondsSinceEpoch / + Timestamp::kMicroSecondsPerSecond); + int microseconds = static_cast(microSecondsSinceEpoch % + Timestamp::kMicroSecondsPerSecond); + if (seconds != t_lastSecond) { t_lastSecond = seconds; struct tm tm_time; - if (g_logTimeZone.valid()) - { + if (g_logTimeZone.valid()) { tm_time = g_logTimeZone.toLocalTime(seconds); - } - else - { + } else { ::gmtime_r(&seconds, &tm_time); // FIXME TimeZone::fromUtcTime } - int len = snprintf(t_time, sizeof(t_time), "%4d%02d%02d %02d:%02d:%02d", - tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday, - tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec); - assert(len == 17); (void)len; + int len = + snprintf(t_time, sizeof(t_time), "%4d%02d%02d %02d:%02d:%02d", + tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday, + tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec); + assert(len == 17); + (void)len; } - if (g_logTimeZone.valid()) - { + if (g_logTimeZone.valid()) { Fmt us(".%06d ", microseconds); assert(us.length() == 8); stream_ << T(t_time, 17) << T(us.data(), 8); - } - else - { + } else { Fmt us(".%06dZ ", microseconds); assert(us.length() == 9); stream_ << T(t_time, 17) << T(us.data(), 9); } } -void Logger::Impl::finish() -{ +void Logger::Impl::finish() { stream_ << " - " << basename_ << ':' << line_ << '\n'; } -Logger::Logger(SourceFile file, int line) - : impl_(INFO, 0, file, line) -{ -} +Logger::Logger(SourceFile file, int line) : impl_(INFO, 0, file, line) {} -Logger::Logger(SourceFile file, int line, LogLevel level, const char* func) - : impl_(level, 0, file, line) -{ +Logger::Logger(SourceFile file, int line, LogLevel level, const char *func) + : impl_(level, 0, file, line) { impl_.stream_ << func << ' '; } Logger::Logger(SourceFile file, int line, LogLevel level) - : impl_(level, 0, file, line) -{ -} + : impl_(level, 0, file, line) {} Logger::Logger(SourceFile file, int line, bool toAbort) - : impl_(toAbort?FATAL:ERROR, errno, file, line) -{ -} + : impl_(toAbort ? FATAL : ERROR, errno, file, line) {} -Logger::~Logger() -{ +Logger::~Logger() { impl_.finish(); - const LogStream::Buffer& buf(stream().buffer()); + const LogStream::Buffer &buf(stream().buffer()); g_output(buf.data(), buf.length()); - if (impl_.level_ == FATAL) - { + if (impl_.level_ == FATAL) { g_flush(); abort(); } } -void Logger::setLogLevel(Logger::LogLevel level) -{ - g_logLevel = level; -} +void Logger::setLogLevel(Logger::LogLevel level) { g_logLevel = level; } -void Logger::setOutput(OutputFunc out) -{ - g_output = out; -} +void Logger::setOutput(OutputFunc out) { g_output = out; } -void Logger::setFlush(FlushFunc flush) -{ - g_flush = flush; -} +void Logger::setFlush(FlushFunc flush) { g_flush = flush; } -void Logger::setTimeZone(const TimeZone& tz) -{ - g_logTimeZone = tz; -} +void Logger::setTimeZone(const TimeZone &tz) { g_logTimeZone = tz; } diff --git a/muduo/base/Logging.h b/muduo/base/Logging.h index be5668991..e95509e31 100644 --- a/muduo/base/Logging.h +++ b/muduo/base/Logging.h @@ -9,16 +9,13 @@ #include "muduo/base/LogStream.h" #include "muduo/base/Timestamp.h" -namespace muduo -{ +namespace muduo { class TimeZone; -class Logger -{ - public: - enum LogLevel - { +class Logger { +public: + enum LogLevel { TRACE, DEBUG, INFO, @@ -29,81 +26,67 @@ class Logger }; // compile time calculation of basename of source file - class SourceFile - { - public: - template - SourceFile(const char (&arr)[N]) - : data_(arr), - size_(N-1) - { - const char* slash = strrchr(data_, '/'); // builtin function - if (slash) - { + class SourceFile { + public: + template + SourceFile(const char (&arr)[N]) : data_(arr), size_(N - 1) { + const char *slash = strrchr(data_, '/'); // builtin function + if (slash) { data_ = slash + 1; size_ -= static_cast(data_ - arr); } } - explicit SourceFile(const char* filename) - : data_(filename) - { - const char* slash = strrchr(filename, '/'); - if (slash) - { + explicit SourceFile(const char *filename) : data_(filename) { + const char *slash = strrchr(filename, '/'); + if (slash) { data_ = slash + 1; } size_ = static_cast(strlen(data_)); } - const char* data_; + const char *data_; int size_; }; Logger(SourceFile file, int line); Logger(SourceFile file, int line, LogLevel level); - Logger(SourceFile file, int line, LogLevel level, const char* func); + Logger(SourceFile file, int line, LogLevel level, const char *func); Logger(SourceFile file, int line, bool toAbort); ~Logger(); - LogStream& stream() { return impl_.stream_; } + LogStream &stream() { return impl_.stream_; } static LogLevel logLevel(); static void setLogLevel(LogLevel level); - typedef void (*OutputFunc)(const char* msg, int len); + typedef void (*OutputFunc)(const char *msg, int len); typedef void (*FlushFunc)(); static void setOutput(OutputFunc); static void setFlush(FlushFunc); - static void setTimeZone(const TimeZone& tz); - - private: - -class Impl -{ - public: - typedef Logger::LogLevel LogLevel; - Impl(LogLevel level, int old_errno, const SourceFile& file, int line); - void formatTime(); - void finish(); - - Timestamp time_; - LogStream stream_; - LogLevel level_; - int line_; - SourceFile basename_; -}; + static void setTimeZone(const TimeZone &tz); + +private: + class Impl { + public: + typedef Logger::LogLevel LogLevel; + Impl(LogLevel level, int old_errno, const SourceFile &file, int line); + void formatTime(); + void finish(); + + Timestamp time_; + LogStream stream_; + LogLevel level_; + int line_; + SourceFile basename_; + }; Impl impl_; - }; extern Logger::LogLevel g_logLevel; -inline Logger::LogLevel Logger::logLevel() -{ - return g_logLevel; -} +inline Logger::LogLevel Logger::logLevel() { return g_logLevel; } // // CAUTION: do not write: @@ -121,39 +104,43 @@ inline Logger::LogLevel Logger::logLevel() // else // logWarnStream << "Bad news"; // -#define LOG_TRACE if (muduo::Logger::logLevel() <= muduo::Logger::TRACE) \ +#define LOG_TRACE \ + if (muduo::Logger::logLevel() <= muduo::Logger::TRACE) \ muduo::Logger(__FILE__, __LINE__, muduo::Logger::TRACE, __func__).stream() -#define LOG_DEBUG if (muduo::Logger::logLevel() <= muduo::Logger::DEBUG) \ +#define LOG_DEBUG \ + if (muduo::Logger::logLevel() <= muduo::Logger::DEBUG) \ muduo::Logger(__FILE__, __LINE__, muduo::Logger::DEBUG, __func__).stream() -#define LOG_INFO if (muduo::Logger::logLevel() <= muduo::Logger::INFO) \ +#define LOG_INFO \ + if (muduo::Logger::logLevel() <= muduo::Logger::INFO) \ muduo::Logger(__FILE__, __LINE__).stream() #define LOG_WARN muduo::Logger(__FILE__, __LINE__, muduo::Logger::WARN).stream() -#define LOG_ERROR muduo::Logger(__FILE__, __LINE__, muduo::Logger::ERROR).stream() -#define LOG_FATAL muduo::Logger(__FILE__, __LINE__, muduo::Logger::FATAL).stream() +#define LOG_ERROR \ + muduo::Logger(__FILE__, __LINE__, muduo::Logger::ERROR).stream() +#define LOG_FATAL \ + muduo::Logger(__FILE__, __LINE__, muduo::Logger::FATAL).stream() #define LOG_SYSERR muduo::Logger(__FILE__, __LINE__, false).stream() #define LOG_SYSFATAL muduo::Logger(__FILE__, __LINE__, true).stream() -const char* strerror_tl(int savedErrno); +const char *strerror_tl(int savedErrno); // Taken from glog/logging.h // // Check that the input is non NULL. This very useful in constructor // initializer lists. -#define CHECK_NOTNULL(val) \ - ::muduo::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val)) +#define CHECK_NOTNULL(val) \ + ::muduo::CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", \ + (val)) // A small helper for CHECK_NOTNULL(). template -T* CheckNotNull(Logger::SourceFile file, int line, const char *names, T* ptr) -{ - if (ptr == NULL) - { - Logger(file, line, Logger::FATAL).stream() << names; +T *CheckNotNull(Logger::SourceFile file, int line, const char *names, T *ptr) { + if (ptr == NULL) { + Logger(file, line, Logger::FATAL).stream() << names; } return ptr; } -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_LOGGING_H +#endif // MUDUO_BASE_LOGGING_H diff --git a/muduo/base/Mutex.h b/muduo/base/Mutex.h index 20746bdc6..f7b7c108c 100644 --- a/muduo/base/Mutex.h +++ b/muduo/base/Mutex.h @@ -17,66 +17,59 @@ // Enable thread safety attributes only with clang. // The attributes can be safely erased when compiling with other compilers. #if defined(__clang__) && (!defined(SWIG)) -#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) +#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) #else -#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op +#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op #endif -#define CAPABILITY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) +#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) -#define SCOPED_CAPABILITY \ - THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) +#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) -#define GUARDED_BY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) +#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) -#define PT_GUARDED_BY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) +#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) -#define ACQUIRED_BEFORE(...) \ +#define ACQUIRED_BEFORE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) -#define ACQUIRED_AFTER(...) \ +#define ACQUIRED_AFTER(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) -#define REQUIRES(...) \ +#define REQUIRES(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__)) -#define REQUIRES_SHARED(...) \ +#define REQUIRES_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__)) -#define ACQUIRE(...) \ +#define ACQUIRE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) -#define ACQUIRE_SHARED(...) \ +#define ACQUIRE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__)) -#define RELEASE(...) \ +#define RELEASE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) -#define RELEASE_SHARED(...) \ +#define RELEASE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__)) -#define TRY_ACQUIRE(...) \ +#define TRY_ACQUIRE(...) \ THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__)) -#define TRY_ACQUIRE_SHARED(...) \ +#define TRY_ACQUIRE_SHARED(...) \ THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__)) -#define EXCLUDES(...) \ - THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) +#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) -#define ASSERT_CAPABILITY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) +#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) -#define ASSERT_SHARED_CAPABILITY(x) \ +#define ASSERT_SHARED_CAPABILITY(x) \ THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) -#define RETURN_CAPABILITY(x) \ - THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) +#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) -#define NO_THREAD_SAFETY_ANALYSIS \ +#define NO_THREAD_SAFETY_ANALYSIS \ THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) // End of thread safety annotations } @@ -85,27 +78,32 @@ #ifdef NDEBUG __BEGIN_DECLS -extern void __assert_perror_fail (int errnum, - const char *file, - unsigned int line, - const char *function) - noexcept __attribute__ ((__noreturn__)); +extern void __assert_perror_fail(int errnum, const char *file, + unsigned int line, + const char *function) noexcept + __attribute__((__noreturn__)); __END_DECLS #endif -#define MCHECK(ret) ({ __typeof__ (ret) errnum = (ret); \ - if (__builtin_expect(errnum != 0, 0)) \ - __assert_perror_fail (errnum, __FILE__, __LINE__, __func__);}) +#define MCHECK(ret) \ + ({ \ + __typeof__(ret) errnum = (ret); \ + if (__builtin_expect(errnum != 0, 0)) \ + __assert_perror_fail(errnum, __FILE__, __LINE__, __func__); \ + }) -#else // CHECK_PTHREAD_RETURN_VALUE +#else // CHECK_PTHREAD_RETURN_VALUE -#define MCHECK(ret) ({ __typeof__ (ret) errnum = (ret); \ - assert(errnum == 0); (void) errnum;}) +#define MCHECK(ret) \ + ({ \ + __typeof__(ret) errnum = (ret); \ + assert(errnum == 0); \ + (void)errnum; \ + }) #endif // CHECK_PTHREAD_RETURN_VALUE -namespace muduo -{ +namespace muduo { // Use as data member of a class, eg. // @@ -118,81 +116,54 @@ namespace muduo // mutable MutexLock mutex_; // std::vector data_ GUARDED_BY(mutex_); // }; -class CAPABILITY("mutex") MutexLock : noncopyable -{ - public: - MutexLock() - : holder_(0) - { - MCHECK(pthread_mutex_init(&mutex_, NULL)); - } +class CAPABILITY("mutex") MutexLock : noncopyable { +public: + MutexLock() : holder_(0) { MCHECK(pthread_mutex_init(&mutex_, NULL)); } - ~MutexLock() - { + ~MutexLock() { assert(holder_ == 0); MCHECK(pthread_mutex_destroy(&mutex_)); } // must be called when locked, i.e. for assertion - bool isLockedByThisThread() const - { - return holder_ == CurrentThread::tid(); - } + bool isLockedByThisThread() const { return holder_ == CurrentThread::tid(); } - void assertLocked() const ASSERT_CAPABILITY(this) - { + void assertLocked() const ASSERT_CAPABILITY(this) { assert(isLockedByThisThread()); } // internal usage - void lock() ACQUIRE() - { + void lock() ACQUIRE() { MCHECK(pthread_mutex_lock(&mutex_)); assignHolder(); } - void unlock() RELEASE() - { + void unlock() RELEASE() { unassignHolder(); MCHECK(pthread_mutex_unlock(&mutex_)); } - pthread_mutex_t* getPthreadMutex() /* non-const */ - { - return &mutex_; - } + pthread_mutex_t *getPthreadMutex() /* non-const */ { return &mutex_; } - private: +private: friend class Condition; - class UnassignGuard : noncopyable - { - public: - explicit UnassignGuard(MutexLock& owner) - : owner_(owner) - { + class UnassignGuard : noncopyable { + public: + explicit UnassignGuard(MutexLock &owner) : owner_(owner) { owner_.unassignHolder(); } - ~UnassignGuard() - { - owner_.assignHolder(); - } + ~UnassignGuard() { owner_.assignHolder(); } - private: - MutexLock& owner_; + private: + MutexLock &owner_; }; - void unassignHolder() - { - holder_ = 0; - } + void unassignHolder() { holder_ = 0; } - void assignHolder() - { - holder_ = CurrentThread::tid(); - } + void assignHolder() { holder_ = CurrentThread::tid(); } pthread_mutex_t mutex_; pid_t holder_; @@ -204,30 +175,23 @@ class CAPABILITY("mutex") MutexLock : noncopyable // MutexLockGuard lock(mutex_); // return data_.size(); // } -class SCOPED_CAPABILITY MutexLockGuard : noncopyable -{ - public: - explicit MutexLockGuard(MutexLock& mutex) ACQUIRE(mutex) - : mutex_(mutex) - { +class SCOPED_CAPABILITY MutexLockGuard : noncopyable { +public: + explicit MutexLockGuard(MutexLock &mutex) ACQUIRE(mutex) : mutex_(mutex) { mutex_.lock(); } - ~MutexLockGuard() RELEASE() - { - mutex_.unlock(); - } - - private: + ~MutexLockGuard() RELEASE() { mutex_.unlock(); } - MutexLock& mutex_; +private: + MutexLock &mutex_; }; -} // namespace muduo +} // namespace muduo // Prevent misuse like: // MutexLockGuard(mutex_); // A tempory object doesn't hold the lock for long! #define MutexLockGuard(x) error "Missing guard object name" -#endif // MUDUO_BASE_MUTEX_H +#endif // MUDUO_BASE_MUTEX_H diff --git a/muduo/base/ProcessInfo.cc b/muduo/base/ProcessInfo.cc index 6ab5ad184..080f1fc3b 100644 --- a/muduo/base/ProcessInfo.cc +++ b/muduo/base/ProcessInfo.cc @@ -14,37 +14,30 @@ #include #include // snprintf #include -#include #include #include +#include -namespace muduo -{ -namespace detail -{ +namespace muduo { +namespace detail { __thread int t_numOpenedFiles = 0; -int fdDirFilter(const struct dirent* d) -{ - if (::isdigit(d->d_name[0])) - { +int fdDirFilter(const struct dirent *d) { + if (::isdigit(d->d_name[0])) { ++t_numOpenedFiles; } return 0; } -__thread std::vector* t_pids = NULL; -int taskDirFilter(const struct dirent* d) -{ - if (::isdigit(d->d_name[0])) - { +__thread std::vector *t_pids = NULL; +int taskDirFilter(const struct dirent *d) { + if (::isdigit(d->d_name[0])) { t_pids->push_back(atoi(d->d_name)); } return 0; } -int scanDir(const char *dirpath, int (*filter)(const struct dirent *)) -{ - struct dirent** namelist = NULL; +int scanDir(const char *dirpath, int (*filter)(const struct dirent *)) { + struct dirent **namelist = NULL; int result = ::scandir(dirpath, &namelist, filter, alphasort); assert(namelist == NULL); return result; @@ -54,66 +47,44 @@ Timestamp g_startTime = Timestamp::now(); // assume those won't change during the life time of a process. int g_clockTicks = static_cast(::sysconf(_SC_CLK_TCK)); int g_pageSize = static_cast(::sysconf(_SC_PAGE_SIZE)); -} // namespace detail -} // namespace muduo +} // namespace detail +} // namespace muduo using namespace muduo; using namespace muduo::detail; -pid_t ProcessInfo::pid() -{ - return ::getpid(); -} +pid_t ProcessInfo::pid() { return ::getpid(); } -string ProcessInfo::pidString() -{ +string ProcessInfo::pidString() { char buf[32]; snprintf(buf, sizeof buf, "%d", pid()); return buf; } -uid_t ProcessInfo::uid() -{ - return ::getuid(); -} +uid_t ProcessInfo::uid() { return ::getuid(); } -string ProcessInfo::username() -{ +string ProcessInfo::username() { struct passwd pwd; - struct passwd* result = NULL; + struct passwd *result = NULL; char buf[8192]; - const char* name = "unknownuser"; + const char *name = "unknownuser"; getpwuid_r(uid(), &pwd, buf, sizeof buf, &result); - if (result) - { + if (result) { name = pwd.pw_name; } return name; } -uid_t ProcessInfo::euid() -{ - return ::geteuid(); -} +uid_t ProcessInfo::euid() { return ::geteuid(); } -Timestamp ProcessInfo::startTime() -{ - return g_startTime; -} +Timestamp ProcessInfo::startTime() { return g_startTime; } -int ProcessInfo::clockTicksPerSecond() -{ - return g_clockTicks; -} +int ProcessInfo::clockTicksPerSecond() { return g_clockTicks; } -int ProcessInfo::pageSize() -{ - return g_pageSize; -} +int ProcessInfo::pageSize() { return g_pageSize; } -bool ProcessInfo::isDebugBuild() -{ +bool ProcessInfo::isDebugBuild() { #ifdef NDEBUG return false; #else @@ -121,55 +92,43 @@ bool ProcessInfo::isDebugBuild() #endif } -string ProcessInfo::hostname() -{ +string ProcessInfo::hostname() { // HOST_NAME_MAX 64 // _POSIX_HOST_NAME_MAX 255 char buf[256]; - if (::gethostname(buf, sizeof buf) == 0) - { - buf[sizeof(buf)-1] = '\0'; + if (::gethostname(buf, sizeof buf) == 0) { + buf[sizeof(buf) - 1] = '\0'; return buf; - } - else - { + } else { return "unknownhost"; } } -string ProcessInfo::procname() -{ - return procname(procStat()).as_string(); -} +string ProcessInfo::procname() { return procname(procStat()).as_string(); } -StringPiece ProcessInfo::procname(const string& stat) -{ +StringPiece ProcessInfo::procname(const string &stat) { StringPiece name; size_t lp = stat.find('('); size_t rp = stat.rfind(')'); - if (lp != string::npos && rp != string::npos && lp < rp) - { - name.set(stat.data()+lp+1, static_cast(rp-lp-1)); + if (lp != string::npos && rp != string::npos && lp < rp) { + name.set(stat.data() + lp + 1, static_cast(rp - lp - 1)); } return name; } -string ProcessInfo::procStatus() -{ +string ProcessInfo::procStatus() { string result; FileUtil::readFile("/proc/self/status", 65536, &result); return result; } -string ProcessInfo::procStat() -{ +string ProcessInfo::procStat() { string result; FileUtil::readFile("/proc/self/stat", 65536, &result); return result; } -string ProcessInfo::threadStat() -{ +string ProcessInfo::threadStat() { char buf[64]; snprintf(buf, sizeof buf, "/proc/self/task/%d/stat", CurrentThread::tid()); string result; @@ -177,44 +136,35 @@ string ProcessInfo::threadStat() return result; } -string ProcessInfo::exePath() -{ +string ProcessInfo::exePath() { string result; char buf[1024]; ssize_t n = ::readlink("/proc/self/exe", buf, sizeof buf); - if (n > 0) - { + if (n > 0) { result.assign(buf, n); } return result; } -int ProcessInfo::openedFiles() -{ +int ProcessInfo::openedFiles() { t_numOpenedFiles = 0; scanDir("/proc/self/fd", fdDirFilter); return t_numOpenedFiles; } -int ProcessInfo::maxOpenFiles() -{ +int ProcessInfo::maxOpenFiles() { struct rlimit rl; - if (::getrlimit(RLIMIT_NOFILE, &rl)) - { + if (::getrlimit(RLIMIT_NOFILE, &rl)) { return openedFiles(); - } - else - { + } else { return static_cast(rl.rlim_cur); } } -ProcessInfo::CpuTime ProcessInfo::cpuTime() -{ +ProcessInfo::CpuTime ProcessInfo::cpuTime() { ProcessInfo::CpuTime t; struct tms tms; - if (::times(&tms) >= 0) - { + if (::times(&tms) >= 0) { const double hz = static_cast(clockTicksPerSecond()); t.userSeconds = static_cast(tms.tms_utime) / hz; t.systemSeconds = static_cast(tms.tms_stime) / hz; @@ -222,20 +172,17 @@ ProcessInfo::CpuTime ProcessInfo::cpuTime() return t; } -int ProcessInfo::numThreads() -{ +int ProcessInfo::numThreads() { int result = 0; string status = procStatus(); size_t pos = status.find("Threads:"); - if (pos != string::npos) - { + if (pos != string::npos) { result = ::atoi(status.c_str() + pos + 8); } return result; } -std::vector ProcessInfo::threads() -{ +std::vector ProcessInfo::threads() { std::vector result; t_pids = &result; scanDir("/proc/self/task", taskDirFilter); @@ -243,4 +190,3 @@ std::vector ProcessInfo::threads() std::sort(result.begin(), result.end()); return result; } - diff --git a/muduo/base/ProcessInfo.h b/muduo/base/ProcessInfo.h index eae1498b1..294f6f9e4 100644 --- a/muduo/base/ProcessInfo.h +++ b/muduo/base/ProcessInfo.h @@ -9,60 +9,57 @@ #define MUDUO_BASE_PROCESSINFO_H #include "muduo/base/StringPiece.h" -#include "muduo/base/Types.h" #include "muduo/base/Timestamp.h" -#include +#include "muduo/base/Types.h" #include +#include -namespace muduo -{ +namespace muduo { -namespace ProcessInfo -{ - pid_t pid(); - string pidString(); - uid_t uid(); - string username(); - uid_t euid(); - Timestamp startTime(); - int clockTicksPerSecond(); - int pageSize(); - bool isDebugBuild(); // constexpr +namespace ProcessInfo { +pid_t pid(); +string pidString(); +uid_t uid(); +string username(); +uid_t euid(); +Timestamp startTime(); +int clockTicksPerSecond(); +int pageSize(); +bool isDebugBuild(); // constexpr - string hostname(); - string procname(); - StringPiece procname(const string& stat); +string hostname(); +string procname(); +StringPiece procname(const string &stat); - /// read /proc/self/status - string procStatus(); +/// read /proc/self/status +string procStatus(); - /// read /proc/self/stat - string procStat(); +/// read /proc/self/stat +string procStat(); - /// read /proc/self/task/tid/stat - string threadStat(); +/// read /proc/self/task/tid/stat +string threadStat(); - /// readlink /proc/self/exe - string exePath(); +/// readlink /proc/self/exe +string exePath(); - int openedFiles(); - int maxOpenFiles(); +int openedFiles(); +int maxOpenFiles(); - struct CpuTime - { - double userSeconds; - double systemSeconds; +struct CpuTime { + double userSeconds; + double systemSeconds; - CpuTime() : userSeconds(0.0), systemSeconds(0.0) { } + CpuTime() : userSeconds(0.0), systemSeconds(0.0) {} - double total() const { return userSeconds + systemSeconds; } - }; - CpuTime cpuTime(); + double total() const { return userSeconds + systemSeconds; } +}; +CpuTime cpuTime(); - int numThreads(); - std::vector threads(); -} // namespace ProcessInfo +int numThreads(); +std::vector threads(); +} // namespace ProcessInfo -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_PROCESSINFO_H +#endif // MUDUO_BASE_PROCESSINFO_H diff --git a/muduo/base/Singleton.h b/muduo/base/Singleton.h index 594943626..f4fd15861 100644 --- a/muduo/base/Singleton.h +++ b/muduo/base/Singleton.h @@ -12,66 +12,55 @@ #include #include // atexit -namespace muduo -{ +namespace muduo { -namespace detail -{ +namespace detail { // This doesn't detect inherited member functions! // http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions -template -struct has_no_destroy -{ +template struct has_no_destroy { template static char test(decltype(&C::no_destroy)); template static int32_t test(...); const static bool value = sizeof(test(0)) == 1; }; -} // namespace detail +} // namespace detail -template -class Singleton : noncopyable -{ - public: +template class Singleton : noncopyable { +public: Singleton() = delete; ~Singleton() = delete; - static T& instance() - { + static T &instance() { pthread_once(&ponce_, &Singleton::init); assert(value_ != NULL); return *value_; } - private: - static void init() - { +private: + static void init() { value_ = new T(); - if (!detail::has_no_destroy::value) - { + if (!detail::has_no_destroy::value) { ::atexit(destroy); } } - static void destroy() - { + static void destroy() { typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; - T_must_be_complete_type dummy; (void) dummy; + T_must_be_complete_type dummy; + (void)dummy; delete value_; value_ = NULL; } - private: +private: static pthread_once_t ponce_; - static T* value_; + static T *value_; }; -template -pthread_once_t Singleton::ponce_ = PTHREAD_ONCE_INIT; +template pthread_once_t Singleton::ponce_ = PTHREAD_ONCE_INIT; -template -T* Singleton::value_ = NULL; +template T *Singleton::value_ = NULL; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_SINGLETON_H +#endif // MUDUO_BASE_SINGLETON_H diff --git a/muduo/base/StringPiece.h b/muduo/base/StringPiece.h index a62eda054..6eb016a1b 100644 --- a/muduo/base/StringPiece.h +++ b/muduo/base/StringPiece.h @@ -40,52 +40,45 @@ #ifndef MUDUO_BASE_STRINGPIECE_H #define MUDUO_BASE_STRINGPIECE_H +#include // for ostream forward-declaration #include -#include // for ostream forward-declaration #include "muduo/base/Types.h" -namespace muduo -{ +namespace muduo { // For passing C-style string argument to a function. class StringArg // copyable { - public: - StringArg(const char* str) - : str_(str) - { } +public: + StringArg(const char *str) : str_(str) {} - StringArg(const string& str) - : str_(str.c_str()) - { } + StringArg(const string &str) : str_(str.c_str()) {} - const char* c_str() const { return str_; } + const char *c_str() const { return str_; } - private: - const char* str_; +private: + const char *str_; }; class StringPiece { - private: - const char* ptr_; - int length_; +private: + const char *ptr_; + int length_; - public: +public: // We provide non-explicit singleton constructors so users can pass // in a "const char*" or a "string" wherever a "StringPiece" is // expected. - StringPiece() - : ptr_(NULL), length_(0) { } - StringPiece(const char* str) - : ptr_(str), length_(static_cast(strlen(ptr_))) { } - StringPiece(const unsigned char* str) - : ptr_(reinterpret_cast(str)), - length_(static_cast(strlen(ptr_))) { } - StringPiece(const string& str) - : ptr_(str.data()), length_(static_cast(str.size())) { } - StringPiece(const char* offset, int len) - : ptr_(offset), length_(len) { } + StringPiece() : ptr_(NULL), length_(0) {} + StringPiece(const char *str) + : ptr_(str), length_(static_cast(strlen(ptr_))) {} + StringPiece(const unsigned char *str) + : ptr_(reinterpret_cast(str)), + length_(static_cast(strlen(ptr_))) {} + StringPiece(const string &str) + : ptr_(str.data()), length_(static_cast(str.size())) {} + StringPiece(const char *offset, int len) : ptr_(offset), length_(len) {} // data() may return a pointer to a buffer with embedded NULs, and the // returned buffer may or may not be null terminated. Therefore it is @@ -93,20 +86,26 @@ class StringPiece { // terminated string. Use "as_string().c_str()" if you really need to do // this. Or better yet, change your routine so it does not rely on NUL // termination. - const char* data() const { return ptr_; } + const char *data() const { return ptr_; } int size() const { return length_; } bool empty() const { return length_ == 0; } - const char* begin() const { return ptr_; } - const char* end() const { return ptr_ + length_; } + const char *begin() const { return ptr_; } + const char *end() const { return ptr_ + length_; } - void clear() { ptr_ = NULL; length_ = 0; } - void set(const char* buffer, int len) { ptr_ = buffer; length_ = len; } - void set(const char* str) { + void clear() { + ptr_ = NULL; + length_ = 0; + } + void set(const char *buffer, int len) { + ptr_ = buffer; + length_ = len; + } + void set(const char *str) { ptr_ = str; length_ = static_cast(strlen(str)); } - void set(const void* buffer, int len) { - ptr_ = reinterpret_cast(buffer); + void set(const void *buffer, int len) { + ptr_ = reinterpret_cast(buffer); length_ = len; } @@ -117,53 +116,46 @@ class StringPiece { length_ -= n; } - void remove_suffix(int n) { - length_ -= n; - } + void remove_suffix(int n) { length_ -= n; } - bool operator==(const StringPiece& x) const { - return ((length_ == x.length_) && - (memcmp(ptr_, x.ptr_, length_) == 0)); - } - bool operator!=(const StringPiece& x) const { - return !(*this == x); + bool operator==(const StringPiece &x) const { + return ((length_ == x.length_) && (memcmp(ptr_, x.ptr_, length_) == 0)); } + bool operator!=(const StringPiece &x) const { return !(*this == x); } -#define STRINGPIECE_BINARY_PREDICATE(cmp,auxcmp) \ - bool operator cmp (const StringPiece& x) const { \ - int r = memcmp(ptr_, x.ptr_, length_ < x.length_ ? length_ : x.length_); \ - return ((r auxcmp 0) || ((r == 0) && (length_ cmp x.length_))); \ +#define STRINGPIECE_BINARY_PREDICATE(cmp, auxcmp) \ + bool operator cmp(const StringPiece &x) const { \ + int r = memcmp(ptr_, x.ptr_, length_ < x.length_ ? length_ : x.length_); \ + return ((r auxcmp 0) || ((r == 0) && (length_ cmp x.length_))); \ } - STRINGPIECE_BINARY_PREDICATE(<, <); + STRINGPIECE_BINARY_PREDICATE(<, <); STRINGPIECE_BINARY_PREDICATE(<=, <); STRINGPIECE_BINARY_PREDICATE(>=, >); - STRINGPIECE_BINARY_PREDICATE(>, >); + STRINGPIECE_BINARY_PREDICATE(>, >); #undef STRINGPIECE_BINARY_PREDICATE - int compare(const StringPiece& x) const { + int compare(const StringPiece &x) const { int r = memcmp(ptr_, x.ptr_, length_ < x.length_ ? length_ : x.length_); if (r == 0) { - if (length_ < x.length_) r = -1; - else if (length_ > x.length_) r = +1; + if (length_ < x.length_) + r = -1; + else if (length_ > x.length_) + r = +1; } return r; } - string as_string() const { - return string(data(), size()); - } + string as_string() const { return string(data(), size()); } - void CopyToString(string* target) const { - target->assign(ptr_, length_); - } + void CopyToString(string *target) const { target->assign(ptr_, length_); } // Does "this" start with "x" - bool starts_with(const StringPiece& x) const { + bool starts_with(const StringPiece &x) const { return ((length_ >= x.length_) && (memcmp(ptr_, x.ptr_, x.length_) == 0)); } }; -} // namespace muduo +} // namespace muduo // ------------------------------------------------------------------ // Functions used to create STL containers that use StringPiece @@ -174,16 +166,16 @@ class StringPiece { #ifdef HAVE_TYPE_TRAITS // This makes vector really fast for some STL implementations -template<> struct __type_traits { - typedef __true_type has_trivial_default_constructor; - typedef __true_type has_trivial_copy_constructor; - typedef __true_type has_trivial_assignment_operator; - typedef __true_type has_trivial_destructor; - typedef __true_type is_POD_type; +template <> struct __type_traits { + typedef __true_type has_trivial_default_constructor; + typedef __true_type has_trivial_copy_constructor; + typedef __true_type has_trivial_assignment_operator; + typedef __true_type has_trivial_destructor; + typedef __true_type is_POD_type; }; #endif // allow StringPiece to be logged -std::ostream& operator<<(std::ostream& o, const muduo::StringPiece& piece); +std::ostream &operator<<(std::ostream &o, const muduo::StringPiece &piece); -#endif // MUDUO_BASE_STRINGPIECE_H +#endif // MUDUO_BASE_STRINGPIECE_H diff --git a/muduo/base/Thread.cc b/muduo/base/Thread.cc index 630a0c9ef..924e6bbe0 100644 --- a/muduo/base/Thread.cc +++ b/muduo/base/Thread.cc @@ -11,36 +11,28 @@ #include #include +#include #include -#include #include #include #include -#include +#include -namespace muduo -{ -namespace detail -{ +namespace muduo { +namespace detail { -pid_t gettid() -{ - return static_cast(::syscall(SYS_gettid)); -} +pid_t gettid() { return static_cast(::syscall(SYS_gettid)); } -void afterFork() -{ +void afterFork() { muduo::CurrentThread::t_cachedTid = 0; muduo::CurrentThread::t_threadName = "main"; CurrentThread::tid(); // no need to call pthread_atfork(NULL, NULL, &afterFork); } -class ThreadNameInitializer -{ - public: - ThreadNameInitializer() - { +class ThreadNameInitializer { +public: + ThreadNameInitializer() { muduo::CurrentThread::t_threadName = "main"; CurrentThread::tid(); pthread_atfork(NULL, NULL, &afterFork); @@ -49,55 +41,41 @@ class ThreadNameInitializer ThreadNameInitializer init; -struct ThreadData -{ +struct ThreadData { typedef muduo::Thread::ThreadFunc ThreadFunc; ThreadFunc func_; string name_; - pid_t* tid_; - CountDownLatch* latch_; - - ThreadData(ThreadFunc func, - const string& name, - pid_t* tid, - CountDownLatch* latch) - : func_(std::move(func)), - name_(name), - tid_(tid), - latch_(latch) - { } - - void runInThread() - { + pid_t *tid_; + CountDownLatch *latch_; + + ThreadData(ThreadFunc func, const string &name, pid_t *tid, + CountDownLatch *latch) + : func_(std::move(func)), name_(name), tid_(tid), latch_(latch) {} + + void runInThread() { *tid_ = muduo::CurrentThread::tid(); tid_ = NULL; latch_->countDown(); latch_ = NULL; - muduo::CurrentThread::t_threadName = name_.empty() ? "muduoThread" : name_.c_str(); + muduo::CurrentThread::t_threadName = + name_.empty() ? "muduoThread" : name_.c_str(); ::prctl(PR_SET_NAME, muduo::CurrentThread::t_threadName); - try - { + try { func_(); muduo::CurrentThread::t_threadName = "finished"; - } - catch (const Exception& ex) - { + } catch (const Exception &ex) { muduo::CurrentThread::t_threadName = "crashed"; fprintf(stderr, "exception caught in Thread %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); fprintf(stderr, "stack trace: %s\n", ex.stackTrace()); abort(); - } - catch (const std::exception& ex) - { + } catch (const std::exception &ex) { muduo::CurrentThread::t_threadName = "crashed"; fprintf(stderr, "exception caught in Thread %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); abort(); - } - catch (...) - { + } catch (...) { muduo::CurrentThread::t_threadName = "crashed"; fprintf(stderr, "unknown exception caught in Thread %s\n", name_.c_str()); throw; // rethrow @@ -105,96 +83,77 @@ struct ThreadData } }; -void* startThread(void* obj) -{ - ThreadData* data = static_cast(obj); +void *startThread(void *obj) { + ThreadData *data = static_cast(obj); data->runInThread(); delete data; return NULL; } -} // namespace detail +} // namespace detail -void CurrentThread::cacheTid() -{ - if (t_cachedTid == 0) - { +void CurrentThread::cacheTid() { + if (t_cachedTid == 0) { t_cachedTid = detail::gettid(); - t_tidStringLength = snprintf(t_tidString, sizeof t_tidString, "%5d ", t_cachedTid); + t_tidStringLength = + snprintf(t_tidString, sizeof t_tidString, "%5d ", t_cachedTid); } } -bool CurrentThread::isMainThread() -{ - return tid() == ::getpid(); -} +bool CurrentThread::isMainThread() { return tid() == ::getpid(); } -void CurrentThread::sleepUsec(int64_t usec) -{ - struct timespec ts = { 0, 0 }; +void CurrentThread::sleepUsec(int64_t usec) { + struct timespec ts = {0, 0}; ts.tv_sec = static_cast(usec / Timestamp::kMicroSecondsPerSecond); - ts.tv_nsec = static_cast(usec % Timestamp::kMicroSecondsPerSecond * 1000); + ts.tv_nsec = + static_cast(usec % Timestamp::kMicroSecondsPerSecond * 1000); ::nanosleep(&ts, NULL); } AtomicInt32 Thread::numCreated_; -Thread::Thread(ThreadFunc func, const string& n) - : started_(false), - joined_(false), - pthreadId_(0), - tid_(0), - func_(std::move(func)), - name_(n), - latch_(1) -{ +Thread::Thread(ThreadFunc func, const string &n) + : started_(false), joined_(false), pthreadId_(0), tid_(0), + func_(std::move(func)), name_(n), latch_(1) { setDefaultName(); } -Thread::~Thread() -{ - if (started_ && !joined_) - { +Thread::~Thread() { + if (started_ && !joined_) { pthread_detach(pthreadId_); } } -void Thread::setDefaultName() -{ +void Thread::setDefaultName() { int num = numCreated_.incrementAndGet(); - if (name_.empty()) - { + if (name_.empty()) { char buf[32]; snprintf(buf, sizeof buf, "Thread%d", num); name_ = buf; } } -void Thread::start() -{ +void Thread::start() { assert(!started_); started_ = true; // FIXME: move(func_) - detail::ThreadData* data = new detail::ThreadData(func_, name_, &tid_, &latch_); - if (pthread_create(&pthreadId_, NULL, &detail::startThread, data)) - { + detail::ThreadData *data = + new detail::ThreadData(func_, name_, &tid_, &latch_); + if (pthread_create(&pthreadId_, NULL, &detail::startThread, data)) { started_ = false; delete data; // or no delete? LOG_SYSFATAL << "Failed in pthread_create"; - } - else - { + } else { latch_.wait(); assert(tid_ > 0); } } -int Thread::join() -{ +int Thread::join() { assert(started_); assert(!joined_); joined_ = true; return pthread_join(pthreadId_, NULL); } -} // namespace muduo +} // namespace muduo diff --git a/muduo/base/Thread.h b/muduo/base/Thread.h index d2305a2c9..0235511b2 100644 --- a/muduo/base/Thread.h +++ b/muduo/base/Thread.h @@ -14,15 +14,13 @@ #include #include -namespace muduo -{ +namespace muduo { -class Thread : noncopyable -{ - public: - typedef std::function ThreadFunc; +class Thread : noncopyable { +public: + typedef std::function ThreadFunc; - explicit Thread(ThreadFunc, const string& name = string()); + explicit Thread(ThreadFunc, const string &name = string()); // FIXME: make it movable in C++11 ~Thread(); @@ -32,23 +30,23 @@ class Thread : noncopyable bool started() const { return started_; } // pthread_t pthreadId() const { return pthreadId_; } pid_t tid() const { return tid_; } - const string& name() const { return name_; } + const string &name() const { return name_; } static int numCreated() { return numCreated_.get(); } - private: +private: void setDefaultName(); - bool started_; - bool joined_; - pthread_t pthreadId_; - pid_t tid_; + bool started_; + bool joined_; + pthread_t pthreadId_; + pid_t tid_; ThreadFunc func_; - string name_; + string name_; CountDownLatch latch_; static AtomicInt32 numCreated_; }; -} // namespace muduo -#endif // MUDUO_BASE_THREAD_H +} // namespace muduo +#endif // MUDUO_BASE_THREAD_H diff --git a/muduo/base/ThreadLocal.h b/muduo/base/ThreadLocal.h index b8283bc3d..3a571ee95 100644 --- a/muduo/base/ThreadLocal.h +++ b/muduo/base/ThreadLocal.h @@ -11,49 +11,39 @@ #include -namespace muduo -{ - -template -class ThreadLocal : noncopyable -{ - public: - ThreadLocal() - { +namespace muduo { + +template class ThreadLocal : noncopyable { +public: + ThreadLocal() { MCHECK(pthread_key_create(&pkey_, &ThreadLocal::destructor)); } - ~ThreadLocal() - { - MCHECK(pthread_key_delete(pkey_)); - } + ~ThreadLocal() { MCHECK(pthread_key_delete(pkey_)); } - T& value() - { - T* perThreadValue = static_cast(pthread_getspecific(pkey_)); - if (!perThreadValue) - { - T* newObj = new T(); + T &value() { + T *perThreadValue = static_cast(pthread_getspecific(pkey_)); + if (!perThreadValue) { + T *newObj = new T(); MCHECK(pthread_setspecific(pkey_, newObj)); perThreadValue = newObj; } return *perThreadValue; } - private: - - static void destructor(void *x) - { - T* obj = static_cast(x); +private: + static void destructor(void *x) { + T *obj = static_cast(x); typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; - T_must_be_complete_type dummy; (void) dummy; + T_must_be_complete_type dummy; + (void)dummy; delete obj; } - private: +private: pthread_key_t pkey_; }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_THREADLOCAL_H +#endif // MUDUO_BASE_THREADLOCAL_H diff --git a/muduo/base/ThreadLocalSingleton.h b/muduo/base/ThreadLocalSingleton.h index 5c544dfc1..103109aa7 100644 --- a/muduo/base/ThreadLocalSingleton.h +++ b/muduo/base/ThreadLocalSingleton.h @@ -11,56 +11,40 @@ #include #include -namespace muduo -{ +namespace muduo { -template -class ThreadLocalSingleton : noncopyable -{ - public: +template class ThreadLocalSingleton : noncopyable { +public: ThreadLocalSingleton() = delete; ~ThreadLocalSingleton() = delete; - static T& instance() - { - if (!t_value_) - { + static T &instance() { + if (!t_value_) { t_value_ = new T(); deleter_.set(t_value_); } return *t_value_; } - static T* pointer() - { - return t_value_; - } + static T *pointer() { return t_value_; } - private: - static void destructor(void* obj) - { +private: + static void destructor(void *obj) { assert(obj == t_value_); typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1]; - T_must_be_complete_type dummy; (void) dummy; + T_must_be_complete_type dummy; + (void)dummy; delete t_value_; t_value_ = 0; } - class Deleter - { - public: - Deleter() - { - pthread_key_create(&pkey_, &ThreadLocalSingleton::destructor); - } + class Deleter { + public: + Deleter() { pthread_key_create(&pkey_, &ThreadLocalSingleton::destructor); } - ~Deleter() - { - pthread_key_delete(pkey_); - } + ~Deleter() { pthread_key_delete(pkey_); } - void set(T* newObj) - { + void set(T *newObj) { assert(pthread_getspecific(pkey_) == NULL); pthread_setspecific(pkey_, newObj); } @@ -68,15 +52,14 @@ class ThreadLocalSingleton : noncopyable pthread_key_t pkey_; }; - static __thread T* t_value_; + static __thread T *t_value_; static Deleter deleter_; }; -template -__thread T* ThreadLocalSingleton::t_value_ = 0; +template __thread T *ThreadLocalSingleton::t_value_ = 0; -template +template typename ThreadLocalSingleton::Deleter ThreadLocalSingleton::deleter_; -} // namespace muduo -#endif // MUDUO_BASE_THREADLOCALSINGLETON_H +} // namespace muduo +#endif // MUDUO_BASE_THREADLOCALSINGLETON_H diff --git a/muduo/base/ThreadPool.cc b/muduo/base/ThreadPool.cc index 6905dd7d5..f7b08e9fe 100644 --- a/muduo/base/ThreadPool.cc +++ b/muduo/base/ThreadPool.cc @@ -12,77 +12,59 @@ using namespace muduo; -ThreadPool::ThreadPool(const string& nameArg) - : mutex_(), - notEmpty_(mutex_), - notFull_(mutex_), - name_(nameArg), - maxQueueSize_(0), - running_(false) -{ -} +ThreadPool::ThreadPool(const string &nameArg) + : mutex_(), notEmpty_(mutex_), notFull_(mutex_), name_(nameArg), + maxQueueSize_(0), running_(false) {} -ThreadPool::~ThreadPool() -{ - if (running_) - { +ThreadPool::~ThreadPool() { + if (running_) { stop(); } } -void ThreadPool::start(int numThreads) -{ +void ThreadPool::start(int numThreads) { assert(threads_.empty()); running_ = true; threads_.reserve(numThreads); - for (int i = 0; i < numThreads; ++i) - { + for (int i = 0; i < numThreads; ++i) { char id[32]; - snprintf(id, sizeof id, "%d", i+1); + snprintf(id, sizeof id, "%d", i + 1); threads_.emplace_back(new muduo::Thread( - std::bind(&ThreadPool::runInThread, this), name_+id)); + std::bind(&ThreadPool::runInThread, this), name_ + id)); threads_[i]->start(); } - if (numThreads == 0 && threadInitCallback_) - { + if (numThreads == 0 && threadInitCallback_) { threadInitCallback_(); } } -void ThreadPool::stop() -{ +void ThreadPool::stop() { { - MutexLockGuard lock(mutex_); - running_ = false; - notEmpty_.notifyAll(); - notFull_.notifyAll(); + MutexLockGuard lock(mutex_); + running_ = false; + notEmpty_.notifyAll(); + notFull_.notifyAll(); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->join(); } } -size_t ThreadPool::queueSize() const -{ +size_t ThreadPool::queueSize() const { MutexLockGuard lock(mutex_); return queue_.size(); } -void ThreadPool::run(Task task) -{ - if (threads_.empty()) - { +void ThreadPool::run(Task task) { + if (threads_.empty()) { task(); - } - else - { + } else { MutexLockGuard lock(mutex_); - while (isFull() && running_) - { + while (isFull() && running_) { notFull_.wait(); } - if (!running_) return; + if (!running_) + return; assert(!isFull()); queue_.push_back(std::move(task)); @@ -90,67 +72,51 @@ void ThreadPool::run(Task task) } } -ThreadPool::Task ThreadPool::take() -{ +ThreadPool::Task ThreadPool::take() { MutexLockGuard lock(mutex_); // always use a while-loop, due to spurious wakeup - while (queue_.empty() && running_) - { + while (queue_.empty() && running_) { notEmpty_.wait(); } Task task; - if (!queue_.empty()) - { + if (!queue_.empty()) { task = queue_.front(); queue_.pop_front(); - if (maxQueueSize_ > 0) - { + if (maxQueueSize_ > 0) { notFull_.notify(); } } return task; } -bool ThreadPool::isFull() const -{ +bool ThreadPool::isFull() const { mutex_.assertLocked(); return maxQueueSize_ > 0 && queue_.size() >= maxQueueSize_; } -void ThreadPool::runInThread() -{ - try - { - if (threadInitCallback_) - { +void ThreadPool::runInThread() { + try { + if (threadInitCallback_) { threadInitCallback_(); } - while (running_) - { + while (running_) { Task task(take()); - if (task) - { + if (task) { task(); } } - } - catch (const Exception& ex) - { + } catch (const Exception &ex) { fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); fprintf(stderr, "stack trace: %s\n", ex.stackTrace()); abort(); - } - catch (const std::exception& ex) - { + } catch (const std::exception &ex) { fprintf(stderr, "exception caught in ThreadPool %s\n", name_.c_str()); fprintf(stderr, "reason: %s\n", ex.what()); abort(); - } - catch (...) - { - fprintf(stderr, "unknown exception caught in ThreadPool %s\n", name_.c_str()); + } catch (...) { + fprintf(stderr, "unknown exception caught in ThreadPool %s\n", + name_.c_str()); throw; // rethrow } } - diff --git a/muduo/base/ThreadPool.h b/muduo/base/ThreadPool.h index 385c1bbcc..5d80db700 100644 --- a/muduo/base/ThreadPool.h +++ b/muduo/base/ThreadPool.h @@ -14,27 +14,23 @@ #include #include -namespace muduo -{ +namespace muduo { -class ThreadPool : noncopyable -{ - public: - typedef std::function Task; +class ThreadPool : noncopyable { +public: + typedef std::function Task; - explicit ThreadPool(const string& nameArg = string("ThreadPool")); + explicit ThreadPool(const string &nameArg = string("ThreadPool")); ~ThreadPool(); // Must be called before start(). void setMaxQueueSize(int maxSize) { maxQueueSize_ = maxSize; } - void setThreadInitCallback(const Task& cb) - { threadInitCallback_ = cb; } + void setThreadInitCallback(const Task &cb) { threadInitCallback_ = cb; } void start(int numThreads); void stop(); - const string& name() const - { return name_; } + const string &name() const { return name_; } size_t queueSize() const; @@ -46,7 +42,7 @@ class ThreadPool : noncopyable // https://stackoverflow.com/a/25408989 void run(Task f); - private: +private: bool isFull() const REQUIRES(mutex_); void runInThread(); Task take(); @@ -62,6 +58,6 @@ class ThreadPool : noncopyable bool running_; }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_THREADPOOL_H +#endif // MUDUO_BASE_THREADPOOL_H diff --git a/muduo/base/TimeZone.cc b/muduo/base/TimeZone.cc index 954438539..ec277b95b 100644 --- a/muduo/base/TimeZone.cc +++ b/muduo/base/TimeZone.cc @@ -4,8 +4,8 @@ // Author: Shuo Chen (chenshuo at chenshuo dot com) #include "muduo/base/TimeZone.h" -#include "muduo/base/noncopyable.h" #include "muduo/base/Date.h" +#include "muduo/base/noncopyable.h" #include #include @@ -19,42 +19,31 @@ #include #include -namespace muduo -{ -namespace detail -{ +namespace muduo { +namespace detail { -struct Transition -{ +struct Transition { time_t gmttime; time_t localtime; int localtimeIdx; Transition(time_t t, time_t l, int localIdx) - : gmttime(t), localtime(l), localtimeIdx(localIdx) - { } - + : gmttime(t), localtime(l), localtimeIdx(localIdx) {} }; -struct Comp -{ +struct Comp { bool compareGmt; - Comp(bool gmt) - : compareGmt(gmt) - { - } + Comp(bool gmt) : compareGmt(gmt) {} - bool operator()(const Transition& lhs, const Transition& rhs) const - { + bool operator()(const Transition &lhs, const Transition &rhs) const { if (compareGmt) return lhs.gmttime < rhs.gmttime; else return lhs.localtime < rhs.localtime; } - bool equal(const Transition& lhs, const Transition& rhs) const - { + bool equal(const Transition &lhs, const Transition &rhs) const { if (compareGmt) return lhs.gmttime == rhs.gmttime; else @@ -62,65 +51,52 @@ struct Comp } }; -struct Localtime -{ +struct Localtime { time_t gmtOffset; bool isDst; int arrbIdx; Localtime(time_t offset, bool dst, int arrb) - : gmtOffset(offset), isDst(dst), arrbIdx(arrb) - { } + : gmtOffset(offset), isDst(dst), arrbIdx(arrb) {} }; -inline void fillHMS(unsigned seconds, struct tm* utc) -{ +inline void fillHMS(unsigned seconds, struct tm *utc) { utc->tm_sec = seconds % 60; unsigned minutes = seconds / 60; utc->tm_min = minutes % 60; utc->tm_hour = minutes / 60; } -} // namespace detail -const int kSecondsPerDay = 24*60*60; -} // namespace muduo +} // namespace detail +const int kSecondsPerDay = 24 * 60 * 60; +} // namespace muduo using namespace muduo; using namespace std; -struct TimeZone::Data -{ +struct TimeZone::Data { vector transitions; vector localtimes; vector names; string abbreviation; }; -namespace muduo -{ -namespace detail -{ - -class File : noncopyable -{ - public: - File(const char* file) - : fp_(::fopen(file, "rb")) - { - } +namespace muduo { +namespace detail { + +class File : noncopyable { +public: + File(const char *file) : fp_(::fopen(file, "rb")) {} - ~File() - { - if (fp_) - { + ~File() { + if (fp_) { ::fclose(fp_); } } bool valid() const { return fp_; } - string readBytes(int n) - { + string readBytes(int n) { char buf[n]; ssize_t nr = ::fread(buf, 1, n, fp_); if (nr != n) @@ -128,8 +104,7 @@ class File : noncopyable return string(buf, n); } - int32_t readInt32() - { + int32_t readInt32() { int32_t x = 0; ssize_t nr = ::fread(&x, 1, sizeof(int32_t), fp_); if (nr != sizeof(int32_t)) @@ -137,8 +112,7 @@ class File : noncopyable return be32toh(x); } - uint8_t readUInt8() - { + uint8_t readUInt8() { uint8_t x = 0; ssize_t nr = ::fread(&x, 1, sizeof(uint8_t), fp_); if (nr != sizeof(uint8_t)) @@ -146,17 +120,14 @@ class File : noncopyable return x; } - private: - FILE* fp_; +private: + FILE *fp_; }; -bool readTimeZoneFile(const char* zonefile, struct TimeZone::Data* data) -{ +bool readTimeZoneFile(const char *zonefile, struct TimeZone::Data *data) { File f(zonefile); - if (f.valid()) - { - try - { + if (f.valid()) { + try { string head = f.readBytes(4); if (head != "TZif") throw logic_error("bad head"); @@ -173,19 +144,16 @@ bool readTimeZoneFile(const char* zonefile, struct TimeZone::Data* data) vector trans; vector localtimes; trans.reserve(timecnt); - for (int i = 0; i < timecnt; ++i) - { + for (int i = 0; i < timecnt; ++i) { trans.push_back(f.readInt32()); } - for (int i = 0; i < timecnt; ++i) - { + for (int i = 0; i < timecnt; ++i) { uint8_t local = f.readUInt8(); localtimes.push_back(local); } - for (int i = 0; i < typecnt; ++i) - { + for (int i = 0; i < typecnt; ++i) { int32_t gmtoff = f.readInt32(); uint8_t isdst = f.readUInt8(); uint8_t abbrind = f.readUInt8(); @@ -193,8 +161,7 @@ bool readTimeZoneFile(const char* zonefile, struct TimeZone::Data* data) data->localtimes.push_back(Localtime(gmtoff, isdst, abbrind)); } - for (int i = 0; i < timecnt; ++i) - { + for (int i = 0; i < timecnt; ++i) { int localIdx = localtimes[i]; time_t localtime = trans[i] + data->localtimes[localIdx].gmtOffset; data->transitions.push_back(Transition(trans[i], localtime, localIdx)); @@ -203,49 +170,37 @@ bool readTimeZoneFile(const char* zonefile, struct TimeZone::Data* data) data->abbreviation = f.readBytes(charcnt); // leapcnt - for (int i = 0; i < leapcnt; ++i) - { + for (int i = 0; i < leapcnt; ++i) { // int32_t leaptime = f.readInt32(); // int32_t cumleap = f.readInt32(); } // FIXME - (void) isstdcnt; - (void) isgmtcnt; - } - catch (logic_error& e) - { + (void)isstdcnt; + (void)isgmtcnt; + } catch (logic_error &e) { fprintf(stderr, "%s\n", e.what()); } } return true; } -const Localtime* findLocaltime(const TimeZone::Data& data, Transition sentry, Comp comp) -{ - const Localtime* local = NULL; +const Localtime *findLocaltime(const TimeZone::Data &data, Transition sentry, + Comp comp) { + const Localtime *local = NULL; - if (data.transitions.empty() || comp(sentry, data.transitions.front())) - { + if (data.transitions.empty() || comp(sentry, data.transitions.front())) { // FIXME: should be first non dst time zone local = &data.localtimes.front(); - } - else - { - vector::const_iterator transI = lower_bound(data.transitions.begin(), - data.transitions.end(), - sentry, - comp); - if (transI != data.transitions.end()) - { - if (!comp.equal(sentry, *transI)) - { + } else { + vector::const_iterator transI = lower_bound( + data.transitions.begin(), data.transitions.end(), sentry, comp); + if (transI != data.transitions.end()) { + if (!comp.equal(sentry, *transI)) { assert(transI != data.transitions.begin()); --transI; } local = &data.localtimes[transI->localtimeIdx]; - } - else - { + } else { // FIXME: use TZ-env local = &data.localtimes[data.transitions.back().localtimeIdx]; } @@ -254,38 +209,32 @@ const Localtime* findLocaltime(const TimeZone::Data& data, Transition sentry, Co return local; } -} // namespace detail -} // namespace muduo - +} // namespace detail +} // namespace muduo -TimeZone::TimeZone(const char* zonefile) - : data_(new TimeZone::Data) -{ - if (!detail::readTimeZoneFile(zonefile, data_.get())) - { +TimeZone::TimeZone(const char *zonefile) : data_(new TimeZone::Data) { + if (!detail::readTimeZoneFile(zonefile, data_.get())) { data_.reset(); } } -TimeZone::TimeZone(int eastOfUtc, const char* name) - : data_(new TimeZone::Data) -{ +TimeZone::TimeZone(int eastOfUtc, const char *name) + : data_(new TimeZone::Data) { data_->localtimes.push_back(detail::Localtime(eastOfUtc, false, 0)); data_->abbreviation = name; } -struct tm TimeZone::toLocalTime(time_t seconds) const -{ +struct tm TimeZone::toLocalTime(time_t seconds) const { struct tm localTime; memZero(&localTime, sizeof(localTime)); assert(data_ != NULL); - const Data& data(*data_); + const Data &data(*data_); detail::Transition sentry(seconds, 0, 0); - const detail::Localtime* local = findLocaltime(data, sentry, detail::Comp(true)); + const detail::Localtime *local = + findLocaltime(data, sentry, detail::Comp(true)); - if (local) - { + if (local) { time_t localSeconds = seconds + local->gmtOffset; ::gmtime_r(&localSeconds, &localTime); // FIXME: fromUtcTime localTime.tm_isdst = local->isDst; @@ -296,22 +245,19 @@ struct tm TimeZone::toLocalTime(time_t seconds) const return localTime; } -time_t TimeZone::fromLocalTime(const struct tm& localTm) const -{ +time_t TimeZone::fromLocalTime(const struct tm &localTm) const { assert(data_ != NULL); - const Data& data(*data_); + const Data &data(*data_); struct tm tmp = localTm; time_t seconds = ::timegm(&tmp); // FIXME: toUtcTime detail::Transition sentry(0, seconds, 0); - const detail::Localtime* local = findLocaltime(data, sentry, detail::Comp(false)); - if (localTm.tm_isdst) - { + const detail::Localtime *local = + findLocaltime(data, sentry, detail::Comp(false)); + if (localTm.tm_isdst) { struct tm tryTm = toLocalTime(seconds - local->gmtOffset); - if (!tryTm.tm_isdst - && tryTm.tm_hour == localTm.tm_hour - && tryTm.tm_min == localTm.tm_min) - { + if (!tryTm.tm_isdst && tryTm.tm_hour == localTm.tm_hour && + tryTm.tm_min == localTm.tm_min) { // FIXME: HACK seconds -= 3600; } @@ -319,15 +265,13 @@ time_t TimeZone::fromLocalTime(const struct tm& localTm) const return seconds - local->gmtOffset; } -struct tm TimeZone::toUtcTime(time_t secondsSinceEpoch, bool yday) -{ +struct tm TimeZone::toUtcTime(time_t secondsSinceEpoch, bool yday) { struct tm utc; memZero(&utc, sizeof(utc)); utc.tm_zone = "GMT"; int seconds = static_cast(secondsSinceEpoch % kSecondsPerDay); int days = static_cast(secondsSinceEpoch / kSecondsPerDay); - if (seconds < 0) - { + if (seconds < 0) { seconds += kSecondsPerDay; --days; } @@ -339,23 +283,20 @@ struct tm TimeZone::toUtcTime(time_t secondsSinceEpoch, bool yday) utc.tm_mday = ymd.day; utc.tm_wday = date.weekDay(); - if (yday) - { + if (yday) { Date startOfYear(ymd.year, 1, 1); utc.tm_yday = date.julianDayNumber() - startOfYear.julianDayNumber(); } return utc; } -time_t TimeZone::fromUtcTime(const struct tm& utc) -{ +time_t TimeZone::fromUtcTime(const struct tm &utc) { return fromUtcTime(utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec); } -time_t TimeZone::fromUtcTime(int year, int month, int day, - int hour, int minute, int seconds) -{ +time_t TimeZone::fromUtcTime(int year, int month, int day, int hour, int minute, + int seconds) { Date date(year, month, day); int secondsInDay = hour * 3600 + minute * 60 + seconds; time_t days = date.julianDayNumber() - Date::kJulianDayOf1970_01_01; diff --git a/muduo/base/TimeZone.h b/muduo/base/TimeZone.h index 6586630d8..ce113358a 100644 --- a/muduo/base/TimeZone.h +++ b/muduo/base/TimeZone.h @@ -10,43 +10,39 @@ #include #include -namespace muduo -{ +namespace muduo { // TimeZone for 1970~2030 -class TimeZone : public muduo::copyable -{ - public: - explicit TimeZone(const char* zonefile); - TimeZone(int eastOfUtc, const char* tzname); // a fixed timezone - TimeZone() = default; // an invalid timezone +class TimeZone : public muduo::copyable { +public: + explicit TimeZone(const char *zonefile); + TimeZone(int eastOfUtc, const char *tzname); // a fixed timezone + TimeZone() = default; // an invalid timezone // default copy ctor/assignment/dtor are Okay. - bool valid() const - { + bool valid() const { // 'explicit operator bool() const' in C++11 return static_cast(data_); } struct tm toLocalTime(time_t secondsSinceEpoch) const; - time_t fromLocalTime(const struct tm&) const; + time_t fromLocalTime(const struct tm &) const; // gmtime(3) static struct tm toUtcTime(time_t secondsSinceEpoch, bool yday = false); // timegm(3) - static time_t fromUtcTime(const struct tm&); + static time_t fromUtcTime(const struct tm &); // year in [1900..2500], month in [1..12], day in [1..31] - static time_t fromUtcTime(int year, int month, int day, - int hour, int minute, int seconds); + static time_t fromUtcTime(int year, int month, int day, int hour, int minute, + int seconds); struct Data; - private: - +private: std::shared_ptr data_; }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_TIMEZONE_H +#endif // MUDUO_BASE_TIMEZONE_H diff --git a/muduo/base/Timestamp.cc b/muduo/base/Timestamp.cc index fc0ed7016..abee83d09 100644 --- a/muduo/base/Timestamp.cc +++ b/muduo/base/Timestamp.cc @@ -5,8 +5,8 @@ #include "muduo/base/Timestamp.h" -#include #include +#include #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS @@ -19,32 +19,29 @@ using namespace muduo; static_assert(sizeof(Timestamp) == sizeof(int64_t), "Timestamp should be same size as int64_t"); -string Timestamp::toString() const -{ +string Timestamp::toString() const { char buf[32] = {0}; int64_t seconds = microSecondsSinceEpoch_ / kMicroSecondsPerSecond; int64_t microseconds = microSecondsSinceEpoch_ % kMicroSecondsPerSecond; - snprintf(buf, sizeof(buf), "%" PRId64 ".%06" PRId64 "", seconds, microseconds); + snprintf(buf, sizeof(buf), "%" PRId64 ".%06" PRId64 "", seconds, + microseconds); return buf; } -string Timestamp::toFormattedString(bool showMicroseconds) const -{ +string Timestamp::toFormattedString(bool showMicroseconds) const { char buf[64] = {0}; - time_t seconds = static_cast(microSecondsSinceEpoch_ / kMicroSecondsPerSecond); + time_t seconds = + static_cast(microSecondsSinceEpoch_ / kMicroSecondsPerSecond); struct tm tm_time; gmtime_r(&seconds, &tm_time); - if (showMicroseconds) - { - int microseconds = static_cast(microSecondsSinceEpoch_ % kMicroSecondsPerSecond); + if (showMicroseconds) { + int microseconds = + static_cast(microSecondsSinceEpoch_ % kMicroSecondsPerSecond); snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d", tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday, - tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, - microseconds); - } - else - { + tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec, microseconds); + } else { snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d", tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday, tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec); @@ -52,11 +49,9 @@ string Timestamp::toFormattedString(bool showMicroseconds) const return buf; } -Timestamp Timestamp::now() -{ +Timestamp Timestamp::now() { struct timeval tv; gettimeofday(&tv, NULL); int64_t seconds = tv.tv_sec; return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec); } - diff --git a/muduo/base/Timestamp.h b/muduo/base/Timestamp.h index ccb522d3c..8d0fa58a5 100644 --- a/muduo/base/Timestamp.h +++ b/muduo/base/Timestamp.h @@ -6,13 +6,12 @@ #ifndef MUDUO_BASE_TIMESTAMP_H #define MUDUO_BASE_TIMESTAMP_H -#include "muduo/base/copyable.h" #include "muduo/base/Types.h" +#include "muduo/base/copyable.h" #include -namespace muduo -{ +namespace muduo { /// /// Time stamp in UTC, in microseconds resolution. @@ -22,28 +21,21 @@ namespace muduo /// class Timestamp : public muduo::copyable, public boost::equality_comparable, - public boost::less_than_comparable -{ - public: + public boost::less_than_comparable { +public: /// /// Constucts an invalid Timestamp. /// - Timestamp() - : microSecondsSinceEpoch_(0) - { - } + Timestamp() : microSecondsSinceEpoch_(0) {} /// /// Constucts a Timestamp at specific time /// /// @param microSecondsSinceEpoch explicit Timestamp(int64_t microSecondsSinceEpochArg) - : microSecondsSinceEpoch_(microSecondsSinceEpochArg) - { - } + : microSecondsSinceEpoch_(microSecondsSinceEpochArg) {} - void swap(Timestamp& that) - { + void swap(Timestamp &that) { std::swap(microSecondsSinceEpoch_, that.microSecondsSinceEpoch_); } @@ -56,41 +48,35 @@ class Timestamp : public muduo::copyable, // for internal usage. int64_t microSecondsSinceEpoch() const { return microSecondsSinceEpoch_; } - time_t secondsSinceEpoch() const - { return static_cast(microSecondsSinceEpoch_ / kMicroSecondsPerSecond); } + time_t secondsSinceEpoch() const { + return static_cast(microSecondsSinceEpoch_ / + kMicroSecondsPerSecond); + } /// /// Get time of now. /// static Timestamp now(); - static Timestamp invalid() - { - return Timestamp(); - } + static Timestamp invalid() { return Timestamp(); } - static Timestamp fromUnixTime(time_t t) - { - return fromUnixTime(t, 0); - } + static Timestamp fromUnixTime(time_t t) { return fromUnixTime(t, 0); } - static Timestamp fromUnixTime(time_t t, int microseconds) - { - return Timestamp(static_cast(t) * kMicroSecondsPerSecond + microseconds); + static Timestamp fromUnixTime(time_t t, int microseconds) { + return Timestamp(static_cast(t) * kMicroSecondsPerSecond + + microseconds); } static const int kMicroSecondsPerSecond = 1000 * 1000; - private: +private: int64_t microSecondsSinceEpoch_; }; -inline bool operator<(Timestamp lhs, Timestamp rhs) -{ +inline bool operator<(Timestamp lhs, Timestamp rhs) { return lhs.microSecondsSinceEpoch() < rhs.microSecondsSinceEpoch(); } -inline bool operator==(Timestamp lhs, Timestamp rhs) -{ +inline bool operator==(Timestamp lhs, Timestamp rhs) { return lhs.microSecondsSinceEpoch() == rhs.microSecondsSinceEpoch(); } @@ -101,8 +87,7 @@ inline bool operator==(Timestamp lhs, Timestamp rhs) /// @return (high-low) in seconds /// @c double has 52-bit precision, enough for one-microsecond /// resolution for next 100 years. -inline double timeDifference(Timestamp high, Timestamp low) -{ +inline double timeDifference(Timestamp high, Timestamp low) { int64_t diff = high.microSecondsSinceEpoch() - low.microSecondsSinceEpoch(); return static_cast(diff) / Timestamp::kMicroSecondsPerSecond; } @@ -112,12 +97,12 @@ inline double timeDifference(Timestamp high, Timestamp low) /// /// @return timestamp+seconds as Timestamp /// -inline Timestamp addTime(Timestamp timestamp, double seconds) -{ - int64_t delta = static_cast(seconds * Timestamp::kMicroSecondsPerSecond); +inline Timestamp addTime(Timestamp timestamp, double seconds) { + int64_t delta = + static_cast(seconds * Timestamp::kMicroSecondsPerSecond); return Timestamp(timestamp.microSecondsSinceEpoch() + delta); } -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_TIMESTAMP_H +#endif // MUDUO_BASE_TIMESTAMP_H diff --git a/muduo/base/Types.h b/muduo/base/Types.h index ad94756c8..9869196eb 100644 --- a/muduo/base/Types.h +++ b/muduo/base/Types.h @@ -2,7 +2,7 @@ #define MUDUO_BASE_TYPES_H #include -#include // memset +#include // memset #include #ifndef NDEBUG @@ -12,15 +12,11 @@ /// /// The most common stuffs. /// -namespace muduo -{ +namespace muduo { using std::string; -inline void memZero(void* p, size_t n) -{ - memset(p, 0, n); -} +inline void memZero(void *p, size_t n) { memset(p, 0, n); } // Taken from google-protobuf stubs/common.h // @@ -76,9 +72,7 @@ inline void memZero(void* p, size_t n) // implicit_cast would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. -template -inline To implicit_cast(From const &f) -{ +template inline To implicit_cast(From const &f) { return f; } @@ -100,24 +94,23 @@ inline To implicit_cast(From const &f) // if (dynamic_cast(foo)) HandleASubclass2Object(foo); // You should design the code some other way not to need this. -template // use like this: down_cast(foo); -inline To down_cast(From* f) // so we only accept pointers +template // use like this: down_cast(foo); +inline To down_cast(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. - if (false) - { - implicit_cast(0); + if (false) { + implicit_cast(0); } #if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI) - assert(f == NULL || dynamic_cast(f) != NULL); // RTTI: debug mode only! + assert(f == NULL || dynamic_cast(f) != NULL); // RTTI: debug mode only! #endif return static_cast(f); } -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_TYPES_H +#endif // MUDUO_BASE_TYPES_H diff --git a/muduo/base/WeakCallback.h b/muduo/base/WeakCallback.h index 5e4650cb2..b129e6f0b 100644 --- a/muduo/base/WeakCallback.h +++ b/muduo/base/WeakCallback.h @@ -9,29 +9,21 @@ #include #include -namespace muduo -{ +namespace muduo { // A barely usable WeakCallback -template -class WeakCallback -{ - public: - - WeakCallback(const std::weak_ptr& object, - const std::function& function) - : object_(object), function_(function) - { - } +template class WeakCallback { +public: + WeakCallback(const std::weak_ptr &object, + const std::function &function) + : object_(object), function_(function) {} // Default dtor, copy ctor and assignment are okay - void operator()(ARGS&&... args) const - { + void operator()(ARGS &&...args) const { std::shared_ptr ptr(object_.lock()); - if (ptr) - { + if (ptr) { function_(ptr.get(), std::forward(args)...); } // else @@ -40,26 +32,25 @@ class WeakCallback // } } - private: - +private: std::weak_ptr object_; - std::function function_; + std::function function_; }; -template -WeakCallback makeWeakCallback(const std::shared_ptr& object, - void (CLASS::*function)(ARGS...)) -{ +template +WeakCallback +makeWeakCallback(const std::shared_ptr &object, + void (CLASS::*function)(ARGS...)) { return WeakCallback(object, function); } -template -WeakCallback makeWeakCallback(const std::shared_ptr& object, - void (CLASS::*function)(ARGS...) const) -{ +template +WeakCallback +makeWeakCallback(const std::shared_ptr &object, + void (CLASS::*function)(ARGS...) const) { return WeakCallback(object, function); } -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_WEAKCALLBACK_H +#endif // MUDUO_BASE_WEAKCALLBACK_H diff --git a/muduo/base/copyable.h b/muduo/base/copyable.h index 352b2878a..29e1d7e13 100644 --- a/muduo/base/copyable.h +++ b/muduo/base/copyable.h @@ -1,19 +1,17 @@ #ifndef MUDUO_BASE_COPYABLE_H #define MUDUO_BASE_COPYABLE_H -namespace muduo -{ +namespace muduo { /// A tag class emphasises the objects are copyable. /// The empty base class optimization applies. /// Any derived class of copyable should be a value type. -class copyable -{ - protected: +class copyable { +protected: copyable() = default; ~copyable() = default; }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_COPYABLE_H +#endif // MUDUO_BASE_COPYABLE_H diff --git a/muduo/base/noncopyable.h b/muduo/base/noncopyable.h index 79931f9be..9549c0574 100644 --- a/muduo/base/noncopyable.h +++ b/muduo/base/noncopyable.h @@ -1,20 +1,18 @@ #ifndef MUDUO_BASE_NONCOPYABLE_H #define MUDUO_BASE_NONCOPYABLE_H -namespace muduo -{ +namespace muduo { -class noncopyable -{ - public: - noncopyable(const noncopyable&) = delete; - void operator=(const noncopyable&) = delete; +class noncopyable { +public: + noncopyable(const noncopyable &) = delete; + void operator=(const noncopyable &) = delete; - protected: +protected: noncopyable() = default; ~noncopyable() = default; }; -} // namespace muduo +} // namespace muduo -#endif // MUDUO_BASE_NONCOPYABLE_H +#endif // MUDUO_BASE_NONCOPYABLE_H diff --git a/muduo/base/tests/AsyncLogging_test.cc b/muduo/base/tests/AsyncLogging_test.cc index ad6fde4ab..de92ad23f 100644 --- a/muduo/base/tests/AsyncLogging_test.cc +++ b/muduo/base/tests/AsyncLogging_test.cc @@ -6,17 +6,13 @@ #include #include -off_t kRollSize = 500*1000*1000; +off_t kRollSize = 500 * 1000 * 1000; -muduo::AsyncLogging* g_asyncLog = NULL; +muduo::AsyncLogging *g_asyncLog = NULL; -void asyncOutput(const char* msg, int len) -{ - g_asyncLog->append(msg, len); -} +void asyncOutput(const char *msg, int len) { g_asyncLog->append(msg, len); } -void bench(bool longLog) -{ +void bench(bool longLog) { muduo::Logger::setOutput(asyncOutput); int cnt = 0; @@ -25,35 +21,32 @@ void bench(bool longLog) muduo::string longStr(3000, 'X'); longStr += " "; - for (int t = 0; t < 30; ++t) - { + for (int t = 0; t < 30; ++t) { muduo::Timestamp start = muduo::Timestamp::now(); - for (int i = 0; i < kBatch; ++i) - { - LOG_INFO << "Hello 0123456789" << " abcdefghijklmnopqrstuvwxyz " - << (longLog ? longStr : empty) + for (int i = 0; i < kBatch; ++i) { + LOG_INFO << "Hello 0123456789" + << " abcdefghijklmnopqrstuvwxyz " << (longLog ? longStr : empty) << cnt; ++cnt; } muduo::Timestamp end = muduo::Timestamp::now(); - printf("%f\n", timeDifference(end, start)*1000000/kBatch); - struct timespec ts = { 0, 500*1000*1000 }; + printf("%f\n", timeDifference(end, start) * 1000000 / kBatch); + struct timespec ts = {0, 500 * 1000 * 1000}; nanosleep(&ts, NULL); } } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { { // set max virtual memory to 2GB. - size_t kOneGB = 1000*1024*1024; - rlimit rl = { 2*kOneGB, 2*kOneGB }; + size_t kOneGB = 1000 * 1024 * 1024; + rlimit rl = {2 * kOneGB, 2 * kOneGB}; setrlimit(RLIMIT_AS, &rl); } printf("pid = %d\n", getpid()); - char name[256] = { '\0' }; + char name[256] = {'\0'}; strncpy(name, argv[0], sizeof name - 1); muduo::AsyncLogging log(::basename(name), kRollSize); log.start(); diff --git a/muduo/base/tests/Atomic_unittest.cc b/muduo/base/tests/Atomic_unittest.cc index 11d610702..2d7bec0a6 100644 --- a/muduo/base/tests/Atomic_unittest.cc +++ b/muduo/base/tests/Atomic_unittest.cc @@ -1,38 +1,36 @@ #include "muduo/base/Atomic.h" #include -int main() -{ +int main() { { - muduo::AtomicInt64 a0; - assert(a0.get() == 0); - assert(a0.getAndAdd(1) == 0); - assert(a0.get() == 1); - assert(a0.addAndGet(2) == 3); - assert(a0.get() == 3); - assert(a0.incrementAndGet() == 4); - assert(a0.get() == 4); - a0.increment(); - assert(a0.get() == 5); - assert(a0.addAndGet(-3) == 2); - assert(a0.getAndSet(100) == 2); - assert(a0.get() == 100); + muduo::AtomicInt64 a0; + assert(a0.get() == 0); + assert(a0.getAndAdd(1) == 0); + assert(a0.get() == 1); + assert(a0.addAndGet(2) == 3); + assert(a0.get() == 3); + assert(a0.incrementAndGet() == 4); + assert(a0.get() == 4); + a0.increment(); + assert(a0.get() == 5); + assert(a0.addAndGet(-3) == 2); + assert(a0.getAndSet(100) == 2); + assert(a0.get() == 100); } { - muduo::AtomicInt32 a1; - assert(a1.get() == 0); - assert(a1.getAndAdd(1) == 0); - assert(a1.get() == 1); - assert(a1.addAndGet(2) == 3); - assert(a1.get() == 3); - assert(a1.incrementAndGet() == 4); - assert(a1.get() == 4); - a1.increment(); - assert(a1.get() == 5); - assert(a1.addAndGet(-3) == 2); - assert(a1.getAndSet(100) == 2); - assert(a1.get() == 100); + muduo::AtomicInt32 a1; + assert(a1.get() == 0); + assert(a1.getAndAdd(1) == 0); + assert(a1.get() == 1); + assert(a1.addAndGet(2) == 3); + assert(a1.get() == 3); + assert(a1.incrementAndGet() == 4); + assert(a1.get() == 4); + a1.increment(); + assert(a1.get() == 5); + assert(a1.addAndGet(-3) == 2); + assert(a1.getAndSet(100) == 2); + assert(a1.get() == 100); } } - diff --git a/muduo/base/tests/BlockingQueue_bench.cc b/muduo/base/tests/BlockingQueue_bench.cc index 6901063da..23f23702d 100644 --- a/muduo/base/tests/BlockingQueue_bench.cc +++ b/muduo/base/tests/BlockingQueue_bench.cc @@ -5,42 +5,35 @@ #include "muduo/base/Timestamp.h" #include -#include -#include #include +#include #include +#include bool g_verbose = false; // Many threads, one queue. -class Bench -{ - public: - Bench(int numThreads) - : latch_(numThreads) - { +class Bench { +public: + Bench(int numThreads) : latch_(numThreads) { threads_.reserve(numThreads); - for (int i = 0; i < numThreads; ++i) - { + for (int i = 0; i < numThreads; ++i) { char name[32]; snprintf(name, sizeof name, "work thread %d", i); threads_.emplace_back(new muduo::Thread( - std::bind(&Bench::threadFunc, this), muduo::string(name))); + std::bind(&Bench::threadFunc, this), muduo::string(name))); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->start(); } } - void run(int times) - { + void run(int times) { printf("waiting for count down latch\n"); latch_.wait(); LOG_INFO << threads_.size() << " threads started"; int64_t total_delay = 0; - for (int i = 0; i < times; ++i) - { + for (int i = 0; i < times; ++i) { muduo::Timestamp now(muduo::Timestamp::now()); queue_.put(now); total_delay += delay_queue_.take(); @@ -48,39 +41,31 @@ class Bench printf("Average delay: %.3fus\n", static_cast(total_delay) / times); } - void joinAll() - { - for (size_t i = 0; i < threads_.size(); ++i) - { + void joinAll() { + for (size_t i = 0; i < threads_.size(); ++i) { queue_.put(muduo::Timestamp::invalid()); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->join(); } LOG_INFO << threads_.size() << " threads stopped"; } - private: - - void threadFunc() - { +private: + void threadFunc() { if (g_verbose) { - printf("tid=%d, %s started\n", - muduo::CurrentThread::tid(), - muduo::CurrentThread::name()); + printf("tid=%d, %s started\n", muduo::CurrentThread::tid(), + muduo::CurrentThread::name()); } std::map delays; latch_.countDown(); bool running = true; - while (running) - { + while (running) { muduo::Timestamp t(queue_.take()); muduo::Timestamp now(muduo::Timestamp::now()); - if (t.valid()) - { + if (t.valid()) { int delay = static_cast(timeDifference(now, t) * 1000000); // printf("tid=%d, latency = %d us\n", // muduo::CurrentThread::tid(), delay); @@ -90,16 +75,12 @@ class Bench running = t.valid(); } - if (g_verbose) - { - printf("tid=%d, %s stopped\n", - muduo::CurrentThread::tid(), + if (g_verbose) { + printf("tid=%d, %s stopped\n", muduo::CurrentThread::tid(), muduo::CurrentThread::name()); - for (const auto& delay : delays) - { + for (const auto &delay : delays) { printf("tid = %d, delay = %d, count = %d\n", - muduo::CurrentThread::tid(), - delay.first, delay.second); + muduo::CurrentThread::tid(), delay.first, delay.second); } } } @@ -110,8 +91,7 @@ class Bench std::vector> threads_; }; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { int threads = argc > 1 ? atoi(argv[1]) : 1; Bench t(threads); diff --git a/muduo/base/tests/BlockingQueue_bench2.cc b/muduo/base/tests/BlockingQueue_bench2.cc index 98b8ab6ba..3d6b84951 100644 --- a/muduo/base/tests/BlockingQueue_bench2.cc +++ b/muduo/base/tests/BlockingQueue_bench2.cc @@ -4,97 +4,81 @@ #include "muduo/base/Timestamp.h" #include -#include -#include #include +#include #include +#include // hot potato benchmarking https://en.wikipedia.org/wiki/Hot_potato // N threads, one hot potato. -class Bench -{ - public: - Bench(int numThreads) - : startLatch_(numThreads), - stopLatch_(1) - { +class Bench { +public: + Bench(int numThreads) : startLatch_(numThreads), stopLatch_(1) { queues_.reserve(numThreads); threads_.reserve(numThreads); - for (int i = 0; i < numThreads; ++i) - { + for (int i = 0; i < numThreads; ++i) { queues_.emplace_back(new muduo::BlockingQueue()); char name[32]; snprintf(name, sizeof name, "work thread %d", i); - threads_.emplace_back(new muduo::Thread( - [this, i] { threadFunc(i); }, - muduo::string(name))); + threads_.emplace_back( + new muduo::Thread([this, i] { threadFunc(i); }, muduo::string(name))); } } - void Start() - { + void Start() { muduo::Timestamp start = muduo::Timestamp::now(); - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->start(); } startLatch_.wait(); muduo::Timestamp started = muduo::Timestamp::now(); - printf("all %zd threads started, %.3fms\n", - threads_.size(), 1e3 * timeDifference(started, start)); + printf("all %zd threads started, %.3fms\n", threads_.size(), + 1e3 * timeDifference(started, start)); } - void Run() - { + void Run() { muduo::Timestamp start = muduo::Timestamp::now(); const int rounds = 100003; queues_[0]->put(rounds); auto done = done_.take(); double elapsed = timeDifference(done.second, start); - printf("thread id=%d done, total %.3fms, %.3fus / round\n", - done.first, 1e3 * elapsed, 1e6 * elapsed / rounds); + printf("thread id=%d done, total %.3fms, %.3fus / round\n", done.first, + 1e3 * elapsed, 1e6 * elapsed / rounds); } - void Stop() - { + void Stop() { muduo::Timestamp stop = muduo::Timestamp::now(); - for (const auto& queue : queues_) - { + for (const auto &queue : queues_) { queue->put(-1); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->join(); } muduo::Timestamp t2 = muduo::Timestamp::now(); - printf("all %zd threads joined, %.3fms\n", - threads_.size(), 1e3 * timeDifference(t2, stop)); + printf("all %zd threads joined, %.3fms\n", threads_.size(), + 1e3 * timeDifference(t2, stop)); } - private: - void threadFunc(int id) - { +private: + void threadFunc(int id) { startLatch_.countDown(); - muduo::BlockingQueue* input = queues_[id].get(); - muduo::BlockingQueue* output = queues_[(id+1) % queues_.size()].get(); - while (true) - { + muduo::BlockingQueue *input = queues_[id].get(); + muduo::BlockingQueue *output = + queues_[(id + 1) % queues_.size()].get(); + while (true) { int value = input->take(); - if (value > 0) - { + if (value > 0) { output->put(value - 1); - if (verbose_) - { + if (verbose_) { // printf("thread %d, got %d\n", id, value); } continue; } - if (value == 0) - { + if (value == 0) { done_.put(std::make_pair(id, muduo::Timestamp::now())); } break; @@ -109,8 +93,7 @@ class Bench const bool verbose_ = true; }; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { int threads = argc > 1 ? atoi(argv[1]) : 1; printf("sizeof BlockingQueue = %zd\n", sizeof(muduo::BlockingQueue)); diff --git a/muduo/base/tests/BlockingQueue_test.cc b/muduo/base/tests/BlockingQueue_test.cc index 413fbd28f..1503adbe5 100644 --- a/muduo/base/tests/BlockingQueue_test.cc +++ b/muduo/base/tests/BlockingQueue_test.cc @@ -3,76 +3,63 @@ #include "muduo/base/Thread.h" #include -#include -#include #include +#include #include +#include -class Test -{ - public: - Test(int numThreads) - : latch_(numThreads) - { - for (int i = 0; i < numThreads; ++i) - { +class Test { +public: + Test(int numThreads) : latch_(numThreads) { + for (int i = 0; i < numThreads; ++i) { char name[32]; snprintf(name, sizeof name, "work thread %d", i); threads_.emplace_back(new muduo::Thread( - std::bind(&Test::threadFunc, this), muduo::string(name))); + std::bind(&Test::threadFunc, this), muduo::string(name))); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->start(); } } - void run(int times) - { + void run(int times) { printf("waiting for count down latch\n"); latch_.wait(); printf("all threads started\n"); - for (int i = 0; i < times; ++i) - { + for (int i = 0; i < times; ++i) { char buf[32]; snprintf(buf, sizeof buf, "hello %d", i); queue_.put(buf); - printf("tid=%d, put data = %s, size = %zd\n", muduo::CurrentThread::tid(), buf, queue_.size()); + printf("tid=%d, put data = %s, size = %zd\n", muduo::CurrentThread::tid(), + buf, queue_.size()); } } - void joinAll() - { - for (size_t i = 0; i < threads_.size(); ++i) - { + void joinAll() { + for (size_t i = 0; i < threads_.size(); ++i) { queue_.put("stop"); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->join(); } } - private: - - void threadFunc() - { - printf("tid=%d, %s started\n", - muduo::CurrentThread::tid(), +private: + void threadFunc() { + printf("tid=%d, %s started\n", muduo::CurrentThread::tid(), muduo::CurrentThread::name()); latch_.countDown(); bool running = true; - while (running) - { + while (running) { std::string d(queue_.take()); - printf("tid=%d, get data = %s, size = %zd\n", muduo::CurrentThread::tid(), d.c_str(), queue_.size()); + printf("tid=%d, get data = %s, size = %zd\n", muduo::CurrentThread::tid(), + d.c_str(), queue_.size()); running = (d != "stop"); } - printf("tid=%d, %s stopped\n", - muduo::CurrentThread::tid(), + printf("tid=%d, %s stopped\n", muduo::CurrentThread::tid(), muduo::CurrentThread::name()); } @@ -81,8 +68,7 @@ class Test std::vector> threads_; }; -void testMove() -{ +void testMove() { muduo::BlockingQueue> queue; queue.put(std::unique_ptr(new int(42))); std::unique_ptr x = queue.take(); @@ -93,8 +79,7 @@ void testMove() printf("took %d\n", *y); } -int main() -{ +int main() { printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid()); Test t(5); t.run(100); diff --git a/muduo/base/tests/BoundedBlockingQueue_test.cc b/muduo/base/tests/BoundedBlockingQueue_test.cc index 49f57fb39..b54616f41 100644 --- a/muduo/base/tests/BoundedBlockingQueue_test.cc +++ b/muduo/base/tests/BoundedBlockingQueue_test.cc @@ -8,73 +8,59 @@ #include #include -class Test -{ - public: - Test(int numThreads) - : queue_(20), - latch_(numThreads) - { +class Test { +public: + Test(int numThreads) : queue_(20), latch_(numThreads) { threads_.reserve(numThreads); - for (int i = 0; i < numThreads; ++i) - { + for (int i = 0; i < numThreads; ++i) { char name[32]; snprintf(name, sizeof name, "work thread %d", i); threads_.emplace_back(new muduo::Thread( - std::bind(&Test::threadFunc, this), muduo::string(name))); + std::bind(&Test::threadFunc, this), muduo::string(name))); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->start(); } } - void run(int times) - { + void run(int times) { printf("waiting for count down latch\n"); latch_.wait(); printf("all threads started\n"); - for (int i = 0; i < times; ++i) - { + for (int i = 0; i < times; ++i) { char buf[32]; snprintf(buf, sizeof buf, "hello %d", i); queue_.put(buf); - printf("tid=%d, put data = %s, size = %zd\n", muduo::CurrentThread::tid(), buf, queue_.size()); + printf("tid=%d, put data = %s, size = %zd\n", muduo::CurrentThread::tid(), + buf, queue_.size()); } } - void joinAll() - { - for (size_t i = 0; i < threads_.size(); ++i) - { + void joinAll() { + for (size_t i = 0; i < threads_.size(); ++i) { queue_.put("stop"); } - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->join(); } } - private: - - void threadFunc() - { - printf("tid=%d, %s started\n", - muduo::CurrentThread::tid(), +private: + void threadFunc() { + printf("tid=%d, %s started\n", muduo::CurrentThread::tid(), muduo::CurrentThread::name()); latch_.countDown(); bool running = true; - while (running) - { + while (running) { std::string d(queue_.take()); - printf("tid=%d, get data = %s, size = %zd\n", muduo::CurrentThread::tid(), d.c_str(), queue_.size()); + printf("tid=%d, get data = %s, size = %zd\n", muduo::CurrentThread::tid(), + d.c_str(), queue_.size()); running = (d != "stop"); } - printf("tid=%d, %s stopped\n", - muduo::CurrentThread::tid(), + printf("tid=%d, %s stopped\n", muduo::CurrentThread::tid(), muduo::CurrentThread::name()); } @@ -83,8 +69,7 @@ class Test std::vector> threads_; }; -void testMove() -{ +void testMove() { #if BOOST_VERSION >= 105500L muduo::BoundedBlockingQueue> queue(10); queue.put(std::unique_ptr(new int(42))); @@ -98,8 +83,7 @@ void testMove() #endif } -int main() -{ +int main() { printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid()); testMove(); Test t(5); diff --git a/muduo/base/tests/Date_unittest.cc b/muduo/base/tests/Date_unittest.cc index bf2d3862d..b2bbe4437 100644 --- a/muduo/base/tests/Date_unittest.cc +++ b/muduo/base/tests/Date_unittest.cc @@ -6,8 +6,7 @@ using muduo::Date; const int kMonthsOfYear = 12; -int isLeapYear(int year) -{ +int isLeapYear(int year) { if (year % 400 == 0) return 1; else if (year % 100 == 0) @@ -18,28 +17,21 @@ int isLeapYear(int year) return 0; } -int daysOfMonth(int year, int month) -{ - static int days[2][kMonthsOfYear+1] = - { - { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, - { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, +int daysOfMonth(int year, int month) { + static int days[2][kMonthsOfYear + 1] = { + {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, + {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, }; return days[isLeapYear(year)][month]; } -void passByConstReference(const Date& x) -{ +void passByConstReference(const Date &x) { printf("%s\n", x.toIsoString().c_str()); } -void passByValue(Date x) -{ - printf("%s\n", x.toIsoString().c_str()); -} +void passByValue(Date x) { printf("%s\n", x.toIsoString().c_str()); } -int main() -{ +int main() { time_t now = time(NULL); struct tm t1 = *gmtime(&now); struct tm t2 = *localtime(&now); @@ -55,14 +47,12 @@ int main() int julianDayNumber = 2415021; int weekDay = 1; // Monday - for (int year = 1900; year < 2500; ++year) - { - assert(Date(year, 3, 1).julianDayNumber() - Date(year, 2, 29).julianDayNumber() - == isLeapYear(year)); - for (int month = 1; month <= kMonthsOfYear; ++month) - { - for (int day = 1; day <= daysOfMonth(year, month); ++day) - { + for (int year = 1900; year < 2500; ++year) { + assert(Date(year, 3, 1).julianDayNumber() - + Date(year, 2, 29).julianDayNumber() == + isLeapYear(year)); + for (int month = 1; month <= kMonthsOfYear; ++month) { + for (int day = 1; day <= daysOfMonth(year, month); ++day) { Date d(year, month, day); // printf("%s %d\n", d.toString().c_str(), d.weekDay()); assert(year == d.year()); @@ -79,10 +69,9 @@ int main() assert(julianDayNumber == d2.julianDayNumber()); ++julianDayNumber; - weekDay = (weekDay+1) % 7; + weekDay = (weekDay + 1) % 7; } } } printf("All passed.\n"); } - diff --git a/muduo/base/tests/Exception_test.cc b/muduo/base/tests/Exception_test.cc index 7fd800480..6df1efbc0 100644 --- a/muduo/base/tests/Exception_test.cc +++ b/muduo/base/tests/Exception_test.cc @@ -1,20 +1,20 @@ #include "muduo/base/CurrentThread.h" #include "muduo/base/Exception.h" #include -#include #include +#include -class Bar -{ - public: - void test(std::vector names = {}) - { +class Bar { +public: + void test(std::vector names = {}) { printf("Stack:\n%s\n", muduo::CurrentThread::stackTrace(true).c_str()); [] { - printf("Stack inside lambda:\n%s\n", muduo::CurrentThread::stackTrace(true).c_str()); + printf("Stack inside lambda:\n%s\n", + muduo::CurrentThread::stackTrace(true).c_str()); }(); std::function func([] { - printf("Stack inside std::function:\n%s\n", muduo::CurrentThread::stackTrace(true).c_str()); + printf("Stack inside std::function:\n%s\n", + muduo::CurrentThread::stackTrace(true).c_str()); }); func(); @@ -24,27 +24,22 @@ class Bar throw muduo::Exception("oops"); } - private: - void callback() - { - printf("Stack inside std::bind:\n%s\n", muduo::CurrentThread::stackTrace(true).c_str()); - } +private: + void callback() { + printf("Stack inside std::bind:\n%s\n", + muduo::CurrentThread::stackTrace(true).c_str()); + } }; -void foo() -{ +void foo() { Bar b; b.test(); } -int main() -{ - try - { +int main() { + try { foo(); - } - catch (const muduo::Exception& ex) - { + } catch (const muduo::Exception &ex) { printf("reason: %s\n", ex.what()); printf("stack trace:\n%s\n", ex.stackTrace()); } diff --git a/muduo/base/tests/FileUtil_test.cc b/muduo/base/tests/FileUtil_test.cc index 9abe29975..5d05db4be 100644 --- a/muduo/base/tests/FileUtil_test.cc +++ b/muduo/base/tests/FileUtil_test.cc @@ -6,8 +6,7 @@ using namespace muduo; -int main() -{ +int main() { string result; int64_t size = 0; int err = FileUtil::readFile("/proc/self", 1024, &result, &size); @@ -27,4 +26,3 @@ int main() err = FileUtil::readFile("/dev/zero", 102400, &result, NULL); printf("%d %zd %" PRIu64 "\n", err, result.size(), size); } - diff --git a/muduo/base/tests/Fork_test.cc b/muduo/base/tests/Fork_test.cc index 6a3cba629..3fa985fba 100644 --- a/muduo/base/tests/Fork_test.cc +++ b/muduo/base/tests/Fork_test.cc @@ -4,42 +4,35 @@ #include #include -namespace -{ +namespace { __thread int x = 0; } -void print() -{ +void print() { printf("pid=%d tid=%d x=%d\n", getpid(), muduo::CurrentThread::tid(), x); } -int main() -{ +int main() { printf("parent %d\n", getpid()); print(); x = 1; print(); pid_t p = fork(); - if (p == 0) - { + if (p == 0) { printf("chlid %d\n", getpid()); // child print(); x = 2; print(); - if (fork() == 0) - { + if (fork() == 0) { printf("grandchlid %d\n", getpid()); print(); x = 3; print(); } - } - else - { + } else { // parent print(); } diff --git a/muduo/base/tests/GzipFile_test.cc b/muduo/base/tests/GzipFile_test.cc index d3f9cc353..6a027c806 100644 --- a/muduo/base/tests/GzipFile_test.cc +++ b/muduo/base/tests/GzipFile_test.cc @@ -2,53 +2,46 @@ #include "muduo/base/Logging.h" -int main() -{ - const char* filename = "/tmp/gzipfile_test.gz"; +int main() { + const char *filename = "/tmp/gzipfile_test.gz"; ::unlink(filename); - const char data[] = "123456789012345678901234567890123456789012345678901234567890\n"; + const char data[] = + "123456789012345678901234567890123456789012345678901234567890\n"; { - muduo::GzipFile writer = muduo::GzipFile::openForAppend(filename); - if (writer.valid()) - { - LOG_INFO << "tell " << writer.tell(); - LOG_INFO << "wrote " << writer.write(data); - LOG_INFO << "tell " << writer.tell(); - } + muduo::GzipFile writer = muduo::GzipFile::openForAppend(filename); + if (writer.valid()) { + LOG_INFO << "tell " << writer.tell(); + LOG_INFO << "wrote " << writer.write(data); + LOG_INFO << "tell " << writer.tell(); + } } { - printf("testing reader\n"); - muduo::GzipFile reader = muduo::GzipFile::openForRead(filename); - if (reader.valid()) - { - char buf[256]; - LOG_INFO << "tell " << reader.tell(); - int nr = reader.read(buf, sizeof buf); - printf("read %d\n", nr); - if (nr >= 0) - { - buf[nr] = '\0'; - printf("data %s", buf); - } - LOG_INFO << "tell " << reader.tell(); - if (strncmp(buf, data, strlen(data)) != 0) - { - printf("failed!!!\n"); - abort(); + printf("testing reader\n"); + muduo::GzipFile reader = muduo::GzipFile::openForRead(filename); + if (reader.valid()) { + char buf[256]; + LOG_INFO << "tell " << reader.tell(); + int nr = reader.read(buf, sizeof buf); + printf("read %d\n", nr); + if (nr >= 0) { + buf[nr] = '\0'; + printf("data %s", buf); + } + LOG_INFO << "tell " << reader.tell(); + if (strncmp(buf, data, strlen(data)) != 0) { + printf("failed!!!\n"); + abort(); + } else { + printf("PASSED\n"); + } } - else - { - printf("PASSED\n"); - } - } } { - muduo::GzipFile writer = muduo::GzipFile::openForWriteExclusive(filename); - if (writer.valid() || errno != EEXIST) - { - printf("FAILED\n"); - } + muduo::GzipFile writer = muduo::GzipFile::openForWriteExclusive(filename); + if (writer.valid() || errno != EEXIST) { + printf("FAILED\n"); + } } } diff --git a/muduo/base/tests/LogFile_test.cc b/muduo/base/tests/LogFile_test.cc index a0b753a6f..98b2825aa 100644 --- a/muduo/base/tests/LogFile_test.cc +++ b/muduo/base/tests/LogFile_test.cc @@ -5,28 +5,21 @@ std::unique_ptr g_logFile; -void outputFunc(const char* msg, int len) -{ - g_logFile->append(msg, len); -} +void outputFunc(const char *msg, int len) { g_logFile->append(msg, len); } -void flushFunc() -{ - g_logFile->flush(); -} +void flushFunc() { g_logFile->flush(); } -int main(int argc, char* argv[]) -{ - char name[256] = { '\0' }; +int main(int argc, char *argv[]) { + char name[256] = {'\0'}; strncpy(name, argv[0], sizeof name - 1); - g_logFile.reset(new muduo::LogFile(::basename(name), 200*1000)); + g_logFile.reset(new muduo::LogFile(::basename(name), 200 * 1000)); muduo::Logger::setOutput(outputFunc); muduo::Logger::setFlush(flushFunc); - muduo::string line = "1234567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ "; + muduo::string line = + "1234567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ "; - for (int i = 0; i < 10000; ++i) - { + for (int i = 0; i < 10000; ++i) { LOG_INFO << line << i; usleep(1000); diff --git a/muduo/base/tests/LogStream_bench.cc b/muduo/base/tests/LogStream_bench.cc index c91637a96..6f7881a0e 100644 --- a/muduo/base/tests/LogStream_bench.cc +++ b/muduo/base/tests/LogStream_bench.cc @@ -12,9 +12,7 @@ const size_t N = 1000000; #pragma GCC diagnostic ignored "-Wold-style-cast" -template -void benchPrintf(const char* fmt) -{ +template void benchPrintf(const char *fmt) { char buf[32]; Timestamp start(Timestamp::now()); for (size_t i = 0; i < N; ++i) @@ -24,14 +22,11 @@ void benchPrintf(const char* fmt) printf("benchPrintf %f\n", timeDifference(end, start)); } -template -void benchStringStream() -{ +template void benchStringStream() { Timestamp start(Timestamp::now()); std::ostringstream os; - for (size_t i = 0; i < N; ++i) - { + for (size_t i = 0; i < N; ++i) { os << (T)(i); os.seekp(0, std::ios_base::beg); } @@ -40,13 +35,10 @@ void benchStringStream() printf("benchStringStream %f\n", timeDifference(end, start)); } -template -void benchLogStream() -{ +template void benchLogStream() { Timestamp start(Timestamp::now()); LogStream os; - for (size_t i = 0; i < N; ++i) - { + for (size_t i = 0; i < N; ++i) { os << (T)(i); os.resetBuffer(); } @@ -55,8 +47,7 @@ void benchLogStream() printf("benchLogStream %f\n", timeDifference(end, start)); } -int main() -{ +int main() { benchPrintf("%d"); puts("int"); @@ -75,8 +66,7 @@ int main() benchLogStream(); puts("void*"); - benchPrintf("%p"); - benchStringStream(); - benchLogStream(); - + benchPrintf("%p"); + benchStringStream(); + benchLogStream(); } diff --git a/muduo/base/tests/LogStream_test.cc b/muduo/base/tests/LogStream_test.cc index b6070e17b..67c2dcf93 100644 --- a/muduo/base/tests/LogStream_test.cc +++ b/muduo/base/tests/LogStream_test.cc @@ -10,10 +10,9 @@ using muduo::string; -BOOST_AUTO_TEST_CASE(testLogStreamBooleans) -{ +BOOST_AUTO_TEST_CASE(testLogStreamBooleans) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); + const muduo::LogStream::Buffer &buf = os.buffer(); BOOST_CHECK_EQUAL(buf.toString(), string("")); os << true; BOOST_CHECK_EQUAL(buf.toString(), string("1")); @@ -23,10 +22,9 @@ BOOST_AUTO_TEST_CASE(testLogStreamBooleans) BOOST_CHECK_EQUAL(buf.toString(), string("1\n0")); } -BOOST_AUTO_TEST_CASE(testLogStreamIntegers) -{ +BOOST_AUTO_TEST_CASE(testLogStreamIntegers) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); + const muduo::LogStream::Buffer &buf = os.buffer(); BOOST_CHECK_EQUAL(buf.toString(), string("")); os << 1; BOOST_CHECK_EQUAL(buf.toString(), string("1")); @@ -40,17 +38,17 @@ BOOST_AUTO_TEST_CASE(testLogStreamIntegers) BOOST_CHECK_EQUAL(buf.toString(), string("0 123x100")); } -BOOST_AUTO_TEST_CASE(testLogStreamIntegerLimits) -{ +BOOST_AUTO_TEST_CASE(testLogStreamIntegerLimits) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); + const muduo::LogStream::Buffer &buf = os.buffer(); os << -2147483647; BOOST_CHECK_EQUAL(buf.toString(), string("-2147483647")); os << static_cast(-2147483647 - 1); BOOST_CHECK_EQUAL(buf.toString(), string("-2147483647-2147483648")); os << ' '; os << 2147483647; - BOOST_CHECK_EQUAL(buf.toString(), string("-2147483647-2147483648 2147483647")); + BOOST_CHECK_EQUAL(buf.toString(), + string("-2147483647-2147483648 2147483647")); os.resetBuffer(); os << std::numeric_limits::min(); @@ -110,10 +108,9 @@ BOOST_AUTO_TEST_CASE(testLogStreamIntegerLimits) BOOST_CHECK_EQUAL(buf.toString(), string("000")); } -BOOST_AUTO_TEST_CASE(testLogStreamFloats) -{ +BOOST_AUTO_TEST_CASE(testLogStreamFloats) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); + const muduo::LogStream::Buffer &buf = os.buffer(); os << 0.0; BOOST_CHECK_EQUAL(buf.toString(), string("0")); @@ -150,11 +147,11 @@ BOOST_AUTO_TEST_CASE(testLogStreamFloats) BOOST_CHECK_EQUAL(buf.toString(), string("0.15")); os.resetBuffer(); - os << a+b; + os << a + b; BOOST_CHECK_EQUAL(buf.toString(), string("0.15")); os.resetBuffer(); - BOOST_CHECK(a+b != c); + BOOST_CHECK(a + b != c); os << 1.23456789; BOOST_CHECK_EQUAL(buf.toString(), string("1.23456789")); @@ -169,24 +166,22 @@ BOOST_AUTO_TEST_CASE(testLogStreamFloats) os.resetBuffer(); } -BOOST_AUTO_TEST_CASE(testLogStreamVoid) -{ +BOOST_AUTO_TEST_CASE(testLogStreamVoid) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); + const muduo::LogStream::Buffer &buf = os.buffer(); - os << static_cast(0); + os << static_cast(0); BOOST_CHECK_EQUAL(buf.toString(), string("0x0")); os.resetBuffer(); - os << reinterpret_cast(8888); + os << reinterpret_cast(8888); BOOST_CHECK_EQUAL(buf.toString(), string("0x22B8")); os.resetBuffer(); } -BOOST_AUTO_TEST_CASE(testLogStreamStrings) -{ +BOOST_AUTO_TEST_CASE(testLogStreamStrings) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); + const muduo::LogStream::Buffer &buf = os.buffer(); os << "Hello "; BOOST_CHECK_EQUAL(buf.toString(), string("Hello ")); @@ -196,10 +191,9 @@ BOOST_AUTO_TEST_CASE(testLogStreamStrings) BOOST_CHECK_EQUAL(buf.toString(), string("Hello Shuo Chen")); } -BOOST_AUTO_TEST_CASE(testLogStreamFmts) -{ +BOOST_AUTO_TEST_CASE(testLogStreamFmts) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); + const muduo::LogStream::Buffer &buf = os.buffer(); os << muduo::Fmt("%4d", 1); BOOST_CHECK_EQUAL(buf.toString(), string(" 1")); @@ -214,15 +208,13 @@ BOOST_AUTO_TEST_CASE(testLogStreamFmts) os.resetBuffer(); } -BOOST_AUTO_TEST_CASE(testLogStreamLong) -{ +BOOST_AUTO_TEST_CASE(testLogStreamLong) { muduo::LogStream os; - const muduo::LogStream::Buffer& buf = os.buffer(); - for (int i = 0; i < 399; ++i) - { + const muduo::LogStream::Buffer &buf = os.buffer(); + for (int i = 0; i < 399; ++i) { os << "123456789 "; - BOOST_CHECK_EQUAL(buf.length(), 10*(i+1)); - BOOST_CHECK_EQUAL(buf.avail(), 4000 - 10*(i+1)); + BOOST_CHECK_EQUAL(buf.length(), 10 * (i + 1)); + BOOST_CHECK_EQUAL(buf.avail(), 4000 - 10 * (i + 1)); } os << "abcdefghi "; @@ -234,8 +226,7 @@ BOOST_AUTO_TEST_CASE(testLogStreamLong) BOOST_CHECK_EQUAL(buf.avail(), 1); } -BOOST_AUTO_TEST_CASE(testFormatSI) -{ +BOOST_AUTO_TEST_CASE(testFormatSI) { BOOST_CHECK_EQUAL(muduo::formatSI(0), string("0")); BOOST_CHECK_EQUAL(muduo::formatSI(999), string("999")); BOOST_CHECK_EQUAL(muduo::formatSI(1000), string("1.00k")); @@ -260,8 +251,7 @@ BOOST_AUTO_TEST_CASE(testFormatSI) BOOST_CHECK_EQUAL(muduo::formatSI(INT64_MAX), string("9.22E")); } -BOOST_AUTO_TEST_CASE(testFormatIEC) -{ +BOOST_AUTO_TEST_CASE(testFormatIEC) { BOOST_CHECK_EQUAL(muduo::formatIEC(0), string("0")); BOOST_CHECK_EQUAL(muduo::formatIEC(1023), string("1023")); BOOST_CHECK_EQUAL(muduo::formatIEC(1024), string("1.00Ki")); diff --git a/muduo/base/tests/Logging_test.cc b/muduo/base/tests/Logging_test.cc index 3de5e869b..fe12e2304 100644 --- a/muduo/base/tests/Logging_test.cc +++ b/muduo/base/tests/Logging_test.cc @@ -1,5 +1,5 @@ -#include "muduo/base/Logging.h" #include "muduo/base/LogFile.h" +#include "muduo/base/Logging.h" #include "muduo/base/ThreadPool.h" #include "muduo/base/TimeZone.h" @@ -7,53 +7,45 @@ #include int g_total; -FILE* g_file; +FILE *g_file; std::unique_ptr g_logFile; -void dummyOutput(const char* msg, int len) -{ +void dummyOutput(const char *msg, int len) { g_total += len; - if (g_file) - { + if (g_file) { fwrite(msg, 1, len, g_file); - } - else if (g_logFile) - { + } else if (g_logFile) { g_logFile->append(msg, len); } } -void bench(const char* type) -{ +void bench(const char *type) { muduo::Logger::setOutput(dummyOutput); muduo::Timestamp start(muduo::Timestamp::now()); g_total = 0; - int n = 1000*1000; + int n = 1000 * 1000; const bool kLongLog = false; muduo::string empty = " "; muduo::string longStr(3000, 'X'); longStr += " "; - for (int i = 0; i < n; ++i) - { - LOG_INFO << "Hello 0123456789" << " abcdefghijklmnopqrstuvwxyz" - << (kLongLog ? longStr : empty) + for (int i = 0; i < n; ++i) { + LOG_INFO << "Hello 0123456789" + << " abcdefghijklmnopqrstuvwxyz" << (kLongLog ? longStr : empty) << i; } muduo::Timestamp end(muduo::Timestamp::now()); double seconds = timeDifference(end, start); - printf("%12s: %f seconds, %d bytes, %10.2f msg/s, %.2f MiB/s\n", - type, seconds, g_total, n / seconds, g_total / seconds / (1024 * 1024)); + printf("%12s: %f seconds, %d bytes, %10.2f msg/s, %.2f MiB/s\n", type, + seconds, g_total, n / seconds, g_total / seconds / (1024 * 1024)); } -void logInThread() -{ +void logInThread() { LOG_INFO << "logInThread"; usleep(1000); } -int main() -{ +int main() { getppid(); // for ltrace and strace muduo::ThreadPool pool("pool"); @@ -77,7 +69,7 @@ int main() sleep(1); bench("nop"); - char buffer[64*1024]; + char buffer[64 * 1024]; g_file = fopen("/dev/null", "w"); setbuffer(g_file, buffer, sizeof buffer); @@ -90,33 +82,33 @@ int main() fclose(g_file); g_file = NULL; - g_logFile.reset(new muduo::LogFile("test_log_st", 500*1000*1000, false)); + g_logFile.reset(new muduo::LogFile("test_log_st", 500 * 1000 * 1000, false)); bench("test_log_st"); - g_logFile.reset(new muduo::LogFile("test_log_mt", 500*1000*1000, true)); + g_logFile.reset(new muduo::LogFile("test_log_mt", 500 * 1000 * 1000, true)); bench("test_log_mt"); g_logFile.reset(); { - g_file = stdout; - sleep(1); - muduo::TimeZone beijing(8*3600, "CST"); - muduo::Logger::setTimeZone(beijing); - LOG_TRACE << "trace CST"; - LOG_DEBUG << "debug CST"; - LOG_INFO << "Hello CST"; - LOG_WARN << "World CST"; - LOG_ERROR << "Error CST"; - - sleep(1); - muduo::TimeZone newyork("/usr/share/zoneinfo/America/New_York"); - muduo::Logger::setTimeZone(newyork); - LOG_TRACE << "trace NYT"; - LOG_DEBUG << "debug NYT"; - LOG_INFO << "Hello NYT"; - LOG_WARN << "World NYT"; - LOG_ERROR << "Error NYT"; - g_file = NULL; + g_file = stdout; + sleep(1); + muduo::TimeZone beijing(8 * 3600, "CST"); + muduo::Logger::setTimeZone(beijing); + LOG_TRACE << "trace CST"; + LOG_DEBUG << "debug CST"; + LOG_INFO << "Hello CST"; + LOG_WARN << "World CST"; + LOG_ERROR << "Error CST"; + + sleep(1); + muduo::TimeZone newyork("/usr/share/zoneinfo/America/New_York"); + muduo::Logger::setTimeZone(newyork); + LOG_TRACE << "trace NYT"; + LOG_DEBUG << "debug NYT"; + LOG_INFO << "Hello NYT"; + LOG_WARN << "World NYT"; + LOG_ERROR << "Error NYT"; + g_file = NULL; } bench("timezone nop"); } diff --git a/muduo/base/tests/Mutex_test.cc b/muduo/base/tests/Mutex_test.cc index 7d1e29904..8f57e8400 100644 --- a/muduo/base/tests/Mutex_test.cc +++ b/muduo/base/tests/Mutex_test.cc @@ -3,33 +3,29 @@ #include "muduo/base/Thread.h" #include "muduo/base/Timestamp.h" -#include #include +#include using namespace muduo; using namespace std; MutexLock g_mutex; vector g_vec; -const int kCount = 10*1000*1000; +const int kCount = 10 * 1000 * 1000; -void threadFunc() -{ - for (int i = 0; i < kCount; ++i) - { +void threadFunc() { + for (int i = 0; i < kCount; ++i) { MutexLockGuard lock(g_mutex); g_vec.push_back(i); } } -int foo() __attribute__ ((noinline)); +int foo() __attribute__((noinline)); int g_count = 0; -int foo() -{ +int foo() { MutexLockGuard lock(g_mutex); - if (!g_mutex.isLockedByThisThread()) - { + if (!g_mutex.isLockedByThisThread()) { printf("FAIL\n"); return -1; } @@ -38,15 +34,13 @@ int foo() return 0; } -int main() -{ +int main() { printf("sizeof pthread_mutex_t: %zd\n", sizeof(pthread_mutex_t)); printf("sizeof Mutex: %zd\n", sizeof(MutexLock)); printf("sizeof pthread_cond_t: %zd\n", sizeof(pthread_cond_t)); printf("sizeof Condition: %zd\n", sizeof(Condition)); MCHECK(foo()); - if (g_count != 1) - { + if (g_count != 1) { printf("MCHECK calls twice.\n"); abort(); } @@ -55,32 +49,30 @@ int main() g_vec.reserve(kMaxThreads * kCount); Timestamp start(Timestamp::now()); - for (int i = 0; i < kCount; ++i) - { + for (int i = 0; i < kCount; ++i) { g_vec.push_back(i); } - printf("single thread without lock %f\n", timeDifference(Timestamp::now(), start)); + printf("single thread without lock %f\n", + timeDifference(Timestamp::now(), start)); start = Timestamp::now(); threadFunc(); - printf("single thread with lock %f\n", timeDifference(Timestamp::now(), start)); + printf("single thread with lock %f\n", + timeDifference(Timestamp::now(), start)); - for (int nthreads = 1; nthreads < kMaxThreads; ++nthreads) - { + for (int nthreads = 1; nthreads < kMaxThreads; ++nthreads) { std::vector> threads; g_vec.clear(); start = Timestamp::now(); - for (int i = 0; i < nthreads; ++i) - { + for (int i = 0; i < nthreads; ++i) { threads.emplace_back(new Thread(&threadFunc)); threads.back()->start(); } - for (int i = 0; i < nthreads; ++i) - { + for (int i = 0; i < nthreads; ++i) { threads[i]->join(); } - printf("%d thread(s) with lock %f\n", nthreads, timeDifference(Timestamp::now(), start)); + printf("%d thread(s) with lock %f\n", nthreads, + timeDifference(Timestamp::now(), start)); } } - diff --git a/muduo/base/tests/ProcessInfo_test.cc b/muduo/base/tests/ProcessInfo_test.cc index 6e30badb4..d8c0c43f6 100644 --- a/muduo/base/tests/ProcessInfo_test.cc +++ b/muduo/base/tests/ProcessInfo_test.cc @@ -3,12 +3,12 @@ #define __STDC_FORMAT_MACROS #include -int main() -{ +int main() { printf("pid = %d\n", muduo::ProcessInfo::pid()); printf("uid = %d\n", muduo::ProcessInfo::uid()); printf("euid = %d\n", muduo::ProcessInfo::euid()); - printf("start time = %s\n", muduo::ProcessInfo::startTime().toFormattedString().c_str()); + printf("start time = %s\n", + muduo::ProcessInfo::startTime().toFormattedString().c_str()); printf("hostname = %s\n", muduo::ProcessInfo::hostname().c_str()); printf("opened files = %d\n", muduo::ProcessInfo::openedFiles()); printf("threads = %zd\n", muduo::ProcessInfo::threads().size()); diff --git a/muduo/base/tests/SingletonThreadLocal_test.cc b/muduo/base/tests/SingletonThreadLocal_test.cc index 29edf6c11..ec5733deb 100644 --- a/muduo/base/tests/SingletonThreadLocal_test.cc +++ b/muduo/base/tests/SingletonThreadLocal_test.cc @@ -1,51 +1,44 @@ -#include "muduo/base/Singleton.h" #include "muduo/base/CurrentThread.h" -#include "muduo/base/ThreadLocal.h" +#include "muduo/base/Singleton.h" #include "muduo/base/Thread.h" +#include "muduo/base/ThreadLocal.h" #include #include -class Test : muduo::noncopyable -{ - public: - Test() - { +class Test : muduo::noncopyable { +public: + Test() { printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this); } - ~Test() - { - printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str()); + ~Test() { + printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, + name_.c_str()); } - const muduo::string& name() const { return name_; } - void setName(const muduo::string& n) { name_ = n; } + const muduo::string &name() const { return name_; } + void setName(const muduo::string &n) { name_ = n; } - private: +private: muduo::string name_; }; -#define STL muduo::Singleton >::instance().value() +#define STL muduo::Singleton>::instance().value() -void print() -{ - printf("tid=%d, %p name=%s\n", - muduo::CurrentThread::tid(), - &STL, +void print() { + printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(), &STL, STL.name().c_str()); } -void threadFunc(const char* changeTo) -{ +void threadFunc(const char *changeTo) { print(); STL.setName(changeTo); sleep(1); print(); } -int main() -{ +int main() { STL.setName("main one"); muduo::Thread t1(std::bind(threadFunc, "thread1")); muduo::Thread t2(std::bind(threadFunc, "thread2")); diff --git a/muduo/base/tests/Singleton_test.cc b/muduo/base/tests/Singleton_test.cc index 124d7f7a6..9c5763077 100644 --- a/muduo/base/tests/Singleton_test.cc +++ b/muduo/base/tests/Singleton_test.cc @@ -1,65 +1,59 @@ -#include "muduo/base/Singleton.h" #include "muduo/base/CurrentThread.h" +#include "muduo/base/Singleton.h" #include "muduo/base/Thread.h" #include -class Test : muduo::noncopyable -{ - public: - Test() - { +class Test : muduo::noncopyable { +public: + Test() { printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this); } - ~Test() - { - printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str()); + ~Test() { + printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, + name_.c_str()); } - const muduo::string& name() const { return name_; } - void setName(const muduo::string& n) { name_ = n; } + const muduo::string &name() const { return name_; } + void setName(const muduo::string &n) { name_ = n; } - private: +private: muduo::string name_; }; -class TestNoDestroy : muduo::noncopyable -{ - public: +class TestNoDestroy : muduo::noncopyable { +public: // Tag member for Singleton void no_destroy(); - TestNoDestroy() - { - printf("tid=%d, constructing TestNoDestroy %p\n", muduo::CurrentThread::tid(), this); + TestNoDestroy() { + printf("tid=%d, constructing TestNoDestroy %p\n", + muduo::CurrentThread::tid(), this); } - ~TestNoDestroy() - { - printf("tid=%d, destructing TestNoDestroy %p\n", muduo::CurrentThread::tid(), this); + ~TestNoDestroy() { + printf("tid=%d, destructing TestNoDestroy %p\n", + muduo::CurrentThread::tid(), this); } }; -void threadFunc() -{ - printf("tid=%d, %p name=%s\n", - muduo::CurrentThread::tid(), +void threadFunc() { + printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(), &muduo::Singleton::instance(), muduo::Singleton::instance().name().c_str()); muduo::Singleton::instance().setName("only one, changed"); } -int main() -{ +int main() { muduo::Singleton::instance().setName("only one"); muduo::Thread t1(threadFunc); t1.start(); t1.join(); - printf("tid=%d, %p name=%s\n", - muduo::CurrentThread::tid(), + printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(), &muduo::Singleton::instance(), muduo::Singleton::instance().name().c_str()); muduo::Singleton::instance(); - printf("with valgrind, you should see %zd-byte memory leak.\n", sizeof(TestNoDestroy)); + printf("with valgrind, you should see %zd-byte memory leak.\n", + sizeof(TestNoDestroy)); } diff --git a/muduo/base/tests/ThreadLocalSingleton_test.cc b/muduo/base/tests/ThreadLocalSingleton_test.cc index efe485a6e..e9d3147f8 100644 --- a/muduo/base/tests/ThreadLocalSingleton_test.cc +++ b/muduo/base/tests/ThreadLocalSingleton_test.cc @@ -1,38 +1,33 @@ -#include "muduo/base/ThreadLocalSingleton.h" #include "muduo/base/CurrentThread.h" #include "muduo/base/Thread.h" +#include "muduo/base/ThreadLocalSingleton.h" #include -class Test : muduo::noncopyable -{ - public: - Test() - { +class Test : muduo::noncopyable { +public: + Test() { printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this); } - ~Test() - { - printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str()); + ~Test() { + printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, + name_.c_str()); } - const muduo::string& name() const { return name_; } - void setName(const muduo::string& n) { name_ = n; } + const muduo::string &name() const { return name_; } + void setName(const muduo::string &n) { name_ = n; } - private: +private: muduo::string name_; }; -void threadFunc(const char* changeTo) -{ - printf("tid=%d, %p name=%s\n", - muduo::CurrentThread::tid(), +void threadFunc(const char *changeTo) { + printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(), &muduo::ThreadLocalSingleton::instance(), muduo::ThreadLocalSingleton::instance().name().c_str()); muduo::ThreadLocalSingleton::instance().setName(changeTo); - printf("tid=%d, %p name=%s\n", - muduo::CurrentThread::tid(), + printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(), &muduo::ThreadLocalSingleton::instance(), muduo::ThreadLocalSingleton::instance().name().c_str()); @@ -40,16 +35,14 @@ void threadFunc(const char* changeTo) // muduo::ThreadLocalSingleton::destroy(); } -int main() -{ +int main() { muduo::ThreadLocalSingleton::instance().setName("main one"); muduo::Thread t1(std::bind(threadFunc, "thread1")); muduo::Thread t2(std::bind(threadFunc, "thread2")); t1.start(); t2.start(); t1.join(); - printf("tid=%d, %p name=%s\n", - muduo::CurrentThread::tid(), + printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(), &muduo::ThreadLocalSingleton::instance(), muduo::ThreadLocalSingleton::instance().name().c_str()); t2.join(); diff --git a/muduo/base/tests/ThreadLocal_test.cc b/muduo/base/tests/ThreadLocal_test.cc index a5b89cf2f..8851c7be3 100644 --- a/muduo/base/tests/ThreadLocal_test.cc +++ b/muduo/base/tests/ThreadLocal_test.cc @@ -1,54 +1,45 @@ -#include "muduo/base/ThreadLocal.h" #include "muduo/base/CurrentThread.h" #include "muduo/base/Thread.h" +#include "muduo/base/ThreadLocal.h" #include -class Test : muduo::noncopyable -{ - public: - Test() - { +class Test : muduo::noncopyable { +public: + Test() { printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this); } - ~Test() - { - printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str()); + ~Test() { + printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, + name_.c_str()); } - const muduo::string& name() const { return name_; } - void setName(const muduo::string& n) { name_ = n; } + const muduo::string &name() const { return name_; } + void setName(const muduo::string &n) { name_ = n; } - private: +private: muduo::string name_; }; muduo::ThreadLocal testObj1; muduo::ThreadLocal testObj2; -void print() -{ - printf("tid=%d, obj1 %p name=%s\n", - muduo::CurrentThread::tid(), - &testObj1.value(), - testObj1.value().name().c_str()); - printf("tid=%d, obj2 %p name=%s\n", - muduo::CurrentThread::tid(), - &testObj2.value(), - testObj2.value().name().c_str()); +void print() { + printf("tid=%d, obj1 %p name=%s\n", muduo::CurrentThread::tid(), + &testObj1.value(), testObj1.value().name().c_str()); + printf("tid=%d, obj2 %p name=%s\n", muduo::CurrentThread::tid(), + &testObj2.value(), testObj2.value().name().c_str()); } -void threadFunc() -{ +void threadFunc() { print(); testObj1.value().setName("changed 1"); testObj2.value().setName("changed 42"); print(); } -int main() -{ +int main() { testObj1.value().setName("main one"); print(); muduo::Thread t1(threadFunc); diff --git a/muduo/base/tests/ThreadPool_test.cc b/muduo/base/tests/ThreadPool_test.cc index de0dd6093..c7b847759 100644 --- a/muduo/base/tests/ThreadPool_test.cc +++ b/muduo/base/tests/ThreadPool_test.cc @@ -1,24 +1,19 @@ -#include "muduo/base/ThreadPool.h" #include "muduo/base/CountDownLatch.h" #include "muduo/base/CurrentThread.h" #include "muduo/base/Logging.h" +#include "muduo/base/ThreadPool.h" #include -#include // usleep +#include // usleep -void print() -{ - printf("tid=%d\n", muduo::CurrentThread::tid()); -} +void print() { printf("tid=%d\n", muduo::CurrentThread::tid()); } -void printString(const std::string& str) -{ +void printString(const std::string &str) { LOG_INFO << str; - usleep(100*1000); + usleep(100 * 1000); } -void test(int maxSize) -{ +void test(int maxSize) { LOG_WARN << "Test ThreadPool with max queue size = " << maxSize; muduo::ThreadPool pool("MainThreadPool"); pool.setMaxQueueSize(maxSize); @@ -27,8 +22,7 @@ void test(int maxSize) LOG_WARN << "Adding"; pool.run(print); pool.run(print); - for (int i = 0; i < 100; ++i) - { + for (int i = 0; i < 100; ++i) { char buf[32]; snprintf(buf, sizeof buf, "task %d", i); pool.run(std::bind(printString, std::string(buf))); @@ -49,36 +43,34 @@ void testMove() pool.start(2); std::unique_ptr x(new int(42)); - pool.run([y = std::move(x)]{ printf("%d: %d\n", muduo::CurrentThread::tid(), *y); }); - pool.stop(); + pool.run([y = std::move(x)]{ printf("%d: %d\n", muduo::CurrentThread::tid(), +*y); }); pool.stop(); } */ -void longTask(int num) -{ +void longTask(int num) { LOG_INFO << "longTask " << num; muduo::CurrentThread::sleepUsec(3000000); } -void test2() -{ +void test2() { LOG_WARN << "Test ThreadPool by stoping early."; muduo::ThreadPool pool("ThreadPool"); pool.setMaxQueueSize(5); pool.start(3); - muduo::Thread thread1([&pool]() - { - for (int i = 0; i < 20; ++i) - { - pool.run(std::bind(longTask, i)); - } - }, "thread1"); + muduo::Thread thread1( + [&pool]() { + for (int i = 0; i < 20; ++i) { + pool.run(std::bind(longTask, i)); + } + }, + "thread1"); thread1.start(); muduo::CurrentThread::sleepUsec(5000000); LOG_WARN << "stop pool"; - pool.stop(); // early stop + pool.stop(); // early stop thread1.join(); // run() after stop() @@ -86,8 +78,7 @@ void test2() LOG_WARN << "test2 Done"; } -int main() -{ +int main() { test(0); test(1); test(5); diff --git a/muduo/base/tests/Thread_bench.cc b/muduo/base/tests/Thread_bench.cc index 5e87e1fb1..4039cadc5 100644 --- a/muduo/base/tests/Thread_bench.cc +++ b/muduo/base/tests/Thread_bench.cc @@ -18,72 +18,57 @@ muduo::MutexLock g_mutex; muduo::AtomicInt32 g_count; std::map g_delays; -void threadFunc() -{ - //printf("tid=%d\n", muduo::CurrentThread::tid()); +void threadFunc() { + // printf("tid=%d\n", muduo::CurrentThread::tid()); g_count.increment(); } -void threadFunc2(muduo::Timestamp start) -{ +void threadFunc2(muduo::Timestamp start) { muduo::Timestamp now(muduo::Timestamp::now()); int delay = static_cast(timeDifference(now, start) * 1000000); muduo::MutexLockGuard lock(g_mutex); ++g_delays[delay]; } -void forkBench() -{ +void forkBench() { sleep(10); muduo::Timestamp start(muduo::Timestamp::now()); - int kProcesses = 10*1000; + int kProcesses = 10 * 1000; printf("Creating %d processes in serial\n", kProcesses); - for (int i = 0; i < kProcesses; ++i) - { + for (int i = 0; i < kProcesses; ++i) { pid_t child = fork(); - if (child == 0) - { + if (child == 0) { exit(0); - } - else - { + } else { waitpid(child, NULL, 0); } } double timeUsed = timeDifference(muduo::Timestamp::now(), start); printf("time elapsed %.3f seconds, process creation time used %.3f us\n", - timeUsed, timeUsed*1e6/kProcesses); + timeUsed, timeUsed * 1e6 / kProcesses); printf("number of created processes %d\n", kProcesses); } -class Bench -{ - public: - Bench(int numThreads) - : startLatch_(numThreads), - stopLatch_(1) - { +class Bench { +public: + Bench(int numThreads) : startLatch_(numThreads), stopLatch_(1) { threads_.reserve(numThreads); - for (int i = 0; i < numThreads; ++i) - { + for (int i = 0; i < numThreads; ++i) { char name[32]; snprintf(name, sizeof name, "work thread %d", i); - threads_.emplace_back(new muduo::Thread( - [this] { threadFunc(); }, - muduo::string(name))); + threads_.emplace_back( + new muduo::Thread([this] { threadFunc(); }, muduo::string(name))); } } - void Start() - { + void Start() { const int numThreads = static_cast(threads_.size()); printf("Creating %d threads in parallel\n", numThreads); muduo::Timestamp start = muduo::Timestamp::now(); - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->start(); } startLatch_.wait(); @@ -92,42 +77,37 @@ class Bench numThreads, 1e3 * timeUsed, 1e6 * timeUsed / numThreads); TimestampQueue::queue_type queue = start_.drain(); - if (g_verbose) - { + if (g_verbose) { // for (const auto& [tid, ts] : queue) - for (const auto& e : queue) - { - printf("thread %d, %.0f us\n", e.first, timeDifference(e.second, start) * 1e6); + for (const auto &e : queue) { + printf("thread %d, %.0f us\n", e.first, + timeDifference(e.second, start) * 1e6); } } } - void Stop() - { + void Stop() { muduo::Timestamp stop = muduo::Timestamp::now(); stopLatch_.countDown(); - for (auto& thr : threads_) - { + for (auto &thr : threads_) { thr->join(); } muduo::Timestamp t2 = muduo::Timestamp::now(); - printf("all %zd threads joined, %.3fms\n", - threads_.size(), 1e3 * timeDifference(t2, stop)); + printf("all %zd threads joined, %.3fms\n", threads_.size(), + 1e3 * timeDifference(t2, stop)); TimestampQueue::queue_type queue = done_.drain(); - if (g_verbose) - { + if (g_verbose) { // for (const auto& [tid, ts] : queue) - for (const auto& e : queue) - { - printf("thread %d, %.0f us\n", e.first, timeDifference(e.second, stop) * 1e6); + for (const auto &e : queue) { + printf("thread %d, %.0f us\n", e.first, + timeDifference(e.second, stop) * 1e6); } } } - private: - void threadFunc() - { +private: + void threadFunc() { const int tid = muduo::CurrentThread::tid(); start_.put(std::make_pair(tid, muduo::Timestamp::now())); startLatch_.countDown(); @@ -141,17 +121,15 @@ class Bench std::vector> threads_; }; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { g_verbose = argc > 1; - printf("pid=%d, tid=%d, verbose=%d\n", - ::getpid(), muduo::CurrentThread::tid(), g_verbose); + printf("pid=%d, tid=%d, verbose=%d\n", ::getpid(), + muduo::CurrentThread::tid(), g_verbose); muduo::Timestamp start(muduo::Timestamp::now()); - int kThreads = 100*1000; + int kThreads = 100 * 1000; printf("Creating %d threads in serial\n", kThreads); - for (int i = 0; i < kThreads; ++i) - { + for (int i = 0; i < kThreads; ++i) { muduo::Thread t1(threadFunc); t1.start(); t1.join(); @@ -159,25 +137,21 @@ int main(int argc, char* argv[]) double timeUsed = timeDifference(muduo::Timestamp::now(), start); printf("elapsed %.3f seconds, thread creation time %.3f us\n", timeUsed, - timeUsed*1e6/kThreads); + timeUsed * 1e6 / kThreads); printf("number of created threads %d, g_count = %d\n", muduo::Thread::numCreated(), g_count.get()); - for (int i = 0; i < kThreads; ++i) - { + for (int i = 0; i < kThreads; ++i) { muduo::Timestamp now(muduo::Timestamp::now()); muduo::Thread t2(std::bind(threadFunc2, now)); t2.start(); t2.join(); } - if (g_verbose) - { + if (g_verbose) { muduo::MutexLockGuard lock(g_mutex); - for (const auto& delay : g_delays) - { - printf("delay = %d, count = %d\n", - delay.first, delay.second); + for (const auto &delay : g_delays) { + printf("delay = %d, count = %d\n", delay.first, delay.second); } } diff --git a/muduo/base/tests/Thread_test.cc b/muduo/base/tests/Thread_test.cc index d6e78b925..cf6a826c4 100644 --- a/muduo/base/tests/Thread_test.cc +++ b/muduo/base/tests/Thread_test.cc @@ -1,56 +1,44 @@ -#include "muduo/base/Thread.h" #include "muduo/base/CurrentThread.h" +#include "muduo/base/Thread.h" -#include #include +#include #include -void mysleep(int seconds) -{ - timespec t = { seconds, 0 }; +void mysleep(int seconds) { + timespec t = {seconds, 0}; nanosleep(&t, NULL); } -void threadFunc() -{ - printf("tid=%d\n", muduo::CurrentThread::tid()); -} +void threadFunc() { printf("tid=%d\n", muduo::CurrentThread::tid()); } -void threadFunc2(int x) -{ +void threadFunc2(int x) { printf("tid=%d, x=%d\n", muduo::CurrentThread::tid(), x); } -void threadFunc3() -{ +void threadFunc3() { printf("tid=%d\n", muduo::CurrentThread::tid()); mysleep(1); } -class Foo -{ - public: - explicit Foo(double x) - : x_(x) - { - } +class Foo { +public: + explicit Foo(double x) : x_(x) {} - void memberFunc() - { + void memberFunc() { printf("tid=%d, Foo::x_=%f\n", muduo::CurrentThread::tid(), x_); } - void memberFunc2(const std::string& text) - { - printf("tid=%d, Foo::x_=%f, text=%s\n", muduo::CurrentThread::tid(), x_, text.c_str()); + void memberFunc2(const std::string &text) { + printf("tid=%d, Foo::x_=%f, text=%s\n", muduo::CurrentThread::tid(), x_, + text.c_str()); } - private: +private: double x_; }; -int main() -{ +int main() { printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid()); muduo::Thread t1(threadFunc); @@ -70,7 +58,8 @@ int main() t3.start(); t3.join(); - muduo::Thread t4(std::bind(&Foo::memberFunc2, std::ref(foo), std::string("Shuo Chen"))); + muduo::Thread t4( + std::bind(&Foo::memberFunc2, std::ref(foo), std::string("Shuo Chen"))); t4.start(); t4.join(); diff --git a/muduo/base/tests/TimeZone_unittest.cc b/muduo/base/tests/TimeZone_unittest.cc index 5d1de82f0..ede862191 100644 --- a/muduo/base/tests/TimeZone_unittest.cc +++ b/muduo/base/tests/TimeZone_unittest.cc @@ -7,9 +7,8 @@ using muduo::TimeZone; -struct tm getTm(int year, int month, int day, - int hour, int minute, int seconds) -{ +struct tm getTm(int year, int month, int day, int hour, int minute, + int seconds) { struct tm gmt; muduo::memZero(&gmt, sizeof gmt); gmt.tm_year = year - 1900; @@ -21,252 +20,224 @@ struct tm getTm(int year, int month, int day, return gmt; } -struct tm getTm(const char* str) -{ +struct tm getTm(const char *str) { struct tm gmt; muduo::memZero(&gmt, sizeof gmt); strptime(str, "%F %T", &gmt); return gmt; } -time_t getGmt(int year, int month, int day, - int hour, int minute, int seconds) -{ +time_t getGmt(int year, int month, int day, int hour, int minute, int seconds) { struct tm gmt = getTm(year, month, day, hour, minute, seconds); return timegm(&gmt); } -time_t getGmt(const char* str) -{ +time_t getGmt(const char *str) { struct tm gmt = getTm(str); return timegm(&gmt); } -struct TestCase -{ - const char* gmt; - const char* local; +struct TestCase { + const char *gmt; + const char *local; bool isdst; }; -void test(const TimeZone& tz, TestCase tc) -{ +void test(const TimeZone &tz, TestCase tc) { time_t gmt = getGmt(tc.gmt); { - struct tm local = tz.toLocalTime(gmt); - char buf[256]; - strftime(buf, sizeof buf, "%F %T%z(%Z)", &local); + struct tm local = tz.toLocalTime(gmt); + char buf[256]; + strftime(buf, sizeof buf, "%F %T%z(%Z)", &local); - if (strcmp(buf, tc.local) != 0 || tc.isdst != local.tm_isdst) - { - printf("WRONG: "); - } - printf("%s -> %s\n", tc.gmt, buf); + if (strcmp(buf, tc.local) != 0 || tc.isdst != local.tm_isdst) { + printf("WRONG: "); + } + printf("%s -> %s\n", tc.gmt, buf); } { - struct tm local = getTm(tc.local); - local.tm_isdst = tc.isdst; - time_t result = tz.fromLocalTime(local); - if (result != gmt) - { - struct tm local2 = tz.toLocalTime(result); - char buf[256]; - strftime(buf, sizeof buf, "%F %T%z(%Z)", &local2); - - printf("WRONG fromLocalTime: %ld %ld %s\n", - static_cast(gmt), static_cast(result), buf); - } + struct tm local = getTm(tc.local); + local.tm_isdst = tc.isdst; + time_t result = tz.fromLocalTime(local); + if (result != gmt) { + struct tm local2 = tz.toLocalTime(result); + char buf[256]; + strftime(buf, sizeof buf, "%F %T%z(%Z)", &local2); + + printf("WRONG fromLocalTime: %ld %ld %s\n", static_cast(gmt), + static_cast(result), buf); + } } } -void testNewYork() -{ +void testNewYork() { TimeZone tz("/usr/share/zoneinfo/America/New_York"); - TestCase cases[] = - { - - { "2006-03-07 00:00:00", "2006-03-06 19:00:00-0500(EST)", false }, - { "2006-04-02 06:59:59", "2006-04-02 01:59:59-0500(EST)", false }, - { "2006-04-02 07:00:00", "2006-04-02 03:00:00-0400(EDT)", true }, - { "2006-05-01 00:00:00", "2006-04-30 20:00:00-0400(EDT)", true }, - { "2006-05-02 01:00:00", "2006-05-01 21:00:00-0400(EDT)", true }, - { "2006-10-21 05:00:00", "2006-10-21 01:00:00-0400(EDT)", true }, - { "2006-10-29 05:59:59", "2006-10-29 01:59:59-0400(EDT)", true }, - { "2006-10-29 06:00:00", "2006-10-29 01:00:00-0500(EST)", false }, - { "2006-10-29 06:59:59", "2006-10-29 01:59:59-0500(EST)", false }, - { "2006-12-31 06:00:00", "2006-12-31 01:00:00-0500(EST)", false }, - { "2007-01-01 00:00:00", "2006-12-31 19:00:00-0500(EST)", false }, - - { "2007-03-07 00:00:00", "2007-03-06 19:00:00-0500(EST)", false }, - { "2007-03-11 06:59:59", "2007-03-11 01:59:59-0500(EST)", false }, - { "2007-03-11 07:00:00", "2007-03-11 03:00:00-0400(EDT)", true }, - { "2007-05-01 00:00:00", "2007-04-30 20:00:00-0400(EDT)", true }, - { "2007-05-02 01:00:00", "2007-05-01 21:00:00-0400(EDT)", true }, - { "2007-10-31 05:00:00", "2007-10-31 01:00:00-0400(EDT)", true }, - { "2007-11-04 05:59:59", "2007-11-04 01:59:59-0400(EDT)", true }, - { "2007-11-04 06:00:00", "2007-11-04 01:00:00-0500(EST)", false }, - { "2007-11-04 06:59:59", "2007-11-04 01:59:59-0500(EST)", false }, - { "2007-12-31 06:00:00", "2007-12-31 01:00:00-0500(EST)", false }, - { "2008-01-01 00:00:00", "2007-12-31 19:00:00-0500(EST)", false }, - - { "2009-03-07 00:00:00", "2009-03-06 19:00:00-0500(EST)", false }, - { "2009-03-08 06:59:59", "2009-03-08 01:59:59-0500(EST)", false }, - { "2009-03-08 07:00:00", "2009-03-08 03:00:00-0400(EDT)", true }, - { "2009-05-01 00:00:00", "2009-04-30 20:00:00-0400(EDT)", true }, - { "2009-05-02 01:00:00", "2009-05-01 21:00:00-0400(EDT)", true }, - { "2009-10-31 05:00:00", "2009-10-31 01:00:00-0400(EDT)", true }, - { "2009-11-01 05:59:59", "2009-11-01 01:59:59-0400(EDT)", true }, - { "2009-11-01 06:00:00", "2009-11-01 01:00:00-0500(EST)", false }, - { "2009-11-01 06:59:59", "2009-11-01 01:59:59-0500(EST)", false }, - { "2009-12-31 06:00:00", "2009-12-31 01:00:00-0500(EST)", false }, - { "2010-01-01 00:00:00", "2009-12-31 19:00:00-0500(EST)", false }, - - { "2010-03-13 00:00:00", "2010-03-12 19:00:00-0500(EST)", false }, - { "2010-03-14 06:59:59", "2010-03-14 01:59:59-0500(EST)", false }, - { "2010-03-14 07:00:00", "2010-03-14 03:00:00-0400(EDT)", true }, - { "2010-05-01 00:00:00", "2010-04-30 20:00:00-0400(EDT)", true }, - { "2010-05-02 01:00:00", "2010-05-01 21:00:00-0400(EDT)", true }, - { "2010-11-06 05:00:00", "2010-11-06 01:00:00-0400(EDT)", true }, - { "2010-11-07 05:59:59", "2010-11-07 01:59:59-0400(EDT)", true }, - { "2010-11-07 06:00:00", "2010-11-07 01:00:00-0500(EST)", false }, - { "2010-11-07 06:59:59", "2010-11-07 01:59:59-0500(EST)", false }, - { "2010-12-31 06:00:00", "2010-12-31 01:00:00-0500(EST)", false }, - { "2011-01-01 00:00:00", "2010-12-31 19:00:00-0500(EST)", false }, - - { "2011-03-01 00:00:00", "2011-02-28 19:00:00-0500(EST)", false }, - { "2011-03-13 06:59:59", "2011-03-13 01:59:59-0500(EST)", false }, - { "2011-03-13 07:00:00", "2011-03-13 03:00:00-0400(EDT)", true }, - { "2011-05-01 00:00:00", "2011-04-30 20:00:00-0400(EDT)", true }, - { "2011-05-02 01:00:00", "2011-05-01 21:00:00-0400(EDT)", true }, - { "2011-11-06 05:59:59", "2011-11-06 01:59:59-0400(EDT)", true }, - { "2011-11-06 06:00:00", "2011-11-06 01:00:00-0500(EST)", false }, - { "2011-11-06 06:59:59", "2011-11-06 01:59:59-0500(EST)", false }, - { "2011-12-31 06:00:00", "2011-12-31 01:00:00-0500(EST)", false }, - { "2012-01-01 00:00:00", "2011-12-31 19:00:00-0500(EST)", false }, + TestCase cases[] = { + + {"2006-03-07 00:00:00", "2006-03-06 19:00:00-0500(EST)", false}, + {"2006-04-02 06:59:59", "2006-04-02 01:59:59-0500(EST)", false}, + {"2006-04-02 07:00:00", "2006-04-02 03:00:00-0400(EDT)", true}, + {"2006-05-01 00:00:00", "2006-04-30 20:00:00-0400(EDT)", true}, + {"2006-05-02 01:00:00", "2006-05-01 21:00:00-0400(EDT)", true}, + {"2006-10-21 05:00:00", "2006-10-21 01:00:00-0400(EDT)", true}, + {"2006-10-29 05:59:59", "2006-10-29 01:59:59-0400(EDT)", true}, + {"2006-10-29 06:00:00", "2006-10-29 01:00:00-0500(EST)", false}, + {"2006-10-29 06:59:59", "2006-10-29 01:59:59-0500(EST)", false}, + {"2006-12-31 06:00:00", "2006-12-31 01:00:00-0500(EST)", false}, + {"2007-01-01 00:00:00", "2006-12-31 19:00:00-0500(EST)", false}, + + {"2007-03-07 00:00:00", "2007-03-06 19:00:00-0500(EST)", false}, + {"2007-03-11 06:59:59", "2007-03-11 01:59:59-0500(EST)", false}, + {"2007-03-11 07:00:00", "2007-03-11 03:00:00-0400(EDT)", true}, + {"2007-05-01 00:00:00", "2007-04-30 20:00:00-0400(EDT)", true}, + {"2007-05-02 01:00:00", "2007-05-01 21:00:00-0400(EDT)", true}, + {"2007-10-31 05:00:00", "2007-10-31 01:00:00-0400(EDT)", true}, + {"2007-11-04 05:59:59", "2007-11-04 01:59:59-0400(EDT)", true}, + {"2007-11-04 06:00:00", "2007-11-04 01:00:00-0500(EST)", false}, + {"2007-11-04 06:59:59", "2007-11-04 01:59:59-0500(EST)", false}, + {"2007-12-31 06:00:00", "2007-12-31 01:00:00-0500(EST)", false}, + {"2008-01-01 00:00:00", "2007-12-31 19:00:00-0500(EST)", false}, + + {"2009-03-07 00:00:00", "2009-03-06 19:00:00-0500(EST)", false}, + {"2009-03-08 06:59:59", "2009-03-08 01:59:59-0500(EST)", false}, + {"2009-03-08 07:00:00", "2009-03-08 03:00:00-0400(EDT)", true}, + {"2009-05-01 00:00:00", "2009-04-30 20:00:00-0400(EDT)", true}, + {"2009-05-02 01:00:00", "2009-05-01 21:00:00-0400(EDT)", true}, + {"2009-10-31 05:00:00", "2009-10-31 01:00:00-0400(EDT)", true}, + {"2009-11-01 05:59:59", "2009-11-01 01:59:59-0400(EDT)", true}, + {"2009-11-01 06:00:00", "2009-11-01 01:00:00-0500(EST)", false}, + {"2009-11-01 06:59:59", "2009-11-01 01:59:59-0500(EST)", false}, + {"2009-12-31 06:00:00", "2009-12-31 01:00:00-0500(EST)", false}, + {"2010-01-01 00:00:00", "2009-12-31 19:00:00-0500(EST)", false}, + + {"2010-03-13 00:00:00", "2010-03-12 19:00:00-0500(EST)", false}, + {"2010-03-14 06:59:59", "2010-03-14 01:59:59-0500(EST)", false}, + {"2010-03-14 07:00:00", "2010-03-14 03:00:00-0400(EDT)", true}, + {"2010-05-01 00:00:00", "2010-04-30 20:00:00-0400(EDT)", true}, + {"2010-05-02 01:00:00", "2010-05-01 21:00:00-0400(EDT)", true}, + {"2010-11-06 05:00:00", "2010-11-06 01:00:00-0400(EDT)", true}, + {"2010-11-07 05:59:59", "2010-11-07 01:59:59-0400(EDT)", true}, + {"2010-11-07 06:00:00", "2010-11-07 01:00:00-0500(EST)", false}, + {"2010-11-07 06:59:59", "2010-11-07 01:59:59-0500(EST)", false}, + {"2010-12-31 06:00:00", "2010-12-31 01:00:00-0500(EST)", false}, + {"2011-01-01 00:00:00", "2010-12-31 19:00:00-0500(EST)", false}, + + {"2011-03-01 00:00:00", "2011-02-28 19:00:00-0500(EST)", false}, + {"2011-03-13 06:59:59", "2011-03-13 01:59:59-0500(EST)", false}, + {"2011-03-13 07:00:00", "2011-03-13 03:00:00-0400(EDT)", true}, + {"2011-05-01 00:00:00", "2011-04-30 20:00:00-0400(EDT)", true}, + {"2011-05-02 01:00:00", "2011-05-01 21:00:00-0400(EDT)", true}, + {"2011-11-06 05:59:59", "2011-11-06 01:59:59-0400(EDT)", true}, + {"2011-11-06 06:00:00", "2011-11-06 01:00:00-0500(EST)", false}, + {"2011-11-06 06:59:59", "2011-11-06 01:59:59-0500(EST)", false}, + {"2011-12-31 06:00:00", "2011-12-31 01:00:00-0500(EST)", false}, + {"2012-01-01 00:00:00", "2011-12-31 19:00:00-0500(EST)", false}, }; - for (const auto& c : cases) - { + for (const auto &c : cases) { test(tz, c); } } -void testLondon() -{ +void testLondon() { TimeZone tz("/usr/share/zoneinfo/Europe/London"); - TestCase cases[] = - { - - { "2011-03-26 00:00:00", "2011-03-26 00:00:00+0000(GMT)", false }, - { "2011-03-27 00:59:59", "2011-03-27 00:59:59+0000(GMT)", false }, - { "2011-03-27 01:00:00", "2011-03-27 02:00:00+0100(BST)", true }, - { "2011-10-30 00:59:59", "2011-10-30 01:59:59+0100(BST)", true }, - { "2011-10-30 01:00:00", "2011-10-30 01:00:00+0000(GMT)", false }, - { "2012-10-30 01:59:59", "2012-10-30 01:59:59+0000(GMT)", false }, - { "2011-12-31 22:00:00", "2011-12-31 22:00:00+0000(GMT)", false }, - { "2012-01-01 00:00:00", "2012-01-01 00:00:00+0000(GMT)", false }, - - { "2012-03-24 00:00:00", "2012-03-24 00:00:00+0000(GMT)", false }, - { "2012-03-25 00:59:59", "2012-03-25 00:59:59+0000(GMT)", false }, - { "2012-03-25 01:00:00", "2012-03-25 02:00:00+0100(BST)", true }, - { "2012-10-28 00:59:59", "2012-10-28 01:59:59+0100(BST)", true }, - { "2012-10-28 01:00:00", "2012-10-28 01:00:00+0000(GMT)", false }, - { "2012-10-28 01:59:59", "2012-10-28 01:59:59+0000(GMT)", false }, - { "2012-12-31 22:00:00", "2012-12-31 22:00:00+0000(GMT)", false }, - { "2013-01-01 00:00:00", "2013-01-01 00:00:00+0000(GMT)", false }, + TestCase cases[] = { + + {"2011-03-26 00:00:00", "2011-03-26 00:00:00+0000(GMT)", false}, + {"2011-03-27 00:59:59", "2011-03-27 00:59:59+0000(GMT)", false}, + {"2011-03-27 01:00:00", "2011-03-27 02:00:00+0100(BST)", true}, + {"2011-10-30 00:59:59", "2011-10-30 01:59:59+0100(BST)", true}, + {"2011-10-30 01:00:00", "2011-10-30 01:00:00+0000(GMT)", false}, + {"2012-10-30 01:59:59", "2012-10-30 01:59:59+0000(GMT)", false}, + {"2011-12-31 22:00:00", "2011-12-31 22:00:00+0000(GMT)", false}, + {"2012-01-01 00:00:00", "2012-01-01 00:00:00+0000(GMT)", false}, + + {"2012-03-24 00:00:00", "2012-03-24 00:00:00+0000(GMT)", false}, + {"2012-03-25 00:59:59", "2012-03-25 00:59:59+0000(GMT)", false}, + {"2012-03-25 01:00:00", "2012-03-25 02:00:00+0100(BST)", true}, + {"2012-10-28 00:59:59", "2012-10-28 01:59:59+0100(BST)", true}, + {"2012-10-28 01:00:00", "2012-10-28 01:00:00+0000(GMT)", false}, + {"2012-10-28 01:59:59", "2012-10-28 01:59:59+0000(GMT)", false}, + {"2012-12-31 22:00:00", "2012-12-31 22:00:00+0000(GMT)", false}, + {"2013-01-01 00:00:00", "2013-01-01 00:00:00+0000(GMT)", false}, }; - for (const auto& c : cases) - { + for (const auto &c : cases) { test(tz, c); } } -void testHongKong() -{ +void testHongKong() { TimeZone tz("/usr/share/zoneinfo/Asia/Hong_Kong"); - TestCase cases[] = - { + TestCase cases[] = { - { "2011-04-03 00:00:00", "2011-04-03 08:00:00+0800(HKT)", false}, + {"2011-04-03 00:00:00", "2011-04-03 08:00:00+0800(HKT)", false}, }; - for (const auto& c : cases) - { + for (const auto &c : cases) { test(tz, c); } } -void testSydney() -{ +void testSydney() { TimeZone tz("/usr/share/zoneinfo/Australia/Sydney"); - TestCase cases[] = - { + TestCase cases[] = { - { "2011-01-01 00:00:00", "2011-01-01 11:00:00+1100(EST)", true }, - { "2011-04-02 15:59:59", "2011-04-03 02:59:59+1100(EST)", true }, - { "2011-04-02 16:00:00", "2011-04-03 02:00:00+1000(EST)", false }, - { "2011-04-02 16:59:59", "2011-04-03 02:59:59+1000(EST)", false }, - { "2011-05-02 01:00:00", "2011-05-02 11:00:00+1000(EST)", false }, - { "2011-10-01 15:59:59", "2011-10-02 01:59:59+1000(EST)", false }, - { "2011-10-01 16:00:00", "2011-10-02 03:00:00+1100(EST)", true }, - { "2011-12-31 22:00:00", "2012-01-01 09:00:00+1100(EST)", true }, + {"2011-01-01 00:00:00", "2011-01-01 11:00:00+1100(EST)", true}, + {"2011-04-02 15:59:59", "2011-04-03 02:59:59+1100(EST)", true}, + {"2011-04-02 16:00:00", "2011-04-03 02:00:00+1000(EST)", false}, + {"2011-04-02 16:59:59", "2011-04-03 02:59:59+1000(EST)", false}, + {"2011-05-02 01:00:00", "2011-05-02 11:00:00+1000(EST)", false}, + {"2011-10-01 15:59:59", "2011-10-02 01:59:59+1000(EST)", false}, + {"2011-10-01 16:00:00", "2011-10-02 03:00:00+1100(EST)", true}, + {"2011-12-31 22:00:00", "2012-01-01 09:00:00+1100(EST)", true}, }; - for (const auto& c : cases) - { + for (const auto &c : cases) { test(tz, c); } } -void testUtc() -{ - const int kRange = 100*1000*1000; - for (time_t t = -kRange; t <= kRange; t += 11) - { - struct tm* t1 = gmtime(&t); +void testUtc() { + const int kRange = 100 * 1000 * 1000; + for (time_t t = -kRange; t <= kRange; t += 11) { + struct tm *t1 = gmtime(&t); struct tm t2 = TimeZone::toUtcTime(t, true); char buf1[80], buf2[80]; strftime(buf1, sizeof buf1, "%F %T %u %j", t1); strftime(buf2, sizeof buf2, "%F %T %u %j", &t2); - if (strcmp(buf1, buf2) != 0) - { + if (strcmp(buf1, buf2) != 0) { printf("'%s' != '%s'\n", buf1, buf2); assert(0); } time_t t3 = TimeZone::fromUtcTime(t2); - if (t != t3) - { + if (t != t3) { printf("%ld != %ld\n", static_cast(t), static_cast(t3)); assert(0); } } } -void testFixedTimezone() -{ - TimeZone tz(8*3600, "CST"); - TestCase cases[] = - { +void testFixedTimezone() { + TimeZone tz(8 * 3600, "CST"); + TestCase cases[] = { - { "2014-04-03 00:00:00", "2014-04-03 08:00:00+0800(CST)", false}, + {"2014-04-03 00:00:00", "2014-04-03 08:00:00+0800(CST)", false}, }; - for (const auto& c : cases) - { + for (const auto &c : cases) { test(tz, c); } } -int main() -{ +int main() { testNewYork(); testLondon(); testSydney(); diff --git a/muduo/base/tests/Timestamp_unittest.cc b/muduo/base/tests/Timestamp_unittest.cc index 5e27592b6..3b53952d9 100644 --- a/muduo/base/tests/Timestamp_unittest.cc +++ b/muduo/base/tests/Timestamp_unittest.cc @@ -1,66 +1,51 @@ #include "muduo/base/Timestamp.h" -#include #include +#include using muduo::Timestamp; -void passByConstReference(const Timestamp& x) -{ +void passByConstReference(const Timestamp &x) { printf("%s\n", x.toString().c_str()); } -void passByValue(Timestamp x) -{ - printf("%s\n", x.toString().c_str()); -} +void passByValue(Timestamp x) { printf("%s\n", x.toString().c_str()); } -void benchmark() -{ - const int kNumber = 1000*1000; +void benchmark() { + const int kNumber = 1000 * 1000; std::vector stamps; stamps.reserve(kNumber); - for (int i = 0; i < kNumber; ++i) - { + for (int i = 0; i < kNumber; ++i) { stamps.push_back(Timestamp::now()); } printf("%s\n", stamps.front().toString().c_str()); printf("%s\n", stamps.back().toString().c_str()); printf("%f\n", timeDifference(stamps.back(), stamps.front())); - int increments[100] = { 0 }; + int increments[100] = {0}; int64_t start = stamps.front().microSecondsSinceEpoch(); - for (int i = 1; i < kNumber; ++i) - { + for (int i = 1; i < kNumber; ++i) { int64_t next = stamps[i].microSecondsSinceEpoch(); int64_t inc = next - start; start = next; - if (inc < 0) - { + if (inc < 0) { printf("reverse!\n"); - } - else if (inc < 100) - { + } else if (inc < 100) { ++increments[inc]; - } - else - { + } else { printf("big gap %d\n", static_cast(inc)); } } - for (int i = 0; i < 100; ++i) - { + for (int i = 0; i < 100; ++i) { printf("%2d: %d\n", i, increments[i]); } } -int main() -{ +int main() { Timestamp now(Timestamp::now()); printf("%s\n", now.toString().c_str()); passByValue(now); passByConstReference(now); benchmark(); } - diff --git a/muduo/net/Acceptor.cc b/muduo/net/Acceptor.cc index 39d0cb6be..925e85e3e 100644 --- a/muduo/net/Acceptor.cc +++ b/muduo/net/Acceptor.cc @@ -22,63 +22,51 @@ using namespace muduo; using namespace muduo::net; -Acceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr, bool reuseport) - : loop_(loop), - acceptSocket_(sockets::createNonblockingOrDie(listenAddr.family())), - acceptChannel_(loop, acceptSocket_.fd()), - listening_(false), - idleFd_(::open("/dev/null", O_RDONLY | O_CLOEXEC)) -{ +Acceptor::Acceptor(EventLoop *loop, const InetAddress &listenAddr, + bool reuseport) + : loop_(loop), + acceptSocket_(sockets::createNonblockingOrDie(listenAddr.family())), + acceptChannel_(loop, acceptSocket_.fd()), listening_(false), + idleFd_(::open("/dev/null", O_RDONLY | O_CLOEXEC)) { assert(idleFd_ >= 0); acceptSocket_.setReuseAddr(true); acceptSocket_.setReusePort(reuseport); acceptSocket_.bindAddress(listenAddr); - acceptChannel_.setReadCallback( - std::bind(&Acceptor::handleRead, this)); + acceptChannel_.setReadCallback(std::bind(&Acceptor::handleRead, this)); } -Acceptor::~Acceptor() -{ +Acceptor::~Acceptor() { acceptChannel_.disableAll(); acceptChannel_.remove(); ::close(idleFd_); } -void Acceptor::listen() -{ +void Acceptor::listen() { loop_->assertInLoopThread(); listening_ = true; acceptSocket_.listen(); acceptChannel_.enableReading(); } -void Acceptor::handleRead() -{ +void Acceptor::handleRead() { loop_->assertInLoopThread(); InetAddress peerAddr; - //FIXME loop until no more + // FIXME loop until no more int connfd = acceptSocket_.accept(&peerAddr); - if (connfd >= 0) - { + if (connfd >= 0) { // string hostport = peerAddr.toIpPort(); // LOG_TRACE << "Accepts of " << hostport; - if (newConnectionCallback_) - { + if (newConnectionCallback_) { newConnectionCallback_(connfd, peerAddr); - } - else - { + } else { sockets::close(connfd); } - } - else - { + } else { LOG_SYSERR << "in Acceptor::handleRead"; // Read the section named "The special problem of // accept()ing when you can't" in libev's doc. // By Marc Lehmann, author of libev. - if (errno == EMFILE) - { + if (errno == EMFILE) { ::close(idleFd_); idleFd_ = ::accept(acceptSocket_.fd(), NULL, NULL); ::close(idleFd_); @@ -86,4 +74,3 @@ void Acceptor::handleRead() } } } - diff --git a/muduo/net/Acceptor.h b/muduo/net/Acceptor.h index 761d073c4..b7cf5726f 100644 --- a/muduo/net/Acceptor.h +++ b/muduo/net/Acceptor.h @@ -16,10 +16,8 @@ #include "muduo/net/Channel.h" #include "muduo/net/Socket.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class EventLoop; class InetAddress; @@ -27,29 +25,30 @@ class InetAddress; /// /// Acceptor of incoming TCP connections. /// -class Acceptor : noncopyable -{ - public: - typedef std::function NewConnectionCallback; +class Acceptor : noncopyable { +public: + typedef std::function + NewConnectionCallback; - Acceptor(EventLoop* loop, const InetAddress& listenAddr, bool reuseport); + Acceptor(EventLoop *loop, const InetAddress &listenAddr, bool reuseport); ~Acceptor(); - void setNewConnectionCallback(const NewConnectionCallback& cb) - { newConnectionCallback_ = cb; } + void setNewConnectionCallback(const NewConnectionCallback &cb) { + newConnectionCallback_ = cb; + } void listen(); bool listening() const { return listening_; } // Deprecated, use the correct spelling one above. - // Leave the wrong spelling here in case one needs to grep it for error messages. - // bool listenning() const { return listening(); } + // Leave the wrong spelling here in case one needs to grep it for error + // messages. bool listenning() const { return listening(); } - private: +private: void handleRead(); - EventLoop* loop_; + EventLoop *loop_; Socket acceptSocket_; Channel acceptChannel_; NewConnectionCallback newConnectionCallback_; @@ -57,7 +56,7 @@ class Acceptor : noncopyable int idleFd_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_ACCEPTOR_H +#endif // MUDUO_NET_ACCEPTOR_H diff --git a/muduo/net/Buffer.cc b/muduo/net/Buffer.cc index 7c921fc40..1ce061b9d 100644 --- a/muduo/net/Buffer.cc +++ b/muduo/net/Buffer.cc @@ -22,13 +22,12 @@ const char Buffer::kCRLF[] = "\r\n"; const size_t Buffer::kCheapPrepend; const size_t Buffer::kInitialSize; -ssize_t Buffer::readFd(int fd, int* savedErrno) -{ +ssize_t Buffer::readFd(int fd, int *savedErrno) { // saved an ioctl()/FIONREAD call to tell how much to read char extrabuf[65536]; struct iovec vec[2]; const size_t writable = writableBytes(); - vec[0].iov_base = begin()+writerIndex_; + vec[0].iov_base = begin() + writerIndex_; vec[0].iov_len = writable; vec[1].iov_base = extrabuf; vec[1].iov_len = sizeof extrabuf; @@ -36,16 +35,11 @@ ssize_t Buffer::readFd(int fd, int* savedErrno) // when extrabuf is used, we read 128k-1 bytes at most. const int iovcnt = (writable < sizeof extrabuf) ? 2 : 1; const ssize_t n = sockets::readv(fd, vec, iovcnt); - if (n < 0) - { + if (n < 0) { *savedErrno = errno; - } - else if (implicit_cast(n) <= writable) - { + } else if (implicit_cast(n) <= writable) { writerIndex_ += n; - } - else - { + } else { writerIndex_ = buffer_.size(); append(extrabuf, n - writable); } @@ -55,4 +49,3 @@ ssize_t Buffer::readFd(int fd, int* savedErrno) // } return n; } - diff --git a/muduo/net/Buffer.h b/muduo/net/Buffer.h index 4fa82d4bd..e6ca116a0 100644 --- a/muduo/net/Buffer.h +++ b/muduo/net/Buffer.h @@ -11,9 +11,9 @@ #ifndef MUDUO_NET_BUFFER_H #define MUDUO_NET_BUFFER_H -#include "muduo/base/copyable.h" #include "muduo/base/StringPiece.h" #include "muduo/base/Types.h" +#include "muduo/base/copyable.h" #include "muduo/net/Endian.h" @@ -24,10 +24,8 @@ #include //#include // ssize_t -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { /// A buffer class modeled after org.jboss.netty.buffer.ChannelBuffer /// @@ -39,17 +37,14 @@ namespace net /// | | | | /// 0 <= readerIndex <= writerIndex <= size /// @endcode -class Buffer : public muduo::copyable -{ - public: +class Buffer : public muduo::copyable { +public: static const size_t kCheapPrepend = 8; static const size_t kInitialSize = 1024; explicit Buffer(size_t initialSize = kInitialSize) - : buffer_(kCheapPrepend + initialSize), - readerIndex_(kCheapPrepend), - writerIndex_(kCheapPrepend) - { + : buffer_(kCheapPrepend + initialSize), readerIndex_(kCheapPrepend), + writerIndex_(kCheapPrepend) { assert(readableBytes() == 0); assert(writableBytes() == initialSize); assert(prependableBytes() == kCheapPrepend); @@ -58,162 +53,119 @@ class Buffer : public muduo::copyable // implicit copy-ctor, move-ctor, dtor and assignment are fine // NOTE: implicit move-ctor is added in g++ 4.6 - void swap(Buffer& rhs) - { + void swap(Buffer &rhs) { buffer_.swap(rhs.buffer_); std::swap(readerIndex_, rhs.readerIndex_); std::swap(writerIndex_, rhs.writerIndex_); } - size_t readableBytes() const - { return writerIndex_ - readerIndex_; } + size_t readableBytes() const { return writerIndex_ - readerIndex_; } - size_t writableBytes() const - { return buffer_.size() - writerIndex_; } + size_t writableBytes() const { return buffer_.size() - writerIndex_; } - size_t prependableBytes() const - { return readerIndex_; } + size_t prependableBytes() const { return readerIndex_; } - const char* peek() const - { return begin() + readerIndex_; } + const char *peek() const { return begin() + readerIndex_; } - const char* findCRLF() const - { + const char *findCRLF() const { // FIXME: replace with memmem()? - const char* crlf = std::search(peek(), beginWrite(), kCRLF, kCRLF+2); + const char *crlf = std::search(peek(), beginWrite(), kCRLF, kCRLF + 2); return crlf == beginWrite() ? NULL : crlf; } - const char* findCRLF(const char* start) const - { + const char *findCRLF(const char *start) const { assert(peek() <= start); assert(start <= beginWrite()); // FIXME: replace with memmem()? - const char* crlf = std::search(start, beginWrite(), kCRLF, kCRLF+2); + const char *crlf = std::search(start, beginWrite(), kCRLF, kCRLF + 2); return crlf == beginWrite() ? NULL : crlf; } - const char* findEOL() const - { - const void* eol = memchr(peek(), '\n', readableBytes()); - return static_cast(eol); + const char *findEOL() const { + const void *eol = memchr(peek(), '\n', readableBytes()); + return static_cast(eol); } - const char* findEOL(const char* start) const - { + const char *findEOL(const char *start) const { assert(peek() <= start); assert(start <= beginWrite()); - const void* eol = memchr(start, '\n', beginWrite() - start); - return static_cast(eol); + const void *eol = memchr(start, '\n', beginWrite() - start); + return static_cast(eol); } // retrieve returns void, to prevent // string str(retrieve(readableBytes()), readableBytes()); // the evaluation of two functions are unspecified - void retrieve(size_t len) - { + void retrieve(size_t len) { assert(len <= readableBytes()); - if (len < readableBytes()) - { + if (len < readableBytes()) { readerIndex_ += len; - } - else - { + } else { retrieveAll(); } } - void retrieveUntil(const char* end) - { + void retrieveUntil(const char *end) { assert(peek() <= end); assert(end <= beginWrite()); retrieve(end - peek()); } - void retrieveInt64() - { - retrieve(sizeof(int64_t)); - } + void retrieveInt64() { retrieve(sizeof(int64_t)); } - void retrieveInt32() - { - retrieve(sizeof(int32_t)); - } + void retrieveInt32() { retrieve(sizeof(int32_t)); } - void retrieveInt16() - { - retrieve(sizeof(int16_t)); - } + void retrieveInt16() { retrieve(sizeof(int16_t)); } - void retrieveInt8() - { - retrieve(sizeof(int8_t)); - } + void retrieveInt8() { retrieve(sizeof(int8_t)); } - void retrieveAll() - { + void retrieveAll() { readerIndex_ = kCheapPrepend; writerIndex_ = kCheapPrepend; } - string retrieveAllAsString() - { - return retrieveAsString(readableBytes()); - } + string retrieveAllAsString() { return retrieveAsString(readableBytes()); } - string retrieveAsString(size_t len) - { + string retrieveAsString(size_t len) { assert(len <= readableBytes()); string result(peek(), len); retrieve(len); return result; } - StringPiece toStringPiece() const - { + StringPiece toStringPiece() const { return StringPiece(peek(), static_cast(readableBytes())); } - void append(const StringPiece& str) - { - append(str.data(), str.size()); - } + void append(const StringPiece &str) { append(str.data(), str.size()); } - void append(const char* /*restrict*/ data, size_t len) - { + void append(const char * /*restrict*/ data, size_t len) { ensureWritableBytes(len); - std::copy(data, data+len, beginWrite()); + std::copy(data, data + len, beginWrite()); hasWritten(len); } - void append(const void* /*restrict*/ data, size_t len) - { - append(static_cast(data), len); + void append(const void * /*restrict*/ data, size_t len) { + append(static_cast(data), len); } - void ensureWritableBytes(size_t len) - { - if (writableBytes() < len) - { + void ensureWritableBytes(size_t len) { + if (writableBytes() < len) { makeSpace(len); } assert(writableBytes() >= len); } - char* beginWrite() - { return begin() + writerIndex_; } + char *beginWrite() { return begin() + writerIndex_; } - const char* beginWrite() const - { return begin() + writerIndex_; } + const char *beginWrite() const { return begin() + writerIndex_; } - void hasWritten(size_t len) - { + void hasWritten(size_t len) { assert(len <= writableBytes()); writerIndex_ += len; } - void unwrite(size_t len) - { + void unwrite(size_t len) { assert(len <= readableBytes()); writerIndex_ -= len; } @@ -221,8 +173,7 @@ class Buffer : public muduo::copyable /// /// Append int64_t using network endian /// - void appendInt64(int64_t x) - { + void appendInt64(int64_t x) { int64_t be64 = sockets::hostToNetwork64(x); append(&be64, sizeof be64); } @@ -230,29 +181,23 @@ class Buffer : public muduo::copyable /// /// Append int32_t using network endian /// - void appendInt32(int32_t x) - { + void appendInt32(int32_t x) { int32_t be32 = sockets::hostToNetwork32(x); append(&be32, sizeof be32); } - void appendInt16(int16_t x) - { + void appendInt16(int16_t x) { int16_t be16 = sockets::hostToNetwork16(x); append(&be16, sizeof be16); } - void appendInt8(int8_t x) - { - append(&x, sizeof x); - } + void appendInt8(int8_t x) { append(&x, sizeof x); } /// /// Read int64_t from network endian /// /// Require: buf->readableBytes() >= sizeof(int32_t) - int64_t readInt64() - { + int64_t readInt64() { int64_t result = peekInt64(); retrieveInt64(); return result; @@ -262,22 +207,19 @@ class Buffer : public muduo::copyable /// Read int32_t from network endian /// /// Require: buf->readableBytes() >= sizeof(int32_t) - int32_t readInt32() - { + int32_t readInt32() { int32_t result = peekInt32(); retrieveInt32(); return result; } - int16_t readInt16() - { + int16_t readInt16() { int16_t result = peekInt16(); retrieveInt16(); return result; } - int8_t readInt8() - { + int8_t readInt8() { int8_t result = peekInt8(); retrieveInt8(); return result; @@ -287,8 +229,7 @@ class Buffer : public muduo::copyable /// Peek int64_t from network endian /// /// Require: buf->readableBytes() >= sizeof(int64_t) - int64_t peekInt64() const - { + int64_t peekInt64() const { assert(readableBytes() >= sizeof(int64_t)); int64_t be64 = 0; ::memcpy(&be64, peek(), sizeof be64); @@ -299,24 +240,21 @@ class Buffer : public muduo::copyable /// Peek int32_t from network endian /// /// Require: buf->readableBytes() >= sizeof(int32_t) - int32_t peekInt32() const - { + int32_t peekInt32() const { assert(readableBytes() >= sizeof(int32_t)); int32_t be32 = 0; ::memcpy(&be32, peek(), sizeof be32); return sockets::networkToHost32(be32); } - int16_t peekInt16() const - { + int16_t peekInt16() const { assert(readableBytes() >= sizeof(int16_t)); int16_t be16 = 0; ::memcpy(&be16, peek(), sizeof be16); return sockets::networkToHost16(be16); } - int8_t peekInt8() const - { + int8_t peekInt8() const { assert(readableBytes() >= sizeof(int8_t)); int8_t x = *peek(); return x; @@ -325,8 +263,7 @@ class Buffer : public muduo::copyable /// /// Prepend int64_t using network endian /// - void prependInt64(int64_t x) - { + void prependInt64(int64_t x) { int64_t be64 = sockets::hostToNetwork64(x); prepend(&be64, sizeof be64); } @@ -334,81 +271,63 @@ class Buffer : public muduo::copyable /// /// Prepend int32_t using network endian /// - void prependInt32(int32_t x) - { + void prependInt32(int32_t x) { int32_t be32 = sockets::hostToNetwork32(x); prepend(&be32, sizeof be32); } - void prependInt16(int16_t x) - { + void prependInt16(int16_t x) { int16_t be16 = sockets::hostToNetwork16(x); prepend(&be16, sizeof be16); } - void prependInt8(int8_t x) - { - prepend(&x, sizeof x); - } + void prependInt8(int8_t x) { prepend(&x, sizeof x); } - void prepend(const void* /*restrict*/ data, size_t len) - { + void prepend(const void * /*restrict*/ data, size_t len) { assert(len <= prependableBytes()); readerIndex_ -= len; - const char* d = static_cast(data); - std::copy(d, d+len, begin()+readerIndex_); + const char *d = static_cast(data); + std::copy(d, d + len, begin() + readerIndex_); } - void shrink(size_t reserve) - { + void shrink(size_t reserve) { // FIXME: use vector::shrink_to_fit() in C++ 11 if possible. Buffer other; - other.ensureWritableBytes(readableBytes()+reserve); + other.ensureWritableBytes(readableBytes() + reserve); other.append(toStringPiece()); swap(other); } - size_t internalCapacity() const - { - return buffer_.capacity(); - } + size_t internalCapacity() const { return buffer_.capacity(); } /// Read data directly into buffer. /// /// It may implement with readv(2) /// @return result of read(2), @c errno is saved - ssize_t readFd(int fd, int* savedErrno); - - private: + ssize_t readFd(int fd, int *savedErrno); - char* begin() - { return &*buffer_.begin(); } +private: + char *begin() { return &*buffer_.begin(); } - const char* begin() const - { return &*buffer_.begin(); } + const char *begin() const { return &*buffer_.begin(); } - void makeSpace(size_t len) - { - if (writableBytes() + prependableBytes() < len + kCheapPrepend) - { + void makeSpace(size_t len) { + if (writableBytes() + prependableBytes() < len + kCheapPrepend) { // FIXME: move readable data - buffer_.resize(writerIndex_+len); - } - else - { + buffer_.resize(writerIndex_ + len); + } else { // move readable data to the front, make space inside buffer assert(kCheapPrepend < readerIndex_); size_t readable = readableBytes(); - std::copy(begin()+readerIndex_, - begin()+writerIndex_, - begin()+kCheapPrepend); + std::copy(begin() + readerIndex_, begin() + writerIndex_, + begin() + kCheapPrepend); readerIndex_ = kCheapPrepend; writerIndex_ = readerIndex_ + readable; assert(readable == readableBytes()); } } - private: +private: std::vector buffer_; size_t readerIndex_; size_t writerIndex_; @@ -416,7 +335,7 @@ class Buffer : public muduo::copyable static const char kCRLF[]; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_BUFFER_H +#endif // MUDUO_NET_BUFFER_H diff --git a/muduo/net/Callbacks.h b/muduo/net/Callbacks.h index 443ed791e..9661a5133 100644 --- a/muduo/net/Callbacks.h +++ b/muduo/net/Callbacks.h @@ -16,8 +16,7 @@ #include #include -namespace muduo -{ +namespace muduo { using std::placeholders::_1; using std::placeholders::_2; @@ -25,35 +24,30 @@ using std::placeholders::_3; // should really belong to base/Types.h, but is not included there. -template -inline T* get_pointer(const std::shared_ptr& ptr) -{ +template inline T *get_pointer(const std::shared_ptr &ptr) { return ptr.get(); } -template -inline T* get_pointer(const std::unique_ptr& ptr) -{ +template inline T *get_pointer(const std::unique_ptr &ptr) { return ptr.get(); } // Adapted from google-protobuf stubs/common.h // see License in muduo/base/Types.h -template -inline ::std::shared_ptr down_pointer_cast(const ::std::shared_ptr& f) { - if (false) - { - implicit_cast(0); +template +inline ::std::shared_ptr +down_pointer_cast(const ::std::shared_ptr &f) { + if (false) { + implicit_cast(0); } #ifndef NDEBUG - assert(f == NULL || dynamic_cast(get_pointer(f)) != NULL); + assert(f == NULL || dynamic_cast(get_pointer(f)) != NULL); #endif return ::std::static_pointer_cast(f); } -namespace net -{ +namespace net { // All client visible callbacks go here. @@ -61,22 +55,21 @@ class Buffer; class TcpConnection; typedef std::shared_ptr TcpConnectionPtr; typedef std::function TimerCallback; -typedef std::function ConnectionCallback; -typedef std::function CloseCallback; -typedef std::function WriteCompleteCallback; -typedef std::function HighWaterMarkCallback; +typedef std::function ConnectionCallback; +typedef std::function CloseCallback; +typedef std::function WriteCompleteCallback; +typedef std::function + HighWaterMarkCallback; // the data has been read to (buf, len) -typedef std::function MessageCallback; +typedef std::function + MessageCallback; -void defaultConnectionCallback(const TcpConnectionPtr& conn); -void defaultMessageCallback(const TcpConnectionPtr& conn, - Buffer* buffer, +void defaultConnectionCallback(const TcpConnectionPtr &conn); +void defaultMessageCallback(const TcpConnectionPtr &conn, Buffer *buffer, Timestamp receiveTime); -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_CALLBACKS_H +#endif // MUDUO_NET_CALLBACKS_H diff --git a/muduo/net/Channel.cc b/muduo/net/Channel.cc index 1e9a40ae7..9fb0eba1f 100644 --- a/muduo/net/Channel.cc +++ b/muduo/net/Channel.cc @@ -6,8 +6,8 @@ // Author: Shuo Chen (chenshuo at chenshuo dot com) -#include "muduo/base/Logging.h" #include "muduo/net/Channel.h" +#include "muduo/base/Logging.h" #include "muduo/net/EventLoop.h" #include @@ -21,110 +21,83 @@ const int Channel::kNoneEvent = 0; const int Channel::kReadEvent = POLLIN | POLLPRI; const int Channel::kWriteEvent = POLLOUT; -Channel::Channel(EventLoop* loop, int fd__) - : loop_(loop), - fd_(fd__), - events_(0), - revents_(0), - index_(-1), - logHup_(true), - tied_(false), - eventHandling_(false), - addedToLoop_(false) -{ -} +Channel::Channel(EventLoop *loop, int fd__) + : loop_(loop), fd_(fd__), events_(0), revents_(0), index_(-1), + logHup_(true), tied_(false), eventHandling_(false), addedToLoop_(false) {} -Channel::~Channel() -{ +Channel::~Channel() { assert(!eventHandling_); assert(!addedToLoop_); - if (loop_->isInLoopThread()) - { + if (loop_->isInLoopThread()) { assert(!loop_->hasChannel(this)); } } -void Channel::tie(const std::shared_ptr& obj) -{ +void Channel::tie(const std::shared_ptr &obj) { tie_ = obj; tied_ = true; } -void Channel::update() -{ +void Channel::update() { addedToLoop_ = true; loop_->updateChannel(this); } -void Channel::remove() -{ +void Channel::remove() { assert(isNoneEvent()); addedToLoop_ = false; loop_->removeChannel(this); } -void Channel::handleEvent(Timestamp receiveTime) -{ +void Channel::handleEvent(Timestamp receiveTime) { std::shared_ptr guard; - if (tied_) - { + if (tied_) { guard = tie_.lock(); - if (guard) - { + if (guard) { handleEventWithGuard(receiveTime); } - } - else - { + } else { handleEventWithGuard(receiveTime); } } -void Channel::handleEventWithGuard(Timestamp receiveTime) -{ +void Channel::handleEventWithGuard(Timestamp receiveTime) { eventHandling_ = true; LOG_TRACE << reventsToString(); - if ((revents_ & POLLHUP) && !(revents_ & POLLIN)) - { - if (logHup_) - { + if ((revents_ & POLLHUP) && !(revents_ & POLLIN)) { + if (logHup_) { LOG_WARN << "fd = " << fd_ << " Channel::handle_event() POLLHUP"; } - if (closeCallback_) closeCallback_(); + if (closeCallback_) + closeCallback_(); } - if (revents_ & POLLNVAL) - { + if (revents_ & POLLNVAL) { LOG_WARN << "fd = " << fd_ << " Channel::handle_event() POLLNVAL"; } - if (revents_ & (POLLERR | POLLNVAL)) - { - if (errorCallback_) errorCallback_(); + if (revents_ & (POLLERR | POLLNVAL)) { + if (errorCallback_) + errorCallback_(); } - if (revents_ & (POLLIN | POLLPRI | POLLRDHUP)) - { - if (readCallback_) readCallback_(receiveTime); + if (revents_ & (POLLIN | POLLPRI | POLLRDHUP)) { + if (readCallback_) + readCallback_(receiveTime); } - if (revents_ & POLLOUT) - { - if (writeCallback_) writeCallback_(); + if (revents_ & POLLOUT) { + if (writeCallback_) + writeCallback_(); } eventHandling_ = false; } -string Channel::reventsToString() const -{ +string Channel::reventsToString() const { return eventsToString(fd_, revents_); } -string Channel::eventsToString() const -{ - return eventsToString(fd_, events_); -} +string Channel::eventsToString() const { return eventsToString(fd_, events_); } -string Channel::eventsToString(int fd, int ev) -{ +string Channel::eventsToString(int fd, int ev) { std::ostringstream oss; oss << fd << ": "; if (ev & POLLIN) diff --git a/muduo/net/Channel.h b/muduo/net/Channel.h index bafa224fa..7b6b9d6b2 100644 --- a/muduo/net/Channel.h +++ b/muduo/net/Channel.h @@ -11,16 +11,14 @@ #ifndef MUDUO_NET_CHANNEL_H #define MUDUO_NET_CHANNEL_H -#include "muduo/base/noncopyable.h" #include "muduo/base/Timestamp.h" +#include "muduo/base/noncopyable.h" #include #include -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class EventLoop; @@ -30,28 +28,23 @@ class EventLoop; /// This class doesn't own the file descriptor. /// The file descriptor could be a socket, /// an eventfd, a timerfd, or a signalfd -class Channel : noncopyable -{ - public: +class Channel : noncopyable { +public: typedef std::function EventCallback; typedef std::function ReadEventCallback; - Channel(EventLoop* loop, int fd); + Channel(EventLoop *loop, int fd); ~Channel(); void handleEvent(Timestamp receiveTime); - void setReadCallback(ReadEventCallback cb) - { readCallback_ = std::move(cb); } - void setWriteCallback(EventCallback cb) - { writeCallback_ = std::move(cb); } - void setCloseCallback(EventCallback cb) - { closeCallback_ = std::move(cb); } - void setErrorCallback(EventCallback cb) - { errorCallback_ = std::move(cb); } + void setReadCallback(ReadEventCallback cb) { readCallback_ = std::move(cb); } + void setWriteCallback(EventCallback cb) { writeCallback_ = std::move(cb); } + void setCloseCallback(EventCallback cb) { closeCallback_ = std::move(cb); } + void setErrorCallback(EventCallback cb) { errorCallback_ = std::move(cb); } /// Tie this channel to the owner object managed by shared_ptr, /// prevent the owner object being destroyed in handleEvent. - void tie(const std::shared_ptr&); + void tie(const std::shared_ptr &); int fd() const { return fd_; } int events() const { return events_; } @@ -59,11 +52,26 @@ class Channel : noncopyable // int revents() const { return revents_; } bool isNoneEvent() const { return events_ == kNoneEvent; } - void enableReading() { events_ |= kReadEvent; update(); } - void disableReading() { events_ &= ~kReadEvent; update(); } - void enableWriting() { events_ |= kWriteEvent; update(); } - void disableWriting() { events_ &= ~kWriteEvent; update(); } - void disableAll() { events_ = kNoneEvent; update(); } + void enableReading() { + events_ |= kReadEvent; + update(); + } + void disableReading() { + events_ &= ~kReadEvent; + update(); + } + void enableWriting() { + events_ |= kWriteEvent; + update(); + } + void disableWriting() { + events_ &= ~kWriteEvent; + update(); + } + void disableAll() { + events_ = kNoneEvent; + update(); + } bool isWriting() const { return events_ & kWriteEvent; } bool isReading() const { return events_ & kReadEvent; } @@ -77,10 +85,10 @@ class Channel : noncopyable void doNotLogHup() { logHup_ = false; } - EventLoop* ownerLoop() { return loop_; } + EventLoop *ownerLoop() { return loop_; } void remove(); - private: +private: static string eventsToString(int fd, int ev); void update(); @@ -90,12 +98,12 @@ class Channel : noncopyable static const int kReadEvent; static const int kWriteEvent; - EventLoop* loop_; - const int fd_; - int events_; - int revents_; // it's the received event types of epoll or poll - int index_; // used by Poller. - bool logHup_; + EventLoop *loop_; + const int fd_; + int events_; + int revents_; // it's the received event types of epoll or poll + int index_; // used by Poller. + bool logHup_; std::weak_ptr tie_; bool tied_; @@ -107,7 +115,7 @@ class Channel : noncopyable EventCallback errorCallback_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_CHANNEL_H +#endif // MUDUO_NET_CHANNEL_H diff --git a/muduo/net/Connector.cc b/muduo/net/Connector.cc index 0b492ad95..fc6a79c2b 100644 --- a/muduo/net/Connector.cc +++ b/muduo/net/Connector.cc @@ -21,103 +21,88 @@ using namespace muduo::net; const int Connector::kMaxRetryDelayMs; -Connector::Connector(EventLoop* loop, const InetAddress& serverAddr) - : loop_(loop), - serverAddr_(serverAddr), - connect_(false), - state_(kDisconnected), - retryDelayMs_(kInitRetryDelayMs) -{ +Connector::Connector(EventLoop *loop, const InetAddress &serverAddr) + : loop_(loop), serverAddr_(serverAddr), connect_(false), + state_(kDisconnected), retryDelayMs_(kInitRetryDelayMs) { LOG_DEBUG << "ctor[" << this << "]"; } -Connector::~Connector() -{ +Connector::~Connector() { LOG_DEBUG << "dtor[" << this << "]"; assert(!channel_); } -void Connector::start() -{ +void Connector::start() { connect_ = true; loop_->runInLoop(std::bind(&Connector::startInLoop, this)); // FIXME: unsafe } -void Connector::startInLoop() -{ +void Connector::startInLoop() { loop_->assertInLoopThread(); assert(state_ == kDisconnected); - if (connect_) - { + if (connect_) { connect(); - } - else - { + } else { LOG_DEBUG << "do not connect"; } } -void Connector::stop() -{ +void Connector::stop() { connect_ = false; - loop_->queueInLoop(std::bind(&Connector::stopInLoop, this)); // FIXME: unsafe - // FIXME: cancel timer + loop_->queueInLoop( + std::bind(&Connector::stopInLoop, this)); // FIXME: unsafe + // FIXME: cancel timer } -void Connector::stopInLoop() -{ +void Connector::stopInLoop() { loop_->assertInLoopThread(); - if (state_ == kConnecting) - { + if (state_ == kConnecting) { setState(kDisconnected); int sockfd = removeAndResetChannel(); retry(sockfd); } } -void Connector::connect() -{ +void Connector::connect() { int sockfd = sockets::createNonblockingOrDie(serverAddr_.family()); int ret = sockets::connect(sockfd, serverAddr_.getSockAddr()); int savedErrno = (ret == 0) ? 0 : errno; - switch (savedErrno) - { - case 0: - case EINPROGRESS: - case EINTR: - case EISCONN: - connecting(sockfd); - break; - - case EAGAIN: - case EADDRINUSE: - case EADDRNOTAVAIL: - case ECONNREFUSED: - case ENETUNREACH: - retry(sockfd); - break; - - case EACCES: - case EPERM: - case EAFNOSUPPORT: - case EALREADY: - case EBADF: - case EFAULT: - case ENOTSOCK: - LOG_SYSERR << "connect error in Connector::startInLoop " << savedErrno; - sockets::close(sockfd); - break; - - default: - LOG_SYSERR << "Unexpected error in Connector::startInLoop " << savedErrno; - sockets::close(sockfd); - // connectErrorCallback_(); - break; + switch (savedErrno) { + case 0: + case EINPROGRESS: + case EINTR: + case EISCONN: + connecting(sockfd); + break; + + case EAGAIN: + case EADDRINUSE: + case EADDRNOTAVAIL: + case ECONNREFUSED: + case ENETUNREACH: + retry(sockfd); + break; + + case EACCES: + case EPERM: + case EAFNOSUPPORT: + case EALREADY: + case EBADF: + case EFAULT: + case ENOTSOCK: + LOG_SYSERR << "connect error in Connector::startInLoop " << savedErrno; + sockets::close(sockfd); + break; + + default: + LOG_SYSERR << "Unexpected error in Connector::startInLoop " << savedErrno; + sockets::close(sockfd); + // connectErrorCallback_(); + break; } } -void Connector::restart() -{ +void Connector::restart() { loop_->assertInLoopThread(); setState(kDisconnected); retryDelayMs_ = kInitRetryDelayMs; @@ -125,8 +110,7 @@ void Connector::restart() startInLoop(); } -void Connector::connecting(int sockfd) -{ +void Connector::connecting(int sockfd) { setState(kConnecting); assert(!channel_); channel_.reset(new Channel(loop_, sockfd)); @@ -140,65 +124,48 @@ void Connector::connecting(int sockfd) channel_->enableWriting(); } -int Connector::removeAndResetChannel() -{ +int Connector::removeAndResetChannel() { channel_->disableAll(); channel_->remove(); int sockfd = channel_->fd(); // Can't reset channel_ here, because we are inside Channel::handleEvent - loop_->queueInLoop(std::bind(&Connector::resetChannel, this)); // FIXME: unsafe + loop_->queueInLoop( + std::bind(&Connector::resetChannel, this)); // FIXME: unsafe return sockfd; } -void Connector::resetChannel() -{ - channel_.reset(); -} +void Connector::resetChannel() { channel_.reset(); } -void Connector::handleWrite() -{ +void Connector::handleWrite() { LOG_TRACE << "Connector::handleWrite " << state_; - if (state_ == kConnecting) - { + if (state_ == kConnecting) { int sockfd = removeAndResetChannel(); int err = sockets::getSocketError(sockfd); - if (err) - { - LOG_WARN << "Connector::handleWrite - SO_ERROR = " - << err << " " << strerror_tl(err); + if (err) { + LOG_WARN << "Connector::handleWrite - SO_ERROR = " << err << " " + << strerror_tl(err); retry(sockfd); - } - else if (sockets::isSelfConnect(sockfd)) - { + } else if (sockets::isSelfConnect(sockfd)) { LOG_WARN << "Connector::handleWrite - Self connect"; retry(sockfd); - } - else - { + } else { setState(kConnected); - if (connect_) - { + if (connect_) { newConnectionCallback_(sockfd); - } - else - { + } else { sockets::close(sockfd); } } - } - else - { + } else { // what happened? assert(state_ == kDisconnected); } } -void Connector::handleError() -{ +void Connector::handleError() { LOG_ERROR << "Connector::handleError state=" << state_; - if (state_ == kConnecting) - { + if (state_ == kConnecting) { int sockfd = removeAndResetChannel(); int err = sockets::getSocketError(sockfd); LOG_TRACE << "SO_ERROR = " << err << " " << strerror_tl(err); @@ -206,21 +173,17 @@ void Connector::handleError() } } -void Connector::retry(int sockfd) -{ +void Connector::retry(int sockfd) { sockets::close(sockfd); setState(kDisconnected); - if (connect_) - { - LOG_INFO << "Connector::retry - Retry connecting to " << serverAddr_.toIpPort() - << " in " << retryDelayMs_ << " milliseconds. "; - loop_->runAfter(retryDelayMs_/1000.0, + if (connect_) { + LOG_INFO << "Connector::retry - Retry connecting to " + << serverAddr_.toIpPort() << " in " << retryDelayMs_ + << " milliseconds. "; + loop_->runAfter(retryDelayMs_ / 1000.0, std::bind(&Connector::startInLoop, shared_from_this())); retryDelayMs_ = std::min(retryDelayMs_ * 2, kMaxRetryDelayMs); - } - else - { + } else { LOG_DEBUG << "do not connect"; } } - diff --git a/muduo/net/Connector.h b/muduo/net/Connector.h index 4b79fb2b2..f6f28a7d0 100644 --- a/muduo/net/Connector.h +++ b/muduo/net/Connector.h @@ -17,35 +17,32 @@ #include #include -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Channel; class EventLoop; -class Connector : noncopyable, - public std::enable_shared_from_this -{ - public: - typedef std::function NewConnectionCallback; +class Connector : noncopyable, public std::enable_shared_from_this { +public: + typedef std::function NewConnectionCallback; - Connector(EventLoop* loop, const InetAddress& serverAddr); + Connector(EventLoop *loop, const InetAddress &serverAddr); ~Connector(); - void setNewConnectionCallback(const NewConnectionCallback& cb) - { newConnectionCallback_ = cb; } + void setNewConnectionCallback(const NewConnectionCallback &cb) { + newConnectionCallback_ = cb; + } - void start(); // can be called in any thread - void restart(); // must be called in loop thread - void stop(); // can be called in any thread + void start(); // can be called in any thread + void restart(); // must be called in loop thread + void stop(); // can be called in any thread - const InetAddress& serverAddress() const { return serverAddr_; } + const InetAddress &serverAddress() const { return serverAddr_; } - private: +private: enum States { kDisconnected, kConnecting, kConnected }; - static const int kMaxRetryDelayMs = 30*1000; + static const int kMaxRetryDelayMs = 30 * 1000; static const int kInitRetryDelayMs = 500; void setState(States s) { state_ = s; } @@ -59,16 +56,16 @@ class Connector : noncopyable, int removeAndResetChannel(); void resetChannel(); - EventLoop* loop_; + EventLoop *loop_; InetAddress serverAddr_; bool connect_; // atomic - States state_; // FIXME: use atomic variable + States state_; // FIXME: use atomic variable std::unique_ptr channel_; NewConnectionCallback newConnectionCallback_; int retryDelayMs_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_CONNECTOR_H +#endif // MUDUO_NET_CONNECTOR_H diff --git a/muduo/net/Endian.h b/muduo/net/Endian.h index 82bd730e5..fd64ec751 100644 --- a/muduo/net/Endian.h +++ b/muduo/net/Endian.h @@ -11,55 +11,34 @@ #ifndef MUDUO_NET_ENDIAN_H #define MUDUO_NET_ENDIAN_H -#include #include +#include -namespace muduo -{ -namespace net -{ -namespace sockets -{ +namespace muduo { +namespace net { +namespace sockets { // the inline assembler code makes type blur, // so we disable warnings for a while. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #pragma GCC diagnostic ignored "-Wold-style-cast" -inline uint64_t hostToNetwork64(uint64_t host64) -{ - return htobe64(host64); -} +inline uint64_t hostToNetwork64(uint64_t host64) { return htobe64(host64); } -inline uint32_t hostToNetwork32(uint32_t host32) -{ - return htobe32(host32); -} +inline uint32_t hostToNetwork32(uint32_t host32) { return htobe32(host32); } -inline uint16_t hostToNetwork16(uint16_t host16) -{ - return htobe16(host16); -} +inline uint16_t hostToNetwork16(uint16_t host16) { return htobe16(host16); } -inline uint64_t networkToHost64(uint64_t net64) -{ - return be64toh(net64); -} +inline uint64_t networkToHost64(uint64_t net64) { return be64toh(net64); } -inline uint32_t networkToHost32(uint32_t net32) -{ - return be32toh(net32); -} +inline uint32_t networkToHost32(uint32_t net32) { return be32toh(net32); } -inline uint16_t networkToHost16(uint16_t net16) -{ - return be16toh(net16); -} +inline uint16_t networkToHost16(uint16_t net16) { return be16toh(net16); } #pragma GCC diagnostic pop -} // namespace sockets -} // namespace net -} // namespace muduo +} // namespace sockets +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_ENDIAN_H +#endif // MUDUO_NET_ENDIAN_H diff --git a/muduo/net/EventLoop.cc b/muduo/net/EventLoop.cc index b3feebe85..d29ce5691 100644 --- a/muduo/net/EventLoop.cc +++ b/muduo/net/EventLoop.cc @@ -24,17 +24,14 @@ using namespace muduo; using namespace muduo::net; -namespace -{ -__thread EventLoop* t_loopInThisThread = 0; +namespace { +__thread EventLoop *t_loopInThisThread = 0; const int kPollTimeMs = 10000; -int createEventfd() -{ +int createEventfd() { int evtfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); - if (evtfd < 0) - { + if (evtfd < 0) { LOG_SYSERR << "Failed in eventfd"; abort(); } @@ -42,11 +39,9 @@ int createEventfd() } #pragma GCC diagnostic ignored "-Wold-style-cast" -class IgnoreSigPipe -{ - public: - IgnoreSigPipe() - { +class IgnoreSigPipe { +public: + IgnoreSigPipe() { ::signal(SIGPIPE, SIG_IGN); // LOG_TRACE << "Ignore SIGPIPE"; } @@ -54,44 +49,32 @@ class IgnoreSigPipe #pragma GCC diagnostic error "-Wold-style-cast" IgnoreSigPipe initObj; -} // namespace +} // namespace -EventLoop* EventLoop::getEventLoopOfCurrentThread() -{ +EventLoop *EventLoop::getEventLoopOfCurrentThread() { return t_loopInThisThread; } EventLoop::EventLoop() - : looping_(false), - quit_(false), - eventHandling_(false), - callingPendingFunctors_(false), - iteration_(0), - threadId_(CurrentThread::tid()), - poller_(Poller::newDefaultPoller(this)), - timerQueue_(new TimerQueue(this)), - wakeupFd_(createEventfd()), - wakeupChannel_(new Channel(this, wakeupFd_)), - currentActiveChannel_(NULL) -{ + : looping_(false), quit_(false), eventHandling_(false), + callingPendingFunctors_(false), iteration_(0), + threadId_(CurrentThread::tid()), poller_(Poller::newDefaultPoller(this)), + timerQueue_(new TimerQueue(this)), wakeupFd_(createEventfd()), + wakeupChannel_(new Channel(this, wakeupFd_)), + currentActiveChannel_(NULL) { LOG_DEBUG << "EventLoop created " << this << " in thread " << threadId_; - if (t_loopInThisThread) - { + if (t_loopInThisThread) { LOG_FATAL << "Another EventLoop " << t_loopInThisThread << " exists in this thread " << threadId_; - } - else - { + } else { t_loopInThisThread = this; } - wakeupChannel_->setReadCallback( - std::bind(&EventLoop::handleRead, this)); + wakeupChannel_->setReadCallback(std::bind(&EventLoop::handleRead, this)); // we are always reading the wakeupfd wakeupChannel_->enableReading(); } -EventLoop::~EventLoop() -{ +EventLoop::~EventLoop() { LOG_DEBUG << "EventLoop " << this << " of thread " << threadId_ << " destructs in thread " << CurrentThread::tid(); wakeupChannel_->disableAll(); @@ -100,27 +83,23 @@ EventLoop::~EventLoop() t_loopInThisThread = NULL; } -void EventLoop::loop() -{ +void EventLoop::loop() { assert(!looping_); assertInLoopThread(); looping_ = true; - quit_ = false; // FIXME: what if someone calls quit() before loop() ? + quit_ = false; // FIXME: what if someone calls quit() before loop() ? LOG_TRACE << "EventLoop " << this << " start looping"; - while (!quit_) - { + while (!quit_) { activeChannels_.clear(); pollReturnTime_ = poller_->poll(kPollTimeMs, &activeChannels_); ++iteration_; - if (Logger::logLevel() <= Logger::TRACE) - { + if (Logger::logLevel() <= Logger::TRACE) { printActiveChannels(); } // TODO sort channel by priority eventHandling_ = true; - for (Channel* channel : activeChannels_) - { + for (Channel *channel : activeChannels_) { currentActiveChannel_ = channel; currentActiveChannel_->handleEvent(pollReturnTime_); } @@ -133,146 +112,118 @@ void EventLoop::loop() looping_ = false; } -void EventLoop::quit() -{ +void EventLoop::quit() { quit_ = true; // There is a chance that loop() just executes while(!quit_) and exits, // then EventLoop destructs, then we are accessing an invalid object. // Can be fixed using mutex_ in both places. - if (!isInLoopThread()) - { + if (!isInLoopThread()) { wakeup(); } } -void EventLoop::runInLoop(Functor cb) -{ - if (isInLoopThread()) - { +void EventLoop::runInLoop(Functor cb) { + if (isInLoopThread()) { cb(); - } - else - { + } else { queueInLoop(std::move(cb)); } } -void EventLoop::queueInLoop(Functor cb) -{ +void EventLoop::queueInLoop(Functor cb) { { - MutexLockGuard lock(mutex_); - pendingFunctors_.push_back(std::move(cb)); + MutexLockGuard lock(mutex_); + pendingFunctors_.push_back(std::move(cb)); } - if (!isInLoopThread() || callingPendingFunctors_) - { + if (!isInLoopThread() || callingPendingFunctors_) { wakeup(); } } -size_t EventLoop::queueSize() const -{ +size_t EventLoop::queueSize() const { MutexLockGuard lock(mutex_); return pendingFunctors_.size(); } -TimerId EventLoop::runAt(Timestamp time, TimerCallback cb) -{ +TimerId EventLoop::runAt(Timestamp time, TimerCallback cb) { return timerQueue_->addTimer(std::move(cb), time, 0.0); } -TimerId EventLoop::runAfter(double delay, TimerCallback cb) -{ +TimerId EventLoop::runAfter(double delay, TimerCallback cb) { Timestamp time(addTime(Timestamp::now(), delay)); return runAt(time, std::move(cb)); } -TimerId EventLoop::runEvery(double interval, TimerCallback cb) -{ +TimerId EventLoop::runEvery(double interval, TimerCallback cb) { Timestamp time(addTime(Timestamp::now(), interval)); return timerQueue_->addTimer(std::move(cb), time, interval); } -void EventLoop::cancel(TimerId timerId) -{ - return timerQueue_->cancel(timerId); -} +void EventLoop::cancel(TimerId timerId) { return timerQueue_->cancel(timerId); } -void EventLoop::updateChannel(Channel* channel) -{ +void EventLoop::updateChannel(Channel *channel) { assert(channel->ownerLoop() == this); assertInLoopThread(); poller_->updateChannel(channel); } -void EventLoop::removeChannel(Channel* channel) -{ +void EventLoop::removeChannel(Channel *channel) { assert(channel->ownerLoop() == this); assertInLoopThread(); - if (eventHandling_) - { + if (eventHandling_) { assert(currentActiveChannel_ == channel || - std::find(activeChannels_.begin(), activeChannels_.end(), channel) == activeChannels_.end()); + std::find(activeChannels_.begin(), activeChannels_.end(), channel) == + activeChannels_.end()); } poller_->removeChannel(channel); } -bool EventLoop::hasChannel(Channel* channel) -{ +bool EventLoop::hasChannel(Channel *channel) { assert(channel->ownerLoop() == this); assertInLoopThread(); return poller_->hasChannel(channel); } -void EventLoop::abortNotInLoopThread() -{ +void EventLoop::abortNotInLoopThread() { LOG_FATAL << "EventLoop::abortNotInLoopThread - EventLoop " << this << " was created in threadId_ = " << threadId_ - << ", current thread id = " << CurrentThread::tid(); + << ", current thread id = " << CurrentThread::tid(); } -void EventLoop::wakeup() -{ +void EventLoop::wakeup() { uint64_t one = 1; ssize_t n = sockets::write(wakeupFd_, &one, sizeof one); - if (n != sizeof one) - { + if (n != sizeof one) { LOG_ERROR << "EventLoop::wakeup() writes " << n << " bytes instead of 8"; } } -void EventLoop::handleRead() -{ +void EventLoop::handleRead() { uint64_t one = 1; ssize_t n = sockets::read(wakeupFd_, &one, sizeof one); - if (n != sizeof one) - { + if (n != sizeof one) { LOG_ERROR << "EventLoop::handleRead() reads " << n << " bytes instead of 8"; } } -void EventLoop::doPendingFunctors() -{ +void EventLoop::doPendingFunctors() { std::vector functors; callingPendingFunctors_ = true; { - MutexLockGuard lock(mutex_); - functors.swap(pendingFunctors_); + MutexLockGuard lock(mutex_); + functors.swap(pendingFunctors_); } - for (const Functor& functor : functors) - { + for (const Functor &functor : functors) { functor(); } callingPendingFunctors_ = false; } -void EventLoop::printActiveChannels() const -{ - for (const Channel* channel : activeChannels_) - { +void EventLoop::printActiveChannels() const { + for (const Channel *channel : activeChannels_) { LOG_TRACE << "{" << channel->reventsToString() << "} "; } } - diff --git a/muduo/net/EventLoop.h b/muduo/net/EventLoop.h index c2c53d346..43f9b8437 100644 --- a/muduo/net/EventLoop.h +++ b/muduo/net/EventLoop.h @@ -17,16 +17,14 @@ #include -#include "muduo/base/Mutex.h" #include "muduo/base/CurrentThread.h" +#include "muduo/base/Mutex.h" #include "muduo/base/Timestamp.h" #include "muduo/net/Callbacks.h" #include "muduo/net/TimerId.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Channel; class Poller; @@ -36,13 +34,12 @@ class TimerQueue; /// Reactor, at most one per thread. /// /// This is an interface class, so don't expose too much details. -class EventLoop : noncopyable -{ - public: +class EventLoop : noncopyable { +public: typedef std::function Functor; EventLoop(); - ~EventLoop(); // force out-line dtor, for std::unique_ptr members. + ~EventLoop(); // force out-line dtor, for std::unique_ptr members. /// /// Loops forever. @@ -101,45 +98,41 @@ class EventLoop : noncopyable // internal usage void wakeup(); - void updateChannel(Channel* channel); - void removeChannel(Channel* channel); - bool hasChannel(Channel* channel); + void updateChannel(Channel *channel); + void removeChannel(Channel *channel); + bool hasChannel(Channel *channel); // pid_t threadId() const { return threadId_; } - void assertInLoopThread() - { - if (!isInLoopThread()) - { + void assertInLoopThread() { + if (!isInLoopThread()) { abortNotInLoopThread(); } } bool isInLoopThread() const { return threadId_ == CurrentThread::tid(); } - // bool callingPendingFunctors() const { return callingPendingFunctors_; } + // bool callingPendingFunctors() const { return callingPendingFunctors_; + // } bool eventHandling() const { return eventHandling_; } - void setContext(const boost::any& context) - { context_ = context; } + void setContext(const boost::any &context) { context_ = context; } - const boost::any& getContext() const - { return context_; } + const boost::any &getContext() const { return context_; } - boost::any* getMutableContext() - { return &context_; } + boost::any *getMutableContext() { return &context_; } - static EventLoop* getEventLoopOfCurrentThread(); + static EventLoop *getEventLoopOfCurrentThread(); - private: +private: void abortNotInLoopThread(); - void handleRead(); // waked up + void handleRead(); // waked up void doPendingFunctors(); void printActiveChannels() const; // DEBUG - typedef std::vector ChannelList; + typedef std::vector ChannelList; bool looping_; /* atomic */ std::atomic quit_; - bool eventHandling_; /* atomic */ + bool eventHandling_; /* atomic */ bool callingPendingFunctors_; /* atomic */ int64_t iteration_; const pid_t threadId_; @@ -154,13 +147,13 @@ class EventLoop : noncopyable // scratch variables ChannelList activeChannels_; - Channel* currentActiveChannel_; + Channel *currentActiveChannel_; mutable MutexLock mutex_; std::vector pendingFunctors_ GUARDED_BY(mutex_); }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_EVENTLOOP_H +#endif // MUDUO_NET_EVENTLOOP_H diff --git a/muduo/net/EventLoopThread.cc b/muduo/net/EventLoopThread.cc index c1b6fa56d..43841a4f4 100644 --- a/muduo/net/EventLoopThread.cc +++ b/muduo/net/EventLoopThread.cc @@ -13,39 +13,33 @@ using namespace muduo; using namespace muduo::net; -EventLoopThread::EventLoopThread(const ThreadInitCallback& cb, - const string& name) - : loop_(NULL), - exiting_(false), - thread_(std::bind(&EventLoopThread::threadFunc, this), name), - mutex_(), - cond_(mutex_), - callback_(cb) -{ -} +EventLoopThread::EventLoopThread(const ThreadInitCallback &cb, + const string &name) + : loop_(NULL), exiting_(false), + thread_(std::bind(&EventLoopThread::threadFunc, this), name), mutex_(), + cond_(mutex_), callback_(cb) {} -EventLoopThread::~EventLoopThread() -{ +EventLoopThread::~EventLoopThread() { exiting_ = true; - if (loop_ != NULL) // not 100% race-free, eg. threadFunc could be running callback_. + if (loop_ != + NULL) // not 100% race-free, eg. threadFunc could be running callback_. { - // still a tiny chance to call destructed object, if threadFunc exits just now. - // but when EventLoopThread destructs, usually programming is exiting anyway. + // still a tiny chance to call destructed object, if threadFunc exits + // just now. but when EventLoopThread destructs, usually programming is + // exiting anyway. loop_->quit(); thread_.join(); } } -EventLoop* EventLoopThread::startLoop() -{ +EventLoop *EventLoopThread::startLoop() { assert(!thread_.started()); thread_.start(); - EventLoop* loop = NULL; + EventLoop *loop = NULL; { MutexLockGuard lock(mutex_); - while (loop_ == NULL) - { + while (loop_ == NULL) { cond_.wait(); } loop = loop_; @@ -54,12 +48,10 @@ EventLoop* EventLoopThread::startLoop() return loop; } -void EventLoopThread::threadFunc() -{ +void EventLoopThread::threadFunc() { EventLoop loop; - if (callback_) - { + if (callback_) { callback_(&loop); } @@ -70,8 +62,7 @@ void EventLoopThread::threadFunc() } loop.loop(); - //assert(exiting_); + // assert(exiting_); MutexLockGuard lock(mutex_); loop_ = NULL; } - diff --git a/muduo/net/EventLoopThread.h b/muduo/net/EventLoopThread.h index 7e839d780..20ac401aa 100644 --- a/muduo/net/EventLoopThread.h +++ b/muduo/net/EventLoopThread.h @@ -15,27 +15,24 @@ #include "muduo/base/Mutex.h" #include "muduo/base/Thread.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class EventLoop; -class EventLoopThread : noncopyable -{ - public: - typedef std::function ThreadInitCallback; +class EventLoopThread : noncopyable { +public: + typedef std::function ThreadInitCallback; - EventLoopThread(const ThreadInitCallback& cb = ThreadInitCallback(), - const string& name = string()); + EventLoopThread(const ThreadInitCallback &cb = ThreadInitCallback(), + const string &name = string()); ~EventLoopThread(); - EventLoop* startLoop(); + EventLoop *startLoop(); - private: +private: void threadFunc(); - EventLoop* loop_ GUARDED_BY(mutex_); + EventLoop *loop_ GUARDED_BY(mutex_); bool exiting_; Thread thread_; MutexLock mutex_; @@ -43,8 +40,7 @@ class EventLoopThread : noncopyable ThreadInitCallback callback_; }; -} // namespace net -} // namespace muduo - -#endif // MUDUO_NET_EVENTLOOPTHREAD_H +} // namespace net +} // namespace muduo +#endif // MUDUO_NET_EVENTLOOPTHREAD_H diff --git a/muduo/net/EventLoopThreadPool.cc b/muduo/net/EventLoopThreadPool.cc index 1ee594954..86064765e 100644 --- a/muduo/net/EventLoopThreadPool.cc +++ b/muduo/net/EventLoopThreadPool.cc @@ -16,82 +16,65 @@ using namespace muduo; using namespace muduo::net; -EventLoopThreadPool::EventLoopThreadPool(EventLoop* baseLoop, const string& nameArg) - : baseLoop_(baseLoop), - name_(nameArg), - started_(false), - numThreads_(0), - next_(0) -{ -} +EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseLoop, + const string &nameArg) + : baseLoop_(baseLoop), name_(nameArg), started_(false), numThreads_(0), + next_(0) {} -EventLoopThreadPool::~EventLoopThreadPool() -{ +EventLoopThreadPool::~EventLoopThreadPool() { // Don't delete loop, it's stack variable } -void EventLoopThreadPool::start(const ThreadInitCallback& cb) -{ +void EventLoopThreadPool::start(const ThreadInitCallback &cb) { assert(!started_); baseLoop_->assertInLoopThread(); started_ = true; - for (int i = 0; i < numThreads_; ++i) - { + for (int i = 0; i < numThreads_; ++i) { char buf[name_.size() + 32]; snprintf(buf, sizeof buf, "%s%d", name_.c_str(), i); - EventLoopThread* t = new EventLoopThread(cb, buf); + EventLoopThread *t = new EventLoopThread(cb, buf); threads_.push_back(std::unique_ptr(t)); loops_.push_back(t->startLoop()); } - if (numThreads_ == 0 && cb) - { + if (numThreads_ == 0 && cb) { cb(baseLoop_); } } -EventLoop* EventLoopThreadPool::getNextLoop() -{ +EventLoop *EventLoopThreadPool::getNextLoop() { baseLoop_->assertInLoopThread(); assert(started_); - EventLoop* loop = baseLoop_; + EventLoop *loop = baseLoop_; - if (!loops_.empty()) - { + if (!loops_.empty()) { // round-robin loop = loops_[next_]; ++next_; - if (implicit_cast(next_) >= loops_.size()) - { + if (implicit_cast(next_) >= loops_.size()) { next_ = 0; } } return loop; } -EventLoop* EventLoopThreadPool::getLoopForHash(size_t hashCode) -{ +EventLoop *EventLoopThreadPool::getLoopForHash(size_t hashCode) { baseLoop_->assertInLoopThread(); - EventLoop* loop = baseLoop_; + EventLoop *loop = baseLoop_; - if (!loops_.empty()) - { + if (!loops_.empty()) { loop = loops_[hashCode % loops_.size()]; } return loop; } -std::vector EventLoopThreadPool::getAllLoops() -{ +std::vector EventLoopThreadPool::getAllLoops() { baseLoop_->assertInLoopThread(); assert(started_); - if (loops_.empty()) - { - return std::vector(1, baseLoop_); - } - else - { + if (loops_.empty()) { + return std::vector(1, baseLoop_); + } else { return loops_; } } diff --git a/muduo/net/EventLoopThreadPool.h b/muduo/net/EventLoopThreadPool.h index 738914875..8897aff44 100644 --- a/muduo/net/EventLoopThreadPool.h +++ b/muduo/net/EventLoopThreadPool.h @@ -11,59 +11,53 @@ #ifndef MUDUO_NET_EVENTLOOPTHREADPOOL_H #define MUDUO_NET_EVENTLOOPTHREADPOOL_H -#include "muduo/base/noncopyable.h" #include "muduo/base/Types.h" +#include "muduo/base/noncopyable.h" #include #include #include -namespace muduo -{ +namespace muduo { -namespace net -{ +namespace net { class EventLoop; class EventLoopThread; -class EventLoopThreadPool : noncopyable -{ - public: - typedef std::function ThreadInitCallback; +class EventLoopThreadPool : noncopyable { +public: + typedef std::function ThreadInitCallback; - EventLoopThreadPool(EventLoop* baseLoop, const string& nameArg); + EventLoopThreadPool(EventLoop *baseLoop, const string &nameArg); ~EventLoopThreadPool(); void setThreadNum(int numThreads) { numThreads_ = numThreads; } - void start(const ThreadInitCallback& cb = ThreadInitCallback()); + void start(const ThreadInitCallback &cb = ThreadInitCallback()); // valid after calling start() /// round-robin - EventLoop* getNextLoop(); + EventLoop *getNextLoop(); /// with the same hash code, it will always return the same EventLoop - EventLoop* getLoopForHash(size_t hashCode); - - std::vector getAllLoops(); + EventLoop *getLoopForHash(size_t hashCode); - bool started() const - { return started_; } + std::vector getAllLoops(); - const string& name() const - { return name_; } + bool started() const { return started_; } - private: + const string &name() const { return name_; } - EventLoop* baseLoop_; +private: + EventLoop *baseLoop_; string name_; bool started_; int numThreads_; int next_; std::vector> threads_; - std::vector loops_; + std::vector loops_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_EVENTLOOPTHREADPOOL_H +#endif // MUDUO_NET_EVENTLOOPTHREADPOOL_H diff --git a/muduo/net/InetAddress.cc b/muduo/net/InetAddress.cc index c353f25a1..efd681016 100644 --- a/muduo/net/InetAddress.cc +++ b/muduo/net/InetAddress.cc @@ -52,20 +52,16 @@ static_assert(offsetof(sockaddr_in6, sin6_family) == 0, "sin6_family offset 0"); static_assert(offsetof(sockaddr_in, sin_port) == 2, "sin_port offset 2"); static_assert(offsetof(sockaddr_in6, sin6_port) == 2, "sin6_port offset 2"); -InetAddress::InetAddress(uint16_t portArg, bool loopbackOnly, bool ipv6) -{ +InetAddress::InetAddress(uint16_t portArg, bool loopbackOnly, bool ipv6) { static_assert(offsetof(InetAddress, addr6_) == 0, "addr6_ offset 0"); static_assert(offsetof(InetAddress, addr_) == 0, "addr_ offset 0"); - if (ipv6) - { + if (ipv6) { memZero(&addr6_, sizeof addr6_); addr6_.sin6_family = AF_INET6; in6_addr ip = loopbackOnly ? in6addr_loopback : in6addr_any; addr6_.sin6_addr = ip; addr6_.sin6_port = sockets::hostToNetwork16(portArg); - } - else - { + } else { memZero(&addr_, sizeof addr_); addr_.sin_family = AF_INET; in_addr_t ip = loopbackOnly ? kInaddrLoopback : kInaddrAny; @@ -74,76 +70,62 @@ InetAddress::InetAddress(uint16_t portArg, bool loopbackOnly, bool ipv6) } } -InetAddress::InetAddress(StringArg ip, uint16_t portArg, bool ipv6) -{ - if (ipv6 || strchr(ip.c_str(), ':')) - { +InetAddress::InetAddress(StringArg ip, uint16_t portArg, bool ipv6) { + if (ipv6 || strchr(ip.c_str(), ':')) { memZero(&addr6_, sizeof addr6_); sockets::fromIpPort(ip.c_str(), portArg, &addr6_); - } - else - { + } else { memZero(&addr_, sizeof addr_); sockets::fromIpPort(ip.c_str(), portArg, &addr_); } } -string InetAddress::toIpPort() const -{ +string InetAddress::toIpPort() const { char buf[64] = ""; sockets::toIpPort(buf, sizeof buf, getSockAddr()); return buf; } -string InetAddress::toIp() const -{ +string InetAddress::toIp() const { char buf[64] = ""; sockets::toIp(buf, sizeof buf, getSockAddr()); return buf; } -uint32_t InetAddress::ipv4NetEndian() const -{ +uint32_t InetAddress::ipv4NetEndian() const { assert(family() == AF_INET); return addr_.sin_addr.s_addr; } -uint16_t InetAddress::port() const -{ +uint16_t InetAddress::port() const { return sockets::networkToHost16(portNetEndian()); } static __thread char t_resolveBuffer[64 * 1024]; -bool InetAddress::resolve(StringArg hostname, InetAddress* out) -{ +bool InetAddress::resolve(StringArg hostname, InetAddress *out) { assert(out != NULL); struct hostent hent; - struct hostent* he = NULL; + struct hostent *he = NULL; int herrno = 0; memZero(&hent, sizeof(hent)); - int ret = gethostbyname_r(hostname.c_str(), &hent, t_resolveBuffer, sizeof t_resolveBuffer, &he, &herrno); - if (ret == 0 && he != NULL) - { + int ret = gethostbyname_r(hostname.c_str(), &hent, t_resolveBuffer, + sizeof t_resolveBuffer, &he, &herrno); + if (ret == 0 && he != NULL) { assert(he->h_addrtype == AF_INET && he->h_length == sizeof(uint32_t)); - out->addr_.sin_addr = *reinterpret_cast(he->h_addr); + out->addr_.sin_addr = *reinterpret_cast(he->h_addr); return true; - } - else - { - if (ret) - { + } else { + if (ret) { LOG_SYSERR << "InetAddress::resolve"; } return false; } } -void InetAddress::setScopeId(uint32_t scope_id) -{ - if (family() == AF_INET6) - { +void InetAddress::setScopeId(uint32_t scope_id) { + if (family() == AF_INET6) { addr6_.sin6_scope_id = scope_id; } } diff --git a/muduo/net/InetAddress.h b/muduo/net/InetAddress.h index c5263a75c..8dd3f86ec 100644 --- a/muduo/net/InetAddress.h +++ b/muduo/net/InetAddress.h @@ -11,30 +11,27 @@ #ifndef MUDUO_NET_INETADDRESS_H #define MUDUO_NET_INETADDRESS_H -#include "muduo/base/copyable.h" #include "muduo/base/StringPiece.h" +#include "muduo/base/copyable.h" #include -namespace muduo -{ -namespace net -{ -namespace sockets -{ -const struct sockaddr* sockaddr_cast(const struct sockaddr_in6* addr); +namespace muduo { +namespace net { +namespace sockets { +const struct sockaddr *sockaddr_cast(const struct sockaddr_in6 *addr); } /// /// Wrapper of sockaddr_in. /// /// This is an POD interface class. -class InetAddress : public muduo::copyable -{ - public: +class InetAddress : public muduo::copyable { +public: /// Constructs an endpoint with given port number. /// Mostly used in TcpServer listening. - explicit InetAddress(uint16_t port = 0, bool loopbackOnly = false, bool ipv6 = false); + explicit InetAddress(uint16_t port = 0, bool loopbackOnly = false, + bool ipv6 = false); /// Constructs an endpoint with given ip and port. /// @c ip should be "1.2.3.4" @@ -42,13 +39,9 @@ class InetAddress : public muduo::copyable /// Constructs an endpoint with given struct @c sockaddr_in /// Mostly used when accepting new connections - explicit InetAddress(const struct sockaddr_in& addr) - : addr_(addr) - { } + explicit InetAddress(const struct sockaddr_in &addr) : addr_(addr) {} - explicit InetAddress(const struct sockaddr_in6& addr) - : addr6_(addr) - { } + explicit InetAddress(const struct sockaddr_in6 &addr) : addr6_(addr) {} sa_family_t family() const { return addr_.sin_family; } string toIp() const; @@ -57,8 +50,10 @@ class InetAddress : public muduo::copyable // default copy/assignment are Okay - const struct sockaddr* getSockAddr() const { return sockets::sockaddr_cast(&addr6_); } - void setSockAddrInet6(const struct sockaddr_in6& addr6) { addr6_ = addr6; } + const struct sockaddr *getSockAddr() const { + return sockets::sockaddr_cast(&addr6_); + } + void setSockAddrInet6(const struct sockaddr_in6 &addr6) { addr6_ = addr6; } uint32_t ipv4NetEndian() const; uint16_t portNetEndian() const { return addr_.sin_port; } @@ -66,21 +61,21 @@ class InetAddress : public muduo::copyable // resolve hostname to IP address, not changing port or sin_family // return true on success. // thread safe - static bool resolve(StringArg hostname, InetAddress* result); - // static std::vector resolveAll(const char* hostname, uint16_t port = 0); + static bool resolve(StringArg hostname, InetAddress *result); + // static std::vector resolveAll(const char* hostname, + // uint16_t port = 0); // set IPv6 ScopeID void setScopeId(uint32_t scope_id); - private: - union - { +private: + union { struct sockaddr_in addr_; struct sockaddr_in6 addr6_; }; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_INETADDRESS_H +#endif // MUDUO_NET_INETADDRESS_H diff --git a/muduo/net/Poller.cc b/muduo/net/Poller.cc index cfe4c3c40..fb885bdad 100644 --- a/muduo/net/Poller.cc +++ b/muduo/net/Poller.cc @@ -13,17 +13,12 @@ using namespace muduo; using namespace muduo::net; -Poller::Poller(EventLoop* loop) - : ownerLoop_(loop) -{ -} +Poller::Poller(EventLoop *loop) : ownerLoop_(loop) {} Poller::~Poller() = default; -bool Poller::hasChannel(Channel* channel) const -{ +bool Poller::hasChannel(Channel *channel) const { assertInLoopThread(); ChannelMap::const_iterator it = channels_.find(channel->fd()); return it != channels_.end() && it->second == channel; } - diff --git a/muduo/net/Poller.h b/muduo/net/Poller.h index 089e60bef..067f3f6fc 100644 --- a/muduo/net/Poller.h +++ b/muduo/net/Poller.h @@ -17,10 +17,8 @@ #include "muduo/base/Timestamp.h" #include "muduo/net/EventLoop.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Channel; @@ -28,44 +26,40 @@ class Channel; /// Base class for IO Multiplexing /// /// This class doesn't own the Channel objects. -class Poller : noncopyable -{ - public: - typedef std::vector ChannelList; +class Poller : noncopyable { +public: + typedef std::vector ChannelList; - Poller(EventLoop* loop); + Poller(EventLoop *loop); virtual ~Poller(); /// Polls the I/O events. /// Must be called in the loop thread. - virtual Timestamp poll(int timeoutMs, ChannelList* activeChannels) = 0; + virtual Timestamp poll(int timeoutMs, ChannelList *activeChannels) = 0; /// Changes the interested I/O events. /// Must be called in the loop thread. - virtual void updateChannel(Channel* channel) = 0; + virtual void updateChannel(Channel *channel) = 0; /// Remove the channel, when it destructs. /// Must be called in the loop thread. - virtual void removeChannel(Channel* channel) = 0; + virtual void removeChannel(Channel *channel) = 0; - virtual bool hasChannel(Channel* channel) const; + virtual bool hasChannel(Channel *channel) const; - static Poller* newDefaultPoller(EventLoop* loop); + static Poller *newDefaultPoller(EventLoop *loop); - void assertInLoopThread() const - { - ownerLoop_->assertInLoopThread(); - } + void assertInLoopThread() const { ownerLoop_->assertInLoopThread(); } - protected: - typedef std::map ChannelMap; +protected: + typedef std::map ChannelMap; ChannelMap channels_; - private: - EventLoop* ownerLoop_; +private: + EventLoop *ownerLoop_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_POLLER_H +#endif // MUDUO_NET_POLLER_H diff --git a/muduo/net/Socket.cc b/muduo/net/Socket.cc index fc131470c..85850dbaa 100644 --- a/muduo/net/Socket.cc +++ b/muduo/net/Socket.cc @@ -14,115 +14,93 @@ #include #include -#include // snprintf +#include // snprintf using namespace muduo; using namespace muduo::net; -Socket::~Socket() -{ - sockets::close(sockfd_); -} +Socket::~Socket() { sockets::close(sockfd_); } -bool Socket::getTcpInfo(struct tcp_info* tcpi) const -{ +bool Socket::getTcpInfo(struct tcp_info *tcpi) const { socklen_t len = sizeof(*tcpi); memZero(tcpi, len); return ::getsockopt(sockfd_, SOL_TCP, TCP_INFO, tcpi, &len) == 0; } -bool Socket::getTcpInfoString(char* buf, int len) const -{ +bool Socket::getTcpInfoString(char *buf, int len) const { struct tcp_info tcpi; bool ok = getTcpInfo(&tcpi); - if (ok) - { - snprintf(buf, len, "unrecovered=%u " + if (ok) { + snprintf(buf, len, + "unrecovered=%u " "rto=%u ato=%u snd_mss=%u rcv_mss=%u " "lost=%u retrans=%u rtt=%u rttvar=%u " "sshthresh=%u cwnd=%u total_retrans=%u", - tcpi.tcpi_retransmits, // Number of unrecovered [RTO] timeouts - tcpi.tcpi_rto, // Retransmit timeout in usec - tcpi.tcpi_ato, // Predicted tick of soft clock in usec - tcpi.tcpi_snd_mss, - tcpi.tcpi_rcv_mss, - tcpi.tcpi_lost, // Lost packets - tcpi.tcpi_retrans, // Retransmitted packets out - tcpi.tcpi_rtt, // Smoothed round trip time in usec - tcpi.tcpi_rttvar, // Medium deviation - tcpi.tcpi_snd_ssthresh, - tcpi.tcpi_snd_cwnd, - tcpi.tcpi_total_retrans); // Total retransmits for entire connection + tcpi.tcpi_retransmits, // Number of unrecovered [RTO] timeouts + tcpi.tcpi_rto, // Retransmit timeout in usec + tcpi.tcpi_ato, // Predicted tick of soft clock in usec + tcpi.tcpi_snd_mss, tcpi.tcpi_rcv_mss, + tcpi.tcpi_lost, // Lost packets + tcpi.tcpi_retrans, // Retransmitted packets out + tcpi.tcpi_rtt, // Smoothed round trip time in usec + tcpi.tcpi_rttvar, // Medium deviation + tcpi.tcpi_snd_ssthresh, tcpi.tcpi_snd_cwnd, + tcpi.tcpi_total_retrans); // Total retransmits for entire + // connection } return ok; } -void Socket::bindAddress(const InetAddress& addr) -{ +void Socket::bindAddress(const InetAddress &addr) { sockets::bindOrDie(sockfd_, addr.getSockAddr()); } -void Socket::listen() -{ - sockets::listenOrDie(sockfd_); -} +void Socket::listen() { sockets::listenOrDie(sockfd_); } -int Socket::accept(InetAddress* peeraddr) -{ +int Socket::accept(InetAddress *peeraddr) { struct sockaddr_in6 addr; memZero(&addr, sizeof addr); int connfd = sockets::accept(sockfd_, &addr); - if (connfd >= 0) - { + if (connfd >= 0) { peeraddr->setSockAddrInet6(addr); } return connfd; } -void Socket::shutdownWrite() -{ - sockets::shutdownWrite(sockfd_); -} +void Socket::shutdownWrite() { sockets::shutdownWrite(sockfd_); } -void Socket::setTcpNoDelay(bool on) -{ +void Socket::setTcpNoDelay(bool on) { int optval = on ? 1 : 0; - ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, - &optval, static_cast(sizeof optval)); + ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &optval, + static_cast(sizeof optval)); // FIXME CHECK } -void Socket::setReuseAddr(bool on) -{ +void Socket::setReuseAddr(bool on) { int optval = on ? 1 : 0; - ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, - &optval, static_cast(sizeof optval)); + ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &optval, + static_cast(sizeof optval)); // FIXME CHECK } -void Socket::setReusePort(bool on) -{ +void Socket::setReusePort(bool on) { #ifdef SO_REUSEPORT int optval = on ? 1 : 0; - int ret = ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, - &optval, static_cast(sizeof optval)); - if (ret < 0 && on) - { + int ret = ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &optval, + static_cast(sizeof optval)); + if (ret < 0 && on) { LOG_SYSERR << "SO_REUSEPORT failed."; } #else - if (on) - { + if (on) { LOG_ERROR << "SO_REUSEPORT is not supported."; } #endif } -void Socket::setKeepAlive(bool on) -{ +void Socket::setKeepAlive(bool on) { int optval = on ? 1 : 0; - ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, - &optval, static_cast(sizeof optval)); + ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, &optval, + static_cast(sizeof optval)); // FIXME CHECK } - diff --git a/muduo/net/Socket.h b/muduo/net/Socket.h index 17567be01..ffeeeca50 100644 --- a/muduo/net/Socket.h +++ b/muduo/net/Socket.h @@ -16,13 +16,11 @@ // struct tcp_info is in struct tcp_info; -namespace muduo -{ +namespace muduo { /// /// TCP networking. /// -namespace net -{ +namespace net { class InetAddress; @@ -31,23 +29,20 @@ class InetAddress; /// /// It closes the sockfd when desctructs. /// It's thread safe, all operations are delagated to OS. -class Socket : noncopyable -{ - public: - explicit Socket(int sockfd) - : sockfd_(sockfd) - { } +class Socket : noncopyable { +public: + explicit Socket(int sockfd) : sockfd_(sockfd) {} // Socket(Socket&&) // move constructor in C++11 ~Socket(); int fd() const { return sockfd_; } // return true if success. - bool getTcpInfo(struct tcp_info*) const; - bool getTcpInfoString(char* buf, int len) const; + bool getTcpInfo(struct tcp_info *) const; + bool getTcpInfoString(char *buf, int len) const; /// abort if address in use - void bindAddress(const InetAddress& localaddr); + void bindAddress(const InetAddress &localaddr); /// abort if address in use void listen(); @@ -55,7 +50,7 @@ class Socket : noncopyable /// a descriptor for the accepted socket, which has been /// set to non-blocking and close-on-exec. *peeraddr is assigned. /// On error, -1 is returned, and *peeraddr is untouched. - int accept(InetAddress* peeraddr); + int accept(InetAddress *peeraddr); void shutdownWrite(); @@ -79,11 +74,11 @@ class Socket : noncopyable /// void setKeepAlive(bool on); - private: +private: const int sockfd_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_SOCKET_H +#endif // MUDUO_NET_SOCKET_H diff --git a/muduo/net/SocketsOps.cc b/muduo/net/SocketsOps.cc index 465c507a6..5adea13d5 100644 --- a/muduo/net/SocketsOps.cc +++ b/muduo/net/SocketsOps.cc @@ -14,23 +14,20 @@ #include #include -#include // snprintf +#include // snprintf #include -#include // readv +#include // readv #include using namespace muduo; using namespace muduo::net; -namespace -{ +namespace { typedef struct sockaddr SA; - -#if VALGRIND || defined (NO_ACCEPT4) -void setNonBlockAndCloseOnExec(int sockfd) -{ +#if VALGRIND || defined(NO_ACCEPT4) +void setNonBlockAndCloseOnExec(int sockfd) { // non-block int flags = ::fcntl(sockfd, F_GETFL, 0); flags |= O_NONBLOCK; @@ -47,270 +44,232 @@ void setNonBlockAndCloseOnExec(int sockfd) } #endif -} // namespace +} // namespace -const struct sockaddr* sockets::sockaddr_cast(const struct sockaddr_in6* addr) -{ - return static_cast(implicit_cast(addr)); +const struct sockaddr *sockets::sockaddr_cast(const struct sockaddr_in6 *addr) { + return static_cast( + implicit_cast(addr)); } -struct sockaddr* sockets::sockaddr_cast(struct sockaddr_in6* addr) -{ - return static_cast(implicit_cast(addr)); +struct sockaddr *sockets::sockaddr_cast(struct sockaddr_in6 *addr) { + return static_cast(implicit_cast(addr)); } -const struct sockaddr* sockets::sockaddr_cast(const struct sockaddr_in* addr) -{ - return static_cast(implicit_cast(addr)); +const struct sockaddr *sockets::sockaddr_cast(const struct sockaddr_in *addr) { + return static_cast( + implicit_cast(addr)); } -const struct sockaddr_in* sockets::sockaddr_in_cast(const struct sockaddr* addr) -{ - return static_cast(implicit_cast(addr)); +const struct sockaddr_in * +sockets::sockaddr_in_cast(const struct sockaddr *addr) { + return static_cast( + implicit_cast(addr)); } -const struct sockaddr_in6* sockets::sockaddr_in6_cast(const struct sockaddr* addr) -{ - return static_cast(implicit_cast(addr)); +const struct sockaddr_in6 * +sockets::sockaddr_in6_cast(const struct sockaddr *addr) { + return static_cast( + implicit_cast(addr)); } -int sockets::createNonblockingOrDie(sa_family_t family) -{ +int sockets::createNonblockingOrDie(sa_family_t family) { #if VALGRIND int sockfd = ::socket(family, SOCK_STREAM, IPPROTO_TCP); - if (sockfd < 0) - { + if (sockfd < 0) { LOG_SYSFATAL << "sockets::createNonblockingOrDie"; } setNonBlockAndCloseOnExec(sockfd); #else - int sockfd = ::socket(family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP); - if (sockfd < 0) - { + int sockfd = + ::socket(family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP); + if (sockfd < 0) { LOG_SYSFATAL << "sockets::createNonblockingOrDie"; } #endif return sockfd; } -void sockets::bindOrDie(int sockfd, const struct sockaddr* addr) -{ - int ret = ::bind(sockfd, addr, static_cast(sizeof(struct sockaddr_in6))); - if (ret < 0) - { +void sockets::bindOrDie(int sockfd, const struct sockaddr *addr) { + int ret = + ::bind(sockfd, addr, static_cast(sizeof(struct sockaddr_in6))); + if (ret < 0) { LOG_SYSFATAL << "sockets::bindOrDie"; } } -void sockets::listenOrDie(int sockfd) -{ +void sockets::listenOrDie(int sockfd) { int ret = ::listen(sockfd, SOMAXCONN); - if (ret < 0) - { + if (ret < 0) { LOG_SYSFATAL << "sockets::listenOrDie"; } } -int sockets::accept(int sockfd, struct sockaddr_in6* addr) -{ +int sockets::accept(int sockfd, struct sockaddr_in6 *addr) { socklen_t addrlen = static_cast(sizeof *addr); -#if VALGRIND || defined (NO_ACCEPT4) +#if VALGRIND || defined(NO_ACCEPT4) int connfd = ::accept(sockfd, sockaddr_cast(addr), &addrlen); setNonBlockAndCloseOnExec(connfd); #else - int connfd = ::accept4(sockfd, sockaddr_cast(addr), - &addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC); + int connfd = ::accept4(sockfd, sockaddr_cast(addr), &addrlen, + SOCK_NONBLOCK | SOCK_CLOEXEC); #endif - if (connfd < 0) - { + if (connfd < 0) { int savedErrno = errno; LOG_SYSERR << "Socket::accept"; - switch (savedErrno) - { - case EAGAIN: - case ECONNABORTED: - case EINTR: - case EPROTO: // ??? - case EPERM: - case EMFILE: // per-process lmit of open file desctiptor ??? - // expected errors - errno = savedErrno; - break; - case EBADF: - case EFAULT: - case EINVAL: - case ENFILE: - case ENOBUFS: - case ENOMEM: - case ENOTSOCK: - case EOPNOTSUPP: - // unexpected errors - LOG_FATAL << "unexpected error of ::accept " << savedErrno; - break; - default: - LOG_FATAL << "unknown error of ::accept " << savedErrno; - break; + switch (savedErrno) { + case EAGAIN: + case ECONNABORTED: + case EINTR: + case EPROTO: // ??? + case EPERM: + case EMFILE: // per-process lmit of open file desctiptor ??? + // expected errors + errno = savedErrno; + break; + case EBADF: + case EFAULT: + case EINVAL: + case ENFILE: + case ENOBUFS: + case ENOMEM: + case ENOTSOCK: + case EOPNOTSUPP: + // unexpected errors + LOG_FATAL << "unexpected error of ::accept " << savedErrno; + break; + default: + LOG_FATAL << "unknown error of ::accept " << savedErrno; + break; } } return connfd; } -int sockets::connect(int sockfd, const struct sockaddr* addr) -{ - return ::connect(sockfd, addr, static_cast(sizeof(struct sockaddr_in6))); +int sockets::connect(int sockfd, const struct sockaddr *addr) { + return ::connect(sockfd, addr, + static_cast(sizeof(struct sockaddr_in6))); } -ssize_t sockets::read(int sockfd, void *buf, size_t count) -{ +ssize_t sockets::read(int sockfd, void *buf, size_t count) { return ::read(sockfd, buf, count); } -ssize_t sockets::readv(int sockfd, const struct iovec *iov, int iovcnt) -{ +ssize_t sockets::readv(int sockfd, const struct iovec *iov, int iovcnt) { return ::readv(sockfd, iov, iovcnt); } -ssize_t sockets::write(int sockfd, const void *buf, size_t count) -{ +ssize_t sockets::write(int sockfd, const void *buf, size_t count) { return ::write(sockfd, buf, count); } -void sockets::close(int sockfd) -{ - if (::close(sockfd) < 0) - { +void sockets::close(int sockfd) { + if (::close(sockfd) < 0) { LOG_SYSERR << "sockets::close"; } } -void sockets::shutdownWrite(int sockfd) -{ - if (::shutdown(sockfd, SHUT_WR) < 0) - { +void sockets::shutdownWrite(int sockfd) { + if (::shutdown(sockfd, SHUT_WR) < 0) { LOG_SYSERR << "sockets::shutdownWrite"; } } -void sockets::toIpPort(char* buf, size_t size, - const struct sockaddr* addr) -{ - if (addr->sa_family == AF_INET6) - { +void sockets::toIpPort(char *buf, size_t size, const struct sockaddr *addr) { + if (addr->sa_family == AF_INET6) { buf[0] = '['; - toIp(buf+1, size-1, addr); + toIp(buf + 1, size - 1, addr); size_t end = ::strlen(buf); - const struct sockaddr_in6* addr6 = sockaddr_in6_cast(addr); + const struct sockaddr_in6 *addr6 = sockaddr_in6_cast(addr); uint16_t port = sockets::networkToHost16(addr6->sin6_port); assert(size > end); - snprintf(buf+end, size-end, "]:%u", port); + snprintf(buf + end, size - end, "]:%u", port); return; } toIp(buf, size, addr); size_t end = ::strlen(buf); - const struct sockaddr_in* addr4 = sockaddr_in_cast(addr); + const struct sockaddr_in *addr4 = sockaddr_in_cast(addr); uint16_t port = sockets::networkToHost16(addr4->sin_port); assert(size > end); - snprintf(buf+end, size-end, ":%u", port); + snprintf(buf + end, size - end, ":%u", port); } -void sockets::toIp(char* buf, size_t size, - const struct sockaddr* addr) -{ - if (addr->sa_family == AF_INET) - { +void sockets::toIp(char *buf, size_t size, const struct sockaddr *addr) { + if (addr->sa_family == AF_INET) { assert(size >= INET_ADDRSTRLEN); - const struct sockaddr_in* addr4 = sockaddr_in_cast(addr); + const struct sockaddr_in *addr4 = sockaddr_in_cast(addr); ::inet_ntop(AF_INET, &addr4->sin_addr, buf, static_cast(size)); - } - else if (addr->sa_family == AF_INET6) - { + } else if (addr->sa_family == AF_INET6) { assert(size >= INET6_ADDRSTRLEN); - const struct sockaddr_in6* addr6 = sockaddr_in6_cast(addr); + const struct sockaddr_in6 *addr6 = sockaddr_in6_cast(addr); ::inet_ntop(AF_INET6, &addr6->sin6_addr, buf, static_cast(size)); } } -void sockets::fromIpPort(const char* ip, uint16_t port, - struct sockaddr_in* addr) -{ +void sockets::fromIpPort(const char *ip, uint16_t port, + struct sockaddr_in *addr) { addr->sin_family = AF_INET; addr->sin_port = hostToNetwork16(port); - if (::inet_pton(AF_INET, ip, &addr->sin_addr) <= 0) - { + if (::inet_pton(AF_INET, ip, &addr->sin_addr) <= 0) { LOG_SYSERR << "sockets::fromIpPort"; } } -void sockets::fromIpPort(const char* ip, uint16_t port, - struct sockaddr_in6* addr) -{ +void sockets::fromIpPort(const char *ip, uint16_t port, + struct sockaddr_in6 *addr) { addr->sin6_family = AF_INET6; addr->sin6_port = hostToNetwork16(port); - if (::inet_pton(AF_INET6, ip, &addr->sin6_addr) <= 0) - { + if (::inet_pton(AF_INET6, ip, &addr->sin6_addr) <= 0) { LOG_SYSERR << "sockets::fromIpPort"; } } -int sockets::getSocketError(int sockfd) -{ +int sockets::getSocketError(int sockfd) { int optval; socklen_t optlen = static_cast(sizeof optval); - if (::getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) < 0) - { + if (::getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) < 0) { return errno; - } - else - { + } else { return optval; } } -struct sockaddr_in6 sockets::getLocalAddr(int sockfd) -{ +struct sockaddr_in6 sockets::getLocalAddr(int sockfd) { struct sockaddr_in6 localaddr; memZero(&localaddr, sizeof localaddr); socklen_t addrlen = static_cast(sizeof localaddr); - if (::getsockname(sockfd, sockaddr_cast(&localaddr), &addrlen) < 0) - { + if (::getsockname(sockfd, sockaddr_cast(&localaddr), &addrlen) < 0) { LOG_SYSERR << "sockets::getLocalAddr"; } return localaddr; } -struct sockaddr_in6 sockets::getPeerAddr(int sockfd) -{ +struct sockaddr_in6 sockets::getPeerAddr(int sockfd) { struct sockaddr_in6 peeraddr; memZero(&peeraddr, sizeof peeraddr); socklen_t addrlen = static_cast(sizeof peeraddr); - if (::getpeername(sockfd, sockaddr_cast(&peeraddr), &addrlen) < 0) - { + if (::getpeername(sockfd, sockaddr_cast(&peeraddr), &addrlen) < 0) { LOG_SYSERR << "sockets::getPeerAddr"; } return peeraddr; } -bool sockets::isSelfConnect(int sockfd) -{ +bool sockets::isSelfConnect(int sockfd) { struct sockaddr_in6 localaddr = getLocalAddr(sockfd); struct sockaddr_in6 peeraddr = getPeerAddr(sockfd); - if (localaddr.sin6_family == AF_INET) - { - const struct sockaddr_in* laddr4 = reinterpret_cast(&localaddr); - const struct sockaddr_in* raddr4 = reinterpret_cast(&peeraddr); - return laddr4->sin_port == raddr4->sin_port - && laddr4->sin_addr.s_addr == raddr4->sin_addr.s_addr; - } - else if (localaddr.sin6_family == AF_INET6) - { - return localaddr.sin6_port == peeraddr.sin6_port - && memcmp(&localaddr.sin6_addr, &peeraddr.sin6_addr, sizeof localaddr.sin6_addr) == 0; - } - else - { + if (localaddr.sin6_family == AF_INET) { + const struct sockaddr_in *laddr4 = + reinterpret_cast(&localaddr); + const struct sockaddr_in *raddr4 = + reinterpret_cast(&peeraddr); + return laddr4->sin_port == raddr4->sin_port && + laddr4->sin_addr.s_addr == raddr4->sin_addr.s_addr; + } else if (localaddr.sin6_family == AF_INET6) { + return localaddr.sin6_port == peeraddr.sin6_port && + memcmp(&localaddr.sin6_addr, &peeraddr.sin6_addr, + sizeof localaddr.sin6_addr) == 0; + } else { return false; } } - diff --git a/muduo/net/SocketsOps.h b/muduo/net/SocketsOps.h index 9c465975f..618fc739e 100644 --- a/muduo/net/SocketsOps.h +++ b/muduo/net/SocketsOps.h @@ -13,52 +13,45 @@ #include -namespace muduo -{ -namespace net -{ -namespace sockets -{ +namespace muduo { +namespace net { +namespace sockets { /// /// Creates a non-blocking socket file descriptor, /// abort if any error. int createNonblockingOrDie(sa_family_t family); -int connect(int sockfd, const struct sockaddr* addr); -void bindOrDie(int sockfd, const struct sockaddr* addr); +int connect(int sockfd, const struct sockaddr *addr); +void bindOrDie(int sockfd, const struct sockaddr *addr); void listenOrDie(int sockfd); -int accept(int sockfd, struct sockaddr_in6* addr); +int accept(int sockfd, struct sockaddr_in6 *addr); ssize_t read(int sockfd, void *buf, size_t count); ssize_t readv(int sockfd, const struct iovec *iov, int iovcnt); ssize_t write(int sockfd, const void *buf, size_t count); void close(int sockfd); void shutdownWrite(int sockfd); -void toIpPort(char* buf, size_t size, - const struct sockaddr* addr); -void toIp(char* buf, size_t size, - const struct sockaddr* addr); +void toIpPort(char *buf, size_t size, const struct sockaddr *addr); +void toIp(char *buf, size_t size, const struct sockaddr *addr); -void fromIpPort(const char* ip, uint16_t port, - struct sockaddr_in* addr); -void fromIpPort(const char* ip, uint16_t port, - struct sockaddr_in6* addr); +void fromIpPort(const char *ip, uint16_t port, struct sockaddr_in *addr); +void fromIpPort(const char *ip, uint16_t port, struct sockaddr_in6 *addr); int getSocketError(int sockfd); -const struct sockaddr* sockaddr_cast(const struct sockaddr_in* addr); -const struct sockaddr* sockaddr_cast(const struct sockaddr_in6* addr); -struct sockaddr* sockaddr_cast(struct sockaddr_in6* addr); -const struct sockaddr_in* sockaddr_in_cast(const struct sockaddr* addr); -const struct sockaddr_in6* sockaddr_in6_cast(const struct sockaddr* addr); +const struct sockaddr *sockaddr_cast(const struct sockaddr_in *addr); +const struct sockaddr *sockaddr_cast(const struct sockaddr_in6 *addr); +struct sockaddr *sockaddr_cast(struct sockaddr_in6 *addr); +const struct sockaddr_in *sockaddr_in_cast(const struct sockaddr *addr); +const struct sockaddr_in6 *sockaddr_in6_cast(const struct sockaddr *addr); struct sockaddr_in6 getLocalAddr(int sockfd); struct sockaddr_in6 getPeerAddr(int sockfd); bool isSelfConnect(int sockfd); -} // namespace sockets -} // namespace net -} // namespace muduo +} // namespace sockets +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_SOCKETSOPS_H +#endif // MUDUO_NET_SOCKETSOPS_H diff --git a/muduo/net/TcpClient.cc b/muduo/net/TcpClient.cc index 1e668b3c2..6b47543ff 100644 --- a/muduo/net/TcpClient.cc +++ b/muduo/net/TcpClient.cc @@ -14,7 +14,7 @@ #include "muduo/net/EventLoop.h" #include "muduo/net/SocketsOps.h" -#include // snprintf +#include // snprintf using namespace muduo; using namespace muduo::net; @@ -30,50 +30,38 @@ using namespace muduo::net; // { // } -namespace muduo -{ -namespace net -{ -namespace detail -{ +namespace muduo { +namespace net { +namespace detail { -void removeConnection(EventLoop* loop, const TcpConnectionPtr& conn) -{ +void removeConnection(EventLoop *loop, const TcpConnectionPtr &conn) { loop->queueInLoop(std::bind(&TcpConnection::connectDestroyed, conn)); } -void removeConnector(const ConnectorPtr& connector) -{ - //connector-> +void removeConnector(const ConnectorPtr &connector) { + // connector-> } -} // namespace detail -} // namespace net -} // namespace muduo - -TcpClient::TcpClient(EventLoop* loop, - const InetAddress& serverAddr, - const string& nameArg) - : loop_(CHECK_NOTNULL(loop)), - connector_(new Connector(loop, serverAddr)), - name_(nameArg), - connectionCallback_(defaultConnectionCallback), - messageCallback_(defaultMessageCallback), - retry_(false), - connect_(true), - nextConnId_(1) -{ +} // namespace detail +} // namespace net +} // namespace muduo + +TcpClient::TcpClient(EventLoop *loop, const InetAddress &serverAddr, + const string &nameArg) + : loop_(CHECK_NOTNULL(loop)), connector_(new Connector(loop, serverAddr)), + name_(nameArg), connectionCallback_(defaultConnectionCallback), + messageCallback_(defaultMessageCallback), retry_(false), connect_(true), + nextConnId_(1) { connector_->setNewConnectionCallback( std::bind(&TcpClient::newConnection, this, _1)); // FIXME setConnectFailedCallback - LOG_INFO << "TcpClient::TcpClient[" << name_ - << "] - connector " << get_pointer(connector_); + LOG_INFO << "TcpClient::TcpClient[" << name_ << "] - connector " + << get_pointer(connector_); } -TcpClient::~TcpClient() -{ - LOG_INFO << "TcpClient::~TcpClient[" << name_ - << "] - connector " << get_pointer(connector_); +TcpClient::~TcpClient() { + LOG_INFO << "TcpClient::~TcpClient[" << name_ << "] - connector " + << get_pointer(connector_); TcpConnectionPtr conn; bool unique = false; { @@ -81,28 +69,22 @@ TcpClient::~TcpClient() unique = connection_.unique(); conn = connection_; } - if (conn) - { + if (conn) { assert(loop_ == conn->getLoop()); // FIXME: not 100% safe, if we are in different thread CloseCallback cb = std::bind(&detail::removeConnection, loop_, _1); - loop_->runInLoop( - std::bind(&TcpConnection::setCloseCallback, conn, cb)); - if (unique) - { + loop_->runInLoop(std::bind(&TcpConnection::setCloseCallback, conn, cb)); + if (unique) { conn->forceClose(); } - } - else - { + } else { connector_->stop(); // FIXME: HACK loop_->runAfter(1, std::bind(&detail::removeConnector, connector_)); } } -void TcpClient::connect() -{ +void TcpClient::connect() { // FIXME: check state LOG_INFO << "TcpClient::connect[" << name_ << "] - connecting to " << connector_->serverAddress().toIpPort(); @@ -110,27 +92,23 @@ void TcpClient::connect() connector_->start(); } -void TcpClient::disconnect() -{ +void TcpClient::disconnect() { connect_ = false; { MutexLockGuard lock(mutex_); - if (connection_) - { + if (connection_) { connection_->shutdown(); } } } -void TcpClient::stop() -{ +void TcpClient::stop() { connect_ = false; connector_->stop(); } -void TcpClient::newConnection(int sockfd) -{ +void TcpClient::newConnection(int sockfd) { loop_->assertInLoopThread(); InetAddress peerAddr(sockets::getPeerAddr(sockfd)); char buf[32]; @@ -141,11 +119,8 @@ void TcpClient::newConnection(int sockfd) InetAddress localAddr(sockets::getLocalAddr(sockfd)); // FIXME poll with zero timeout to double confirm the new connection // FIXME use make_shared if necessary - TcpConnectionPtr conn(new TcpConnection(loop_, - connName, - sockfd, - localAddr, - peerAddr)); + TcpConnectionPtr conn( + new TcpConnection(loop_, connName, sockfd, localAddr, peerAddr)); conn->setConnectionCallback(connectionCallback_); conn->setMessageCallback(messageCallback_); @@ -159,8 +134,7 @@ void TcpClient::newConnection(int sockfd) conn->connectEstablished(); } -void TcpClient::removeConnection(const TcpConnectionPtr& conn) -{ +void TcpClient::removeConnection(const TcpConnectionPtr &conn) { loop_->assertInLoopThread(); assert(loop_ == conn->getLoop()); @@ -171,11 +145,9 @@ void TcpClient::removeConnection(const TcpConnectionPtr& conn) } loop_->queueInLoop(std::bind(&TcpConnection::connectDestroyed, conn)); - if (retry_ && connect_) - { + if (retry_ && connect_) { LOG_INFO << "TcpClient::connect[" << name_ << "] - Reconnecting to " << connector_->serverAddress().toIpPort(); connector_->restart(); } } - diff --git a/muduo/net/TcpClient.h b/muduo/net/TcpClient.h index c498cb3fd..5fcda652f 100644 --- a/muduo/net/TcpClient.h +++ b/muduo/net/TcpClient.h @@ -14,63 +14,60 @@ #include "muduo/base/Mutex.h" #include "muduo/net/TcpConnection.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Connector; typedef std::shared_ptr ConnectorPtr; -class TcpClient : noncopyable -{ - public: +class TcpClient : noncopyable { +public: // TcpClient(EventLoop* loop); // TcpClient(EventLoop* loop, const string& host, uint16_t port); - TcpClient(EventLoop* loop, - const InetAddress& serverAddr, - const string& nameArg); - ~TcpClient(); // force out-line dtor, for std::unique_ptr members. + TcpClient(EventLoop *loop, const InetAddress &serverAddr, + const string &nameArg); + ~TcpClient(); // force out-line dtor, for std::unique_ptr members. void connect(); void disconnect(); void stop(); - TcpConnectionPtr connection() const - { + TcpConnectionPtr connection() const { MutexLockGuard lock(mutex_); return connection_; } - EventLoop* getLoop() const { return loop_; } + EventLoop *getLoop() const { return loop_; } bool retry() const { return retry_; } void enableRetry() { retry_ = true; } - const string& name() const - { return name_; } + const string &name() const { return name_; } /// Set connection callback. /// Not thread safe. - void setConnectionCallback(ConnectionCallback cb) - { connectionCallback_ = std::move(cb); } + void setConnectionCallback(ConnectionCallback cb) { + connectionCallback_ = std::move(cb); + } /// Set message callback. /// Not thread safe. - void setMessageCallback(MessageCallback cb) - { messageCallback_ = std::move(cb); } + void setMessageCallback(MessageCallback cb) { + messageCallback_ = std::move(cb); + } /// Set write complete callback. /// Not thread safe. - void setWriteCompleteCallback(WriteCompleteCallback cb) - { writeCompleteCallback_ = std::move(cb); } + void setWriteCompleteCallback(WriteCompleteCallback cb) { + writeCompleteCallback_ = std::move(cb); + } - private: +private: /// Not thread safe, but in loop void newConnection(int sockfd); /// Not thread safe, but in loop - void removeConnection(const TcpConnectionPtr& conn); + void removeConnection(const TcpConnectionPtr &conn); - EventLoop* loop_; + EventLoop *loop_; ConnectorPtr connector_; // avoid revealing Connector const string name_; ConnectionCallback connectionCallback_; @@ -84,7 +81,7 @@ class TcpClient : noncopyable TcpConnectionPtr connection_ GUARDED_BY(mutex_); }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_TCPCLIENT_H +#endif // MUDUO_NET_TCPCLIENT_H diff --git a/muduo/net/TcpConnection.cc b/muduo/net/TcpConnection.cc index 37f58a452..3ffea96d7 100644 --- a/muduo/net/TcpConnection.cc +++ b/muduo/net/TcpConnection.cc @@ -20,150 +20,114 @@ using namespace muduo; using namespace muduo::net; -void muduo::net::defaultConnectionCallback(const TcpConnectionPtr& conn) -{ +void muduo::net::defaultConnectionCallback(const TcpConnectionPtr &conn) { LOG_TRACE << conn->localAddress().toIpPort() << " -> " << conn->peerAddress().toIpPort() << " is " << (conn->connected() ? "UP" : "DOWN"); - // do not call conn->forceClose(), because some users want to register message callback only. + // do not call conn->forceClose(), because some users want to register + // message callback only. } -void muduo::net::defaultMessageCallback(const TcpConnectionPtr&, - Buffer* buf, - Timestamp) -{ +void muduo::net::defaultMessageCallback(const TcpConnectionPtr &, Buffer *buf, + Timestamp) { buf->retrieveAll(); } -TcpConnection::TcpConnection(EventLoop* loop, - const string& nameArg, - int sockfd, - const InetAddress& localAddr, - const InetAddress& peerAddr) - : loop_(CHECK_NOTNULL(loop)), - name_(nameArg), - state_(kConnecting), - reading_(true), - socket_(new Socket(sockfd)), - channel_(new Channel(loop, sockfd)), - localAddr_(localAddr), - peerAddr_(peerAddr), - highWaterMark_(64*1024*1024) -{ - channel_->setReadCallback( - std::bind(&TcpConnection::handleRead, this, _1)); - channel_->setWriteCallback( - std::bind(&TcpConnection::handleWrite, this)); - channel_->setCloseCallback( - std::bind(&TcpConnection::handleClose, this)); - channel_->setErrorCallback( - std::bind(&TcpConnection::handleError, this)); - LOG_DEBUG << "TcpConnection::ctor[" << name_ << "] at " << this +TcpConnection::TcpConnection(EventLoop *loop, const string &nameArg, int sockfd, + const InetAddress &localAddr, + const InetAddress &peerAddr) + : loop_(CHECK_NOTNULL(loop)), name_(nameArg), state_(kConnecting), + reading_(true), socket_(new Socket(sockfd)), + channel_(new Channel(loop, sockfd)), localAddr_(localAddr), + peerAddr_(peerAddr), highWaterMark_(64 * 1024 * 1024) { + channel_->setReadCallback(std::bind(&TcpConnection::handleRead, this, _1)); + channel_->setWriteCallback(std::bind(&TcpConnection::handleWrite, this)); + channel_->setCloseCallback(std::bind(&TcpConnection::handleClose, this)); + channel_->setErrorCallback(std::bind(&TcpConnection::handleError, this)); + LOG_DEBUG << "TcpConnection::ctor[" << name_ << "] at " << this << " fd=" << sockfd; socket_->setKeepAlive(true); } -TcpConnection::~TcpConnection() -{ - LOG_DEBUG << "TcpConnection::dtor[" << name_ << "] at " << this - << " fd=" << channel_->fd() - << " state=" << stateToString(); +TcpConnection::~TcpConnection() { + LOG_DEBUG << "TcpConnection::dtor[" << name_ << "] at " << this + << " fd=" << channel_->fd() << " state=" << stateToString(); assert(state_ == kDisconnected); } -bool TcpConnection::getTcpInfo(struct tcp_info* tcpi) const -{ +bool TcpConnection::getTcpInfo(struct tcp_info *tcpi) const { return socket_->getTcpInfo(tcpi); } -string TcpConnection::getTcpInfoString() const -{ +string TcpConnection::getTcpInfoString() const { char buf[1024]; buf[0] = '\0'; socket_->getTcpInfoString(buf, sizeof buf); return buf; } -void TcpConnection::send(const void* data, int len) -{ - send(StringPiece(static_cast(data), len)); +void TcpConnection::send(const void *data, int len) { + send(StringPiece(static_cast(data), len)); } -void TcpConnection::send(const StringPiece& message) -{ - if (state_ == kConnected) - { - if (loop_->isInLoopThread()) - { +void TcpConnection::send(const StringPiece &message) { + if (state_ == kConnected) { + if (loop_->isInLoopThread()) { sendInLoop(message); - } - else - { - void (TcpConnection::*fp)(const StringPiece& message) = &TcpConnection::sendInLoop; - loop_->runInLoop( - std::bind(fp, - this, // FIXME - message.as_string())); - //std::forward(message))); + } else { + void (TcpConnection::*fp)(const StringPiece &message) = + &TcpConnection::sendInLoop; + loop_->runInLoop(std::bind(fp, + this, // FIXME + message.as_string())); + // std::forward(message))); } } } // FIXME efficiency!!! -void TcpConnection::send(Buffer* buf) -{ - if (state_ == kConnected) - { - if (loop_->isInLoopThread()) - { +void TcpConnection::send(Buffer *buf) { + if (state_ == kConnected) { + if (loop_->isInLoopThread()) { sendInLoop(buf->peek(), buf->readableBytes()); buf->retrieveAll(); - } - else - { - void (TcpConnection::*fp)(const StringPiece& message) = &TcpConnection::sendInLoop; - loop_->runInLoop( - std::bind(fp, - this, // FIXME - buf->retrieveAllAsString())); - //std::forward(message))); + } else { + void (TcpConnection::*fp)(const StringPiece &message) = + &TcpConnection::sendInLoop; + loop_->runInLoop(std::bind(fp, + this, // FIXME + buf->retrieveAllAsString())); + // std::forward(message))); } } } -void TcpConnection::sendInLoop(const StringPiece& message) -{ +void TcpConnection::sendInLoop(const StringPiece &message) { sendInLoop(message.data(), message.size()); } -void TcpConnection::sendInLoop(const void* data, size_t len) -{ +void TcpConnection::sendInLoop(const void *data, size_t len) { loop_->assertInLoopThread(); ssize_t nwrote = 0; size_t remaining = len; bool faultError = false; - if (state_ == kDisconnected) - { + if (state_ == kDisconnected) { LOG_WARN << "disconnected, give up writing"; return; } // if no thing in output queue, try writing directly - if (!channel_->isWriting() && outputBuffer_.readableBytes() == 0) - { + if (!channel_->isWriting() && outputBuffer_.readableBytes() == 0) { nwrote = sockets::write(channel_->fd(), data, len); - if (nwrote >= 0) - { + if (nwrote >= 0) { remaining = len - nwrote; - if (remaining == 0 && writeCompleteCallback_) - { - loop_->queueInLoop(std::bind(writeCompleteCallback_, shared_from_this())); + if (remaining == 0 && writeCompleteCallback_) { + loop_->queueInLoop( + std::bind(writeCompleteCallback_, shared_from_this())); } - } - else // nwrote < 0 + } else // nwrote < 0 { nwrote = 0; - if (errno != EWOULDBLOCK) - { + if (errno != EWOULDBLOCK) { LOG_SYSERR << "TcpConnection::sendInLoop"; if (errno == EPIPE || errno == ECONNRESET) // FIXME: any others? { @@ -174,39 +138,32 @@ void TcpConnection::sendInLoop(const void* data, size_t len) } assert(remaining <= len); - if (!faultError && remaining > 0) - { + if (!faultError && remaining > 0) { size_t oldLen = outputBuffer_.readableBytes(); - if (oldLen + remaining >= highWaterMark_ - && oldLen < highWaterMark_ - && highWaterMarkCallback_) - { - loop_->queueInLoop(std::bind(highWaterMarkCallback_, shared_from_this(), oldLen + remaining)); + if (oldLen + remaining >= highWaterMark_ && oldLen < highWaterMark_ && + highWaterMarkCallback_) { + loop_->queueInLoop(std::bind(highWaterMarkCallback_, shared_from_this(), + oldLen + remaining)); } - outputBuffer_.append(static_cast(data)+nwrote, remaining); - if (!channel_->isWriting()) - { + outputBuffer_.append(static_cast(data) + nwrote, remaining); + if (!channel_->isWriting()) { channel_->enableWriting(); } } } -void TcpConnection::shutdown() -{ +void TcpConnection::shutdown() { // FIXME: use compare and swap - if (state_ == kConnected) - { + if (state_ == kConnected) { setState(kDisconnecting); // FIXME: shared_from_this()? loop_->runInLoop(std::bind(&TcpConnection::shutdownInLoop, this)); } } -void TcpConnection::shutdownInLoop() -{ +void TcpConnection::shutdownInLoop() { loop_->assertInLoopThread(); - if (!channel_->isWriting()) - { + if (!channel_->isWriting()) { // we are not writing socket_->shutdownWrite(); } @@ -218,7 +175,8 @@ void TcpConnection::shutdownInLoop() // if (state_ == kConnected) // { // setState(kDisconnecting); -// loop_->runInLoop(std::bind(&TcpConnection::shutdownAndForceCloseInLoop, this, seconds)); +// loop_->runInLoop(std::bind(&TcpConnection::shutdownAndForceCloseInLoop, +// this, seconds)); // } // } @@ -236,92 +194,76 @@ void TcpConnection::shutdownInLoop() // &TcpConnection::forceCloseInLoop)); // } -void TcpConnection::forceClose() -{ +void TcpConnection::forceClose() { // FIXME: use compare and swap - if (state_ == kConnected || state_ == kDisconnecting) - { + if (state_ == kConnected || state_ == kDisconnecting) { setState(kDisconnecting); - loop_->queueInLoop(std::bind(&TcpConnection::forceCloseInLoop, shared_from_this())); + loop_->queueInLoop( + std::bind(&TcpConnection::forceCloseInLoop, shared_from_this())); } } -void TcpConnection::forceCloseWithDelay(double seconds) -{ - if (state_ == kConnected || state_ == kDisconnecting) - { +void TcpConnection::forceCloseWithDelay(double seconds) { + if (state_ == kConnected || state_ == kDisconnecting) { setState(kDisconnecting); - loop_->runAfter( - seconds, - makeWeakCallback(shared_from_this(), - &TcpConnection::forceClose)); // not forceCloseInLoop to avoid race condition + loop_->runAfter(seconds, + makeWeakCallback( + shared_from_this(), + &TcpConnection::forceClose)); // not forceCloseInLoop to + // avoid race condition } } -void TcpConnection::forceCloseInLoop() -{ +void TcpConnection::forceCloseInLoop() { loop_->assertInLoopThread(); - if (state_ == kConnected || state_ == kDisconnecting) - { + if (state_ == kConnected || state_ == kDisconnecting) { // as if we received 0 byte in handleRead(); handleClose(); } } -const char* TcpConnection::stateToString() const -{ - switch (state_) - { - case kDisconnected: - return "kDisconnected"; - case kConnecting: - return "kConnecting"; - case kConnected: - return "kConnected"; - case kDisconnecting: - return "kDisconnecting"; - default: - return "unknown state"; +const char *TcpConnection::stateToString() const { + switch (state_) { + case kDisconnected: + return "kDisconnected"; + case kConnecting: + return "kConnecting"; + case kConnected: + return "kConnected"; + case kDisconnecting: + return "kDisconnecting"; + default: + return "unknown state"; } } -void TcpConnection::setTcpNoDelay(bool on) -{ - socket_->setTcpNoDelay(on); -} +void TcpConnection::setTcpNoDelay(bool on) { socket_->setTcpNoDelay(on); } -void TcpConnection::startRead() -{ +void TcpConnection::startRead() { loop_->runInLoop(std::bind(&TcpConnection::startReadInLoop, this)); } -void TcpConnection::startReadInLoop() -{ +void TcpConnection::startReadInLoop() { loop_->assertInLoopThread(); - if (!reading_ || !channel_->isReading()) - { + if (!reading_ || !channel_->isReading()) { channel_->enableReading(); reading_ = true; } } -void TcpConnection::stopRead() -{ +void TcpConnection::stopRead() { loop_->runInLoop(std::bind(&TcpConnection::stopReadInLoop, this)); } -void TcpConnection::stopReadInLoop() -{ +void TcpConnection::stopReadInLoop() { loop_->assertInLoopThread(); - if (reading_ || channel_->isReading()) - { + if (reading_ || channel_->isReading()) { channel_->disableReading(); reading_ = false; } } -void TcpConnection::connectEstablished() -{ +void TcpConnection::connectEstablished() { loop_->assertInLoopThread(); assert(state_ == kConnecting); setState(kConnected); @@ -331,11 +273,9 @@ void TcpConnection::connectEstablished() connectionCallback_(shared_from_this()); } -void TcpConnection::connectDestroyed() -{ +void TcpConnection::connectDestroyed() { loop_->assertInLoopThread(); - if (state_ == kConnected) - { + if (state_ == kConnected) { setState(kDisconnected); channel_->disableAll(); @@ -344,69 +284,52 @@ void TcpConnection::connectDestroyed() channel_->remove(); } -void TcpConnection::handleRead(Timestamp receiveTime) -{ +void TcpConnection::handleRead(Timestamp receiveTime) { loop_->assertInLoopThread(); int savedErrno = 0; ssize_t n = inputBuffer_.readFd(channel_->fd(), &savedErrno); - if (n > 0) - { + if (n > 0) { messageCallback_(shared_from_this(), &inputBuffer_, receiveTime); - } - else if (n == 0) - { + } else if (n == 0) { handleClose(); - } - else - { + } else { errno = savedErrno; LOG_SYSERR << "TcpConnection::handleRead"; handleError(); } } -void TcpConnection::handleWrite() -{ +void TcpConnection::handleWrite() { loop_->assertInLoopThread(); - if (channel_->isWriting()) - { - ssize_t n = sockets::write(channel_->fd(), - outputBuffer_.peek(), + if (channel_->isWriting()) { + ssize_t n = sockets::write(channel_->fd(), outputBuffer_.peek(), outputBuffer_.readableBytes()); - if (n > 0) - { + if (n > 0) { outputBuffer_.retrieve(n); - if (outputBuffer_.readableBytes() == 0) - { + if (outputBuffer_.readableBytes() == 0) { channel_->disableWriting(); - if (writeCompleteCallback_) - { - loop_->queueInLoop(std::bind(writeCompleteCallback_, shared_from_this())); + if (writeCompleteCallback_) { + loop_->queueInLoop( + std::bind(writeCompleteCallback_, shared_from_this())); } - if (state_ == kDisconnecting) - { + if (state_ == kDisconnecting) { shutdownInLoop(); } } - } - else - { + } else { LOG_SYSERR << "TcpConnection::handleWrite"; // if (state_ == kDisconnecting) // { // shutdownInLoop(); // } } - } - else - { + } else { LOG_TRACE << "Connection fd = " << channel_->fd() << " is down, no more writing"; } } -void TcpConnection::handleClose() -{ +void TcpConnection::handleClose() { loop_->assertInLoopThread(); LOG_TRACE << "fd = " << channel_->fd() << " state = " << stateToString(); assert(state_ == kConnected || state_ == kDisconnecting); @@ -420,10 +343,8 @@ void TcpConnection::handleClose() closeCallback_(guardThis); } -void TcpConnection::handleError() -{ +void TcpConnection::handleError() { int err = sockets::getSocketError(channel_->fd()); LOG_ERROR << "TcpConnection::handleError [" << name_ << "] - SO_ERROR = " << err << " " << strerror_tl(err); } - diff --git a/muduo/net/TcpConnection.h b/muduo/net/TcpConnection.h index cb7633153..ae977f215 100644 --- a/muduo/net/TcpConnection.h +++ b/muduo/net/TcpConnection.h @@ -11,11 +11,11 @@ #ifndef MUDUO_NET_TCPCONNECTION_H #define MUDUO_NET_TCPCONNECTION_H -#include "muduo/base/noncopyable.h" #include "muduo/base/StringPiece.h" #include "muduo/base/Types.h" -#include "muduo/net/Callbacks.h" +#include "muduo/base/noncopyable.h" #include "muduo/net/Buffer.h" +#include "muduo/net/Callbacks.h" #include "muduo/net/InetAddress.h" #include @@ -25,10 +25,8 @@ // struct tcp_info is in struct tcp_info; -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Channel; class EventLoop; @@ -39,101 +37,98 @@ class Socket; /// /// This is an interface class, so don't expose too much details. class TcpConnection : noncopyable, - public std::enable_shared_from_this -{ - public: + public std::enable_shared_from_this { +public: /// Constructs a TcpConnection with a connected sockfd /// /// User should not create this object. - TcpConnection(EventLoop* loop, - const string& name, - int sockfd, - const InetAddress& localAddr, - const InetAddress& peerAddr); + TcpConnection(EventLoop *loop, const string &name, int sockfd, + const InetAddress &localAddr, const InetAddress &peerAddr); ~TcpConnection(); - EventLoop* getLoop() const { return loop_; } - const string& name() const { return name_; } - const InetAddress& localAddress() const { return localAddr_; } - const InetAddress& peerAddress() const { return peerAddr_; } + EventLoop *getLoop() const { return loop_; } + const string &name() const { return name_; } + const InetAddress &localAddress() const { return localAddr_; } + const InetAddress &peerAddress() const { return peerAddr_; } bool connected() const { return state_ == kConnected; } bool disconnected() const { return state_ == kDisconnected; } // return true if success. - bool getTcpInfo(struct tcp_info*) const; + bool getTcpInfo(struct tcp_info *) const; string getTcpInfoString() const; // void send(string&& message); // C++11 - void send(const void* message, int len); - void send(const StringPiece& message); + void send(const void *message, int len); + void send(const StringPiece &message); // void send(Buffer&& message); // C++11 - void send(Buffer* message); // this one will swap data - void shutdown(); // NOT thread safe, no simultaneous calling - // void shutdownAndForceCloseAfter(double seconds); // NOT thread safe, no simultaneous calling + void send(Buffer *message); // this one will swap data + void shutdown(); // NOT thread safe, no simultaneous calling + // void shutdownAndForceCloseAfter(double seconds); // NOT thread safe, + // no simultaneous calling void forceClose(); void forceCloseWithDelay(double seconds); void setTcpNoDelay(bool on); // reading or not void startRead(); void stopRead(); - bool isReading() const { return reading_; }; // NOT thread safe, may race with start/stopReadInLoop + bool isReading() const { + return reading_; + }; // NOT thread safe, may race with start/stopReadInLoop - void setContext(const boost::any& context) - { context_ = context; } + void setContext(const boost::any &context) { context_ = context; } - const boost::any& getContext() const - { return context_; } + const boost::any &getContext() const { return context_; } - boost::any* getMutableContext() - { return &context_; } + boost::any *getMutableContext() { return &context_; } - void setConnectionCallback(const ConnectionCallback& cb) - { connectionCallback_ = cb; } + void setConnectionCallback(const ConnectionCallback &cb) { + connectionCallback_ = cb; + } - void setMessageCallback(const MessageCallback& cb) - { messageCallback_ = cb; } + void setMessageCallback(const MessageCallback &cb) { messageCallback_ = cb; } - void setWriteCompleteCallback(const WriteCompleteCallback& cb) - { writeCompleteCallback_ = cb; } + void setWriteCompleteCallback(const WriteCompleteCallback &cb) { + writeCompleteCallback_ = cb; + } - void setHighWaterMarkCallback(const HighWaterMarkCallback& cb, size_t highWaterMark) - { highWaterMarkCallback_ = cb; highWaterMark_ = highWaterMark; } + void setHighWaterMarkCallback(const HighWaterMarkCallback &cb, + size_t highWaterMark) { + highWaterMarkCallback_ = cb; + highWaterMark_ = highWaterMark; + } /// Advanced interface - Buffer* inputBuffer() - { return &inputBuffer_; } + Buffer *inputBuffer() { return &inputBuffer_; } - Buffer* outputBuffer() - { return &outputBuffer_; } + Buffer *outputBuffer() { return &outputBuffer_; } /// Internal use only. - void setCloseCallback(const CloseCallback& cb) - { closeCallback_ = cb; } + void setCloseCallback(const CloseCallback &cb) { closeCallback_ = cb; } // called when TcpServer accepts a new connection - void connectEstablished(); // should be called only once + void connectEstablished(); // should be called only once // called when TcpServer has removed me from its map - void connectDestroyed(); // should be called only once + void connectDestroyed(); // should be called only once - private: +private: enum StateE { kDisconnected, kConnecting, kConnected, kDisconnecting }; void handleRead(Timestamp receiveTime); void handleWrite(); void handleClose(); void handleError(); // void sendInLoop(string&& message); - void sendInLoop(const StringPiece& message); - void sendInLoop(const void* message, size_t len); + void sendInLoop(const StringPiece &message); + void sendInLoop(const void *message, size_t len); void shutdownInLoop(); // void shutdownAndForceCloseInLoop(double seconds); void forceCloseInLoop(); void setState(StateE s) { state_ = s; } - const char* stateToString() const; + const char *stateToString() const; void startReadInLoop(); void stopReadInLoop(); - EventLoop* loop_; + EventLoop *loop_; const string name_; - StateE state_; // FIXME: use atomic variable + StateE state_; // FIXME: use atomic variable bool reading_; // we don't expose those classes to client. std::unique_ptr socket_; @@ -155,7 +150,7 @@ class TcpConnection : noncopyable, typedef std::shared_ptr TcpConnectionPtr; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_TCPCONNECTION_H +#endif // MUDUO_NET_TCPCONNECTION_H diff --git a/muduo/net/TcpServer.cc b/muduo/net/TcpServer.cc index e4f8e249d..704e3501a 100644 --- a/muduo/net/TcpServer.cc +++ b/muduo/net/TcpServer.cc @@ -14,80 +14,64 @@ #include "muduo/net/EventLoopThreadPool.h" #include "muduo/net/SocketsOps.h" -#include // snprintf +#include // snprintf using namespace muduo; using namespace muduo::net; -TcpServer::TcpServer(EventLoop* loop, - const InetAddress& listenAddr, - const string& nameArg, - Option option) - : loop_(CHECK_NOTNULL(loop)), - ipPort_(listenAddr.toIpPort()), - name_(nameArg), - acceptor_(new Acceptor(loop, listenAddr, option == kReusePort)), - threadPool_(new EventLoopThreadPool(loop, name_)), - connectionCallback_(defaultConnectionCallback), - messageCallback_(defaultMessageCallback), - nextConnId_(1) -{ +TcpServer::TcpServer(EventLoop *loop, const InetAddress &listenAddr, + const string &nameArg, Option option) + : loop_(CHECK_NOTNULL(loop)), ipPort_(listenAddr.toIpPort()), + name_(nameArg), + acceptor_(new Acceptor(loop, listenAddr, option == kReusePort)), + threadPool_(new EventLoopThreadPool(loop, name_)), + connectionCallback_(defaultConnectionCallback), + messageCallback_(defaultMessageCallback), nextConnId_(1) { acceptor_->setNewConnectionCallback( std::bind(&TcpServer::newConnection, this, _1, _2)); } -TcpServer::~TcpServer() -{ +TcpServer::~TcpServer() { loop_->assertInLoopThread(); LOG_TRACE << "TcpServer::~TcpServer [" << name_ << "] destructing"; - for (auto& item : connections_) - { + for (auto &item : connections_) { TcpConnectionPtr conn(item.second); item.second.reset(); conn->getLoop()->runInLoop( - std::bind(&TcpConnection::connectDestroyed, conn)); + std::bind(&TcpConnection::connectDestroyed, conn)); } } -void TcpServer::setThreadNum(int numThreads) -{ +void TcpServer::setThreadNum(int numThreads) { assert(0 <= numThreads); threadPool_->setThreadNum(numThreads); } -void TcpServer::start() -{ - if (started_.getAndSet(1) == 0) - { +void TcpServer::start() { + if (started_.getAndSet(1) == 0) { threadPool_->start(threadInitCallback_); assert(!acceptor_->listening()); - loop_->runInLoop( - std::bind(&Acceptor::listen, get_pointer(acceptor_))); + loop_->runInLoop(std::bind(&Acceptor::listen, get_pointer(acceptor_))); } } -void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr) -{ +void TcpServer::newConnection(int sockfd, const InetAddress &peerAddr) { loop_->assertInLoopThread(); - EventLoop* ioLoop = threadPool_->getNextLoop(); + EventLoop *ioLoop = threadPool_->getNextLoop(); char buf[64]; snprintf(buf, sizeof buf, "-%s#%d", ipPort_.c_str(), nextConnId_); ++nextConnId_; string connName = name_ + buf; - LOG_INFO << "TcpServer::newConnection [" << name_ - << "] - new connection [" << connName - << "] from " << peerAddr.toIpPort(); + LOG_INFO << "TcpServer::newConnection [" << name_ << "] - new connection [" + << connName << "] from " << peerAddr.toIpPort(); InetAddress localAddr(sockets::getLocalAddr(sockfd)); // FIXME poll with zero timeout to double confirm the new connection // FIXME use make_shared if necessary - TcpConnectionPtr conn(new TcpConnection(ioLoop, - connName, - sockfd, - localAddr, - peerAddr)); + TcpConnectionPtr conn( + new TcpConnection(ioLoop, connName, sockfd, localAddr, peerAddr)); connections_[connName] = conn; conn->setConnectionCallback(connectionCallback_); conn->setMessageCallback(messageCallback_); @@ -97,22 +81,18 @@ void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr) ioLoop->runInLoop(std::bind(&TcpConnection::connectEstablished, conn)); } -void TcpServer::removeConnection(const TcpConnectionPtr& conn) -{ +void TcpServer::removeConnection(const TcpConnectionPtr &conn) { // FIXME: unsafe loop_->runInLoop(std::bind(&TcpServer::removeConnectionInLoop, this, conn)); } -void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn) -{ +void TcpServer::removeConnectionInLoop(const TcpConnectionPtr &conn) { loop_->assertInLoopThread(); LOG_INFO << "TcpServer::removeConnectionInLoop [" << name_ << "] - connection " << conn->name(); size_t n = connections_.erase(conn->name()); (void)n; assert(n == 1); - EventLoop* ioLoop = conn->getLoop(); - ioLoop->queueInLoop( - std::bind(&TcpConnection::connectDestroyed, conn)); + EventLoop *ioLoop = conn->getLoop(); + ioLoop->queueInLoop(std::bind(&TcpConnection::connectDestroyed, conn)); } - diff --git a/muduo/net/TcpServer.h b/muduo/net/TcpServer.h index 3fbfead5c..c36fdf847 100644 --- a/muduo/net/TcpServer.h +++ b/muduo/net/TcpServer.h @@ -17,10 +17,8 @@ #include -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Acceptor; class EventLoop; @@ -30,26 +28,22 @@ class EventLoopThreadPool; /// TCP server, supports single-threaded and thread-pool models. /// /// This is an interface class, so don't expose too much details. -class TcpServer : noncopyable -{ - public: - typedef std::function ThreadInitCallback; - enum Option - { +class TcpServer : noncopyable { +public: + typedef std::function ThreadInitCallback; + enum Option { kNoReusePort, kReusePort, }; - //TcpServer(EventLoop* loop, const InetAddress& listenAddr); - TcpServer(EventLoop* loop, - const InetAddress& listenAddr, - const string& nameArg, - Option option = kNoReusePort); - ~TcpServer(); // force out-line dtor, for std::unique_ptr members. + // TcpServer(EventLoop* loop, const InetAddress& listenAddr); + TcpServer(EventLoop *loop, const InetAddress &listenAddr, + const string &nameArg, Option option = kNoReusePort); + ~TcpServer(); // force out-line dtor, for std::unique_ptr members. - const string& ipPort() const { return ipPort_; } - const string& name() const { return name_; } - EventLoop* getLoop() const { return loop_; } + const string &ipPort() const { return ipPort_; } + const string &name() const { return name_; } + EventLoop *getLoop() const { return loop_; } /// Set the number of threads for handling input. /// @@ -62,11 +56,11 @@ class TcpServer : noncopyable /// - N means a thread pool with N threads, new connections /// are assigned on a round-robin basis. void setThreadNum(int numThreads); - void setThreadInitCallback(const ThreadInitCallback& cb) - { threadInitCallback_ = cb; } + void setThreadInitCallback(const ThreadInitCallback &cb) { + threadInitCallback_ = cb; + } /// valid after calling start() - std::shared_ptr threadPool() - { return threadPool_; } + std::shared_ptr threadPool() { return threadPool_; } /// Starts the server if it's not listening. /// @@ -76,30 +70,31 @@ class TcpServer : noncopyable /// Set connection callback. /// Not thread safe. - void setConnectionCallback(const ConnectionCallback& cb) - { connectionCallback_ = cb; } + void setConnectionCallback(const ConnectionCallback &cb) { + connectionCallback_ = cb; + } /// Set message callback. /// Not thread safe. - void setMessageCallback(const MessageCallback& cb) - { messageCallback_ = cb; } + void setMessageCallback(const MessageCallback &cb) { messageCallback_ = cb; } /// Set write complete callback. /// Not thread safe. - void setWriteCompleteCallback(const WriteCompleteCallback& cb) - { writeCompleteCallback_ = cb; } + void setWriteCompleteCallback(const WriteCompleteCallback &cb) { + writeCompleteCallback_ = cb; + } - private: +private: /// Not thread safe, but in loop - void newConnection(int sockfd, const InetAddress& peerAddr); + void newConnection(int sockfd, const InetAddress &peerAddr); /// Thread safe. - void removeConnection(const TcpConnectionPtr& conn); + void removeConnection(const TcpConnectionPtr &conn); /// Not thread safe, but in loop - void removeConnectionInLoop(const TcpConnectionPtr& conn); + void removeConnectionInLoop(const TcpConnectionPtr &conn); typedef std::map ConnectionMap; - EventLoop* loop_; // the acceptor loop + EventLoop *loop_; // the acceptor loop const string ipPort_; const string name_; std::unique_ptr acceptor_; // avoid revealing Acceptor @@ -114,7 +109,7 @@ class TcpServer : noncopyable ConnectionMap connections_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_TCPSERVER_H +#endif // MUDUO_NET_TCPSERVER_H diff --git a/muduo/net/Timer.cc b/muduo/net/Timer.cc index a4d443373..0c7793823 100644 --- a/muduo/net/Timer.cc +++ b/muduo/net/Timer.cc @@ -13,14 +13,10 @@ using namespace muduo::net; AtomicInt64 Timer::s_numCreated_; -void Timer::restart(Timestamp now) -{ - if (repeat_) - { +void Timer::restart(Timestamp now) { + if (repeat_) { expiration_ = addTime(now, interval_); - } - else - { + } else { expiration_ = Timestamp::invalid(); } } diff --git a/muduo/net/Timer.h b/muduo/net/Timer.h index 904584e59..9b6df768b 100644 --- a/muduo/net/Timer.h +++ b/muduo/net/Timer.h @@ -15,31 +15,21 @@ #include "muduo/base/Timestamp.h" #include "muduo/net/Callbacks.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { /// /// Internal class for timer event. /// -class Timer : noncopyable -{ - public: +class Timer : noncopyable { +public: Timer(TimerCallback cb, Timestamp when, double interval) - : callback_(std::move(cb)), - expiration_(when), - interval_(interval), - repeat_(interval > 0.0), - sequence_(s_numCreated_.incrementAndGet()) - { } - - void run() const - { - callback_(); - } - - Timestamp expiration() const { return expiration_; } + : callback_(std::move(cb)), expiration_(when), interval_(interval), + repeat_(interval > 0.0), sequence_(s_numCreated_.incrementAndGet()) {} + + void run() const { callback_(); } + + Timestamp expiration() const { return expiration_; } bool repeat() const { return repeat_; } int64_t sequence() const { return sequence_; } @@ -47,7 +37,7 @@ class Timer : noncopyable static int64_t numCreated() { return s_numCreated_.get(); } - private: +private: const TimerCallback callback_; Timestamp expiration_; const double interval_; @@ -57,7 +47,7 @@ class Timer : noncopyable static AtomicInt64 s_numCreated_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_TIMER_H +#endif // MUDUO_NET_TIMER_H diff --git a/muduo/net/TimerId.h b/muduo/net/TimerId.h index fcc52646e..4777bb66a 100644 --- a/muduo/net/TimerId.h +++ b/muduo/net/TimerId.h @@ -13,41 +13,30 @@ #include "muduo/base/copyable.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Timer; /// /// An opaque identifier, for canceling Timer. /// -class TimerId : public muduo::copyable -{ - public: - TimerId() - : timer_(NULL), - sequence_(0) - { - } - - TimerId(Timer* timer, int64_t seq) - : timer_(timer), - sequence_(seq) - { - } +class TimerId : public muduo::copyable { +public: + TimerId() : timer_(NULL), sequence_(0) {} + + TimerId(Timer *timer, int64_t seq) : timer_(timer), sequence_(seq) {} // default copy-ctor, dtor and assignment are okay friend class TimerQueue; - private: - Timer* timer_; +private: + Timer *timer_; int64_t sequence_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_TIMERID_H +#endif // MUDUO_NET_TIMERID_H diff --git a/muduo/net/TimerQueue.cc b/muduo/net/TimerQueue.cc index 89119aeb0..d10abb1de 100644 --- a/muduo/net/TimerQueue.cc +++ b/muduo/net/TimerQueue.cc @@ -20,53 +20,44 @@ #include #include -namespace muduo -{ -namespace net -{ -namespace detail -{ - -int createTimerfd() -{ - int timerfd = ::timerfd_create(CLOCK_MONOTONIC, - TFD_NONBLOCK | TFD_CLOEXEC); - if (timerfd < 0) - { +namespace muduo { +namespace net { +namespace detail { + +int createTimerfd() { + int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); + if (timerfd < 0) { LOG_SYSFATAL << "Failed in timerfd_create"; } return timerfd; } -struct timespec howMuchTimeFromNow(Timestamp when) -{ - int64_t microseconds = when.microSecondsSinceEpoch() - - Timestamp::now().microSecondsSinceEpoch(); - if (microseconds < 100) - { +struct timespec howMuchTimeFromNow(Timestamp when) { + int64_t microseconds = + when.microSecondsSinceEpoch() - Timestamp::now().microSecondsSinceEpoch(); + if (microseconds < 100) { microseconds = 100; } struct timespec ts; - ts.tv_sec = static_cast( - microseconds / Timestamp::kMicroSecondsPerSecond); + ts.tv_sec = + static_cast(microseconds / Timestamp::kMicroSecondsPerSecond); ts.tv_nsec = static_cast( (microseconds % Timestamp::kMicroSecondsPerSecond) * 1000); return ts; } -void readTimerfd(int timerfd, Timestamp now) -{ +void readTimerfd(int timerfd, Timestamp now) { uint64_t howmany; ssize_t n = ::read(timerfd, &howmany, sizeof howmany); - LOG_TRACE << "TimerQueue::handleRead() " << howmany << " at " << now.toString(); - if (n != sizeof howmany) - { - LOG_ERROR << "TimerQueue::handleRead() reads " << n << " bytes instead of 8"; + LOG_TRACE << "TimerQueue::handleRead() " << howmany << " at " + << now.toString(); + if (n != sizeof howmany) { + LOG_ERROR << "TimerQueue::handleRead() reads " << n + << " bytes instead of 8"; } } -void resetTimerfd(int timerfd, Timestamp expiration) -{ +void resetTimerfd(int timerfd, Timestamp expiration) { // wake up loop by timerfd_settime() struct itimerspec newValue; struct itimerspec oldValue; @@ -74,94 +65,75 @@ void resetTimerfd(int timerfd, Timestamp expiration) memZero(&oldValue, sizeof oldValue); newValue.it_value = howMuchTimeFromNow(expiration); int ret = ::timerfd_settime(timerfd, 0, &newValue, &oldValue); - if (ret) - { + if (ret) { LOG_SYSERR << "timerfd_settime()"; } } -} // namespace detail -} // namespace net -} // namespace muduo +} // namespace detail +} // namespace net +} // namespace muduo using namespace muduo; using namespace muduo::net; using namespace muduo::net::detail; -TimerQueue::TimerQueue(EventLoop* loop) - : loop_(loop), - timerfd_(createTimerfd()), - timerfdChannel_(loop, timerfd_), - timers_(), - callingExpiredTimers_(false) -{ - timerfdChannel_.setReadCallback( - std::bind(&TimerQueue::handleRead, this)); +TimerQueue::TimerQueue(EventLoop *loop) + : loop_(loop), timerfd_(createTimerfd()), timerfdChannel_(loop, timerfd_), + timers_(), callingExpiredTimers_(false) { + timerfdChannel_.setReadCallback(std::bind(&TimerQueue::handleRead, this)); // we are always reading the timerfd, we disarm it with timerfd_settime. timerfdChannel_.enableReading(); } -TimerQueue::~TimerQueue() -{ +TimerQueue::~TimerQueue() { timerfdChannel_.disableAll(); timerfdChannel_.remove(); ::close(timerfd_); // do not remove channel, since we're in EventLoop::dtor(); - for (const Entry& timer : timers_) - { + for (const Entry &timer : timers_) { delete timer.second; } } -TimerId TimerQueue::addTimer(TimerCallback cb, - Timestamp when, - double interval) -{ - Timer* timer = new Timer(std::move(cb), when, interval); - loop_->runInLoop( - std::bind(&TimerQueue::addTimerInLoop, this, timer)); +TimerId TimerQueue::addTimer(TimerCallback cb, Timestamp when, + double interval) { + Timer *timer = new Timer(std::move(cb), when, interval); + loop_->runInLoop(std::bind(&TimerQueue::addTimerInLoop, this, timer)); return TimerId(timer, timer->sequence()); } -void TimerQueue::cancel(TimerId timerId) -{ - loop_->runInLoop( - std::bind(&TimerQueue::cancelInLoop, this, timerId)); +void TimerQueue::cancel(TimerId timerId) { + loop_->runInLoop(std::bind(&TimerQueue::cancelInLoop, this, timerId)); } -void TimerQueue::addTimerInLoop(Timer* timer) -{ +void TimerQueue::addTimerInLoop(Timer *timer) { loop_->assertInLoopThread(); bool earliestChanged = insert(timer); - if (earliestChanged) - { + if (earliestChanged) { resetTimerfd(timerfd_, timer->expiration()); } } -void TimerQueue::cancelInLoop(TimerId timerId) -{ +void TimerQueue::cancelInLoop(TimerId timerId) { loop_->assertInLoopThread(); assert(timers_.size() == activeTimers_.size()); ActiveTimer timer(timerId.timer_, timerId.sequence_); ActiveTimerSet::iterator it = activeTimers_.find(timer); - if (it != activeTimers_.end()) - { + if (it != activeTimers_.end()) { size_t n = timers_.erase(Entry(it->first->expiration(), it->first)); - assert(n == 1); (void)n; + assert(n == 1); + (void)n; delete it->first; // FIXME: no delete please activeTimers_.erase(it); - } - else if (callingExpiredTimers_) - { + } else if (callingExpiredTimers_) { cancelingTimers_.insert(timer); } assert(timers_.size() == activeTimers_.size()); } -void TimerQueue::handleRead() -{ +void TimerQueue::handleRead() { loop_->assertInLoopThread(); Timestamp now(Timestamp::now()); readTimerfd(timerfd_, now); @@ -171,8 +143,7 @@ void TimerQueue::handleRead() callingExpiredTimers_ = true; cancelingTimers_.clear(); // safe to callback outside critical section - for (const Entry& it : expired) - { + for (const Entry &it : expired) { it.second->run(); } callingExpiredTimers_ = false; @@ -180,81 +151,72 @@ void TimerQueue::handleRead() reset(expired, now); } -std::vector TimerQueue::getExpired(Timestamp now) -{ +std::vector TimerQueue::getExpired(Timestamp now) { assert(timers_.size() == activeTimers_.size()); std::vector expired; - Entry sentry(now, reinterpret_cast(UINTPTR_MAX)); + Entry sentry(now, reinterpret_cast(UINTPTR_MAX)); TimerList::iterator end = timers_.lower_bound(sentry); assert(end == timers_.end() || now < end->first); std::copy(timers_.begin(), end, back_inserter(expired)); timers_.erase(timers_.begin(), end); - for (const Entry& it : expired) - { + for (const Entry &it : expired) { ActiveTimer timer(it.second, it.second->sequence()); size_t n = activeTimers_.erase(timer); - assert(n == 1); (void)n; + assert(n == 1); + (void)n; } assert(timers_.size() == activeTimers_.size()); return expired; } -void TimerQueue::reset(const std::vector& expired, Timestamp now) -{ +void TimerQueue::reset(const std::vector &expired, Timestamp now) { Timestamp nextExpire; - for (const Entry& it : expired) - { + for (const Entry &it : expired) { ActiveTimer timer(it.second, it.second->sequence()); - if (it.second->repeat() - && cancelingTimers_.find(timer) == cancelingTimers_.end()) - { + if (it.second->repeat() && + cancelingTimers_.find(timer) == cancelingTimers_.end()) { it.second->restart(now); insert(it.second); - } - else - { + } else { // FIXME move to a free list delete it.second; // FIXME: no delete please } } - if (!timers_.empty()) - { + if (!timers_.empty()) { nextExpire = timers_.begin()->second->expiration(); } - if (nextExpire.valid()) - { + if (nextExpire.valid()) { resetTimerfd(timerfd_, nextExpire); } } -bool TimerQueue::insert(Timer* timer) -{ +bool TimerQueue::insert(Timer *timer) { loop_->assertInLoopThread(); assert(timers_.size() == activeTimers_.size()); bool earliestChanged = false; Timestamp when = timer->expiration(); TimerList::iterator it = timers_.begin(); - if (it == timers_.end() || when < it->first) - { + if (it == timers_.end() || when < it->first) { earliestChanged = true; } { - std::pair result - = timers_.insert(Entry(when, timer)); - assert(result.second); (void)result; + std::pair result = + timers_.insert(Entry(when, timer)); + assert(result.second); + (void)result; } { - std::pair result - = activeTimers_.insert(ActiveTimer(timer, timer->sequence())); - assert(result.second); (void)result; + std::pair result = + activeTimers_.insert(ActiveTimer(timer, timer->sequence())); + assert(result.second); + (void)result; } assert(timers_.size() == activeTimers_.size()); return earliestChanged; } - diff --git a/muduo/net/TimerQueue.h b/muduo/net/TimerQueue.h index 85da6b71a..dd4e9ebf0 100644 --- a/muduo/net/TimerQueue.h +++ b/muduo/net/TimerQueue.h @@ -19,10 +19,8 @@ #include "muduo/net/Callbacks.h" #include "muduo/net/Channel.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class EventLoop; class Timer; @@ -32,10 +30,9 @@ class TimerId; /// A best efforts timer queue. /// No guarantee that the callback will be on time. /// -class TimerQueue : noncopyable -{ - public: - explicit TimerQueue(EventLoop* loop); +class TimerQueue : noncopyable { +public: + explicit TimerQueue(EventLoop *loop); ~TimerQueue(); /// @@ -43,33 +40,30 @@ class TimerQueue : noncopyable /// repeats if @c interval > 0.0. /// /// Must be thread safe. Usually be called from other threads. - TimerId addTimer(TimerCallback cb, - Timestamp when, - double interval); + TimerId addTimer(TimerCallback cb, Timestamp when, double interval); void cancel(TimerId timerId); - private: - +private: // FIXME: use unique_ptr instead of raw pointers. // This requires heterogeneous comparison lookup (N3465) from C++14 // so that we can find an T* in a set>. - typedef std::pair Entry; + typedef std::pair Entry; typedef std::set TimerList; - typedef std::pair ActiveTimer; + typedef std::pair ActiveTimer; typedef std::set ActiveTimerSet; - void addTimerInLoop(Timer* timer); + void addTimerInLoop(Timer *timer); void cancelInLoop(TimerId timerId); // called when timerfd alarms void handleRead(); // move out all expired timers std::vector getExpired(Timestamp now); - void reset(const std::vector& expired, Timestamp now); + void reset(const std::vector &expired, Timestamp now); - bool insert(Timer* timer); + bool insert(Timer *timer); - EventLoop* loop_; + EventLoop *loop_; const int timerfd_; Channel timerfdChannel_; // Timer list sorted by expiration @@ -81,6 +75,6 @@ class TimerQueue : noncopyable ActiveTimerSet cancelingTimers_; }; -} // namespace net -} // namespace muduo -#endif // MUDUO_NET_TIMERQUEUE_H +} // namespace net +} // namespace muduo +#endif // MUDUO_NET_TIMERQUEUE_H diff --git a/muduo/net/ZlibStream.h b/muduo/net/ZlibStream.h index 0f143b0c9..43870212f 100644 --- a/muduo/net/ZlibStream.h +++ b/muduo/net/ZlibStream.h @@ -5,113 +5,90 @@ #pragma GCC diagnostic ignored "-Wold-style-cast" #include -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { // input is zlib compressed data, output uncompressed data // FIXME: finish this -class ZlibInputStream : noncopyable -{ - public: - explicit ZlibInputStream(Buffer* output) - : output_(output), - zerror_(Z_OK) - { +class ZlibInputStream : noncopyable { +public: + explicit ZlibInputStream(Buffer *output) : output_(output), zerror_(Z_OK) { memZero(&zstream_, sizeof zstream_); zerror_ = inflateInit(&zstream_); } - ~ZlibInputStream() - { - finish(); - } + ~ZlibInputStream() { finish(); } bool write(StringPiece buf); - bool write(Buffer* input); + bool write(Buffer *input); bool finish(); - // inflateEnd(&zstream_); + // inflateEnd(&zstream_); - private: +private: int decompress(int flush); - Buffer* output_; + Buffer *output_; z_stream zstream_; int zerror_; }; // input is uncompressed data, output zlib compressed data -class ZlibOutputStream : noncopyable -{ - public: - explicit ZlibOutputStream(Buffer* output) - : output_(output), - zerror_(Z_OK), - bufferSize_(1024) - { +class ZlibOutputStream : noncopyable { +public: + explicit ZlibOutputStream(Buffer *output) + : output_(output), zerror_(Z_OK), bufferSize_(1024) { memZero(&zstream_, sizeof zstream_); zerror_ = deflateInit(&zstream_, Z_DEFAULT_COMPRESSION); } - ~ZlibOutputStream() - { - finish(); - } + ~ZlibOutputStream() { finish(); } // Return last error message or NULL if no error. - const char* zlibErrorMessage() const { return zstream_.msg; } + const char *zlibErrorMessage() const { return zstream_.msg; } int zlibErrorCode() const { return zerror_; } int64_t inputBytes() const { return zstream_.total_in; } int64_t outputBytes() const { return zstream_.total_out; } int internalOutputBufferSize() const { return bufferSize_; } - bool write(StringPiece buf) - { + bool write(StringPiece buf) { if (zerror_ != Z_OK) return false; assert(zstream_.next_in == NULL && zstream_.avail_in == 0); - void* in = const_cast(buf.data()); - zstream_.next_in = static_cast(in); + void *in = const_cast(buf.data()); + zstream_.next_in = static_cast(in); zstream_.avail_in = buf.size(); - while (zstream_.avail_in > 0 && zerror_ == Z_OK) - { + while (zstream_.avail_in > 0 && zerror_ == Z_OK) { zerror_ = compress(Z_NO_FLUSH); } - if (zstream_.avail_in == 0) - { - assert(static_cast(zstream_.next_in) == buf.end()); + if (zstream_.avail_in == 0) { + assert(static_cast(zstream_.next_in) == buf.end()); zstream_.next_in = NULL; } return zerror_ == Z_OK; } // compress input as much as possible, not guarantee consuming all data. - bool write(Buffer* input) - { + bool write(Buffer *input) { if (zerror_ != Z_OK) return false; - void* in = const_cast(input->peek()); - zstream_.next_in = static_cast(in); + void *in = const_cast(input->peek()); + zstream_.next_in = static_cast(in); zstream_.avail_in = static_cast(input->readableBytes()); - if (zstream_.avail_in > 0 && zerror_ == Z_OK) - { + if (zstream_.avail_in > 0 && zerror_ == Z_OK) { zerror_ = compress(Z_NO_FLUSH); } input->retrieve(input->readableBytes() - zstream_.avail_in); return zerror_ == Z_OK; } - bool finish() - { + bool finish() { if (zerror_ != Z_OK) return false; - while (zerror_ == Z_OK) - { + while (zerror_ == Z_OK) { zerror_ = compress(Z_FINISH); } zerror_ = deflateEnd(&zstream_); @@ -120,26 +97,24 @@ class ZlibOutputStream : noncopyable return ok; } - private: - int compress(int flush) - { +private: + int compress(int flush) { output_->ensureWritableBytes(bufferSize_); - zstream_.next_out = reinterpret_cast(output_->beginWrite()); + zstream_.next_out = reinterpret_cast(output_->beginWrite()); zstream_.avail_out = static_cast(output_->writableBytes()); int error = ::deflate(&zstream_, flush); output_->hasWritten(output_->writableBytes() - zstream_.avail_out); - if (output_->writableBytes() == 0 && bufferSize_ < 65536) - { + if (output_->writableBytes() == 0 && bufferSize_ < 65536) { bufferSize_ *= 2; } return error; } - Buffer* output_; + Buffer *output_; z_stream zstream_; int zerror_; int bufferSize_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo diff --git a/muduo/net/boilerplate.cc b/muduo/net/boilerplate.cc index d0ebe2650..dffe53dc5 100644 --- a/muduo/net/boilerplate.cc +++ b/muduo/net/boilerplate.cc @@ -11,5 +11,3 @@ using namespace muduo; using namespace muduo::net; - - diff --git a/muduo/net/boilerplate.h b/muduo/net/boilerplate.h index 780661c4f..df1a34020 100644 --- a/muduo/net/boilerplate.h +++ b/muduo/net/boilerplate.h @@ -14,19 +14,15 @@ #include "muduo/base/noncopyable.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { -class BoilerPlate : noncopyable -{ - public: - - private: +class BoilerPlate : noncopyable { +public: +private: }; -} -} +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_BOILERPLATE_H +#endif // MUDUO_NET_BOILERPLATE_H diff --git a/muduo/net/http/HttpContext.cc b/muduo/net/http/HttpContext.cc index bef3a8091..100994b25 100644 --- a/muduo/net/http/HttpContext.cc +++ b/muduo/net/http/HttpContext.cc @@ -7,47 +7,35 @@ // Author: Shuo Chen (chenshuo at chenshuo dot com) // -#include "muduo/net/Buffer.h" #include "muduo/net/http/HttpContext.h" +#include "muduo/net/Buffer.h" using namespace muduo; using namespace muduo::net; -bool HttpContext::processRequestLine(const char* begin, const char* end) -{ +bool HttpContext::processRequestLine(const char *begin, const char *end) { bool succeed = false; - const char* start = begin; - const char* space = std::find(start, end, ' '); - if (space != end && request_.setMethod(start, space)) - { - start = space+1; + const char *start = begin; + const char *space = std::find(start, end, ' '); + if (space != end && request_.setMethod(start, space)) { + start = space + 1; space = std::find(start, end, ' '); - if (space != end) - { - const char* question = std::find(start, space, '?'); - if (question != space) - { + if (space != end) { + const char *question = std::find(start, space, '?'); + if (question != space) { request_.setPath(start, question); request_.setQuery(question, space); - } - else - { + } else { request_.setPath(start, space); } - start = space+1; - succeed = end-start == 8 && std::equal(start, end-1, "HTTP/1."); - if (succeed) - { - if (*(end-1) == '1') - { + start = space + 1; + succeed = end - start == 8 && std::equal(start, end - 1, "HTTP/1."); + if (succeed) { + if (*(end - 1) == '1') { request_.setVersion(HttpRequest::kHttp11); - } - else if (*(end-1) == '0') - { + } else if (*(end - 1) == '0') { request_.setVersion(HttpRequest::kHttp10); - } - else - { + } else { succeed = false; } } @@ -57,60 +45,41 @@ bool HttpContext::processRequestLine(const char* begin, const char* end) } // return false if any error -bool HttpContext::parseRequest(Buffer* buf, Timestamp receiveTime) -{ +bool HttpContext::parseRequest(Buffer *buf, Timestamp receiveTime) { bool ok = true; bool hasMore = true; - while (hasMore) - { - if (state_ == kExpectRequestLine) - { - const char* crlf = buf->findCRLF(); - if (crlf) - { + while (hasMore) { + if (state_ == kExpectRequestLine) { + const char *crlf = buf->findCRLF(); + if (crlf) { ok = processRequestLine(buf->peek(), crlf); - if (ok) - { + if (ok) { request_.setReceiveTime(receiveTime); buf->retrieveUntil(crlf + 2); state_ = kExpectHeaders; - } - else - { + } else { hasMore = false; } - } - else - { + } else { hasMore = false; } - } - else if (state_ == kExpectHeaders) - { - const char* crlf = buf->findCRLF(); - if (crlf) - { - const char* colon = std::find(buf->peek(), crlf, ':'); - if (colon != crlf) - { + } else if (state_ == kExpectHeaders) { + const char *crlf = buf->findCRLF(); + if (crlf) { + const char *colon = std::find(buf->peek(), crlf, ':'); + if (colon != crlf) { request_.addHeader(buf->peek(), colon, crlf); - } - else - { + } else { // empty line, end of header // FIXME: state_ = kGotAll; hasMore = false; } buf->retrieveUntil(crlf + 2); - } - else - { + } else { hasMore = false; } - } - else if (state_ == kExpectBody) - { + } else if (state_ == kExpectBody) { // FIXME: } } diff --git a/muduo/net/http/HttpContext.h b/muduo/net/http/HttpContext.h index 4beee5cd5..f678b3cdf 100644 --- a/muduo/net/http/HttpContext.h +++ b/muduo/net/http/HttpContext.h @@ -15,58 +15,47 @@ #include "muduo/net/http/HttpRequest.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Buffer; -class HttpContext : public muduo::copyable -{ - public: - enum HttpRequestParseState - { +class HttpContext : public muduo::copyable { +public: + enum HttpRequestParseState { kExpectRequestLine, kExpectHeaders, kExpectBody, kGotAll, }; - HttpContext() - : state_(kExpectRequestLine) - { - } + HttpContext() : state_(kExpectRequestLine) {} // default copy-ctor, dtor and assignment are fine // return false if any error - bool parseRequest(Buffer* buf, Timestamp receiveTime); + bool parseRequest(Buffer *buf, Timestamp receiveTime); - bool gotAll() const - { return state_ == kGotAll; } + bool gotAll() const { return state_ == kGotAll; } - void reset() - { + void reset() { state_ = kExpectRequestLine; HttpRequest dummy; request_.swap(dummy); } - const HttpRequest& request() const - { return request_; } + const HttpRequest &request() const { return request_; } - HttpRequest& request() - { return request_; } + HttpRequest &request() { return request_; } - private: - bool processRequestLine(const char* begin, const char* end); +private: + bool processRequestLine(const char *begin, const char *end); HttpRequestParseState state_; HttpRequest request_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_HTTP_HTTPCONTEXT_H +#endif // MUDUO_NET_HTTP_HTTPCONTEXT_H diff --git a/muduo/net/http/HttpRequest.h b/muduo/net/http/HttpRequest.h index 9c70c5dc0..e2b8de7e4 100644 --- a/muduo/net/http/HttpRequest.h +++ b/muduo/net/http/HttpRequest.h @@ -11,159 +11,112 @@ #ifndef MUDUO_NET_HTTP_HTTPREQUEST_H #define MUDUO_NET_HTTP_HTTPREQUEST_H -#include "muduo/base/copyable.h" #include "muduo/base/Timestamp.h" #include "muduo/base/Types.h" +#include "muduo/base/copyable.h" -#include #include +#include #include -namespace muduo -{ -namespace net -{ - -class HttpRequest : public muduo::copyable -{ - public: - enum Method - { - kInvalid, kGet, kPost, kHead, kPut, kDelete - }; - enum Version - { - kUnknown, kHttp10, kHttp11 - }; - - HttpRequest() - : method_(kInvalid), - version_(kUnknown) - { - } +namespace muduo { +namespace net { - void setVersion(Version v) - { - version_ = v; - } +class HttpRequest : public muduo::copyable { +public: + enum Method { kInvalid, kGet, kPost, kHead, kPut, kDelete }; + enum Version { kUnknown, kHttp10, kHttp11 }; + + HttpRequest() : method_(kInvalid), version_(kUnknown) {} - Version getVersion() const - { return version_; } + void setVersion(Version v) { version_ = v; } - bool setMethod(const char* start, const char* end) - { + Version getVersion() const { return version_; } + + bool setMethod(const char *start, const char *end) { assert(method_ == kInvalid); string m(start, end); - if (m == "GET") - { + if (m == "GET") { method_ = kGet; - } - else if (m == "POST") - { + } else if (m == "POST") { method_ = kPost; - } - else if (m == "HEAD") - { + } else if (m == "HEAD") { method_ = kHead; - } - else if (m == "PUT") - { + } else if (m == "PUT") { method_ = kPut; - } - else if (m == "DELETE") - { + } else if (m == "DELETE") { method_ = kDelete; - } - else - { + } else { method_ = kInvalid; } return method_ != kInvalid; } - Method method() const - { return method_; } - - const char* methodString() const - { - const char* result = "UNKNOWN"; - switch(method_) - { - case kGet: - result = "GET"; - break; - case kPost: - result = "POST"; - break; - case kHead: - result = "HEAD"; - break; - case kPut: - result = "PUT"; - break; - case kDelete: - result = "DELETE"; - break; - default: - break; + Method method() const { return method_; } + + const char *methodString() const { + const char *result = "UNKNOWN"; + switch (method_) { + case kGet: + result = "GET"; + break; + case kPost: + result = "POST"; + break; + case kHead: + result = "HEAD"; + break; + case kPut: + result = "PUT"; + break; + case kDelete: + result = "DELETE"; + break; + default: + break; } return result; } - void setPath(const char* start, const char* end) - { - path_.assign(start, end); - } + void setPath(const char *start, const char *end) { path_.assign(start, end); } - const string& path() const - { return path_; } + const string &path() const { return path_; } - void setQuery(const char* start, const char* end) - { + void setQuery(const char *start, const char *end) { query_.assign(start, end); } - const string& query() const - { return query_; } + const string &query() const { return query_; } - void setReceiveTime(Timestamp t) - { receiveTime_ = t; } + void setReceiveTime(Timestamp t) { receiveTime_ = t; } - Timestamp receiveTime() const - { return receiveTime_; } + Timestamp receiveTime() const { return receiveTime_; } - void addHeader(const char* start, const char* colon, const char* end) - { + void addHeader(const char *start, const char *colon, const char *end) { string field(start, colon); ++colon; - while (colon < end && isspace(*colon)) - { + while (colon < end && isspace(*colon)) { ++colon; } string value(colon, end); - while (!value.empty() && isspace(value[value.size()-1])) - { - value.resize(value.size()-1); + while (!value.empty() && isspace(value[value.size() - 1])) { + value.resize(value.size() - 1); } headers_[field] = value; } - string getHeader(const string& field) const - { + string getHeader(const string &field) const { string result; std::map::const_iterator it = headers_.find(field); - if (it != headers_.end()) - { + if (it != headers_.end()) { result = it->second; } return result; } - const std::map& headers() const - { return headers_; } + const std::map &headers() const { return headers_; } - void swap(HttpRequest& that) - { + void swap(HttpRequest &that) { std::swap(method_, that.method_); std::swap(version_, that.version_); path_.swap(that.path_); @@ -172,7 +125,7 @@ class HttpRequest : public muduo::copyable headers_.swap(that.headers_); } - private: +private: Method method_; Version version_; string path_; @@ -181,7 +134,7 @@ class HttpRequest : public muduo::copyable std::map headers_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_HTTP_HTTPREQUEST_H +#endif // MUDUO_NET_HTTP_HTTPREQUEST_H diff --git a/muduo/net/http/HttpResponse.cc b/muduo/net/http/HttpResponse.cc index 0e2e74dfa..2609b2753 100644 --- a/muduo/net/http/HttpResponse.cc +++ b/muduo/net/http/HttpResponse.cc @@ -15,27 +15,22 @@ using namespace muduo; using namespace muduo::net; -void HttpResponse::appendToBuffer(Buffer* output) const -{ +void HttpResponse::appendToBuffer(Buffer *output) const { char buf[32]; snprintf(buf, sizeof buf, "HTTP/1.1 %d ", statusCode_); output->append(buf); output->append(statusMessage_); output->append("\r\n"); - if (closeConnection_) - { + if (closeConnection_) { output->append("Connection: close\r\n"); - } - else - { + } else { snprintf(buf, sizeof buf, "Content-Length: %zd\r\n", body_.size()); output->append(buf); output->append("Connection: Keep-Alive\r\n"); } - for (const auto& header : headers_) - { + for (const auto &header : headers_) { output->append(header.first); output->append(": "); output->append(header.second); diff --git a/muduo/net/http/HttpResponse.h b/muduo/net/http/HttpResponse.h index eb3910fa3..f53b9ebf4 100644 --- a/muduo/net/http/HttpResponse.h +++ b/muduo/net/http/HttpResponse.h @@ -11,22 +11,18 @@ #ifndef MUDUO_NET_HTTP_HTTPRESPONSE_H #define MUDUO_NET_HTTP_HTTPRESPONSE_H -#include "muduo/base/copyable.h" #include "muduo/base/Types.h" +#include "muduo/base/copyable.h" #include -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Buffer; -class HttpResponse : public muduo::copyable -{ - public: - enum HttpStatusCode - { +class HttpResponse : public muduo::copyable { +public: + enum HttpStatusCode { kUnknown, k200Ok = 200, k301MovedPermanently = 301, @@ -35,36 +31,30 @@ class HttpResponse : public muduo::copyable }; explicit HttpResponse(bool close) - : statusCode_(kUnknown), - closeConnection_(close) - { - } + : statusCode_(kUnknown), closeConnection_(close) {} - void setStatusCode(HttpStatusCode code) - { statusCode_ = code; } + void setStatusCode(HttpStatusCode code) { statusCode_ = code; } - void setStatusMessage(const string& message) - { statusMessage_ = message; } + void setStatusMessage(const string &message) { statusMessage_ = message; } - void setCloseConnection(bool on) - { closeConnection_ = on; } + void setCloseConnection(bool on) { closeConnection_ = on; } - bool closeConnection() const - { return closeConnection_; } + bool closeConnection() const { return closeConnection_; } - void setContentType(const string& contentType) - { addHeader("Content-Type", contentType); } + void setContentType(const string &contentType) { + addHeader("Content-Type", contentType); + } // FIXME: replace string with StringPiece - void addHeader(const string& key, const string& value) - { headers_[key] = value; } + void addHeader(const string &key, const string &value) { + headers_[key] = value; + } - void setBody(const string& body) - { body_ = body; } + void setBody(const string &body) { body_ = body; } - void appendToBuffer(Buffer* output) const; + void appendToBuffer(Buffer *output) const; - private: +private: std::map headers_; HttpStatusCode statusCode_; // FIXME: add http version @@ -73,7 +63,7 @@ class HttpResponse : public muduo::copyable string body_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_HTTP_HTTPRESPONSE_H +#endif // MUDUO_NET_HTTP_HTTPRESPONSE_H diff --git a/muduo/net/http/HttpServer.cc b/muduo/net/http/HttpServer.cc index f7d46782c..8b1cd209f 100644 --- a/muduo/net/http/HttpServer.cc +++ b/muduo/net/http/HttpServer.cc @@ -17,84 +17,69 @@ using namespace muduo; using namespace muduo::net; -namespace muduo -{ -namespace net -{ -namespace detail -{ +namespace muduo { +namespace net { +namespace detail { -void defaultHttpCallback(const HttpRequest&, HttpResponse* resp) -{ +void defaultHttpCallback(const HttpRequest &, HttpResponse *resp) { resp->setStatusCode(HttpResponse::k404NotFound); resp->setStatusMessage("Not Found"); resp->setCloseConnection(true); } -} // namespace detail -} // namespace net -} // namespace muduo +} // namespace detail +} // namespace net +} // namespace muduo -HttpServer::HttpServer(EventLoop* loop, - const InetAddress& listenAddr, - const string& name, - TcpServer::Option option) - : server_(loop, listenAddr, name, option), - httpCallback_(detail::defaultHttpCallback) -{ - server_.setConnectionCallback( - std::bind(&HttpServer::onConnection, this, _1)); +HttpServer::HttpServer(EventLoop *loop, const InetAddress &listenAddr, + const string &name, TcpServer::Option option) + : server_(loop, listenAddr, name, option), + httpCallback_(detail::defaultHttpCallback) { + server_.setConnectionCallback(std::bind(&HttpServer::onConnection, this, _1)); server_.setMessageCallback( std::bind(&HttpServer::onMessage, this, _1, _2, _3)); } -void HttpServer::start() -{ - LOG_WARN << "HttpServer[" << server_.name() - << "] starts listening on " << server_.ipPort(); +void HttpServer::start() { + LOG_WARN << "HttpServer[" << server_.name() << "] starts listening on " + << server_.ipPort(); server_.start(); } -void HttpServer::onConnection(const TcpConnectionPtr& conn) -{ - if (conn->connected()) - { +void HttpServer::onConnection(const TcpConnectionPtr &conn) { + if (conn->connected()) { conn->setContext(HttpContext()); } } -void HttpServer::onMessage(const TcpConnectionPtr& conn, - Buffer* buf, - Timestamp receiveTime) -{ - HttpContext* context = boost::any_cast(conn->getMutableContext()); +void HttpServer::onMessage(const TcpConnectionPtr &conn, Buffer *buf, + Timestamp receiveTime) { + HttpContext *context = + boost::any_cast(conn->getMutableContext()); - if (!context->parseRequest(buf, receiveTime)) - { + if (!context->parseRequest(buf, receiveTime)) { conn->send("HTTP/1.1 400 Bad Request\r\n\r\n"); conn->shutdown(); } - if (context->gotAll()) - { + if (context->gotAll()) { onRequest(conn, context->request()); context->reset(); } } -void HttpServer::onRequest(const TcpConnectionPtr& conn, const HttpRequest& req) -{ - const string& connection = req.getHeader("Connection"); - bool close = connection == "close" || - (req.getVersion() == HttpRequest::kHttp10 && connection != "Keep-Alive"); +void HttpServer::onRequest(const TcpConnectionPtr &conn, + const HttpRequest &req) { + const string &connection = req.getHeader("Connection"); + bool close = + connection == "close" || + (req.getVersion() == HttpRequest::kHttp10 && connection != "Keep-Alive"); HttpResponse response(close); httpCallback_(req, &response); Buffer buf; response.appendToBuffer(&buf); conn->send(&buf); - if (response.closeConnection()) - { + if (response.closeConnection()) { conn->shutdown(); } } - diff --git a/muduo/net/http/HttpServer.h b/muduo/net/http/HttpServer.h index 9609a119e..a51554e3d 100644 --- a/muduo/net/http/HttpServer.h +++ b/muduo/net/http/HttpServer.h @@ -13,56 +13,43 @@ #include "muduo/net/TcpServer.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class HttpRequest; class HttpResponse; /// A simple embeddable HTTP server designed for report status of a program. -/// It is not a fully HTTP 1.1 compliant server, but provides minimum features -/// that can communicate with HttpClient and Web browser. -/// It is synchronous, just like Java Servlet. -class HttpServer : noncopyable -{ - public: - typedef std::function HttpCallback; - - HttpServer(EventLoop* loop, - const InetAddress& listenAddr, - const string& name, +/// It is not a fully HTTP 1.1 compliant server, but provides minimum +/// features that can communicate with HttpClient and Web browser. It is +/// synchronous, just like Java Servlet. +class HttpServer : noncopyable { +public: + typedef std::function HttpCallback; + + HttpServer(EventLoop *loop, const InetAddress &listenAddr, const string &name, TcpServer::Option option = TcpServer::kNoReusePort); - EventLoop* getLoop() const { return server_.getLoop(); } + EventLoop *getLoop() const { return server_.getLoop(); } /// Not thread safe, callback be registered before calling start(). - void setHttpCallback(const HttpCallback& cb) - { - httpCallback_ = cb; - } + void setHttpCallback(const HttpCallback &cb) { httpCallback_ = cb; } - void setThreadNum(int numThreads) - { - server_.setThreadNum(numThreads); - } + void setThreadNum(int numThreads) { server_.setThreadNum(numThreads); } void start(); - private: - void onConnection(const TcpConnectionPtr& conn); - void onMessage(const TcpConnectionPtr& conn, - Buffer* buf, +private: + void onConnection(const TcpConnectionPtr &conn); + void onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp receiveTime); - void onRequest(const TcpConnectionPtr&, const HttpRequest&); + void onRequest(const TcpConnectionPtr &, const HttpRequest &); TcpServer server_; HttpCallback httpCallback_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_HTTP_HTTPSERVER_H +#endif // MUDUO_NET_HTTP_HTTPSERVER_H diff --git a/muduo/net/http/tests/HttpRequest_unittest.cc b/muduo/net/http/tests/HttpRequest_unittest.cc index cb8930535..b9754fb65 100644 --- a/muduo/net/http/tests/HttpRequest_unittest.cc +++ b/muduo/net/http/tests/HttpRequest_unittest.cc @@ -1,5 +1,5 @@ -#include "muduo/net/http/HttpContext.h" #include "muduo/net/Buffer.h" +#include "muduo/net/http/HttpContext.h" //#define BOOST_TEST_MODULE BufferTest #define BOOST_TEST_MAIN @@ -12,17 +12,16 @@ using muduo::net::Buffer; using muduo::net::HttpContext; using muduo::net::HttpRequest; -BOOST_AUTO_TEST_CASE(testParseRequestAllInOne) -{ +BOOST_AUTO_TEST_CASE(testParseRequestAllInOne) { HttpContext context; Buffer input; input.append("GET /index.html HTTP/1.1\r\n" - "Host: www.chenshuo.com\r\n" - "\r\n"); + "Host: www.chenshuo.com\r\n" + "\r\n"); BOOST_CHECK(context.parseRequest(&input, Timestamp::now())); BOOST_CHECK(context.gotAll()); - const HttpRequest& request = context.request(); + const HttpRequest &request = context.request(); BOOST_CHECK_EQUAL(request.method(), HttpRequest::kGet); BOOST_CHECK_EQUAL(request.path(), string("/index.html")); BOOST_CHECK_EQUAL(request.getVersion(), HttpRequest::kHttp11); @@ -30,14 +29,12 @@ BOOST_AUTO_TEST_CASE(testParseRequestAllInOne) BOOST_CHECK_EQUAL(request.getHeader("User-Agent"), string("")); } -BOOST_AUTO_TEST_CASE(testParseRequestInTwoPieces) -{ +BOOST_AUTO_TEST_CASE(testParseRequestInTwoPieces) { string all("GET /index.html HTTP/1.1\r\n" - "Host: www.chenshuo.com\r\n" - "\r\n"); + "Host: www.chenshuo.com\r\n" + "\r\n"); - for (size_t sz1 = 0; sz1 < all.size(); ++sz1) - { + for (size_t sz1 = 0; sz1 < all.size(); ++sz1) { HttpContext context; Buffer input; input.append(all.c_str(), sz1); @@ -48,7 +45,7 @@ BOOST_AUTO_TEST_CASE(testParseRequestInTwoPieces) input.append(all.c_str() + sz1, sz2); BOOST_CHECK(context.parseRequest(&input, Timestamp::now())); BOOST_CHECK(context.gotAll()); - const HttpRequest& request = context.request(); + const HttpRequest &request = context.request(); BOOST_CHECK_EQUAL(request.method(), HttpRequest::kGet); BOOST_CHECK_EQUAL(request.path(), string("/index.html")); BOOST_CHECK_EQUAL(request.getVersion(), HttpRequest::kHttp11); @@ -57,19 +54,18 @@ BOOST_AUTO_TEST_CASE(testParseRequestInTwoPieces) } } -BOOST_AUTO_TEST_CASE(testParseRequestEmptyHeaderValue) -{ +BOOST_AUTO_TEST_CASE(testParseRequestEmptyHeaderValue) { HttpContext context; Buffer input; input.append("GET /index.html HTTP/1.1\r\n" - "Host: www.chenshuo.com\r\n" - "User-Agent:\r\n" - "Accept-Encoding: \r\n" - "\r\n"); + "Host: www.chenshuo.com\r\n" + "User-Agent:\r\n" + "Accept-Encoding: \r\n" + "\r\n"); BOOST_CHECK(context.parseRequest(&input, Timestamp::now())); BOOST_CHECK(context.gotAll()); - const HttpRequest& request = context.request(); + const HttpRequest &request = context.request(); BOOST_CHECK_EQUAL(request.method(), HttpRequest::kGet); BOOST_CHECK_EQUAL(request.path(), string("/index.html")); BOOST_CHECK_EQUAL(request.getVersion(), HttpRequest::kHttp11); diff --git a/muduo/net/http/tests/HttpServer_test.cc b/muduo/net/http/tests/HttpServer_test.cc index 0ec38fb10..c9296b843 100644 --- a/muduo/net/http/tests/HttpServer_test.cc +++ b/muduo/net/http/tests/HttpServer_test.cc @@ -1,8 +1,8 @@ -#include "muduo/net/http/HttpServer.h" +#include "muduo/base/Logging.h" +#include "muduo/net/EventLoop.h" #include "muduo/net/http/HttpRequest.h" #include "muduo/net/http/HttpResponse.h" -#include "muduo/net/EventLoop.h" -#include "muduo/base/Logging.h" +#include "muduo/net/http/HttpServer.h" #include #include @@ -13,57 +13,46 @@ using namespace muduo::net; extern char favicon[555]; bool benchmark = false; -void onRequest(const HttpRequest& req, HttpResponse* resp) -{ - std::cout << "Headers " << req.methodString() << " " << req.path() << std::endl; - if (!benchmark) - { - const std::map& headers = req.headers(); - for (const auto& header : headers) - { +void onRequest(const HttpRequest &req, HttpResponse *resp) { + std::cout << "Headers " << req.methodString() << " " << req.path() + << std::endl; + if (!benchmark) { + const std::map &headers = req.headers(); + for (const auto &header : headers) { std::cout << header.first << ": " << header.second << std::endl; } } - if (req.path() == "/") - { + if (req.path() == "/") { resp->setStatusCode(HttpResponse::k200Ok); resp->setStatusMessage("OK"); resp->setContentType("text/html"); resp->addHeader("Server", "Muduo"); string now = Timestamp::now().toFormattedString(); resp->setBody("This is title" - "

Hello

Now is " + now + - ""); - } - else if (req.path() == "/favicon.ico") - { + "

Hello

Now is " + + now + ""); + } else if (req.path() == "/favicon.ico") { resp->setStatusCode(HttpResponse::k200Ok); resp->setStatusMessage("OK"); resp->setContentType("image/png"); resp->setBody(string(favicon, sizeof favicon)); - } - else if (req.path() == "/hello") - { + } else if (req.path() == "/hello") { resp->setStatusCode(HttpResponse::k200Ok); resp->setStatusMessage("OK"); resp->setContentType("text/plain"); resp->addHeader("Server", "Muduo"); resp->setBody("hello, world!\n"); - } - else - { + } else { resp->setStatusCode(HttpResponse::k404NotFound); resp->setStatusMessage("Not Found"); resp->setCloseConnection(true); } } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { int numThreads = 0; - if (argc > 1) - { + if (argc > 1) { benchmark = true; Logger::setLogLevel(Logger::WARN); numThreads = atoi(argv[1]); @@ -77,74 +66,66 @@ int main(int argc, char* argv[]) } char favicon[555] = { - '\x89', 'P', 'N', 'G', '\xD', '\xA', '\x1A', '\xA', - '\x0', '\x0', '\x0', '\xD', 'I', 'H', 'D', 'R', - '\x0', '\x0', '\x0', '\x10', '\x0', '\x0', '\x0', '\x10', - '\x8', '\x6', '\x0', '\x0', '\x0', '\x1F', '\xF3', '\xFF', - 'a', '\x0', '\x0', '\x0', '\x19', 't', 'E', 'X', - 't', 'S', 'o', 'f', 't', 'w', 'a', 'r', - 'e', '\x0', 'A', 'd', 'o', 'b', 'e', '\x20', - 'I', 'm', 'a', 'g', 'e', 'R', 'e', 'a', - 'd', 'y', 'q', '\xC9', 'e', '\x3C', '\x0', '\x0', - '\x1', '\xCD', 'I', 'D', 'A', 'T', 'x', '\xDA', - '\x94', '\x93', '9', 'H', '\x3', 'A', '\x14', '\x86', - '\xFF', '\x5D', 'b', '\xA7', '\x4', 'R', '\xC4', 'm', - '\x22', '\x1E', '\xA0', 'F', '\x24', '\x8', '\x16', '\x16', - 'v', '\xA', '6', '\xBA', 'J', '\x9A', '\x80', '\x8', - 'A', '\xB4', 'q', '\x85', 'X', '\x89', 'G', '\xB0', - 'I', '\xA9', 'Q', '\x24', '\xCD', '\xA6', '\x8', '\xA4', - 'H', 'c', '\x91', 'B', '\xB', '\xAF', 'V', '\xC1', - 'F', '\xB4', '\x15', '\xCF', '\x22', 'X', '\x98', '\xB', - 'T', 'H', '\x8A', 'd', '\x93', '\x8D', '\xFB', 'F', - 'g', '\xC9', '\x1A', '\x14', '\x7D', '\xF0', 'f', 'v', - 'f', '\xDF', '\x7C', '\xEF', '\xE7', 'g', 'F', '\xA8', - '\xD5', 'j', 'H', '\x24', '\x12', '\x2A', '\x0', '\x5', - '\xBF', 'G', '\xD4', '\xEF', '\xF7', '\x2F', '6', '\xEC', - '\x12', '\x20', '\x1E', '\x8F', '\xD7', '\xAA', '\xD5', '\xEA', - '\xAF', 'I', '5', 'F', '\xAA', 'T', '\x5F', '\x9F', - '\x22', 'A', '\x2A', '\x95', '\xA', '\x83', '\xE5', 'r', - '9', 'd', '\xB3', 'Y', '\x96', '\x99', 'L', '\x6', - '\xE9', 't', '\x9A', '\x25', '\x85', '\x2C', '\xCB', 'T', - '\xA7', '\xC4', 'b', '1', '\xB5', '\x5E', '\x0', '\x3', - 'h', '\x9A', '\xC6', '\x16', '\x82', '\x20', 'X', 'R', - '\x14', 'E', '6', 'S', '\x94', '\xCB', 'e', 'x', - '\xBD', '\x5E', '\xAA', 'U', 'T', '\x23', 'L', '\xC0', - '\xE0', '\xE2', '\xC1', '\x8F', '\x0', '\x9E', '\xBC', '\x9', - 'A', '\x7C', '\x3E', '\x1F', '\x83', 'D', '\x22', '\x11', - '\xD5', 'T', '\x40', '\x3F', '8', '\x80', 'w', '\xE5', - '3', '\x7', '\xB8', '\x5C', '\x2E', 'H', '\x92', '\x4', - '\x87', '\xC3', '\x81', '\x40', '\x20', '\x40', 'g', '\x98', - '\xE9', '6', '\x1A', '\xA6', 'g', '\x15', '\x4', '\xE3', - '\xD7', '\xC8', '\xBD', '\x15', '\xE1', 'i', '\xB7', 'C', - '\xAB', '\xEA', 'x', '\x2F', 'j', 'X', '\x92', '\xBB', - '\x18', '\x20', '\x9F', '\xCF', '3', '\xC3', '\xB8', '\xE9', - 'N', '\xA7', '\xD3', 'l', 'J', '\x0', 'i', '6', - '\x7C', '\x8E', '\xE1', '\xFE', 'V', '\x84', '\xE7', '\x3C', - '\x9F', 'r', '\x2B', '\x3A', 'B', '\x7B', '7', 'f', - 'w', '\xAE', '\x8E', '\xE', '\xF3', '\xBD', 'R', '\xA9', - 'd', '\x2', 'B', '\xAF', '\x85', '2', 'f', 'F', - '\xBA', '\xC', '\xD9', '\x9F', '\x1D', '\x9A', 'l', '\x22', - '\xE6', '\xC7', '\x3A', '\x2C', '\x80', '\xEF', '\xC1', '\x15', - '\x90', '\x7', '\x93', '\xA2', '\x28', '\xA0', 'S', 'j', - '\xB1', '\xB8', '\xDF', '\x29', '5', 'C', '\xE', '\x3F', - 'X', '\xFC', '\x98', '\xDA', 'y', 'j', 'P', '\x40', - '\x0', '\x87', '\xAE', '\x1B', '\x17', 'B', '\xB4', '\x3A', - '\x3F', '\xBE', 'y', '\xC7', '\xA', '\x26', '\xB6', '\xEE', - '\xD9', '\x9A', '\x60', '\x14', '\x93', '\xDB', '\x8F', '\xD', - '\xA', '\x2E', '\xE9', '\x23', '\x95', '\x29', 'X', '\x0', - '\x27', '\xEB', 'n', 'V', 'p', '\xBC', '\xD6', '\xCB', - '\xD6', 'G', '\xAB', '\x3D', 'l', '\x7D', '\xB8', '\xD2', - '\xDD', '\xA0', '\x60', '\x83', '\xBA', '\xEF', '\x5F', '\xA4', - '\xEA', '\xCC', '\x2', 'N', '\xAE', '\x5E', 'p', '\x1A', - '\xEC', '\xB3', '\x40', '9', '\xAC', '\xFE', '\xF2', '\x91', - '\x89', 'g', '\x91', '\x85', '\x21', '\xA8', '\x87', '\xB7', - 'X', '\x7E', '\x7E', '\x85', '\xBB', '\xCD', 'N', 'N', - 'b', 't', '\x40', '\xFA', '\x93', '\x89', '\xEC', '\x1E', - '\xEC', '\x86', '\x2', 'H', '\x26', '\x93', '\xD0', 'u', - '\x1D', '\x7F', '\x9', '2', '\x95', '\xBF', '\x1F', '\xDB', - '\xD7', 'c', '\x8A', '\x1A', '\xF7', '\x5C', '\xC1', '\xFF', - '\x22', 'J', '\xC3', '\x87', '\x0', '\x3', '\x0', 'K', - '\xBB', '\xF8', '\xD6', '\x2A', 'v', '\x98', 'I', '\x0', - '\x0', '\x0', '\x0', 'I', 'E', 'N', 'D', '\xAE', - 'B', '\x60', '\x82', + '\x89', 'P', 'N', 'G', '\xD', '\xA', '\x1A', '\xA', '\x0', + '\x0', '\x0', '\xD', 'I', 'H', 'D', 'R', '\x0', '\x0', + '\x0', '\x10', '\x0', '\x0', '\x0', '\x10', '\x8', '\x6', '\x0', + '\x0', '\x0', '\x1F', '\xF3', '\xFF', 'a', '\x0', '\x0', '\x0', + '\x19', 't', 'E', 'X', 't', 'S', 'o', 'f', 't', + 'w', 'a', 'r', 'e', '\x0', 'A', 'd', 'o', 'b', + 'e', '\x20', 'I', 'm', 'a', 'g', 'e', 'R', 'e', + 'a', 'd', 'y', 'q', '\xC9', 'e', '\x3C', '\x0', '\x0', + '\x1', '\xCD', 'I', 'D', 'A', 'T', 'x', '\xDA', '\x94', + '\x93', '9', 'H', '\x3', 'A', '\x14', '\x86', '\xFF', '\x5D', + 'b', '\xA7', '\x4', 'R', '\xC4', 'm', '\x22', '\x1E', '\xA0', + 'F', '\x24', '\x8', '\x16', '\x16', 'v', '\xA', '6', '\xBA', + 'J', '\x9A', '\x80', '\x8', 'A', '\xB4', 'q', '\x85', 'X', + '\x89', 'G', '\xB0', 'I', '\xA9', 'Q', '\x24', '\xCD', '\xA6', + '\x8', '\xA4', 'H', 'c', '\x91', 'B', '\xB', '\xAF', 'V', + '\xC1', 'F', '\xB4', '\x15', '\xCF', '\x22', 'X', '\x98', '\xB', + 'T', 'H', '\x8A', 'd', '\x93', '\x8D', '\xFB', 'F', 'g', + '\xC9', '\x1A', '\x14', '\x7D', '\xF0', 'f', 'v', 'f', '\xDF', + '\x7C', '\xEF', '\xE7', 'g', 'F', '\xA8', '\xD5', 'j', 'H', + '\x24', '\x12', '\x2A', '\x0', '\x5', '\xBF', 'G', '\xD4', '\xEF', + '\xF7', '\x2F', '6', '\xEC', '\x12', '\x20', '\x1E', '\x8F', '\xD7', + '\xAA', '\xD5', '\xEA', '\xAF', 'I', '5', 'F', '\xAA', 'T', + '\x5F', '\x9F', '\x22', 'A', '\x2A', '\x95', '\xA', '\x83', '\xE5', + 'r', '9', 'd', '\xB3', 'Y', '\x96', '\x99', 'L', '\x6', + '\xE9', 't', '\x9A', '\x25', '\x85', '\x2C', '\xCB', 'T', '\xA7', + '\xC4', 'b', '1', '\xB5', '\x5E', '\x0', '\x3', 'h', '\x9A', + '\xC6', '\x16', '\x82', '\x20', 'X', 'R', '\x14', 'E', '6', + 'S', '\x94', '\xCB', 'e', 'x', '\xBD', '\x5E', '\xAA', 'U', + 'T', '\x23', 'L', '\xC0', '\xE0', '\xE2', '\xC1', '\x8F', '\x0', + '\x9E', '\xBC', '\x9', 'A', '\x7C', '\x3E', '\x1F', '\x83', 'D', + '\x22', '\x11', '\xD5', 'T', '\x40', '\x3F', '8', '\x80', 'w', + '\xE5', '3', '\x7', '\xB8', '\x5C', '\x2E', 'H', '\x92', '\x4', + '\x87', '\xC3', '\x81', '\x40', '\x20', '\x40', 'g', '\x98', '\xE9', + '6', '\x1A', '\xA6', 'g', '\x15', '\x4', '\xE3', '\xD7', '\xC8', + '\xBD', '\x15', '\xE1', 'i', '\xB7', 'C', '\xAB', '\xEA', 'x', + '\x2F', 'j', 'X', '\x92', '\xBB', '\x18', '\x20', '\x9F', '\xCF', + '3', '\xC3', '\xB8', '\xE9', 'N', '\xA7', '\xD3', 'l', 'J', + '\x0', 'i', '6', '\x7C', '\x8E', '\xE1', '\xFE', 'V', '\x84', + '\xE7', '\x3C', '\x9F', 'r', '\x2B', '\x3A', 'B', '\x7B', '7', + 'f', 'w', '\xAE', '\x8E', '\xE', '\xF3', '\xBD', 'R', '\xA9', + 'd', '\x2', 'B', '\xAF', '\x85', '2', 'f', 'F', '\xBA', + '\xC', '\xD9', '\x9F', '\x1D', '\x9A', 'l', '\x22', '\xE6', '\xC7', + '\x3A', '\x2C', '\x80', '\xEF', '\xC1', '\x15', '\x90', '\x7', '\x93', + '\xA2', '\x28', '\xA0', 'S', 'j', '\xB1', '\xB8', '\xDF', '\x29', + '5', 'C', '\xE', '\x3F', 'X', '\xFC', '\x98', '\xDA', 'y', + 'j', 'P', '\x40', '\x0', '\x87', '\xAE', '\x1B', '\x17', 'B', + '\xB4', '\x3A', '\x3F', '\xBE', 'y', '\xC7', '\xA', '\x26', '\xB6', + '\xEE', '\xD9', '\x9A', '\x60', '\x14', '\x93', '\xDB', '\x8F', '\xD', + '\xA', '\x2E', '\xE9', '\x23', '\x95', '\x29', 'X', '\x0', '\x27', + '\xEB', 'n', 'V', 'p', '\xBC', '\xD6', '\xCB', '\xD6', 'G', + '\xAB', '\x3D', 'l', '\x7D', '\xB8', '\xD2', '\xDD', '\xA0', '\x60', + '\x83', '\xBA', '\xEF', '\x5F', '\xA4', '\xEA', '\xCC', '\x2', 'N', + '\xAE', '\x5E', 'p', '\x1A', '\xEC', '\xB3', '\x40', '9', '\xAC', + '\xFE', '\xF2', '\x91', '\x89', 'g', '\x91', '\x85', '\x21', '\xA8', + '\x87', '\xB7', 'X', '\x7E', '\x7E', '\x85', '\xBB', '\xCD', 'N', + 'N', 'b', 't', '\x40', '\xFA', '\x93', '\x89', '\xEC', '\x1E', + '\xEC', '\x86', '\x2', 'H', '\x26', '\x93', '\xD0', 'u', '\x1D', + '\x7F', '\x9', '2', '\x95', '\xBF', '\x1F', '\xDB', '\xD7', 'c', + '\x8A', '\x1A', '\xF7', '\x5C', '\xC1', '\xFF', '\x22', 'J', '\xC3', + '\x87', '\x0', '\x3', '\x0', 'K', '\xBB', '\xF8', '\xD6', '\x2A', + 'v', '\x98', 'I', '\x0', '\x0', '\x0', '\x0', 'I', 'E', + 'N', 'D', '\xAE', 'B', '\x60', '\x82', }; diff --git a/muduo/net/inspect/Inspector.cc b/muduo/net/inspect/Inspector.cc index 894abd3ac..de3a38077 100644 --- a/muduo/net/inspect/Inspector.cc +++ b/muduo/net/inspect/Inspector.cc @@ -14,8 +14,8 @@ #include "muduo/net/EventLoop.h" #include "muduo/net/http/HttpRequest.h" #include "muduo/net/http/HttpResponse.h" -#include "muduo/net/inspect/ProcessInspector.h" #include "muduo/net/inspect/PerformanceInspector.h" +#include "muduo/net/inspect/ProcessInspector.h" #include "muduo/net/inspect/SystemInspector.h" //#include @@ -27,45 +27,38 @@ using namespace muduo; using namespace muduo::net; -namespace -{ -Inspector* g_globalInspector = 0; +namespace { +Inspector *g_globalInspector = 0; // Looks buggy -std::vector split(const string& str) -{ +std::vector split(const string &str) { std::vector result; size_t start = 0; size_t pos = str.find('/'); - while (pos != string::npos) - { - if (pos > start) - { - result.push_back(str.substr(start, pos-start)); + while (pos != string::npos) { + if (pos > start) { + result.push_back(str.substr(start, pos - start)); } - start = pos+1; + start = pos + 1; pos = str.find('/', start); } - if (start < str.length()) - { + if (start < str.length()) { result.push_back(str.substr(start)); } return result; } -} // namespace +} // namespace extern char favicon[1743]; -Inspector::Inspector(EventLoop* loop, - const InetAddress& httpAddr, - const string& name) - : server_(loop, httpAddr, "Inspector:"+name), +Inspector::Inspector(EventLoop *loop, const InetAddress &httpAddr, + const string &name) + : server_(loop, httpAddr, "Inspector:" + name), processInspector_(new ProcessInspector), - systemInspector_(new SystemInspector) -{ + systemInspector_(new SystemInspector) { assert(CurrentThread::isMainThread()); assert(g_globalInspector == 0); g_globalInspector = this; @@ -76,54 +69,41 @@ Inspector::Inspector(EventLoop* loop, performanceInspector_.reset(new PerformanceInspector); performanceInspector_->registerCommands(this); #endif - loop->runAfter(0, std::bind(&Inspector::start, this)); // little race condition + loop->runAfter(0, + std::bind(&Inspector::start, this)); // little race condition } -Inspector::~Inspector() -{ +Inspector::~Inspector() { assert(CurrentThread::isMainThread()); g_globalInspector = NULL; } -void Inspector::add(const string& module, - const string& command, - const Callback& cb, - const string& help) -{ +void Inspector::add(const string &module, const string &command, + const Callback &cb, const string &help) { MutexLockGuard lock(mutex_); modules_[module][command] = cb; helps_[module][command] = help; } -void Inspector::remove(const string& module, const string& command) -{ +void Inspector::remove(const string &module, const string &command) { MutexLockGuard lock(mutex_); std::map::iterator it = modules_.find(module); - if (it != modules_.end()) - { + if (it != modules_.end()) { it->second.erase(command); helps_[module].erase(command); } } -void Inspector::start() -{ - server_.start(); -} +void Inspector::start() { server_.start(); } -void Inspector::onRequest(const HttpRequest& req, HttpResponse* resp) -{ - if (req.path() == "/") - { +void Inspector::onRequest(const HttpRequest &req, HttpResponse *resp) { + if (req.path() == "/") { string result; MutexLockGuard lock(mutex_); for (std::map::const_iterator helpListI = helps_.begin(); - helpListI != helps_.end(); - ++helpListI) - { - const HelpList& list = helpListI->second; - for (const auto& it : list) - { + helpListI != helps_.end(); ++helpListI) { + const HelpList &list = helpListI->second; + for (const auto &it : list) { result += "/"; result += helpListI->first; result += "/"; @@ -138,246 +118,250 @@ void Inspector::onRequest(const HttpRequest& req, HttpResponse* resp) resp->setStatusMessage("OK"); resp->setContentType("text/plain"); resp->setBody(result); - } - else - { + } else { std::vector result = split(req.path()); // boost::split(result, req.path(), boost::is_any_of("/")); - //std::copy(result.begin(), result.end(), std::ostream_iterator(std::cout, ", ")); - //std::cout << "\n"; + // std::copy(result.begin(), result.end(), + // std::ostream_iterator(std::cout, ", ")); std::cout << "\n"; bool ok = false; - if (result.size() == 0) - { + if (result.size() == 0) { LOG_DEBUG << req.path(); - } - else if (result.size() == 1) - { + } else if (result.size() == 1) { string module = result[0]; - if (module == "favicon.ico") - { + if (module == "favicon.ico") { resp->setStatusCode(HttpResponse::k200Ok); resp->setStatusMessage("OK"); resp->setContentType("image/png"); resp->setBody(string(favicon, sizeof favicon)); ok = true; - } - else - { + } else { LOG_ERROR << "Unimplemented " << module; } - } - else - { + } else { string module = result[0]; MutexLockGuard lock(mutex_); - std::map::const_iterator commListI = modules_.find(module); - if (commListI != modules_.end()) - { + std::map::const_iterator commListI = + modules_.find(module); + if (commListI != modules_.end()) { string command = result[1]; - const CommandList& commList = commListI->second; + const CommandList &commList = commListI->second; CommandList::const_iterator it = commList.find(command); - if (it != commList.end()) - { - ArgList args(result.begin()+2, result.end()); - if (it->second) - { + if (it != commList.end()) { + ArgList args(result.begin() + 2, result.end()); + if (it->second) { resp->setStatusCode(HttpResponse::k200Ok); resp->setStatusMessage("OK"); resp->setContentType("text/plain"); - const Callback& cb = it->second; + const Callback &cb = it->second; resp->setBody(cb(req.method(), args)); ok = true; } } } - } - if (!ok) - { + if (!ok) { resp->setStatusCode(HttpResponse::k404NotFound); resp->setStatusMessage("Not Found"); } - //resp->setCloseConnection(true); + // resp->setCloseConnection(true); } } -char favicon[1743] = -{ - '\x89', '\x50', '\x4e', '\x47', '\x0d', '\x0a', '\x1a', '\x0a', '\x00', '\x00', - '\x00', '\x0d', '\x49', '\x48', '\x44', '\x52', '\x00', '\x00', '\x00', '\x10', - '\x00', '\x00', '\x00', '\x10', '\x08', '\x06', '\x00', '\x00', '\x00', '\x1f', - '\xf3', '\xff', '\x61', '\x00', '\x00', '\x00', '\x04', '\x73', '\x42', '\x49', - '\x54', '\x08', '\x08', '\x08', '\x08', '\x7c', '\x08', '\x64', '\x88', '\x00', - '\x00', '\x00', '\x09', '\x70', '\x48', '\x59', '\x73', '\x00', '\x00', '\x0b', - '\x12', '\x00', '\x00', '\x0b', '\x12', '\x01', '\xd2', '\xdd', '\x7e', '\xfc', - '\x00', '\x00', '\x00', '\x1c', '\x74', '\x45', '\x58', '\x74', '\x53', '\x6f', - '\x66', '\x74', '\x77', '\x61', '\x72', '\x65', '\x00', '\x41', '\x64', '\x6f', - '\x62', '\x65', '\x20', '\x46', '\x69', '\x72', '\x65', '\x77', '\x6f', '\x72', - '\x6b', '\x73', '\x20', '\x43', '\x53', '\x33', '\x98', '\xd6', '\x46', '\x03', - '\x00', '\x00', '\x00', '\x15', '\x74', '\x45', '\x58', '\x74', '\x43', '\x72', - '\x65', '\x61', '\x74', '\x69', '\x6f', '\x6e', '\x20', '\x54', '\x69', '\x6d', - '\x65', '\x00', '\x32', '\x2f', '\x31', '\x37', '\x2f', '\x30', '\x38', '\x20', - '\x9c', '\xaa', '\x58', '\x00', '\x00', '\x04', '\x11', '\x74', '\x45', '\x58', - '\x74', '\x58', '\x4d', '\x4c', '\x3a', '\x63', '\x6f', '\x6d', '\x2e', '\x61', - '\x64', '\x6f', '\x62', '\x65', '\x2e', '\x78', '\x6d', '\x70', '\x00', '\x3c', - '\x3f', '\x78', '\x70', '\x61', '\x63', '\x6b', '\x65', '\x74', '\x20', '\x62', - '\x65', '\x67', '\x69', '\x6e', '\x3d', '\x22', '\x20', '\x20', '\x20', '\x22', - '\x20', '\x69', '\x64', '\x3d', '\x22', '\x57', '\x35', '\x4d', '\x30', '\x4d', - '\x70', '\x43', '\x65', '\x68', '\x69', '\x48', '\x7a', '\x72', '\x65', '\x53', - '\x7a', '\x4e', '\x54', '\x63', '\x7a', '\x6b', '\x63', '\x39', '\x64', '\x22', - '\x3f', '\x3e', '\x0a', '\x3c', '\x78', '\x3a', '\x78', '\x6d', '\x70', '\x6d', - '\x65', '\x74', '\x61', '\x20', '\x78', '\x6d', '\x6c', '\x6e', '\x73', '\x3a', - '\x78', '\x3d', '\x22', '\x61', '\x64', '\x6f', '\x62', '\x65', '\x3a', '\x6e', - '\x73', '\x3a', '\x6d', '\x65', '\x74', '\x61', '\x2f', '\x22', '\x20', '\x78', - '\x3a', '\x78', '\x6d', '\x70', '\x74', '\x6b', '\x3d', '\x22', '\x41', '\x64', - '\x6f', '\x62', '\x65', '\x20', '\x58', '\x4d', '\x50', '\x20', '\x43', '\x6f', - '\x72', '\x65', '\x20', '\x34', '\x2e', '\x31', '\x2d', '\x63', '\x30', '\x33', - '\x34', '\x20', '\x34', '\x36', '\x2e', '\x32', '\x37', '\x32', '\x39', '\x37', - '\x36', '\x2c', '\x20', '\x53', '\x61', '\x74', '\x20', '\x4a', '\x61', '\x6e', - '\x20', '\x32', '\x37', '\x20', '\x32', '\x30', '\x30', '\x37', '\x20', '\x32', - '\x32', '\x3a', '\x31', '\x31', '\x3a', '\x34', '\x31', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x22', '\x3e', '\x0a', '\x20', '\x20', - '\x20', '\x3c', '\x72', '\x64', '\x66', '\x3a', '\x52', '\x44', '\x46', '\x20', - '\x78', '\x6d', '\x6c', '\x6e', '\x73', '\x3a', '\x72', '\x64', '\x66', '\x3d', - '\x22', '\x68', '\x74', '\x74', '\x70', '\x3a', '\x2f', '\x2f', '\x77', '\x77', - '\x77', '\x2e', '\x77', '\x33', '\x2e', '\x6f', '\x72', '\x67', '\x2f', '\x31', - '\x39', '\x39', '\x39', '\x2f', '\x30', '\x32', '\x2f', '\x32', '\x32', '\x2d', - '\x72', '\x64', '\x66', '\x2d', '\x73', '\x79', '\x6e', '\x74', '\x61', '\x78', - '\x2d', '\x6e', '\x73', '\x23', '\x22', '\x3e', '\x0a', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x3c', '\x72', '\x64', '\x66', '\x3a', '\x44', '\x65', - '\x73', '\x63', '\x72', '\x69', '\x70', '\x74', '\x69', '\x6f', '\x6e', '\x20', - '\x72', '\x64', '\x66', '\x3a', '\x61', '\x62', '\x6f', '\x75', '\x74', '\x3d', - '\x22', '\x22', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x78', '\x6d', '\x6c', '\x6e', '\x73', - '\x3a', '\x78', '\x61', '\x70', '\x3d', '\x22', '\x68', '\x74', '\x74', '\x70', - '\x3a', '\x2f', '\x2f', '\x6e', '\x73', '\x2e', '\x61', '\x64', '\x6f', '\x62', - '\x65', '\x2e', '\x63', '\x6f', '\x6d', '\x2f', '\x78', '\x61', '\x70', '\x2f', - '\x31', '\x2e', '\x30', '\x2f', '\x22', '\x3e', '\x0a', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x3c', '\x78', '\x61', '\x70', - '\x3a', '\x43', '\x72', '\x65', '\x61', '\x74', '\x6f', '\x72', '\x54', '\x6f', - '\x6f', '\x6c', '\x3e', '\x41', '\x64', '\x6f', '\x62', '\x65', '\x20', '\x46', - '\x69', '\x72', '\x65', '\x77', '\x6f', '\x72', '\x6b', '\x73', '\x20', '\x43', - '\x53', '\x33', '\x3c', '\x2f', '\x78', '\x61', '\x70', '\x3a', '\x43', '\x72', - '\x65', '\x61', '\x74', '\x6f', '\x72', '\x54', '\x6f', '\x6f', '\x6c', '\x3e', - '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x3c', '\x78', '\x61', '\x70', '\x3a', '\x43', '\x72', '\x65', '\x61', '\x74', - '\x65', '\x44', '\x61', '\x74', '\x65', '\x3e', '\x32', '\x30', '\x30', '\x38', - '\x2d', '\x30', '\x32', '\x2d', '\x31', '\x37', '\x54', '\x30', '\x32', '\x3a', - '\x33', '\x36', '\x3a', '\x34', '\x35', '\x5a', '\x3c', '\x2f', '\x78', '\x61', - '\x70', '\x3a', '\x43', '\x72', '\x65', '\x61', '\x74', '\x65', '\x44', '\x61', - '\x74', '\x65', '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x3c', '\x78', '\x61', '\x70', '\x3a', '\x4d', '\x6f', - '\x64', '\x69', '\x66', '\x79', '\x44', '\x61', '\x74', '\x65', '\x3e', '\x32', - '\x30', '\x30', '\x38', '\x2d', '\x30', '\x33', '\x2d', '\x32', '\x34', '\x54', - '\x31', '\x39', '\x3a', '\x30', '\x30', '\x3a', '\x34', '\x32', '\x5a', '\x3c', - '\x2f', '\x78', '\x61', '\x70', '\x3a', '\x4d', '\x6f', '\x64', '\x69', '\x66', - '\x79', '\x44', '\x61', '\x74', '\x65', '\x3e', '\x0a', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x3c', '\x2f', '\x72', '\x64', '\x66', '\x3a', '\x44', - '\x65', '\x73', '\x63', '\x72', '\x69', '\x70', '\x74', '\x69', '\x6f', '\x6e', - '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x3c', '\x72', - '\x64', '\x66', '\x3a', '\x44', '\x65', '\x73', '\x63', '\x72', '\x69', '\x70', - '\x74', '\x69', '\x6f', '\x6e', '\x20', '\x72', '\x64', '\x66', '\x3a', '\x61', - '\x62', '\x6f', '\x75', '\x74', '\x3d', '\x22', '\x22', '\x0a', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x78', '\x6d', '\x6c', '\x6e', '\x73', '\x3a', '\x64', '\x63', '\x3d', '\x22', - '\x68', '\x74', '\x74', '\x70', '\x3a', '\x2f', '\x2f', '\x70', '\x75', '\x72', - '\x6c', '\x2e', '\x6f', '\x72', '\x67', '\x2f', '\x64', '\x63', '\x2f', '\x65', - '\x6c', '\x65', '\x6d', '\x65', '\x6e', '\x74', '\x73', '\x2f', '\x31', '\x2e', - '\x31', '\x2f', '\x22', '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x3c', '\x64', '\x63', '\x3a', '\x66', '\x6f', - '\x72', '\x6d', '\x61', '\x74', '\x3e', '\x69', '\x6d', '\x61', '\x67', '\x65', - '\x2f', '\x70', '\x6e', '\x67', '\x3c', '\x2f', '\x64', '\x63', '\x3a', '\x66', - '\x6f', '\x72', '\x6d', '\x61', '\x74', '\x3e', '\x0a', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x3c', '\x2f', '\x72', '\x64', '\x66', '\x3a', '\x44', - '\x65', '\x73', '\x63', '\x72', '\x69', '\x70', '\x74', '\x69', '\x6f', '\x6e', - '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x3c', '\x2f', '\x72', '\x64', '\x66', - '\x3a', '\x52', '\x44', '\x46', '\x3e', '\x0a', '\x3c', '\x2f', '\x78', '\x3a', - '\x78', '\x6d', '\x70', '\x6d', '\x65', '\x74', '\x61', '\x3e', '\x0a', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x0a', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', - '\x20', '\x20', '\x35', '\x1d', '\x52', '\x64', '\x00', '\x00', '\x02', '\x0b', - '\x49', '\x44', '\x41', '\x54', '\x38', '\x8d', '\xa5', '\x93', '\x41', '\x6b', - '\x1a', '\x41', '\x18', '\x86', '\x9f', '\x89', '\x06', '\x23', '\x2e', '\x74', - '\xf5', '\x20', '\x4a', '\x0e', '\x6b', '\x20', '\xe4', '\xe2', '\xa5', '\x78', - '\xc8', '\xa1', '\x78', '\x89', '\x82', '\x17', '\x85', '\x82', '\x82', '\x3d', - '\x26', '\x62', '\x58', '\x72', '\xcd', '\x4f', '\xf1', '\x18', '\x4b', '\x1b', - '\x2f', '\xa5', '\x32', '\xe0', '\xb5', '\x9e', '\x35', '\x1a', '\x58', '\x2f', - '\xe9', '\x0f', '\xe8', '\x65', '\x6d', '\x84', '\xa2', '\x84', '\x2c', '\x0a', - '\x6b', '\x58', '\x62', '\xa7', '\x87', '\x68', '\x68', '\x13', '\xa1', '\xa5', - '\x79', '\xe1', '\x3b', '\x0c', '\xc3', '\xfb', '\xcc', '\x37', '\xef', '\x7c', - '\x23', '\x94', '\x52', '\xbc', '\x44', '\x7e', '\x00', '\x21', '\x04', '\x00', - '\xad', '\x56', '\xcb', '\x18', '\x8f', '\xc7', '\x0d', '\xdb', '\xb6', '\xd3', - '\x8e', '\xe3', '\xf8', '\x83', '\xc1', '\xa0', '\x8a', '\xc7', '\xe3', '\x3f', - '\x12', '\x89', '\x44', '\xb9', '\x5c', '\x2e', '\xf7', '\x56', '\xa6', '\xdf', - '\x0f', '\x15', '\x4a', '\x29', '\x84', '\x10', '\x34', '\x9b', '\xcd', '\x77', - '\x96', '\x65', '\x7d', '\x36', '\x0c', '\x43', '\xe4', '\x72', '\x39', '\xe2', - '\xf1', '\x38', '\xb7', '\xb7', '\xb7', '\xf4', '\xfb', '\x7d', '\x06', '\x83', - '\x01', '\xa9', '\x54', '\xea', '\x43', '\xa5', '\x52', '\x39', '\x7e', '\x0a', - '\x40', '\x29', '\x45', '\xab', '\xd5', '\x32', '\x4e', '\x4f', '\x4f', '\x7f', - '\x4a', '\x29', '\xd5', '\xdd', '\xdd', '\xdd', '\xb3', '\xea', '\xf5', '\x7a', - '\xea', '\xe4', '\xe4', '\x44', '\x49', '\x29', '\xd3', '\x2b', '\xcf', '\xaa', - '\x36', '\x00', '\xc6', '\xe3', '\x71', '\x63', '\x67', '\x67', '\x47', '\xe4', - '\xf3', '\x79', '\x00', '\x3c', '\xcf', '\xa3', '\x50', '\x28', '\xe0', '\xba', - '\x2e', '\x9e', '\xe7', '\x91', '\x4a', '\xa5', '\xd8', '\xdb', '\xdb', '\x63', - '\x34', '\x1a', '\x7d', '\x7c', '\x9a', '\xc1', '\x06', '\x80', '\x6d', '\xdb', - '\xe9', '\x6c', '\x36', '\x8b', '\xcf', '\xe7', '\xc3', '\xf3', '\x3c', '\x5c', - '\xd7', '\x05', '\x60', '\x36', '\x9b', '\xe1', '\xba', '\x2e', '\x8b', '\xc5', - '\x82', '\x4c', '\x26', '\x83', '\x6d', '\xdb', '\xbb', '\x6b', '\x43', '\x74', - '\x1c', '\xc7', '\x1f', '\x8b', '\xc5', '\x00', '\x28', '\x16', '\x8b', '\x8f', - '\x9b', '\xd5', '\x6a', '\x15', '\x00', '\x29', '\x25', '\x9a', '\xa6', '\x31', - '\x9f', '\xcf', '\xc5', '\x5a', '\xc0', '\xd6', '\xd6', '\x96', '\x9a', '\x4c', - '\x26', '\x22', '\x14', '\x0a', '\x21', '\xa5', '\x64', '\x36', '\x9b', '\x51', - '\xad', '\x56', '\xa9', '\xd5', '\x6a', '\x68', '\x9a', '\x06', '\xc0', '\xf5', - '\xf5', '\x35', '\xba', '\xae', '\xdf', '\xaf', '\xbd', '\x82', '\x61', '\x18', - '\xdf', '\x2c', '\xcb', '\x7a', '\x20', '\xfa', '\xfd', '\x04', '\x02', '\x01', - '\x00', '\x34', '\x4d', '\x23', '\x10', '\x08', '\xb0', '\x58', '\x2c', '\xe8', - '\x76', '\xbb', '\x24', '\x12', '\x89', '\x8b', '\xb5', '\x1d', '\x6c', '\x6f', - '\x6f', '\x1f', '\x75', '\x3a', '\x9d', '\x7e', '\x38', '\x1c', '\x26', '\x97', - '\xcb', '\x21', '\x84', '\x40', '\x4a', '\x09', '\xc0', '\xe6', '\xe6', '\x26', - '\xed', '\x76', '\x9b', '\xc9', '\x64', '\xa2', '\xa6', '\xd3', '\xe9', '\x27', - '\x78', '\x98', '\x9b', '\xd5', '\x53', '\x3e', '\xce', '\xc1', '\xf9', '\xf9', - '\xf9', '\xfb', '\xc1', '\x60', '\x70', '\x9c', '\x4c', '\x26', '\xd9', '\xdf', - '\xdf', '\x27', '\x12', '\x89', '\x30', '\x1c', '\x0e', '\xb9', '\xbc', '\xbc', - '\xe4', '\xe6', '\xe6', '\x46', '\xf9', '\x7c', '\xbe', '\x2f', '\xd3', '\xe9', - '\x34', '\x0f', '\x34', '\xea', '\xf5', '\x7a', '\xe5', '\x19', '\x60', '\x19', - '\xd6', '\x9b', '\xd1', '\x68', '\xd4', '\x18', '\x0e', '\x87', '\xbb', '\xf3', - '\xf9', '\x5c', '\xe8', '\xba', '\x7e', '\x6f', '\x18', '\xc6', '\x45', '\x34', - '\x1a', '\x3d', '\x2c', '\x95', '\x4a', '\xdf', '\x4d', '\xd3', '\xbc', '\x02', - '\x5e', '\x03', '\x5f', '\x81', '\x83', '\xb3', '\xb3', '\x33', '\xe7', '\x0f', - '\xc0', '\xdf', '\x64', '\x9a', '\xa6', '\xb1', '\x34', '\xeb', '\x80', '\x03', - '\x1c', '\x6c', '\xfc', '\x93', '\x73', '\xa9', '\x7a', '\xbd', '\x6e', '\x03', - '\x47', '\xcb', '\xa5', '\x0e', '\xbc', '\xe2', '\x7f', '\x7e', '\xa3', '\x69', - '\x9a', '\x87', '\xa6', '\x69', '\xbe', '\x55', '\x4a', '\x3d', '\x64', '\xf0', - '\x12', '\xfd', '\x02', '\x0d', '\x53', '\x06', '\x24', '\x88', '\x3f', '\xe1', - '\x69', '\x00', '\x00', '\x00', '\x00', '\x49', '\x45', '\x4e', '\x44', '\xae', - '\x42', '\x60', '\x82', +char favicon[1743] = { + '\x89', '\x50', '\x4e', '\x47', '\x0d', '\x0a', '\x1a', '\x0a', '\x00', + '\x00', '\x00', '\x0d', '\x49', '\x48', '\x44', '\x52', '\x00', '\x00', + '\x00', '\x10', '\x00', '\x00', '\x00', '\x10', '\x08', '\x06', '\x00', + '\x00', '\x00', '\x1f', '\xf3', '\xff', '\x61', '\x00', '\x00', '\x00', + '\x04', '\x73', '\x42', '\x49', '\x54', '\x08', '\x08', '\x08', '\x08', + '\x7c', '\x08', '\x64', '\x88', '\x00', '\x00', '\x00', '\x09', '\x70', + '\x48', '\x59', '\x73', '\x00', '\x00', '\x0b', '\x12', '\x00', '\x00', + '\x0b', '\x12', '\x01', '\xd2', '\xdd', '\x7e', '\xfc', '\x00', '\x00', + '\x00', '\x1c', '\x74', '\x45', '\x58', '\x74', '\x53', '\x6f', '\x66', + '\x74', '\x77', '\x61', '\x72', '\x65', '\x00', '\x41', '\x64', '\x6f', + '\x62', '\x65', '\x20', '\x46', '\x69', '\x72', '\x65', '\x77', '\x6f', + '\x72', '\x6b', '\x73', '\x20', '\x43', '\x53', '\x33', '\x98', '\xd6', + '\x46', '\x03', '\x00', '\x00', '\x00', '\x15', '\x74', '\x45', '\x58', + '\x74', '\x43', '\x72', '\x65', '\x61', '\x74', '\x69', '\x6f', '\x6e', + '\x20', '\x54', '\x69', '\x6d', '\x65', '\x00', '\x32', '\x2f', '\x31', + '\x37', '\x2f', '\x30', '\x38', '\x20', '\x9c', '\xaa', '\x58', '\x00', + '\x00', '\x04', '\x11', '\x74', '\x45', '\x58', '\x74', '\x58', '\x4d', + '\x4c', '\x3a', '\x63', '\x6f', '\x6d', '\x2e', '\x61', '\x64', '\x6f', + '\x62', '\x65', '\x2e', '\x78', '\x6d', '\x70', '\x00', '\x3c', '\x3f', + '\x78', '\x70', '\x61', '\x63', '\x6b', '\x65', '\x74', '\x20', '\x62', + '\x65', '\x67', '\x69', '\x6e', '\x3d', '\x22', '\x20', '\x20', '\x20', + '\x22', '\x20', '\x69', '\x64', '\x3d', '\x22', '\x57', '\x35', '\x4d', + '\x30', '\x4d', '\x70', '\x43', '\x65', '\x68', '\x69', '\x48', '\x7a', + '\x72', '\x65', '\x53', '\x7a', '\x4e', '\x54', '\x63', '\x7a', '\x6b', + '\x63', '\x39', '\x64', '\x22', '\x3f', '\x3e', '\x0a', '\x3c', '\x78', + '\x3a', '\x78', '\x6d', '\x70', '\x6d', '\x65', '\x74', '\x61', '\x20', + '\x78', '\x6d', '\x6c', '\x6e', '\x73', '\x3a', '\x78', '\x3d', '\x22', + '\x61', '\x64', '\x6f', '\x62', '\x65', '\x3a', '\x6e', '\x73', '\x3a', + '\x6d', '\x65', '\x74', '\x61', '\x2f', '\x22', '\x20', '\x78', '\x3a', + '\x78', '\x6d', '\x70', '\x74', '\x6b', '\x3d', '\x22', '\x41', '\x64', + '\x6f', '\x62', '\x65', '\x20', '\x58', '\x4d', '\x50', '\x20', '\x43', + '\x6f', '\x72', '\x65', '\x20', '\x34', '\x2e', '\x31', '\x2d', '\x63', + '\x30', '\x33', '\x34', '\x20', '\x34', '\x36', '\x2e', '\x32', '\x37', + '\x32', '\x39', '\x37', '\x36', '\x2c', '\x20', '\x53', '\x61', '\x74', + '\x20', '\x4a', '\x61', '\x6e', '\x20', '\x32', '\x37', '\x20', '\x32', + '\x30', '\x30', '\x37', '\x20', '\x32', '\x32', '\x3a', '\x31', '\x31', + '\x3a', '\x34', '\x31', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x22', '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x3c', + '\x72', '\x64', '\x66', '\x3a', '\x52', '\x44', '\x46', '\x20', '\x78', + '\x6d', '\x6c', '\x6e', '\x73', '\x3a', '\x72', '\x64', '\x66', '\x3d', + '\x22', '\x68', '\x74', '\x74', '\x70', '\x3a', '\x2f', '\x2f', '\x77', + '\x77', '\x77', '\x2e', '\x77', '\x33', '\x2e', '\x6f', '\x72', '\x67', + '\x2f', '\x31', '\x39', '\x39', '\x39', '\x2f', '\x30', '\x32', '\x2f', + '\x32', '\x32', '\x2d', '\x72', '\x64', '\x66', '\x2d', '\x73', '\x79', + '\x6e', '\x74', '\x61', '\x78', '\x2d', '\x6e', '\x73', '\x23', '\x22', + '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x3c', + '\x72', '\x64', '\x66', '\x3a', '\x44', '\x65', '\x73', '\x63', '\x72', + '\x69', '\x70', '\x74', '\x69', '\x6f', '\x6e', '\x20', '\x72', '\x64', + '\x66', '\x3a', '\x61', '\x62', '\x6f', '\x75', '\x74', '\x3d', '\x22', + '\x22', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x78', '\x6d', '\x6c', '\x6e', + '\x73', '\x3a', '\x78', '\x61', '\x70', '\x3d', '\x22', '\x68', '\x74', + '\x74', '\x70', '\x3a', '\x2f', '\x2f', '\x6e', '\x73', '\x2e', '\x61', + '\x64', '\x6f', '\x62', '\x65', '\x2e', '\x63', '\x6f', '\x6d', '\x2f', + '\x78', '\x61', '\x70', '\x2f', '\x31', '\x2e', '\x30', '\x2f', '\x22', + '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x3c', '\x78', '\x61', '\x70', '\x3a', '\x43', '\x72', + '\x65', '\x61', '\x74', '\x6f', '\x72', '\x54', '\x6f', '\x6f', '\x6c', + '\x3e', '\x41', '\x64', '\x6f', '\x62', '\x65', '\x20', '\x46', '\x69', + '\x72', '\x65', '\x77', '\x6f', '\x72', '\x6b', '\x73', '\x20', '\x43', + '\x53', '\x33', '\x3c', '\x2f', '\x78', '\x61', '\x70', '\x3a', '\x43', + '\x72', '\x65', '\x61', '\x74', '\x6f', '\x72', '\x54', '\x6f', '\x6f', + '\x6c', '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x3c', '\x78', '\x61', '\x70', '\x3a', '\x43', + '\x72', '\x65', '\x61', '\x74', '\x65', '\x44', '\x61', '\x74', '\x65', + '\x3e', '\x32', '\x30', '\x30', '\x38', '\x2d', '\x30', '\x32', '\x2d', + '\x31', '\x37', '\x54', '\x30', '\x32', '\x3a', '\x33', '\x36', '\x3a', + '\x34', '\x35', '\x5a', '\x3c', '\x2f', '\x78', '\x61', '\x70', '\x3a', + '\x43', '\x72', '\x65', '\x61', '\x74', '\x65', '\x44', '\x61', '\x74', + '\x65', '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x3c', '\x78', '\x61', '\x70', '\x3a', '\x4d', + '\x6f', '\x64', '\x69', '\x66', '\x79', '\x44', '\x61', '\x74', '\x65', + '\x3e', '\x32', '\x30', '\x30', '\x38', '\x2d', '\x30', '\x33', '\x2d', + '\x32', '\x34', '\x54', '\x31', '\x39', '\x3a', '\x30', '\x30', '\x3a', + '\x34', '\x32', '\x5a', '\x3c', '\x2f', '\x78', '\x61', '\x70', '\x3a', + '\x4d', '\x6f', '\x64', '\x69', '\x66', '\x79', '\x44', '\x61', '\x74', + '\x65', '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x3c', '\x2f', '\x72', '\x64', '\x66', '\x3a', '\x44', '\x65', '\x73', + '\x63', '\x72', '\x69', '\x70', '\x74', '\x69', '\x6f', '\x6e', '\x3e', + '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x3c', '\x72', + '\x64', '\x66', '\x3a', '\x44', '\x65', '\x73', '\x63', '\x72', '\x69', + '\x70', '\x74', '\x69', '\x6f', '\x6e', '\x20', '\x72', '\x64', '\x66', + '\x3a', '\x61', '\x62', '\x6f', '\x75', '\x74', '\x3d', '\x22', '\x22', + '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x78', '\x6d', '\x6c', '\x6e', '\x73', + '\x3a', '\x64', '\x63', '\x3d', '\x22', '\x68', '\x74', '\x74', '\x70', + '\x3a', '\x2f', '\x2f', '\x70', '\x75', '\x72', '\x6c', '\x2e', '\x6f', + '\x72', '\x67', '\x2f', '\x64', '\x63', '\x2f', '\x65', '\x6c', '\x65', + '\x6d', '\x65', '\x6e', '\x74', '\x73', '\x2f', '\x31', '\x2e', '\x31', + '\x2f', '\x22', '\x3e', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x3c', '\x64', '\x63', '\x3a', '\x66', + '\x6f', '\x72', '\x6d', '\x61', '\x74', '\x3e', '\x69', '\x6d', '\x61', + '\x67', '\x65', '\x2f', '\x70', '\x6e', '\x67', '\x3c', '\x2f', '\x64', + '\x63', '\x3a', '\x66', '\x6f', '\x72', '\x6d', '\x61', '\x74', '\x3e', + '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x3c', '\x2f', + '\x72', '\x64', '\x66', '\x3a', '\x44', '\x65', '\x73', '\x63', '\x72', + '\x69', '\x70', '\x74', '\x69', '\x6f', '\x6e', '\x3e', '\x0a', '\x20', + '\x20', '\x20', '\x3c', '\x2f', '\x72', '\x64', '\x66', '\x3a', '\x52', + '\x44', '\x46', '\x3e', '\x0a', '\x3c', '\x2f', '\x78', '\x3a', '\x78', + '\x6d', '\x70', '\x6d', '\x65', '\x74', '\x61', '\x3e', '\x0a', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x0a', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', '\x20', + '\x20', '\x20', '\x20', '\x20', '\x35', '\x1d', '\x52', '\x64', '\x00', + '\x00', '\x02', '\x0b', '\x49', '\x44', '\x41', '\x54', '\x38', '\x8d', + '\xa5', '\x93', '\x41', '\x6b', '\x1a', '\x41', '\x18', '\x86', '\x9f', + '\x89', '\x06', '\x23', '\x2e', '\x74', '\xf5', '\x20', '\x4a', '\x0e', + '\x6b', '\x20', '\xe4', '\xe2', '\xa5', '\x78', '\xc8', '\xa1', '\x78', + '\x89', '\x82', '\x17', '\x85', '\x82', '\x82', '\x3d', '\x26', '\x62', + '\x58', '\x72', '\xcd', '\x4f', '\xf1', '\x18', '\x4b', '\x1b', '\x2f', + '\xa5', '\x32', '\xe0', '\xb5', '\x9e', '\x35', '\x1a', '\x58', '\x2f', + '\xe9', '\x0f', '\xe8', '\x65', '\x6d', '\x84', '\xa2', '\x84', '\x2c', + '\x0a', '\x6b', '\x58', '\x62', '\xa7', '\x87', '\x68', '\x68', '\x13', + '\xa1', '\xa5', '\x79', '\xe1', '\x3b', '\x0c', '\xc3', '\xfb', '\xcc', + '\x37', '\xef', '\x7c', '\x23', '\x94', '\x52', '\xbc', '\x44', '\x7e', + '\x00', '\x21', '\x04', '\x00', '\xad', '\x56', '\xcb', '\x18', '\x8f', + '\xc7', '\x0d', '\xdb', '\xb6', '\xd3', '\x8e', '\xe3', '\xf8', '\x83', + '\xc1', '\xa0', '\x8a', '\xc7', '\xe3', '\x3f', '\x12', '\x89', '\x44', + '\xb9', '\x5c', '\x2e', '\xf7', '\x56', '\xa6', '\xdf', '\x0f', '\x15', + '\x4a', '\x29', '\x84', '\x10', '\x34', '\x9b', '\xcd', '\x77', '\x96', + '\x65', '\x7d', '\x36', '\x0c', '\x43', '\xe4', '\x72', '\x39', '\xe2', + '\xf1', '\x38', '\xb7', '\xb7', '\xb7', '\xf4', '\xfb', '\x7d', '\x06', + '\x83', '\x01', '\xa9', '\x54', '\xea', '\x43', '\xa5', '\x52', '\x39', + '\x7e', '\x0a', '\x40', '\x29', '\x45', '\xab', '\xd5', '\x32', '\x4e', + '\x4f', '\x4f', '\x7f', '\x4a', '\x29', '\xd5', '\xdd', '\xdd', '\xdd', + '\xb3', '\xea', '\xf5', '\x7a', '\xea', '\xe4', '\xe4', '\x44', '\x49', + '\x29', '\xd3', '\x2b', '\xcf', '\xaa', '\x36', '\x00', '\xc6', '\xe3', + '\x71', '\x63', '\x67', '\x67', '\x47', '\xe4', '\xf3', '\x79', '\x00', + '\x3c', '\xcf', '\xa3', '\x50', '\x28', '\xe0', '\xba', '\x2e', '\x9e', + '\xe7', '\x91', '\x4a', '\xa5', '\xd8', '\xdb', '\xdb', '\x63', '\x34', + '\x1a', '\x7d', '\x7c', '\x9a', '\xc1', '\x06', '\x80', '\x6d', '\xdb', + '\xe9', '\x6c', '\x36', '\x8b', '\xcf', '\xe7', '\xc3', '\xf3', '\x3c', + '\x5c', '\xd7', '\x05', '\x60', '\x36', '\x9b', '\xe1', '\xba', '\x2e', + '\x8b', '\xc5', '\x82', '\x4c', '\x26', '\x83', '\x6d', '\xdb', '\xbb', + '\x6b', '\x43', '\x74', '\x1c', '\xc7', '\x1f', '\x8b', '\xc5', '\x00', + '\x28', '\x16', '\x8b', '\x8f', '\x9b', '\xd5', '\x6a', '\x15', '\x00', + '\x29', '\x25', '\x9a', '\xa6', '\x31', '\x9f', '\xcf', '\xc5', '\x5a', + '\xc0', '\xd6', '\xd6', '\x96', '\x9a', '\x4c', '\x26', '\x22', '\x14', + '\x0a', '\x21', '\xa5', '\x64', '\x36', '\x9b', '\x51', '\xad', '\x56', + '\xa9', '\xd5', '\x6a', '\x68', '\x9a', '\x06', '\xc0', '\xf5', '\xf5', + '\x35', '\xba', '\xae', '\xdf', '\xaf', '\xbd', '\x82', '\x61', '\x18', + '\xdf', '\x2c', '\xcb', '\x7a', '\x20', '\xfa', '\xfd', '\x04', '\x02', + '\x01', '\x00', '\x34', '\x4d', '\x23', '\x10', '\x08', '\xb0', '\x58', + '\x2c', '\xe8', '\x76', '\xbb', '\x24', '\x12', '\x89', '\x8b', '\xb5', + '\x1d', '\x6c', '\x6f', '\x6f', '\x1f', '\x75', '\x3a', '\x9d', '\x7e', + '\x38', '\x1c', '\x26', '\x97', '\xcb', '\x21', '\x84', '\x40', '\x4a', + '\x09', '\xc0', '\xe6', '\xe6', '\x26', '\xed', '\x76', '\x9b', '\xc9', + '\x64', '\xa2', '\xa6', '\xd3', '\xe9', '\x27', '\x78', '\x98', '\x9b', + '\xd5', '\x53', '\x3e', '\xce', '\xc1', '\xf9', '\xf9', '\xf9', '\xfb', + '\xc1', '\x60', '\x70', '\x9c', '\x4c', '\x26', '\xd9', '\xdf', '\xdf', + '\x27', '\x12', '\x89', '\x30', '\x1c', '\x0e', '\xb9', '\xbc', '\xbc', + '\xe4', '\xe6', '\xe6', '\x46', '\xf9', '\x7c', '\xbe', '\x2f', '\xd3', + '\xe9', '\x34', '\x0f', '\x34', '\xea', '\xf5', '\x7a', '\xe5', '\x19', + '\x60', '\x19', '\xd6', '\x9b', '\xd1', '\x68', '\xd4', '\x18', '\x0e', + '\x87', '\xbb', '\xf3', '\xf9', '\x5c', '\xe8', '\xba', '\x7e', '\x6f', + '\x18', '\xc6', '\x45', '\x34', '\x1a', '\x3d', '\x2c', '\x95', '\x4a', + '\xdf', '\x4d', '\xd3', '\xbc', '\x02', '\x5e', '\x03', '\x5f', '\x81', + '\x83', '\xb3', '\xb3', '\x33', '\xe7', '\x0f', '\xc0', '\xdf', '\x64', + '\x9a', '\xa6', '\xb1', '\x34', '\xeb', '\x80', '\x03', '\x1c', '\x6c', + '\xfc', '\x93', '\x73', '\xa9', '\x7a', '\xbd', '\x6e', '\x03', '\x47', + '\xcb', '\xa5', '\x0e', '\xbc', '\xe2', '\x7f', '\x7e', '\xa3', '\x69', + '\x9a', '\x87', '\xa6', '\x69', '\xbe', '\x55', '\x4a', '\x3d', '\x64', + '\xf0', '\x12', '\xfd', '\x02', '\x0d', '\x53', '\x06', '\x24', '\x88', + '\x3f', '\xe1', '\x69', '\x00', '\x00', '\x00', '\x00', '\x49', '\x45', + '\x4e', '\x44', '\xae', '\x42', '\x60', '\x82', }; diff --git a/muduo/net/inspect/Inspector.h b/muduo/net/inspect/Inspector.h index 09041d1b9..9ae6ad193 100644 --- a/muduo/net/inspect/Inspector.h +++ b/muduo/net/inspect/Inspector.h @@ -17,10 +17,8 @@ #include -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class ProcessInspector; class PerformanceInspector; @@ -28,29 +26,25 @@ class SystemInspector; // An internal inspector of the running process, usually a singleton. // Better to run in a seperated thread, as some method may block for seconds -class Inspector : noncopyable -{ - public: +class Inspector : noncopyable { +public: typedef std::vector ArgList; - typedef std::function Callback; - Inspector(EventLoop* loop, - const InetAddress& httpAddr, - const string& name); + typedef std::function + Callback; + Inspector(EventLoop *loop, const InetAddress &httpAddr, const string &name); ~Inspector(); /// Add a Callback for handling the special uri : /mudule/command - void add(const string& module, - const string& command, - const Callback& cb, - const string& help); - void remove(const string& module, const string& command); + void add(const string &module, const string &command, const Callback &cb, + const string &help); + void remove(const string &module, const string &command); - private: +private: typedef std::map CommandList; typedef std::map HelpList; void start(); - void onRequest(const HttpRequest& req, HttpResponse* resp); + void onRequest(const HttpRequest &req, HttpResponse *resp); HttpServer server_; std::unique_ptr processInspector_; @@ -61,7 +55,7 @@ class Inspector : noncopyable std::map helps_ GUARDED_BY(mutex_); }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_INSPECT_INSPECTOR_H +#endif // MUDUO_NET_INSPECT_INSPECTOR_H diff --git a/muduo/net/inspect/PerformanceInspector.cc b/muduo/net/inspect/PerformanceInspector.cc index a0fb9e93e..ffa7e7ad1 100644 --- a/muduo/net/inspect/PerformanceInspector.cc +++ b/muduo/net/inspect/PerformanceInspector.cc @@ -21,34 +21,39 @@ using namespace muduo; using namespace muduo::net; -void PerformanceInspector::registerCommands(Inspector* ins) -{ +void PerformanceInspector::registerCommands(Inspector *ins) { ins->add("pprof", "heap", PerformanceInspector::heap, "get heap information"); - ins->add("pprof", "growth", PerformanceInspector::growth, "get heap growth information"); + ins->add("pprof", "growth", PerformanceInspector::growth, + "get heap growth information"); ins->add("pprof", "profile", PerformanceInspector::profile, - "get cpu profiling information. CAUTION: blocking thread for 30 seconds!"); - ins->add("pprof", "cmdline", PerformanceInspector::cmdline, "get command line"); - ins->add("pprof", "memstats", PerformanceInspector::memstats, "get memory stats"); - ins->add("pprof", "memhistogram", PerformanceInspector::memhistogram, "get memory histogram"); - ins->add("pprof", "releasefreememory", PerformanceInspector::releaseFreeMemory, "release free memory"); + "get cpu profiling information. CAUTION: blocking thread for 30 " + "seconds!"); + ins->add("pprof", "cmdline", PerformanceInspector::cmdline, + "get command line"); + ins->add("pprof", "memstats", PerformanceInspector::memstats, + "get memory stats"); + ins->add("pprof", "memhistogram", PerformanceInspector::memhistogram, + "get memory histogram"); + ins->add("pprof", "releasefreememory", + PerformanceInspector::releaseFreeMemory, "release free memory"); } -string PerformanceInspector::heap(HttpRequest::Method, const Inspector::ArgList&) -{ +string PerformanceInspector::heap(HttpRequest::Method, + const Inspector::ArgList &) { std::string result; MallocExtension::instance()->GetHeapSample(&result); return string(result.data(), result.size()); } -string PerformanceInspector::growth(HttpRequest::Method, const Inspector::ArgList&) -{ +string PerformanceInspector::growth(HttpRequest::Method, + const Inspector::ArgList &) { std::string result; MallocExtension::instance()->GetHeapGrowthStacks(&result); return string(result.data(), result.size()); } -string PerformanceInspector::profile(HttpRequest::Method, const Inspector::ArgList&) -{ +string PerformanceInspector::profile(HttpRequest::Method, + const Inspector::ArgList &) { string filename = "/tmp/" + ProcessInfo::procname(); filename += "."; filename += ProcessInfo::pidString(); @@ -57,34 +62,35 @@ string PerformanceInspector::profile(HttpRequest::Method, const Inspector::ArgLi filename += ".profile"; string profile; - if (ProfilerStart(filename.c_str())) - { + if (ProfilerStart(filename.c_str())) { // FIXME: async CurrentThread::sleepUsec(30 * 1000 * 1000); ProfilerStop(); - FileUtil::readFile(filename, 1024*1024, &profile, NULL, NULL); + FileUtil::readFile(filename, 1024 * 1024, &profile, NULL, NULL); ::unlink(filename.c_str()); } return profile; } -string PerformanceInspector::cmdline(HttpRequest::Method, const Inspector::ArgList&) -{ +string PerformanceInspector::cmdline(HttpRequest::Method, + const Inspector::ArgList &) { return ""; } -string PerformanceInspector::memstats(HttpRequest::Method, const Inspector::ArgList&) -{ - char buf[1024*64]; +string PerformanceInspector::memstats(HttpRequest::Method, + const Inspector::ArgList &) { + char buf[1024 * 64]; MallocExtension::instance()->GetStats(buf, sizeof buf); return buf; } -string PerformanceInspector::memhistogram(HttpRequest::Method, const Inspector::ArgList&) -{ +string PerformanceInspector::memhistogram(HttpRequest::Method, + const Inspector::ArgList &) { int blocks = 0; size_t total = 0; - int histogram[kMallocHistogramSize] = { 0, }; + int histogram[kMallocHistogramSize] = { + 0, + }; MallocExtension::instance()->MallocMemoryStats(&blocks, &total, histogram); LogStream s; @@ -94,10 +100,11 @@ string PerformanceInspector::memhistogram(HttpRequest::Method, const Inspector:: return s.buffer().toString(); } -string PerformanceInspector::releaseFreeMemory(HttpRequest::Method, const Inspector::ArgList&) -{ +string PerformanceInspector::releaseFreeMemory(HttpRequest::Method, + const Inspector::ArgList &) { char buf[256]; - snprintf(buf, sizeof buf, "memory release rate: %f\nAll free memory released.\n", + snprintf(buf, sizeof buf, + "memory release rate: %f\nAll free memory released.\n", MallocExtension::instance()->GetMemoryReleaseRate()); MallocExtension::instance()->ReleaseFreeMemory(); return buf; diff --git a/muduo/net/inspect/PerformanceInspector.h b/muduo/net/inspect/PerformanceInspector.h index 241682456..071ed28f9 100644 --- a/muduo/net/inspect/PerformanceInspector.h +++ b/muduo/net/inspect/PerformanceInspector.h @@ -13,28 +13,26 @@ #include "muduo/net/inspect/Inspector.h" -namespace muduo -{ -namespace net -{ - -class PerformanceInspector : noncopyable -{ - public: - void registerCommands(Inspector* ins); - - static string heap(HttpRequest::Method, const Inspector::ArgList&); - static string growth(HttpRequest::Method, const Inspector::ArgList&); - static string profile(HttpRequest::Method, const Inspector::ArgList&); - static string cmdline(HttpRequest::Method, const Inspector::ArgList&); - static string memstats(HttpRequest::Method, const Inspector::ArgList&); - static string memhistogram(HttpRequest::Method, const Inspector::ArgList&); - static string releaseFreeMemory(HttpRequest::Method, const Inspector::ArgList&); - - static string symbol(HttpRequest::Method, const Inspector::ArgList&); +namespace muduo { +namespace net { + +class PerformanceInspector : noncopyable { +public: + void registerCommands(Inspector *ins); + + static string heap(HttpRequest::Method, const Inspector::ArgList &); + static string growth(HttpRequest::Method, const Inspector::ArgList &); + static string profile(HttpRequest::Method, const Inspector::ArgList &); + static string cmdline(HttpRequest::Method, const Inspector::ArgList &); + static string memstats(HttpRequest::Method, const Inspector::ArgList &); + static string memhistogram(HttpRequest::Method, const Inspector::ArgList &); + static string releaseFreeMemory(HttpRequest::Method, + const Inspector::ArgList &); + + static string symbol(HttpRequest::Method, const Inspector::ArgList &); }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_INSPECT_PERFORMANCEINSPECTOR_H +#endif // MUDUO_NET_INSPECT_PERFORMANCEINSPECTOR_H diff --git a/muduo/net/inspect/ProcessInspector.cc b/muduo/net/inspect/ProcessInspector.cc index d89f0ce9a..a576caadc 100644 --- a/muduo/net/inspect/ProcessInspector.cc +++ b/muduo/net/inspect/ProcessInspector.cc @@ -11,85 +11,73 @@ #include "muduo/base/FileUtil.h" #include "muduo/base/ProcessInfo.h" #include -#include #include +#include #include using namespace muduo; using namespace muduo::net; -namespace muduo -{ -namespace inspect -{ +namespace muduo { +namespace inspect { -string uptime(Timestamp now, Timestamp start, bool showMicroseconds) -{ +string uptime(Timestamp now, Timestamp start, bool showMicroseconds) { char buf[256]; int64_t age = now.microSecondsSinceEpoch() - start.microSecondsSinceEpoch(); int seconds = static_cast(age / Timestamp::kMicroSecondsPerSecond); - int days = seconds/86400; + int days = seconds / 86400; int hours = (seconds % 86400) / 3600; int minutes = (seconds % 3600) / 60; - if (showMicroseconds) - { - int microseconds = static_cast(age % Timestamp::kMicroSecondsPerSecond); - snprintf(buf, sizeof buf, "%d days %02d:%02d:%02d.%06d", - days, hours, minutes, seconds % 60, microseconds); - } - else - { - snprintf(buf, sizeof buf, "%d days %02d:%02d:%02d", - days, hours, minutes, seconds % 60); + if (showMicroseconds) { + int microseconds = + static_cast(age % Timestamp::kMicroSecondsPerSecond); + snprintf(buf, sizeof buf, "%d days %02d:%02d:%02d.%06d", days, hours, + minutes, seconds % 60, microseconds); + } else { + snprintf(buf, sizeof buf, "%d days %02d:%02d:%02d", days, hours, minutes, + seconds % 60); } return buf; } -long getLong(const string& procStatus, const char* key) -{ +long getLong(const string &procStatus, const char *key) { long result = 0; size_t pos = procStatus.find(key); - if (pos != string::npos) - { + if (pos != string::npos) { result = ::atol(procStatus.c_str() + pos + strlen(key)); } return result; } -string getProcessName(const string& procStatus) -{ +string getProcessName(const string &procStatus) { string result; size_t pos = procStatus.find("Name:"); - if (pos != string::npos) - { + if (pos != string::npos) { pos += strlen("Name:"); while (procStatus[pos] == '\t') ++pos; size_t eol = pos; while (procStatus[eol] != '\n') ++eol; - result = procStatus.substr(pos, eol-pos); + result = procStatus.substr(pos, eol - pos); } return result; } -StringPiece next(StringPiece data) -{ - const char* sp = static_cast(::memchr(data.data(), ' ', data.size())); - if (sp) - { - data.remove_prefix(static_cast(sp+1-data.begin())); +StringPiece next(StringPiece data) { + const char *sp = + static_cast(::memchr(data.data(), ' ', data.size())); + if (sp) { + data.remove_prefix(static_cast(sp + 1 - data.begin())); return data; } return ""; } -ProcessInfo::CpuTime getCpuTime(StringPiece data) -{ +ProcessInfo::CpuTime getCpuTime(StringPiece data) { ProcessInfo::CpuTime t; - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { data = next(data); } long utime = strtol(data.data(), NULL, 10); @@ -101,10 +89,10 @@ ProcessInfo::CpuTime getCpuTime(StringPiece data) return t; } -int stringPrintf(string* out, const char* fmt, ...) __attribute__ ((format (printf, 2, 3))); +int stringPrintf(string *out, const char *fmt, ...) + __attribute__((format(printf, 2, 3))); -int stringPrintf(string* out, const char* fmt, ...) -{ +int stringPrintf(string *out, const char *fmt, ...) { char buf[256]; va_list args; va_start(args, fmt); @@ -114,24 +102,27 @@ int stringPrintf(string* out, const char* fmt, ...) return ret; } -} // namespace inspect -} // namespace muduo +} // namespace inspect +} // namespace muduo using namespace muduo::inspect; string ProcessInspector::username_ = ProcessInfo::username(); -void ProcessInspector::registerCommands(Inspector* ins) -{ - ins->add("proc", "overview", ProcessInspector::overview, "print basic overview"); +void ProcessInspector::registerCommands(Inspector *ins) { + ins->add("proc", "overview", ProcessInspector::overview, + "print basic overview"); ins->add("proc", "pid", ProcessInspector::pid, "print pid"); - ins->add("proc", "status", ProcessInspector::procStatus, "print /proc/self/status"); - // ins->add("proc", "opened_files", ProcessInspector::openedFiles, "count /proc/self/fd"); - ins->add("proc", "threads", ProcessInspector::threads, "list /proc/self/task"); + ins->add("proc", "status", ProcessInspector::procStatus, + "print /proc/self/status"); + // ins->add("proc", "opened_files", ProcessInspector::openedFiles, "count + // /proc/self/fd"); + ins->add("proc", "threads", ProcessInspector::threads, + "list /proc/self/task"); } -string ProcessInspector::overview(HttpRequest::Method, const Inspector::ArgList&) -{ +string ProcessInspector::overview(HttpRequest::Method, + const Inspector::ArgList &) { string result; result.reserve(1024); Timestamp now = Timestamp::now(); @@ -140,7 +131,7 @@ string ProcessInspector::overview(HttpRequest::Method, const Inspector::ArgList& result += " (UTC)\nStarted at "; result += ProcessInfo::startTime().toFormattedString(); result += " (UTC), up for "; - result += uptime(now, ProcessInfo::startTime(), true/* show microseconds */); + result += uptime(now, ProcessInfo::startTime(), true /* show microseconds */); result += "\n"; string procStatus = ProcessInfo::procStatus(); @@ -153,13 +144,13 @@ string ProcessInspector::overview(HttpRequest::Method, const Inspector::ArgList& result += ProcessInfo::hostname(); // cache ? result += "\n"; - if (ProcessInfo::isDebugBuild()) - { + if (ProcessInfo::isDebugBuild()) { result += "WARNING: debug build!\n"; } stringPrintf(&result, "pid %d, num of threads %ld, bits %zd\n", - ProcessInfo::pid(), getLong(procStatus, "Threads:"), CHAR_BIT * sizeof(void*)); + ProcessInfo::pid(), getLong(procStatus, "Threads:"), + CHAR_BIT * sizeof(void *)); result += "Virtual memory: "; stringPrintf(&result, "%.3f MiB, ", @@ -190,50 +181,46 @@ string ProcessInspector::overview(HttpRequest::Method, const Inspector::ArgList& return result; } -string ProcessInspector::pid(HttpRequest::Method, const Inspector::ArgList&) -{ +string ProcessInspector::pid(HttpRequest::Method, const Inspector::ArgList &) { char buf[32]; snprintf(buf, sizeof buf, "%d", ProcessInfo::pid()); return buf; } -string ProcessInspector::procStatus(HttpRequest::Method, const Inspector::ArgList&) -{ +string ProcessInspector::procStatus(HttpRequest::Method, + const Inspector::ArgList &) { return ProcessInfo::procStatus(); } -string ProcessInspector::openedFiles(HttpRequest::Method, const Inspector::ArgList&) -{ +string ProcessInspector::openedFiles(HttpRequest::Method, + const Inspector::ArgList &) { char buf[32]; snprintf(buf, sizeof buf, "%d", ProcessInfo::openedFiles()); return buf; } -string ProcessInspector::threads(HttpRequest::Method, const Inspector::ArgList&) -{ +string ProcessInspector::threads(HttpRequest::Method, + const Inspector::ArgList &) { std::vector threads = ProcessInfo::threads(); string result = " TID NAME S User Time System Time\n"; result.reserve(threads.size() * 64); string stat; - for (pid_t tid : threads) - { + for (pid_t tid : threads) { char buf[256]; snprintf(buf, sizeof buf, "/proc/%d/task/%d/stat", ProcessInfo::pid(), tid); - if (FileUtil::readFile(buf, 65536, &stat) == 0) - { + if (FileUtil::readFile(buf, 65536, &stat) == 0) { StringPiece name = ProcessInfo::procname(stat); - const char* rp = name.end(); + const char *rp = name.end(); assert(*rp == ')'); - const char* state = rp + 2; - *const_cast(rp) = '\0'; // don't do this at home + const char *state = rp + 2; + *const_cast(rp) = '\0'; // don't do this at home StringPiece data(stat); data.remove_prefix(static_cast(state - data.data() + 2)); ProcessInfo::CpuTime t = getCpuTime(data); - snprintf(buf, sizeof buf, "%5d %-16s %c %12.3f %12.3f\n", - tid, name.data(), *state, t.userSeconds, t.systemSeconds); + snprintf(buf, sizeof buf, "%5d %-16s %c %12.3f %12.3f\n", tid, + name.data(), *state, t.userSeconds, t.systemSeconds); result += buf; } } return result; } - diff --git a/muduo/net/inspect/ProcessInspector.h b/muduo/net/inspect/ProcessInspector.h index f1df4783c..d4f853d04 100644 --- a/muduo/net/inspect/ProcessInspector.h +++ b/muduo/net/inspect/ProcessInspector.h @@ -13,26 +13,23 @@ #include "muduo/net/inspect/Inspector.h" -namespace muduo -{ -namespace net -{ - -class ProcessInspector : noncopyable -{ - public: - void registerCommands(Inspector* ins); - - static string overview(HttpRequest::Method, const Inspector::ArgList&); - static string pid(HttpRequest::Method, const Inspector::ArgList&); - static string procStatus(HttpRequest::Method, const Inspector::ArgList&); - static string openedFiles(HttpRequest::Method, const Inspector::ArgList&); - static string threads(HttpRequest::Method, const Inspector::ArgList&); +namespace muduo { +namespace net { + +class ProcessInspector : noncopyable { +public: + void registerCommands(Inspector *ins); + + static string overview(HttpRequest::Method, const Inspector::ArgList &); + static string pid(HttpRequest::Method, const Inspector::ArgList &); + static string procStatus(HttpRequest::Method, const Inspector::ArgList &); + static string openedFiles(HttpRequest::Method, const Inspector::ArgList &); + static string threads(HttpRequest::Method, const Inspector::ArgList &); static string username_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_INSPECT_PROCESSINSPECTOR_H +#endif // MUDUO_NET_INSPECT_PROCESSINSPECTOR_H diff --git a/muduo/net/inspect/SystemInspector.cc b/muduo/net/inspect/SystemInspector.cc index fb45e76d0..fa06e3eec 100644 --- a/muduo/net/inspect/SystemInspector.cc +++ b/muduo/net/inspect/SystemInspector.cc @@ -15,21 +15,20 @@ using namespace muduo; using namespace muduo::net; -namespace muduo -{ -namespace inspect -{ +namespace muduo { +namespace inspect { string uptime(Timestamp now, Timestamp start, bool showMicroseconds); -long getLong(const string& content, const char* key); -int stringPrintf(string* out, const char* fmt, ...) __attribute__ ((format (printf, 2, 3))); -} -} +long getLong(const string &content, const char *key); +int stringPrintf(string *out, const char *fmt, ...) + __attribute__((format(printf, 2, 3))); +} // namespace inspect +} // namespace muduo using namespace muduo::inspect; -void SystemInspector::registerCommands(Inspector* ins) -{ - ins->add("sys", "overview", SystemInspector::overview, "print system overview"); +void SystemInspector::registerCommands(Inspector *ins) { + ins->add("sys", "overview", SystemInspector::overview, + "print system overview"); ins->add("sys", "loadavg", SystemInspector::loadavg, "print /proc/loadavg"); ins->add("sys", "version", SystemInspector::version, "print /proc/version"); ins->add("sys", "cpuinfo", SystemInspector::cpuinfo, "print /proc/cpuinfo"); @@ -37,43 +36,42 @@ void SystemInspector::registerCommands(Inspector* ins) ins->add("sys", "stat", SystemInspector::stat, "print /proc/stat"); } -string SystemInspector::loadavg(HttpRequest::Method, const Inspector::ArgList&) -{ +string SystemInspector::loadavg(HttpRequest::Method, + const Inspector::ArgList &) { string loadavg; FileUtil::readFile("/proc/loadavg", 65536, &loadavg); return loadavg; } -string SystemInspector::version(HttpRequest::Method, const Inspector::ArgList&) -{ +string SystemInspector::version(HttpRequest::Method, + const Inspector::ArgList &) { string version; FileUtil::readFile("/proc/version", 65536, &version); return version; } -string SystemInspector::cpuinfo(HttpRequest::Method, const Inspector::ArgList&) -{ +string SystemInspector::cpuinfo(HttpRequest::Method, + const Inspector::ArgList &) { string cpuinfo; FileUtil::readFile("/proc/cpuinfo", 65536, &cpuinfo); return cpuinfo; } -string SystemInspector::meminfo(HttpRequest::Method, const Inspector::ArgList&) -{ +string SystemInspector::meminfo(HttpRequest::Method, + const Inspector::ArgList &) { string meminfo; FileUtil::readFile("/proc/meminfo", 65536, &meminfo); return meminfo; } -string SystemInspector::stat(HttpRequest::Method, const Inspector::ArgList&) -{ +string SystemInspector::stat(HttpRequest::Method, const Inspector::ArgList &) { string stat; FileUtil::readFile("/proc/stat", 65536, &stat); return stat; } -string SystemInspector::overview(HttpRequest::Method, const Inspector::ArgList&) -{ +string SystemInspector::overview(HttpRequest::Method, + const Inspector::ArgList &) { string result; result.reserve(1024); Timestamp now = Timestamp::now(); @@ -82,17 +80,18 @@ string SystemInspector::overview(HttpRequest::Method, const Inspector::ArgList&) result += " (UTC)\n"; // Hardware and OS { - struct utsname un; - if (::uname(&un) == 0) - { - stringPrintf(&result, "Hostname: %s\n", un.nodename); - stringPrintf(&result, "Machine: %s\n", un.machine); - stringPrintf(&result, "OS: %s %s %s\n", un.sysname, un.release, un.version); - } + struct utsname un; + if (::uname(&un) == 0) { + stringPrintf(&result, "Hostname: %s\n", un.nodename); + stringPrintf(&result, "Machine: %s\n", un.machine); + stringPrintf(&result, "OS: %s %s %s\n", un.sysname, un.release, + un.version); + } } string stat; FileUtil::readFile("/proc/stat", 65536, &stat); - Timestamp bootTime(Timestamp::kMicroSecondsPerSecond * getLong(stat, "btime ")); + Timestamp bootTime(Timestamp::kMicroSecondsPerSecond * + getLong(stat, "btime ")); result += "Boot time: "; result += bootTime.toFormattedString(false /* show microseconds */); result += " (UTC)\n"; @@ -102,29 +101,32 @@ string SystemInspector::overview(HttpRequest::Method, const Inspector::ArgList&) // CPU load { - string loadavg; - FileUtil::readFile("/proc/loadavg", 65536, &loadavg); - stringPrintf(&result, "Processes created: %ld\n", getLong(stat, "processes ")); - stringPrintf(&result, "Loadavg: %s\n", loadavg.c_str()); + string loadavg; + FileUtil::readFile("/proc/loadavg", 65536, &loadavg); + stringPrintf(&result, "Processes created: %ld\n", + getLong(stat, "processes ")); + stringPrintf(&result, "Loadavg: %s\n", loadavg.c_str()); } // Memory { - string meminfo; - FileUtil::readFile("/proc/meminfo", 65536, &meminfo); - long total_kb = getLong(meminfo, "MemTotal:"); - long free_kb = getLong(meminfo, "MemFree:"); - long buffers_kb = getLong(meminfo, "Buffers:"); - long cached_kb = getLong(meminfo, "Cached:"); - - stringPrintf(&result, "Total Memory: %6ld MiB\n", total_kb / 1024); - stringPrintf(&result, "Free Memory: %6ld MiB\n", free_kb / 1024); - stringPrintf(&result, "Buffers: %6ld MiB\n", buffers_kb / 1024); - stringPrintf(&result, "Cached: %6ld MiB\n", cached_kb / 1024); - stringPrintf(&result, "Real Used: %6ld MiB\n", (total_kb - free_kb - buffers_kb - cached_kb) / 1024); - stringPrintf(&result, "Real Free: %6ld MiB\n", (free_kb + buffers_kb + cached_kb) / 1024); - - // Swap + string meminfo; + FileUtil::readFile("/proc/meminfo", 65536, &meminfo); + long total_kb = getLong(meminfo, "MemTotal:"); + long free_kb = getLong(meminfo, "MemFree:"); + long buffers_kb = getLong(meminfo, "Buffers:"); + long cached_kb = getLong(meminfo, "Cached:"); + + stringPrintf(&result, "Total Memory: %6ld MiB\n", total_kb / 1024); + stringPrintf(&result, "Free Memory: %6ld MiB\n", free_kb / 1024); + stringPrintf(&result, "Buffers: %6ld MiB\n", buffers_kb / 1024); + stringPrintf(&result, "Cached: %6ld MiB\n", cached_kb / 1024); + stringPrintf(&result, "Real Used: %6ld MiB\n", + (total_kb - free_kb - buffers_kb - cached_kb) / 1024); + stringPrintf(&result, "Real Free: %6ld MiB\n", + (free_kb + buffers_kb + cached_kb) / 1024); + + // Swap } // Disk // Network diff --git a/muduo/net/inspect/SystemInspector.h b/muduo/net/inspect/SystemInspector.h index 8f2a604f5..2800c5c69 100644 --- a/muduo/net/inspect/SystemInspector.h +++ b/muduo/net/inspect/SystemInspector.h @@ -13,25 +13,22 @@ #include "muduo/net/inspect/Inspector.h" -namespace muduo -{ -namespace net -{ - -class SystemInspector : noncopyable -{ - public: - void registerCommands(Inspector* ins); - - static string overview(HttpRequest::Method, const Inspector::ArgList&); - static string loadavg(HttpRequest::Method, const Inspector::ArgList&); - static string version(HttpRequest::Method, const Inspector::ArgList&); - static string cpuinfo(HttpRequest::Method, const Inspector::ArgList&); - static string meminfo(HttpRequest::Method, const Inspector::ArgList&); - static string stat(HttpRequest::Method, const Inspector::ArgList&); +namespace muduo { +namespace net { + +class SystemInspector : noncopyable { +public: + void registerCommands(Inspector *ins); + + static string overview(HttpRequest::Method, const Inspector::ArgList &); + static string loadavg(HttpRequest::Method, const Inspector::ArgList &); + static string version(HttpRequest::Method, const Inspector::ArgList &); + static string cpuinfo(HttpRequest::Method, const Inspector::ArgList &); + static string meminfo(HttpRequest::Method, const Inspector::ArgList &); + static string stat(HttpRequest::Method, const Inspector::ArgList &); }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_INSPECT_SYSTEMINSPECTOR_H +#endif // MUDUO_NET_INSPECT_SYSTEMINSPECTOR_H diff --git a/muduo/net/inspect/tests/Inspector_test.cc b/muduo/net/inspect/tests/Inspector_test.cc index 20025ff39..dff40098d 100644 --- a/muduo/net/inspect/tests/Inspector_test.cc +++ b/muduo/net/inspect/tests/Inspector_test.cc @@ -1,15 +1,13 @@ -#include "muduo/net/inspect/Inspector.h" #include "muduo/net/EventLoop.h" #include "muduo/net/EventLoopThread.h" +#include "muduo/net/inspect/Inspector.h" using namespace muduo; using namespace muduo::net; -int main() -{ +int main() { EventLoop loop; EventLoopThread t; Inspector ins(t.startLoop(), InetAddress(12345), "test"); loop.loop(); } - diff --git a/muduo/net/poller/DefaultPoller.cc b/muduo/net/poller/DefaultPoller.cc index 5ea0d03a9..b1604f264 100644 --- a/muduo/net/poller/DefaultPoller.cc +++ b/muduo/net/poller/DefaultPoller.cc @@ -7,21 +7,17 @@ // Author: Shuo Chen (chenshuo at chenshuo dot com) #include "muduo/net/Poller.h" -#include "muduo/net/poller/PollPoller.h" #include "muduo/net/poller/EPollPoller.h" +#include "muduo/net/poller/PollPoller.h" #include using namespace muduo::net; -Poller* Poller::newDefaultPoller(EventLoop* loop) -{ - if (::getenv("MUDUO_USE_POLL")) - { +Poller *Poller::newDefaultPoller(EventLoop *loop) { + if (::getenv("MUDUO_USE_POLL")) { return new PollPoller(loop); - } - else - { + } else { return new EPollPoller(loop); } } diff --git a/muduo/net/poller/EPollPoller.cc b/muduo/net/poller/EPollPoller.cc index b2f913a4c..8a4a5e6c6 100644 --- a/muduo/net/poller/EPollPoller.cc +++ b/muduo/net/poller/EPollPoller.cc @@ -22,63 +22,46 @@ using namespace muduo::net; // On Linux, the constants of poll(2) and epoll(4) // are expected to be the same. -static_assert(EPOLLIN == POLLIN, "epoll uses same flag values as poll"); -static_assert(EPOLLPRI == POLLPRI, "epoll uses same flag values as poll"); -static_assert(EPOLLOUT == POLLOUT, "epoll uses same flag values as poll"); -static_assert(EPOLLRDHUP == POLLRDHUP, "epoll uses same flag values as poll"); -static_assert(EPOLLERR == POLLERR, "epoll uses same flag values as poll"); -static_assert(EPOLLHUP == POLLHUP, "epoll uses same flag values as poll"); - -namespace -{ +static_assert(EPOLLIN == POLLIN, "epoll uses same flag values as poll"); +static_assert(EPOLLPRI == POLLPRI, "epoll uses same flag values as poll"); +static_assert(EPOLLOUT == POLLOUT, "epoll uses same flag values as poll"); +static_assert(EPOLLRDHUP == POLLRDHUP, "epoll uses same flag values as poll"); +static_assert(EPOLLERR == POLLERR, "epoll uses same flag values as poll"); +static_assert(EPOLLHUP == POLLHUP, "epoll uses same flag values as poll"); + +namespace { const int kNew = -1; const int kAdded = 1; const int kDeleted = 2; -} +} // namespace -EPollPoller::EPollPoller(EventLoop* loop) - : Poller(loop), - epollfd_(::epoll_create1(EPOLL_CLOEXEC)), - events_(kInitEventListSize) -{ - if (epollfd_ < 0) - { +EPollPoller::EPollPoller(EventLoop *loop) + : Poller(loop), epollfd_(::epoll_create1(EPOLL_CLOEXEC)), + events_(kInitEventListSize) { + if (epollfd_ < 0) { LOG_SYSFATAL << "EPollPoller::EPollPoller"; } } -EPollPoller::~EPollPoller() -{ - ::close(epollfd_); -} +EPollPoller::~EPollPoller() { ::close(epollfd_); } -Timestamp EPollPoller::poll(int timeoutMs, ChannelList* activeChannels) -{ +Timestamp EPollPoller::poll(int timeoutMs, ChannelList *activeChannels) { LOG_TRACE << "fd total count " << channels_.size(); - int numEvents = ::epoll_wait(epollfd_, - &*events_.begin(), - static_cast(events_.size()), - timeoutMs); + int numEvents = ::epoll_wait(epollfd_, &*events_.begin(), + static_cast(events_.size()), timeoutMs); int savedErrno = errno; Timestamp now(Timestamp::now()); - if (numEvents > 0) - { + if (numEvents > 0) { LOG_TRACE << numEvents << " events happened"; fillActiveChannels(numEvents, activeChannels); - if (implicit_cast(numEvents) == events_.size()) - { - events_.resize(events_.size()*2); + if (implicit_cast(numEvents) == events_.size()) { + events_.resize(events_.size() * 2); } - } - else if (numEvents == 0) - { + } else if (numEvents == 0) { LOG_TRACE << "nothing happened"; - } - else - { + } else { // error happens, log uncommon ones - if (savedErrno != EINTR) - { + if (savedErrno != EINTR) { errno = savedErrno; LOG_SYSERR << "EPollPoller::poll()"; } @@ -87,12 +70,10 @@ Timestamp EPollPoller::poll(int timeoutMs, ChannelList* activeChannels) } void EPollPoller::fillActiveChannels(int numEvents, - ChannelList* activeChannels) const -{ + ChannelList *activeChannels) const { assert(implicit_cast(numEvents) <= events_.size()); - for (int i = 0; i < numEvents; ++i) - { - Channel* channel = static_cast(events_[i].data.ptr); + for (int i = 0; i < numEvents; ++i) { + Channel *channel = static_cast(events_[i].data.ptr); #ifndef NDEBUG int fd = channel->fd(); ChannelMap::const_iterator it = channels_.find(fd); @@ -104,22 +85,18 @@ void EPollPoller::fillActiveChannels(int numEvents, } } -void EPollPoller::updateChannel(Channel* channel) -{ +void EPollPoller::updateChannel(Channel *channel) { Poller::assertInLoopThread(); const int index = channel->index(); - LOG_TRACE << "fd = " << channel->fd() - << " events = " << channel->events() << " index = " << index; - if (index == kNew || index == kDeleted) - { + LOG_TRACE << "fd = " << channel->fd() << " events = " << channel->events() + << " index = " << index; + if (index == kNew || index == kDeleted) { // a new one, add with EPOLL_CTL_ADD int fd = channel->fd(); - if (index == kNew) - { + if (index == kNew) { assert(channels_.find(fd) == channels_.end()); channels_[fd] = channel; - } - else // index == kDeleted + } else // index == kDeleted { assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); @@ -127,29 +104,23 @@ void EPollPoller::updateChannel(Channel* channel) channel->set_index(kAdded); update(EPOLL_CTL_ADD, channel); - } - else - { + } else { // update existing one with EPOLL_CTL_MOD/DEL int fd = channel->fd(); (void)fd; assert(channels_.find(fd) != channels_.end()); assert(channels_[fd] == channel); assert(index == kAdded); - if (channel->isNoneEvent()) - { + if (channel->isNoneEvent()) { update(EPOLL_CTL_DEL, channel); channel->set_index(kDeleted); - } - else - { + } else { update(EPOLL_CTL_MOD, channel); } } } -void EPollPoller::removeChannel(Channel* channel) -{ +void EPollPoller::removeChannel(Channel *channel) { Poller::assertInLoopThread(); int fd = channel->fd(); LOG_TRACE << "fd = " << fd; @@ -162,47 +133,42 @@ void EPollPoller::removeChannel(Channel* channel) (void)n; assert(n == 1); - if (index == kAdded) - { + if (index == kAdded) { update(EPOLL_CTL_DEL, channel); } channel->set_index(kNew); } -void EPollPoller::update(int operation, Channel* channel) -{ +void EPollPoller::update(int operation, Channel *channel) { struct epoll_event event; memZero(&event, sizeof event); event.events = channel->events(); event.data.ptr = channel; int fd = channel->fd(); LOG_TRACE << "epoll_ctl op = " << operationToString(operation) - << " fd = " << fd << " event = { " << channel->eventsToString() << " }"; - if (::epoll_ctl(epollfd_, operation, fd, &event) < 0) - { - if (operation == EPOLL_CTL_DEL) - { - LOG_SYSERR << "epoll_ctl op =" << operationToString(operation) << " fd =" << fd; - } - else - { - LOG_SYSFATAL << "epoll_ctl op =" << operationToString(operation) << " fd =" << fd; + << " fd = " << fd << " event = { " << channel->eventsToString() + << " }"; + if (::epoll_ctl(epollfd_, operation, fd, &event) < 0) { + if (operation == EPOLL_CTL_DEL) { + LOG_SYSERR << "epoll_ctl op =" << operationToString(operation) + << " fd =" << fd; + } else { + LOG_SYSFATAL << "epoll_ctl op =" << operationToString(operation) + << " fd =" << fd; } } } -const char* EPollPoller::operationToString(int op) -{ - switch (op) - { - case EPOLL_CTL_ADD: - return "ADD"; - case EPOLL_CTL_DEL: - return "DEL"; - case EPOLL_CTL_MOD: - return "MOD"; - default: - assert(false && "ERROR op"); - return "Unknown Operation"; +const char *EPollPoller::operationToString(int op) { + switch (op) { + case EPOLL_CTL_ADD: + return "ADD"; + case EPOLL_CTL_DEL: + return "DEL"; + case EPOLL_CTL_MOD: + return "MOD"; + default: + assert(false && "ERROR op"); + return "Unknown Operation"; } } diff --git a/muduo/net/poller/EPollPoller.h b/muduo/net/poller/EPollPoller.h index c112f1881..b2ec75833 100644 --- a/muduo/net/poller/EPollPoller.h +++ b/muduo/net/poller/EPollPoller.h @@ -17,32 +17,28 @@ struct epoll_event; -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { /// /// IO Multiplexing with epoll(4). /// -class EPollPoller : public Poller -{ - public: - EPollPoller(EventLoop* loop); +class EPollPoller : public Poller { +public: + EPollPoller(EventLoop *loop); ~EPollPoller() override; - Timestamp poll(int timeoutMs, ChannelList* activeChannels) override; - void updateChannel(Channel* channel) override; - void removeChannel(Channel* channel) override; + Timestamp poll(int timeoutMs, ChannelList *activeChannels) override; + void updateChannel(Channel *channel) override; + void removeChannel(Channel *channel) override; - private: +private: static const int kInitEventListSize = 16; - static const char* operationToString(int op); + static const char *operationToString(int op); - void fillActiveChannels(int numEvents, - ChannelList* activeChannels) const; - void update(int operation, Channel* channel); + void fillActiveChannels(int numEvents, ChannelList *activeChannels) const; + void update(int operation, Channel *channel); typedef std::vector EventList; @@ -50,6 +46,6 @@ class EPollPoller : public Poller EventList events_; }; -} // namespace net -} // namespace muduo -#endif // MUDUO_NET_POLLER_EPOLLPOLLER_H +} // namespace net +} // namespace muduo +#endif // MUDUO_NET_POLLER_EPOLLPOLLER_H diff --git a/muduo/net/poller/PollPoller.cc b/muduo/net/poller/PollPoller.cc index 793307997..f3d0cc96a 100644 --- a/muduo/net/poller/PollPoller.cc +++ b/muduo/net/poller/PollPoller.cc @@ -19,32 +19,22 @@ using namespace muduo; using namespace muduo::net; -PollPoller::PollPoller(EventLoop* loop) - : Poller(loop) -{ -} +PollPoller::PollPoller(EventLoop *loop) : Poller(loop) {} PollPoller::~PollPoller() = default; -Timestamp PollPoller::poll(int timeoutMs, ChannelList* activeChannels) -{ +Timestamp PollPoller::poll(int timeoutMs, ChannelList *activeChannels) { // XXX pollfds_ shouldn't change int numEvents = ::poll(&*pollfds_.begin(), pollfds_.size(), timeoutMs); int savedErrno = errno; Timestamp now(Timestamp::now()); - if (numEvents > 0) - { + if (numEvents > 0) { LOG_TRACE << numEvents << " events happened"; fillActiveChannels(numEvents, activeChannels); - } - else if (numEvents == 0) - { + } else if (numEvents == 0) { LOG_TRACE << " nothing happened"; - } - else - { - if (savedErrno != EINTR) - { + } else { + if (savedErrno != EINTR) { errno = savedErrno; LOG_SYSERR << "PollPoller::poll()"; } @@ -53,17 +43,14 @@ Timestamp PollPoller::poll(int timeoutMs, ChannelList* activeChannels) } void PollPoller::fillActiveChannels(int numEvents, - ChannelList* activeChannels) const -{ + ChannelList *activeChannels) const { for (PollFdList::const_iterator pfd = pollfds_.begin(); - pfd != pollfds_.end() && numEvents > 0; ++pfd) - { - if (pfd->revents > 0) - { + pfd != pollfds_.end() && numEvents > 0; ++pfd) { + if (pfd->revents > 0) { --numEvents; ChannelMap::const_iterator ch = channels_.find(pfd->fd); assert(ch != channels_.end()); - Channel* channel = ch->second; + Channel *channel = ch->second; assert(channel->fd() == pfd->fd); channel->set_revents(pfd->revents); // pfd->revents = 0; @@ -72,12 +59,10 @@ void PollPoller::fillActiveChannels(int numEvents, } } -void PollPoller::updateChannel(Channel* channel) -{ +void PollPoller::updateChannel(Channel *channel) { Poller::assertInLoopThread(); LOG_TRACE << "fd = " << channel->fd() << " events = " << channel->events(); - if (channel->index() < 0) - { + if (channel->index() < 0) { // a new one, add to pollfds_ assert(channels_.find(channel->fd()) == channels_.end()); struct pollfd pfd; @@ -85,32 +70,28 @@ void PollPoller::updateChannel(Channel* channel) pfd.events = static_cast(channel->events()); pfd.revents = 0; pollfds_.push_back(pfd); - int idx = static_cast(pollfds_.size())-1; + int idx = static_cast(pollfds_.size()) - 1; channel->set_index(idx); channels_[pfd.fd] = channel; - } - else - { + } else { // update existing one assert(channels_.find(channel->fd()) != channels_.end()); assert(channels_[channel->fd()] == channel); int idx = channel->index(); assert(0 <= idx && idx < static_cast(pollfds_.size())); - struct pollfd& pfd = pollfds_[idx]; - assert(pfd.fd == channel->fd() || pfd.fd == -channel->fd()-1); + struct pollfd &pfd = pollfds_[idx]; + assert(pfd.fd == channel->fd() || pfd.fd == -channel->fd() - 1); pfd.fd = channel->fd(); pfd.events = static_cast(channel->events()); pfd.revents = 0; - if (channel->isNoneEvent()) - { + if (channel->isNoneEvent()) { // ignore this pollfd - pfd.fd = -channel->fd()-1; + pfd.fd = -channel->fd() - 1; } } } -void PollPoller::removeChannel(Channel* channel) -{ +void PollPoller::removeChannel(Channel *channel) { Poller::assertInLoopThread(); LOG_TRACE << "fd = " << channel->fd(); assert(channels_.find(channel->fd()) != channels_.end()); @@ -118,24 +99,21 @@ void PollPoller::removeChannel(Channel* channel) assert(channel->isNoneEvent()); int idx = channel->index(); assert(0 <= idx && idx < static_cast(pollfds_.size())); - const struct pollfd& pfd = pollfds_[idx]; (void)pfd; - assert(pfd.fd == -channel->fd()-1 && pfd.events == channel->events()); + const struct pollfd &pfd = pollfds_[idx]; + (void)pfd; + assert(pfd.fd == -channel->fd() - 1 && pfd.events == channel->events()); size_t n = channels_.erase(channel->fd()); - assert(n == 1); (void)n; - if (implicit_cast(idx) == pollfds_.size()-1) - { + assert(n == 1); + (void)n; + if (implicit_cast(idx) == pollfds_.size() - 1) { pollfds_.pop_back(); - } - else - { + } else { int channelAtEnd = pollfds_.back().fd; - iter_swap(pollfds_.begin()+idx, pollfds_.end()-1); - if (channelAtEnd < 0) - { - channelAtEnd = -channelAtEnd-1; + iter_swap(pollfds_.begin() + idx, pollfds_.end() - 1); + if (channelAtEnd < 0) { + channelAtEnd = -channelAtEnd - 1; } channels_[channelAtEnd]->set_index(idx); pollfds_.pop_back(); } } - diff --git a/muduo/net/poller/PollPoller.h b/muduo/net/poller/PollPoller.h index 465753435..6510a8e0c 100644 --- a/muduo/net/poller/PollPoller.h +++ b/muduo/net/poller/PollPoller.h @@ -17,33 +17,28 @@ struct pollfd; -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { /// /// IO Multiplexing with poll(2). /// -class PollPoller : public Poller -{ - public: - - PollPoller(EventLoop* loop); +class PollPoller : public Poller { +public: + PollPoller(EventLoop *loop); ~PollPoller() override; - Timestamp poll(int timeoutMs, ChannelList* activeChannels) override; - void updateChannel(Channel* channel) override; - void removeChannel(Channel* channel) override; + Timestamp poll(int timeoutMs, ChannelList *activeChannels) override; + void updateChannel(Channel *channel) override; + void removeChannel(Channel *channel) override; - private: - void fillActiveChannels(int numEvents, - ChannelList* activeChannels) const; +private: + void fillActiveChannels(int numEvents, ChannelList *activeChannels) const; typedef std::vector PollFdList; PollFdList pollfds_; }; -} // namespace net -} // namespace muduo -#endif // MUDUO_NET_POLLER_POLLPOLLER_H +} // namespace net +} // namespace muduo +#endif // MUDUO_NET_POLLER_POLLPOLLER_H diff --git a/muduo/net/protobuf/BufferStream.h b/muduo/net/protobuf/BufferStream.h index 322bc44ab..8d3dc4d16 100644 --- a/muduo/net/protobuf/BufferStream.h +++ b/muduo/net/protobuf/BufferStream.h @@ -9,26 +9,20 @@ #pragma once #include "muduo/net/Buffer.h" #include -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { // FIXME: // class BufferInputStream : google::protobuf::io::ZeroCopyInputStream // { // }; -class BufferOutputStream : public google::protobuf::io::ZeroCopyOutputStream -{ - public: - BufferOutputStream(Buffer* buf) - : buffer_(CHECK_NOTNULL(buf)), - originalSize_(buffer_->readableBytes()) - { - } +class BufferOutputStream : public google::protobuf::io::ZeroCopyOutputStream { +public: + BufferOutputStream(Buffer *buf) + : buffer_(CHECK_NOTNULL(buf)), originalSize_(buffer_->readableBytes()) {} - virtual bool Next(void** data, int* size) // override + virtual bool Next(void **data, int *size) // override { buffer_->ensureWritableBytes(4096); *data = buffer_->beginWrite(); @@ -47,10 +41,10 @@ class BufferOutputStream : public google::protobuf::io::ZeroCopyOutputStream return buffer_->readableBytes() - originalSize_; } - private: - Buffer* buffer_; +private: + Buffer *buffer_; size_t originalSize_; }; -} -} +} // namespace net +} // namespace muduo diff --git a/muduo/net/protobuf/ProtobufCodecLite.cc b/muduo/net/protobuf/ProtobufCodecLite.cc index 9d406ee20..873685001 100644 --- a/muduo/net/protobuf/ProtobufCodecLite.cc +++ b/muduo/net/protobuf/ProtobufCodecLite.cc @@ -20,224 +20,204 @@ using namespace muduo; using namespace muduo::net; -namespace -{ - int ProtobufVersionCheck() - { - GOOGLE_PROTOBUF_VERIFY_VERSION; - return 0; - } - int __attribute__ ((unused)) dummy = ProtobufVersionCheck(); +namespace { +int ProtobufVersionCheck() { + GOOGLE_PROTOBUF_VERIFY_VERSION; + return 0; } +int __attribute__((unused)) dummy = ProtobufVersionCheck(); +} // namespace -void ProtobufCodecLite::send(const TcpConnectionPtr& conn, - const ::google::protobuf::Message& message) -{ +void ProtobufCodecLite::send(const TcpConnectionPtr &conn, + const ::google::protobuf::Message &message) { // FIXME: serialize to TcpConnection::outputBuffer() muduo::net::Buffer buf; fillEmptyBuffer(&buf, message); conn->send(&buf); } -void ProtobufCodecLite::fillEmptyBuffer(muduo::net::Buffer* buf, - const google::protobuf::Message& message) -{ +void ProtobufCodecLite::fillEmptyBuffer( + muduo::net::Buffer *buf, const google::protobuf::Message &message) { assert(buf->readableBytes() == 0); // FIXME: can we move serialization & checksum to other thread? buf->append(tag_); int byte_size = serializeToBuffer(message, buf); - int32_t checkSum = checksum(buf->peek(), static_cast(buf->readableBytes())); + int32_t checkSum = + checksum(buf->peek(), static_cast(buf->readableBytes())); buf->appendInt32(checkSum); - assert(buf->readableBytes() == tag_.size() + byte_size + kChecksumLen); (void) byte_size; - int32_t len = sockets::hostToNetwork32(static_cast(buf->readableBytes())); + assert(buf->readableBytes() == tag_.size() + byte_size + kChecksumLen); + (void)byte_size; + int32_t len = + sockets::hostToNetwork32(static_cast(buf->readableBytes())); buf->prepend(&len, sizeof len); } -void ProtobufCodecLite::onMessage(const TcpConnectionPtr& conn, - Buffer* buf, - Timestamp receiveTime) -{ - while (buf->readableBytes() >= static_cast(kMinMessageLen+kHeaderLen)) - { +void ProtobufCodecLite::onMessage(const TcpConnectionPtr &conn, Buffer *buf, + Timestamp receiveTime) { + while (buf->readableBytes() >= + static_cast(kMinMessageLen + kHeaderLen)) { const int32_t len = buf->peekInt32(); - if (len > kMaxMessageLen || len < kMinMessageLen) - { + if (len > kMaxMessageLen || len < kMinMessageLen) { errorCallback_(conn, buf, receiveTime, kInvalidLength); break; - } - else if (buf->readableBytes() >= implicit_cast(kHeaderLen+len)) - { - if (rawCb_ && !rawCb_(conn, StringPiece(buf->peek(), kHeaderLen+len), receiveTime)) - { - buf->retrieve(kHeaderLen+len); + } else if (buf->readableBytes() >= + implicit_cast(kHeaderLen + len)) { + if (rawCb_ && !rawCb_(conn, StringPiece(buf->peek(), kHeaderLen + len), + receiveTime)) { + buf->retrieve(kHeaderLen + len); continue; } MessagePtr message(prototype_->New()); // FIXME: can we move deserialization & callback to other thread? - ErrorCode errorCode = parse(buf->peek()+kHeaderLen, len, message.get()); - if (errorCode == kNoError) - { + ErrorCode errorCode = parse(buf->peek() + kHeaderLen, len, message.get()); + if (errorCode == kNoError) { // FIXME: try { } catch (...) { } messageCallback_(conn, message, receiveTime); - buf->retrieve(kHeaderLen+len); - } - else - { + buf->retrieve(kHeaderLen + len); + } else { errorCallback_(conn, buf, receiveTime, errorCode); break; } - } - else - { + } else { break; } } } -bool ProtobufCodecLite::parseFromBuffer(StringPiece buf, google::protobuf::Message* message) -{ +bool ProtobufCodecLite::parseFromBuffer(StringPiece buf, + google::protobuf::Message *message) { return message->ParseFromArray(buf.data(), buf.size()); } -int ProtobufCodecLite::serializeToBuffer(const google::protobuf::Message& message, Buffer* buf) -{ +int ProtobufCodecLite::serializeToBuffer( + const google::protobuf::Message &message, Buffer *buf) { // TODO: use BufferOutputStream // BufferOutputStream os(buf); // message.SerializeToZeroCopyStream(&os); // return static_cast(os.ByteCount()); - // code copied from MessageLite::SerializeToArray() and MessageLite::SerializePartialToArray(). - GOOGLE_DCHECK(message.IsInitialized()) << InitializationErrorMessage("serialize", message); + // code copied from MessageLite::SerializeToArray() and + // MessageLite::SerializePartialToArray(). + GOOGLE_DCHECK(message.IsInitialized()) + << InitializationErrorMessage("serialize", message); /** - * 'ByteSize()' of message is deprecated in Protocol Buffers v3.4.0 firstly. But, till to v3.11.0, it just getting start to be marked by '__attribute__((deprecated()))'. - * So, here, v3.9.2 is selected as maximum version using 'ByteSize()' to avoid potential effect for previous muduo code/projects as far as possible. - * Note: All information above just INFER from - * 1) https://github.com/protocolbuffers/protobuf/releases/tag/v3.4.0 - * 2) MACRO in file 'include/google/protobuf/port_def.inc'. eg. '#define PROTOBUF_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))'. - * In addition, usage of 'ToIntSize()' comes from Impl of ByteSize() in new version's Protocol Buffers. + * 'ByteSize()' of message is deprecated in Protocol Buffers v3.4.0 firstly. + * But, till to v3.11.0, it just getting start to be marked by + * '__attribute__((deprecated()))'. So, here, v3.9.2 is selected as maximum + * version using 'ByteSize()' to avoid potential effect for previous muduo + * code/projects as far as possible. Note: All information above just INFER + * from 1) https://github.com/protocolbuffers/protobuf/releases/tag/v3.4.0 + * 2) MACRO in file 'include/google/protobuf/port_def.inc'. eg. '#define + * PROTOBUF_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))'. In + * addition, usage of 'ToIntSize()' comes from Impl of ByteSize() in new + * version's Protocol Buffers. */ - #if GOOGLE_PROTOBUF_VERSION > 3009002 - int byte_size = google::protobuf::internal::ToIntSize(message.ByteSizeLong()); - #else - int byte_size = message.ByteSize(); - #endif +#if GOOGLE_PROTOBUF_VERSION > 3009002 + int byte_size = google::protobuf::internal::ToIntSize(message.ByteSizeLong()); +#else + int byte_size = message.ByteSize(); +#endif buf->ensureWritableBytes(byte_size + kChecksumLen); - uint8_t* start = reinterpret_cast(buf->beginWrite()); - uint8_t* end = message.SerializeWithCachedSizesToArray(start); - if (end - start != byte_size) - { - #if GOOGLE_PROTOBUF_VERSION > 3009002 - ByteSizeConsistencyError(byte_size, google::protobuf::internal::ToIntSize(message.ByteSizeLong()), static_cast(end - start)); - #else - ByteSizeConsistencyError(byte_size, message.ByteSize(), static_cast(end - start)); - #endif + uint8_t *start = reinterpret_cast(buf->beginWrite()); + uint8_t *end = message.SerializeWithCachedSizesToArray(start); + if (end - start != byte_size) { +#if GOOGLE_PROTOBUF_VERSION > 3009002 + ByteSizeConsistencyError( + byte_size, + google::protobuf::internal::ToIntSize(message.ByteSizeLong()), + static_cast(end - start)); +#else + ByteSizeConsistencyError(byte_size, message.ByteSize(), + static_cast(end - start)); +#endif } buf->hasWritten(byte_size); return byte_size; } -namespace -{ - const string kNoErrorStr = "NoError"; - const string kInvalidLengthStr = "InvalidLength"; - const string kCheckSumErrorStr = "CheckSumError"; - const string kInvalidNameLenStr = "InvalidNameLen"; - const string kUnknownMessageTypeStr = "UnknownMessageType"; - const string kParseErrorStr = "ParseError"; - const string kUnknownErrorStr = "UnknownError"; -} - -const string& ProtobufCodecLite::errorCodeToString(ErrorCode errorCode) -{ - switch (errorCode) - { - case kNoError: - return kNoErrorStr; - case kInvalidLength: - return kInvalidLengthStr; - case kCheckSumError: - return kCheckSumErrorStr; - case kInvalidNameLen: - return kInvalidNameLenStr; - case kUnknownMessageType: - return kUnknownMessageTypeStr; - case kParseError: - return kParseErrorStr; - default: - return kUnknownErrorStr; +namespace { +const string kNoErrorStr = "NoError"; +const string kInvalidLengthStr = "InvalidLength"; +const string kCheckSumErrorStr = "CheckSumError"; +const string kInvalidNameLenStr = "InvalidNameLen"; +const string kUnknownMessageTypeStr = "UnknownMessageType"; +const string kParseErrorStr = "ParseError"; +const string kUnknownErrorStr = "UnknownError"; +} // namespace + +const string &ProtobufCodecLite::errorCodeToString(ErrorCode errorCode) { + switch (errorCode) { + case kNoError: + return kNoErrorStr; + case kInvalidLength: + return kInvalidLengthStr; + case kCheckSumError: + return kCheckSumErrorStr; + case kInvalidNameLen: + return kInvalidNameLenStr; + case kUnknownMessageType: + return kUnknownMessageTypeStr; + case kParseError: + return kParseErrorStr; + default: + return kUnknownErrorStr; } } -void ProtobufCodecLite::defaultErrorCallback(const TcpConnectionPtr& conn, - Buffer* buf, - Timestamp, - ErrorCode errorCode) -{ - LOG_ERROR << "ProtobufCodecLite::defaultErrorCallback - " << errorCodeToString(errorCode); - if (conn && conn->connected()) - { +void ProtobufCodecLite::defaultErrorCallback(const TcpConnectionPtr &conn, + Buffer *buf, Timestamp, + ErrorCode errorCode) { + LOG_ERROR << "ProtobufCodecLite::defaultErrorCallback - " + << errorCodeToString(errorCode); + if (conn && conn->connected()) { conn->shutdown(); } } -int32_t ProtobufCodecLite::asInt32(const char* buf) -{ +int32_t ProtobufCodecLite::asInt32(const char *buf) { int32_t be32 = 0; ::memcpy(&be32, buf, sizeof(be32)); return sockets::networkToHost32(be32); } -int32_t ProtobufCodecLite::checksum(const void* buf, int len) -{ +int32_t ProtobufCodecLite::checksum(const void *buf, int len) { return static_cast( - ::adler32(1, static_cast(buf), len)); + ::adler32(1, static_cast(buf), len)); } -bool ProtobufCodecLite::validateChecksum(const char* buf, int len) -{ +bool ProtobufCodecLite::validateChecksum(const char *buf, int len) { // check sum int32_t expectedCheckSum = asInt32(buf + len - kChecksumLen); int32_t checkSum = checksum(buf, len - kChecksumLen); return checkSum == expectedCheckSum; } -ProtobufCodecLite::ErrorCode ProtobufCodecLite::parse(const char* buf, - int len, - ::google::protobuf::Message* message) -{ +ProtobufCodecLite::ErrorCode +ProtobufCodecLite::parse(const char *buf, int len, + ::google::protobuf::Message *message) { ErrorCode error = kNoError; - if (validateChecksum(buf, len)) - { - if (memcmp(buf, tag_.data(), tag_.size()) == 0) - { + if (validateChecksum(buf, len)) { + if (memcmp(buf, tag_.data(), tag_.size()) == 0) { // parse from buffer - const char* data = buf + tag_.size(); + const char *data = buf + tag_.size(); int32_t dataLen = len - kChecksumLen - static_cast(tag_.size()); - if (parseFromBuffer(StringPiece(data, dataLen), message)) - { + if (parseFromBuffer(StringPiece(data, dataLen), message)) { error = kNoError; - } - else - { + } else { error = kParseError; } - } - else - { + } else { error = kUnknownMessageType; } - } - else - { + } else { error = kCheckSumError; } return error; } - diff --git a/muduo/net/protobuf/ProtobufCodecLite.h b/muduo/net/protobuf/ProtobufCodecLite.h index 134ee7b50..92b06740d 100644 --- a/muduo/net/protobuf/ProtobufCodecLite.h +++ b/muduo/net/protobuf/ProtobufCodecLite.h @@ -14,26 +14,22 @@ #ifndef MUDUO_NET_PROTOBUF_PROTOBUFCODECLITE_H #define MUDUO_NET_PROTOBUF_PROTOBUFCODECLITE_H -#include "muduo/base/noncopyable.h" #include "muduo/base/StringPiece.h" #include "muduo/base/Timestamp.h" +#include "muduo/base/noncopyable.h" #include "muduo/net/Callbacks.h" #include #include -namespace google -{ -namespace protobuf -{ +namespace google { +namespace protobuf { class Message; } -} +} // namespace google -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { typedef std::shared_ptr MessagePtr; @@ -47,15 +43,14 @@ typedef std::shared_ptr MessagePtr; // checksum 4-byte adler32 of tag+payload // // This is an internal class, you should use ProtobufCodecT instead. -class ProtobufCodecLite : noncopyable -{ - public: +class ProtobufCodecLite : noncopyable { +public: const static int kHeaderLen = sizeof(int32_t); const static int kChecksumLen = sizeof(int32_t); - const static int kMaxMessageLen = 64*1024*1024; // same as codec_stream.h kDefaultTotalBytesLimit + const static int kMaxMessageLen = + 64 * 1024 * 1024; // same as codec_stream.h kDefaultTotalBytesLimit - enum ErrorCode - { + enum ErrorCode { kNoError = 0, kInvalidLength, kCheckSumError, @@ -65,63 +60,57 @@ class ProtobufCodecLite : noncopyable }; // return false to stop parsing protobuf message - typedef std::function RawMessageCallback; + typedef std::function + RawMessageCallback; - typedef std::function ProtobufMessageCallback; + typedef std::function + ProtobufMessageCallback; - typedef std::function ErrorCallback; + typedef std::function + ErrorCallback; - ProtobufCodecLite(const ::google::protobuf::Message* prototype, + ProtobufCodecLite(const ::google::protobuf::Message *prototype, StringPiece tagArg, - const ProtobufMessageCallback& messageCb, - const RawMessageCallback& rawCb = RawMessageCallback(), - const ErrorCallback& errorCb = defaultErrorCallback) - : prototype_(prototype), - tag_(tagArg.as_string()), - messageCallback_(messageCb), - rawCb_(rawCb), - errorCallback_(errorCb), - kMinMessageLen(tagArg.size() + kChecksumLen) - { - } + const ProtobufMessageCallback &messageCb, + const RawMessageCallback &rawCb = RawMessageCallback(), + const ErrorCallback &errorCb = defaultErrorCallback) + : prototype_(prototype), tag_(tagArg.as_string()), + messageCallback_(messageCb), rawCb_(rawCb), errorCallback_(errorCb), + kMinMessageLen(tagArg.size() + kChecksumLen) {} virtual ~ProtobufCodecLite() = default; - const string& tag() const { return tag_; } + const string &tag() const { return tag_; } - void send(const TcpConnectionPtr& conn, - const ::google::protobuf::Message& message); + void send(const TcpConnectionPtr &conn, + const ::google::protobuf::Message &message); - void onMessage(const TcpConnectionPtr& conn, - Buffer* buf, + void onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp receiveTime); - virtual bool parseFromBuffer(StringPiece buf, google::protobuf::Message* message); - virtual int serializeToBuffer(const google::protobuf::Message& message, Buffer* buf); + virtual bool parseFromBuffer(StringPiece buf, + google::protobuf::Message *message); + virtual int serializeToBuffer(const google::protobuf::Message &message, + Buffer *buf); - static const string& errorCodeToString(ErrorCode errorCode); + static const string &errorCodeToString(ErrorCode errorCode); // public for unit tests - ErrorCode parse(const char* buf, int len, ::google::protobuf::Message* message); - void fillEmptyBuffer(muduo::net::Buffer* buf, const google::protobuf::Message& message); - - static int32_t checksum(const void* buf, int len); - static bool validateChecksum(const char* buf, int len); - static int32_t asInt32(const char* buf); - static void defaultErrorCallback(const TcpConnectionPtr&, - Buffer*, - Timestamp, - ErrorCode); - - private: - const ::google::protobuf::Message* prototype_; + ErrorCode parse(const char *buf, int len, + ::google::protobuf::Message *message); + void fillEmptyBuffer(muduo::net::Buffer *buf, + const google::protobuf::Message &message); + + static int32_t checksum(const void *buf, int len); + static bool validateChecksum(const char *buf, int len); + static int32_t asInt32(const char *buf); + static void defaultErrorCallback(const TcpConnectionPtr &, Buffer *, + Timestamp, ErrorCode); + +private: + const ::google::protobuf::Message *prototype_; const string tag_; ProtobufMessageCallback messageCallback_; RawMessageCallback rawCb_; @@ -129,64 +118,59 @@ class ProtobufCodecLite : noncopyable const int kMinMessageLen; }; -template // TAG must be a variable with external linkage, not a string literal -class ProtobufCodecLiteT -{ - static_assert(std::is_base_of::value, "CODEC should be derived from ProtobufCodecLite"); - public: +template // TAG must be a variable with external + // linkage, not a string literal +class ProtobufCodecLiteT { + static_assert(std::is_base_of::value, + "CODEC should be derived from ProtobufCodecLite"); + +public: typedef std::shared_ptr ConcreteMessagePtr; - typedef std::function ProtobufMessageCallback; + typedef std::function + ProtobufMessageCallback; typedef ProtobufCodecLite::RawMessageCallback RawMessageCallback; typedef ProtobufCodecLite::ErrorCallback ErrorCallback; - explicit ProtobufCodecLiteT(const ProtobufMessageCallback& messageCb, - const RawMessageCallback& rawCb = RawMessageCallback(), - const ErrorCallback& errorCb = ProtobufCodecLite::defaultErrorCallback) - : messageCallback_(messageCb), - codec_(&MSG::default_instance(), - TAG, - std::bind(&ProtobufCodecLiteT::onRpcMessage, this, _1, _2, _3), - rawCb, - errorCb) - { - } + explicit ProtobufCodecLiteT( + const ProtobufMessageCallback &messageCb, + const RawMessageCallback &rawCb = RawMessageCallback(), + const ErrorCallback &errorCb = ProtobufCodecLite::defaultErrorCallback) + : messageCallback_(messageCb), + codec_(&MSG::default_instance(), TAG, + std::bind(&ProtobufCodecLiteT::onRpcMessage, this, _1, _2, _3), + rawCb, errorCb) {} - const string& tag() const { return codec_.tag(); } + const string &tag() const { return codec_.tag(); } - void send(const TcpConnectionPtr& conn, - const MSG& message) - { + void send(const TcpConnectionPtr &conn, const MSG &message) { codec_.send(conn, message); } - void onMessage(const TcpConnectionPtr& conn, - Buffer* buf, - Timestamp receiveTime) - { + void onMessage(const TcpConnectionPtr &conn, Buffer *buf, + Timestamp receiveTime) { codec_.onMessage(conn, buf, receiveTime); } // internal - void onRpcMessage(const TcpConnectionPtr& conn, - const MessagePtr& message, - Timestamp receiveTime) - { - messageCallback_(conn, ::muduo::down_pointer_cast(message), receiveTime); + void onRpcMessage(const TcpConnectionPtr &conn, const MessagePtr &message, + Timestamp receiveTime) { + messageCallback_(conn, ::muduo::down_pointer_cast(message), + receiveTime); } - void fillEmptyBuffer(muduo::net::Buffer* buf, const MSG& message) - { + void fillEmptyBuffer(muduo::net::Buffer *buf, const MSG &message) { codec_.fillEmptyBuffer(buf, message); } - private: +private: ProtobufMessageCallback messageCallback_; CODEC codec_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_PROTOBUF_PROTOBUFCODECLITE_H +#endif // MUDUO_NET_PROTOBUF_PROTOBUFCODECLITE_H diff --git a/muduo/net/protorpc/RpcChannel.cc b/muduo/net/protorpc/RpcChannel.cc index d18e081fc..97c2cee82 100644 --- a/muduo/net/protorpc/RpcChannel.cc +++ b/muduo/net/protorpc/RpcChannel.cc @@ -17,42 +17,36 @@ using namespace muduo; using namespace muduo::net; RpcChannel::RpcChannel() - : codec_(std::bind(&RpcChannel::onRpcMessage, this, _1, _2, _3)), - services_(NULL) -{ + : codec_(std::bind(&RpcChannel::onRpcMessage, this, _1, _2, _3)), + services_(NULL) { LOG_INFO << "RpcChannel::ctor - " << this; } -RpcChannel::RpcChannel(const TcpConnectionPtr& conn) - : codec_(std::bind(&RpcChannel::onRpcMessage, this, _1, _2, _3)), - conn_(conn), - services_(NULL) -{ +RpcChannel::RpcChannel(const TcpConnectionPtr &conn) + : codec_(std::bind(&RpcChannel::onRpcMessage, this, _1, _2, _3)), + conn_(conn), services_(NULL) { LOG_INFO << "RpcChannel::ctor - " << this; } -RpcChannel::~RpcChannel() -{ +RpcChannel::~RpcChannel() { LOG_INFO << "RpcChannel::dtor - " << this; - for (const auto& outstanding : outstandings_) - { + for (const auto &outstanding : outstandings_) { OutstandingCall out = outstanding.second; delete out.response; delete out.done; } } - // Call the given method of the remote service. The signature of this - // procedure looks the same as Service::CallMethod(), but the requirements - // are less strict in one important way: the request and response objects - // need not be of any specific class as long as their descriptors are - // method->input_type() and method->output_type(). -void RpcChannel::CallMethod(const ::google::protobuf::MethodDescriptor* method, - google::protobuf::RpcController* controller, - const ::google::protobuf::Message* request, - ::google::protobuf::Message* response, - ::google::protobuf::Closure* done) -{ +// Call the given method of the remote service. The signature of this +// procedure looks the same as Service::CallMethod(), but the requirements +// are less strict in one important way: the request and response objects +// need not be of any specific class as long as their descriptors are +// method->input_type() and method->output_type(). +void RpcChannel::CallMethod(const ::google::protobuf::MethodDescriptor *method, + google::protobuf::RpcController *controller, + const ::google::protobuf::Message *request, + ::google::protobuf::Message *response, + ::google::protobuf::Closure *done) { RpcMessage message; message.set_type(REQUEST); int64_t id = id_.incrementAndGet(); @@ -61,119 +55,99 @@ void RpcChannel::CallMethod(const ::google::protobuf::MethodDescriptor* method, message.set_method(method->name()); message.set_request(request->SerializeAsString()); // FIXME: error check - OutstandingCall out = { response, done }; + OutstandingCall out = {response, done}; { - MutexLockGuard lock(mutex_); - outstandings_[id] = out; + MutexLockGuard lock(mutex_); + outstandings_[id] = out; } codec_.send(conn_, message); } -void RpcChannel::onMessage(const TcpConnectionPtr& conn, - Buffer* buf, - Timestamp receiveTime) -{ +void RpcChannel::onMessage(const TcpConnectionPtr &conn, Buffer *buf, + Timestamp receiveTime) { codec_.onMessage(conn, buf, receiveTime); } -void RpcChannel::onRpcMessage(const TcpConnectionPtr& conn, - const RpcMessagePtr& messagePtr, - Timestamp receiveTime) -{ +void RpcChannel::onRpcMessage(const TcpConnectionPtr &conn, + const RpcMessagePtr &messagePtr, + Timestamp receiveTime) { assert(conn == conn_); - //printf("%s\n", message.DebugString().c_str()); - RpcMessage& message = *messagePtr; - if (message.type() == RESPONSE) - { + // printf("%s\n", message.DebugString().c_str()); + RpcMessage &message = *messagePtr; + if (message.type() == RESPONSE) { int64_t id = message.id(); assert(message.has_response() || message.has_error()); - OutstandingCall out = { NULL, NULL }; + OutstandingCall out = {NULL, NULL}; { MutexLockGuard lock(mutex_); std::map::iterator it = outstandings_.find(id); - if (it != outstandings_.end()) - { + if (it != outstandings_.end()) { out = it->second; outstandings_.erase(it); } } - if (out.response) - { + if (out.response) { std::unique_ptr d(out.response); - if (message.has_response()) - { + if (message.has_response()) { out.response->ParseFromString(message.response()); } - if (out.done) - { + if (out.done) { out.done->Run(); } } - } - else if (message.type() == REQUEST) - { + } else if (message.type() == REQUEST) { // FIXME: extract to a function ErrorCode error = WRONG_PROTO; - if (services_) - { - std::map::const_iterator it = services_->find(message.service()); - if (it != services_->end()) - { - google::protobuf::Service* service = it->second; + if (services_) { + std::map::const_iterator it = + services_->find(message.service()); + if (it != services_->end()) { + google::protobuf::Service *service = it->second; assert(service != NULL); - const google::protobuf::ServiceDescriptor* desc = service->GetDescriptor(); - const google::protobuf::MethodDescriptor* method - = desc->FindMethodByName(message.method()); - if (method) - { - std::unique_ptr request(service->GetRequestPrototype(method).New()); - if (request->ParseFromString(message.request())) - { - google::protobuf::Message* response = service->GetResponsePrototype(method).New(); + const google::protobuf::ServiceDescriptor *desc = + service->GetDescriptor(); + const google::protobuf::MethodDescriptor *method = + desc->FindMethodByName(message.method()); + if (method) { + std::unique_ptr request( + service->GetRequestPrototype(method).New()); + if (request->ParseFromString(message.request())) { + google::protobuf::Message *response = + service->GetResponsePrototype(method).New(); // response is deleted in doneCallback int64_t id = message.id(); - service->CallMethod(method, NULL, get_pointer(request), response, - NewCallback(this, &RpcChannel::doneCallback, response, id)); + service->CallMethod( + method, NULL, get_pointer(request), response, + NewCallback(this, &RpcChannel::doneCallback, response, id)); error = NO_ERROR; - } - else - { + } else { error = INVALID_REQUEST; } - } - else - { + } else { error = NO_METHOD; } - } - else - { + } else { error = NO_SERVICE; } - } - else - { + } else { error = NO_SERVICE; } - if (error != NO_ERROR) - { + if (error != NO_ERROR) { RpcMessage response; response.set_type(RESPONSE); response.set_id(message.id()); response.set_error(error); codec_.send(conn_, response); } - } - else if (message.type() == ERROR) - { + } else if (message.type() == ERROR) { } } -void RpcChannel::doneCallback(::google::protobuf::Message* response, int64_t id) -{ +void RpcChannel::doneCallback(::google::protobuf::Message *response, + int64_t id) { std::unique_ptr d(response); RpcMessage message; message.set_type(RESPONSE); @@ -181,4 +155,3 @@ void RpcChannel::doneCallback(::google::protobuf::Message* response, int64_t id) message.set_response(response->SerializeAsString()); // FIXME: error check codec_.send(conn_, message); } - diff --git a/muduo/net/protorpc/RpcChannel.h b/muduo/net/protorpc/RpcChannel.h index 172b41ebe..245627990 100644 --- a/muduo/net/protorpc/RpcChannel.h +++ b/muduo/net/protorpc/RpcChannel.h @@ -60,79 +60,69 @@ namespace google { namespace protobuf { // Defined in other files. -class Descriptor; // descriptor.h -class ServiceDescriptor; // descriptor.h -class MethodDescriptor; // descriptor.h -class Message; // message.h +class Descriptor; // descriptor.h +class ServiceDescriptor; // descriptor.h +class MethodDescriptor; // descriptor.h +class Message; // message.h class Closure; class RpcController; class Service; -} // namespace protobuf -} // namespace google +} // namespace protobuf +} // namespace google - -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { // Abstract interface for an RPC channel. An RpcChannel represents a // communication line to a Service which can be used to call that Service's // methods. The Service may be running on another machine. Normally, you -// should not call an RpcChannel directly, but instead construct a stub Service -// wrapping it. Example: +// should not call an RpcChannel directly, but instead construct a stub +// Service wrapping it. Example: // FIXME: update here // RpcChannel* channel = new MyRpcChannel("remotehost.example.com:1234"); // MyService* service = new MyService::Stub(channel); // service->MyMethod(request, &response, callback); -class RpcChannel : public ::google::protobuf::RpcChannel -{ - public: +class RpcChannel : public ::google::protobuf::RpcChannel { +public: RpcChannel(); - explicit RpcChannel(const TcpConnectionPtr& conn); + explicit RpcChannel(const TcpConnectionPtr &conn); ~RpcChannel() override; - void setConnection(const TcpConnectionPtr& conn) - { - conn_ = conn; - } + void setConnection(const TcpConnectionPtr &conn) { conn_ = conn; } - void setServices(const std::map* services) - { + void setServices( + const std::map *services) { services_ = services; } // Call the given method of the remote service. The signature of this - // procedure looks the same as Service::CallMethod(), but the requirements - // are less strict in one important way: the request and response objects - // need not be of any specific class as long as their descriptors are - // method->input_type() and method->output_type(). - void CallMethod(const ::google::protobuf::MethodDescriptor* method, - ::google::protobuf::RpcController* controller, - const ::google::protobuf::Message* request, - ::google::protobuf::Message* response, - ::google::protobuf::Closure* done) override; - - void onMessage(const TcpConnectionPtr& conn, - Buffer* buf, + // procedure looks the same as Service::CallMethod(), but the + // requirements are less strict in one important way: the request and + // response objects need not be of any specific class as long as their + // descriptors are method->input_type() and method->output_type(). + void CallMethod(const ::google::protobuf::MethodDescriptor *method, + ::google::protobuf::RpcController *controller, + const ::google::protobuf::Message *request, + ::google::protobuf::Message *response, + ::google::protobuf::Closure *done) override; + + void onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp receiveTime); - private: - void onRpcMessage(const TcpConnectionPtr& conn, - const RpcMessagePtr& messagePtr, - Timestamp receiveTime); +private: + void onRpcMessage(const TcpConnectionPtr &conn, + const RpcMessagePtr &messagePtr, Timestamp receiveTime); - void doneCallback(::google::protobuf::Message* response, int64_t id); + void doneCallback(::google::protobuf::Message *response, int64_t id); - struct OutstandingCall - { - ::google::protobuf::Message* response; - ::google::protobuf::Closure* done; + struct OutstandingCall { + ::google::protobuf::Message *response; + ::google::protobuf::Closure *done; }; RpcCodec codec_; @@ -142,11 +132,11 @@ class RpcChannel : public ::google::protobuf::RpcChannel MutexLock mutex_; std::map outstandings_ GUARDED_BY(mutex_); - const std::map* services_; + const std::map *services_; }; typedef std::shared_ptr RpcChannelPtr; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_PROTORPC_RPCCHANNEL_H +#endif // MUDUO_NET_PROTORPC_RPCCHANNEL_H diff --git a/muduo/net/protorpc/RpcCodec.cc b/muduo/net/protorpc/RpcCodec.cc index e466e1ddc..82a7b2a0e 100644 --- a/muduo/net/protorpc/RpcCodec.cc +++ b/muduo/net/protorpc/RpcCodec.cc @@ -12,26 +12,22 @@ #include "muduo/net/Endian.h" #include "muduo/net/TcpConnection.h" -#include "muduo/net/protorpc/rpc.pb.h" #include "muduo/net/protorpc/google-inl.h" +#include "muduo/net/protorpc/rpc.pb.h" using namespace muduo; using namespace muduo::net; -namespace -{ - int ProtobufVersionCheck() - { - GOOGLE_PROTOBUF_VERIFY_VERSION; - return 0; - } - int dummy __attribute__ ((unused)) = ProtobufVersionCheck(); +namespace { +int ProtobufVersionCheck() { + GOOGLE_PROTOBUF_VERIFY_VERSION; + return 0; } +int dummy __attribute__((unused)) = ProtobufVersionCheck(); +} // namespace -namespace muduo -{ -namespace net -{ -const char rpctag [] = "RPC0"; -} +namespace muduo { +namespace net { +const char rpctag[] = "RPC0"; } +} // namespace muduo diff --git a/muduo/net/protorpc/RpcCodec.h b/muduo/net/protorpc/RpcCodec.h index 07fab9cfd..f7718e012 100644 --- a/muduo/net/protorpc/RpcCodec.h +++ b/muduo/net/protorpc/RpcCodec.h @@ -14,10 +14,8 @@ #include "muduo/base/Timestamp.h" #include "muduo/net/protobuf/ProtobufCodecLite.h" -namespace muduo -{ -namespace net -{ +namespace muduo { +namespace net { class Buffer; class TcpConnection; @@ -25,7 +23,7 @@ typedef std::shared_ptr TcpConnectionPtr; class RpcMessage; typedef std::shared_ptr RpcMessagePtr; -extern const char rpctag[];// = "RPC0"; +extern const char rpctag[]; // = "RPC0"; // wire format // @@ -39,7 +37,7 @@ extern const char rpctag[];// = "RPC0"; typedef ProtobufCodecLiteT RpcCodec; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_PROTORPC_RPCCODEC_H +#endif // MUDUO_NET_PROTORPC_RPCCODEC_H diff --git a/muduo/net/protorpc/RpcCodec_test.cc b/muduo/net/protorpc/RpcCodec_test.cc index 645fffdb9..0bde88666 100644 --- a/muduo/net/protorpc/RpcCodec_test.cc +++ b/muduo/net/protorpc/RpcCodec_test.cc @@ -1,33 +1,26 @@ #undef NDEBUG +#include "muduo/net/Buffer.h" +#include "muduo/net/protobuf/ProtobufCodecLite.h" #include "muduo/net/protorpc/RpcCodec.h" #include "muduo/net/protorpc/rpc.pb.h" -#include "muduo/net/protobuf/ProtobufCodecLite.h" -#include "muduo/net/Buffer.h" #include using namespace muduo; using namespace muduo::net; -void rpcMessageCallback(const TcpConnectionPtr&, - const RpcMessagePtr&, - Timestamp) -{ -} +void rpcMessageCallback(const TcpConnectionPtr &, const RpcMessagePtr &, + Timestamp) {} MessagePtr g_msgptr; -void messageCallback(const TcpConnectionPtr&, - const MessagePtr& msg, - Timestamp) -{ +void messageCallback(const TcpConnectionPtr &, const MessagePtr &msg, + Timestamp) { g_msgptr = msg; } -void print(const Buffer& buf) -{ +void print(const Buffer &buf) { printf("encoded to %zd bytes\n", buf.readableBytes()); - for (size_t i = 0; i < buf.readableBytes(); ++i) - { + for (size_t i = 0; i < buf.readableBytes(); ++i) { unsigned char ch = static_cast(buf.peek()[i]); printf("%2zd: 0x%02x %c\n", i, ch, isgraph(ch) ? ch : ' '); @@ -36,45 +29,49 @@ void print(const Buffer& buf) char rpctag[] = "RPC0"; -int main() -{ +int main() { RpcMessage message; message.set_type(REQUEST); message.set_id(2); - char wire[] = "\0\0\0\x13" "RPC0" "\x08\x01\x11\x02\0\0\0\0\0\0\0" "\x0f\xef\x01\x32"; - string expected(wire, sizeof(wire)-1); + char wire[] = "\0\0\0\x13" + "RPC0" + "\x08\x01\x11\x02\0\0\0\0\0\0\0" + "\x0f\xef\x01\x32"; + string expected(wire, sizeof(wire) - 1); string s1, s2; Buffer buf1, buf2; { - RpcCodec codec(rpcMessageCallback); - codec.fillEmptyBuffer(&buf1, message); - print(buf1); - s1 = buf1.toStringPiece().as_string(); + RpcCodec codec(rpcMessageCallback); + codec.fillEmptyBuffer(&buf1, message); + print(buf1); + s1 = buf1.toStringPiece().as_string(); } { - ProtobufCodecLite codec(&RpcMessage::default_instance(), "RPC0", messageCallback); - codec.fillEmptyBuffer(&buf2, message); - print(buf2); - s2 = buf2.toStringPiece().as_string(); - codec.onMessage(TcpConnectionPtr(), &buf1, Timestamp::now()); - assert(g_msgptr); - assert(g_msgptr->DebugString() == message.DebugString()); - g_msgptr.reset(); + ProtobufCodecLite codec(&RpcMessage::default_instance(), "RPC0", + messageCallback); + codec.fillEmptyBuffer(&buf2, message); + print(buf2); + s2 = buf2.toStringPiece().as_string(); + codec.onMessage(TcpConnectionPtr(), &buf1, Timestamp::now()); + assert(g_msgptr); + assert(g_msgptr->DebugString() == message.DebugString()); + g_msgptr.reset(); } assert(s1 == s2); assert(s1 == expected); assert(s2 == expected); { - Buffer buf; - ProtobufCodecLite codec(&RpcMessage::default_instance(), "XYZ", messageCallback); - codec.fillEmptyBuffer(&buf, message); - print(buf); - s2 = buf.toStringPiece().as_string(); - codec.onMessage(TcpConnectionPtr(), &buf, Timestamp::now()); - assert(g_msgptr); - assert(g_msgptr->DebugString() == message.DebugString()); + Buffer buf; + ProtobufCodecLite codec(&RpcMessage::default_instance(), "XYZ", + messageCallback); + codec.fillEmptyBuffer(&buf, message); + print(buf); + s2 = buf.toStringPiece().as_string(); + codec.onMessage(TcpConnectionPtr(), &buf, Timestamp::now()); + assert(g_msgptr); + assert(g_msgptr->DebugString() == message.DebugString()); } google::protobuf::ShutdownProtobufLibrary(); diff --git a/muduo/net/protorpc/RpcServer.cc b/muduo/net/protorpc/RpcServer.cc index fc1248b4a..d32150dbd 100644 --- a/muduo/net/protorpc/RpcServer.cc +++ b/muduo/net/protorpc/RpcServer.cc @@ -17,42 +17,31 @@ using namespace muduo; using namespace muduo::net; -RpcServer::RpcServer(EventLoop* loop, - const InetAddress& listenAddr) - : server_(loop, listenAddr, "RpcServer") -{ - server_.setConnectionCallback( - std::bind(&RpcServer::onConnection, this, _1)); -// server_.setMessageCallback( -// std::bind(&RpcServer::onMessage, this, _1, _2, _3)); +RpcServer::RpcServer(EventLoop *loop, const InetAddress &listenAddr) + : server_(loop, listenAddr, "RpcServer") { + server_.setConnectionCallback(std::bind(&RpcServer::onConnection, this, _1)); + // server_.setMessageCallback( + // std::bind(&RpcServer::onMessage, this, _1, _2, _3)); } -void RpcServer::registerService(google::protobuf::Service* service) -{ - const google::protobuf::ServiceDescriptor* desc = service->GetDescriptor(); +void RpcServer::registerService(google::protobuf::Service *service) { + const google::protobuf::ServiceDescriptor *desc = service->GetDescriptor(); services_[desc->full_name()] = service; } -void RpcServer::start() -{ - server_.start(); -} +void RpcServer::start() { server_.start(); } -void RpcServer::onConnection(const TcpConnectionPtr& conn) -{ +void RpcServer::onConnection(const TcpConnectionPtr &conn) { LOG_INFO << "RpcServer - " << conn->peerAddress().toIpPort() << " -> " - << conn->localAddress().toIpPort() << " is " - << (conn->connected() ? "UP" : "DOWN"); - if (conn->connected()) - { + << conn->localAddress().toIpPort() << " is " + << (conn->connected() ? "UP" : "DOWN"); + if (conn->connected()) { RpcChannelPtr channel(new RpcChannel(conn)); channel->setServices(&services_); conn->setMessageCallback( std::bind(&RpcChannel::onMessage, get_pointer(channel), _1, _2, _3)); conn->setContext(channel); - } - else - { + } else { conn->setContext(RpcChannelPtr()); // FIXME: } @@ -62,7 +51,7 @@ void RpcServer::onConnection(const TcpConnectionPtr& conn) // Buffer* buf, // Timestamp time) // { -// RpcChannelPtr& channel = boost::any_cast(conn->getContext()); +// RpcChannelPtr& channel = +// boost::any_cast(conn->getContext()); // channel->onMessage(conn, buf, time); // } - diff --git a/muduo/net/protorpc/RpcServer.h b/muduo/net/protorpc/RpcServer.h index 681880170..8c251e93e 100644 --- a/muduo/net/protorpc/RpcServer.h +++ b/muduo/net/protorpc/RpcServer.h @@ -18,40 +18,33 @@ namespace protobuf { class Service; -} // namespace protobuf -} // namespace google - -namespace muduo -{ -namespace net -{ - -class RpcServer -{ - public: - RpcServer(EventLoop* loop, - const InetAddress& listenAddr); - - void setThreadNum(int numThreads) - { - server_.setThreadNum(numThreads); - } - - void registerService(::google::protobuf::Service*); +} // namespace protobuf +} // namespace google + +namespace muduo { +namespace net { + +class RpcServer { +public: + RpcServer(EventLoop *loop, const InetAddress &listenAddr); + + void setThreadNum(int numThreads) { server_.setThreadNum(numThreads); } + + void registerService(::google::protobuf::Service *); void start(); - private: - void onConnection(const TcpConnectionPtr& conn); +private: + void onConnection(const TcpConnectionPtr &conn); // void onMessage(const TcpConnectionPtr& conn, // Buffer* buf, // Timestamp time); TcpServer server_; - std::map services_; + std::map services_; }; -} // namespace net -} // namespace muduo +} // namespace net +} // namespace muduo -#endif // MUDUO_NET_PROTORPC_RPCSERVER_H +#endif // MUDUO_NET_PROTORPC_RPCSERVER_H diff --git a/muduo/net/protorpc/google-inl.h b/muduo/net/protorpc/google-inl.h index 2a905a9af..771ddbb8d 100644 --- a/muduo/net/protorpc/google-inl.h +++ b/muduo/net/protorpc/google-inl.h @@ -44,25 +44,24 @@ // protobuf implementation but is more likely caused by concurrent modification // of the message. This function attempts to distinguish between the two and // provide a useful error message. -inline -void ByteSizeConsistencyError(int byte_size_before_serialization, - int byte_size_after_serialization, - int bytes_produced_by_serialization) -{ +inline void ByteSizeConsistencyError(int byte_size_before_serialization, + int byte_size_after_serialization, + int bytes_produced_by_serialization) { GOOGLE_CHECK_EQ(byte_size_before_serialization, byte_size_after_serialization) << "Protocol message was modified concurrently during serialization."; - GOOGLE_CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization) + GOOGLE_CHECK_EQ(bytes_produced_by_serialization, + byte_size_before_serialization) << "Byte size calculation and serialization were inconsistent. This " "may indicate a bug in protocol buffers or it may be caused by " "concurrent modification of the message."; GOOGLE_LOG(FATAL) << "This shouldn't be called if all the sizes are equal."; } -inline -std::string InitializationErrorMessage(const char* action, - const google::protobuf::MessageLite& message) -{ - // Note: We want to avoid depending on strutil in the lite library, otherwise +inline std::string +InitializationErrorMessage(const char *action, + const google::protobuf::MessageLite &message) { + // Note: We want to avoid depending on strutil in the lite library, + // otherwise // we'd use: // // return strings::Substitute( @@ -80,5 +79,3 @@ std::string InitializationErrorMessage(const char* action, result += message.InitializationErrorString(); return result; } - - diff --git a/muduo/net/tests/Buffer_unittest.cc b/muduo/net/tests/Buffer_unittest.cc index af7fb8124..77eba377b 100644 --- a/muduo/net/tests/Buffer_unittest.cc +++ b/muduo/net/tests/Buffer_unittest.cc @@ -8,8 +8,7 @@ using muduo::string; using muduo::net::Buffer; -BOOST_AUTO_TEST_CASE(testBufferAppendRetrieve) -{ +BOOST_AUTO_TEST_CASE(testBufferAppendRetrieve) { Buffer buf; BOOST_CHECK_EQUAL(buf.readableBytes(), 0); BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize); @@ -21,19 +20,21 @@ BOOST_AUTO_TEST_CASE(testBufferAppendRetrieve) BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - str.size()); BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend); - const string str2 = buf.retrieveAsString(50); + const string str2 = buf.retrieveAsString(50); BOOST_CHECK_EQUAL(str2.size(), 50); BOOST_CHECK_EQUAL(buf.readableBytes(), str.size() - str2.size()); BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - str.size()); - BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend + str2.size()); + BOOST_CHECK_EQUAL(buf.prependableBytes(), + Buffer::kCheapPrepend + str2.size()); BOOST_CHECK_EQUAL(str2, string(50, 'x')); buf.append(str); - BOOST_CHECK_EQUAL(buf.readableBytes(), 2*str.size() - str2.size()); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 2*str.size()); - BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend + str2.size()); + BOOST_CHECK_EQUAL(buf.readableBytes(), 2 * str.size() - str2.size()); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 2 * str.size()); + BOOST_CHECK_EQUAL(buf.prependableBytes(), + Buffer::kCheapPrepend + str2.size()); - const string str3 = buf.retrieveAllAsString(); + const string str3 = buf.retrieveAllAsString(); BOOST_CHECK_EQUAL(str3.size(), 350); BOOST_CHECK_EQUAL(buf.readableBytes(), 0); BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize); @@ -41,22 +42,22 @@ BOOST_AUTO_TEST_CASE(testBufferAppendRetrieve) BOOST_CHECK_EQUAL(str3, string(350, 'x')); } -BOOST_AUTO_TEST_CASE(testBufferGrow) -{ +BOOST_AUTO_TEST_CASE(testBufferGrow) { Buffer buf; buf.append(string(400, 'y')); BOOST_CHECK_EQUAL(buf.readableBytes(), 400); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-400); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 400); buf.retrieve(50); BOOST_CHECK_EQUAL(buf.readableBytes(), 350); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-400); - BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+50); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 400); + BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend + 50); buf.append(string(1000, 'z')); BOOST_CHECK_EQUAL(buf.readableBytes(), 1350); BOOST_CHECK_EQUAL(buf.writableBytes(), 0); - BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+50); // FIXME + BOOST_CHECK_EQUAL(buf.prependableBytes(), + Buffer::kCheapPrepend + 50); // FIXME buf.retrieveAll(); BOOST_CHECK_EQUAL(buf.readableBytes(), 0); @@ -64,26 +65,24 @@ BOOST_AUTO_TEST_CASE(testBufferGrow) BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend); } -BOOST_AUTO_TEST_CASE(testBufferInsideGrow) -{ +BOOST_AUTO_TEST_CASE(testBufferInsideGrow) { Buffer buf; buf.append(string(800, 'y')); BOOST_CHECK_EQUAL(buf.readableBytes(), 800); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-800); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 800); buf.retrieve(500); BOOST_CHECK_EQUAL(buf.readableBytes(), 300); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-800); - BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+500); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 800); + BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend + 500); buf.append(string(300, 'z')); BOOST_CHECK_EQUAL(buf.readableBytes(), 600); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-600); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 600); BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend); } -BOOST_AUTO_TEST_CASE(testBufferShrink) -{ +BOOST_AUTO_TEST_CASE(testBufferShrink) { Buffer buf; buf.append(string(2000, 'y')); BOOST_CHECK_EQUAL(buf.readableBytes(), 2000); @@ -93,43 +92,41 @@ BOOST_AUTO_TEST_CASE(testBufferShrink) buf.retrieve(1500); BOOST_CHECK_EQUAL(buf.readableBytes(), 500); BOOST_CHECK_EQUAL(buf.writableBytes(), 0); - BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend+1500); + BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend + 1500); buf.shrink(0); BOOST_CHECK_EQUAL(buf.readableBytes(), 500); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-500); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 500); BOOST_CHECK_EQUAL(buf.retrieveAllAsString(), string(500, 'y')); BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend); } -BOOST_AUTO_TEST_CASE(testBufferPrepend) -{ +BOOST_AUTO_TEST_CASE(testBufferPrepend) { Buffer buf; buf.append(string(200, 'y')); BOOST_CHECK_EQUAL(buf.readableBytes(), 200); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-200); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 200); BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend); int x = 0; buf.prepend(&x, sizeof x); BOOST_CHECK_EQUAL(buf.readableBytes(), 204); - BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize-200); + BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize - 200); BOOST_CHECK_EQUAL(buf.prependableBytes(), Buffer::kCheapPrepend - 4); } -BOOST_AUTO_TEST_CASE(testBufferReadInt) -{ +BOOST_AUTO_TEST_CASE(testBufferReadInt) { Buffer buf; buf.append("HTTP"); BOOST_CHECK_EQUAL(buf.readableBytes(), 4); BOOST_CHECK_EQUAL(buf.peekInt8(), 'H'); int top16 = buf.peekInt16(); - BOOST_CHECK_EQUAL(top16, 'H'*256 + 'T'); - BOOST_CHECK_EQUAL(buf.peekInt32(), top16*65536 + 'T'*256 + 'P'); + BOOST_CHECK_EQUAL(top16, 'H' * 256 + 'T'); + BOOST_CHECK_EQUAL(buf.peekInt32(), top16 * 65536 + 'T' * 256 + 'P'); BOOST_CHECK_EQUAL(buf.readInt8(), 'H'); - BOOST_CHECK_EQUAL(buf.readInt16(), 'T'*256 + 'T'); + BOOST_CHECK_EQUAL(buf.readInt16(), 'T' * 256 + 'T'); BOOST_CHECK_EQUAL(buf.readInt8(), 'P'); BOOST_CHECK_EQUAL(buf.readableBytes(), 0); BOOST_CHECK_EQUAL(buf.writableBytes(), Buffer::kInitialSize); @@ -143,28 +140,25 @@ BOOST_AUTO_TEST_CASE(testBufferReadInt) BOOST_CHECK_EQUAL(buf.readInt32(), -3); } -BOOST_AUTO_TEST_CASE(testBufferFindEOL) -{ +BOOST_AUTO_TEST_CASE(testBufferFindEOL) { Buffer buf; buf.append(string(100000, 'x')); - const char* null = NULL; + const char *null = NULL; BOOST_CHECK_EQUAL(buf.findEOL(), null); - BOOST_CHECK_EQUAL(buf.findEOL(buf.peek()+90000), null); + BOOST_CHECK_EQUAL(buf.findEOL(buf.peek() + 90000), null); } -void output(Buffer&& buf, const void* inner) -{ +void output(Buffer &&buf, const void *inner) { Buffer newbuf(std::move(buf)); // printf("New Buffer at %p, inner %p\n", &newbuf, newbuf.peek()); BOOST_CHECK_EQUAL(inner, newbuf.peek()); } // NOTE: This test fails in g++ 4.4, passes in g++ 4.6. -BOOST_AUTO_TEST_CASE(testMove) -{ +BOOST_AUTO_TEST_CASE(testMove) { Buffer buf; buf.append("muduo", 5); - const void* inner = buf.peek(); + const void *inner = buf.peek(); // printf("Buffer at %p, inner %p\n", &buf, inner); output(std::move(buf), inner); } diff --git a/muduo/net/tests/Channel_test.cc b/muduo/net/tests/Channel_test.cc index 627653110..72e089db4 100644 --- a/muduo/net/tests/Channel_test.cc +++ b/muduo/net/tests/Channel_test.cc @@ -6,81 +6,67 @@ #include #include -#include #include +#include using namespace muduo; using namespace muduo::net; -void print(const char* msg) -{ - static std::map lasts; - Timestamp& last = lasts[msg]; +void print(const char *msg) { + static std::map lasts; + Timestamp &last = lasts[msg]; Timestamp now = Timestamp::now(); - printf("%s tid %d %s delay %f\n", now.toString().c_str(), CurrentThread::tid(), - msg, timeDifference(now, last)); + printf("%s tid %d %s delay %f\n", now.toString().c_str(), + CurrentThread::tid(), msg, timeDifference(now, last)); last = now; } -namespace muduo -{ -namespace net -{ -namespace detail -{ +namespace muduo { +namespace net { +namespace detail { int createTimerfd(); void readTimerfd(int timerfd, Timestamp now); -} -} -} +} // namespace detail +} // namespace net +} // namespace muduo // Use relative time, immunized to wall clock changes. -class PeriodicTimer -{ - public: - PeriodicTimer(EventLoop* loop, double interval, const TimerCallback& cb) - : loop_(loop), - timerfd_(muduo::net::detail::createTimerfd()), - timerfdChannel_(loop, timerfd_), - interval_(interval), - cb_(cb) - { +class PeriodicTimer { +public: + PeriodicTimer(EventLoop *loop, double interval, const TimerCallback &cb) + : loop_(loop), timerfd_(muduo::net::detail::createTimerfd()), + timerfdChannel_(loop, timerfd_), interval_(interval), cb_(cb) { timerfdChannel_.setReadCallback( std::bind(&PeriodicTimer::handleRead, this)); timerfdChannel_.enableReading(); } - void start() - { + void start() { struct itimerspec spec; memZero(&spec, sizeof spec); spec.it_interval = toTimeSpec(interval_); spec.it_value = spec.it_interval; int ret = ::timerfd_settime(timerfd_, 0 /* relative timer */, &spec, NULL); - if (ret) - { + if (ret) { LOG_SYSERR << "timerfd_settime()"; } } - ~PeriodicTimer() - { + ~PeriodicTimer() { timerfdChannel_.disableAll(); timerfdChannel_.remove(); ::close(timerfd_); } - private: - void handleRead() - { +private: + void handleRead() { loop_->assertInLoopThread(); muduo::net::detail::readTimerfd(timerfd_, Timestamp::now()); if (cb_) cb_(); } - static struct timespec toTimeSpec(double seconds) - { + static struct timespec toTimeSpec(double seconds) { struct timespec ts; memZero(&ts, sizeof ts); const int64_t kNanoSecondsPerSecond = 1000000000; @@ -93,15 +79,14 @@ class PeriodicTimer return ts; } - EventLoop* loop_; + EventLoop *loop_; const int timerfd_; Channel timerfdChannel_; const double interval_; // in seconds TimerCallback cb_; }; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid() << " Try adjusting the wall clock, see what happens."; EventLoop loop; diff --git a/muduo/net/tests/EchoClient_unittest.cc b/muduo/net/tests/EchoClient_unittest.cc index 44d973ac8..6109061be 100644 --- a/muduo/net/tests/EchoClient_unittest.cc +++ b/muduo/net/tests/EchoClient_unittest.cc @@ -18,38 +18,29 @@ class EchoClient; std::vector> clients; int current = 0; -class EchoClient : noncopyable -{ - public: - EchoClient(EventLoop* loop, const InetAddress& listenAddr, const string& id) - : loop_(loop), - client_(loop, listenAddr, "EchoClient"+id) - { +class EchoClient : noncopyable { +public: + EchoClient(EventLoop *loop, const InetAddress &listenAddr, const string &id) + : loop_(loop), client_(loop, listenAddr, "EchoClient" + id) { client_.setConnectionCallback( std::bind(&EchoClient::onConnection, this, _1)); client_.setMessageCallback( std::bind(&EchoClient::onMessage, this, _1, _2, _3)); - //client_.enableRetry(); + // client_.enableRetry(); } - void connect() - { - client_.connect(); - } + void connect() { client_.connect(); } // void stop(); - private: - void onConnection(const TcpConnectionPtr& conn) - { +private: + void onConnection(const TcpConnectionPtr &conn) { LOG_TRACE << conn->localAddress().toIpPort() << " -> " - << conn->peerAddress().toIpPort() << " is " - << (conn->connected() ? "UP" : "DOWN"); + << conn->peerAddress().toIpPort() << " is " + << (conn->connected() ? "UP" : "DOWN"); - if (conn->connected()) - { + if (conn->connected()) { ++current; - if (implicit_cast(current) < clients.size()) - { + if (implicit_cast(current) < clients.size()) { clients[current]->connect(); } LOG_INFO << "*** connected " << current; @@ -57,58 +48,46 @@ class EchoClient : noncopyable conn->send("world\n"); } - void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time) - { + void onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp time) { string msg(buf->retrieveAllAsString()); - LOG_TRACE << conn->name() << " recv " << msg.size() << " bytes at " << time.toString(); - if (msg == "quit\n") - { + LOG_TRACE << conn->name() << " recv " << msg.size() << " bytes at " + << time.toString(); + if (msg == "quit\n") { conn->send("bye\n"); conn->shutdown(); - } - else if (msg == "shutdown\n") - { + } else if (msg == "shutdown\n") { loop_->quit(); - } - else - { + } else { conn->send(msg); } } - EventLoop* loop_; + EventLoop *loop_; TcpClient client_; }; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid(); - if (argc > 1) - { + if (argc > 1) { EventLoop loop; bool ipv6 = argc > 3; InetAddress serverAddr(argv[1], 2000, ipv6); int n = 1; - if (argc > 2) - { + if (argc > 2) { n = atoi(argv[2]); } clients.reserve(n); - for (int i = 0; i < n; ++i) - { + for (int i = 0; i < n; ++i) { char buf[32]; - snprintf(buf, sizeof buf, "%d", i+1); + snprintf(buf, sizeof buf, "%d", i + 1); clients.emplace_back(new EchoClient(&loop, serverAddr, buf)); } clients[current]->connect(); loop.loop(); - } - else - { + } else { printf("Usage: %s host_ip [current#]\n", argv[0]); } } - diff --git a/muduo/net/tests/EchoServer_unittest.cc b/muduo/net/tests/EchoServer_unittest.cc index 08756688b..2cab3f4c9 100644 --- a/muduo/net/tests/EchoServer_unittest.cc +++ b/muduo/net/tests/EchoServer_unittest.cc @@ -15,13 +15,10 @@ using namespace muduo::net; int numThreads = 0; -class EchoServer -{ - public: - EchoServer(EventLoop* loop, const InetAddress& listenAddr) - : loop_(loop), - server_(loop, listenAddr, "EchoServer") - { +class EchoServer { +public: + EchoServer(EventLoop *loop, const InetAddress &listenAddr) + : loop_(loop), server_(loop, listenAddr, "EchoServer") { server_.setConnectionCallback( std::bind(&EchoServer::onConnection, this, _1)); server_.setMessageCallback( @@ -29,49 +26,41 @@ class EchoServer server_.setThreadNum(numThreads); } - void start() - { - server_.start(); - } + void start() { server_.start(); } // void stop(); - private: - void onConnection(const TcpConnectionPtr& conn) - { +private: + void onConnection(const TcpConnectionPtr &conn) { LOG_TRACE << conn->peerAddress().toIpPort() << " -> " - << conn->localAddress().toIpPort() << " is " - << (conn->connected() ? "UP" : "DOWN"); + << conn->localAddress().toIpPort() << " is " + << (conn->connected() ? "UP" : "DOWN"); LOG_INFO << conn->getTcpInfoString(); conn->send("hello\n"); } - void onMessage(const TcpConnectionPtr& conn, Buffer* buf, Timestamp time) - { + void onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp time) { string msg(buf->retrieveAllAsString()); - LOG_TRACE << conn->name() << " recv " << msg.size() << " bytes at " << time.toString(); - if (msg == "exit\n") - { + LOG_TRACE << conn->name() << " recv " << msg.size() << " bytes at " + << time.toString(); + if (msg == "exit\n") { conn->send("bye\n"); conn->shutdown(); } - if (msg == "quit\n") - { + if (msg == "quit\n") { loop_->quit(); } conn->send(msg); } - EventLoop* loop_; + EventLoop *loop_; TcpServer server_; }; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid(); LOG_INFO << "sizeof TcpConnection = " << sizeof(TcpConnection); - if (argc > 1) - { + if (argc > 1) { numThreads = atoi(argv[1]); } bool ipv6 = argc > 2; @@ -83,4 +72,3 @@ int main(int argc, char* argv[]) loop.loop(); } - diff --git a/muduo/net/tests/EventLoopThreadPool_unittest.cc b/muduo/net/tests/EventLoopThreadPool_unittest.cc index 1bf1bd35a..2fbac714d 100644 --- a/muduo/net/tests/EventLoopThreadPool_unittest.cc +++ b/muduo/net/tests/EventLoopThreadPool_unittest.cc @@ -1,6 +1,6 @@ -#include "muduo/net/EventLoopThreadPool.h" -#include "muduo/net/EventLoop.h" #include "muduo/base/Thread.h" +#include "muduo/net/EventLoop.h" +#include "muduo/net/EventLoopThreadPool.h" #include #include @@ -8,20 +8,17 @@ using namespace muduo; using namespace muduo::net; -void print(EventLoop* p = NULL) -{ - printf("main(): pid = %d, tid = %d, loop = %p\n", - getpid(), CurrentThread::tid(), p); +void print(EventLoop *p = NULL) { + printf("main(): pid = %d, tid = %d, loop = %p\n", getpid(), + CurrentThread::tid(), p); } -void init(EventLoop* p) -{ - printf("init(): pid = %d, tid = %d, loop = %p\n", - getpid(), CurrentThread::tid(), p); +void init(EventLoop *p) { + printf("init(): pid = %d, tid = %d, loop = %p\n", getpid(), + CurrentThread::tid(), p); } -int main() -{ +int main() { print(); EventLoop loop; @@ -42,7 +39,7 @@ int main() EventLoopThreadPool model(&loop, "another"); model.setThreadNum(1); model.start(init); - EventLoop* nextLoop = model.getNextLoop(); + EventLoop *nextLoop = model.getNextLoop(); nextLoop->runAfter(2, std::bind(print, nextLoop)); assert(nextLoop != &loop); assert(nextLoop == model.getNextLoop()); @@ -55,7 +52,7 @@ int main() EventLoopThreadPool model(&loop, "three"); model.setThreadNum(3); model.start(init); - EventLoop* nextLoop = model.getNextLoop(); + EventLoop *nextLoop = model.getNextLoop(); nextLoop->runInLoop(std::bind(print, nextLoop)); assert(nextLoop != &loop); assert(nextLoop != model.getNextLoop()); @@ -65,4 +62,3 @@ int main() loop.loop(); } - diff --git a/muduo/net/tests/EventLoopThread_unittest.cc b/muduo/net/tests/EventLoopThread_unittest.cc index d67c12852..19f5e7c85 100644 --- a/muduo/net/tests/EventLoopThread_unittest.cc +++ b/muduo/net/tests/EventLoopThread_unittest.cc @@ -1,7 +1,7 @@ -#include "muduo/net/EventLoopThread.h" -#include "muduo/net/EventLoop.h" -#include "muduo/base/Thread.h" #include "muduo/base/CountDownLatch.h" +#include "muduo/base/Thread.h" +#include "muduo/net/EventLoop.h" +#include "muduo/net/EventLoopThread.h" #include #include @@ -9,40 +9,36 @@ using namespace muduo; using namespace muduo::net; -void print(EventLoop* p = NULL) -{ - printf("print: pid = %d, tid = %d, loop = %p\n", - getpid(), CurrentThread::tid(), p); +void print(EventLoop *p = NULL) { + printf("print: pid = %d, tid = %d, loop = %p\n", getpid(), + CurrentThread::tid(), p); } -void quit(EventLoop* p) -{ +void quit(EventLoop *p) { print(p); p->quit(); } -int main() -{ +int main() { print(); { - EventLoopThread thr1; // never start + EventLoopThread thr1; // never start } { - // dtor calls quit() - EventLoopThread thr2; - EventLoop* loop = thr2.startLoop(); - loop->runInLoop(std::bind(print, loop)); - CurrentThread::sleepUsec(500 * 1000); + // dtor calls quit() + EventLoopThread thr2; + EventLoop *loop = thr2.startLoop(); + loop->runInLoop(std::bind(print, loop)); + CurrentThread::sleepUsec(500 * 1000); } { - // quit() before dtor - EventLoopThread thr3; - EventLoop* loop = thr3.startLoop(); - loop->runInLoop(std::bind(quit, loop)); - CurrentThread::sleepUsec(500 * 1000); + // quit() before dtor + EventLoopThread thr3; + EventLoop *loop = thr3.startLoop(); + loop->runInLoop(std::bind(quit, loop)); + CurrentThread::sleepUsec(500 * 1000); } } - diff --git a/muduo/net/tests/EventLoop_unittest.cc b/muduo/net/tests/EventLoop_unittest.cc index 6cb6d7d9f..9f688d5a4 100644 --- a/muduo/net/tests/EventLoop_unittest.cc +++ b/muduo/net/tests/EventLoop_unittest.cc @@ -1,5 +1,5 @@ -#include "muduo/net/EventLoop.h" #include "muduo/base/Thread.h" +#include "muduo/net/EventLoop.h" #include #include @@ -8,16 +8,14 @@ using namespace muduo; using namespace muduo::net; -EventLoop* g_loop; +EventLoop *g_loop; -void callback() -{ +void callback() { printf("callback(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid()); EventLoop anotherLoop; } -void threadFunc() -{ +void threadFunc() { printf("threadFunc(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid()); assert(EventLoop::getEventLoopOfCurrentThread() == NULL); @@ -27,8 +25,7 @@ void threadFunc() loop.loop(); } -int main() -{ +int main() { printf("main(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid()); assert(EventLoop::getEventLoopOfCurrentThread() == NULL); diff --git a/muduo/net/tests/InetAddress_unittest.cc b/muduo/net/tests/InetAddress_unittest.cc index bdd31e059..68223bfcc 100644 --- a/muduo/net/tests/InetAddress_unittest.cc +++ b/muduo/net/tests/InetAddress_unittest.cc @@ -10,8 +10,7 @@ using muduo::string; using muduo::net::InetAddress; -BOOST_AUTO_TEST_CASE(testInetAddress) -{ +BOOST_AUTO_TEST_CASE(testInetAddress) { InetAddress addr0(1234); BOOST_CHECK_EQUAL(addr0.toIp(), string("0.0.0.0")); BOOST_CHECK_EQUAL(addr0.toIpPort(), string("0.0.0.0:1234")); @@ -33,8 +32,7 @@ BOOST_AUTO_TEST_CASE(testInetAddress) BOOST_CHECK_EQUAL(addr3.port(), 65535); } -BOOST_AUTO_TEST_CASE(testInet6Address) -{ +BOOST_AUTO_TEST_CASE(testInet6Address) { InetAddress addr0(1234, false, true); BOOST_CHECK_EQUAL(addr0.toIp(), string("::")); BOOST_CHECK_EQUAL(addr0.toIpPort(), string("[::]:1234")); @@ -56,15 +54,11 @@ BOOST_AUTO_TEST_CASE(testInet6Address) BOOST_CHECK_EQUAL(addr3.port(), 8888); } -BOOST_AUTO_TEST_CASE(testInetAddressResolve) -{ +BOOST_AUTO_TEST_CASE(testInetAddressResolve) { InetAddress addr(80); - if (InetAddress::resolve("google.com", &addr)) - { + if (InetAddress::resolve("google.com", &addr)) { LOG_INFO << "google.com resolved to " << addr.toIpPort(); - } - else - { + } else { LOG_ERROR << "Unable to resolve google.com"; } } diff --git a/muduo/net/tests/TcpClient_reg1.cc b/muduo/net/tests/TcpClient_reg1.cc index 41b76b284..81dc4e96c 100644 --- a/muduo/net/tests/TcpClient_reg1.cc +++ b/muduo/net/tests/TcpClient_reg1.cc @@ -7,16 +7,14 @@ using namespace muduo; using namespace muduo::net; -TcpClient* g_client; +TcpClient *g_client; -void timeout() -{ +void timeout() { LOG_INFO << "timeout"; g_client->stop(); } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { EventLoop loop; InetAddress serverAddr("127.0.0.1", 2); // no such server TcpClient client(&loop, serverAddr, "TcpClient"); diff --git a/muduo/net/tests/TcpClient_reg2.cc b/muduo/net/tests/TcpClient_reg2.cc index 1637dbd64..70ecaaa75 100644 --- a/muduo/net/tests/TcpClient_reg2.cc +++ b/muduo/net/tests/TcpClient_reg2.cc @@ -8,18 +8,16 @@ using namespace muduo; using namespace muduo::net; -void threadFunc(EventLoop* loop) -{ +void threadFunc(EventLoop *loop) { InetAddress serverAddr("127.0.0.1", 1234); // should succeed TcpClient client(loop, serverAddr, "TcpClient"); client.connect(); - CurrentThread::sleepUsec(1000*1000); + CurrentThread::sleepUsec(1000 * 1000); // client destructs when connected. } -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { Logger::setLogLevel(Logger::DEBUG); EventLoop loop; diff --git a/muduo/net/tests/TcpClient_reg3.cc b/muduo/net/tests/TcpClient_reg3.cc index bb1e5ee6c..7723548e6 100644 --- a/muduo/net/tests/TcpClient_reg3.cc +++ b/muduo/net/tests/TcpClient_reg3.cc @@ -7,17 +7,16 @@ using namespace muduo; using namespace muduo::net; -int main(int argc, char* argv[]) -{ +int main(int argc, char *argv[]) { Logger::setLogLevel(Logger::DEBUG); EventLoopThread loopThread; { - InetAddress serverAddr("127.0.0.1", 1234); // should succeed - TcpClient client(loopThread.startLoop(), serverAddr, "TcpClient"); - client.connect(); - CurrentThread::sleepUsec(500 * 1000); // wait for connect - client.disconnect(); + InetAddress serverAddr("127.0.0.1", 1234); // should succeed + TcpClient client(loopThread.startLoop(), serverAddr, "TcpClient"); + client.connect(); + CurrentThread::sleepUsec(500 * 1000); // wait for connect + client.disconnect(); } CurrentThread::sleepUsec(1000 * 1000); diff --git a/muduo/net/tests/TimerQueue_unittest.cc b/muduo/net/tests/TimerQueue_unittest.cc index 65cff93e7..0dd0047f8 100644 --- a/muduo/net/tests/TimerQueue_unittest.cc +++ b/muduo/net/tests/TimerQueue_unittest.cc @@ -1,6 +1,6 @@ +#include "muduo/base/Thread.h" #include "muduo/net/EventLoop.h" #include "muduo/net/EventLoopThread.h" -#include "muduo/base/Thread.h" #include #include @@ -9,31 +9,26 @@ using namespace muduo; using namespace muduo::net; int cnt = 0; -EventLoop* g_loop; +EventLoop *g_loop; -void printTid() -{ +void printTid() { printf("pid = %d, tid = %d\n", getpid(), CurrentThread::tid()); printf("now %s\n", Timestamp::now().toString().c_str()); } -void print(const char* msg) -{ +void print(const char *msg) { printf("msg %s %s\n", Timestamp::now().toString().c_str(), msg); - if (++cnt == 20) - { + if (++cnt == 20) { g_loop->quit(); } } -void cancel(TimerId timer) -{ +void cancel(TimerId timer) { g_loop->cancel(timer); printf("cancelled at %s\n", Timestamp::now().toString().c_str()); } -int main() -{ +int main() { printTid(); sleep(1); { @@ -58,7 +53,7 @@ int main() sleep(1); { EventLoopThread loopThread; - EventLoop* loop = loopThread.startLoop(); + EventLoop *loop = loopThread.startLoop(); loop->runAfter(2, printTid); sleep(3); print("thread loop exits"); diff --git a/muduo/net/tests/ZlibStream_unittest.cc b/muduo/net/tests/ZlibStream_unittest.cc index 144dda0ec..48e49cae2 100644 --- a/muduo/net/tests/ZlibStream_unittest.cc +++ b/muduo/net/tests/ZlibStream_unittest.cc @@ -8,8 +8,7 @@ #include -BOOST_AUTO_TEST_CASE(testZlibOutputStream) -{ +BOOST_AUTO_TEST_CASE(testZlibOutputStream) { muduo::net::Buffer output; { muduo::net::ZlibOutputStream stream(&output); @@ -18,8 +17,7 @@ BOOST_AUTO_TEST_CASE(testZlibOutputStream) BOOST_CHECK_EQUAL(output.readableBytes(), 8); } -BOOST_AUTO_TEST_CASE(testZlibOutputStream1) -{ +BOOST_AUTO_TEST_CASE(testZlibOutputStream1) { muduo::net::Buffer output; muduo::net::ZlibOutputStream stream(&output); BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_OK); @@ -27,44 +25,41 @@ BOOST_AUTO_TEST_CASE(testZlibOutputStream1) BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_STREAM_END); } -BOOST_AUTO_TEST_CASE(testZlibOutputStream2) -{ +BOOST_AUTO_TEST_CASE(testZlibOutputStream2) { muduo::net::Buffer output; muduo::net::ZlibOutputStream stream(&output); BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_OK); - BOOST_CHECK(stream.write("01234567890123456789012345678901234567890123456789")); + BOOST_CHECK( + stream.write("01234567890123456789012345678901234567890123456789")); stream.finish(); // printf("%zd\n", output.readableBytes()); BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_STREAM_END); } -BOOST_AUTO_TEST_CASE(testZlibOutputStream3) -{ +BOOST_AUTO_TEST_CASE(testZlibOutputStream3) { muduo::net::Buffer output; muduo::net::ZlibOutputStream stream(&output); BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_OK); - for (int i = 0; i < 1024*1024; ++i) - { - BOOST_CHECK(stream.write("01234567890123456789012345678901234567890123456789")); + for (int i = 0; i < 1024 * 1024; ++i) { + BOOST_CHECK( + stream.write("01234567890123456789012345678901234567890123456789")); } stream.finish(); // printf("total %zd\n", output.readableBytes()); BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_STREAM_END); } -BOOST_AUTO_TEST_CASE(testZlibOutputStream4) -{ +BOOST_AUTO_TEST_CASE(testZlibOutputStream4) { muduo::net::Buffer output; muduo::net::ZlibOutputStream stream(&output); BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_OK); muduo::string input; - for (int i = 0; i < 32768; ++i) - { - input += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-"[rand() % 64]; + for (int i = 0; i < 32768; ++i) { + input += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-" + [rand() % 64]; } - for (int i = 0; i < 10; ++i) - { + for (int i = 0; i < 10; ++i) { BOOST_CHECK(stream.write(input)); } stream.finish(); @@ -72,14 +67,12 @@ BOOST_AUTO_TEST_CASE(testZlibOutputStream4) BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_STREAM_END); } -BOOST_AUTO_TEST_CASE(testZlibOutputStream5) -{ +BOOST_AUTO_TEST_CASE(testZlibOutputStream5) { muduo::net::Buffer output; muduo::net::ZlibOutputStream stream(&output); BOOST_CHECK_EQUAL(stream.zlibErrorCode(), Z_OK); - muduo::string input(1024*1024, '_'); - for (int i = 0; i < 64; ++i) - { + muduo::string input(1024 * 1024, '_'); + for (int i = 0; i < 64; ++i) { BOOST_CHECK(stream.write(input)); } printf("bufsiz %d\n", stream.internalOutputBufferSize());