Wednesday, November 24, 2010

SkipObject Bug Solution

Yesterday I blogged about a bug I was having while implementing a serializer for my append only file storage.  I blogged about it here.

The problem with the code is found by gaining a better understanding of how the += operator works:

x += y;

Is equivalent to writing

x = x + y;

The problem in this case can is explained in the following snippet:

public void SkipObject(Stream stream)
{
var reader = new BinaryReader(stream);
// The problem here is that we first get the current position
// from the stream, then we read our int (moving the stream
// forward 4 bytes), then sum the position and the int, but the
// position value we read initially is now out of date so we wind
// up being 4 bytes away from where we expected.
stream.Position = stream.Position + reader.ReadInt32();
}

The fixed version of the function can be seen here:

public void SkipObject(Stream stream)
{
var reader = new BinaryReader(stream);
var objectSize = reader.ReadInt32();
stream.Position += objectSize;
}

Tuesday, November 23, 2010

Where is the bug?

I was recently working on an append only file data store.  I am building a list of the data at load time.  The code that builds the index doesn’t know how to read anything, but the header information for an object.  I have another class which implements ISerializer to handle reading and writing the objects that I want to store.  The ISerializer interface has a method called SkipObject which is supposed to advance the the stream past the object, which will have it at the start of the next object’s header.  The serializer can know how long the object is because the first 4 bytes of the object make up an integer that is the length of the object in bytes.

Here is what I initially had for the SkipObject method:

public void SkipObject(Stream stream)
{
var reader = new BinaryReader(stream);
stream.Position += reader.ReadInt32();
}
view raw SkipObject.cs hosted with ❤ by GitHub

Can you spot the bug? I'll post the answer tomorrow.