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_WORKER_STACK_H_
6 #define BASE_TASK_SCHEDULER_SCHEDULER_WORKER_STACK_H_
7 
8 #include <stddef.h>
9 
10 #include <vector>
11 
12 #include "base/base_export.h"
13 #include "base/macros.h"
14 
15 namespace base {
16 namespace internal {
17 
18 class SchedulerWorker;
19 
20 // A stack of SchedulerWorkers which has custom logic to treat the worker on top
21 // of the stack as being "in-use" (so its time in that position doesn't count
22 // towards being inactive / reclaimable). Supports removal of arbitrary
23 // SchedulerWorkers. DCHECKs when a SchedulerWorker is inserted multiple times.
24 // SchedulerWorkers are not owned by the stack. Push() is amortized O(1). Pop(),
25 // Peek(), Size() and Empty() are O(1). Contains() and Remove() are O(n). This
26 // class is NOT thread-safe.
27 class BASE_EXPORT SchedulerWorkerStack {
28  public:
29   SchedulerWorkerStack();
30   ~SchedulerWorkerStack();
31 
32   // Inserts |worker| at the top of the stack. |worker| must not already be on
33   // the stack. Flags the SchedulerWorker previously on top of the stack, if
34   // any, as unused.
35   void Push(SchedulerWorker* worker);
36 
37   // Removes the top SchedulerWorker from the stack and returns it. Returns
38   // nullptr if the stack is empty. Flags the SchedulerWorker now on top of the
39   // stack, if any, as being in-use.
40   SchedulerWorker* Pop();
41 
42   // Returns the top SchedulerWorker from the stack, nullptr if empty.
43   SchedulerWorker* Peek() const;
44 
45   // Returns true if |worker| is already on the stack.
46   bool Contains(const SchedulerWorker* worker) const;
47 
48   // Removes |worker| from the stack. Must not be invoked for the first worker
49   // on the stack.
50   void Remove(const SchedulerWorker* worker);
51 
52   // Returns the number of SchedulerWorkers on the stack.
Size()53   size_t Size() const { return stack_.size(); }
54 
55   // Returns true if the stack is empty.
IsEmpty()56   bool IsEmpty() const { return stack_.empty(); }
57 
58  private:
59   std::vector<SchedulerWorker*> stack_;
60 
61   DISALLOW_COPY_AND_ASSIGN(SchedulerWorkerStack);
62 };
63 
64 }  // namespace internal
65 }  // namespace base
66 
67 #endif  // BASE_TASK_SCHEDULER_SCHEDULER_WORKER_STACK_H_
68