Simple-Log  alpha-v0.7
RecordQueue.hpp
Go to the documentation of this file.
1 // Copyright Dominic Koepke 2021 - 2021.
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE_1_0.txt or copy at
4 // https://www.boost.org/LICENSE_1_0.txt)
5 
6 #ifndef SL_LOG_RECORD_QUEUE_HPP
7 #define SL_LOG_RECORD_QUEUE_HPP
8 
9 #pragma once
10 
11 #include "Record.hpp"
12 
13 #include <chrono>
14 #include <condition_variable>
15 #include <mutex>
16 #include <optional>
17 #include <queue>
18 #include <type_traits>
19 
20 namespace sl::log
21 {
32  template <Record TRecord>
34  {
35  public:
36  using Record_t = std::remove_cvref_t<TRecord>;
37 
43  void push(Record_t record)
44  {
45  {
46  std::scoped_lock lock{ m_RecordMx };
47  m_QueuedRecords.emplace(std::move(record));
48  }
49  m_PushVar.notify_one();
50  }
51 
60  [[nodiscard]]
61  std::optional<Record_t> take(std::optional<std::chrono::milliseconds> waitingDuration = std::nullopt)
62  {
63  auto isQueueNotEmpty = [&records = m_QueuedRecords]() { return !std::empty(records); };
64 
65  std::unique_lock lock{ m_RecordMx };
66  if (waitingDuration)
67  {
68  if (m_PushVar.wait_for(lock, *waitingDuration, isQueueNotEmpty))
69  {
70  return takeNextAsOpt();
71  }
72  return std::nullopt;
73  }
74 
75  m_PushVar.wait(lock, isQueueNotEmpty);
76  return takeNextAsOpt();
77  }
78 
84  [[nodiscard]]
85  bool empty() const noexcept
86  {
87  std::scoped_lock lock{ m_RecordMx };
88  return std::empty(m_QueuedRecords);
89  }
90 
96  [[nodiscard]]
97  std::size_t size() const noexcept
98  {
99  std::scoped_lock lock{ m_RecordMx };
100  return std::size(m_QueuedRecords);
101  }
102 
103  private:
104  [[nodiscard]]
105  std::optional<Record_t> takeNextAsOpt()
106  {
107  auto record = std::move(m_QueuedRecords.front());
108  m_QueuedRecords.pop();
109  return std::optional<Record_t>{ std::in_place, std::move(record) };
110  }
111 
112  mutable std::mutex m_RecordMx;
113  std::queue<Record_t> m_QueuedRecords;
114  std::condition_variable m_PushVar;
115  };
116 
118 }
119 
120 #endif
Storage for Record s.
Definition: RecordQueue.hpp:34
std::size_t size() const noexcept
Checks size of the internal queue.
Definition: RecordQueue.hpp:97
std::optional< Record_t > take(std::optional< std::chrono::milliseconds > waitingDuration=std::nullopt)
Takes the first Record from the queue.
Definition: RecordQueue.hpp:61
void push(Record_t record)
Pushes Record s to the internal queue.
Definition: RecordQueue.hpp:43
std::remove_cvref_t< TRecord > Record_t
Definition: RecordQueue.hpp:36
bool empty() const noexcept
Checks if the internal queue is empty.
Definition: RecordQueue.hpp:85
Definition: BasicSink.hpp:22