h2-mod/src/common/utils/string.hpp

106 lines
2.5 KiB
C++
Raw Normal View History

2021-04-20 00:56:11 +02:00
#pragma once
2021-07-29 02:53:40 +02:00
#include "memory.hpp"
2021-09-07 00:40:37 +02:00
#include <cstdint>
#ifndef ARRAYSIZE
template <class Type, size_t n>
size_t ARRAYSIZE(Type (&)[n]) { return n; }
#endif
2021-04-20 00:56:11 +02:00
namespace utils::string
{
template <size_t Buffers, size_t MinBufferSize>
class va_provider final
{
public:
static_assert(Buffers != 0 && MinBufferSize != 0, "Buffers and MinBufferSize mustn't be 0");
va_provider() : current_buffer_(0)
{
}
char* get(const char* format, const va_list ap)
{
++this->current_buffer_ %= ARRAYSIZE(this->string_pool_);
auto entry = &this->string_pool_[this->current_buffer_];
if (!entry->size || !entry->buffer)
{
throw std::runtime_error("String pool not initialized");
}
while (true)
{
const int res = vsnprintf_s(entry->buffer, entry->size, _TRUNCATE, format, ap);
if (res > 0) break; // Success
if (res == 0) return nullptr; // Error
entry->double_size();
}
return entry->buffer;
}
private:
class entry final
{
public:
explicit entry(const size_t _size = MinBufferSize) : size(_size), buffer(nullptr)
{
if (this->size < MinBufferSize) this->size = MinBufferSize;
this->allocate();
}
~entry()
{
if (this->buffer) memory::get_allocator()->free(this->buffer);
this->size = 0;
this->buffer = nullptr;
}
void allocate()
{
if (this->buffer) memory::get_allocator()->free(this->buffer);
this->buffer = memory::get_allocator()->allocate_array<char>(this->size + 1);
}
void double_size()
{
this->size *= 2;
this->allocate();
}
size_t size;
char* buffer;
};
size_t current_buffer_;
entry string_pool_[Buffers];
};
const char* va(const char* fmt, ...);
std::vector<std::string> split(const std::string& s, char delim);
std::string to_lower(std::string text);
std::string to_upper(std::string text);
bool starts_with(const std::string& text, const std::string& substring);
2021-09-07 00:40:37 +02:00
bool ends_with(const std::string& text, const std::string& substring);
2021-04-20 00:56:11 +02:00
std::string dump_hex(const std::string& data, const std::string& separator = " ");
std::string get_clipboard_data();
2021-12-20 01:53:01 +01:00
void set_clipboard_data(const std::string& text);
2021-04-20 00:56:11 +02:00
void strip(const char* in, char* out, int max);
2021-04-23 03:46:11 +02:00
2021-09-07 00:40:37 +02:00
std::string convert(const std::wstring& wstr);
std::wstring convert(const std::string& str);
2021-04-23 03:46:11 +02:00
std::string replace(std::string str, const std::string& from, const std::string& to);
2021-12-21 15:21:50 +01:00
bool find_lower(const std::string& a, const std::string& b);
2021-12-22 22:25:41 +01:00
2021-12-22 22:27:58 +01:00
std::string truncate(const std::string& text, const size_t length, const std::string& end);
2021-04-20 00:56:11 +02:00
}