Kylin/Nng/Buffer.cpp
2024-11-10 18:02:28 +08:00

56 lines
1.2 KiB
C++

#include "Buffer.h"
#include <cstring>
#include <nng/nng.h>
namespace Nng {
Buffer::Buffer(std::size_t size) {
m_size = size;
m_buffer = nng_alloc(size);
}
Buffer::Buffer(const Buffer &rhs) : Buffer(rhs.m_size) {
std::memcpy(m_buffer, rhs.m_buffer, rhs.m_size);
}
Buffer &Buffer::operator=(const Buffer &rhs) {
if (this != &rhs) {
if (m_size != rhs.m_size) {
if (m_buffer != nullptr) nng_free(m_buffer, m_size);
m_buffer = nng_alloc(rhs.m_size);
m_size = rhs.m_size;
}
memcpy(m_buffer, rhs.m_buffer, m_size);
}
return *this;
}
Buffer &Buffer::operator=(Buffer &&rhs) noexcept {
if (this != &rhs) {
if (m_buffer != nullptr) nng_free(m_buffer, m_size);
m_buffer = rhs.m_buffer;
m_size = rhs.m_size;
rhs.m_buffer = nullptr;
rhs.m_size = 0;
}
return *this;
}
Buffer::~Buffer() {
if (m_buffer != nullptr) {
nng_free(m_buffer, m_size);
}
}
void *Buffer::release() {
auto ret = m_buffer;
m_buffer = nullptr;
m_size = 0;
return m_buffer;
}
std::string_view Buffer::data() const noexcept {
return std::string_view{reinterpret_cast<const char *>(m_buffer), m_size};
}
} // namespace Nng