• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.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 private:
38     inline bool IsFull();
39     inline bool IsEmpty();
40     void Release();
41 
42     uint32_t writeIndex_ = 0; // Producer
43     uint32_t readIndex_ = 0; // Consumer
44     uint32_t singleSize_ = 0; // single buf size
45     uint32_t num_ = 0;  // buffer num
46     uint8_t **bufArray_ = nullptr;
47     uint32_t *lenArray_ = nullptr;
48     bool isStop_ = false;
49     std::condition_variable notFull_;
50     std::condition_variable notEmpty_;
51     std::mutex notifyMtx_;
52 };
53 } // namespace Updater
54 #endif // __RING_BUFFER_H__