I am trying to decorate the Stream
class with a CaesarStream
class, which basically applies Caesar cipher to both Read
and Write
operations. I've managed to override the Write
method quite easily, but the Read
is giving me a headache. From what I understand, I need to call the underlying FileStream
's Read
method and somehow modify it, but how do I make it read the values while also adding a number to each byte, similar to what I did in the Write()
method? This is harder for me, because Read
's return value is just the amount of bytes read, not the actual read items.
public class CaesarStream : Stream
{
private int _offset;
private FileStream _stream;
public CaesarStream(FileStream stream, int offset)
{
_offset = offset;
_stream = stream;
}
public override int Read(byte[] array, int offset, int count)
{
//I imagine i need to call
//_stream.Read(array, offset, count);
//and modify the array, but how do i make my stream return it afterwards?
//I have no access to the underlying private FileStream fields so I'm clueless
}
public override void Write(byte[] buffer, int offset, int count)
{
byte[] changedBytes = new byte[buffer.Length];
int index = 0;
foreach (byte b in buffer)
{
changedBytes[index] = (byte) (b + (byte) _offset);
index++;
}
_stream.Write(changedBytes, offset, count);
}
}
PS I know i should also check the amount of bytes read/written and keep reading/writing until it's finished, but I haven't gotten to that yet. I'd like to be done with the reading part first.