1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "mojo/system/waiter_list.h"
6
7#include "base/logging.h"
8#include "mojo/system/handle_signals_state.h"
9#include "mojo/system/waiter.h"
10
11namespace mojo {
12namespace system {
13
14WaiterList::WaiterList() {
15}
16
17WaiterList::~WaiterList() {
18  DCHECK(waiters_.empty());
19}
20
21void WaiterList::AwakeWaitersForStateChange(const HandleSignalsState& state) {
22  for (WaiterInfoList::iterator it = waiters_.begin(); it != waiters_.end();
23       ++it) {
24    if (state.satisfies(it->signals))
25      it->waiter->Awake(MOJO_RESULT_OK, it->context);
26    else if (!state.can_satisfy(it->signals))
27      it->waiter->Awake(MOJO_RESULT_FAILED_PRECONDITION, it->context);
28  }
29}
30
31void WaiterList::CancelAllWaiters() {
32  for (WaiterInfoList::iterator it = waiters_.begin(); it != waiters_.end();
33       ++it) {
34    it->waiter->Awake(MOJO_RESULT_CANCELLED, it->context);
35  }
36  waiters_.clear();
37}
38
39void WaiterList::AddWaiter(Waiter* waiter,
40                           MojoHandleSignals signals,
41                           uint32_t context) {
42  waiters_.push_back(WaiterInfo(waiter, signals, context));
43}
44
45void WaiterList::RemoveWaiter(Waiter* waiter) {
46  // We allow a thread to wait on the same handle multiple times simultaneously,
47  // so we need to scan the entire list and remove all occurrences of |waiter|.
48  for (WaiterInfoList::iterator it = waiters_.begin(); it != waiters_.end();) {
49    WaiterInfoList::iterator maybe_delete = it;
50    ++it;
51    if (maybe_delete->waiter == waiter)
52      waiters_.erase(maybe_delete);
53  }
54}
55
56}  // namespace system
57}  // namespace mojo
58