Sub topic 12
Bulk reads and writes across the wrap point
This chapter assumes you can write single-item push and pop on a ring buffer with a count field, and that you know how modulo wraps an index. Here you move many items per call instead of one.
Why bulk operations need care
Looping push once per item works, but it is slow for large transfers such as network packets or audio blocks. Copying a whole block with one slice assignment (or memcpy in C) is faster. The difficulty is that a block can cross the end of the array. A contiguous block of storage never wraps by itself, so a write that starts near the end has to be split into two copies.
The two-chunk rule
Let cap be the capacity and tail the write index. The first chunk can hold at most cap - tail items before it hits the end of the array. So:
first = min(n, cap - tail)items go attail.n - firstitems, possibly zero, go at index 0.
Reads follow the same rule using head. Check the free space (or stored count) before copying anything, so a rejected call leaves the buffer unchanged.
A bulk implementation
This version uses the count-field design from earlier chapters.
class BulkRing:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self._buf = [None] * capacity
self._head = 0
self._count = 0
def __len__(self):
return self._count
def write(self, data):
n = len(data)
cap = len(self._buf)
if n > cap - self._count:
raise OverflowError("not enough free space")
tail = (self._head + self._count) % cap
first = min(n, cap - tail)
self._buf[tail:tail + first] = data[:first]
self._buf[0:n - first] = data[first:]
self._count += n
def read(self, n):
cap = len(self._buf)
if n > self._count:
raise IndexError("not enough items")
first = min(n, cap - self._head)
out = self._buf[self._head:self._head + first] + self._buf[0:n - first]
self._buf[self._head:self._head + first] = [None] * first
self._buf[0:n - first] = [None] * (n - first)
self._head = (self._head + n) % cap
self._count -= n
return out
rb = BulkRing(8)
rb.write(list(range(6)))
print(rb.read(5)) # [0, 1, 2, 3, 4]
rb.write([6, 7, 8, 9, 10]) # tail is 6, so this wraps
print(rb.read(6)) # [5, 6, 7, 8, 9, 10]The second write is the interesting call. The tail is at index 6, so first is 2. Items 6 and 7 fill the end of the array, and 8, 9 and 10 land at indices 0 to 2. When first equals n, the second slice is empty and does nothing, so no special case is needed.
Edge cases to watch
| Situation | What happens | Handling |
|---|---|---|
| `n == 0` | `first` is 0, both copies are empty | Safe, no branch needed |
| Write ends exactly at the array end | `first == n`, second copy empty | The next tail wraps to 0 through modulo |
| `n` equals free space | Buffer becomes full | Allowed with a count field |
| `n` larger than capacity | Fails the free-space check | Reject, or split it in the caller |
Returning two views instead of copying
Some APIs avoid the extra copy by returning the two contiguous regions, often called a "two-segment view". Examples are scatter/gather I/O calls such as writev. The caller processes segment one, then segment two. This saves a copy for large payloads, but the caller must not use the regions after the buffer's indices advance.
Exercise
A ring buffer has capacity 10, head 7, and count 6. You call read(5). What are the two chunk sizes, and what are the new head and count?
Show answer
The first chunk is min(5, 10 - 7) = 3 items, from indices 7, 8, 9. The second chunk is 5 - 3 = 2 items, from indices 0 and 1. The new head is (7 + 5) % 10 = 2 and the new count is 1.