11#include <unordered_map>
70 static_assert(!std::is_same_v<T, std::any>,
71 "RequestContext::set<std::any>() is not supported: assigning an any into the slot's "
72 "own any merges them instead of nesting one inside the other");
74 slot.
value = std::move(value);
75 return *std::any_cast<T>(&slot.
value);
81 Slot* slot =
find(std::type_index(
typeid(T)));
82 return slot ? std::any_cast<T>(&slot->
value) :
nullptr;
85 const T*
get()
const {
86 const Slot* slot =
find(std::type_index(
typeid(T)));
87 return slot ? std::any_cast<T>(&slot->
value) :
nullptr;
93 return get<T>() !=
nullptr;
98 template <
typename T,
typename... Args>
100 if (T* existing = get<T>())
return *existing;
101 return set<T>(T(std::forward<Args>(args)...));
106 template <
typename T>
108 Slot* slot =
find(std::type_index(
typeid(T)));
109 if (!slot)
return false;
111 slot->
key = std::type_index(
typeid(
void));
119 void set_attr(std::string name, std::string value) {
attrs_[std::move(name)] = std::move(value); }
122 const std::string*
attr(std::string_view name)
const {
123 auto it =
attrs_.find(std::string(name));
124 return it ==
attrs_.end() ? nullptr : &it->second;
129 std::type_index
key{
typeid(void)};
138 if (slot.used && slot.key == key)
return &slot;
142 if (slot.used && slot.key == key)
return &slot;
153 if (
Slot* existing =
find(key))
return *existing;
181 std::unordered_map<std::string, std::string>
attrs_;
Type-indexed, per-request storage: middleware that computes something for later middleware or the han...
Definition RequestContext.hpp:65
std::unordered_map< std::string, std::string > attrs_
Definition RequestContext.hpp:181
void set_attr(std::string name, std::string value)
Sets a named string attribute (distinct storage from set<T>()).
Definition RequestContext.hpp:119
static constexpr size_t kInlineCapacity
Definition RequestContext.hpp:134
Slot * find(std::type_index key)
Definition RequestContext.hpp:136
std::optional< std::deque< Slot > > overflow_
Definition RequestContext.hpp:180
const Slot * find(std::type_index key) const
Definition RequestContext.hpp:147
T & ensure(Args &&... args)
Definition RequestContext.hpp:99
T & set(T value)
Sets (replacing any previous value) and returns a reference to it.
Definition RequestContext.hpp:69
std::array< Slot, kInlineCapacity > inline_
Definition RequestContext.hpp:179
Slot & slot_for(std::type_index key)
Definition RequestContext.hpp:152
const std::string * attr(std::string_view name) const
A named attribute, or null if it was never set.
Definition RequestContext.hpp:122
T * get()
The value for T, or null if none is set.
Definition RequestContext.hpp:80
bool has() const
True if a value for T is set.
Definition RequestContext.hpp:92
bool erase()
Definition RequestContext.hpp:107
const T * get() const
Definition RequestContext.hpp:85
Definition RequestContext.hpp:128
bool used
Definition RequestContext.hpp:131
std::type_index key
Definition RequestContext.hpp:129
std::any value
Definition RequestContext.hpp:130