Grok 10.0.5
SparseCache.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2016-2023 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:
31 virtual ~SparseCache(void)
32 {
33 for(auto& ch : chunks)
34 {
35 for(size_t i = 0; i < chunkSize_; ++i)
36 delete ch.second[i];
37 delete[] ch.second;
38 }
39 }
40
41 T* tryGet(uint64_t index)
42 {
45 if(currChunk_ == nullptr || (chunkIndex != currChunkIndex_))
46 {
47 auto iter = chunks.find(chunkIndex);
48 if(iter != chunks.end())
49 currChunk_ = iter->second;
50 else
51 return nullptr;
52 }
53 return currChunk_[itemIndex];
54 }
55
56 T* get(uint64_t index)
57 {
60 if(currChunk_ == nullptr || (chunkIndex != currChunkIndex_))
61 {
63 auto iter = chunks.find(chunkIndex);
64 if(iter != chunks.end())
65 {
66 currChunk_ = iter->second;
67 }
68 else
69 {
70 currChunk_ = new T*[chunkSize_];
71 memset(currChunk_, 0, chunkSize_ * sizeof(T*));
73 }
74 }
76 if(!item)
77 {
78 item = create(index);
80 }
81 return item;
82 }
83
84 protected:
85 virtual T* create(uint64_t index) = 0;
86
87 private:
88 std::map<uint64_t, T**> chunks;
92};
93
94} // namespace grk
Definition SparseCache.h:25
T * tryGet(uint64_t index)
Definition SparseCache.h:41
virtual T * create(uint64_t index)=0
T * get(uint64_t index)
Definition SparseCache.h:56
T ** currChunk_
Definition SparseCache.h:90
std::map< uint64_t, T ** > chunks
Definition SparseCache.h:88
uint64_t currChunkIndex_
Definition SparseCache.h:91
SparseCache(uint64_t maxChunkSize)
Definition SparseCache.h:27
virtual ~SparseCache(void)
Definition SparseCache.h:31
uint64_t chunkSize_
Definition SparseCache.h:89
Copyright (C) 2016-2023 Grok Image Compression Inc.
Definition ICacheable.h:20
void grk_read(const uint8_t *buffer, TYPE *value, uint32_t numBytes)
Definition BufferedStream.h:239