roo_transport
API Documentation for roo_transport
Loading...
Searching...
No Matches
ring_buffer.h
Go to the documentation of this file.
1#pragma once
2
4#include "roo_logging.h"
5
6namespace roo_transport {
7namespace internal {
8
9// Circular buffer implementation for 16-bit sequence numbers.
10// The buffer is implemented as a ring buffer, with a fixed size of
11// 2^capacity_log2.
12//
13// Used for both incoming and outgoing data.
15 public:
16 RingBuffer(int capacity_log2, uint16_t initial_seq = 0)
17 : capacity_log2_(capacity_log2), begin_(initial_seq), end_(initial_seq) {
18 CHECK_LE(capacity_log2, 10);
19 }
20
21 uint16_t slotsUsed() const { return end_ - begin_; }
22
23 uint16_t slotsFree() const { return capacity() - slotsUsed(); }
24
25 SeqNum begin() const { return begin_; }
26 SeqNum end() const { return end_; }
27
29 CHECK(slotsFree() > 0);
30 return end_++;
31 }
32
34 CHECK(slotsUsed() > 0);
35 return begin_++;
36 }
37
38 bool empty() const { return slotsUsed() == 0; }
39
40 void reset(SeqNum seq) {
41 CHECK_EQ(begin_, end_);
42 begin_ = seq;
43 end_ = seq;
44 }
45
46 // Relies on wrap-around semantics of SeqNum.
47 bool contains(SeqNum seq) const { return begin_ <= seq && seq < end_; }
48
49 uint16_t offset_for(SeqNum seq) const {
50 DCHECK(contains(seq));
51 return seq.raw() & (capacity() - 1);
52 }
53
54 // Restores high bits of seq, extending it to uint16_t, by assuming that
55 // truncated_pos must be 'close' to the range. Specifically, we make sure to
56 // pick high bits so that the result is within 1 << (pos_bits/2) from
57 // begin.
58 SeqNum restorePosHighBits(uint16_t truncated_pos, int pos_bits) {
59 DCHECK_GE(pos_bits, capacity_log2_ + 2);
60 uint16_t left = begin_.raw() - (1 << (pos_bits - 1));
61 return left + (((uint16_t)(truncated_pos - left)) % (1 << pos_bits));
62 }
63
64 int capacity_log2() const { return capacity_log2_; }
65 uint16_t capacity() const { return 1 << capacity_log2_; }
66
67 private:
68 uint16_t offset_begin() const { return begin_.raw() & (capacity() - 1); }
69 uint16_t offset_end() const { return end_.raw() & (capacity() - 1); }
70
71 int capacity_log2_;
72 SeqNum begin_;
73 SeqNum end_;
74};
75
76} // namespace internal
77} // namespace roo_transport
RingBuffer(int capacity_log2, uint16_t initial_seq=0)
Definition ring_buffer.h:16
bool contains(SeqNum seq) const
Definition ring_buffer.h:47
uint16_t offset_for(SeqNum seq) const
Definition ring_buffer.h:49
SeqNum restorePosHighBits(uint16_t truncated_pos, int pos_bits)
Definition ring_buffer.h:58