1 /*
2  * Copyright (c) 2021, 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 CPP_TELEMETRY_CARTELEMETRYD_SRC_RINGBUFFER_H_
18 #define CPP_TELEMETRY_CARTELEMETRYD_SRC_RINGBUFFER_H_
19 
20 #include "BufferedCarData.h"
21 
22 #include <list>
23 
24 namespace android {
25 namespace automotive {
26 namespace telemetry {
27 
28 // A ring buffer that holds BufferedCarData. It drops old data if it's full.
29 // Not thread-safe.
30 class RingBuffer {
31 public:
32     // RingBuffer limits the number of elements in the buffer to the given param `sizeLimit`.
33     // Doesn't pre-allocate the memory.
34     explicit RingBuffer(int32_t sizeLimit);
35 
36     // Not copyable or movable
37     RingBuffer(const RingBuffer&) = delete;
38     RingBuffer& operator=(const RingBuffer&) = delete;
39     RingBuffer(RingBuffer&&) = delete;
40     RingBuffer& operator=(RingBuffer&&) = delete;
41 
42     // Pushes the data to the buffer. If the buffer is full, it removes the oldest data.
43     // Supports moving the data to the RingBuffer.
44     void push(BufferedCarData&& data);
45 
46     // Returns the newest element from the ring buffer and removes it from the buffer.
47     BufferedCarData popBack();
48 
49     // Dumps the current state for dumpsys.
50     void dump(int fd) const;
51 
52     // Returns the number of elements in the buffer.
53     int32_t size() const;
54 
55 private:
56     const int32_t mSizeLimit;
57 
58     // TODO(b/174608802): Improve dropped CarData handling, see ag/13818937 for details.
59     int64_t mTotalDroppedDataCount;
60 
61     // Linked list that holds all the data and allows deleting old data when the buffer is full.
62     std::list<BufferedCarData> mList;
63 };
64 
65 }  // namespace telemetry
66 }  // namespace automotive
67 }  // namespace android
68 
69 #endif  // CPP_TELEMETRY_CARTELEMETRYD_SRC_RINGBUFFER_H_
70