| 33 | } |
| 34 | |
| 35 | WeakFileAccessor FileAccessorCache::Open(const std::string& filePath) |
| 36 | { |
| 37 | const auto id = GetCacheAccessorID(filePath); |
| 38 | std::unique_lock lock(m_mutex); |
| 39 | |
| 40 | // Check if the file is already in the cache. |
| 41 | if (const auto it = m_accessors.find(id); it != m_accessors.end()) |
| 42 | { |
| 43 | // Move the accessed ID to the back so we keep it in the cache. |
| 44 | auto pos = std::find(m_cache.begin(), m_cache.end(), id); |
| 45 | if (pos != m_cache.end()) |
| 46 | m_cache.erase(pos); |
| 47 | m_cache.push_back(id); |
| 48 | |
| 49 | return WeakFileAccessor(it->second, filePath); |
| 50 | } |
| 51 | |
| 52 | // Evict if we are going to go above the limit. |
| 53 | while (m_cache.size() >= m_cacheSize) |
| 54 | EvictLastUsed(); |
| 55 | |
| 56 | // Create a new file accessor and add it to the cache. |
| 57 | auto accessor = MappedFileAccessor::Open(filePath); |
| 58 | if (accessor == nullptr) |
| 59 | { |
| 60 | // We failed to open the file, we must throw hard! |
| 61 | // TODO: Make this mechanism more thought out... |
| 62 | throw std::runtime_error("Failed to open file: " + filePath); |
| 63 | } |
| 64 | auto sharedAccessor = std::make_shared<MappedFileAccessor>(std::move(*accessor)); |
| 65 | m_accessors.insert_or_assign(id, sharedAccessor); |
| 66 | m_cache.push_back(id); |
| 67 | |
| 68 | return WeakFileAccessor(sharedAccessor, filePath); |
| 69 | } |
| 70 | |
| 71 | void FileAccessorCache::RemoveAccessor(const CacheAccessorID id) |
| 72 | { |
no test coverage detected