feat merge develop
Some checks failed
linux-x64-gcc / linux-gcc (push) Failing after 55s
rpcrypto-build / build (Release, himix200.toolchain.cmake) (push) Successful in 1m4s
rpcrypto-build / build (Debug, himix200.toolchain.cmake) (push) Successful in 1m7s
rpcrypto-build / build (Debug, hisiv510.toolchain.cmake) (push) Successful in 1m7s
linux-hisiv500-gcc / linux-gcc-hisiv500 (push) Successful in 1m20s
rpcrypto-build / build (Release, hisiv510.toolchain.cmake) (push) Successful in 1m23s
linux-mips64-gcc / linux-gcc-mips64el (push) Failing after 2m59s

This commit is contained in:
tqcq 2024-01-05 09:48:31 +08:00
commit 7f6f00c8f5
13 changed files with 18446 additions and 27 deletions

15308
3party/mongoose/mongoose.c Normal file

File diff suppressed because it is too large Load Diff

2929
3party/mongoose/mongoose.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,10 @@
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(ulib LANGUAGES CXX VERSION 0.1.0) project(ulib LANGUAGES CXX C VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 98) set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_EXTENSIONS OFF)
@ -9,7 +12,7 @@ option(ULIB_BUILD_TESTS "Build tests" OFF)
option(ULIB_SHARED_LIB "Build shared library" OFF) option(ULIB_SHARED_LIB "Build shared library" OFF)
option(ULIB_BUILD_EXAMPLES "Build examples" OFF) option(ULIB_BUILD_EXAMPLES "Build examples" OFF)
if (NOT CMAKE_BUILD_TYPE) if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release") set(CMAKE_BUILD_TYPE "Release")
# set stripped # set stripped
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -s") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -s")
@ -17,7 +20,7 @@ endif()
# add -static-libgcc and -static-libstdc++ to link flags # add -static-libgcc and -static-libstdc++ to link flags
set(CMAKE_POSITION_INDEPENDENT_CODE ON) set(CMAKE_POSITION_INDEPENDENT_CODE ON)
if (ULIB_SHARED_LIB) if(ULIB_SHARED_LIB)
add_library(${PROJECT_NAME} SHARED "") add_library(${PROJECT_NAME} SHARED "")
else() else()
add_library(${PROJECT_NAME} STATIC "" add_library(${PROJECT_NAME} STATIC ""
@ -25,6 +28,7 @@ else()
src/ulib/system/timer.h) src/ulib/system/timer.h)
endif() endif()
target_sources(${PROJECT_NAME} PRIVATE target_sources(${PROJECT_NAME} PRIVATE
3party/mongoose/mongoose.c
src/ulib/base/location.h src/ulib/base/location.h
src/ulib/base/location.cpp src/ulib/base/location.cpp
src/ulib/concorrency/barrier.cpp src/ulib/concorrency/barrier.cpp
@ -53,12 +57,12 @@ find_package(Threads REQUIRED)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
## CMP0063 ## CMP0063
if (POLICY CMP0063) if(POLICY CMP0063)
cmake_policy(SET CMP0063 NEW) cmake_policy(SET CMP0063 NEW)
endif () endif()
if (POLICY CMP0048) if(POLICY CMP0048)
cmake_policy(SET CMP0048 NEW) cmake_policy(SET CMP0048 NEW)
endif () endif()
set(FMT_USE_CPP11 OFF CACHE BOOL "Use C++11" FORCE) set(FMT_USE_CPP11 OFF CACHE BOOL "Use C++11" FORCE)
set(FMT_TEST OFF CACHE BOOL "Build tests" FORCE) set(FMT_TEST OFF CACHE BOOL "Build tests" FORCE)
@ -83,6 +87,7 @@ target_compile_definitions(${PROJECT_NAME} PRIVATE ULIB_LIBRARY_IMPL)
target_include_directories(${PROJECT_NAME} PUBLIC target_include_directories(${PROJECT_NAME} PUBLIC
3party/nlohmann 3party/nlohmann
3party/inja 3party/inja
3party/mongoose
src src
) )
@ -97,6 +102,6 @@ if(ULIB_BUILD_TESTS)
add_subdirectory(tests) add_subdirectory(tests)
endif() endif()
if (ULIB_BUILD_EXAMPLES) if(ULIB_BUILD_EXAMPLES)
add_subdirectory(examples) add_subdirectory(examples)
endif() endif()

View File

@ -42,6 +42,48 @@ public:
FATAL = ULOG_LEVEL_FATAL FATAL = ULOG_LEVEL_FATAL
}; };
static const char *GetConsoleColorPrefix(int level)
{
switch (level) {
case kTrace:
return "\033[0;37m";
case kDebug:
return "\033[0;36m";
case kInfo:
return "\033[0;32m";
case kWarn:
return "\033[0;33m";
case kError:
return "\033[0;31m";
case kFatal:
return "\033[0;31m";
default:
return "\033[0m";
}
}
static const char *GetConsoleColorSuffix(int level) { return "\033[0m"; }
static const char *ToShortString(int level)
{
switch (level) {
case kTrace:
return "T";
case kDebug:
return "D";
case kInfo:
return "I";
case kWarn:
return "W";
case kError:
return "E";
case kFatal:
return "F";
default:
return "UNKNOWN";
}
}
static const char *ToString(int level) static const char *ToString(int level)
{ {
switch (level) { switch (level) {

View File

@ -53,7 +53,7 @@ Logger::Log(int32_t level,
const char *msg) const char *msg)
{ {
if (level < level_) { return; } if (level < level_) { return; }
const char *level_name = Level::ToString(level); const char *level_name = Level::ToShortString(level);
/** /**
* @brief time file:line@func tag level_name msg * @brief time file:line@func tag level_name msg
*/ */
@ -62,7 +62,8 @@ Logger::Log(int32_t level,
/** /**
* @brief time level_name tag file:line@func msg * @brief time level_name tag file:line@func msg
*/ */
std::string pattern = "{} [{}] {} {}:{}@{}: {}"; std::string pattern = std::string() + Level::GetConsoleColorPrefix(level)
+ "{} {} {} {}:{}@{}: {}" + Level::GetConsoleColorSuffix(level);
std::string log_time; std::string log_time;
{ {
std::time_t now = time(NULL); std::time_t now = time(NULL);

View File

@ -39,8 +39,10 @@ public:
*impl->tid_ = GetTid(); *impl->tid_ = GetTid();
#if __APPLE__ #if __APPLE__
pthread_setname_np(impl->thread_name_.c_str()); pthread_setname_np(impl->thread_name_.c_str());
#else #elif ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
pthread_setname_np(impl->thread_, impl->thread_name_.c_str()); pthread_setname_np(impl->thread_, impl->thread_name_.c_str());
#else
// TODO set thread name
#endif #endif
impl->latch_.CountDown(); impl->latch_.CountDown();

View File

@ -1,5 +1,4 @@
#include "thread_pool.h" #include "thread_pool.h"
#include <fmt/format.h>
namespace ulib { namespace ulib {
ThreadPool::ThreadPool(int max_thread_num, ThreadPool::ThreadPool(int max_thread_num,

View File

@ -2,6 +2,7 @@
#define ULIB_SRC_ULIB_SYSTEM_THREAD_POOL_H_ #define ULIB_SRC_ULIB_SYSTEM_THREAD_POOL_H_
#include "thread.h" #include "thread.h"
#include <fmt/format.h>
#include "ulib/log/log.h" #include "ulib/log/log.h"
#include "ulib/concorrency/condition_variable.h" #include "ulib/concorrency/condition_variable.h"
#include "ulib/concorrency/mutex.h" #include "ulib/concorrency/mutex.h"
@ -39,7 +40,8 @@ public:
tasks_.emplace([task]() { (*task)(); }); tasks_.emplace([task]() { (*task)(); });
if (tasks_.size() > idle_thread_num_ if (tasks_.size() > idle_thread_num_
&& workers_.size() < max_thread_num_) { && workers_.size() < max_thread_num_) {
AddThread(thread_pool_name_ + std::to_string(workers_.size())); AddThread(thread_pool_name_
+ fmt::format("{}", workers_.size()));
} }
if (tasks_.size() > 1) { if (tasks_.size() > 1) {
tasks_cond_.NotifyAll(); tasks_cond_.NotifyAll();

51
src/ulib/utils/defer.h Normal file
View File

@ -0,0 +1,51 @@
#ifndef ULIB_SRC_ULIB_UTILS_DEFER_H_
#define ULIB_SRC_ULIB_UTILS_DEFER_H_
#include "ulib/base/noncopyable.h"
#include "ulib/base/stringize_macros.h"
#include <memory>
#include <algorithm>
#include <vector>
#include <functional>
namespace ulib {
class Defer : NonCopyable {
public:
using DeferFunc = std::function<void()>;
Defer() = default;
Defer(const DeferFunc &defer_func) { Add(defer_func); }
Defer(DeferFunc &&defer_func) { Add(std::move(defer_func)); }
Defer(Defer &&other) noexcept : defer_funcs_(std::move(other.defer_funcs_))
{}
~Defer()
{
std::for_each(defer_funcs_.rbegin(), defer_funcs_.rend(),
[](const DeferFunc &defer_func) { defer_func(); });
}
template<typename F, typename... Args>
void Add(F &&func, Args &&...args)
{
defer_funcs_.push_back(
std::bind(std::forward<F>(func), std::forward<Args>(args)...));
}
void Clear() { defer_funcs_.clear(); }
private:
std::vector<DeferFunc> defer_funcs_;
};
#define _ULIB_DEFER_CONCAT(a, b) a##b
#define ULIB_DEFER_CONCAT(a, b) _ULIB_DEFER_CONCAT(a, b)
#define defer(x) \
::ulib::Defer ULIB_DEFER_CONCAT(__ulib_defer__, __LINE__) = \
::ulib::Defer(x);
}// namespace ulib
#endif// ULIB_SRC_ULIB_UTILS_DEFER_H_

View File

@ -11,6 +11,7 @@ add_executable(ulib_test
ulib/system/thread_pool_unittest.cpp ulib/system/thread_pool_unittest.cpp
ulib/system/timer_unittest.cpp ulib/system/timer_unittest.cpp
3party/inja/inja_unittest.cpp 3party/inja/inja_unittest.cpp
ulib/utils/defer_unittest.cpp
) )
target_link_libraries(ulib_test PRIVATE target_link_libraries(ulib_test PRIVATE
ulib ulib

View File

@ -4,7 +4,10 @@
class ThreadPoolTest : public ::testing::Test { class ThreadPoolTest : public ::testing::Test {
protected: protected:
void SetUp() override { thread_pool_ = std::make_unique<ulib::ThreadPool>(10); } void SetUp() override
{
thread_pool_ = std::make_unique<ulib::ThreadPool>(10);
}
std::unique_ptr<ulib::ThreadPool> thread_pool_; std::unique_ptr<ulib::ThreadPool> thread_pool_;
}; };
@ -32,3 +35,15 @@ TEST_F(ThreadPoolTest, MultiTask)
for (auto &future : futures) { ASSERT_EQ(future.get(), 3); } for (auto &future : futures) { ASSERT_EQ(future.get(), 3); }
} }
TEST_F(ThreadPoolTest, NoArgs)
{
std::vector<std::future<int>> futures;
for (int i = 0; i < 1000; ++i) {
futures.emplace_back(thread_pool_->Submit([]() {
ulib::Thread::Sleep(1000);
return 1;
}));
}
for (auto &future : futures) { future.get(); }
}

View File

@ -7,30 +7,34 @@
class TimerTest : public ::testing::Test { class TimerTest : public ::testing::Test {
protected: protected:
void SetUp() override { latch_ = nullptr; } void SetUp() override { latch_ = nullptr; }
void TearDown() override { delete latch_; } void TearDown() override { delete latch_; }
protected: protected:
ulib::CountDownLatch *latch_; ulib::CountDownLatch *latch_;
}; };
TEST_F(TimerTest, OnceTrigger) { TEST_F(TimerTest, OnceTrigger)
{
latch_ = new ulib::CountDownLatch(1); latch_ = new ulib::CountDownLatch(1);
ulib::TimerId timer_id = ulib::TimerManager::AddTimer([&]{ ulib::TimerId timer_id =
latch_->CountDown(); ulib::TimerManager::AddTimer([&] { latch_->CountDown(); }, 1000);
}, 1000);
latch_->Await(); latch_->Await();
ulib::TimerManager::CancelTimer(timer_id); ulib::TimerManager::CancelTimer(timer_id);
} }
TEST_F(TimerTest, PeriodTrigger) { TEST_F(TimerTest, PeriodTrigger)
{
latch_ = new ulib::CountDownLatch(3); latch_ = new ulib::CountDownLatch(3);
std::atomic_int cnt(3); std::atomic_int cnt(3);
ulib::TimerId timer_id = ulib::TimerManager::AddTimer([&]{ ulib::TimerId timer_id = ulib::TimerManager::AddTimer(
if (cnt.fetch_sub(1) > 0) { [&] {
ULOG_INFO("timer.unittest", "start count down: {}", cnt); if (cnt.fetch_sub(1) > 0) {
latch_->CountDown(); ULOG_INFO("timer.unittest", "start count down: {}", cnt);
} latch_->CountDown();
}, 1000, 3000); }
},
1000, 1000);
latch_->Await(); latch_->Await();
ulib::TimerManager::CancelTimer(timer_id); ulib::TimerManager::CancelTimer(timer_id);
} }

View File

@ -0,0 +1,60 @@
#include <gtest/gtest.h>
#include <ulib/utils/defer.h>
TEST(Defer, Defer)
{
int i = 0;
{
defer([&i]() { i++; });
EXPECT_EQ(i, 0);
}
EXPECT_EQ(i, 1);
}
TEST(Defer, DeferFunc)
{
int i = 0;
{
defer([&i]() { i++; });
EXPECT_EQ(i, 0);
}
EXPECT_EQ(i, 1);
}
TEST(Defer, DeferMove)
{
int i = 0;
{
defer([&i]() { i++; });
EXPECT_EQ(i, 0);
defer([&i]() { i++; });
EXPECT_EQ(i, 0);
}
EXPECT_EQ(i, 2);
}
TEST(Defer, Add)
{
int i = 0;
{
ulib::Defer defer;
defer.Add([&i]() { i++; });
EXPECT_EQ(i, 0);
defer.Add([&i]() { i++; });
EXPECT_EQ(i, 0);
}
EXPECT_EQ(i, 2);
}
TEST(Defer, Clear)
{
int i = 0;
{
ulib::Defer defer;
defer.Add([&i]() { i++; });
EXPECT_EQ(i, 0);
defer.Clear();
EXPECT_EQ(i, 0);
}
EXPECT_EQ(i, 0);
}