1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef CHRE_UTIL_FRAGMENTATION_MANAGER_IMPL
18 #define CHRE_UTIL_FRAGMENTATION_MANAGER_IMPL
19
20 // IWYU pragma: private
21 #include "chre/util/fragmentation_manager.h"
22 #include "chre/util/optional.h"
23
24 namespace chre {
25
26 template <typename ObjectType, size_t fragmentSize>
init(ObjectType * dataSource,size_t dataSize)27 bool FragmentationManager<ObjectType, fragmentSize>::init(
28 ObjectType *dataSource, size_t dataSize) {
29 if (dataSource == nullptr) {
30 return false;
31 }
32 mData = dataSource;
33 mDataSize = dataSize;
34 mEmittedFragment = 0;
35 return true;
36 }
37
38 template <typename ObjectType, size_t fragmentSize>
deinit()39 void FragmentationManager<ObjectType, fragmentSize>::deinit() {
40 mData = nullptr;
41 mDataSize = 0;
42 mEmittedFragment = 0;
43 }
44
45 template <typename ObjectType, size_t fragmentSize>
46 Optional<Fragment<ObjectType>>
getNextFragment()47 FragmentationManager<ObjectType, fragmentSize>::getNextFragment() {
48 if (hasNoMoreFragment()) {
49 return Optional<Fragment<ObjectType>>();
50 }
51 size_t currentFragmentSize = fragmentSize;
52 // Special case to calculate the size of the last fragment.
53 if ((mEmittedFragment + 1) * fragmentSize > mDataSize) {
54 currentFragmentSize = mDataSize % fragmentSize;
55 }
56 Fragment<ObjectType> fragment(mData + mEmittedFragment * fragmentSize,
57 currentFragmentSize);
58 ++mEmittedFragment;
59 return fragment;
60 }
61
62 } // namespace chre
63 #endif // CHRE_UTIL_FRAGMENTATION_MANAGER_IMPL
64