scc 2026.07
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 "ities.h"
21#include <array>
22#include <cassert>
23
29namespace util {
30
37template <typename T, uint64_t SIZE, unsigned PAGE_ADDR_BITS = 24> class sparse_array {
38public:
39 static_assert(SIZE > 0, "sparse_array size must be greater than 0");
40
41 static constexpr uint64_t page_addr_mask = (1 << PAGE_ADDR_BITS) - 1;
42
43 static constexpr uint64_t page_size = (1 << PAGE_ADDR_BITS);
44
45 static constexpr unsigned page_count = (SIZE + page_size - 1) / page_size;
46
47 static constexpr uint64_t page_addr_width = PAGE_ADDR_BITS;
48
49 using page_type = std::array<T, 1 << PAGE_ADDR_BITS>;
53 sparse_array() { arr.fill(nullptr); }
58 for(auto i : arr)
59 delete i;
60 }
61
67 T& operator[](uint32_t addr) {
68 assert(addr < SIZE);
69 T nr = addr >> PAGE_ADDR_BITS;
70 if(arr[nr] == nullptr)
71 arr[nr] = new page_type();
72 return arr[nr]->at(addr & page_addr_mask);
73 }
74
80 page_type& operator()(uint32_t page_nr) {
81 assert(page_nr < page_count);
82 if(arr[page_nr] == nullptr)
83 arr.at(page_nr) = new page_type();
84 return *(arr[page_nr]);
85 }
86
92 bool is_allocated(uint32_t addr) {
93 assert(addr < SIZE);
94 T nr = addr >> PAGE_ADDR_BITS;
95 return arr.at(nr) != nullptr;
96 }
97
102 uint64_t size() { return SIZE; }
103
104protected:
105 std::array<page_type*, SIZE / (1 << PAGE_ADDR_BITS) + 1> arr;
106};
107} // namespace util
109#endif /* _SPARSE_ARRAY_H_ */
bool is_allocated(uint32_t addr)
page_type & operator()(uint32_t page_nr)
T & operator[](uint32_t addr)
SCC common utilities.
Definition bit_field.h:30