diff options
| author | ivanmautin <[email protected]> | 2024-06-06 16:16:48 +0300 | 
|---|---|---|
| committer | ivanmautin <[email protected]> | 2024-06-06 16:32:57 +0300 | 
| commit | 7e1624f2fd672349e2f89baffeca12ef8272ec8d (patch) | |
| tree | 94ace8996703dad25ce4031005691c45b9f9ad8c /library/cpp/cache | |
| parent | 2123e799dc1993fb65554a96fbf38f94aa588978 (diff) | |
add GetOrNull method to threadsafe cache
2c3ce3e36d35b563fe21b581380310ac84007f57
Diffstat (limited to 'library/cpp/cache')
| -rw-r--r-- | library/cpp/cache/thread_safe_cache.h | 10 | ||||
| -rw-r--r-- | library/cpp/cache/ut/cache_ut.cpp | 21 | 
2 files changed, 31 insertions, 0 deletions
| diff --git a/library/cpp/cache/thread_safe_cache.h b/library/cpp/cache/thread_safe_cache.h index 08c899ad3dc..e77d1a45fd8 100644 --- a/library/cpp/cache/thread_safe_cache.h +++ b/library/cpp/cache/thread_safe_cache.h @@ -49,6 +49,16 @@ namespace NPrivate {              Cache.Update(key, value);          } +        const TPtr GetOrNull(TArgs... args) { +            Key key = Callbacks.GetKey(args...); +            TReadGuard r(Mutex); +            auto iter = Cache.Find(key); +            if (iter == Cache.End()) { +                return nullptr; +            } +            return iter.Value(); +        } +          const TPtr Get(TArgs... args) const {              return GetValue<true>(args...);          } diff --git a/library/cpp/cache/ut/cache_ut.cpp b/library/cpp/cache/ut/cache_ut.cpp index 8546bc166c9..16f29b29d1f 100644 --- a/library/cpp/cache/ut/cache_ut.cpp +++ b/library/cpp/cache/ut/cache_ut.cpp @@ -513,6 +513,27 @@ Y_UNIT_TEST_SUITE(TThreadSafeCacheTest) {          UNIT_ASSERT(callbacks.Creations == 0);          UNIT_ASSERT(*item == "hjk");      } + +    Y_UNIT_TEST(GetOrNullTest) { +        TCallbacks callbacks; +        TCache cache(callbacks, 10); +        i32 expectedCreations = 0; + +        auto item = cache.GetOrNull(0); +        UNIT_ASSERT(item == nullptr); +        UNIT_ASSERT(callbacks.Creations == expectedCreations); +        UNIT_ASSERT(cache.TotalSize() == 0); + +        item = cache.Get(0); +        UNIT_ASSERT(*item == "abcd"); +        UNIT_ASSERT(callbacks.Creations == ++expectedCreations); +        UNIT_ASSERT(cache.TotalSize() == 1); + +        item = cache.GetOrNull(0); +        UNIT_ASSERT(*item == "abcd"); +        UNIT_ASSERT(callbacks.Creations == expectedCreations); +        UNIT_ASSERT(cache.TotalSize() == 1); +    }  }  Y_UNIT_TEST_SUITE(TThreadSafeCacheUnsafeTest) { | 
