实现缓冲的接收器对象时,如何知道何时要写入数据?

时间:2013-11-25 09:57:34

标签: c++ boost file-io iostream

我正在为可以写入数据的接收器类型设备建模。这将用于写入512字节块的上下文中。

接收器内部,字节被缓冲为512字节向量;当满时,该缓冲区被写入当前选择的512字节块。然后清空缓冲区并写入下一个块。

我的问题是:如果缓冲区不是满的,例如当没有更多的传入数据时,如何成功刷新剩余的内容?我当然可以实现公共刷新功能,但这并不是特别优雅。想法:

class DataWriter
{

public:

    DataWriter(/* ommitted for brevity */) {}

    typedef char                                   char_type;
    typedef boost::iostreams::seekable_device_tag  category;

    std::streamsize write(char_type const * const buf, std::streamsize const n) const
    {
        for(int i = 0; i < n; ++i) {
            bufferByteForWriting(s[i]);
        }
        return n;
    }

    // to flush any remaining data. Doesn't feel 
    // that elegant
    void flush()
    {
        writeBufferedDataToBlock(m_buffer.size());
    }

private:
    void bufferByteForWriting(char const byte) const
    {
        if(m_buffer.size() == 512) {
            writeBufferedDataToBlock(512);
            std::vector<uint8_t>.swap(m_buffer);
        }
    }

    writeBufferedDataToBlock(unsigned long const count) const
    {
        // omitted for brevity
        // this writes data to a specific block
        // and increments to a new 512 byte block
        // that the next 512 byte chunk of data will be written to
    }

    std::vector<uint8_t> m_buffer;
};

0 个答案:

没有答案