1 /*
2  * Copyright (c) 2022 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 
16 #include "circle_stream_buffer.h"
17 
18 namespace OHOS {
19 namespace MMI {
CopyDataToBegin()20 void CircleStreamBuffer::CopyDataToBegin()
21 {
22     int32_t unreadSize = UnreadSize();
23     if (unreadSize > 0 && rPos_ > 0) {
24         int32_t pos = 0;
25         for (int32_t i = rPos_; i <= wPos_;) {
26             szBuff_[pos++] = szBuff_[i++];
27         }
28     }
29     MMI_HILOGD("unreadSize:%{public}d rPos:%{public}d wPos:%{public}d", unreadSize, rPos_, wPos_);
30     rPos_ = 0;
31     wPos_ = unreadSize;
32 }
33 
CheckWrite(size_t size)34 bool CircleStreamBuffer::CheckWrite(size_t size)
35 {
36     int32_t bufferSize = static_cast<int32_t>(size);
37     int32_t availSize = GetAvailableBufSize();
38     if (bufferSize > availSize && rPos_ > 0) {
39         CopyDataToBegin();
40         availSize = GetAvailableBufSize();
41     }
42     return (availSize >= bufferSize);
43 }
44 
Write(const char * buf,size_t size)45 bool CircleStreamBuffer::Write(const char *buf, size_t size)
46 {
47     if (!CheckWrite(size)) {
48         MMI_HILOGE("Out of buffer memory, availableSize:%{public}d, size:%{public}zu,"
49             "unreadSize:%{public}d, rPos:%{public}d, wPos:%{public}d",
50             GetAvailableBufSize(), size, UnreadSize(), rPos_, wPos_);
51         return false;
52     }
53     return StreamBuffer::Write(buf, size);
54 }
55 } // namespace MMI
56 } // namespace OHOS