| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- #pragma once
- #include <map>
- #include <optional>
- #include <jvalidate/detail/expect.h>
- #include <jvalidate/detail/pointer.h>
- #include <jvalidate/detail/reference.h>
- #include <jvalidate/forward.h>
- #include <jvalidate/uri.h>
- namespace jvalidate {
- template <Adapter A> class DocumentCache {
- public:
- using value_type = typename A::value_type;
- private:
- URIResolver<A> resolve_;
- std::map<URI, A> references_;
- std::map<URI, value_type> cache_;
- public:
- DocumentCache() = default;
- DocumentCache(URIResolver<A> const & resolve) : resolve_(resolve) {}
- void cache_reference(URI const & where, A const & handle) {
- EXPECT(references_.emplace(where, handle).second);
- }
- operator bool() const { return resolve_; }
- std::optional<A> try_load(detail::Reference const & ref) {
- if (auto it = references_.find(ref.uri()); it != references_.end()) {
- return ref.pointer().walk(it->second);
- }
- if (not resolve_) {
- return std::nullopt;
- }
- auto [it, created] = cache_.try_emplace(ref.uri());
- if (created && not resolve_(ref.uri(), it->second)) {
- cache_.erase(it);
- return std::nullopt;
- }
- return ref.pointer().walk(A(it->second));
- }
- };
- }
|