Removed the trantor namespace.

This commit is contained in:
Relintai 2022-02-10 12:07:47 +01:00
parent b9d441bf60
commit 8992cf49b3
150 changed files with 770 additions and 894 deletions

View File

@ -28,14 +28,13 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assert.h>
#include "concurrent_task_queue.h" #include "concurrent_task_queue.h"
#include "core/log/logger.h" #include "core/log/logger.h"
#include <assert.h>
#ifdef __linux__ #ifdef __linux__
#include <sys/prctl.h> #include <sys/prctl.h>
#endif #endif
using namespace trantor;
ConcurrentTaskQueue::ConcurrentTaskQueue(size_t threadNum, ConcurrentTaskQueue::ConcurrentTaskQueue(size_t threadNum,
const std::string &name) : const std::string &name) :
queueCount_(threadNum), queueName_(name), stop_(false) { queueCount_(threadNum), queueName_(name), stop_(false) {

View File

@ -37,7 +37,6 @@
#include <string> #include <string>
#include <vector> #include <vector>
namespace trantor {
/** /**
* @brief This class implements a task queue running in parallel. Basically this * @brief This class implements a task queue running in parallel. Basically this
* can be called a threads pool. * can be called a threads pool.
@ -99,5 +98,3 @@ private:
std::atomic_bool stop_; std::atomic_bool stop_;
void queueFunc(int queueNum); void queueFunc(int queueNum);
}; };
} // namespace trantor

View File

@ -34,7 +34,6 @@
#include <memory> #include <memory>
#include <type_traits> #include <type_traits>
namespace trantor {
/** /**
* @brief This class template represents a lock-free multiple producers single * @brief This class template represents a lock-free multiple producers single
* consumer queue * consumer queue
@ -122,5 +121,3 @@ private:
std::atomic<BufferNode *> head_; std::atomic<BufferNode *> head_;
std::atomic<BufferNode *> tail_; std::atomic<BufferNode *> tail_;
}; };
} // namespace trantor

View File

@ -42,10 +42,7 @@
#include <assert.h> #include <assert.h>
#include <errno.h> #include <errno.h>
using namespace trantor;
namespace trantor {
static constexpr size_t kBufferOffset{ 8 }; static constexpr size_t kBufferOffset{ 8 };
}
MsgBuffer::MsgBuffer(size_t len) : MsgBuffer::MsgBuffer(size_t len) :
head_(kBufferOffset), initCap_(len), buffer_(len + head_), tail_(head_) { head_(kBufferOffset), initCap_(len), buffer_(len + head_), tail_(head_) {

View File

@ -40,8 +40,6 @@
using ssize_t = long long; using ssize_t = long long;
#endif #endif
namespace trantor
{
static constexpr size_t kBufferDefaultLength{2048}; static constexpr size_t kBufferDefaultLength{2048};
static constexpr char CRLF[]{"\r\n"}; static constexpr char CRLF[]{"\r\n"};
@ -379,12 +377,11 @@ inline void swap(MsgBuffer &one, MsgBuffer &two) noexcept
{ {
one.swap(two); one.swap(two);
} }
} // namespace trantor
namespace std namespace std
{ {
template <> template <>
inline void swap(trantor::MsgBuffer &one, trantor::MsgBuffer &two) noexcept inline void swap(MsgBuffer &one, MsgBuffer &two) noexcept
{ {
one.swap(two); one.swap(two);
} }

View File

@ -33,7 +33,8 @@
#ifdef __linux__ #ifdef __linux__
#include <sys/prctl.h> #include <sys/prctl.h>
#endif #endif
namespace trantor {
SerialTaskQueue::SerialTaskQueue(const std::string &name) : SerialTaskQueue::SerialTaskQueue(const std::string &name) :
queueName_(name.empty() ? "SerailTaskQueue" : name), queueName_(name.empty() ? "SerailTaskQueue" : name),
loopThread_(queueName_) { loopThread_(queueName_) {
@ -62,4 +63,3 @@ void SerialTaskQueue::waitAllTasksFinished() {
}); });
} }
} // namespace trantor

View File

@ -36,8 +36,8 @@
#include <queue> #include <queue>
#include <mutex> #include <mutex>
#include <atomic> #include <atomic>
namespace trantor
{
/** /**
* @brief This class represents a task queue in which all tasks are executed one * @brief This class represents a task queue in which all tasks are executed one
* by one. * by one.
@ -112,4 +112,3 @@ class SerialTaskQueue : public TaskQueue
EventLoopThread loopThread_; EventLoopThread loopThread_;
bool stop_{false}; bool stop_{false};
}; };
} // namespace trantor

View File

@ -34,7 +34,6 @@
#include <future> #include <future>
#include <string> #include <string>
namespace trantor {
/** /**
* @brief This class is a pure virtual class that can be implemented as a * @brief This class is a pure virtual class that can be implemented as a
* SerialTaskQueue or a ConcurrentTaskQueue. * SerialTaskQueue or a ConcurrentTaskQueue.
@ -74,4 +73,4 @@ public:
virtual ~TaskQueue() { virtual ~TaskQueue() {
} }
}; };
} // namespace trantor

View File

@ -40,13 +40,9 @@
#include <functional> #include <functional>
#include <iostream> #include <iostream>
namespace trantor {
static constexpr std::chrono::seconds kLogFlushTimeout{ 1 }; static constexpr std::chrono::seconds kLogFlushTimeout{ 1 };
static constexpr size_t kMemBufferSize{ 4 * 1024 * 1024 }; static constexpr size_t kMemBufferSize{ 4 * 1024 * 1024 };
extern const char *strerror_tl(int savedErrno); extern const char *strerror_tl(int savedErrno);
} // namespace trantor
using namespace trantor;
AsyncFileLogger::AsyncFileLogger() : AsyncFileLogger::AsyncFileLogger() :
logBufferPtr_(new std::string), nextBufferPtr_(new std::string) { logBufferPtr_(new std::string), nextBufferPtr_(new std::string) {

View File

@ -39,7 +39,6 @@
#include <string> #include <string>
#include <thread> #include <thread>
namespace trantor {
using StringPtr = std::shared_ptr<std::string>; using StringPtr = std::shared_ptr<std::string>;
using StringPtrQueue = std::queue<StringPtr>; using StringPtrQueue = std::queue<StringPtr>;
@ -159,5 +158,3 @@ protected:
uint64_t lostCounter_{ 0 }; uint64_t lostCounter_{ 0 };
void swapBuffer(); void swapBuffer();
}; };
} // namespace trantor

View File

@ -38,10 +38,8 @@
#include <iostream> #include <iostream>
#include <limits> #include <limits>
using namespace trantor; using namespace detail;
using namespace trantor::detail;
namespace trantor {
namespace detail { namespace detail {
const char digits[] = "9876543210123456789"; const char digits[] = "9876543210123456789";
const char *zero = digits + 9; const char *zero = digits + 9;
@ -89,7 +87,6 @@ template class FixedBuffer<kSmallBuffer>;
template class FixedBuffer<kLargeBuffer>; template class FixedBuffer<kLargeBuffer>;
} // namespace detail } // namespace detail
} // namespace trantor
template <int SIZE> template <int SIZE>
const char *FixedBuffer<SIZE>::debugString() { const char *FixedBuffer<SIZE>::debugString() {

View File

@ -36,7 +36,6 @@
#include <string.h> // memcpy #include <string.h> // memcpy
#include <string> #include <string>
namespace trantor {
namespace detail { namespace detail {
static constexpr size_t kSmallBuffer{ 4000 }; static constexpr size_t kSmallBuffer{ 4000 };
static constexpr size_t kLargeBuffer{ 4000 * 1000 }; static constexpr size_t kLargeBuffer{ 4000 * 1000 };
@ -260,4 +259,3 @@ inline LogStream &operator<<(LogStream &s, const Fmt &fmt) {
return s; return s;
} }
} // namespace trantor

View File

@ -88,7 +88,6 @@ void RLogger::_log_index_error(const char *p_function, const char *p_file, int p
printf("!INDEX ERROR: (%s) %s:%d :: index: %d/%d. %s\n", p_file, p_function, p_line, index, size, str); printf("!INDEX ERROR: (%s) %s:%d :: index: %d/%d. %s\n", p_file, p_function, p_line, index, size, str);
} }
namespace trantor {
// helper class for known string length at compile time // helper class for known string length at compile time
class T { class T {
public: public:
@ -120,8 +119,6 @@ inline LogStream &operator<<(LogStream &s, const Logger::SourceFile &v) {
s.append(v.data_, v.size_); s.append(v.data_, v.size_);
return s; return s;
} }
} // namespace trantor
using namespace trantor;
static thread_local uint64_t lastSecond_{ 0 }; static thread_local uint64_t lastSecond_{ 0 };
static thread_local char lastTimeString_[32] = { 0 }; static thread_local char lastTimeString_[32] = { 0 };

View File

@ -61,7 +61,6 @@ public:
static void _log_index_error(const char *p_function, const char *p_file, int p_line, const int index, const int size, const char *str); static void _log_index_error(const char *p_function, const char *p_file, int p_line, const int index, const int size, const char *str);
}; };
namespace trantor {
/** /**
* @brief This class implements log functions. * @brief This class implements log functions.
* *
@ -249,64 +248,64 @@ private:
#ifdef NDEBUG #ifdef NDEBUG
#define LOG_TRACE \ #define LOG_TRACE \
if (0) \ if (0) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.stream() .stream()
#else #else
#define LOG_TRACE \ #define LOG_TRACE \
if (trantor::Logger::logLevel() <= trantor::Logger::kTrace) \ if (Logger::logLevel() <= Logger::kTrace) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.stream() .stream()
#define LOG_TRACE_TO(index) \ #define LOG_TRACE_TO(index) \
if (trantor::Logger::logLevel() <= trantor::Logger::kTrace) \ if (Logger::logLevel() <= Logger::kTrace) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.setIndex(index) \ .setIndex(index) \
.stream() .stream()
#endif #endif
#define LOG_DEBUG \ #define LOG_DEBUG \
if (trantor::Logger::logLevel() <= trantor::Logger::kDebug) \ if (Logger::logLevel() <= Logger::kDebug) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kDebug, __func__) \ Logger(__FILE__, __LINE__, Logger::kDebug, __func__) \
.stream() .stream()
#define LOG_DEBUG_TO(index) \ #define LOG_DEBUG_TO(index) \
if (trantor::Logger::logLevel() <= trantor::Logger::kDebug) \ if (Logger::logLevel() <= Logger::kDebug) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kDebug, __func__) \ Logger(__FILE__, __LINE__, Logger::kDebug, __func__) \
.setIndex(index) \ .setIndex(index) \
.stream() .stream()
#define LOG_INFO \ #define LOG_INFO \
if (trantor::Logger::logLevel() <= trantor::Logger::kInfo) \ if (Logger::logLevel() <= Logger::kInfo) \
trantor::Logger(__FILE__, __LINE__).stream() Logger(__FILE__, __LINE__).stream()
#define LOG_INFO_TO(index) \ #define LOG_INFO_TO(index) \
if (trantor::Logger::logLevel() <= trantor::Logger::kInfo) \ if (Logger::logLevel() <= Logger::kInfo) \
trantor::Logger(__FILE__, __LINE__).setIndex(index).stream() Logger(__FILE__, __LINE__).setIndex(index).stream()
#define LOG_WARN \ #define LOG_WARN \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kWarn).stream() Logger(__FILE__, __LINE__, Logger::kWarn).stream()
#define LOG_WARN_TO(index) \ #define LOG_WARN_TO(index) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kWarn) \ Logger(__FILE__, __LINE__, Logger::kWarn) \
.setIndex(index) \ .setIndex(index) \
.stream() .stream()
#define LOG_ERROR \ #define LOG_ERROR \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kError).stream() Logger(__FILE__, __LINE__, Logger::kError).stream()
#define LOG_ERROR_TO(index) \ #define LOG_ERROR_TO(index) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kError) \ Logger(__FILE__, __LINE__, Logger::kError) \
.setIndex(index) \ .setIndex(index) \
.stream() .stream()
#define LOG_FATAL \ #define LOG_FATAL \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kFatal).stream() Logger(__FILE__, __LINE__, Logger::kFatal).stream()
#define LOG_FATAL_TO(index) \ #define LOG_FATAL_TO(index) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kFatal) \ Logger(__FILE__, __LINE__, Logger::kFatal) \
.setIndex(index) \ .setIndex(index) \
.stream() .stream()
#define LOG_SYSERR trantor::Logger(__FILE__, __LINE__, true).stream() #define LOG_SYSERR Logger(__FILE__, __LINE__, true).stream()
#define LOG_SYSERR_TO(index) \ #define LOG_SYSERR_TO(index) \
trantor::Logger(__FILE__, __LINE__, true).setIndex(index).stream() Logger(__FILE__, __LINE__, true).setIndex(index).stream()
#define LOG_RAW trantor::RawLogger().stream() #define LOG_RAW RawLogger().stream()
#define LOG_RAW_TO(index) trantor::RawLogger().setIndex(index).stream() #define LOG_RAW_TO(index) RawLogger().setIndex(index).stream()
#define LOG_TRACE_IF(cond) \ #define LOG_TRACE_IF(cond) \
if ((trantor::Logger::logLevel() <= trantor::Logger::kTrace) && (cond)) \ if ((Logger::logLevel() <= Logger::kTrace) && (cond)) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.stream() .stream()
#define LOG_DEBUG_IF(cond) \ #define LOG_DEBUG_IF(cond) \
if ((Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) && (cond)) \ if ((Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) && (cond)) \
@ -328,7 +327,7 @@ private:
#ifdef NDEBUG #ifdef NDEBUG
#define DLOG_TRACE \ #define DLOG_TRACE \
if (0) \ if (0) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.stream() .stream()
#define DLOG_DEBUG \ #define DLOG_DEBUG \
if (0) \ if (0) \
@ -349,7 +348,7 @@ private:
#define DLOG_TRACE_IF(cond) \ #define DLOG_TRACE_IF(cond) \
if (0) \ if (0) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.stream() .stream()
#define DLOG_DEBUG_IF(cond) \ #define DLOG_DEBUG_IF(cond) \
if (0) \ if (0) \
@ -369,8 +368,8 @@ private:
Tensor::Logger(__FILE__, __LINE__, Tensor::Logger::kFatal).stream() Tensor::Logger(__FILE__, __LINE__, Tensor::Logger::kFatal).stream()
#else #else
#define DLOG_TRACE \ #define DLOG_TRACE \
if (trantor::Logger::logLevel() <= trantor::Logger::kTrace) \ if (Logger::logLevel() <= Logger::kTrace) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.stream() .stream()
#define DLOG_DEBUG \ #define DLOG_DEBUG \
if (Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) \ if (Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) \
@ -387,8 +386,8 @@ private:
Tensor::Logger(__FILE__, __LINE__, Tensor::Logger::kFatal).stream() Tensor::Logger(__FILE__, __LINE__, Tensor::Logger::kFatal).stream()
#define DLOG_TRACE_IF(cond) \ #define DLOG_TRACE_IF(cond) \
if ((trantor::Logger::logLevel() <= trantor::Logger::kTrace) && (cond)) \ if ((Logger::logLevel() <= Logger::kTrace) && (cond)) \
trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \
.stream() .stream()
#define DLOG_DEBUG_IF(cond) \ #define DLOG_DEBUG_IF(cond) \
if ((Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) && (cond)) \ if ((Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) && (cond)) \
@ -409,6 +408,5 @@ private:
#endif #endif
const char *strerror_tl(int savedErrno); const char *strerror_tl(int savedErrno);
} // namespace trantor
#endif #endif

View File

@ -29,7 +29,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "acceptor.h" #include "acceptor.h"
using namespace trantor;
#ifndef O_CLOEXEC #ifndef O_CLOEXEC
#define O_CLOEXEC O_NOINHERIT #define O_CLOEXEC O_NOINHERIT

View File

@ -36,7 +36,6 @@
#include "event_loop.h" #include "event_loop.h"
#include <functional> #include <functional>
namespace trantor {
using NewConnectionCallback = std::function<void(int fd, const InetAddress &)>; using NewConnectionCallback = std::function<void(int fd, const InetAddress &)>;
class Acceptor { class Acceptor {
protected: protected:
@ -71,4 +70,3 @@ protected:
Channel acceptChannel_; Channel acceptChannel_;
void readCallback(); void readCallback();
}; };
} // namespace trantor

View File

@ -32,8 +32,7 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
namespace trantor
{
enum class SSLError enum class SSLError
{ {
kSSLHandshakeError, kSSLHandshakeError,
@ -56,4 +55,3 @@ using HighWaterMarkCallback =
std::function<void(const TcpConnectionPtr &, const size_t)>; std::function<void(const TcpConnectionPtr &, const size_t)>;
using SSLErrorCallback = std::function<void(SSLError)>; using SSLErrorCallback = std::function<void(SSLError)>;
} // namespace trantor

View File

@ -43,7 +43,7 @@
#include <poll.h> #include <poll.h>
#endif #endif
#include <iostream> #include <iostream>
namespace trantor {
const int Channel::kNoneEvent = 0; const int Channel::kNoneEvent = 0;
const int Channel::kReadEvent = POLLIN | POLLPRI; const int Channel::kReadEvent = POLLIN | POLLPRI;
@ -111,4 +111,3 @@ void Channel::handleEventSafely() {
} }
} }
} // namespace trantor

View File

@ -35,7 +35,6 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
namespace trantor {
class EventLoop; class EventLoop;
/** /**
* @brief This class is used to implement reactor pattern. A Channel object * @brief This class is used to implement reactor pattern. A Channel object
@ -304,4 +303,3 @@ private:
std::weak_ptr<void> tie_; std::weak_ptr<void> tie_;
bool tied_; bool tied_;
}; };
} // namespace trantor

View File

@ -57,7 +57,6 @@ using ssize_t = long long;
#include <signal.h> #include <signal.h>
#include <algorithm> #include <algorithm>
namespace trantor {
#ifdef __linux__ #ifdef __linux__
int createEventfd() { int createEventfd() {
int evtfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); int evtfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
@ -334,5 +333,3 @@ void EventLoop::runOnQuit(Func &&cb) {
void EventLoop::runOnQuit(const Func &cb) { void EventLoop::runOnQuit(const Func &cb) {
funcsOnQuit_.enqueue(cb); funcsOnQuit_.enqueue(cb);
} }
} // namespace trantor

View File

@ -42,7 +42,6 @@
#include <thread> #include <thread>
#include <vector> #include <vector>
namespace trantor {
class Poller; class Poller;
class TimerQueue; class TimerQueue;
class Channel; class Channel;
@ -323,5 +322,3 @@ private:
#endif #endif
EventLoop **threadLocalLoopPtr_; EventLoop **threadLocalLoopPtr_;
}; };
} // namespace trantor

View File

@ -34,7 +34,6 @@
#include <sys/prctl.h> #include <sys/prctl.h>
#endif #endif
using namespace trantor;
EventLoopThread::EventLoopThread(const std::string &threadName) : EventLoopThread::EventLoopThread(const std::string &threadName) :
loop_(nullptr), loop_(nullptr),
loopThreadName_(threadName), loopThreadName_(threadName),

View File

@ -37,7 +37,6 @@
#include <mutex> #include <mutex>
#include <thread> #include <thread>
namespace trantor {
/** /**
* @brief This class represents an event loop thread. * @brief This class represents an event loop thread.
* *
@ -86,5 +85,3 @@ private:
std::once_flag once_; std::once_flag once_;
std::thread thread_; std::thread thread_;
}; };
} // namespace trantor

View File

@ -30,7 +30,6 @@
#include "event_loop_thread_pool.h" #include "event_loop_thread_pool.h"
using namespace trantor;
EventLoopThreadPool::EventLoopThreadPool(size_t threadNum, EventLoopThreadPool::EventLoopThreadPool(size_t threadNum,
const std::string &name) : const std::string &name) :
loopIndex_(0) { loopIndex_(0) {

View File

@ -34,7 +34,6 @@
#include <memory> #include <memory>
#include <vector> #include <vector>
namespace trantor {
/** /**
* @brief This class represents a pool of EventLoopThread objects * @brief This class represents a pool of EventLoopThread objects
* *
@ -108,4 +107,3 @@ private:
std::vector<std::shared_ptr<EventLoopThread> > loopThreadVector_; std::vector<std::shared_ptr<EventLoopThread> > loopThreadVector_;
size_t loopIndex_; size_t loopIndex_;
}; };
} // namespace trantor

View File

@ -37,7 +37,8 @@
#else #else
#include "poller/kqueue.h" #include "poller/kqueue.h"
#endif #endif
using namespace trantor;
Poller *Poller::newPoller(EventLoop *loop) { Poller *Poller::newPoller(EventLoop *loop) {
#if defined __linux__ || defined _WIN32 #if defined __linux__ || defined _WIN32
return new EpollPoller(loop); return new EpollPoller(loop);

View File

@ -35,7 +35,6 @@
#include <map> #include <map>
#include <memory> #include <memory>
namespace trantor {
class Channel; class Channel;
#ifdef _WIN32 #ifdef _WIN32
using EventCallback = std::function<void(uint64_t)>; using EventCallback = std::function<void(uint64_t)>;
@ -70,4 +69,3 @@ public:
private: private:
EventLoop *ownerLoop_; EventLoop *ownerLoop_;
}; };
} // namespace trantor

View File

@ -48,7 +48,6 @@
#define EPOLL_CLOEXEC _O_NOINHERIT #define EPOLL_CLOEXEC _O_NOINHERIT
#endif #endif
namespace trantor {
#if defined __linux__ || defined _WIN32 #if defined __linux__ || defined _WIN32
#if defined __linux__ #if defined __linux__
@ -219,4 +218,3 @@ void EpollPoller::removeChannel(Channel *) {
} }
#endif #endif
} // namespace trantor

View File

@ -39,7 +39,6 @@
using EventList = std::vector<struct epoll_event>; using EventList = std::vector<struct epoll_event>;
#endif #endif
namespace trantor {
class Channel; class Channel;
class EpollPoller : public Poller { class EpollPoller : public Poller {
@ -74,4 +73,3 @@ private:
void fillActiveChannels(int numEvents, ChannelList *activeChannels) const; void fillActiveChannels(int numEvents, ChannelList *activeChannels) const;
#endif #endif
}; };
} // namespace trantor

View File

@ -41,7 +41,6 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
namespace trantor {
#ifdef USE_KQUEUE #ifdef USE_KQUEUE
namespace { namespace {
const int kNew = -1; const int kNew = -1;
@ -232,4 +231,3 @@ void KQueue::removeChannel(Channel *) {
void KQueue::resetAfterFork() { void KQueue::resetAfterFork() {
} }
#endif #endif
} // namespace trantor

View File

@ -41,7 +41,6 @@
using EventList = std::vector<struct kevent>; using EventList = std::vector<struct kevent>;
#endif #endif
namespace trantor {
class Channel; class Channel;
class KQueue : public Poller { class KQueue : public Poller {
@ -65,5 +64,3 @@ private:
void update(Channel *channel); void update(Channel *channel);
#endif #endif
}; };
} // namespace trantor

View File

@ -2,7 +2,7 @@
This library is based on [wepoll v1.5.8](https://github.com/piscisaureus/wepoll/commit/0598a791bf9cbbf480793d778930fc635b044980). This library is based on [wepoll v1.5.8](https://github.com/piscisaureus/wepoll/commit/0598a791bf9cbbf480793d778930fc635b044980).
An eventfd-like mechanism is added to it. After making the changes, we can wake up `trantor::EventLoop` from the epoll_wait() function. An eventfd-like mechanism is added to it. After making the changes, we can wake up `EventLoop` from the epoll_wait() function.
## Modifications ## Modifications

View File

@ -32,7 +32,6 @@
#include "core/log/logger.h" #include "core/log/logger.h"
#include "core/loops/event_loop.h" #include "core/loops/event_loop.h"
namespace trantor {
std::atomic<TimerId> Timer::timersCreated_ = ATOMIC_VAR_INIT(InvalidTimerId); std::atomic<TimerId> Timer::timersCreated_ = ATOMIC_VAR_INIT(InvalidTimerId);
Timer::Timer(const TimerCallback &cb, Timer::Timer(const TimerCallback &cb,
const TimePoint &when, const TimePoint &when,
@ -68,4 +67,3 @@ bool Timer::operator<(const Timer &t) const {
bool Timer::operator>(const Timer &t) const { bool Timer::operator>(const Timer &t) const {
return when_ > t.when_; return when_ > t.when_;
} }
} // namespace trantor

View File

@ -36,7 +36,6 @@
#include <functional> #include <functional>
#include <iostream> #include <iostream>
namespace trantor {
using TimerId = uint64_t; using TimerId = uint64_t;
using TimePoint = std::chrono::steady_clock::time_point; using TimePoint = std::chrono::steady_clock::time_point;
using TimeInterval = std::chrono::microseconds; using TimeInterval = std::chrono::microseconds;
@ -82,4 +81,3 @@ private:
static std::atomic<TimerId> timersCreated_; static std::atomic<TimerId> timersCreated_;
}; };
} // namespace trantor

View File

@ -41,7 +41,6 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
using namespace trantor;
#ifdef __linux__ #ifdef __linux__
static int createTimerfd() { static int createTimerfd() {
int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);

View File

@ -37,7 +37,6 @@
#include <queue> #include <queue>
#include <unordered_set> #include <unordered_set>
namespace trantor {
// class Timer; // class Timer;
class EventLoop; class EventLoop;
class Channel; class Channel;
@ -92,4 +91,3 @@ protected:
private: private:
std::unordered_set<uint64_t> timerIdSet_; std::unordered_set<uint64_t> timerIdSet_;
}; };
} // namespace trantor

View File

@ -30,9 +30,8 @@
#include "core/loops/timing_wheel.h" #include "core/loops/timing_wheel.h"
using namespace trantor;
TimingWheel::TimingWheel(trantor::EventLoop *loop, TimingWheel::TimingWheel(EventLoop *loop,
size_t maxTimeout, size_t maxTimeout,
float ticksInterval, float ticksInterval,
size_t bucketsNumPerWheel) : size_t bucketsNumPerWheel) :

View File

@ -45,8 +45,6 @@
#define TIMING_BUCKET_NUM_PER_WHEEL 100 #define TIMING_BUCKET_NUM_PER_WHEEL 100
#define TIMING_TICK_INTERVAL 1.0 #define TIMING_TICK_INTERVAL 1.0
namespace trantor
{
using EntryPtr = std::shared_ptr<void>; using EntryPtr = std::shared_ptr<void>;
using EntryBucket = std::unordered_set<EntryPtr>; using EntryBucket = std::unordered_set<EntryPtr>;
@ -88,7 +86,7 @@ class TimingWheel
* @example Four wheels with 200 buckets per wheel means the timing wheel * @example Four wheels with 200 buckets per wheel means the timing wheel
* can work with a timeout up to 200^4 seconds, about 50 years; * can work with a timeout up to 200^4 seconds, about 50 years;
*/ */
TimingWheel(trantor::EventLoop *loop, TimingWheel(EventLoop *loop,
size_t maxTimeout, size_t maxTimeout,
float ticksInterval = TIMING_TICK_INTERVAL, float ticksInterval = TIMING_TICK_INTERVAL,
size_t bucketsNumPerWheel = TIMING_BUCKET_NUM_PER_WHEEL); size_t bucketsNumPerWheel = TIMING_BUCKET_NUM_PER_WHEEL);
@ -109,11 +107,10 @@ class TimingWheel
std::atomic<size_t> ticksCounter_{0}; std::atomic<size_t> ticksCounter_{0};
trantor::TimerId timerId_; TimerId timerId_;
trantor::EventLoop *loop_; EventLoop *loop_;
float ticksInterval_; float ticksInterval_;
size_t wheelsNum_; size_t wheelsNum_;
size_t bucketsNumPerWheel_; size_t bucketsNumPerWheel_;
}; };
} // namespace trantor

