• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_bluetooth_proxy/internal/h4_storage.h"
16 
17 #include <mutex>
18 
19 #include "pw_assert/check.h"
20 
21 namespace pw::bluetooth::proxy {
22 
23 std::array<containers::Pair<uint8_t*, bool>, H4Storage::kNumH4Buffs>
InitOccupiedMap()24 H4Storage::InitOccupiedMap() {
25   std::lock_guard lock(storage_mutex_);
26   std::array<containers::Pair<uint8_t*, bool>, kNumH4Buffs> arr;
27   for (size_t i = 0; i < kNumH4Buffs; ++i) {
28     arr[i] = {h4_buffs_[i].data(), false};
29   }
30   return arr;
31 }
32 
H4Storage()33 H4Storage::H4Storage() : h4_buff_occupied_(InitOccupiedMap()) {}
34 
ReserveH4Buff()35 std::optional<pw::span<uint8_t>> H4Storage::ReserveH4Buff() {
36   std::lock_guard lock(storage_mutex_);
37   for (const auto& [buff, occupied] : h4_buff_occupied_) {
38     if (!occupied) {
39       h4_buff_occupied_.at(buff) = true;
40       pw::span<uint8_t> h4_buff = {buff, kH4BuffSize};
41       std::fill(h4_buff.begin(), h4_buff.end(), 0);
42       return h4_buff;
43     }
44   }
45   return std::nullopt;
46 }
47 
ReleaseH4Buff(const uint8_t * buffer)48 void H4Storage::ReleaseH4Buff(const uint8_t* buffer) {
49   std::lock_guard lock(storage_mutex_);
50   PW_CHECK(h4_buff_occupied_.contains(const_cast<uint8_t*>(buffer)),
51            "Received release callback for invalid buffer address.");
52 
53   h4_buff_occupied_.at(const_cast<uint8_t*>(buffer)) = false;
54 }
55 
56 }  // namespace pw::bluetooth::proxy
57