1 /*
2 * Copyright (c) 2024 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 #ifndef API_BASE_CONTAINERS_ALLOCATOR_H
17 #define API_BASE_CONTAINERS_ALLOCATOR_H
18
19 #include <cstdint>
20 #include <cstdlib> // malloc, free
21 #include <securec.h>
22
23 #include <base/namespace.h>
24 #include <base/util/log.h>
25
26 BASE_BEGIN_NAMESPACE()
27 struct allocator {
28 using size_type = size_t;
29 void* instance { nullptr };
30 void* (*alloc)(void* instance, size_type size) { nullptr };
31 void (*free)(void* instance, void* ptr) { nullptr };
32 };
33
CloneData(void * const dst,const size_t dstSize,const void * const src,const size_t srcSize)34 inline bool CloneData(void* const dst, const size_t dstSize, const void* const src, const size_t srcSize)
35 {
36 if (dst && src && srcSize <= dstSize) {
37 // Note: arguments for memcpy have been verified.
38 auto status = memcpy_s(dst, dstSize, src, srcSize);
39 if (status != 0) {
40 return false;
41 }
42 } else {
43 BASE_LOG_E("CloneData invalid arguments.");
44 }
45 return (dst && src && srcSize <= dstSize);
46 }
47
MoveData(void * const dst,const size_t dstSize,const void * const src,const size_t srcSize)48 inline bool MoveData(void* const dst, const size_t dstSize, const void* const src, const size_t srcSize)
49 {
50 if (dst && src && srcSize <= dstSize) {
51 // Note: arguments for memmove have been verified.
52 auto status = memmove_s(dst, dstSize, src, srcSize);
53 if (status != 0) {
54 return false;
55 }
56 } else {
57 BASE_LOG_E("MoveData invalid arguments.");
58 }
59 return (dst && src && srcSize <= dstSize);
60 }
61
ClearToValue(void * dst,size_t dstSize,uint8_t val,size_t count)62 inline bool ClearToValue(void* dst, size_t dstSize, uint8_t val, size_t count)
63 {
64 if (dst == nullptr) {
65 BASE_LOG_E("ClearToValue invalid arguments");
66 return false;
67 } else if (count > dstSize) {
68 count = dstSize;
69 }
70 // Note: arguments for memset have been verified.
71 auto status = memset_s(dst, dstSize, val, count);
72 if (status != 0) {
73 return false;
74 }
75 return true;
76 }
77
default_allocator()78 inline allocator& default_allocator()
79 {
80 static allocator DefaultAllocInstance { nullptr,
81 [](void* instance, allocator::size_type size) -> void* { return ::malloc(size); },
82 [](void* instance, void* aPtr) { ::free(aPtr); } };
83 return DefaultAllocInstance;
84 }
85 BASE_END_NAMESPACE()
86
87 #endif // API_BASE_CONTAINERS_ALLOCATOR_H
88