#pragma once // Spec: SPEC.md 0.3 (every cache has a hard cap). Per-target view models (vote, poll, report) that SwiftUI keeps in // @State: views are rebuilt every frame here, so the model object must outlive the frame. Keyed by target id. #include #include #include #include #include #include "spec/PostsSpec.hpp" namespace dp { template class ModelCache { public: using Ptr = std::shared_ptr; // Returns the model for `key`, creating it with `make` when absent. At the cap the oldest entry is dropped // (callbacks of in-flight requests keep their model alive through their own shared_ptr). Ptr get(const std::string& key, const std::function& make) { auto it = items_.find(key); if (it != items_.end()) return it->second; while (items_.size() >= spec::PostsLimits::kModelCacheEntries && !order_.empty()) { items_.erase(order_.front()); order_.pop_front(); } Ptr model = make(); items_[key] = model; order_.push_back(key); return model; } void clear() { items_.clear(); order_.clear(); } std::size_t size() const { return items_.size(); } private: std::map items_; std::deque order_; }; } // namespace dp