View File

@ -41,7 +41,6 @@
#include <time.h> #include <time.h>
#endif #endif
namespace trantor {
#ifdef _WIN32 #ifdef _WIN32
int gettimeofday(timeval *tp, void *tzp) { int gettimeofday(timeval *tp, void *tzp) {
time_t clock; time_t clock;
@ -295,7 +294,7 @@ Date Date::fromDbStringLocal(const std::string &datetime) {
} }
} }
return std::move( return std::move(
trantor::Date(year, month, day, hour, minute, second, microSecond)); Date(year, month, day, hour, minute, second, microSecond));
} }
std::string Date::toCustomedFormattedStringLocal(const std::string &fmtStr, std::string Date::toCustomedFormattedStringLocal(const std::string &fmtStr,
bool showMicroseconds) const { bool showMicroseconds) const {
@ -337,5 +336,3 @@ Date::Date(unsigned int year,
epoch = mktime(&tm); epoch = mktime(&tm);
microSecondsSinceEpoch_ = epoch * MICRO_SECONDS_PRE_SEC + microSecond; microSecondsSinceEpoch_ = epoch * MICRO_SECONDS_PRE_SEC + microSecond;
} }
} // namespace trantor

View File

@ -35,8 +35,6 @@
#define MICRO_SECONDS_PRE_SEC 1000000 #define MICRO_SECONDS_PRE_SEC 1000000
namespace trantor
{
/** /**
* @brief This class represents a time point. * @brief This class represents a time point.
* *
@ -293,4 +291,3 @@ class Date
private: private:
int64_t microSecondsSinceEpoch_{0}; int64_t microSecondsSinceEpoch_{0};
}; };
} // namespace trantor

View File

@ -324,7 +324,7 @@ public:
return hf; return hf;
} }
// Taken from trantor (MIT License) - Funcs.h // Taken from Trantor (BSD-style License) - Funcs.h
// Copyright (c) 2018 An Tao // Copyright (c) 2018 An Tao
static _ALWAYS_INLINE_ uint64_t hton64(uint64_t n) { static _ALWAYS_INLINE_ uint64_t hton64(uint64_t n) {
static const int one = 1; static const int one = 1;
@ -336,7 +336,7 @@ public:
return n; return n;
} }
// Taken from trantor (MIT License) - Funcs.h // Taken from Trantor (BSD-style License) - Funcs.h
// Copyright (c) 2018 An Tao // Copyright (c) 2018 An Tao
static _ALWAYS_INLINE_ uint64_t ntoh64(uint64_t n) { static _ALWAYS_INLINE_ uint64_t ntoh64(uint64_t n) {
return hton64(n); return hton64(n);

View File

@ -54,10 +54,7 @@
#endif #endif
#include <regex> #include <regex>
using namespace trantor;
#ifdef USE_OPENSSL #ifdef USE_OPENSSL
namespace trantor {
namespace internal { namespace internal {
#ifdef _WIN32 #ifdef _WIN32
// Code yanked from stackoverflow // Code yanked from stackoverflow
@ -316,9 +313,9 @@ std::shared_ptr<SSLContext> newSSLServerContext(
} }
return ctx; return ctx;
} }
} // namespace trantor
#else #else
namespace trantor {
std::shared_ptr<SSLContext> newSSLServerContext( std::shared_ptr<SSLContext> newSSLServerContext(
const std::string &certPath, const std::string &certPath,
const std::string &keyPath, const std::string &keyPath,
@ -327,7 +324,7 @@ std::shared_ptr<SSLContext> newSSLServerContext(
LOG_FATAL << "OpenSSL is not found in your system!"; LOG_FATAL << "OpenSSL is not found in your system!";
abort(); abort();
} }
} // namespace trantor
#endif #endif
TcpConnectionImpl::TcpConnectionImpl(EventLoop *loop, TcpConnectionImpl::TcpConnectionImpl(EventLoop *loop,

View File

@ -40,8 +40,7 @@
#include <thread> #include <thread>
#include <array> #include <array>
namespace trantor
{
#ifdef USE_OPENSSL #ifdef USE_OPENSSL
enum class SSLStatus enum class SSLStatus
{ {
@ -77,7 +76,7 @@ class TcpConnectionImpl : public TcpConnection,
{ {
friend class TcpServer; friend class TcpServer;
friend class TcpClient; friend class TcpClient;
friend void trantor::removeConnection(EventLoop *loop, friend void removeConnection(EventLoop *loop,
const TcpConnectionPtr &conn); const TcpConnectionPtr &conn);
protected: protected:
@ -363,5 +362,3 @@ protected:
}; };
using TcpConnectionImplPtr = std::shared_ptr<TcpConnectionImpl>; using TcpConnectionImplPtr = std::shared_ptr<TcpConnectionImpl>;
} // namespace trantor

View File

@ -32,8 +32,6 @@
#include "core/loops/channel.h" #include "core/loops/channel.h"
#include "core/net/socket.h" #include "core/net/socket.h"
using namespace trantor;
Connector::Connector(EventLoop *loop, const InetAddress &addr, bool retry) : Connector::Connector(EventLoop *loop, const InetAddress &addr, bool retry) :
loop_(loop), serverAddr_(addr), retry_(retry) { loop_(loop), serverAddr_(addr), retry_(retry) {
} }

View File

@ -35,7 +35,6 @@
#include <atomic> #include <atomic>
#include <memory> #include <memory>
namespace trantor {
class Connector : public std::enable_shared_from_this<Connector> { class Connector : public std::enable_shared_from_this<Connector> {
protected: protected:
Connector(const Connector &) = delete; Connector(const Connector &) = delete;
@ -98,5 +97,3 @@ private:
void handleError(); void handleError();
void retry(int sockfd); void retry(int sockfd);
}; };
} // namespace trantor

View File

@ -71,7 +71,6 @@ static const in_addr_t kInaddrLoopback = INADDR_LOOPBACK;
// uint32_t sin6_scope_id; /* IPv6 scope-id */ // uint32_t sin6_scope_id; /* IPv6 scope-id */
// }; // };
using namespace trantor;
/* /*
#ifdef __linux__ #ifdef __linux__

View File

@ -46,8 +46,6 @@ using uint16_t = unsigned short;
#include <unordered_map> #include <unordered_map>
#include <mutex> #include <mutex>
namespace trantor
{
/** /**
* @brief Wrapper of sockaddr_in. This is an POD interface class. * @brief Wrapper of sockaddr_in. This is an POD interface class.
* *
@ -231,6 +229,4 @@ class InetAddress
bool isUnspecified_{true}; bool isUnspecified_{true};
}; };
} // namespace trantor
#endif // MUDUO_NET_INETADDRESS_H #endif // MUDUO_NET_INETADDRESS_H

View File

@ -34,8 +34,6 @@
#include "core/loops/event_loop.h" #include "core/loops/event_loop.h"
#include "core/net/inet_address.h" #include "core/net/inet_address.h"
namespace trantor
{
/** /**
* @brief This class represents an asynchronous DNS resolver. * @brief This class represents an asynchronous DNS resolver.
* @note Although the c-ares library is not essential, it is recommended to * @note Although the c-ares library is not essential, it is recommended to
@ -44,7 +42,7 @@ namespace trantor
class Resolver class Resolver
{ {
public: public:
using Callback = std::function<void(const trantor::InetAddress&)>; using Callback = std::function<void(const InetAddress&)>;
/** /**
* @brief Create a new DNS resolver. * @brief Create a new DNS resolver.
@ -77,4 +75,3 @@ class Resolver
*/ */
static bool isCAresUsed(); static bool isCAresUsed();
}; };
} // namespace trantor

