PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 6ms RepoModel.GetById 34ms app.codeStats 0ms

/mordor/streams/progress.h

http://github.com/mozy/mordor
C Header | 98 lines | 74 code | 21 blank | 3 comment | 7 complexity | e28dba6374e8d5d1554de4623a80f578 MD5 | raw file
 1#ifndef __MORDOR_PROGRESS_STREAM_H__
 2#define __MORDOR_PROGRESS_STREAM_H__
 3// Copyright (c) 2010 - Mozy, Inc.
 4
 5#include <boost/function.hpp>
 6
 7#include "filter.h"
 8
 9namespace Mordor {
10
11class ProgressStream : public FilterStream
12{
13public:
14    typedef boost::shared_ptr<ProgressStream> ptr;
15    typedef boost::function<void (size_t)> progress_callback;
16
17private:
18    progress_callback m_readDg, m_writeDg;
19    size_t m_pendingRead, m_pendingWrite, m_threshold;
20
21    void reportRead()
22    {
23        if (m_readDg && m_pendingRead > 0) {
24            m_readDg(m_pendingRead);
25            m_pendingRead = 0;
26        }
27    }
28
29    void reportWrite()
30    {
31        if (m_writeDg && m_pendingWrite > 0) {
32            m_writeDg(m_pendingWrite);
33            m_pendingWrite = 0;
34        }
35    }
36
37public:
38    ProgressStream(Stream::ptr parent,
39                   progress_callback readDg,
40                   progress_callback writeDg,
41                   size_t threshold = 0,
42                   bool own = true)
43        : FilterStream(parent, own),
44          m_readDg(readDg),
45          m_writeDg(writeDg),
46          m_pendingRead(0),
47          m_pendingWrite(0),
48          m_threshold(threshold)
49    {}
50
51
52    void close(CloseType type = BOTH)
53    {
54        // report any unreported data before close
55        reportRead();
56        reportWrite();
57
58        if (ownsParent())
59            parent()->close(type);
60    }
61
62    using FilterStream::read;
63    size_t read(Buffer &b, size_t len)
64    {
65        size_t result = parent()->read(b, len);
66
67        m_pendingRead += result;
68        if (m_pendingRead >= m_threshold)
69            reportRead();
70
71        return result;
72    }
73
74    using FilterStream::write;
75    size_t write(const Buffer &b, size_t len)
76    {
77        size_t result = parent()->write(b, len);
78
79        m_pendingWrite += result;
80        if (m_pendingWrite >= m_threshold)
81            reportWrite();
82
83        return result;
84    }
85
86    void flush(bool flushParent = true)
87    {
88        // report any unreported data before flush
89        reportRead();
90        reportWrite();
91
92        parent()->flush(flushParent);
93    }
94};
95
96}
97
98#endif