OLD | NEW |
| (Empty) |
1 // Copyright 2016 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 #ifndef BASE_TASK_SCHEDULER_SCHEDULER_UNIQUE_STACK_H_ | |
6 #define BASE_TASK_SCHEDULER_SCHEDULER_UNIQUE_STACK_H_ | |
7 | |
8 #include <stddef.h> | |
9 | |
10 #include <algorithm> | |
11 #include <vector> | |
12 | |
13 #include "base/logging.h" | |
14 #include "base/macros.h" | |
15 | |
16 namespace base { | |
17 namespace internal { | |
18 | |
19 // A stack that supports removal of arbitrary values and doesn't allow multiple | |
20 // insertions of the same value. This class is NOT thread-safe. | |
21 template <typename T> | |
22 class SchedulerUniqueStack { | |
23 public: | |
24 SchedulerUniqueStack(); | |
25 ~SchedulerUniqueStack(); | |
26 | |
27 // Inserts |val| at the top of the stack. |val| must not already be on the | |
28 // stack. | |
29 void Push(const T& val); | |
30 | |
31 // Removes the top value from the stack and returns it. Cannot be called on an | |
32 // empty stack. | |
33 T Pop(); | |
34 | |
35 // Removes |val| from the stack. | |
36 void Remove(const T& val); | |
37 | |
38 // Returns the number of values on the stack. | |
39 size_t Size() const; | |
40 | |
41 // Returns true if the stack is empty. | |
42 bool Empty() const; | |
43 | |
44 private: | |
45 std::vector<T> stack_; | |
46 | |
47 DISALLOW_COPY_AND_ASSIGN(SchedulerUniqueStack); | |
48 }; | |
49 | |
50 template <typename T> | |
51 SchedulerUniqueStack<T>::SchedulerUniqueStack() = default; | |
52 | |
53 template <typename T> | |
54 SchedulerUniqueStack<T>::~SchedulerUniqueStack() = default; | |
55 | |
56 template <typename T> | |
57 void SchedulerUniqueStack<T>::Push(const T& val) { | |
58 DCHECK(std::find(stack_.begin(), stack_.end(), val) == stack_.end()) | |
59 << "Value already on stack"; | |
60 stack_.push_back(val); | |
61 } | |
62 | |
63 template <typename T> | |
64 T SchedulerUniqueStack<T>::Pop() { | |
65 DCHECK(!stack_.empty()); | |
66 const T val = stack_.back(); | |
67 stack_.pop_back(); | |
68 return val; | |
69 } | |
70 | |
71 template <typename T> | |
72 void SchedulerUniqueStack<T>::Remove(const T& val) { | |
73 auto it = std::find(stack_.begin(), stack_.end(), val); | |
74 if (it != stack_.end()) | |
75 stack_.erase(it); | |
76 } | |
77 | |
78 template <typename T> | |
79 size_t SchedulerUniqueStack<T>::Size() const { | |
80 return stack_.size(); | |
81 } | |
82 | |
83 template <typename T> | |
84 bool SchedulerUniqueStack<T>::Empty() const { | |
85 return stack_.empty(); | |
86 } | |
87 | |
88 } // namespace internal | |
89 } // namespace base | |
90 | |
91 #endif // BASE_TASK_SCHEDULER_SCHEDULER_UNIQUE_STACK_H_ | |
OLD | NEW |