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