You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
spdlog/include/c11log/details/stack_buf.h

112 lines
2.6 KiB
C

12 years ago
#pragma once
12 years ago
#include <array>
12 years ago
#include <vector>
12 years ago
#include <algorithm>
#include <cstring>
12 years ago
// Fast memory storage
12 years ago
// stores its contents on the stack when possible, in vector<char> otherwise
// NOTE: User should be remember that returned buffer might be on the stack!!
12 years ago
namespace c11log
{
namespace details
{
12 years ago
template<std::size_t STACK_SIZE=128>
12 years ago
class stack_buf
12 years ago
{
public:
12 years ago
stack_buf():_stack_size(0) {}
~stack_buf() {};
12 years ago
12 years ago
stack_buf(const bufpair_t& buf_to_copy):stack_buf()
12 years ago
{
append(buf_to_copy);
}
12 years ago
12 years ago
stack_buf(const stack_buf& other)
12 years ago
{
_stack_size = other._stack_size;
if(!other._v.empty())
_v = other._v;
else if(_stack_size)
std::copy(other._stack_buf.begin(), other._stack_buf.begin()+_stack_size, _stack_buf.begin());
}
12 years ago
stack_buf(stack_buf&& other)
12 years ago
{
_stack_size = other._stack_size;
if(!other._v.empty())
_v = other._v;
else if(_stack_size)
std::copy(other._stack_buf.begin(), other._stack_buf.begin()+_stack_size, _stack_buf.begin());
other.clear();
}
12 years ago
stack_buf& operator=(const stack_buf& other) = delete;
stack_buf& operator=(stack_buf&& other) = delete;
12 years ago
12 years ago
void append(const char* buf, std::size_t buf_size)
12 years ago
{
//If we are aleady using _v, forget about the stack
if(!_v.empty())
{
12 years ago
_v.insert(_v.end(), buf, buf+ buf_size);
12 years ago
}
//Try use the stack
else
{
12 years ago
if(_stack_size+buf_size <= STACK_SIZE)
12 years ago
{
12 years ago
std::memcpy(&_stack_buf[_stack_size], buf, buf_size);
_stack_size+=buf_size;
12 years ago
}
//Not enough stack space. Copy all to _v
else
{
12 years ago
_v.reserve(_stack_size+buf_size);
12 years ago
if(_stack_size)
_v.insert(_v.end(), _stack_buf.begin(), _stack_buf.begin() +_stack_size);
12 years ago
_v.insert(_v.end(), buf, buf+buf_size);
12 years ago
}
}
}
12 years ago
void append(const bufpair_t &buf)
{
append(buf.first, buf.second);
}
12 years ago
void clear()
{
_stack_size = 0;
_v.clear();
}
12 years ago
bufpair_t get() const
12 years ago
{
if(!_v.empty())
return bufpair_t(_v.data(), _v.size());
else
return bufpair_t(_stack_buf.data(), _stack_size);
}
12 years ago
std::size_t size() const
12 years ago
{
if(!_v.empty())
return _v.size();
else
return _stack_size;
}
12 years ago
private:
std::vector<char> _v;
std::array<char, STACK_SIZE> _stack_buf;
12 years ago
std::size_t _stack_size;
12 years ago
};
}
} //namespace c11log { namespace details {