簡體   English   中英

繼承流; 在Read()中緩沖

[英]Inherited Stream; buffering in Read()

我繼承了Stream類,其中我不知道如何正確實現Read()函數,所以我不會最終得到很多嵌套ifs並且難以調試代碼。 關鍵是從該流的源讀取返回常量大小的緩沖區(例如,不可更改),但Read()函數接受不同的緩沖區大小。 我雖然添加了BufferedStream,但我認為這是個壞主意。 感謝幫助!

內部源返回固定大小的緩沖區? 如果是這種情況,那就不像BufferedStream那樣 - 這只會減少對物理流的調用次數。 你需要一個單獨的機制來緩存 - 你填充的MemoryStream和空是一個合理的選擇。 例如(完全未經測試):

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);
}

這是你的“10人入門”(不確定是否全球翻譯)。

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;
}

未經測試可能會有一些錯誤。 目前還不清楚您的源流的長度是否為其固定大小的精確倍數。 如果沒有,則最終的部分緩沖區需要一些額外的邏輯。

基本原則是維護自己的固定大小的緩沖區,並跟蹤到目前為止讀取消耗的緩沖區中的位置

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM