Skip to content

Commit

Permalink
Stop using Vector::unsafeAppendWithoutCapacityCheck() in TinyLRUCache
Browse files Browse the repository at this point in the history
https://bugs.webkit.org/show_bug.cgi?id=264585

Reviewed by Ryosuke Niwa.

* Source/WTF/wtf/TinyLRUCache.h:
(WTF::TinyLRUCache::get):
(WTF::TinyLRUCache::cacheBuffer):

Canonical link: https://commits.webkit.org/270556@main
  • Loading branch information
cdumez committed Nov 10, 2023
1 parent 4b111b6 commit 9528598
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions Source/WTF/wtf/TinyLRUCache.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@

#pragma once

#include <algorithm>
#include <span>
#include <type_traits>
#include <wtf/NeverDestroyed.h>
#include <wtf/Vector.h>

namespace WTF {

Expand All @@ -49,29 +51,38 @@ class TinyLRUCache {
return valueForNull;
}

auto index = m_cache.reverseFindIf([&key](auto& entry) { return entry.first == key; });
if (index != notFound) {
// Move entry to the end of the cache if necessary.
if (index != m_cache.size() - 1) {
auto entry = WTFMove(m_cache[index]);
m_cache.remove(index);
m_cache.unsafeAppendWithoutCapacityCheck(WTFMove(entry));
auto* cacheBuffer = this->cacheBuffer();
for (size_t i = m_size; i-- > 0;) {
if (cacheBuffer[i].first == key) {
if (i < m_size - 1) {
// Move entry to the end of the cache if necessary.
auto entry = WTFMove(cacheBuffer[i]);
do {
cacheBuffer[i] = WTFMove(cacheBuffer[i + 1]);
} while (++i < m_size - 1);
cacheBuffer[m_size - 1] = WTFMove(entry);
}
return cacheBuffer[m_size - 1].second;
}
return m_cache[m_cache.size() - 1].second;
}

// m_cache[0] is the LRU entry, so remove it.
if (m_cache.size() == capacity)
m_cache.remove(0);
// cacheBuffer[0] is the LRU entry, so remove it.
if (m_size == capacity) {
for (size_t i = 0; i < m_size - 1; ++i)
cacheBuffer[i] = WTFMove(cacheBuffer[i + 1]);
} else
++m_size;

m_cache.unsafeAppendWithoutCapacityCheck(std::pair { Policy::createKeyForStorage(key), Policy::createValueForKey(key) });
return m_cache.last().second;
cacheBuffer[m_size - 1] = std::pair { Policy::createKeyForStorage(key), Policy::createValueForKey(key) };
return cacheBuffer[m_size - 1].second;
}

private:
using Entry = std::pair<KeyType, ValueType>;
using Cache = Vector<Entry, capacity>;
Cache m_cache;
Entry* cacheBuffer() { return reinterpret_cast_ptr<Entry*>(m_cacheBuffer); }

std::aligned_storage_t<sizeof(Entry), std::alignment_of_v<Entry>> m_cacheBuffer[capacity];
size_t m_size { 0 };
};

} // namespace WTF
Expand Down

0 comments on commit 9528598

Please sign in to comment.