PageRenderTime 47ms CodeModel.GetById 22ms RepoModel.GetById 0ms 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
Possible License(s): BSD-3-Clause
  1. #ifndef __MORDOR_PROGRESS_STREAM_H__
  2. #define __MORDOR_PROGRESS_STREAM_H__
  3. // Copyright (c) 2010 - Mozy, Inc.
  4. #include <boost/function.hpp>
  5. #include "filter.h"
  6. namespace Mordor {
  7. class ProgressStream : public FilterStream
  8. {
  9. public:
  10. typedef boost::shared_ptr<ProgressStream> ptr;
  11. typedef boost::function<void (size_t)> progress_callback;
  12. private:
  13. progress_callback m_readDg, m_writeDg;
  14. size_t m_pendingRead, m_pendingWrite, m_threshold;
  15. void reportRead()
  16. {
  17. if (m_readDg && m_pendingRead > 0) {
  18. m_readDg(m_pendingRead);
  19. m_pendingRead = 0;
  20. }
  21. }
  22. void reportWrite()
  23. {
  24. if (m_writeDg && m_pendingWrite > 0) {
  25. m_writeDg(m_pendingWrite);
  26. m_pendingWrite = 0;
  27. }
  28. }
  29. public:
  30. ProgressStream(Stream::ptr parent,
  31. progress_callback readDg,
  32. progress_callback writeDg,
  33. size_t threshold = 0,
  34. bool own = true)
  35. : FilterStream(parent, own),
  36. m_readDg(readDg),
  37. m_writeDg(writeDg),
  38. m_pendingRead(0),
  39. m_pendingWrite(0),
  40. m_threshold(threshold)
  41. {}
  42. void close(CloseType type = BOTH)
  43. {
  44. // report any unreported data before close
  45. reportRead();
  46. reportWrite();
  47. if (ownsParent())
  48. parent()->close(type);
  49. }
  50. using FilterStream::read;
  51. size_t read(Buffer &b, size_t len)
  52. {
  53. size_t result = parent()->read(b, len);
  54. m_pendingRead += result;
  55. if (m_pendingRead >= m_threshold)
  56. reportRead();
  57. return result;
  58. }
  59. using FilterStream::write;
  60. size_t write(const Buffer &b, size_t len)
  61. {
  62. size_t result = parent()->write(b, len);
  63. m_pendingWrite += result;
  64. if (m_pendingWrite >= m_threshold)
  65. reportWrite();
  66. return result;
  67. }
  68. void flush(bool flushParent = true)
  69. {
  70. // report any unreported data before flush
  71. reportRead();
  72. reportWrite();
  73. parent()->flush(flushParent);
  74. }
  75. };
  76. }
  77. #endif