PageRenderTime 33ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/mordor/streams/notify.h

http://github.com/mozy/mordor
C Header | 101 lines | 84 code | 16 blank | 1 comment | 11 complexity | 9c807af314059ba64e3fb8da85c414de MD5 | raw file
Possible License(s): BSD-3-Clause
  1. #ifndef __MORDOR_NOTIFY_STREAM_H__
  2. #define __MORDOR_NOTIFY_STREAM_H__
  3. // Copyright (c) 2009 - Mozy, Inc.
  4. #include <boost/function.hpp>
  5. #include "filter.h"
  6. namespace Mordor {
  7. class NotifyStream : public FilterStream
  8. {
  9. public:
  10. typedef boost::shared_ptr<NotifyStream> ptr;
  11. public:
  12. NotifyStream(Stream::ptr parent, bool own = true)
  13. : FilterStream(parent, own)
  14. {}
  15. boost::function<void ()> notifyOnFlush;
  16. boost::function<void ()> notifyOnEof;
  17. boost::function<void ()> notifyOnException;
  18. void close(CloseType type = BOTH)
  19. {
  20. try {
  21. if (ownsParent())
  22. parent()->close(type);
  23. } catch (...) {
  24. if (notifyOnException)
  25. notifyOnException();
  26. throw;
  27. }
  28. if (m_notifyOnClose)
  29. m_notifyOnClose(type);
  30. }
  31. using FilterStream::read;
  32. size_t read(Buffer &b, size_t len)
  33. {
  34. size_t result;
  35. try {
  36. result = parent()->read(b, len);
  37. } catch(...) {
  38. if (notifyOnException)
  39. notifyOnException();
  40. throw;
  41. }
  42. if (result == 0 && notifyOnEof)
  43. notifyOnEof();
  44. return result;
  45. }
  46. using FilterStream::write;
  47. size_t write(const Buffer &b, size_t len)
  48. {
  49. try {
  50. return parent()->write(b, len);
  51. } catch(...) {
  52. if (notifyOnException)
  53. notifyOnException();
  54. throw;
  55. }
  56. }
  57. void flush(bool flushParent = true)
  58. {
  59. try {
  60. parent()->flush(flushParent);
  61. } catch(...) {
  62. if (notifyOnException)
  63. notifyOnException();
  64. throw;
  65. }
  66. if (notifyOnFlush)
  67. notifyOnFlush();
  68. }
  69. void notifyOnClose(boost::function<void ()> dg = NULL)
  70. {
  71. if (dg)
  72. notifyOnClose2(boost::bind(&NotifyStream::onCloseAdapter, dg, _1));
  73. else
  74. notifyOnClose2(NULL);
  75. }
  76. void notifyOnClose2(boost::function<void (CloseType)> dg)
  77. { m_notifyOnClose = dg; }
  78. private:
  79. static void onCloseAdapter(boost::function<void ()> dg, CloseType type)
  80. { dg(); }
  81. private:
  82. boost::function<void (CloseType)> m_notifyOnClose;
  83. };
  84. }
  85. #endif