View File

@ -42,10 +42,8 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
using namespace trantor;
using namespace std::placeholders; using namespace std::placeholders;
namespace {
double getSeconds(struct timeval *tv) { double getSeconds(struct timeval *tv) {
if (tv) if (tv)
return double(tv->tv_sec) + double(tv->tv_usec) / 1000000.0; return double(tv->tv_sec) + double(tv->tv_usec) / 1000000.0;
@ -62,8 +60,6 @@ const char *getSocketType(int type) {
return "Unknown"; return "Unknown";
} }
} // namespace
bool Resolver::isCAresUsed() { bool Resolver::isCAresUsed() {
return true; return true;
} }
@ -77,7 +73,7 @@ AresResolver::LibraryInitializer::~LibraryInitializer() {
AresResolver::LibraryInitializer AresResolver::libraryInitializer_; AresResolver::LibraryInitializer AresResolver::libraryInitializer_;
std::shared_ptr<Resolver> Resolver::newResolver(trantor::EventLoop *loop, std::shared_ptr<Resolver> Resolver::newResolver(EventLoop *loop,
size_t timeout) { size_t timeout) {
return std::make_shared<AresResolver>(loop, timeout); return std::make_shared<AresResolver>(loop, timeout);
} }
@ -122,7 +118,7 @@ void AresResolver::resolveInLoop(const std::string &hostname,
loop_->assertInLoopThread(); loop_->assertInLoopThread();
#ifdef _WIN32 #ifdef _WIN32
if (hostname == "localhost") { if (hostname == "localhost") {
const static trantor::InetAddress localhost_{ "127.0.0.1", 0 }; const static InetAddress localhost_{ "127.0.0.1", 0 };
cb(localhost_); cb(localhost_);
return; return;
} }
@ -182,7 +178,7 @@ void AresResolver::onQueryResult(int status,
std::lock_guard<std::mutex> lock(globalMutex()); std::lock_guard<std::mutex> lock(globalMutex());
auto &addrItem = globalCache()[hostname]; auto &addrItem = globalCache()[hostname];
addrItem.first = addr.sin_addr; addrItem.first = addr.sin_addr;
addrItem.second = trantor::Date::date(); addrItem.second = Date::date();
} }
callback(inet); callback(inet);
} }

