scc  2022.4.0
SystemC components library
sparse_array.h
1 /*******************************************************************************
2  * Copyright 2017 MINRES Technologies GmbH
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 _SPARSE_ARRAY_H_
18 #define _SPARSE_ARRAY_H_
19 
20 #include <array>
21 #include <cassert>
22 
28 namespace util {
29 
36 template <typename T, uint64_t SIZE, unsigned PAGE_ADDR_BITS = 24> class sparse_array {
37 public:
38  static_assert(SIZE > 0, "sparse_array size must be greater than 0");
39 
40  const uint64_t page_addr_mask = (1 << PAGE_ADDR_BITS) - 1;
41 
42  const uint64_t page_size = (1 << PAGE_ADDR_BITS);
43 
44  const unsigned page_count = (SIZE + page_size - 1) / page_size;
45 
46  const uint64_t page_addr_width = PAGE_ADDR_BITS;
47 
48  using page_type = std::array<T, 1 << PAGE_ADDR_BITS>;
52  sparse_array() { arr.fill(nullptr); }
57  for(auto i : arr)
58  delete i;
59  }
66  T& operator[](uint32_t addr) {
67  assert(addr < SIZE);
68  T nr = addr >> PAGE_ADDR_BITS;
69  if(arr[nr] == nullptr)
70  arr[nr] = new page_type();
71  return arr[nr]->at(addr & page_addr_mask);
72  }
79  page_type& operator()(uint32_t page_nr) {
80  assert(page_nr < page_count);
81  if(arr[page_nr] == nullptr)
82  arr.at(page_nr) = new page_type();
83  return *(arr[page_nr]);
84  }
91  bool is_allocated(uint32_t addr) {
92  assert(addr < SIZE);
93  T nr = addr >> PAGE_ADDR_BITS;
94  return arr.at(nr) != nullptr;
95  }
101  uint64_t size() { return SIZE; }
102 
103 protected:
104  std::array<page_type*, SIZE / (1 << PAGE_ADDR_BITS) + 1> arr;
105 };
106 } // namespace util
108 #endif /* _SPARSE_ARRAY_H_ */
a sparse array suitable for large sizes
Definition: sparse_array.h:36
bool is_allocated(uint32_t addr)
Definition: sparse_array.h:91
page_type & operator()(uint32_t page_nr)
Definition: sparse_array.h:79
T & operator[](uint32_t addr)
Definition: sparse_array.h:66
SCC common utilities.
Definition: bit_field.h:30