<commit_before>﻿using BitSharp.Common;
using BitSharp.Common.ExtensionMethods;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BitSharp.Storage
{
    public class MemoryCache<TKey, TValue> : IDisposable
    {
        public event Action OnClear;
        
        private readonly string _name;
        protected readonly Func<TValue, long> sizeEstimator;

        // memory cache
        private readonly ReaderWriterLockSlim cacheLock;
        private readonly ConcurrentDictionary<CacheKey<TKey>, TValue> cache;
        private long _currentSize;
        private long cacheIndex;

        private CancellationTokenSource shutdownToken;

        private readonly Worker cacheWorker;
        private readonly ManualResetEventSlim cacheBlockEvent;

        public MemoryCache(string name, long maxSize, Func<TValue, long> sizeEstimator)
        {
            this._name = name;
            this.MaxSize = maxSize;

            this.cacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
            this.cache = new ConcurrentDictionary<CacheKey<TKey>, TValue>();
            this._currentSize = 0;

            this.sizeEstimator = sizeEstimator;

            this.cacheWorker = new Worker("MemoryCache.{0}.CacheWorker".Format2(name), CacheWorker, true, TimeSpan.FromMilliseconds(25), TimeSpan.FromSeconds(5));
            this.cacheBlockEvent = new ManualResetEventSlim(true);

            this.shutdownToken = new CancellationTokenSource();

            // start cache thread, responsible for monitoring memory usage of block and transaction caches
            this.cacheWorker.Start();
        }

        public string Name { get { return this._name; } }

        public long CurrentSize { get { return this._currentSize; } }

        public long MaxSize { get; set; }

        public void Dispose()
        {
            this.shutdownToken.Cancel();
            
            new IDisposable[]
            {
                this.cacheWorker,
                this.cacheBlockEvent,
                this.cacheLock,
                this.shutdownToken
            }.DisposeList();
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            this.cacheLock.EnterReadLock();
            try
            {
                TValue cachedValue;
                if (this.cache.TryGetValue((CacheKey<TKey>)key, out cachedValue))
                {
                    value = cachedValue;
                    return true;
                }
                else
                {
                    value = default(TValue);
                    return false;
                }
            }
            finally
            {
                this.cacheLock.ExitReadLock();
            }
        }

        // clear all state and reload
        public void Clear()
        {
            // clear memory cache<commit_msg>add ContainsKey to memory cache<commit_after>﻿using BitSharp.Common;
using BitSharp.Common.ExtensionMethods;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BitSharp.Storage
{
    public class MemoryCache<TKey, TValue> : IDisposable
    {
        public event Action OnClear;
        
        private readonly string _name;
        protected readonly Func<TValue, long> sizeEstimator;

        // memory cache
        private readonly ReaderWriterLockSlim cacheLock;
        private readonly ConcurrentDictionary<CacheKey<TKey>, TValue> cache;
        private long _currentSize;
        private long cacheIndex;

        private CancellationTokenSource shutdownToken;

        private readonly Worker cacheWorker;
        private readonly ManualResetEventSlim cacheBlockEvent;

        public MemoryCache(string name, long maxSize, Func<TValue, long> sizeEstimator)
        {
            this._name = name;
            this.MaxSize = maxSize;

            this.cacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
            this.cache = new ConcurrentDictionary<CacheKey<TKey>, TValue>();
            this._currentSize = 0;

            this.sizeEstimator = sizeEstimator;

            this.cacheWorker = new Worker("MemoryCache.{0}.CacheWorker".Format2(name), CacheWorker, true, TimeSpan.FromMilliseconds(25), TimeSpan.FromSeconds(5));
            this.cacheBlockEvent = new ManualResetEventSlim(true);

            this.shutdownToken = new CancellationTokenSource();

            // start cache thread, responsible for monitoring memory usage of block and transaction caches
            this.cacheWorker.Start();
        }

        public string Name { get { return this._name; } }

        public long CurrentSize { get { return this._currentSize; } }

        public long MaxSize { get; set; }

        public void Dispose()
        {
            this.shutdownToken.Cancel();
            
            new IDisposable[]
            {
                this.cacheWorker,
                this.cacheBlockEvent,
                this.cacheLock,
                this.shutdownToken
            }.DisposeList();
        }

        public bool ContainsKey(TKey key)
        {
            return this.cacheLock.DoRead(() =>
                this.cache.ContainsKey((CacheKey<TKey>)key));
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            this.cacheLock.EnterReadLock();
            try
            {
                TValue cachedValue;
                if (this.cache.TryGetValue((CacheKey<TKey>)key, out cachedValue))
                {
                    value = cachedValue;
                    return true;
                }
                else
                {
                    value = default(TValue);
                    return false;
                }
            }
            finally
            {
                this.cacheLock.ExitReadLock();
            }
        }

        // clear all state and reload
        public void Clear()
        {
            // clear memory cache
{'fraction_non_alphanumeric': 0.074791800128123, 'fraction_numerical': 0.0019218449711723255, 'mean_word_length': 1.792933810375671, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6320706', 'n_tokens_mistral': 1586, 'n_tokens_neox': 1503, 'n_words': 376}