View File

@ -41,7 +41,7 @@ struct hostent;
struct ares_channeldata; struct ares_channeldata;
using ares_channel = struct ares_channeldata *; using ares_channel = struct ares_channeldata *;
} }
namespace trantor {
class AresResolver : public Resolver, class AresResolver : public Resolver,
public std::enable_shared_from_this<AresResolver> { public std::enable_shared_from_this<AresResolver> {
protected: protected:
@ -52,7 +52,7 @@ protected:
AresResolver &operator=(AresResolver &&) noexcept(true) = default; AresResolver &operator=(AresResolver &&) noexcept(true) = default;
public: public:
AresResolver(trantor::EventLoop *loop, size_t timeout); AresResolver(EventLoop *loop, size_t timeout);
~AresResolver(); ~AresResolver();
virtual void resolve(const std::string &hostname, virtual void resolve(const std::string &hostname,
@ -65,7 +65,7 @@ public:
if (iter != globalCache().end()) { if (iter != globalCache().end()) {
auto &cachedAddr = iter->second; auto &cachedAddr = iter->second;
if (timeout_ == 0 || if (timeout_ == 0 ||
cachedAddr.second.after(timeout_) > trantor::Date::date()) { cachedAddr.second.after(timeout_) > Date::date()) {
struct sockaddr_in addr; struct sockaddr_in addr;
memset(&addr, 0, sizeof addr); memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
@ -102,16 +102,16 @@ private:
}; };
void resolveInLoop(const std::string &hostname, const Callback &cb); void resolveInLoop(const std::string &hostname, const Callback &cb);
void init(); void init();
trantor::EventLoop *loop_; EventLoop *loop_;
ares_channel ctx_{ nullptr }; ares_channel ctx_{ nullptr };
bool timerActive_{ false }; bool timerActive_{ false };
using ChannelList = std::map<int, std::unique_ptr<trantor::Channel> >; using ChannelList = std::map<int, std::unique_ptr<Channel> >;
ChannelList channels_; ChannelList channels_;
static std::unordered_map<std::string, static std::unordered_map<std::string,
std::pair<struct in_addr, trantor::Date> > & std::pair<struct in_addr, Date> > &
globalCache() { globalCache() {
static std::unordered_map<std::string, static std::unordered_map<std::string,
std::pair<struct in_addr, trantor::Date> > std::pair<struct in_addr, Date> >
dnsCache; dnsCache;
return dnsCache; return dnsCache;
} }
@ -158,4 +158,3 @@ private:
}; };
static LibraryInitializer libraryInitializer_; static LibraryInitializer libraryInitializer_;
}; };
} // namespace trantor

View File

@ -40,9 +40,7 @@
#include <sys/socket.h> #include <sys/socket.h>
#endif #endif
using namespace trantor; std::shared_ptr<Resolver> Resolver::newResolver(EventLoop *,
std::shared_ptr<Resolver> Resolver::newResolver(trantor::EventLoop *,
size_t timeout) { size_t timeout) {
return std::make_shared<NormalResolver>(timeout); return std::make_shared<NormalResolver>(timeout);
} }
@ -57,7 +55,7 @@ void NormalResolver::resolve(const std::string &hostname,
if (iter != globalCache().end()) { if (iter != globalCache().end()) {
auto &cachedAddr = iter->second; auto &cachedAddr = iter->second;
if (timeout_ == 0 || cachedAddr.second.after(static_cast<double>( if (timeout_ == 0 || cachedAddr.second.after(static_cast<double>(
timeout_)) > trantor::Date::date()) { timeout_)) > Date::date()) {
callback(cachedAddr.first); callback(cachedAddr.first);
return; return;
} }
@ -73,7 +71,7 @@ void NormalResolver::resolve(const std::string &hostname,
auto &cachedAddr = iter->second; auto &cachedAddr = iter->second;
if (thisPtr->timeout_ == 0 || if (thisPtr->timeout_ == 0 ||
cachedAddr.second.after(static_cast<double>( cachedAddr.second.after(static_cast<double>(
thisPtr->timeout_)) > trantor::Date::date()) { thisPtr->timeout_)) > Date::date()) {
callback(cachedAddr.first); callback(cachedAddr.first);
return; return;
} }
@ -107,7 +105,7 @@ void NormalResolver::resolve(const std::string &hostname,
std::lock_guard<std::mutex> guard(thisPtr->globalMutex()); std::lock_guard<std::mutex> guard(thisPtr->globalMutex());
auto &addrItem = thisPtr->globalCache()[hostname]; auto &addrItem = thisPtr->globalCache()[hostname];
addrItem.first = inet; addrItem.first = inet;
addrItem.second = trantor::Date::date(); addrItem.second = Date::date();
} }
return; return;
}); });

View File

@ -35,8 +35,8 @@
#include <thread> #include <thread>
#include <vector> #include <vector>
namespace trantor {
constexpr size_t kResolveBufferLength{ 16 * 1024 }; constexpr size_t kResolveBufferLength{ 16 * 1024 };
class NormalResolver : public Resolver, class NormalResolver : public Resolver,
public std::enable_shared_from_this<NormalResolver> { public std::enable_shared_from_this<NormalResolver> {
protected: protected:
@ -57,11 +57,11 @@ public:
private: private:
static std::unordered_map<std::string, static std::unordered_map<std::string,
std::pair<trantor::InetAddress, trantor::Date> > & std::pair<InetAddress, Date> > &
globalCache() { globalCache() {
static std::unordered_map< static std::unordered_map<
std::string, std::string,
std::pair<trantor::InetAddress, trantor::Date> > std::pair<InetAddress, Date> >
dnsCache_; dnsCache_;
return dnsCache_; return dnsCache_;
} }
@ -69,8 +69,8 @@ private:
static std::mutex mutex_; static std::mutex mutex_;
return mutex_; return mutex_;
} }
static trantor::ConcurrentTaskQueue &concurrentTaskQueue() { static ConcurrentTaskQueue &concurrentTaskQueue() {
static trantor::ConcurrentTaskQueue queue( static ConcurrentTaskQueue queue(
std::thread::hardware_concurrency() < 8 ? 8 : std::thread::hardware_concurrency(), std::thread::hardware_concurrency() < 8 ? 8 : std::thread::hardware_concurrency(),
"Dns Queue"); "Dns Queue");
return queue; return queue;
@ -78,4 +78,3 @@ private:
const size_t timeout_; const size_t timeout_;
std::vector<char> resolveBuffer_; std::vector<char> resolveBuffer_;
}; };
} // namespace trantor

View File

@ -39,7 +39,6 @@
#include <sys/socket.h> #include <sys/socket.h>
#endif #endif
using namespace trantor;
bool Socket::isSelfConnect(int sockfd) { bool Socket::isSelfConnect(int sockfd) {
struct sockaddr_in6 localaddr = getLocalAddr(sockfd); struct sockaddr_in6 localaddr = getLocalAddr(sockfd);

View File

@ -40,7 +40,6 @@
#endif #endif
#include <fcntl.h> #include <fcntl.h>
namespace trantor {
class Socket { class Socket {
protected: protected:
@ -167,5 +166,3 @@ public:
#endif #endif
} }
}; };
} // namespace trantor

View File

@ -32,9 +32,9 @@
#include "core/net/tcp_client.h" #include "core/net/tcp_client.h"
#include "connector.h" #include "connector.h"
#include "core/net/connections/tcp_connection_impl.h"
#include "core/loops/event_loop.h"
#include "core/log/logger.h" #include "core/log/logger.h"
#include "core/loops/event_loop.h"
#include "core/net/connections/tcp_connection_impl.h"
#include <algorithm> #include <algorithm>
#include <functional> #include <functional>
@ -43,10 +43,8 @@
#include <stdio.h> // snprintf #include <stdio.h> // snprintf
using namespace trantor;
using namespace std::placeholders; using namespace std::placeholders;
namespace trantor {
// void removeConnector(const ConnectorPtr &) // void removeConnector(const ConnectorPtr &)
// { // {
// // connector-> // // connector->
@ -67,8 +65,6 @@ static void defaultMessageCallback(const TcpConnectionPtr &, MsgBuffer *buf) {
buf->retrieveAll(); buf->retrieveAll();
} }
} // namespace trantor
TcpClient::TcpClient(EventLoop *loop, TcpClient::TcpClient(EventLoop *loop,
const InetAddress &serverAddr, const InetAddress &serverAddr,
const std::string &nameArg) : const std::string &nameArg) :

