Leosac  0.7.0
OpenSourceAccessControl
circularbuffer.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2014-2016 Leosac
3 
4  This file is part of Leosac.
5 
6  Leosac is free software: you can redistribute it and/or modify
7  it under the terms of the GNU Affero General Public License as published by
8  the Free Software Foundation, either version 3 of the License, or
9  (at your option) any later version.
10 
11  Leosac is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU Affero General Public License for more details.
15 
16  You should have received a copy of the GNU Affero General Public License
17  along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19 
26 #include "circularbuffer.hpp"
27 
28 #include <algorithm>
29 
30 using namespace Leosac::Module::Rpleth;
31 
33  : _buffer(size)
34  , _size(size)
35  , _rIdx(0)
36  , _wIdx(0)
37  , _toRead(0)
38 {
39 }
40 
41 std::size_t CircularBuffer::read(Byte *data, std::size_t size)
42 {
43  std::size_t readIdx;
44 
45  if (!size || size > _size)
46  return (0);
47  if (!_toRead)
48  return (0);
49  size = std::min(size, _toRead);
50  for (readIdx = 0; readIdx < size; ++readIdx)
51  data[readIdx] = _buffer[(_rIdx + readIdx) % _size];
52  if (readIdx == size)
53  return (0);
54  ++readIdx;
55  _rIdx += readIdx;
56  _rIdx %= _size;
57  _toRead -= readIdx;
58  return (readIdx);
59 }
60 
61 std::size_t CircularBuffer::write(const Byte *data, std::size_t size)
62 {
63  if (!size || size > _size)
64  return (0);
65  for (std::size_t i = 0; i < size; ++i)
66  _buffer[((_wIdx + i) % _size)] = data[i];
67  _wIdx += size;
68  _wIdx %= _size;
69  if (_rIdx == _wIdx)
70  _toRead = _size;
71  else
72  _toRead = ((_wIdx - _rIdx) + _size) % _size;
73  return (size);
74 }
75 
77 {
78  return (_buffer[(_rIdx + idx) % _size]);
79 }
80 
81 void CircularBuffer::fastForward(std::size_t offset)
82 {
83  if (offset > _toRead)
84  offset = _toRead;
85  _rIdx = (_rIdx + offset) % _size;
86  _toRead -= offset;
87 }
88 
90 {
91  _rIdx = 0;
92  _wIdx = 0;
93  _toRead = 0;
94 }
95 
96 std::size_t CircularBuffer::getSize() const
97 {
98  return (_size);
99 }
100 
101 std::size_t CircularBuffer::toRead() const
102 {
103  return (_toRead);
104 }
105 
107 {
108  return (_toRead > 0);
109 }
std::uint8_t Byte
Definition: bufferutils.hpp:31
std::size_t read(Byte *data, std::size_t size)
Namespace where implementation for Rpleth support takes place.
simple circular buffer class
CircularBuffer(std::size_t size=DefaultSize)
std::size_t write(const Byte *data, std::size_t size)
void fastForward(std::size_t offset)