1 /*
2  * Copyright (C) 2021 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 #include "rust/topshim/btif/btif_shim.h"
18 
19 #include <algorithm>
20 #include <cstdlib>
21 #include <cstring>
22 #include <memory>
23 
24 #include "rust/cxx.h"
25 #include "src/btif.rs.h"
26 
27 namespace bluetooth {
28 namespace topshim {
29 namespace rust {
30 
InitFlags()31 InitFlags::InitFlags() {}
~InitFlags()32 InitFlags::~InitFlags() {
33   if (flags_) {
34     for (int i = 0; flags_[i] != nullptr; ++i) {
35       std::free(const_cast<void*>(static_cast<const void*>(flags_[i])));
36     }
37 
38     std::free(const_cast<void*>(static_cast<const void*>(flags_)));
39   }
40 }
41 
Convert(::rust::Vec<::rust::String> & initFlags)42 void InitFlags::Convert(::rust::Vec<::rust::String>& initFlags) {
43   // Allocate number of flags + 1 (last entry must be null to signify end)
44   // Must be calloc so our cleanup correctly frees everything
45   flags_ = static_cast<const char**>(std::calloc(initFlags.size() + 1, sizeof(char*)));
46   if (!flags_) return;
47 
48   for (size_t i = 0; i < initFlags.size(); ++i) {
49     flags_[i] = strndup(initFlags[i].data(), initFlags[i].size());
50     if (!flags_[i]) {
51       return;
52     }
53   }
54 }
55 
ConvertFlags(::rust::Vec<::rust::String> flags)56 std::unique_ptr<InitFlags> ConvertFlags(::rust::Vec<::rust::String> flags) {
57   auto ret = std::make_unique<InitFlags>();
58   ret->Convert(flags);
59 
60   return ret;
61 }
62 
63 }  // namespace rust
64 }  // namespace topshim
65 }  // namespace bluetooth
66