File size: 2,138 Bytes
bfd87b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

#pragma once

#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/Cache.h>
#include <aws/core/utils/threading/ReaderWriterLock.h>

namespace Aws
{
    namespace Utils
    {
        template <typename TKey, typename TValue>
        class ConcurrentCache
        {
        public:
            explicit ConcurrentCache(size_t size = 1000) : m_cache(size) { }

            bool Get(const TKey& key, TValue& value) const
            {
                Aws::Utils::Threading::ReaderLockGuard g(m_rwlock);
                return m_cache.Get(key, value);
            }

            template<typename UValue>
            void Put(const TKey& key, UValue&& val, std::chrono::milliseconds duration)
            {
                Aws::Utils::Threading::WriterLockGuard g(m_rwlock);
                m_cache.Put(key, std::forward<UValue>(val), duration);
            }

            template<typename UValue>
            void Put(TKey&& key, UValue&& val, std::chrono::milliseconds duration)
            {
                Aws::Utils::Threading::WriterLockGuard g(m_rwlock);
                m_cache.Put(std::move(key), std::forward<UValue>(val), duration);
            }

            using TransformFunction = std::function<typename Aws::Utils::Cache<TKey, TValue>::Value(const TKey &,
                const typename Aws::Utils::Cache<TKey, TValue>::Value &)>;

            void Transform(TransformFunction function) {
                Aws::Utils::Threading::WriterLockGuard g(m_rwlock);
                m_cache.Transform(function);
            }

            using FilterFunction = std::function<bool(const TKey &,
                const typename Aws::Utils::Cache<TKey, TValue>::Value &)>;

            void Filter(FilterFunction function) {
                Aws::Utils::Threading::WriterLockGuard g(m_rwlock);
                m_cache.Filter(function);
            }

        private:
            Aws::Utils::Cache<TKey, TValue> m_cache;
            mutable Aws::Utils::Threading::ReaderWriterLock m_rwlock;
        };
    }
}