ECFifoBuffer.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright 2005 - 2016 Zarafa and its licensors
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU Affero General Public License, version 3,
  6. * as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Affero General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Affero General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. */
  17. #ifndef ECFIFOBUFFER_H
  18. #define ECFIFOBUFFER_H
  19. #include <kopano/zcdefs.h>
  20. #include <condition_variable>
  21. #include <deque>
  22. #include <mutex>
  23. #include <kopano/kcodes.h>
  24. namespace KC {
  25. // Thread safe buffer for FIFO operations
  26. class _kc_export ECFifoBuffer _kc_final {
  27. public:
  28. typedef std::deque<unsigned char> storage_type;
  29. typedef storage_type::size_type size_type;
  30. enum close_flags { cfRead = 1, cfWrite = 2 };
  31. ECFifoBuffer(size_type ulMaxSize = 131072);
  32. ECRESULT Write(const void *lpBuf, size_type cbBuf, unsigned int ulTimeoutMs, size_type *lpcbWritten);
  33. ECRESULT Read(void *lpBuf, size_type cbBuf, unsigned int ulTimeoutMs, size_type *lpcbRead);
  34. ECRESULT Close(close_flags flags);
  35. _kc_hidden ECRESULT Flush(void);
  36. _kc_hidden bool IsClosed(ULONG flags) const;
  37. _kc_hidden bool IsEmpty(void) const;
  38. _kc_hidden bool IsFull(void) const;
  39. private:
  40. // prohibit copy
  41. ECFifoBuffer(const ECFifoBuffer &) = delete;
  42. ECFifoBuffer &operator=(const ECFifoBuffer &) = delete;
  43. storage_type m_storage;
  44. size_type m_ulMaxSize;
  45. bool m_bReaderClosed = false, m_bWriterClosed = false;
  46. std::mutex m_hMutex;
  47. std::condition_variable m_hCondNotEmpty, m_hCondNotFull, m_hCondFlushed;
  48. };
  49. // inlines
  50. inline bool ECFifoBuffer::IsClosed(ULONG flags) const {
  51. switch (flags) {
  52. case cfRead:
  53. return m_bReaderClosed;
  54. case cfWrite:
  55. return m_bWriterClosed;
  56. case cfRead|cfWrite:
  57. return m_bReaderClosed && m_bWriterClosed;
  58. default:
  59. assert(false);
  60. return false;
  61. }
  62. }
  63. inline bool ECFifoBuffer::IsEmpty() const {
  64. return m_storage.empty();
  65. }
  66. inline bool ECFifoBuffer::IsFull() const {
  67. return m_storage.size() == m_ulMaxSize;
  68. }
  69. } /* namespace */
  70. #endif // ndef ECFIFOBUFFER_H