I am currently in the process of writing a BinaryReader that caches the BaseStream.Position and BaseStream.Length properties. Here is what I have so far:
public class FastBinaryReader
{
BinaryReader reader;
public long Length { get; private set; }
public long Position { get; private set; }
public FastBinaryReader(Stream stream)
{
reader = new BinaryReader(stream);
Length = stream.Length;
Position = 0;
}
public void Seek(long newPosition)
{
reader.BaseStream.Position = newPosition;
Position = newPosition;
}
public byte[] ReadBytes(int count)
{
if (Position + count >= Length)
Position = Length;
else
Position += count;
return reader.ReadBytes(count);
}
public void Close()
{
reader.Close();
}
}
Instead of providing a Length and Position property, I would like to create a BaseStream property that allows me to expose my Position and Length properties as FastBinaryReader.BaseStream.Position and FastBinaryReader.BaseStream.Length, so that my existing code will stay compatible with the original BinaryReader class.
How would I go about doing this?
I wouldn't do this exactly the way you have it here.
Consider that you need to expose a property of type
Stream(whatBinaryReader.BaseStreamis). So you 'll need to create your own class deriving fromStream. This class would need to:FastBinaryReaderso that it can overrideStream.LengthandStream.Offsetby delegating to aFastBinaryReadermemberStream(the same one passed in theFastBinaryReaderconstructor) in order to delegate all other operations to that stream (you could have thesethrow new NotImplementedException()instead, but you never know which library method is going to call them!)You can imagine how it'd look:
This would work, but it seems to me to be slightly clumsy. The logical continuation would be to put the caching in
StreamWrapperinstead of insideFastBinaryReaderitself:This would allow you to use
StreamWrappertransparently and keep the caching behavior. But it raises the question: is theStreamyou work with so dumb that it doesn't cache this by itself?And if it isn't, maybe the performance gain you see is the result of that
ifstatement insideReadBytesand not of cachingLengthandPosition?