Blender V4.3
MEM_alloc_string_storage.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4#pragma once
5
13#include <any>
14#include <cassert>
15#include <string>
16#include <unordered_map>
17
18namespace intern::memutil {
19
25template<typename keyT, template<typename> typename hashT> class AllocStringStorage {
26 std::unordered_map<keyT, std::string, hashT<keyT>> storage_;
27
28 public:
34 bool contains(const keyT &key)
35 {
36 return storage_.count(key) != 0;
37 }
38
44 const char *find(const keyT &key)
45 {
46 if (storage_.count(key) != 0) {
47 return storage_[key].c_str();
48 }
49 return nullptr;
50 }
51
59 const char *insert(const keyT &key, std::string alloc_string)
60 {
61#ifndef NDEBUG
62 assert(storage_.count(key) == 0);
63#endif
64 return (storage_[key] = std::move(alloc_string)).c_str();
65 }
66};
67
68namespace internal {
69
74 std::unordered_map<std::string, std::any> storage_;
75
76 public:
83 template<typename keyT, template<typename> typename hashT>
84 std::any &ensure_storage(const std::string &storage_identifier)
85 {
86 if (storage_.count(storage_identifier) == 0) {
87 AllocStringStorage<keyT, hashT> storage_for_identifier;
88 return (storage_[storage_identifier] = std::make_any<AllocStringStorage<keyT, hashT>>(
89 std::move(storage_for_identifier)));
90 }
91 return storage_[storage_identifier];
92 }
93};
94
99AllocStringStorageContainer &ensure_storage_container();
100
101} // namespace internal
102
110template<typename keyT, template<typename> typename hashT>
111AllocStringStorage<keyT, hashT> &alloc_string_storage_get(const std::string &storage_identifier)
112{
114 std::any &storage = storage_container.ensure_storage<keyT, hashT>(storage_identifier);
115 return std::any_cast<AllocStringStorage<keyT, hashT> &>(storage);
116}
117
118} // namespace intern::memutil
const char * insert(const keyT &key, std::string alloc_string)
std::any & ensure_storage(const std::string &storage_identifier)
AllocStringStorageContainer & ensure_storage_container()
AllocStringStorage< keyT, hashT > & alloc_string_storage_get(const std::string &storage_identifier)