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 
16 #include "circle_stream_buffer.h"
17 
18 #include "sensor_errors.h"
19 
20 namespace OHOS {
21 namespace Sensors {
CheckWrite(size_t size)22 bool CircleStreamBuffer::CheckWrite(size_t size)
23 {
24 #ifdef OHOS_BUILD_ENABLE_RUST
25     return StreamBufferCheckWrite(streamBufferPtr_.get(), size);
26 #else
27     size_t availSize = GetAvailableBufSize();
28     if (size > availSize && rPos_ > 0) {
29         CopyDataToBegin();
30         availSize = GetAvailableBufSize();
31     }
32     return (availSize >= size);
33 #endif // OHOS_BUILD_ENABLE_RUST
34 }
35 
Write(const char * buf,size_t size)36 bool CircleStreamBuffer::Write(const char *buf, size_t size)
37 {
38 #ifdef OHOS_BUILD_ENABLE_RUST
39     return CircleStreamBufferWrite(streamBufferPtr_.get(), buf, size);
40 #else
41     if (!CheckWrite(size)) {
42         SEN_HILOGE("Buffer is overflow, availableSize:%{public}zu, size:%{public}zu,"
43                    "unreadSize:%{public}zu, rPos:%{public}zu, wPos:%{public}zu",
44                    GetAvailableBufSize(), size, UnreadSize(), rPos_, wPos_);
45         return false;
46     }
47     return StreamBuffer::Write(buf, size);
48 #endif // OHOS_BUILD_ENABLE_RUST
49 }
50 
CopyDataToBegin()51 void CircleStreamBuffer::CopyDataToBegin()
52 {
53 #ifdef OHOS_BUILD_ENABLE_RUST
54     CircleStreamBufferCopyDataToBegin(streamBufferPtr_.get());
55 #else
56     size_t unreadSize = UnreadSize();
57     if (unreadSize > 0 && rPos_ > 0) {
58         size_t pos = 0;
59         for (size_t i = rPos_; i <= wPos_;) {
60             szBuff_[pos++] = szBuff_[i++];
61         }
62     }
63     SEN_HILOGD("UnreadSize:%{public}zu, rPos:%{public}zu, wPos:%{public}zu", unreadSize, rPos_, wPos_);
64     rPos_ = 0;
65     wPos_ = unreadSize;
66 #endif // OHOS_BUILD_ENABLE_RUST
67 }
68 } // namespace Sensors
69 } // namespace OHOS