Grok 12.0.1
SparseCache.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2016-2024 Grok Image Compression Inc.
3 *
4 * This source code is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License, version 3,
6 * as published by the Free Software Foundation.
7 *
8 * This source code is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Affero General Public License for more details.
12 *
13 * You should have received a copy of the GNU Affero General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16#pragma once
17#include "grk_includes.h"
18
19#include <map>
20
21namespace grk
22{
23template<typename T>
25{
26 public:
30 virtual ~SparseCache(void)
31 {
32 for(auto& ch : chunks)
33 {
34 for(size_t i = 0; i < chunkSize_; ++i)
35 delete ch.second[i];
36 delete[] ch.second;
37 }
38 }
39
40 T* tryGet(uint64_t index)
41 {
44 if(currChunk_ == nullptr || (chunkIndex != currChunkIndex_))
45 {
46 auto iter = chunks.find(chunkIndex);
47 if(iter != chunks.end())
48 currChunk_ = iter->second;
49 else
50 return nullptr;
51 }
52 return currChunk_[itemIndex];
53 }
54
55 T* get(uint64_t index)
56 {
59 if(currChunk_ == nullptr || (chunkIndex != currChunkIndex_))
60 {
62 auto iter = chunks.find(chunkIndex);
63 if(iter != chunks.end())
64 {
65 currChunk_ = iter->second;
66 }
67 else
68 {
69 currChunk_ = new T*[chunkSize_];
70 memset(currChunk_, 0, chunkSize_ * sizeof(T*));
72 }
73 }
75 if(!item)
76 {
77 item = create(index);
79 }
80 return item;
81 }
82
83 protected:
84 virtual T* create(uint64_t index) = 0;
85
86 private:
87 std::map<uint64_t, T**> chunks;
91};
92
93} // namespace grk
Definition SparseCache.h:25
T * tryGet(uint64_t index)
Definition SparseCache.h:40
virtual T * create(uint64_t index)=0
T * get(uint64_t index)
Definition SparseCache.h:55
T ** currChunk_
Definition SparseCache.h:89
std::map< uint64_t, T ** > chunks
Definition SparseCache.h:87
uint64_t currChunkIndex_
Definition SparseCache.h:90
SparseCache(uint64_t maxChunkSize)
Definition SparseCache.h:27
virtual ~SparseCache(void)
Definition SparseCache.h:30
uint64_t chunkSize_
Definition SparseCache.h:88
Copyright (C) 2016-2024 Grok Image Compression Inc.
Definition ICacheable.h:20
void grk_read(const uint8_t *buffer, TYPE *value, uint32_t numBytes)
Definition BufferedStream.h:239