From 65db1f85f48312b68ecd3717bbba38ad4cdc95a6 Mon Sep 17 00:00:00 2001 From: Uwe Seimet Date: Mon, 13 Jan 2025 23:53:54 +0100 Subject: [PATCH] Refactoring --- cpp/devices/disk_cache.cpp | 50 ++++++++++++++------------------------ 1 file changed, 18 insertions(+), 32 deletions(-) diff --git a/cpp/devices/disk_cache.cpp b/cpp/devices/disk_cache.cpp index a8c4f195..788cc0ca 100644 --- a/cpp/devices/disk_cache.cpp +++ b/cpp/devices/disk_cache.cpp @@ -95,32 +95,20 @@ shared_ptr DiskCache::Assign(int track) } } - // Next, check for empty - for (size_t i = 0; i < cache.size(); ++i) { - if (!cache[i].disktrk) { - // Try loading - if (Load(static_cast(i), track, nullptr)) { - // Success loading - cache[i].serial = serial; - return cache[i].disktrk; - } - - // Load failed - return nullptr; + // Check for an empty cache slot + for (CacheData &c : cache) { + if (!c.disktrk && Load(&c - &cache[0], track, nullptr)) { + c.serial = serial; + return c.disktrk; } } - // Finally, find the youngest serial number and delete it - - // Set index 0 as candidate c + // Find the cache entry with the smallest serial number, i.e. the oldest entry uint32_t s = cache[0].serial; size_t c = 0; - - // Compare candidate with serial and update to smaller one - for (size_t i = 0; i < cache.size(); ++i) { + for (size_t i = 1; i < cache.size(); ++i) { assert(cache[i].disktrk); - // Compare and update the existing serial if (cache[i].serial < s) { s = cache[i].serial; c = i; @@ -128,21 +116,19 @@ shared_ptr DiskCache::Assign(int track) } // Save this track - if (!cache[c].disktrk->Save(sec_path, cache_miss_write_count)) { - return nullptr; - } - - // Delete this track - shared_ptr disktrk = cache[c].disktrk; - cache[c].disktrk.reset(); - - if (Load(static_cast(c), track, disktrk)) { - // Successful loading - cache[c].serial = serial; - return cache[c].disktrk; + if (cache[c].disktrk->Save(sec_path, cache_miss_write_count)) { + // Delete this track + shared_ptr disktrk = cache[c].disktrk; + cache[c].disktrk.reset(); + + if (Load(static_cast(c), track, disktrk)) { + // Successful loading + cache[c].serial = serial; + return cache[c].disktrk; + } } - // Load failed + // Save or load failed return nullptr; }