document_cache.h 793 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #pragma once
  2. #include <map>
  3. #include <optional>
  4. #include <jvalidate/detail/expect.h>
  5. #include <jvalidate/forward.h>
  6. #include <jvalidate/uri.h>
  7. namespace jvalidate {
  8. template <Adapter A> class DocumentCache {
  9. public:
  10. using value_type = typename A::value_type;
  11. private:
  12. URIResolver<A> resolve_;
  13. std::map<URI, value_type> cache_;
  14. public:
  15. DocumentCache() = default;
  16. DocumentCache(URIResolver<A> const & resolve) : resolve_(resolve) {}
  17. operator bool() const { return resolve_; }
  18. std::optional<A> try_load(URI const & uri) {
  19. if (not resolve_) {
  20. return std::nullopt;
  21. }
  22. auto [it, created] = cache_.try_emplace(uri);
  23. if (created && not resolve_(uri, it->second)) {
  24. cache_.erase(it);
  25. return std::nullopt;
  26. }
  27. return A(it->second);
  28. }
  29. };
  30. }