1 /*
2  * Copyright (C) 2021 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 "obex_body.h"
17 #include <cstring>
18 #include <memory>
19 #include "log.h"
20 #include "obex_types.h"
21 
22 namespace OHOS {
23 namespace bluetooth {
ObexArrayBodyObject(const uint8_t * buf,size_t bufLen)24 ObexArrayBodyObject::ObexArrayBodyObject(const uint8_t *buf, size_t bufLen)
25 {
26     auto ret = PrivateWrite(buf, bufLen);
27     if (ret == 0) {
28         OBEX_LOG_ERROR("%{public}s, ret=%zu", __PRETTY_FUNCTION__, ret);
29     }
30 }
31 
Read(uint8_t * buf,size_t bufLen)32 size_t ObexArrayBodyObject::Read(uint8_t *buf, size_t bufLen)
33 {
34     std::lock_guard<std::mutex> lock(mutex_);
35     size_t readSize = bufLen;
36     size_t remainSize = body_.size() - index_;
37     if (remainSize < readSize) {
38         readSize = remainSize;
39     }
40     for (size_t i = 0; i < readSize; i++) {
41         buf[i] = body_[index_++];
42     }
43     OBEX_LOG_DEBUG("ObexArrayBodyObject::Read: %zu / %zu", index_, body_.size());
44     return readSize;
45 }
46 
Write(const uint8_t * buf,size_t bufLen)47 size_t ObexArrayBodyObject::Write(const uint8_t *buf, size_t bufLen)
48 {
49     return PrivateWrite(buf, bufLen);
50 }
51 
PrivateWrite(const uint8_t * buf,size_t bufLen)52 size_t ObexArrayBodyObject::PrivateWrite(const uint8_t *buf, size_t bufLen)
53 {
54     std::lock_guard<std::mutex> lock(mutex_);
55     body_.insert(body_.end(), buf, buf + bufLen);
56     return bufLen;
57 }
58 
Close()59 int ObexArrayBodyObject::Close()
60 {
61     std::lock_guard<std::mutex> lock(mutex_);
62     return 0;
63 }
64 }  // namespace bluetooth
65 }  // namespace OHOS