Apollo  6.0
Open source self driving car software
indexed_queue.h
Go to the documentation of this file.
1 /******************************************************************************
2  * Copyright 2017 The Apollo Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *****************************************************************************/
16 
21 #pragma once
22 
23 #include <memory>
24 #include <queue>
25 #include <unordered_map>
26 #include <utility>
27 
29 
30 namespace apollo {
31 namespace planning {
32 
33 template <typename I, typename T>
34 class IndexedQueue {
35  public:
36  // Get infinite capacity with 0.
37  explicit IndexedQueue(size_t capacity) : capacity_(capacity) {}
38 
39  const T *Find(const I id) const {
40  auto *result = apollo::common::util::FindOrNull(map_, id);
41  return result ? result->get() : nullptr;
42  }
43 
44  const T *Latest() const {
45  if (queue_.empty()) {
46  return nullptr;
47  }
48  return Find(queue_.back().first);
49  }
50 
51  bool Add(const I id, std::unique_ptr<T> ptr) {
52  if (Find(id)) {
53  return false;
54  }
55  if (capacity_ > 0 && queue_.size() == capacity_) {
56  map_.erase(queue_.front().first);
57  queue_.pop();
58  }
59  queue_.emplace(id, ptr.get());
60  map_[id] = std::move(ptr);
61  return true;
62  }
63 
64  void Clear() {
65  while (!queue_.empty()) {
66  queue_.pop();
67  }
68  map_.clear();
69  }
70 
71  public:
72  size_t capacity_ = 0;
73  std::queue<std::pair<I, const T *>> queue_;
74  std::unordered_map<I, std::unique_ptr<T>> map_;
75 };
76 
77 } // namespace planning
78 } // namespace apollo
void Clear()
Definition: indexed_queue.h:64
bool Add(const I id, std::unique_ptr< T > ptr)
Definition: indexed_queue.h:51
const T * Find(const I id) const
Definition: indexed_queue.h:39
PlanningContext is the runtime context in planning. It is persistent across multiple frames...
Definition: atomic_hash_map.h:25
size_t capacity_
Definition: indexed_queue.h:72
Planning module main class. It processes GPS and IMU as input, to generate planning info...
Some map util functions.
std::unordered_map< I, std::unique_ptr< T > > map_
Definition: indexed_queue.h:74
IndexedQueue(size_t capacity)
Definition: indexed_queue.h:37
std::queue< std::pair< I, const T * > > queue_
Definition: indexed_queue.h:73
Definition: indexed_queue.h:34
const T * Latest() const
Definition: indexed_queue.h:44