1 /*
2  * Copyright (c) 2022 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 OHOS_UTILS_MEMORY_LIBPURGEABLEMEM_CPP_INCLUDE_PURGEABLE_MEM_BUILDER_H
17 #define OHOS_UTILS_MEMORY_LIBPURGEABLEMEM_CPP_INCLUDE_PURGEABLE_MEM_BUILDER_H
18 
19 #include <memory> /* unique_ptr */
20 #include <functional>
21 
22 namespace OHOS {
23 namespace PurgeableMem {
24 /*
25  * Class PurgeableMemBuilder is a base class of user's builder.
26  * PurgeableMem users can define their builders by inheriting this class.
27  * In its member func Build(), user should define how to build the content of a PurgeableMem obj.
28  */
29 class PurgeableMemBuilder {
30 public:
31     virtual ~PurgeableMemBuilder();
32 
33     /*
34      * User should define how to build the content of a PurgeableMem obj in this func.
35      * Input:   data: data ptr, ponits to start address of a PurgeableMem obj's content.
36      * Input:   size: data size of the content.
37      * Return:  build content result, true means success, while false is fail.
38      */
39     virtual bool Build(void *data, size_t size) = 0;
40 
SetRebuildSuccessCallback(std::function<void ()> & callback)41     void SetRebuildSuccessCallback(std::function<void()> &callback)
42     {
43         rebuildSuccessCallback_ = callback;
44     }
45 
DoRebuildSuccessCallback()46     void DoRebuildSuccessCallback()
47     {
48         if (rebuildSuccessCallback_) {
49             rebuildSuccessCallback_();
50         }
51     }
52 
53 private:
54     std::function<void()> rebuildSuccessCallback_ = nullptr;
55     std::unique_ptr<PurgeableMemBuilder> nextBuilder_ = nullptr;
56 
57     /* Only called by its friend */
58     void AppendBuilder(std::unique_ptr<PurgeableMemBuilder> builder);
59     bool BuildAll(void *data, size_t size);
60     friend class PurgeableMemBase;
61 };
62 } /* namespace PurgeableMem */
63 } /* namespace OHOS */
64 #endif /* OHOS_UTILS_MEMORY_LIBPURGEABLEMEM_CPP_INCLUDE_PURGEABLE_MEM_BUILDER_H */
65