CatapultServer  v0.5.0.1 (Elephant)
WeakContainer.h
Go to the documentation of this file.
1 
21 #pragma once
22 #include "SpinLock.h"
23 #include "catapult/functions.h"
24 #include <list>
25 #include <memory>
26 
27 namespace catapult { namespace utils {
28 
30  template<typename T>
31  class WeakContainer {
32  public:
34  WeakContainer() : WeakContainer([](const auto&) {})
35  {}
36 
38  WeakContainer(const consumer<T&>& close) : m_close(close)
39  {}
40 
41  public:
43  size_t size() const {
44  SpinLockGuard guard(m_lock);
45  const_cast<WeakContainer*>(this)->pruneInternal();
46  return m_entries.size();
47  }
48 
50  void insert(const std::weak_ptr<T>& pEntry) {
51  SpinLockGuard guard(m_lock);
52  pruneInternal();
53  m_entries.push_back(pEntry);
54  }
55 
57  void clear() {
58  SpinLockGuard guard(m_lock);
59  for (const auto& pEntry : m_entries) {
60  auto pSharedEntry = pEntry.lock();
61  if (!pSharedEntry)
62  continue;
63 
64  m_close(*pSharedEntry);
65  }
66 
67  m_entries.clear();
68  }
69 
70  private:
71  void pruneInternal() {
72  m_entries.remove_if([](const auto& pExistingEntry) { return !pExistingEntry.lock(); });
73  }
74 
75  private:
77  std::list<std::weak_ptr<T>> m_entries;
79  };
80 }}
SpinLock.h
catapult::utils::WeakContainer::m_close
consumer< T & > m_close
Definition: WeakContainer.h:76
catapult::utils::WeakContainer::size
size_t size() const
Gets the number of items in the container and removes all previously deleted items.
Definition: WeakContainer.h:43
catapult::utils::WeakContainer::m_entries
std::list< std::weak_ptr< T > > m_entries
Definition: WeakContainer.h:77
functions.h
catapult::utils::SpinLock
Definition: SpinLock.h:31
catapult::utils::WeakContainer::pruneInternal
void pruneInternal()
Definition: WeakContainer.h:71
catapult::utils::WeakContainer::insert
void insert(const std::weak_ptr< T > &pEntry)
Adds pEntry to this container and removes all previously deleted items.
Definition: WeakContainer.h:50
catapult::utils::WeakContainer
A container of weak_ptr<T> pointing to closable items.
Definition: WeakContainer.h:31
catapult::utils::WeakContainer::WeakContainer
WeakContainer()
Creates an empty container.
Definition: WeakContainer.h:34
catapult::utils::WeakContainer::clear
void clear()
Closes and removes all items in this container.
Definition: WeakContainer.h:57
catapult::utils::WeakContainer::m_lock
utils::SpinLock m_lock
Definition: WeakContainer.h:78
catapult
Definition: AddressExtractionExtension.cpp:28
catapult::utils::WeakContainer::WeakContainer
WeakContainer(const consumer< T & > &close)
Creates an empty container with a custom close function (close).
Definition: WeakContainer.h:38
catapult::consumer
std::function< void(TArgs...)> consumer
A consumer function.
Definition: functions.h:35
catapult::utils::SpinLockGuard
std::lock_guard< SpinLock > SpinLockGuard
A spin lock guard.
Definition: SpinLock.h:60