<?xml version="1.0" encoding="UTF-8" standalone="yes"?><oembed><version><![CDATA[1.0]]></version><provider_name><![CDATA[The ryg blog]]></provider_name><provider_url><![CDATA[https://fgiesen.wordpress.com]]></provider_url><author_name><![CDATA[fgiesen]]></author_name><author_url><![CDATA[https://fgiesen.wordpress.com/author/fgiesen/]]></author_url><title><![CDATA[Buffer-centric IO]]></title><type><![CDATA[link]]></type><html><![CDATA[<p>This is a small but nifty solution I discovered while working on IO code for <a href="http://www.radgametools.com/iggy.htm">Iggy</a>. I don&#8217;t claim to have invented it &#8211; as usual in CS, this was probably first published in the 60s or 70s &#8211; but I definitely never ran across it in this form before, so it seems worth writing up. Small disclaimer up front: First, this describes a combination of techniques that are somewhat orthogonal, but they nicely complement each other, so I describe them at the same time. Second, it&#8217;s definitely not the best approach in every scenario, but it&#8217;s nifty and definitely worth knowing about. I&#8217;ve found it particularly useful when dealing with compressed data.</p>
<h3>Setting</h3>
<p>A lot of code needs to be able to accept data from different sources. Sometimes you want to load data from a file; sometimes it&#8217;s already in memory, or it&#8217;s a memory-mapped file (boils down to the same thing). If it comes from a file, you may have one file per item you want to load, or pack a bunch of related data into a &#8220;bundle&#8221; file. Finally, data may be compressed or encrypted.</p>
<p>If possible, the simplest solution is to just write your code to assume one such method and stick with it &#8211; the easiest usually being the &#8220;already in memory&#8221; option. This is fine, but can get problematic depending on the file format: for example, the <code>SWF</code> (Flash) files that Iggy loads are usually Deflate-compressed as a whole, and may contain chunks of image data that are themselves JPEG- or Deflate-compressed. Finally, Iggy wants all the data in its own format, not in the Flash file format, since even uncompressed Flash files involve a lot of bit-packing and implicit information that makes them awkward to deal with directly.</p>
<p>Ultimately, all we want to have in memory is our own data structures; but an implementation that expects all data to be decompressed to memory first will need a lot of extra memory (temporarily at least), which is problematic on memory-constrained platforms.</p>
<p>The standard solution is to get rid of the memory-centric view completely and instead implement a stream abstraction. For read-only IO (which is what I&#8217;ll be talking about here), a simple but typical (C++) implementation looks like this:</p>
<pre>
class SimpleStream {
public:
    virtual ErrorCode Read(U8 *buffer, U32 numBytes,
                           U32 *bytesActuallyRead) = 0;
};
</pre>
<p>Code that needs to read data takes a <code>Stream</code> argument and calls <code>Read</code> when necessary to fill its input buffers. You&#8217;ll find designs like this in most C++ libraries that handle at least some degree of IO.</p>
<p>Simple, right?</p>
<h3>The problems</h3>
<p>Actually, there&#8217;s multiple problems with this approach.</p>
<p>For example, consider the case where the file is already loaded into memory (or memory-mapped). The app expects data to land in <code>buffer</code>, so our <code>Read</code> implementation will end up having to do a <code>memcpy</code> or something similar. That&#8217;s unlikely to be a performance problem if it happens only once, but it&#8217;s certainly not pretty, and if you have multiple streams nested inside each other, the overhead keeps adding up.</p>
<p>Somewhat more subtly, there&#8217;s the business with <code>numBytes</code> and <code>bytesActuallyRead</code>. We request some number of bytes, but may get a different number of bytes back (anything between 0 and <code>numBytes</code> inclusive). So client code has to be able to deal with this. In theory, &#8220;stream producer&#8221; code can use this to make things simpler; to give an example, lots of compressed formats are internally subdivided into chunks (with sizes typically somewhere between 32KB and 1MB), and it&#8217;s convenient to write the code such that a single <code>Read</code> will never cross a chunk boundary. In practice, a lot of the &#8220;stream consumer&#8221; code ends up being written using memory or uncompressed file streams as input, and will implicitly assume that the only cases where &#8220;partial&#8221; blocks are returned are &#8220;end of file&#8221; or error conditions (because that&#8217;s all they ever see while developing the code). This behavior may be technically wrong, but it&#8217;s common, and the actual cost (slightly more complexity in the producer code) is low enough to not usually be worth making a stand about.</p>
<p>So we have an API where we frequently end up having to check for and deal with what&#8217;s basically the same boundary condition on both sides of the fence. That&#8217;s a bad sign.</p>
<p>Finally, there&#8217;s the issue of error handling. If we&#8217;re loading from memory, there&#8217;s basically only one error condition that can happen: unexpected end, when we&#8217;ve exhausted the input buffer even though we want to read more. But for a general stream, there&#8217;s all kinds of errors that can happen: end of file, yes, but also read errors from disk, timeouts when reading from a network file system, integrity-check errors, errors decompressing or decrypting a stream, and so on. Ideally, every single caller should check error codes (and perform error handling if necessary) all the time. Again, in practice, this is rarely done everywhere, and what error-handling code is there is often poorly tested.</p>
<p>The problem is that checking for and reacting to error conditions everywhere is <em>inconvenient</em>. One solution is using exception handling; but this is, at least among game developers, a somewhat controversial C++ feature. In the case of Iggy, which is written in C, it&#8217;s not even an option (okay, there is <code>setjmp</code> / <code>longjmp</code>, which we even use in some cases &#8211; though not for IO &#8211; but let&#8217;s not go there). A different option is to write the code such that error checking isn&#8217;t required after every <code>Read</code> call; if possible, this is usually much nicer to use.</p>
<h3>A different approach</h3>
<p>Without further ado, here&#8217;s a different stream abstraction:</p>
<pre>
struct BufferedStream {
    const U8 *start;      // Start of buffer.
    const U8 *end;        // (One past) end of buffer
                          // i.e. buffer_size = end-start.
    const U8 *cursor;     // Cursor in buffer. 
                          // Invariant: start &lt;= cursor &lt;= end.
    ErrorCode error;      // Initialized to NoError.

    ErrorCode (*Refill)(BufferedStream *s);
    // Pre-condition: cursor == end (buffer fully consumed).
    // Post-condition: start == cursor &lt; end.
    // Always returns "error".
};
</pre>
<p>There&#8217;s 3 big conceptual differences here:</p>
<ol>
<li>The buffer is owned and managed by the producer &#8211; the consumer does <em>not</em> get to specify where data ends up.</li>
<li>The <code>Read</code> function has been replaced with a <code>Refill</code> function, which reads in an unspecified amount of bytes &#8211; the one guarantee here is that at least one more byte will be returned, even in case of error; more about that later. Also note it&#8217;s a function pointer, not a virtual function. Again, there&#8217;s a good reason for that.</li>
<li>Instead of reporting an error code on every <code>Read</code>, there&#8217;s a persistent <code>error</code> variable &#8211; think <code>errno</code> (but local to the given stream, which avoids the serious problems that hamper the &#8216;real&#8217; <code>errno</code>).</li>
</ol>
<p>Note that this abstraction is both more general and more specific than the stream abstraction above: more general in the sense that it&#8217;s easy to implement <code>SimpleStream::Read</code> on top of the <code>BufferedStream</code> abstraction (I&#8217;ll get to that in a second), and more specific in the sense that all <code>BufferedStream</code> implementations are, by necessity, buffered (it might just be a one-byte-buffer, but it&#8217;s there). It&#8217;s also lower-level; the buffer isn&#8217;t encapsulated, it&#8217;s visible to client code. That turns out to be fairly important. Instead of elaborating, I&#8217;m gonna present a series of examples that demonstrate some of the strengths of this approach.</p>
<h3>Example 1: all zeros</h3>
<p>Probably the simplest implementation of this interface just generates an infinite stream of zeros:</p>
<pre>
static ErrorCode refillZeros(BufferedStream *s)
{
    static const U8 zeros[256] = { 0 };
    s-&gt;start = zeros;
    s-&gt;cursor = zeros;
    s-&gt;end = zeros + sizeof(zeros);
    return s-&gt;error;
}

static void initZeroStream(BufferedStream *s)
{
    s-&gt;Refill = refillZeros;
    s-&gt;error = NoError;
    s-&gt;Refill(s);
}
</pre>
<p>Not much to say here: whenever <code>Refill</code> is called, we reset the pointers to go over the same array of zeros again (the count of 256 is completely arbitrary; you could just as well use 1, but then you&#8217;d end up calling <code>Refill</code> a lot).</p>
<h3>Example 2: stream from memory</h2>
<p>For the next step up, here&#8217;s a stream that reads either directly from memory, or from a memory-mapped file:</p>
<pre>
static ErrorCode fail(BufferedStream *s, ErrorCode reason)
{
    // For errors: Set the error status, then continue returning
    // zeros indefinitely.
    s-&gt;error = reason;
    s-&gt;Refill = refillZeros;
    return s-&gt;Refill(s);
}

static ErrorCode refillMemStream(BufferedStream *s)
{
    // If this gets called, clients wants to read past the end of
    // the memory buffer, which is an error.
    return fail(s, ReadPastEOF);
}

static void initMemStream(BufferedStream *s, U8 *mem, size_t size)
{
    s-&gt;start = mem;
    s-&gt;cursor = mem;
    s-&gt;end = mem + size;
    s-&gt;error = NoError;
    s-&gt;Refill = refillMemStream;
}
</pre>
<p>The init function isn&#8217;t very interesting, but the <code>Refill</code> part deserves some explanation: As mentioned before, the client calls <code>Refill</code> when it&#8217;s finished with the current buffer and still needs more data. In this case, the &#8220;buffer&#8221; was all the data we had; therefore, if we ever try to refill, that means the client is trying to read past the end-of-file, which is an error, so we call <code>fail</code>, which first sets the error code. We then change the refill function pointer to <code>refillZeros</code>, our previous example: in other words, if the client tries to read past the end of file, they&#8217;ll get an infinite stream of zeros (satisfying our above invariant that <code>Refill</code> <em>always</em> returns at least one more byte). But the error flag will be set, and since <code>refillZeros</code> doesn&#8217;t touch it, it will stay the way it was.</p>
<p>In effect, making <code>Refill</code> a function pointer allows us to implicitly turn any stream into a state machine. This is a powerful facility, and it&#8217;s great for this kind of error handling and to deal with certain compressed formats (more later), but like any kind of state machine, it quickly gets more confusing than it&#8217;s worth if there&#8217;s more than a handful of states.</p>
<p>Anyway, there&#8217;s one more thing worth pointing out: <em>there&#8217;s no copying here</em>. A from-memory implementation of <code>SimpleStream</code> would need to do a <em>memcpy</em> (or something equivalent) in its <code>Read</code> function, but since we don&#8217;t let the client decide where the data ends up, we can just point it directly to the original bytes without doing any extra work. Because forwarding is effectively free, it makes it easy to decouple &#8220;framing&#8221; from data processing even in performance-critical code.</p>
<h3>Example 3: parsing JPEG data</h3>
<p>Case in point: JPEG data. JPEG files interleave compressed bitstream data and metadata. Metadata exists in several types and is denoted by a special code, a so-called &#8220;marker&#8221;. A marker consists of an all-1-bits byte (0xff) followed by a nonzero byte. Because the compressed bitstream can contain 0xff bytes too, they need to be escaped using the special code 0xff 0x00 (which is not interpreted as a marker). Thus code that reads JPEG data needs to look at every byte read, check if it&#8217;s 0xff, and if so look at the next byte to figure out whether it&#8217;s part of a marker or just an escape code. Having to do this in the decoder inner loop is both annoying (because it complicates the code) and slow (because it forces byte-wise processing and adds a bunch of branches). It&#8217;s much nicer to do it in a separate pass, and with this approach we can naturally phrase it as a layered stream (I&#8217;ll skip the initialization this time):</p>
<pre>
struct JPEGDataStream : public BufferedStream {
    BufferedStream *src; // Read from here
};

static ErrorCode refillJPEG_lastWasFF(BufferedStream *s);

static ErrorCode refillJPEG(BufferedStream *str)
{
    JPEGDataStream *j = (JPEGDataStream *)str;
    BufferedStream *s = j-&gt;src;

    // Refill if necessary and check for errors
    if (s-&gt;cursor == s-&gt;end) {
        if (s-&gt;Refill(s) != NoError)
            return fail(str, s-&gt;error);
    }

    // Find next 0xff byte (if any)
    U8 *next_ff = memchr(s-&gt;cursor, 0xff, s-&gt;end - s-&gt;cursor);
    if (next_ff) {
        // return bytes until 0xff,
        // continue with refillJPEG_lastWasFF.
        j-&gt;start = s-&gt;cursor;
        j-&gt;cursor = s-&gt;cursor; // EDIT typo fixed (was "current")
        j-&gt;end = next_ff;
        j-&gt;Refill = refillJPEG_lastWasFF;
        s-&gt;cursor = next_ff + 1; // mark 0xff byte as read
    } else {
        // return all of current buffer
        j-&gt;start = s-&gt;cursor;
        j-&gt;cursor = s-&gt;cursor;
        j-&gt;end = s-&gt;end;
        s-&gt;cursor = s-&gt;end; // read everything
    }
}

static ErrorCode refillJPEG_lastWasFF(BufferedStream *str)
{
    static const U8 one_ff[1] = { 0xff };
    JPEGDataStream *j = (JPEGDataStream *)str;
    BufferedStream *s = j-&gt;src;

    // Refill if necessary and check for errors
    if (s-&gt;cursor == s-&gt;end) {
        if (s-&gt;Refill(s) != NoError)
            return fail(str, s-&gt;error);
    }

    // Process marker type byte
    switch (*s-&gt;cursor++) {
    case 0x00:
        // Not a marker, just an escaped 0xff!
        // Return one 0xff byte, then resume regular parsing.
        j-&gt;start = one_ff;
        j-&gt;cursor = one_ff;
        j-&gt;end = one_ff + 1;
        j-&gt;Refill = refillJPEG;                        
        break;

        // Was a marker. Handle other cases here...

    case 0xff: // 0xff 0xff is invalid in JPEG
        return fail(str, CorruptedData);

    default:
        return fail(str, UnknownMarker);
    }
}
</pre>
<p>It&#8217;s a bit more code than the preceding examples, but it demonstrates how streams can be &#8220;layered&#8221; and also nicely shows how the implicit state machine can be useful.</p>
<h3>Discussion</h3>
<p>This clearly solves the first issue I raised &#8211; there&#8217;s no unnecessary copying going on. The interface is also really simple: Everything is in memory. Client code still has to deal with partial results, but because the client never gets to specify how much data to read in the first place, the interface makes it a lot clearer that handling this case is necessary. It also makes it a lot more common, which goes a long way towards making sure that it gets handled. Finally, error handling &#8211; this is only partially resolved, but the invariants have been picked to make the life of client code as easy as possible: All errors are &#8220;sticky&#8221;, so there&#8217;s no risk of &#8220;missing&#8221; an error if you do something else in between doing the read and checking for errors (a typical issue with <code>errno</code>, <code>GetLastError</code> and the like). And our error-&#8220;refill&#8221; functions still return data (albeit just zeros in these examples). These two things together mean that, in practice, you only really need to check for errors inside loops that might not terminate otherwise. In all other cases, you will fall through to the end of functions eventually; as long as you check the error code before you dispose of the stream, it will be noticed.</p>
<p>One really cool thing you can do with this type of approach (that I don&#8217;t want to discuss in full or with code because it would get lengthy and is really only interesting to a handful of people) is give the client pointers into the window in a LZ77-type compressor. This completely removes the need for any separate output buffers, saving a lot of copying and some small amount of memory. This is especially nice on memory-constrained targets like SPUs. In general, giving the producer (instead of the consumer) control over where the buffer is in memory allows producer code to use ring buffers (like a LZ77 window) completely transparently, which I think is pretty cool.</p>
<p>There&#8217;s a lot more that could be said about this, and initially I wanted to, but I didn&#8217;t want to make this too long; better have two medium-sized posts than one huge post that nobody reads to the finish. Besides, it means I can base a potential second post on actual questions I get, rather than having to guess what questions you might have, which I&#8217;m not very good at.</p>
]]></html></oembed>