Inherited stream buffering in Read ()

I inherited the Stream class, in which I don’t know how to implement the Read () function correctly, so I don’t get many nested ifs and it’s hard to debug the code. The fact is that reading from the source of this stream returns a buffer with a constant size (for example, not changeable), but the Read () function accepts different buffer sizes. I, however, added a BufferedStream, but I think this is a bad idea. Thanks for the help!

+3
source share
2 answers

Does the internal source return fixed size buffers? In this case, this is not exactly what it does BufferedStream- it simply reduces the number of calls in the physical stream. You will need a separate caching mechanism - a MemoryStream, which you fill in and empty, would be a smart choice. For example (completely untested):

MemoryStream localBuffer = new MemoryStream();
bool ReadNextChunk()
{
    // clear
    localBuffer.Position = 0;
    localBuffer.SetLength(0);
    // get data
    byte[] chunk = null; // TODO - read from source
    if(chunk == null || chunk.Length == 0) return false; // EOF
    localBuffer.Write(chunk, 0, chunk.Length);
    localBuffer.Position = 0;
    return true;
}
public override int Read(byte[] buffer, int offset, int count)
{
    int bytes;
    if ((bytes = localBuffer.Read(buffer, offset, count)) > 0) return bytes;
    if (!ReadNextChunk()) return 0;
    return localBuffer.Read(buffer, offset, count);
}
+1
source

Here is your "starter for 10" (not sure if this translates globally).

byte[] myBuffer = new byte[fixedSize];
int myBufferPos = fixedSize;

public int Read(byte[] buffer, int offset, int count)
{
    int copiedCount = 0
    while (copiedCount < count)
    {
        if (myBufferPos >= fixedSize)
        {
            //Read new fixed buffer into myBuffer
            // use break on no more buffer.
            myBufferPos = 0;
        }

        int bytesToCopy = fixedSize - myBufferPos;
        if (bytesToCopy > count - copiedCount)
            byteToCopy = count - copiedCount;

        Array.Copy(myBuffer, myBufferPos, buffer, offset, byteToCopy);

        offset += bytesToCopy;
        myBufferPos += bytesToCopy;
        copiedCount += bytesToCopy;
    }

    return copiedCount;
}

Loose, so there may be some errors. Its unclear whether your source stream has exact multiple lengths of a fixed size. If not, then the final partial buffer needs additional logic.

, ,

0

Source: https://habr.com/ru/post/1703694/


All Articles