ofen/src/of_util.cpp

70 lines
1.7 KiB
C++
Raw Normal View History

2024-12-11 10:21:57 +08:00
#include "of_util.h"
#include <chrono>
#include <iomanip>
#include <sstream>
2024-12-11 10:21:57 +08:00
namespace ofen {
void CMutBuffer::push(const char* data, int len)
{
std::lock_guard<std::mutex> lock(mutex_);
buffer_.insert(buffer_.end(), data, data + len);
}
int CMutBuffer::index_of(const char* data, int len, int start_pos)
{
std::lock_guard<std::mutex> lock(mutex_);
if (start_pos < 0 || start_pos >= static_cast<int>(buffer_.size()) || len <= 0) {
return -1;
}
auto it = std::search(buffer_.begin() + start_pos, buffer_.end(), data, data + len);
if (it != buffer_.end()) {
return std::distance(buffer_.begin(), it);
}
return -1;
}
void CMutBuffer::remove_of(int start_pos, int len)
{
std::lock_guard<std::mutex> lock(mutex_);
if (start_pos < 0 || start_pos >= static_cast<int>(buffer_.size()) || len <= 0) {
return;
}
auto end_pos = std::min(start_pos + len, static_cast<int>(buffer_.size()));
buffer_.erase(buffer_.begin() + start_pos, buffer_.begin() + end_pos);
}
2024-12-11 17:00:42 +08:00
const char* CMutBuffer::get_data() const
{
return buffer_.data();
}
2024-12-11 22:49:46 +08:00
int CMutBuffer::get_len() const
{
return static_cast<int>(buffer_.size());
}
2024-12-11 10:21:57 +08:00
void CMutBuffer::clear()
{
std::lock_guard<std::mutex> lock(mutex_);
buffer_.clear();
}
OfUtil::OfUtil()
{
}
OfUtil::~OfUtil()
{
}
ofString OfUtil::now_time()
{
auto now = std::chrono::system_clock::now();
auto time_t_now = std::chrono::system_clock::to_time_t(now);
std::tm tm_now;
#if defined(_WIN32) || defined(_WIN64)
localtime_s(&tm_now, &time_t_now);
#else
localtime_r(&time_t_now, &tm_now);
#endif
std::ostringstream oss;
oss << std::put_time(&tm_now, "%Y-%m-%d %H:%M:%S");
return oss.str();
}
2024-12-11 10:21:57 +08:00
} // namespace ofen