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 FFRT_RING_BUFFER_H 16 #define FFRT_RING_BUFFER_H 17 18 #include <iostream> 19 #include <cstring> 20 #include <mutex> 21 #include <securec.h> 22 23 namespace ffrt { 24 25 class FFRTRingBuffer { 26 public: FFRTRingBuffer(char * buf,uint32_t len)27 FFRTRingBuffer(char *buf, uint32_t len) : buf_(buf), bufferLen_(len), writtenSize_(0) 28 { 29 memset_s(buf_, bufferLen_, 0, bufferLen_); 30 } 31 32 template<typename T> Write(T data)33 int Write(T data) 34 { 35 std::lock_guard<std::mutex> lock(bufferMutex_); 36 if (writtenSize_ + sizeof(T) > bufferLen_) { 37 writtenSize_ = sizeof(T); 38 return memcpy_s(buf_, bufferLen_, &data, sizeof(T)); 39 } else { 40 int ret = memcpy_s(buf_ + writtenSize_, bufferLen_ - writtenSize_, &data, sizeof(T)); 41 writtenSize_ += sizeof(T); 42 return ret; 43 } 44 } 45 GetBuffer()46 char *GetBuffer() 47 { 48 return buf_; 49 } 50 GetBufferSize()51 uint32_t GetBufferSize() 52 { 53 return bufferLen_; 54 } 55 56 private: 57 char *buf_; 58 uint32_t bufferLen_; 59 uint32_t writtenSize_; 60 std::mutex bufferMutex_; 61 }; 62 } 63 #endif // FFRT_RING_BUFFER_H 64