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 #include "array_buffer_util.h"
16 #include "securec.h"
17 #include "intell_voice_log.h"
18
19 #define LOG_TAG "ArrayBufferUtil"
20
21 namespace OHOS {
22 namespace IntellVoiceUtils {
Init(uint32_t size,const T * data)23 template<class T> bool ArrayBufferUtil<T>::Init(uint32_t size, const T *data)
24 {
25 if (size == 0) {
26 INTELL_VOICE_LOG_ERROR("size is zero");
27 return false;
28 }
29
30 data_ = std::make_unique<T[]>(size);
31 if (data_ == nullptr) {
32 INTELL_VOICE_LOG_ERROR("allocate data failed");
33 return false;
34 }
35
36 if (data == nullptr) {
37 (void)memset_s(data_.get(), size * sizeof(T), 0, size * sizeof(T));
38 } else {
39 (void)memcpy_s(data_.get(), size * sizeof(T), data, size * sizeof(T));
40 }
41
42 size_ = size;
43 return true;
44 }
45
CreateArrayBuffer(uint32_t size,const T * data)46 template<class T> std::unique_ptr<ArrayBufferUtil<T>> CreateArrayBuffer(uint32_t size, const T *data)
47 {
48 auto ret = std::unique_ptr<ArrayBufferUtil<T>>(new (std::nothrow) ArrayBufferUtil<T>());
49 if (ret == nullptr) {
50 INTELL_VOICE_LOG_ERROR("allocate array buffer failed");
51 return nullptr;
52 }
53
54 if (!ret->Init(size, data)) {
55 INTELL_VOICE_LOG_ERROR("init array buffer failed");
56 return nullptr;
57 }
58
59 return ret;
60 }
61
62 template class ArrayBufferUtil<uint8_t>;
63 template std::unique_ptr<Uint8ArrayBuffer> CreateArrayBuffer(uint32_t size, const uint8_t *data = nullptr);
64 }
65 }