1 /*
2 * Copyright (c) 2022-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
16 #include "circle_stream_buffer.h"
17
18 namespace OHOS {
19 namespace Msdp {
CopyDataToBegin()20 void CircleStreamBuffer::CopyDataToBegin()
21 {
22 int32_t residualSize = ResidualSize();
23 if (residualSize > 0 && rPos_ > 0) {
24 int32_t pos = 0;
25 for (int32_t i = rPos_; i <= wPos_;) {
26 szBuff_[pos++] = szBuff_[i++];
27 }
28 }
29 FI_HILOGD("ResidualSize:%{public}d rPos:%{public}d wPos:%{public}d", residualSize, rPos_, wPos_);
30 rPos_ = 0;
31 wPos_ = residualSize;
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 availableSize = GetAvailableBufSize();
38 if (bufferSize > availableSize && rPos_ > 0) {
39 CopyDataToBegin();
40 availableSize = GetAvailableBufSize();
41 }
42 return (availableSize >= 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 FI_HILOGE("Out of buffer memory, availableSize:%{public}d, size:%{public}zu,"
49 "residualSize:%{public}d, rPos:%{public}d, wPos:%{public}d",
50 GetAvailableBufSize(), size, ResidualSize(), rPos_, wPos_);
51 return false;
52 }
53 return StreamBuffer::Write(buf, size);
54 }
55 } // namespace Msdp
56 } // namespace OHOS