• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 
17 #ifndef _DNS_LOCKED_QUEUE_H
18 #define _DNS_LOCKED_QUEUE_H
19 
20 #include <algorithm>
21 #include <deque>
22 #include <mutex>
23 
24 #include <android-base/thread_annotations.h>
25 
26 namespace android {
27 namespace net {
28 
29 template <typename T>
30 class LockedQueue {
31   public:
32     // Push an item onto the queue.
push(T item)33     void push(T item) {
34         std::lock_guard guard(mLock);
35         mQueue.push_front(std::move(item));
36     }
37 
38     // Swap out the contents of the queue
swap(std::deque<T> & other)39     void swap(std::deque<T>& other) {
40         std::lock_guard guard(mLock);
41         mQueue.swap(other);
42     }
43 
44   private:
45     std::mutex mLock;
46     std::deque<T> mQueue GUARDED_BY(mLock);
47 };
48 
49 template <typename T>
50 class LockedRingBuffer {
51   public:
LockedRingBuffer(size_t size)52     explicit LockedRingBuffer(size_t size) : mCapacity(size) {}
53 
push(T && record)54     void push(T&& record) {
55         std::lock_guard guard(mLock);
56         mQueue.push_back(std::move(record));
57         if (mQueue.size() > mCapacity) {
58             mQueue.pop_front();
59         }
60     }
61 
copy()62     std::deque<T> copy() const {
63         std::lock_guard guard(mLock);
64         return mQueue;
65     }
66 
67   private:
68     mutable std::mutex mLock;
69     const size_t mCapacity;
70     std::deque<T> mQueue GUARDED_BY(mLock);
71 };
72 
73 }  // end of namespace net
74 }  // end of namespace android
75 
76 #endif  // _DNS_LOCKEDQUEUE_H
77