1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef __RING_BUFFER_H__
16 #define __RING_BUFFER_H__
17 
18 #include <atomic>
19 #include <cstdlib>
20 #include <cstdio>
21 #include <condition_variable>
22 #include <mutex>
23 
24 #include "macros_updater.h"
25 
26 namespace Updater {
27 // for singleProducer singleConsumer
28 class RingBuffer {
29     DISALLOW_COPY_MOVE(RingBuffer);
30 public:
31     RingBuffer() = default;
32     virtual ~RingBuffer();
33     [[nodiscard]] bool Init(uint32_t singleSize, uint32_t num);
34     bool Push(uint8_t *buf, uint32_t len);
35     bool Pop(uint8_t *buf, uint32_t maxLen, uint32_t &len);
36     void Stop();
37     void StopPush();
38     void StopPop();
39     void Reset();
40 private:
41     inline bool IsFull();
42     inline bool IsEmpty();
43     void Release();
44 
45     uint32_t writeIndex_ = 0; // Producer
46     uint32_t readIndex_ = 0; // Consumer
47     uint32_t singleSize_ = 0; // single buf size
48     uint32_t num_ = 0;  // buffer num
49     uint8_t **bufArray_ = nullptr;
50     uint32_t *lenArray_ = nullptr;
51     bool isStop_ = false;
52     std::condition_variable notFull_;
53     std::condition_variable notEmpty_;
54     std::mutex notifyMtx_;
55 };
56 } // namespace Updater
57 #endif // __RING_BUFFER_H__