blob: d7c42588cdfe544fe15ceeabb57742277b1d7ec2 [file] [log] [blame]
Ben Chan6e726922011-06-28 15:54:32 -07001// Copyright (c) 2011 The Chromium OS 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 "cros-disks/device-event-queue.h"
6
Ben Chan6e726922011-06-28 15:54:32 -07007#include <base/logging.h>
8
9#include "cros-disks/device-event.h"
10
11namespace cros_disks {
12
13DeviceEventQueue::DeviceEventQueue() {
14}
15
16DeviceEventQueue::~DeviceEventQueue() {
17}
18
19void DeviceEventQueue::Remove() {
20 if (!events_.empty())
21 events_.pop_back();
22}
23
24void DeviceEventQueue::Add(const DeviceEvent& event) {
25 // Discard an Ignored or DeviceScanned event.
26 if (event.event_type == DeviceEvent::kIgnored ||
27 event.event_type == DeviceEvent::kDeviceScanned)
28 return;
29
Ben Chan7599f992011-12-13 16:04:34 -080030 for (DeviceEventList::iterator last_event_iterator = events_.begin();
31 last_event_iterator != events_.end(); ++last_event_iterator) {
Ben Chan6e726922011-06-28 15:54:32 -070032 const DeviceEvent& last_event = *last_event_iterator;
33
34 // Skip an unrelated event.
35 if (event.device_path != last_event.device_path ||
36 event.IsDiskEvent() != last_event.IsDiskEvent())
37 continue;
38
39 // Combine events of the same type and device path and keep the latest one.
40 if (event.event_type == last_event.event_type) {
41 events_.erase(last_event_iterator);
42 events_.push_front(event);
43 return;
44 }
45
46 // Discard a Removed event and its last related event, which is an
Ben Chan7599f992011-12-13 16:04:34 -080047 // Added/Changed event. Note that the last related event cannot be
48 // a Removed event as that is already handled by the code above.
Ben Chan6e726922011-06-28 15:54:32 -070049 if (event.event_type == DeviceEvent::kDeviceRemoved ||
50 event.event_type == DeviceEvent::kDiskRemoved) {
51 CHECK(last_event.event_type != DeviceEvent::kDeviceRemoved &&
Ben Chan7599f992011-12-13 16:04:34 -080052 last_event.event_type != DeviceEvent::kDiskRemoved)
53 << "Last event should not be a Removed event";
Ben Chan6e726922011-06-28 15:54:32 -070054 events_.erase(last_event_iterator);
55 return;
56 }
57
Ben Chan7599f992011-12-13 16:04:34 -080058 // Discard a DiskChanged event if a related DiskAdded event is already
59 // in the queue.
Ben Chan6e726922011-06-28 15:54:32 -070060 if (event.event_type == DeviceEvent::kDiskChanged &&
Ben Chan7599f992011-12-13 16:04:34 -080061 last_event.event_type == DeviceEvent::kDiskAdded)
Ben Chan6e726922011-06-28 15:54:32 -070062 return;
63 }
64
65 events_.push_front(event);
66}
67
68const DeviceEvent* DeviceEventQueue::Head() const {
69 return events_.empty() ? NULL : &events_.back();
70}
71
72} // namespace cros_disks