1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <algorithm> #include "ring_buffer_s.h"
inline ring_buffer_s::ring_buffer_s(const size_t capacity) : front_(0) , rear_(0) , size_(0) , capacity_(capacity) { data_ = new uint8_t[capacity]; }
inline ring_buffer_s::~ring_buffer_s() { delete[] data_; }
inline size_t ring_buffer_s::size() const { return size_; }
inline size_t ring_buffer_s::capacity() const { return capacity_; }
inline size_t ring_buffer_s::write(const void *data, const size_t bytes) { if (bytes == 0) return 0;
std::lock_guard<std::mutex>lk_write(mut_write_); const auto capacity = capacity_; const auto bytes_to_write = std::min(bytes, capacity - size_);
if (bytes_to_write == 0) return 0;
if (bytes_to_write <= capacity - rear_) { memcpy(data_ + rear_, data, bytes_to_write); rear_ += bytes_to_write; if (rear_ == capacity) rear_ = 0; } else { const auto size_1 = capacity - rear_; memcpy(data_ + rear_, data, size_1);
const auto size_2 = bytes_to_write - size_1; memcpy(data_, static_cast<const uint8_t*>(data) + size_1, size_2); rear_ = size_2; }
std::lock_guard<spin_mutex>lk(mut_); size_ += bytes_to_write; return bytes_to_write; }
inline size_t ring_buffer_s::read(void *data, const size_t bytes) { if (bytes == 0) return 0;
std::lock_guard<std::mutex>lk_read(mut_read_);
const auto capacity = capacity_; const auto bytes_to_read = std::min(bytes, size_);
if (bytes_to_read == 0) return 0;
if (bytes_to_read <= capacity - front_) { memcpy(data, data_ + front_, bytes_to_read); front_ += bytes_to_read; if (front_ == capacity) front_ = 0; } else { const auto size_1 = capacity - front_; memcpy(data, data_ + front_, size_1); const auto size_2 = bytes_to_read - size_1; memcpy(static_cast<uint8_t*>(data) + size_1, data_, size_2); front_ = size_2; }
std::lock_guard<spin_mutex>lk(mut_); size_ -= bytes_to_read; return bytes_to_read; }
|