Skip to content
Repos

mologram

C++ 901 B35 lines Opens in site

Directory Raw Download

#include "mologram/EventBus.hpp"

#include <algorithm>

namespace mologram {

void EventBus::add(const std::shared_ptr<Connection>& c) {
  std::lock_guard<std::mutex> g(mutex_);
  conns_.push_back(c);
}

void EventBus::remove(const Connection* c) {
  std::lock_guard<std::mutex> g(mutex_);
  conns_.erase(std::remove_if(conns_.begin(), conns_.end(), [&](const std::weak_ptr<Connection>& w) {
    auto s = w.lock();
    return !s || s.get() == c;
  }), conns_.end());
}

size_t EventBus::size() {
  std::lock_guard<std::mutex> g(mutex_);
  return conns_.size();
}

void EventBus::onEvent(const Event& e) {
  std::vector<std::shared_ptr<Connection>> live;
  {
    std::lock_guard<std::mutex> g(mutex_);
    for (auto& w : conns_) if (auto s = w.lock()) live.push_back(s);
  }
  js::Value frame = Wire::event(e);
  for (auto& c : live) { c->send(frame); stats_.eventsSent++; }
}

} // namespace mologram
30.1ms