Buffers
An Introduction
Prof. David Bernstein
James Madison University
Computer Science Department
bernstdh@jmu.edu
Motivation
Stream
:
An infinitely long sequence of bytes that can be read from and/or written to
Buffer:
A fixed amount of data that can be sent to or received from an I/O component
Properties
Capacity:
The number of items that it can store
Limit:
The number of "live" items
Position:
The index of the next element that can be read from or written to
Mark:
What the position should be upon reset
Properties (cont.)
Invariants:
\(0 \leq \text{mark} \leq \text{position} \leq \text{limit} \leq \text{capacity}\)
Initial Values:
\(\text{capacity} = \text{limit}\): Determined at construction-time
position: 0
mark: undefined
Operations on these Properties
Clear:
Set the position to 0, the limit to the capacity, and discard the mark
Flip:
Set the limit to the position, set the position to 0, and discard the mark if it is defined
Mark:
Set the mark to the position
Reset:
Set the position to the mark (leaving the mark unchanged)
Rewind:
Set the position to 0, and discard the mark
Operations on the Contents
Filling:
Puts a value into the element with index position and increases position (if limit hasn't been exceeded)
Draining:
Gets the value from the element at index position and increases position (if limit hasn't been reached)
Operations on the Contents (cont.)
Modes:
The buffer is either in filling mode or draining mode
Switching Modes:
Flip the buffer
Putting It All Together
An Example
There's Always More to Learn