View File

@ -39,7 +39,6 @@
#include <functional> #include <functional>
#include <thread> #include <thread>
namespace trantor {
class Connector; class Connector;
using ConnectorPtr = std::shared_ptr<Connector>; using ConnectorPtr = std::shared_ptr<Connector>;
class SSLContext; class SSLContext;
@ -246,5 +245,3 @@ private:
static IgnoreSigPipe initObj; static IgnoreSigPipe initObj;
#endif #endif
}; };
} // namespace trantor

View File

@ -38,7 +38,6 @@
#include <memory> #include <memory>
#include <string> #include <string>
namespace trantor {
class SSLContext; class SSLContext;
std::shared_ptr<SSLContext> newSSLServerContext( std::shared_ptr<SSLContext> newSSLServerContext(
const std::string &certPath, const std::string &certPath,
@ -265,4 +264,3 @@ private:
std::shared_ptr<void> contextPtr_; std::shared_ptr<void> contextPtr_;
}; };
} // namespace trantor

View File

@ -34,7 +34,7 @@
#include "core/log/logger.h" #include "core/log/logger.h"
#include <functional> #include <functional>
#include <vector> #include <vector>
using namespace trantor;
using namespace std::placeholders; using namespace std::placeholders;
TcpServer::TcpServer(EventLoop *loop, TcpServer::TcpServer(EventLoop *loop,
@ -175,7 +175,7 @@ const std::string TcpServer::ipPort() const {
return acceptorPtr_->addr().toIpPort(); return acceptorPtr_->addr().toIpPort();
} }
const trantor::InetAddress &TcpServer::address() const { const InetAddress &TcpServer::address() const {
return acceptorPtr_->addr(); return acceptorPtr_->addr();
} }

View File

@ -41,7 +41,6 @@
#include <set> #include <set>
#include <string> #include <string>
namespace trantor {
class Acceptor; class Acceptor;
class SSLContext; class SSLContext;
/** /**
@ -169,9 +168,9 @@ public:
/** /**
* @brief Get the address of the server. * @brief Get the address of the server.
* *
* @return const trantor::InetAddress& * @return const InetAddress&
*/ */
const trantor::InetAddress &address() const; const InetAddress &address() const;
/** /**
* @brief Get the event loop of the server. * @brief Get the event loop of the server.
@ -253,5 +252,3 @@ private:
// OpenSSL SSL context Object; // OpenSSL SSL context Object;
std::shared_ptr<SSLContext> sslCtxPtr_; std::shared_ptr<SSLContext> sslCtxPtr_;
}; };
} // namespace trantor

View File

@ -4,10 +4,10 @@
#include <thread> #include <thread>
int main() int main()
{ {
trantor::AsyncFileLogger asyncFileLogger; AsyncFileLogger asyncFileLogger;
asyncFileLogger.setFileName("async_test"); asyncFileLogger.setFileName("async_test");
asyncFileLogger.startLogging(); asyncFileLogger.startLogging();
trantor::Logger::setOutputFunction( Logger::setOutputFunction(
[&](const char *msg, const uint64_t len) { [&](const char *msg, const uint64_t len) {
asyncFileLogger.output(msg, len); asyncFileLogger.output(msg, len);
}, },

View File

@ -7,10 +7,10 @@
using namespace std::chrono_literals; using namespace std::chrono_literals;
int main() int main()
{ {
trantor::AsyncFileLogger asyncFileLogger; AsyncFileLogger asyncFileLogger;
asyncFileLogger.setFileName("async_test"); asyncFileLogger.setFileName("async_test");
asyncFileLogger.startLogging(); asyncFileLogger.startLogging();
trantor::Logger::setOutputFunction( Logger::setOutputFunction(
[&](const char *msg, const uint64_t len) { [&](const char *msg, const uint64_t len) {
asyncFileLogger.output(msg, len); asyncFileLogger.output(msg, len);
}, },

View File

@ -10,7 +10,7 @@ using namespace std::chrono_literals;
int main() int main()
{ {
trantor::ConcurrentTaskQueue queue(5, "concurrT"); ConcurrentTaskQueue queue(5, "concurrT");
std::atomic_int sum; std::atomic_int sum;
sum = 0; sum = 0;
for (int i = 0; i < 4; ++i) for (int i = 0; i < 4; ++i)

View File

@ -4,11 +4,11 @@
#include <string> #include <string>
#include <iostream> #include <iostream>
#include <atomic> #include <atomic>
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main() int main()
{ {
trantor::Logger::setLogLevel(trantor::Logger::kTrace); Logger::setLogLevel(Logger::kTrace);
LOG_DEBUG << "TcpClient class test!"; LOG_DEBUG << "TcpClient class test!";
EventLoop loop; EventLoop loop;
#if USE_IPV6 #if USE_IPV6
@ -16,12 +16,12 @@ int main()
#else #else
InetAddress serverAddr("127.0.0.1", 8888); InetAddress serverAddr("127.0.0.1", 8888);
#endif #endif
std::shared_ptr<trantor::TcpClient> client[10]; std::shared_ptr<TcpClient> client[10];
std::atomic_int connCount; std::atomic_int connCount;
connCount = 10; connCount = 10;
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
{ {
client[i] = std::make_shared<trantor::TcpClient>(&loop, client[i] = std::make_shared<TcpClient>(&loop,
serverAddr, serverAddr,
"tcpclienttest"); "tcpclienttest");
client[i]->setConnectionCallback( client[i]->setConnectionCallback(

View File

@ -3,7 +3,7 @@
#include "core/loops/event_loop_thread.h" #include "core/loops/event_loop_thread.h"
#include <string> #include <string>
#include <iostream> #include <iostream>
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main() int main()
{ {

View File

@ -1,38 +1,38 @@
#include "core/net/resolver.h" #include "core/net/resolver.h"
#include <iostream> #include <iostream>
void dns(const std::shared_ptr<trantor::Resolver> &resolver) void dns(const std::shared_ptr<Resolver> &resolver)
{ {
auto now = trantor::Date::now(); auto now = Date::now();
resolver->resolve("www.baidu.com", [now](const trantor::InetAddress &addr) { resolver->resolve("www.baidu.com", [now](const InetAddress &addr) {
auto interval = trantor::Date::now().microSecondsSinceEpoch() - auto interval = Date::now().microSecondsSinceEpoch() -
now.microSecondsSinceEpoch(); now.microSecondsSinceEpoch();
std::cout << "baidu:" << addr.toIp() << " " << interval / 1000 << "ms" std::cout << "baidu:" << addr.toIp() << " " << interval / 1000 << "ms"
<< std::endl; << std::endl;
}); });
resolver->resolve("www.google.com", resolver->resolve("www.google.com",
[now](const trantor::InetAddress &addr) { [now](const InetAddress &addr) {
auto interval = auto interval =
trantor::Date::now().microSecondsSinceEpoch() - Date::now().microSecondsSinceEpoch() -
now.microSecondsSinceEpoch(); now.microSecondsSinceEpoch();
std::cout << "google:" << addr.toIp() << " " std::cout << "google:" << addr.toIp() << " "
<< interval / 1000 << "ms" << std::endl; << interval / 1000 << "ms" << std::endl;
}); });
resolver->resolve("www.sina.com", [now](const trantor::InetAddress &addr) { resolver->resolve("www.sina.com", [now](const InetAddress &addr) {
auto interval = trantor::Date::now().microSecondsSinceEpoch() - auto interval = Date::now().microSecondsSinceEpoch() -
now.microSecondsSinceEpoch(); now.microSecondsSinceEpoch();
std::cout << "sina:" << addr.toIp() << " " << interval / 1000 << "ms" std::cout << "sina:" << addr.toIp() << " " << interval / 1000 << "ms"
<< std::endl; << std::endl;
}); });
resolver->resolve("www.xjfisfjaskfeiakdjfg.com", resolver->resolve("www.xjfisfjaskfeiakdjfg.com",
[now](const trantor::InetAddress &addr) { [now](const InetAddress &addr) {
auto interval = auto interval =
trantor::Date::now().microSecondsSinceEpoch() - Date::now().microSecondsSinceEpoch() -
now.microSecondsSinceEpoch(); now.microSecondsSinceEpoch();
std::cout << "bad address:" << addr.toIp() << " " std::cout << "bad address:" << addr.toIp() << " "
<< interval / 1000 << "ms" << std::endl; << interval / 1000 << "ms" << std::endl;
}); });
resolver->resolve("localhost", [now](const trantor::InetAddress &addr) { resolver->resolve("localhost", [now](const InetAddress &addr) {
auto interval = trantor::Date::now().microSecondsSinceEpoch() - auto interval = Date::now().microSecondsSinceEpoch() -
now.microSecondsSinceEpoch(); now.microSecondsSinceEpoch();
std::cout << "localhost:" << addr.toIp() << " " << interval / 1000 std::cout << "localhost:" << addr.toIp() << " " << interval / 1000
<< "ms" << std::endl; << "ms" << std::endl;
@ -40,8 +40,8 @@ void dns(const std::shared_ptr<trantor::Resolver> &resolver)
} }
int main() int main()
{ {
trantor::EventLoop loop; EventLoop loop;
auto resolver = trantor::Resolver::newResolver(&loop); auto resolver = Resolver::newResolver(&loop);
dns(resolver); dns(resolver);
loop.runAfter(1.0, [resolver]() { dns(resolver); }); loop.runAfter(1.0, [resolver]() { dns(resolver); });
loop.loop(); loop.loop();

View File

@ -3,7 +3,7 @@
#include "core/loops/event_loop_thread.h" #include "core/loops/event_loop_thread.h"
#include <string> #include <string>
#include <iostream> #include <iostream>
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main() int main()
{ {

View File

@ -8,7 +8,7 @@ int main()
LOG_DEBUG << (const char)'8'; LOG_DEBUG << (const char)'8';
LOG_DEBUG << &i; LOG_DEBUG << &i;
LOG_DEBUG << (long double)3.1415; LOG_DEBUG << (long double)3.1415;
LOG_DEBUG << trantor::Fmt("%.3g", 3.1415926); LOG_DEBUG << Fmt("%.3g", 3.1415926);
LOG_DEBUG << "debug log!" << 1; LOG_DEBUG << "debug log!" << 1;
LOG_TRACE << "trace log!" << 2; LOG_TRACE << "trace log!" << 2;
LOG_INFO << "info log!" << 3; LOG_INFO << "info log!" << 3;

View File

@ -13,7 +13,7 @@
using namespace std::chrono_literals; using namespace std::chrono_literals;
int main() int main()
{ {
trantor::EventLoop loop; EventLoop loop;
std::thread thread([&loop]() { std::thread thread([&loop]() {
std::this_thread::sleep_for(3s); std::this_thread::sleep_for(3s);
loop.runInLoop([&loop]() { loop.runInLoop([&loop]() {

View File

@ -12,7 +12,7 @@ int main()
counter = 0; counter = 0;
std::promise<int> pro; std::promise<int> pro;
auto ft = pro.get_future(); auto ft = pro.get_future();
trantor::EventLoopThread loopThread; EventLoopThread loopThread;
auto loop = loopThread.getLoop(); auto loop = loopThread.getLoop();
loop->runInLoop([&counter, &pro, loop]() { loop->runInLoop([&counter, &pro, loop]() {

View File

@ -10,7 +10,7 @@ int main()
{ {
std::atomic<bool> flag(false); std::atomic<bool> flag(false);
{ {
trantor::EventLoopThread thr; EventLoopThread thr;
thr.getLoop()->runOnQuit([&]() { flag = true; }); thr.getLoop()->runOnQuit([&]() { flag = true; });
thr.run(); thr.run();
thr.getLoop()->quit(); thr.getLoop()->quit();

View File

@ -4,11 +4,11 @@
#include <string> #include <string>
#include <iostream> #include <iostream>
#include <atomic> #include <atomic>
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main() int main()
{ {
trantor::Logger::setLogLevel(trantor::Logger::kTrace); Logger::setLogLevel(Logger::kTrace);
LOG_DEBUG << "TcpClient class test!"; LOG_DEBUG << "TcpClient class test!";
EventLoop loop; EventLoop loop;
#if USE_IPV6 #if USE_IPV6
@ -16,12 +16,12 @@ int main()
#else #else
InetAddress serverAddr("127.0.0.1", 8888); InetAddress serverAddr("127.0.0.1", 8888);
#endif #endif
std::shared_ptr<trantor::TcpClient> client[10]; std::shared_ptr<TcpClient> client[10];
std::atomic_int connCount; std::atomic_int connCount;
connCount = 1; connCount = 1;
for (int i = 0; i < connCount; ++i) for (int i = 0; i < connCount; ++i)
{ {
client[i] = std::make_shared<trantor::TcpClient>(&loop, client[i] = std::make_shared<TcpClient>(&loop,
serverAddr, serverAddr,
"tcpclienttest"); "tcpclienttest");
client[i]->enableSSL(false, false); client[i]->enableSSL(false, false);

View File

@ -3,7 +3,7 @@
#include "core/loops/event_loop_thread.h" #include "core/loops/event_loop_thread.h"
#include <string> #include <string>
#include <iostream> #include <iostream>
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main() int main()
{ {

View File

@ -10,7 +10,7 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {

View File

@ -7,9 +7,9 @@
using namespace std::chrono_literals; using namespace std::chrono_literals;
int main() int main()
{ {
trantor::Logger::setLogLevel(trantor::Logger::kTrace); Logger::setLogLevel(Logger::kTrace);
trantor::SerialTaskQueue queue1("test queue1"); SerialTaskQueue queue1("test queue1");
trantor::SerialTaskQueue queue2(""); SerialTaskQueue queue2("");
queue1.runTaskInQueue([&]() { queue1.runTaskInQueue([&]() {
for (int i = 0; i < 5; ++i) for (int i = 0; i < 5; ++i)
{ {

View File

@ -12,7 +12,7 @@ int main()
counter = 0; counter = 0;
std::promise<int> pro; std::promise<int> pro;
auto ft = pro.get_future(); auto ft = pro.get_future();
trantor::SerialTaskQueue queue(""); SerialTaskQueue queue("");
queue.runTaskInQueue([&counter, &pro, &queue]() { queue.runTaskInQueue([&counter, &pro, &queue]() {
for (int i = 0; i < 10000; ++i) for (int i = 0; i < 10000; ++i)
{ {

View File

@ -4,11 +4,11 @@
#include <string> #include <string>
#include <iostream> #include <iostream>
#include <atomic> #include <atomic>
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main() int main()
{ {
trantor::Logger::setLogLevel(trantor::Logger::kTrace); Logger::setLogLevel(Logger::kTrace);
LOG_DEBUG << "TcpClient class test!"; LOG_DEBUG << "TcpClient class test!";
EventLoop loop; EventLoop loop;
#if USE_IPV6 #if USE_IPV6
@ -16,12 +16,12 @@ int main()
#else #else
InetAddress serverAddr("127.0.0.1", 8888); InetAddress serverAddr("127.0.0.1", 8888);
#endif #endif
std::shared_ptr<trantor::TcpClient> client[10]; std::shared_ptr<TcpClient> client[10];
std::atomic_int connCount; std::atomic_int connCount;
connCount = 10; connCount = 10;
for (int i = 0; i < 10; ++i) for (int i = 0; i < 10; ++i)
{ {
client[i] = std::make_shared<trantor::TcpClient>(&loop, client[i] = std::make_shared<TcpClient>(&loop,
serverAddr, serverAddr,
"tcpclienttest"); "tcpclienttest");
client[i]->setConnectionCallback( client[i]->setConnectionCallback(

View File

@ -3,7 +3,7 @@
#include "core/loops/event_loop_thread.h" #include "core/loops/event_loop_thread.h"
#include <string> #include <string>
#include <iostream> #include <iostream>
using namespace trantor;
#define USE_IPV6 0 #define USE_IPV6 0
int main() int main()
{ {

View File

@ -7,8 +7,8 @@ using namespace std::literals;
int main() int main()
{ {
trantor::Logger::setLogLevel(trantor::Logger::kTrace); Logger::setLogLevel(Logger::kTrace);
trantor::EventLoop loop; EventLoop loop;
auto id1 = loop.runAfter(1s, []() { auto id1 = loop.runAfter(1s, []() {
LOG_ERROR << "This info shouldn't be displayed!"; LOG_ERROR << "This info shouldn't be displayed!";
}); });
@ -22,7 +22,7 @@ int main()
}); });
thread.detach(); thread.detach();
loop.runEvery(3, []() { LOG_DEBUG << " runEvery 3s"; }); loop.runEvery(3, []() { LOG_DEBUG << " runEvery 3s"; });
loop.runAt(trantor::Date::date().after(10), loop.runAt(Date::date().after(10),
[]() { LOG_DEBUG << "runAt 10s later"; }); []() { LOG_DEBUG << "runAt 10s later"; });
loop.runAfter(5, []() { std::cout << "runAt 5s later" << std::endl; }); loop.runAfter(5, []() { std::cout << "runAt 5s later" << std::endl; });
loop.runEvery(1, []() { std::cout << "runEvery 1s" << std::endl; }); loop.runEvery(1, []() { std::cout << "runEvery 1s" << std::endl; });

View File

@ -3,9 +3,9 @@
#include <iostream> #include <iostream>
int main() int main()
{ {
trantor::EventLoop loop; EventLoop loop;
LOG_FATAL << trantor::Date::date().roundDay().microSecondsSinceEpoch(); LOG_FATAL << Date::date().roundDay().microSecondsSinceEpoch();
trantor::Date begin = trantor::Date::date().roundSecond().after(2); Date begin = Date::date().roundSecond().after(2);
auto id = loop.runAt(begin, [begin, &loop]() { auto id = loop.runAt(begin, [begin, &loop]() {
LOG_DEBUG << "test begin:"; LOG_DEBUG << "test begin:";
srand((unsigned int)time(NULL)); srand((unsigned int)time(NULL));

View File

@ -26,9 +26,9 @@ MyClass::~MyClass()
int main() int main()
{ {
LOG_DEBUG << "start"; LOG_DEBUG << "start";
trantor::EventLoop loop; EventLoop loop;
std::weak_ptr<MyClass> weakEntry; std::weak_ptr<MyClass> weakEntry;
trantor::TimingWheel wheel(&loop, 75, 0.1, 100); TimingWheel wheel(&loop, 75, 0.1, 100);
{ {
auto entry = std::shared_ptr<MyClass>(new MyClass); auto entry = std::shared_ptr<MyClass>(new MyClass);

View File

@ -2,37 +2,37 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <string> #include <string>
#include <iostream> #include <iostream>
using namespace trantor;
TEST(Date, constructorTest) TEST(Date, constructorTest)
{ {
EXPECT_STREQ("1985-01-01 00:00:00", EXPECT_STREQ("1985-01-01 00:00:00",
trantor::Date(1985, 1, 1) Date(1985, 1, 1)
.toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S") .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S")
.c_str()); .c_str());
EXPECT_STREQ("2004-02-29 00:00:00.000000", EXPECT_STREQ("2004-02-29 00:00:00.000000",
trantor::Date(2004, 2, 29) Date(2004, 2, 29)
.toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true) .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true)
.c_str()); .c_str());
EXPECT_STRNE("2001-02-29 00:00:00.000000", EXPECT_STRNE("2001-02-29 00:00:00.000000",
trantor::Date(2001, 2, 29) Date(2001, 2, 29)
.toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true) .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true)
.c_str()); .c_str());
EXPECT_STREQ("2018-01-01 00:00:00.000000", EXPECT_STREQ("2018-01-01 00:00:00.000000",
trantor::Date(2018, 1, 1, 12, 12, 12, 2321) Date(2018, 1, 1, 12, 12, 12, 2321)
.roundDay() .roundDay()
.toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true) .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true)
.c_str()); .c_str());
} }
TEST(Date, DatabaseStringTest) TEST(Date, DatabaseStringTest)
{ {
auto now = trantor::Date::now(); auto now = Date::now();
EXPECT_EQ(now, trantor::Date::fromDbStringLocal(now.toDbStringLocal())); EXPECT_EQ(now, Date::fromDbStringLocal(now.toDbStringLocal()));
std::string dbString = "2018-01-01 00:00:00.123"; std::string dbString = "2018-01-01 00:00:00.123";
auto dbDate = trantor::Date::fromDbStringLocal(dbString); auto dbDate = Date::fromDbStringLocal(dbString);
auto ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000; auto ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000;
EXPECT_EQ(ms, 123); EXPECT_EQ(ms, 123);
dbString = "2018-01-01 00:00:00"; dbString = "2018-01-01 00:00:00";
dbDate = trantor::Date::fromDbStringLocal(dbString); dbDate = Date::fromDbStringLocal(dbString);
ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000; ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000;
EXPECT_EQ(ms, 0); EXPECT_EQ(ms, 0);
} }

View File

@ -2,7 +2,7 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <string> #include <string>
#include <iostream> #include <iostream>
using namespace trantor;
TEST(InetAddress, innerIpTest) TEST(InetAddress, innerIpTest)
{ {
EXPECT_EQ(true, InetAddress("192.168.0.1", 0).isIntranetIp()); EXPECT_EQ(true, InetAddress("192.168.0.1", 0).isIntranetIp());

View File

@ -2,7 +2,7 @@
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <string> #include <string>
#include <iostream> #include <iostream>
using namespace trantor;
TEST(MsgBufferTest, readableTest) TEST(MsgBufferTest, readableTest)
{ {
MsgBuffer buffer; MsgBuffer buffer;

View File

@ -1,7 +1,7 @@
#include "core/math/date.h" #include "core/math/date.h"
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <iostream> #include <iostream>
using namespace trantor;
TEST(splitString, ACCEPT_EMPTY_STRING1) TEST(splitString, ACCEPT_EMPTY_STRING1)
{ {
std::string originString = "1,2,3"; std::string originString = "1,2,3";
@ -31,7 +31,7 @@ TEST(splitString, ACCEPT_EMPTY_STRING4)
} }
TEST(splitString, ACCEPT_EMPTY_STRING5) TEST(splitString, ACCEPT_EMPTY_STRING5)
{ {
std::string originString = "trantor::splitString"; std::string originString = "splitString";
auto out = splitString(originString, "::", true); auto out = splitString(originString, "::", true);
EXPECT_EQ(out.size(), 2); EXPECT_EQ(out.size(), 2);
EXPECT_STREQ(out[0].data(), "trantor"); EXPECT_STREQ(out[0].data(), "trantor");
@ -39,7 +39,7 @@ TEST(splitString, ACCEPT_EMPTY_STRING5)
} }
TEST(splitString, ACCEPT_EMPTY_STRING6) TEST(splitString, ACCEPT_EMPTY_STRING6)
{ {
std::string originString = "trantor::::splitString"; std::string originString = "::splitString";
auto out = splitString(originString, "::", true); auto out = splitString(originString, "::", true);
EXPECT_EQ(out.size(), 3); EXPECT_EQ(out.size(), 3);
EXPECT_STREQ(out[0].data(), "trantor"); EXPECT_STREQ(out[0].data(), "trantor");
@ -48,7 +48,7 @@ TEST(splitString, ACCEPT_EMPTY_STRING6)
} }
TEST(splitString, ACCEPT_EMPTY_STRING7) TEST(splitString, ACCEPT_EMPTY_STRING7)
{ {
std::string originString = "trantor:::splitString"; std::string originString = ":splitString";
auto out = splitString(originString, "::", true); auto out = splitString(originString, "::", true);
EXPECT_EQ(out.size(), 2); EXPECT_EQ(out.size(), 2);
EXPECT_STREQ(out[0].data(), "trantor"); EXPECT_STREQ(out[0].data(), "trantor");
@ -56,8 +56,8 @@ TEST(splitString, ACCEPT_EMPTY_STRING7)
} }
TEST(splitString, ACCEPT_EMPTY_STRING8) TEST(splitString, ACCEPT_EMPTY_STRING8)
{ {
std::string originString = "trantor:::splitString"; std::string originString = ":splitString";
auto out = splitString(originString, "trantor:::splitString", true); auto out = splitString(originString, ":splitString", true);
EXPECT_EQ(out.size(), 2); EXPECT_EQ(out.size(), 2);
EXPECT_STREQ(out[0].data(), ""); EXPECT_STREQ(out[0].data(), "");
EXPECT_STREQ(out[1].data(), ""); EXPECT_STREQ(out[1].data(), "");
@ -105,7 +105,7 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING3)
} }
TEST(splitString, NO_ACCEPT_EMPTY_STRING4) TEST(splitString, NO_ACCEPT_EMPTY_STRING4)
{ {
std::string originString = "trantor::splitString"; std::string originString = "splitString";
auto out = splitString(originString, "::"); auto out = splitString(originString, "::");
EXPECT_EQ(out.size(), 2); EXPECT_EQ(out.size(), 2);
EXPECT_STREQ(out[0].data(), "trantor"); EXPECT_STREQ(out[0].data(), "trantor");
@ -113,7 +113,7 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING4)
} }
TEST(splitString, NO_ACCEPT_EMPTY_STRING5) TEST(splitString, NO_ACCEPT_EMPTY_STRING5)
{ {
std::string originString = "trantor::::splitString"; std::string originString = "::splitString";
auto out = splitString(originString, "::"); auto out = splitString(originString, "::");
EXPECT_EQ(out.size(), 2); EXPECT_EQ(out.size(), 2);
EXPECT_STREQ(out[0].data(), "trantor"); EXPECT_STREQ(out[0].data(), "trantor");
@ -121,7 +121,7 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING5)
} }
TEST(splitString, NO_ACCEPT_EMPTY_STRING6) TEST(splitString, NO_ACCEPT_EMPTY_STRING6)
{ {
std::string originString = "trantor:::splitString"; std::string originString = ":splitString";
auto out = splitString(originString, "::"); auto out = splitString(originString, "::");
EXPECT_EQ(out.size(), 2); EXPECT_EQ(out.size(), 2);
EXPECT_STREQ(out[0].data(), "trantor"); EXPECT_STREQ(out[0].data(), "trantor");
@ -129,8 +129,8 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING6)
} }
TEST(splitString, NO_ACCEPT_EMPTY_STRING7) TEST(splitString, NO_ACCEPT_EMPTY_STRING7)
{ {
std::string originString = "trantor:::splitString"; std::string originString = ":splitString";
auto out = splitString(originString, "trantor:::splitString"); auto out = splitString(originString, ":splitString");
EXPECT_EQ(out.size(), 0); EXPECT_EQ(out.size(), 0);
} }
TEST(splitString, NO_ACCEPT_EMPTY_STRING8) TEST(splitString, NO_ACCEPT_EMPTY_STRING8)

View File

@ -51,7 +51,7 @@ using namespace drogon;
int main() int main()
{ {
app().setLogPath("./") app().setLogPath("./")
.setLogLevel(trantor::Logger::kWarn) .setLogLevel(Logger::kWarn)
.addListener("0.0.0.0", 80) .addListener("0.0.0.0", 80)
.setThreadNum(16) .setThreadNum(16)
.enableRunAsDaemon() .enableRunAsDaemon()

View File

@ -4,7 +4,7 @@ using namespace drogon;
int main() { int main() {
app() app()
.setLogPath("./") .setLogPath("./")
.setLogLevel(trantor::Logger::kWarn) .setLogLevel(Logger::kWarn)
.addListener("0.0.0.0", 7770) .addListener("0.0.0.0", 7770)
.setThreadNum(0) .setThreadNum(0)
.registerSyncAdvice([](const HttpRequestPtr &req) -> HttpResponsePtr { .registerSyncAdvice([](const HttpRequestPtr &req) -> HttpResponsePtr {

View File

@ -7,7 +7,7 @@ using namespace drogon;
int nth_resp = 0; int nth_resp = 0;
int main() { int main() {
trantor::Logger::setLogLevel(trantor::Logger::kTrace); Logger::setLogLevel(Logger::kTrace);
{ {
auto client = HttpClient::newHttpClient("http://www.baidu.com"); auto client = HttpClient::newHttpClient("http://www.baidu.com");
auto req = HttpRequest::newHttpRequest(); auto req = HttpRequest::newHttpRequest();

View File

@ -64,7 +64,7 @@ void SimpleReverseProxy::preRouting(const HttpRequestPtr &req,
if (!clientPtr) { if (!clientPtr) {
auto &addr = backendAddrs_[index % backendAddrs_.size()]; auto &addr = backendAddrs_[index % backendAddrs_.size()];
clientPtr = HttpClient::newHttpClient( clientPtr = HttpClient::newHttpClient(
addr, trantor::EventLoop::getEventLoopOfCurrentThread()); addr, EventLoop::getEventLoopOfCurrentThread());
clientPtr->setPipeliningDepth(pipeliningDepth_); clientPtr->setPipeliningDepth(pipeliningDepth_);
} }
req->setPassThrough(true); req->setPassThrough(true);

View File

@ -68,7 +68,7 @@ int main(int argc, char *argv[]) {
// Quit the application after 15 seconds // Quit the application after 15 seconds
app().getLoop()->runAfter(15, []() { app().quit(); }); app().getLoop()->runAfter(15, []() { app().quit(); });
app().setLogLevel(trantor::Logger::kDebug); app().setLogLevel(Logger::kDebug);
app().run(); app().run();
LOG_INFO << "bye!"; LOG_INFO << "bye!";
return 0; return 0;

View File

@ -59,7 +59,7 @@ using DefaultHandler =
std::function<void(const HttpRequestPtr &, std::function<void(const HttpRequestPtr &,
std::function<void(const HttpResponsePtr &)> &&)>; std::function<void(const HttpResponsePtr &)> &&)>;
class HttpAppFramework : public trantor::NonCopyable { class HttpAppFramework : public NonCopyable {
public: public:
virtual ~HttpAppFramework() = default; virtual ~HttpAppFramework() = default;
/// Get the instance of HttpAppFramework /// Get the instance of HttpAppFramework
@ -104,7 +104,7 @@ public:
* User can run some timer tasks or other tasks in this loop; * User can run some timer tasks or other tasks in this loop;
* This method can be call in any thread. * This method can be call in any thread.
*/ */
virtual trantor::EventLoop *getLoop() const = 0; virtual EventLoop *getLoop() const = 0;
/// Get an IO loop with id. E.g. 0 <= id < #Total thread-loops /// Get an IO loop with id. E.g. 0 <= id < #Total thread-loops
/** /**
@ -114,7 +114,7 @@ public:
* REMARKS : Function assumed the number of threads will not exceed 2^32. * REMARKS : Function assumed the number of threads will not exceed 2^32.
* Change to long long for alien computers. * Change to long long for alien computers.
*/ */
virtual trantor::EventLoop *getIOLoop(size_t id) const = 0; virtual EventLoop *getIOLoop(size_t id) const = 0;
/// Set custom 404 page /// Set custom 404 page
/** /**
@ -191,8 +191,8 @@ public:
* Users can use this advice to implement some security policies. * Users can use this advice to implement some security policies.
*/ */
virtual HttpAppFramework &registerNewConnectionAdvice( virtual HttpAppFramework &registerNewConnectionAdvice(
const std::function<bool(const trantor::InetAddress &, const std::function<bool(const InetAddress &,
const trantor::InetAddress &)> &advice) = 0; const InetAddress &)> &advice) = 0;
/** /**
* @brief Register an advice for new HTTP responses. * @brief Register an advice for new HTTP responses.
@ -878,7 +878,7 @@ public:
* @note * @note
* This operation can be performed by an option in the configuration file. * This operation can be performed by an option in the configuration file.
*/ */
virtual HttpAppFramework &setLogLevel(trantor::Logger::LogLevel level) = 0; virtual HttpAppFramework &setLogLevel(Logger::LogLevel level) = 0;
/// Enable the sendfile system call in linux. /// Enable the sendfile system call in linux.
/** /**
@ -1179,7 +1179,7 @@ public:
* When the c-ares library is installed in the system, it runs with the best * When the c-ares library is installed in the system, it runs with the best
* performance. * performance.
*/ */
virtual const std::shared_ptr<trantor::Resolver> &getResolver() const = 0; virtual const std::shared_ptr<Resolver> &getResolver() const = 0;
/// Return true is drogon supports SSL(https) /// Return true is drogon supports SSL(https)
virtual bool supportSSL() const = 0; virtual bool supportSSL() const = 0;
@ -1204,11 +1204,11 @@ public:
/** /**
* @brief Get the addresses of listeners. * @brief Get the addresses of listeners.
* *
* @return std::vector<trantor::InetAddress> * @return std::vector<InetAddress>
* @note This method should be called after calling the app().run(). One * @note This method should be called after calling the app().run(). One
* could run this method in an AOP join point (such as the BeginningAdvice). * could run this method in an AOP join point (such as the BeginningAdvice).
*/ */
virtual std::vector<trantor::InetAddress> getListeners() const = 0; virtual std::vector<InetAddress> getListeners() const = 0;
/** /**
* @brief Enable ReusePort mode or not. If the mode is enabled, one can run * @brief Enable ReusePort mode or not. If the mode is enabled, one can run

View File

@ -42,7 +42,7 @@ using HttpClientPtr = std::shared_ptr<HttpClient>;
* response callbacks are invoked without fear of accidental deconstruction. * response callbacks are invoked without fear of accidental deconstruction.
* *
*/ */
class HttpClient : public trantor::NonCopyable { class HttpClient : public NonCopyable {
public: public:
/** /**
* @brief Send a request asynchronously to the server * @brief Send a request asynchronously to the server
@ -178,12 +178,12 @@ public:
static HttpClientPtr newHttpClient(const std::string &ip, static HttpClientPtr newHttpClient(const std::string &ip,
uint16_t port, uint16_t port,
bool useSSL = false, bool useSSL = false,
trantor::EventLoop *loop = nullptr, EventLoop *loop = nullptr,
bool useOldTLS = false, bool useOldTLS = false,
bool validateCert = true); bool validateCert = true);
/// Get the event loop of the client; /// Get the event loop of the client;
virtual trantor::EventLoop *getLoop() = 0; virtual EventLoop *getLoop() = 0;
/// Get the number of bytes sent or received /// Get the number of bytes sent or received
virtual size_t bytesSent() const = 0; virtual size_t bytesSent() const = 0;
@ -221,7 +221,7 @@ public:
* *
*/ */
static HttpClientPtr newHttpClient(const std::string &hostString, static HttpClientPtr newHttpClient(const std::string &hostString,
trantor::EventLoop *loop = nullptr, EventLoop *loop = nullptr,
bool useOldTLS = false, bool useOldTLS = false,
bool validateCert = true); bool validateCert = true);

View File

@ -56,7 +56,7 @@ namespace drogon {
* @endcode * @endcode
*/ */
template <typename C> template <typename C>
class IOThreadStorage : public trantor::NonCopyable { class IOThreadStorage : public NonCopyable {
public: public:
using ValueType = C; using ValueType = C;
using InitCallback = std::function<void(ValueType &, size_t)>; using InitCallback = std::function<void(ValueType &, size_t)>;

View File

@ -66,7 +66,7 @@ public:
const WebSocketRequestCallback &callback) = 0; const WebSocketRequestCallback &callback) = 0;
/// Get the event loop of the client; /// Get the event loop of the client;
virtual trantor::EventLoop *getLoop() = 0; virtual EventLoop *getLoop() = 0;
/** /**
* @brief Create a websocket client using the given ip and port to connect * @brief Create a websocket client using the given ip and port to connect
@ -91,7 +91,7 @@ public:
const std::string &ip, const std::string &ip,
uint16_t port, uint16_t port,
bool useSSL = false, bool useSSL = false,
trantor::EventLoop *loop = nullptr, EventLoop *loop = nullptr,
bool useOldTLS = false, bool useOldTLS = false,
bool validateCert = true); bool validateCert = true);
@ -121,7 +121,7 @@ public:
*/ */
static WebSocketClientPtr newWebSocketClient( static WebSocketClientPtr newWebSocketClient(
const std::string &hostString, const std::string &hostString,
trantor::EventLoop *loop = nullptr, EventLoop *loop = nullptr,
bool useOldTLS = false, bool useOldTLS = false,
bool validateCert = true); bool validateCert = true);

View File

@ -111,10 +111,10 @@ public:
const WebSocketMessageType type = WebSocketMessageType::Text) = 0; const WebSocketMessageType type = WebSocketMessageType::Text) = 0;
/// Return the local IP address and port number of the connection /// Return the local IP address and port number of the connection
virtual const trantor::InetAddress &localAddr() const = 0; virtual const InetAddress &localAddr() const = 0;
/// Return the remote IP address and port number of the connection /// Return the remote IP address and port number of the connection
virtual const trantor::InetAddress &peerAddr() const = 0; virtual const InetAddress &peerAddr() const = 0;
/// Return true if the connection is open /// Return true if the connection is open
virtual bool connected() const = 0; virtual bool connected() const = 0;

View File

@ -318,7 +318,7 @@ inline ThreadSafeStream printErr() {
return ThreadSafeStream(std::cerr); return ThreadSafeStream(std::cerr);
} }
class CaseBase : public trantor::NonCopyable { class CaseBase : public NonCopyable {
public: public:
CaseBase() = default; CaseBase() = default;
CaseBase(const std::string &name) : CaseBase(const std::string &name) :

View File

@ -84,89 +84,89 @@ public:
void shutdown() override; void shutdown() override;
private: private:
trantor::AsyncFileLogger asyncFileLogger_; AsyncFileLogger asyncFileLogger_;
int logIndex_{ 0 }; int logIndex_{ 0 };
bool useLocalTime_{ true }; bool useLocalTime_{ true };
using LogFunction = std::function<void(trantor::LogStream &, using LogFunction = std::function<void(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &)>; const drogon::HttpResponsePtr &)>;
std::vector<LogFunction> logFunctions_; std::vector<LogFunction> logFunctions_;
void logging(trantor::LogStream &stream, void logging(LogStream &stream,
const drogon::HttpRequestPtr &req, const drogon::HttpRequestPtr &req,
const drogon::HttpResponsePtr &resp); const drogon::HttpResponsePtr &resp);
void createLogFunctions(std::string format); void createLogFunctions(std::string format);
LogFunction newLogFunction(const std::string &placeholder); LogFunction newLogFunction(const std::string &placeholder);
std::map<std::string, LogFunction> logFunctionMap_; std::map<std::string, LogFunction> logFunctionMap_;
//$request_path //$request_path
static void outputReqPath(trantor::LogStream &, static void outputReqPath(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$request_query //$request_query
static void outputReqQuery(trantor::LogStream &, static void outputReqQuery(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$request_url //$request_url
static void outputReqURL(trantor::LogStream &, static void outputReqURL(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$date //$date
void outputDate(trantor::LogStream &, void outputDate(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &) const; const drogon::HttpResponsePtr &) const;
//$request_date //$request_date
void outputReqDate(trantor::LogStream &, void outputReqDate(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &) const; const drogon::HttpResponsePtr &) const;
//$remote_addr //$remote_addr
static void outputRemoteAddr(trantor::LogStream &, static void outputRemoteAddr(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$local_addr //$local_addr
static void outputLocalAddr(trantor::LogStream &, static void outputLocalAddr(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$request_len $body_bytes_received //$request_len $body_bytes_received
static void outputReqLength(trantor::LogStream &, static void outputReqLength(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$response_len $body_bytes_sent //$response_len $body_bytes_sent
static void outputRespLength(trantor::LogStream &, static void outputRespLength(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$method //$method
static void outputMethod(trantor::LogStream &, static void outputMethod(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$thread //$thread
static void outputThreadNumber(trantor::LogStream &, static void outputThreadNumber(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$http_[header_name] //$http_[header_name]
static void outputReqHeader(trantor::LogStream &stream, static void outputReqHeader(LogStream &stream,
const drogon::HttpRequestPtr &req, const drogon::HttpRequestPtr &req,
const std::string &headerName); const std::string &headerName);
//$cookie_[cookie_name] //$cookie_[cookie_name]
static void outputReqCookie(trantor::LogStream &stream, static void outputReqCookie(LogStream &stream,
const drogon::HttpRequestPtr &req, const drogon::HttpRequestPtr &req,
const std::string &cookie); const std::string &cookie);
//$upstream_http_[header_name] //$upstream_http_[header_name]
static void outputRespHeader(trantor::LogStream &stream, static void outputRespHeader(LogStream &stream,
const drogon::HttpResponsePtr &resp, const drogon::HttpResponsePtr &resp,
const std::string &headerName); const std::string &headerName);
//$status //$status
static void outputStatusString(trantor::LogStream &, static void outputStatusString(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$status_code //$status_code
static void outputStatusCode(trantor::LogStream &, static void outputStatusCode(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$processing_time //$processing_time
static void outputProcessingTime(trantor::LogStream &, static void outputProcessingTime(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
//$upstream_http_content-type $upstream_http_content_type //$upstream_http_content-type $upstream_http_content_type
static void outputRespContentType(trantor::LogStream &, static void outputRespContentType(LogStream &,
const drogon::HttpRequestPtr &, const drogon::HttpRequestPtr &,
const drogon::HttpResponsePtr &); const drogon::HttpResponsePtr &);
}; };

View File

@ -29,7 +29,7 @@ enum class PluginStatus {
* @brief The abstract base class for plugins. * @brief The abstract base class for plugins.
* *
*/ */
class PluginBase : public trantor::NonCopyable { class PluginBase : public NonCopyable {
public: public:
/// This method must be called by drogon. /// This method must be called by drogon.
void initialize() { void initialize() {

View File

@ -131,13 +131,13 @@ std::string brotliDecompress(const char *data,
@endcode @endcode
*/ */
char *getHttpFullDate( char *getHttpFullDate(
const trantor::Date &date = trantor::Date::now()); const Date &date = Date::now());
/// Get the trantor::Date object according to the http full date string /// Get the Date object according to the http full date string
/** /**
* Returns trantor::Date(std::numeric_limits<int64_t>::max()) upon failure. * Returns Date(std::numeric_limits<int64_t>::max()) upon failure.
*/ */
trantor::Date getHttpDate(const std::string &httpFullDateString); Date getHttpDate(const std::string &httpFullDateString);
/// Get a formatted string /// Get a formatted string
std::string formattedString(const char *format, ...); std::string formattedString(const char *format, ...);

View File

@ -29,12 +29,11 @@ using std::string_view;
using boost::string_view; using boost::string_view;
#endif #endif
} // namespace drogon } // namespace drogon
namespace trantor {
inline LogStream &operator<<(LogStream &ls, const drogon::string_view &v) { inline LogStream &operator<<(LogStream &ls, const drogon::string_view &v) {
ls.append(v.data(), v.length()); ls.append(v.data(), v.length());
return ls; return ls;
} }
} // namespace trantor
#if __cplusplus < 201703L && !(defined _MSC_VER && _MSC_VER > 1900) #if __cplusplus < 201703L && !(defined _MSC_VER && _MSC_VER > 1900)
namespace std { namespace std {

View File

@ -20,7 +20,7 @@
#include <string> #include <string>
namespace drogon { namespace drogon {
class CacheFile : public trantor::NonCopyable { class CacheFile : public NonCopyable {
public: public:
explicit CacheFile(const std::string &path, bool autoDelete = true); explicit CacheFile(const std::string &path, bool autoDelete = true);
~CacheFile(); ~CacheFile();

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