diff --git a/src/Enyim.Caching/Configuration/AuthenticationConfiguration.cs b/src/Enyim.Caching/Configuration/AuthenticationConfiguration.cs index f504048e..d44cd3e9 100644 --- a/src/Enyim.Caching/Configuration/AuthenticationConfiguration.cs +++ b/src/Enyim.Caching/Configuration/AuthenticationConfiguration.cs @@ -6,22 +6,22 @@ namespace Enyim.Caching.Configuration { public class AuthenticationConfiguration : IAuthenticationConfiguration { - private Type authenticator; - private Dictionary parameters; + private Type _authenticator; + private Dictionary _parameters; Type IAuthenticationConfiguration.Type { - get { return this.authenticator; } + get { return _authenticator; } set { ConfigurationHelper.CheckForInterface(value, typeof(ISaslAuthenticationProvider)); - this.authenticator = value; + _authenticator = value; } } Dictionary IAuthenticationConfiguration.Parameters { - get { return this.parameters ?? (this.parameters = new Dictionary()); } + get { return _parameters ?? (_parameters = new Dictionary()); } } } } diff --git a/src/Enyim.Caching/Configuration/JsonVBucketConfig.cs b/src/Enyim.Caching/Configuration/JsonVBucketConfig.cs index 610b30a2..201eab55 100644 --- a/src/Enyim.Caching/Configuration/JsonVBucketConfig.cs +++ b/src/Enyim.Caching/Configuration/JsonVBucketConfig.cs @@ -14,9 +14,9 @@ // /// // public class JsonVBucketConfig : IVBucketConfiguration // { -// private Func factory; -// private IPEndPoint[] servers; -// private VBucket[] buckets; +// private Func _factory; +// private IPEndPoint[] _servers; +// private VBucket[] _buckets; // public JsonVBucketConfig(string json) // { @@ -25,11 +25,11 @@ // if (config.numReplicas < 0) // throw new ArgumentException("Invalid numReplicas: " + config.numReplicas, "json"); -// if (hashFactory.TryGetValue(config.hashAlgorithm, out this.factory)) +// if (hashFactory.TryGetValue(config.hashAlgorithm, out _factory)) // throw new ArgumentException("Unknown hash algorithm: " + config.hashAlgorithm, "json"); -// this.servers = config.serverList.Select(endpoint => ConfigurationHelper.ResolveToEndPoint(endpoint)).ToArray(); -// this.buckets = config.vBucketMap.Select((bucket, index) => +// _servers = config.serverList.Select(endpoint => ConfigurationHelper.ResolveToEndPoint(endpoint)).ToArray(); +// _buckets = config.vBucketMap.Select((bucket, index) => // { // if (bucket == null || bucket.Length != config.numReplicas + 1) // throw new ArgumentException("Invalid bucket definition at index " + index, "json"); @@ -58,12 +58,12 @@ // IList IVBucketConfiguration.Servers // { -// get { return this.servers; } +// get { return _servers; } // } // IList IVBucketConfiguration.Buckets // { -// get { return this.buckets; } +// get { return _buckets; } // } // #endregion diff --git a/src/Enyim.Caching/Configuration/MemcachedClientConfiguration.cs b/src/Enyim.Caching/Configuration/MemcachedClientConfiguration.cs index 74e4c8ba..192045ac 100755 --- a/src/Enyim.Caching/Configuration/MemcachedClientConfiguration.cs +++ b/src/Enyim.Caching/Configuration/MemcachedClientConfiguration.cs @@ -18,7 +18,7 @@ namespace Enyim.Caching.Configuration public class MemcachedClientConfiguration : IMemcachedClientConfiguration { // these are lazy initialized in the getters - private Type nodeLocator; + private Type _nodeLocator; private ITranscoder _transcoder; private IMemcachedKeyTransformer _keyTransformer; private ILogger _logger; @@ -137,7 +137,7 @@ public MemcachedClientConfiguration( } else if (keyTransformer != null) { - this._keyTransformer = keyTransformer; + _keyTransformer = keyTransformer; _logger.LogDebug($"Use KeyTransformer Type : '{keyTransformer.ToString()}'"); } @@ -167,7 +167,7 @@ public MemcachedClientConfiguration( } else if (transcoder != null) { - this._transcoder = transcoder; + _transcoder = transcoder; _logger.LogDebug($"Use Transcoder Type : '{transcoder.ToString()}'"); } @@ -218,7 +218,7 @@ private void ConfigureServers(MemcachedClientOptions options) /// The address and the port of the server in the format 'host:port'. public void AddServer(string address) { - this.Servers.Add(ConfigurationHelper.ResolveToEndPoint(address)); + Servers.Add(ConfigurationHelper.ResolveToEndPoint(address)); } /// @@ -228,7 +228,7 @@ public void AddServer(string address) /// The port number of the memcached instance. public void AddServer(string host, int port) { - this.Servers.Add(new DnsEndPoint(host, port)); + Servers.Add(new DnsEndPoint(host, port)); } /// @@ -251,8 +251,8 @@ public void AddServer(string host, int port) /// public IMemcachedKeyTransformer KeyTransformer { - get { return this._keyTransformer ?? (this._keyTransformer = new DefaultKeyTransformer()); } - set { this._keyTransformer = value; } + get { return _keyTransformer ?? (_keyTransformer = new DefaultKeyTransformer()); } + set { _keyTransformer = value; } } /// @@ -261,11 +261,11 @@ public IMemcachedKeyTransformer KeyTransformer /// If both and are assigned then the latter takes precedence. public Type NodeLocator { - get { return this.nodeLocator; } + get { return _nodeLocator; } set { ConfigurationHelper.CheckForInterface(value, typeof(IMemcachedNodeLocator)); - this.nodeLocator = value; + _nodeLocator = value; } } @@ -293,48 +293,48 @@ public ITranscoder Transcoder IList IMemcachedClientConfiguration.Servers { - get { return this.Servers; } + get { return Servers; } } ISocketPoolConfiguration IMemcachedClientConfiguration.SocketPool { - get { return this.SocketPool; } + get { return SocketPool; } } IAuthenticationConfiguration IMemcachedClientConfiguration.Authentication { - get { return this.Authentication; } + get { return Authentication; } } IMemcachedKeyTransformer IMemcachedClientConfiguration.CreateKeyTransformer() { - return this.KeyTransformer; + return KeyTransformer; } IMemcachedNodeLocator IMemcachedClientConfiguration.CreateNodeLocator() { - var f = this.NodeLocatorFactory; + var f = NodeLocatorFactory; if (f != null) return f.Create(); - return this.NodeLocator == null + return NodeLocator == null ? new SingleNodeLocator() - : (IMemcachedNodeLocator)FastActivator.Create(this.NodeLocator); + : (IMemcachedNodeLocator)FastActivator.Create(NodeLocator); } ITranscoder IMemcachedClientConfiguration.CreateTranscoder() { - return this.Transcoder; + return Transcoder; } IServerPool IMemcachedClientConfiguration.CreatePool() { - switch (this.Protocol) + switch (Protocol) { case MemcachedProtocol.Text: return new DefaultServerPool(this, new Memcached.Protocol.Text.TextOperationFactory(), _logger); case MemcachedProtocol.Binary: return new BinaryPool(this, _logger); } - throw new ArgumentOutOfRangeException("Unknown protocol: " + (int)this.Protocol); + throw new ArgumentOutOfRangeException("Unknown protocol: " + (int)Protocol); } public bool UseSslStream { get; private set; } diff --git a/src/Enyim.Caching/Configuration/SocketPoolConfiguration.cs b/src/Enyim.Caching/Configuration/SocketPoolConfiguration.cs index 05f5c6cc..f85476cb 100644 --- a/src/Enyim.Caching/Configuration/SocketPoolConfiguration.cs +++ b/src/Enyim.Caching/Configuration/SocketPoolConfiguration.cs @@ -8,20 +8,20 @@ namespace Enyim.Caching.Configuration { public class SocketPoolConfiguration : ISocketPoolConfiguration { - private int minPoolSize = 5; - private int maxPoolSize = 100; - private bool useSslStream = false; - private TimeSpan connectionTimeout = new TimeSpan(0, 0, 10); - private TimeSpan receiveTimeout = new TimeSpan(0, 0, 10); - private TimeSpan deadTimeout = new TimeSpan(0, 0, 10); - private TimeSpan queueTimeout = new TimeSpan(0, 0, 0, 0, 100); + private int _minPoolSize = 5; + private int _maxPoolSize = 100; + private bool _useSslStream = false; + private TimeSpan _connectionTimeout = new TimeSpan(0, 0, 10); + private TimeSpan _receiveTimeout = new TimeSpan(0, 0, 10); + private TimeSpan _deadTimeout = new TimeSpan(0, 0, 10); + private TimeSpan _queueTimeout = new TimeSpan(0, 0, 0, 0, 100); private TimeSpan _initPoolTimeout = new TimeSpan(0, 1, 0); - private INodeFailurePolicyFactory FailurePolicyFactory = new ThrottlingFailurePolicyFactory(5, TimeSpan.FromMilliseconds(2000)); + private INodeFailurePolicyFactory _failurePolicyFactory = new ThrottlingFailurePolicyFactory(5, TimeSpan.FromMilliseconds(2000)); int ISocketPoolConfiguration.MinPoolSize { - get { return this.minPoolSize; } - set { this.minPoolSize = value; } + get { return _minPoolSize; } + set { _minPoolSize = value; } } /// @@ -31,43 +31,43 @@ int ISocketPoolConfiguration.MinPoolSize /// It should be 0.75 * (number of threads) for optimal performance. int ISocketPoolConfiguration.MaxPoolSize { - get { return this.maxPoolSize; } - set { this.maxPoolSize = value; } + get { return _maxPoolSize; } + set { _maxPoolSize = value; } } TimeSpan ISocketPoolConfiguration.ConnectionTimeout { - get { return this.connectionTimeout; } + get { return _connectionTimeout; } set { if (value < TimeSpan.Zero) throw new ArgumentOutOfRangeException("value", "value must be positive"); - this.connectionTimeout = value; + _connectionTimeout = value; } } TimeSpan ISocketPoolConfiguration.ReceiveTimeout { - get { return this.receiveTimeout; } + get { return _receiveTimeout; } set { if (value < TimeSpan.Zero) throw new ArgumentOutOfRangeException("value", "value must be positive"); - this.receiveTimeout = value; + _receiveTimeout = value; } } TimeSpan ISocketPoolConfiguration.QueueTimeout { - get { return this.queueTimeout; } + get { return _queueTimeout; } set { if (value < TimeSpan.Zero) throw new ArgumentOutOfRangeException("value", "value must be positive"); - this.queueTimeout = value; + _queueTimeout = value; } } @@ -85,25 +85,25 @@ TimeSpan ISocketPoolConfiguration.InitPoolTimeout TimeSpan ISocketPoolConfiguration.DeadTimeout { - get { return this.deadTimeout; } + get { return _deadTimeout; } set { if (value < TimeSpan.Zero) throw new ArgumentOutOfRangeException("value", "value must be positive"); - this.deadTimeout = value; + _deadTimeout = value; } } INodeFailurePolicyFactory ISocketPoolConfiguration.FailurePolicyFactory { - get { return this.FailurePolicyFactory; } + get { return _failurePolicyFactory; } set { if (value == null) throw new ArgumentNullException("value"); - this.FailurePolicyFactory = value; + _failurePolicyFactory = value; } } } diff --git a/src/Enyim.Caching/CountdownEvent.cs b/src/Enyim.Caching/CountdownEvent.cs index 1b4fa79d..be5fc110 100644 --- a/src/Enyim.Caching/CountdownEvent.cs +++ b/src/Enyim.Caching/CountdownEvent.cs @@ -9,57 +9,57 @@ namespace Enyim.Caching { - public class CountdownEvent : IDisposable - { - private int count; - private ManualResetEvent mre; + public class CountdownEvent : IDisposable + { + private int _count; + private ManualResetEvent _mre; - public CountdownEvent(int count) - { - this.count = count; - this.mre = new ManualResetEvent(false); - } + public CountdownEvent(int count) + { + _count = count; + _mre = new ManualResetEvent(false); + } - public void Signal() - { - if (this.count == 0) throw new InvalidOperationException("Counter underflow"); + public void Signal() + { + if (_count == 0) throw new InvalidOperationException("Counter underflow"); - int tmp = Interlocked.Decrement(ref this.count); + int tmp = Interlocked.Decrement(ref _count); - if (tmp == 0) - { if (!this.mre.Set()) throw new InvalidOperationException("couldn't signal"); } - else if (tmp < 0) - throw new InvalidOperationException("Counter underflow"); - } + if (tmp == 0) + { if (!_mre.Set()) throw new InvalidOperationException("couldn't signal"); } + else if (tmp < 0) + throw new InvalidOperationException("Counter underflow"); + } - public void Wait() - { - if (this.count == 0) return; + public void Wait() + { + if (_count == 0) return; - this.mre.WaitOne(); - } + _mre.WaitOne(); + } - ~CountdownEvent() - { - this.Dispose(); - } + ~CountdownEvent() + { + Dispose(); + } - void IDisposable.Dispose() - { - this.Dispose(); - } + void IDisposable.Dispose() + { + Dispose(); + } - public void Dispose() - { - GC.SuppressFinalize(this); + public void Dispose() + { + GC.SuppressFinalize(this); - if (this.mre != null) - { - this.mre.Dispose(); - this.mre = null; - } - } - } + if (_mre != null) + { + _mre.Dispose(); + _mre = null; + } + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/FnvHash.cs b/src/Enyim.Caching/FnvHash.cs index fd11d9f9..0481d327 100755 --- a/src/Enyim.Caching/FnvHash.cs +++ b/src/Enyim.Caching/FnvHash.cs @@ -3,201 +3,201 @@ namespace Enyim { - /// - /// Implements a 64 bit long FNV1 hash. - /// - /// - /// Calculation found at http://lists.danga.com/pipermail/memcached/2007-April/003846.html, but - /// it is pretty much available everywhere - /// - public class FNV64 : System.Security.Cryptography.HashAlgorithm, IUIntHashAlgorithm - { - protected const ulong Init = 0xcbf29ce484222325L; - protected const ulong Prime = 0x100000001b3L; - - protected ulong CurrentHashValue; - - /// - /// Initializes a new instance of the class. - /// - public FNV64() - { - //base.HashSize = 64; - } - - /// - /// Initializes an instance of . - /// - public override void Initialize() - { - this.CurrentHashValue = Init; - } - - /// Routes data written to the object into the hash algorithm for computing the hash. - /// The input data. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the array to use as data. - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - int end = ibStart + cbSize; - - for (int i = ibStart; i < end; i++) - { - this.CurrentHashValue *= Prime; - this.CurrentHashValue ^= array[i]; - } - } - - /// - /// Returns the computed hash value after all data has been written to the object. - /// - /// The computed hash code. - protected override byte[] HashFinal() - { - return BitConverter.GetBytes(this.CurrentHashValue); - } - - #region [ IUIntHashAlgorithm ] - - uint IUIntHashAlgorithm.ComputeHash(byte[] data) - { - this.Initialize(); - this.HashCore(data, 0, data.Length); - - return (uint)this.CurrentHashValue; - } - - #endregion - } - - /// - /// Implements a 64 bit long FVNV1a hash. - /// - public sealed class FNV64a : FNV64 - { - /// Routes data written to the object into the hash algorithm for computing the hash. - /// The input data. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the array to use as data. - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - int end = ibStart + cbSize; - - for (int i = ibStart; i < end; i++) - { - this.CurrentHashValue ^= array[i]; - this.CurrentHashValue *= Prime; - } - } - } - - /// - /// Implements an FNV1 hash algorithm. - /// - public class FNV1 : HashAlgorithm, IUIntHashAlgorithm - { - protected const uint Prime = 16777619; - protected const uint Init = 2166136261; - - /// - /// The current hash value. - /// - protected uint CurrentHashValue; - - /// - /// Initializes a new instance of the class. - /// - public FNV1() - { - } - - /// - /// Initializes an instance of . - /// - public override void Initialize() - { - this.CurrentHashValue = Init; - } - - /// Routes data written to the object into the hash algorithm for computing the hash. - /// The input data. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the array to use as data. - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - int end = ibStart + cbSize; - - for (int i = ibStart; i < end; i++) - { - this.CurrentHashValue *= FNV1.Prime; - this.CurrentHashValue ^= array[i]; - } - } - - /// - /// Returns the computed hash value after all data has been written to the object. - /// - /// The computed hash code. - protected override byte[] HashFinal() - { - return BitConverter.GetBytes(this.CurrentHashValue); - } - - #region [ IUIntHashAlgorithm ] - - uint IUIntHashAlgorithm.ComputeHash(byte[] data) - { - this.Initialize(); - this.HashCore(data, 0, data.Length); - - return this.CurrentHashValue; - } - - #endregion - } - - /// - /// Implements an FNV1a hash algorithm. - /// - public class FNV1a : FNV1 - { - /// Routes data written to the object into the hash algorithm for computing the hash. - /// The input data. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the array to use as data. - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - int end = ibStart + cbSize; - - for (int i = ibStart; i < end; i++) - { - this.CurrentHashValue ^= array[i]; - this.CurrentHashValue *= FNV1.Prime; - } - } - } - - /// - /// Implements a modified FNV hash. Provides better distribution than FNV1 but it's only 32 bit long. - /// - /// Algorithm found at http://bretm.home.comcast.net/hash/6.html - public class ModifiedFNV : FNV1a - { - /// - /// Returns the computed hash value after all data has been written to the object. - /// - /// The computed hash code. - protected override byte[] HashFinal() - { - this.CurrentHashValue += this.CurrentHashValue << 13; - this.CurrentHashValue ^= this.CurrentHashValue >> 7; - this.CurrentHashValue += this.CurrentHashValue << 3; - this.CurrentHashValue ^= this.CurrentHashValue >> 17; - this.CurrentHashValue += this.CurrentHashValue << 5; - - return base.HashFinal(); - } - } + /// + /// Implements a 64 bit long FNV1 hash. + /// + /// + /// Calculation found at http://lists.danga.com/pipermail/memcached/2007-April/003846.html, but + /// it is pretty much available everywhere + /// + public class FNV64 : System.Security.Cryptography.HashAlgorithm, IUIntHashAlgorithm + { + protected const ulong Init = 0xcbf29ce484222325L; + protected const ulong Prime = 0x100000001b3L; + + protected ulong CurrentHashValue; + + /// + /// Initializes a new instance of the class. + /// + public FNV64() + { + //base.HashSize = 64; + } + + /// + /// Initializes an instance of . + /// + public override void Initialize() + { + CurrentHashValue = Init; + } + + /// Routes data written to the object into the hash algorithm for computing the hash. + /// The input data. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the array to use as data. + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + int end = ibStart + cbSize; + + for (int i = ibStart; i < end; i++) + { + CurrentHashValue *= Prime; + CurrentHashValue ^= array[i]; + } + } + + /// + /// Returns the computed hash value after all data has been written to the object. + /// + /// The computed hash code. + protected override byte[] HashFinal() + { + return BitConverter.GetBytes(CurrentHashValue); + } + + #region [ IUIntHashAlgorithm ] + + uint IUIntHashAlgorithm.ComputeHash(byte[] data) + { + Initialize(); + HashCore(data, 0, data.Length); + + return (uint)CurrentHashValue; + } + + #endregion + } + + /// + /// Implements a 64 bit long FVNV1a hash. + /// + public sealed class FNV64a : FNV64 + { + /// Routes data written to the object into the hash algorithm for computing the hash. + /// The input data. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the array to use as data. + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + int end = ibStart + cbSize; + + for (int i = ibStart; i < end; i++) + { + CurrentHashValue ^= array[i]; + CurrentHashValue *= Prime; + } + } + } + + /// + /// Implements an FNV1 hash algorithm. + /// + public class FNV1 : HashAlgorithm, IUIntHashAlgorithm + { + protected const uint Prime = 16777619; + protected const uint Init = 2166136261; + + /// + /// The current hash value. + /// + protected uint CurrentHashValue; + + /// + /// Initializes a new instance of the class. + /// + public FNV1() + { + } + + /// + /// Initializes an instance of . + /// + public override void Initialize() + { + CurrentHashValue = Init; + } + + /// Routes data written to the object into the hash algorithm for computing the hash. + /// The input data. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the array to use as data. + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + int end = ibStart + cbSize; + + for (int i = ibStart; i < end; i++) + { + CurrentHashValue *= FNV1.Prime; + CurrentHashValue ^= array[i]; + } + } + + /// + /// Returns the computed hash value after all data has been written to the object. + /// + /// The computed hash code. + protected override byte[] HashFinal() + { + return BitConverter.GetBytes(CurrentHashValue); + } + + #region [ IUIntHashAlgorithm ] + + uint IUIntHashAlgorithm.ComputeHash(byte[] data) + { + Initialize(); + HashCore(data, 0, data.Length); + + return CurrentHashValue; + } + + #endregion + } + + /// + /// Implements an FNV1a hash algorithm. + /// + public class FNV1a : FNV1 + { + /// Routes data written to the object into the hash algorithm for computing the hash. + /// The input data. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the array to use as data. + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + int end = ibStart + cbSize; + + for (int i = ibStart; i < end; i++) + { + CurrentHashValue ^= array[i]; + CurrentHashValue *= FNV1.Prime; + } + } + } + + /// + /// Implements a modified FNV hash. Provides better distribution than FNV1 but it's only 32 bit long. + /// + /// Algorithm found at http://bretm.home.comcast.net/hash/6.html + public class ModifiedFNV : FNV1a + { + /// + /// Returns the computed hash value after all data has been written to the object. + /// + /// The computed hash code. + protected override byte[] HashFinal() + { + CurrentHashValue += CurrentHashValue << 13; + CurrentHashValue ^= CurrentHashValue >> 7; + CurrentHashValue += CurrentHashValue << 3; + CurrentHashValue ^= CurrentHashValue >> 17; + CurrentHashValue += CurrentHashValue << 5; + + return base.HashFinal(); + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/HashCodeCombiner.cs b/src/Enyim.Caching/HashCodeCombiner.cs index 7514f5d1..68b87594 100755 --- a/src/Enyim.Caching/HashCodeCombiner.cs +++ b/src/Enyim.Caching/HashCodeCombiner.cs @@ -1,45 +1,45 @@ namespace Enyim { - /// - /// Combines multiple hash codes into one. - /// - public class HashCodeCombiner - { - private int currentHash; - - public HashCodeCombiner() : this(0x1505) { } - - public HashCodeCombiner(int initialValue) - { - this.currentHash = initialValue; - } - - public static int Combine(int code1, int code2) - { - return ((code1 << 5) + code1) ^ code2; - } - - public void Add(int value) - { - this.currentHash = HashCodeCombiner.Combine(this.currentHash, value); - } - - public int CurrentHash - { - get { return this.currentHash; } - } - - public static int Combine(int code1, int code2, int code3) - { - return HashCodeCombiner.Combine(HashCodeCombiner.Combine(code1, code2), code3); - } - - public static int Combine(int code1, int code2, int code3, int code4) - { - return HashCodeCombiner.Combine(HashCodeCombiner.Combine(code1, code2), HashCodeCombiner.Combine(code3, code4)); - } - } + /// + /// Combines multiple hash codes into one. + /// + public class HashCodeCombiner + { + private int _currentHash; + + public HashCodeCombiner() : this(0x1505) { } + + public HashCodeCombiner(int initialValue) + { + _currentHash = initialValue; + } + + public static int Combine(int code1, int code2) + { + return ((code1 << 5) + code1) ^ code2; + } + + public void Add(int value) + { + _currentHash = Combine(_currentHash, value); + } + + public int CurrentHash + { + get { return _currentHash; } + } + + public static int Combine(int code1, int code2, int code3) + { + return Combine(Combine(code1, code2), code3); + } + + public static int Combine(int code1, int code2, int code3, int code4) + { + return Combine(Combine(code1, code2), Combine(code3, code4)); + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/HashkitCrc32.cs b/src/Enyim.Caching/HashkitCrc32.cs index d03fb231..26d4379c 100644 --- a/src/Enyim.Caching/HashkitCrc32.cs +++ b/src/Enyim.Caching/HashkitCrc32.cs @@ -6,149 +6,149 @@ namespace Enyim { - /// - /// CRC-32 implementation. Compatible with libhashkit. - /// - internal class HashkitCrc32 : HashAlgorithm, IUIntHashAlgorithm - { - private bool shouldReset; - private uint currentHash; - - public HashkitCrc32() - { - this.shouldReset = true; - } - - public override void Initialize() - { - // ComputeHash calls Initialize - // so this way we keep the CurrentValue until the next hash calculation - this.shouldReset = true; - } - - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - if (array == null) throw new ArgumentNullException("array"); - if (ibStart < 0 || ibStart > array.Length) throw new ArgumentOutOfRangeException("ibStart"); - if (ibStart + cbSize > array.Length) throw new ArgumentOutOfRangeException("cbSize"); - - if (this.shouldReset) - { - this.currentHash = UInt32.MaxValue; - this.shouldReset = false; - } - else - this.currentHash ^= UInt32.MaxValue; - - this.UnsafeHashCore(array, ibStart, cbSize); - } - - private void FinalizeHash() - { - // strangely libhaskit truncates CRC-32 to 15 bits. we'll do the same to be on the safe side. - this.currentHash = ((~this.currentHash) >> 16) & 0x7fff; - //this.currentHash = (~this.currentHash); - } - - protected override byte[] HashFinal() - { - this.FinalizeHash(); - - return BitConverter.GetBytes((uint)currentHash); - } - - public uint CurrentHash { get { return this.currentHash; } } - - #region [ UnsafeHashCore ] - - private unsafe void UnsafeHashCore(byte[] buffer, int offset, int count) - { - fixed (byte* ptr = buffer) - { - byte* current = ptr + offset; - - while (count > 0) - { - this.currentHash = CrcTable[(byte)(this.currentHash ^ (*current))] ^ (this.currentHash >> 8); - - count--; - current++; - } - } - } - - #endregion - #region [ CrcTable ] - private static readonly uint[] CrcTable = new uint[] - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, - 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, - 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, - 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, - 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, - 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, - 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, - 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, - 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, - 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, - 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, - 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, - 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, - 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, - 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, - 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, - 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, - 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, - 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, - 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, - 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, - 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, - 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, - 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, - 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, - 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, - 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, - 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, - 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, - 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, - 0x2D02EF8D - }; - #endregion - #region [ IUIntHash ] - - uint IUIntHashAlgorithm.ComputeHash(byte[] data) - { - this.Initialize(); - - this.HashCore(data, 0, data.Length); - this.FinalizeHash(); - - return this.currentHash; - } - - #endregion - } + /// + /// CRC-32 implementation. Compatible with libhashkit. + /// + internal class HashkitCrc32 : HashAlgorithm, IUIntHashAlgorithm + { + private bool _shouldReset; + private uint _currentHash; + + public HashkitCrc32() + { + _shouldReset = true; + } + + public override void Initialize() + { + // ComputeHash calls Initialize + // so this way we keep the CurrentValue until the next hash calculation + _shouldReset = true; + } + + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + if (array == null) throw new ArgumentNullException("array"); + if (ibStart < 0 || ibStart > array.Length) throw new ArgumentOutOfRangeException("ibStart"); + if (ibStart + cbSize > array.Length) throw new ArgumentOutOfRangeException("cbSize"); + + if (_shouldReset) + { + _currentHash = UInt32.MaxValue; + _shouldReset = false; + } + else + _currentHash ^= UInt32.MaxValue; + + UnsafeHashCore(array, ibStart, cbSize); + } + + private void FinalizeHash() + { + // strangely libhaskit truncates CRC-32 to 15 bits. we'll do the same to be on the safe side. + _currentHash = ((~_currentHash) >> 16) & 0x7fff; + // _currentHash = (~_currentHash); + } + + protected override byte[] HashFinal() + { + FinalizeHash(); + + return BitConverter.GetBytes(_currentHash); + } + + public uint CurrentHash { get { return _currentHash; } } + + #region [ UnsafeHashCore ] + + private unsafe void UnsafeHashCore(byte[] buffer, int offset, int count) + { + fixed (byte* ptr = buffer) + { + byte* current = ptr + offset; + + while (count > 0) + { + _currentHash = CrcTable[(byte)(_currentHash ^ (*current))] ^ (_currentHash >> 8); + + count--; + current++; + } + } + } + + #endregion + #region [ CrcTable ] + private static readonly uint[] CrcTable = new uint[] + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, + 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, + 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, + 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, + 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, + 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, + 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, + 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, + 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, + 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, + 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, + 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, + 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, + 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, + 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, + 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, + 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, + 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, + 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, + 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, + 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, + 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, + 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, + 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, + 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, + 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, + 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, + 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, + 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, + 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, + 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, + 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, + 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, + 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, + 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, + 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, + 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, + 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, + 0x2D02EF8D + }; + #endregion + #region [ IUIntHash ] + + uint IUIntHashAlgorithm.ComputeHash(byte[] data) + { + Initialize(); + + HashCore(data, 0, data.Length); + FinalizeHash(); + + return _currentHash; + } + + #endregion + } } #region [ License information ] diff --git a/src/Enyim.Caching/HashkitMurmur.cs b/src/Enyim.Caching/HashkitMurmur.cs index c0de2d19..f37423da 100644 --- a/src/Enyim.Caching/HashkitMurmur.cs +++ b/src/Enyim.Caching/HashkitMurmur.cs @@ -6,115 +6,115 @@ namespace Enyim { - /// - /// Murmur hash. Uses the same seed values as libhashkit. - /// - /// Does not support block based hashing. - internal class HashkitMurmur : HashAlgorithm, IUIntHashAlgorithm - { - public HashkitMurmur() - { - - } - - public override void Initialize() { } - - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - if (array == null) throw new ArgumentNullException("array"); - if (ibStart < 0 || ibStart > array.Length) throw new ArgumentOutOfRangeException("ibStart"); - if (ibStart + cbSize > array.Length) throw new ArgumentOutOfRangeException("cbSize"); - - this.CurrentHash = HashkitMurmur.UnsafeHashCore(array, ibStart, cbSize); - } - - protected override byte[] HashFinal() - { - return BitConverter.GetBytes(this.CurrentHash); - } - - public uint CurrentHash { get; private set; } - - #region [ UnsafeHashCore ] - - // this could be rewritten to support streams tho - // cache the tail of the buffer if its length is not mod4 then merge with the next buffer (this is a perf hit since we cannot do our pointer magics) - // then the swicth and the last XORs could be moved into TransformFinal - // -- or -- - // just cache tail and if we have a cache dvalue and the next block is not mod4 long then throw an exception (thus only allow random length blocks for the last one) - static unsafe uint UnsafeHashCore(byte[] data, int offset, int length) - { - const uint M = 0x5bd1e995; - const int R = 24; - - uint seed = (uint)(0xdeadbeef * length); - uint hash = (uint)(seed ^ length); - - int count = length >> 2; - - fixed (byte* start = &(data[offset])) - { - uint* ptrUInt = (uint*)start; - - while (count > 0) - { - uint current = *ptrUInt; - - current = (uint)(current * M); - current ^= current >> R; - current = (uint)(current * M); - hash = (uint)(hash * M); - hash ^= current; - - count--; - ptrUInt++; - } - - switch (length & 3) - { - case 3: - // reverse the last 3 bytes and convert it to an uint - // so cast the last to into an UInt16 and get the 3rd as a byte - // ABC --> CBA; (UInt16)(AB) --> BA - //h ^= (uint)(*ptrByte); - //h ^= (uint)(ptrByte[1] << 8); - hash ^= (*(UInt16*)ptrUInt); - hash ^= (uint)(((byte*)ptrUInt)[2] << 16); - hash *= M; - break; - - case 2: - hash ^= (*(UInt16*)ptrUInt); - hash *= M; - break; - - case 1: - hash ^= (*((byte*)ptrUInt)); - hash *= M; - break; - } - } - - hash ^= hash >> 13; - hash *= M; - hash ^= hash >> 15; - - return hash; - } - #endregion - #region [ IUIntHash ] - - uint IUIntHashAlgorithm.ComputeHash(byte[] data) - { - this.Initialize(); - - this.HashCore(data, 0, data.Length); - - return this.CurrentHash; - } - - #endregion - } + /// + /// Murmur hash. Uses the same seed values as libhashkit. + /// + /// Does not support block based hashing. + internal class HashkitMurmur : HashAlgorithm, IUIntHashAlgorithm + { + public HashkitMurmur() + { + + } + + public override void Initialize() { } + + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + if (array == null) throw new ArgumentNullException("array"); + if (ibStart < 0 || ibStart > array.Length) throw new ArgumentOutOfRangeException("ibStart"); + if (ibStart + cbSize > array.Length) throw new ArgumentOutOfRangeException("cbSize"); + + CurrentHash = UnsafeHashCore(array, ibStart, cbSize); + } + + protected override byte[] HashFinal() + { + return BitConverter.GetBytes(CurrentHash); + } + + public uint CurrentHash { get; private set; } + + #region [ UnsafeHashCore ] + + // this could be rewritten to support streams tho + // cache the tail of the buffer if its length is not mod4 then merge with the next buffer (this is a perf hit since we cannot do our pointer magics) + // then the swicth and the last XORs could be moved into TransformFinal + // -- or -- + // just cache tail and if we have a cache dvalue and the next block is not mod4 long then throw an exception (thus only allow random length blocks for the last one) + static unsafe uint UnsafeHashCore(byte[] data, int offset, int length) + { + const uint M = 0x5bd1e995; + const int R = 24; + + uint seed = (uint)(0xdeadbeef * length); + uint hash = (uint)(seed ^ length); + + int count = length >> 2; + + fixed (byte* start = &(data[offset])) + { + uint* ptrUInt = (uint*)start; + + while (count > 0) + { + uint current = *ptrUInt; + + current = (uint)(current * M); + current ^= current >> R; + current = (uint)(current * M); + hash = (uint)(hash * M); + hash ^= current; + + count--; + ptrUInt++; + } + + switch (length & 3) + { + case 3: + // reverse the last 3 bytes and convert it to an uint + // so cast the last to into an UInt16 and get the 3rd as a byte + // ABC --> CBA; (UInt16)(AB) --> BA + //h ^= (uint)(*ptrByte); + //h ^= (uint)(ptrByte[1] << 8); + hash ^= (*(UInt16*)ptrUInt); + hash ^= (uint)(((byte*)ptrUInt)[2] << 16); + hash *= M; + break; + + case 2: + hash ^= (*(UInt16*)ptrUInt); + hash *= M; + break; + + case 1: + hash ^= (*((byte*)ptrUInt)); + hash *= M; + break; + } + } + + hash ^= hash >> 13; + hash *= M; + hash ^= hash >> 15; + + return hash; + } + #endregion + #region [ IUIntHash ] + + uint IUIntHashAlgorithm.ComputeHash(byte[] data) + { + Initialize(); + + HashCore(data, 0, data.Length); + + return CurrentHash; + } + + #endregion + } } #region [ License information ] diff --git a/src/Enyim.Caching/HashkitOneAtATime.cs b/src/Enyim.Caching/HashkitOneAtATime.cs index f18a65ce..c7227ff0 100644 --- a/src/Enyim.Caching/HashkitOneAtATime.cs +++ b/src/Enyim.Caching/HashkitOneAtATime.cs @@ -6,80 +6,80 @@ namespace Enyim { - /// - /// This is Jenkin's "One at A time Hash". - /// http://en.wikipedia.org/wiki/Jenkins_hash_function - /// - /// Coming from libhashkit. - /// - /// Does not support block based hashing. - internal class HashkitOneAtATime : HashAlgorithm, IUIntHashAlgorithm - { - public HashkitOneAtATime() - { - } - - - public override void Initialize() { } - - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - if (array == null) throw new ArgumentNullException("array"); - if (ibStart < 0 || ibStart > array.Length) throw new ArgumentOutOfRangeException("ibStart"); - if (ibStart + cbSize > array.Length) throw new ArgumentOutOfRangeException("cbSize"); - - HashkitOneAtATime.UnsafeHashCore(array, ibStart, cbSize); - } - - protected override byte[] HashFinal() - { - return BitConverter.GetBytes(this.CurrentHash); - } - - public uint CurrentHash { get; private set; } - - #region [ UnsafeHashCore ] - - // see the murmur hash about stream support - private static unsafe uint UnsafeHashCore(byte[] data, int offset, int count) - { - uint hash = 0; - - fixed (byte* start = &(data[offset])) - { - var ptr = start; - - while (count > 0) - { - hash += *ptr; - hash += (hash << 10); - hash ^= (hash >> 6); - - count--; - ptr++; - } - } - - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - - return hash; - } - #endregion - #region [ IUIntHash ] - - uint IUIntHashAlgorithm.ComputeHash(byte[] data) - { - this.Initialize(); - - this.HashCore(data, 0, data.Length); - - return this.CurrentHash; - } - - #endregion - } + /// + /// This is Jenkin's "One at A time Hash". + /// http://en.wikipedia.org/wiki/Jenkins_hash_function + /// + /// Coming from libhashkit. + /// + /// Does not support block based hashing. + internal class HashkitOneAtATime : HashAlgorithm, IUIntHashAlgorithm + { + public HashkitOneAtATime() + { + } + + + public override void Initialize() { } + + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + if (array == null) throw new ArgumentNullException("array"); + if (ibStart < 0 || ibStart > array.Length) throw new ArgumentOutOfRangeException("ibStart"); + if (ibStart + cbSize > array.Length) throw new ArgumentOutOfRangeException("cbSize"); + + HashkitOneAtATime.UnsafeHashCore(array, ibStart, cbSize); + } + + protected override byte[] HashFinal() + { + return BitConverter.GetBytes(CurrentHash); + } + + public uint CurrentHash { get; private set; } + + #region [ UnsafeHashCore ] + + // see the murmur hash about stream support + private static unsafe uint UnsafeHashCore(byte[] data, int offset, int count) + { + uint hash = 0; + + fixed (byte* start = &(data[offset])) + { + var ptr = start; + + while (count > 0) + { + hash += *ptr; + hash += (hash << 10); + hash ^= (hash >> 6); + + count--; + ptr++; + } + } + + hash += (hash << 3); + hash ^= (hash >> 11); + hash += (hash << 15); + + return hash; + } + #endregion + #region [ IUIntHash ] + + uint IUIntHashAlgorithm.ComputeHash(byte[] data) + { + Initialize(); + + HashCore(data, 0, data.Length); + + return CurrentHash; + } + + #endregion + } } #region [ License information ] diff --git a/src/Enyim.Caching/InterlockedQueue.cs b/src/Enyim.Caching/InterlockedQueue.cs index 677c723c..6179ab75 100644 --- a/src/Enyim.Caching/InterlockedQueue.cs +++ b/src/Enyim.Caching/InterlockedQueue.cs @@ -3,177 +3,177 @@ namespace Enyim.Collections { - /// - /// Implements a non-locking queue. - /// - /// - public class InterlockedQueue - { - private Node headNode; - private Node tailNode; - - /// - /// Initializes a new instance of the class. - /// - public InterlockedQueue() - { - Node node = new Node(default(T)); - - this.headNode = node; - this.tailNode = node; - } - - /// - /// Removes and returns the item at the beginning of the . - /// - /// The object that is removed from the beginning of the . - /// true if an item was successfully dequeued; otherwise false. - public bool Dequeue(out T value) - { - Node head; - Node tail; - Node next; - - while (true) - { - // read head - head = this.headNode; - tail = this.tailNode; - next = head.Next; - - // Are head, tail, and next consistent? - if (Object.ReferenceEquals(this.headNode, head)) - { - // is tail falling behind - if (Object.ReferenceEquals(head, tail)) - { - // is the queue empty? - if (Object.ReferenceEquals(next, null)) - { - value = default(T); - - // queue is empty and cannot dequeue - return false; - } - - Interlocked.CompareExchange( - ref this.tailNode, - next, - tail); - } - else // No need to deal with tail - { - // read value before CAS otherwise another deque might try to free the next node - value = next.Value; - - // try to swing the head to the next node - if (Interlocked.CompareExchange( - ref this.headNode, - next, - head) == head) - { - return true; - } - } - } - } - } - - public bool Peek(out T value) - { - Node head; - Node tail; - Node next; - - while (true) - { - // read head - head = this.headNode; - tail = this.tailNode; - next = head.Next; - - // Are head, tail, and next consistent? - if (Object.ReferenceEquals(this.headNode, head)) - { - // is tail falling behind - if (Object.ReferenceEquals(head, tail)) - { - // is the queue empty? - if (Object.ReferenceEquals(next, null)) - { - value = default(T); - - // queue is empty - return false; - } - - Interlocked.CompareExchange( - ref this.tailNode, - next, - tail); - } - else // No need to deal with tail - { - // read value before CAS otherwise another deque might try to free the next node - value = next.Value; - return true; - } - } - } - } - - /// - /// Adds an object to the end of the . - /// - /// The item to be added to the . The value can be null. - public void Enqueue(T value) - { - // Allocate a new node from the free list - Node valueNode = new Node(value); - - while (true) - { - Node tail = this.tailNode; - Node next = tail.Next; - - // are tail and next consistent - if (Object.ReferenceEquals(tail, this.tailNode)) - { - // was tail pointing to the last node? - if (Object.ReferenceEquals(next, null)) - { - if (Object.ReferenceEquals( - Interlocked.CompareExchange(ref tail.Next, valueNode, next), - next - ) - ) - { - Interlocked.CompareExchange(ref this.tailNode, valueNode, tail); - break; - } - } - else // tail was not pointing to last node - { - // try to swing Tail to the next node - Interlocked.CompareExchange(ref this.tailNode, next, tail); - } - } - } - } - - #region [ Node ] - private class Node - { - public readonly T Value; - public Node Next; - - public Node(T value) - { - this.Value = value; - } - } - #endregion - } + /// + /// Implements a non-locking queue. + /// + /// + public class InterlockedQueue + { + private Node _headNode; + private Node _tailNode; + + /// + /// Initializes a new instance of the class. + /// + public InterlockedQueue() + { + Node node = new Node(default(T)); + + _headNode = node; + _tailNode = node; + } + + /// + /// Removes and returns the item at the beginning of the . + /// + /// The object that is removed from the beginning of the . + /// true if an item was successfully dequeued; otherwise false. + public bool Dequeue(out T value) + { + Node head; + Node tail; + Node next; + + while (true) + { + // read head + head = _headNode; + tail = _tailNode; + next = head.Next; + + // Are head, tail, and next consistent? + if (Object.ReferenceEquals(_headNode, head)) + { + // is tail falling behind + if (Object.ReferenceEquals(head, tail)) + { + // is the queue empty? + if (Object.ReferenceEquals(next, null)) + { + value = default(T); + + // queue is empty and cannot dequeue + return false; + } + + Interlocked.CompareExchange( + ref _tailNode, + next, + tail); + } + else // No need to deal with tail + { + // read value before CAS otherwise another deque might try to free the next node + value = next.Value; + + // try to swing the head to the next node + if (Interlocked.CompareExchange( + ref _headNode, + next, + head) == head) + { + return true; + } + } + } + } + } + + public bool Peek(out T value) + { + Node head; + Node tail; + Node next; + + while (true) + { + // read head + head = _headNode; + tail = _tailNode; + next = head.Next; + + // Are head, tail, and next consistent? + if (Object.ReferenceEquals(_headNode, head)) + { + // is tail falling behind + if (Object.ReferenceEquals(head, tail)) + { + // is the queue empty? + if (Object.ReferenceEquals(next, null)) + { + value = default(T); + + // queue is empty + return false; + } + + Interlocked.CompareExchange( + ref _tailNode, + next, + tail); + } + else // No need to deal with tail + { + // read value before CAS otherwise another deque might try to free the next node + value = next.Value; + return true; + } + } + } + } + + /// + /// Adds an object to the end of the . + /// + /// The item to be added to the . The value can be null. + public void Enqueue(T value) + { + // Allocate a new node from the free list + Node valueNode = new Node(value); + + while (true) + { + Node tail = _tailNode; + Node next = tail.Next; + + // are tail and next consistent + if (Object.ReferenceEquals(tail, _tailNode)) + { + // was tail pointing to the last node? + if (Object.ReferenceEquals(next, null)) + { + if (Object.ReferenceEquals( + Interlocked.CompareExchange(ref tail.Next, valueNode, next), + next + ) + ) + { + Interlocked.CompareExchange(ref _tailNode, valueNode, tail); + break; + } + } + else // tail was not pointing to last node + { + // try to swing Tail to the next node + Interlocked.CompareExchange(ref _tailNode, next, tail); + } + } + } + } + + #region [ Node ] + private class Node + { + public readonly T Value; + public Node Next; + + public Node(T value) + { + Value = value; + } + } + #endregion + } } #region [ License information ] diff --git a/src/Enyim.Caching/InterlockedStack.cs b/src/Enyim.Caching/InterlockedStack.cs index 22c1da2a..4ce1c9d1 100644 --- a/src/Enyim.Caching/InterlockedStack.cs +++ b/src/Enyim.Caching/InterlockedStack.cs @@ -10,19 +10,19 @@ namespace Enyim.Collections [Obsolete] public class InterlockedStack { - private Node head; + private Node _head; public InterlockedStack() { - this.head = new Node(default(TItem)); + _head = new Node(default(TItem)); } public void Push(TItem item) { var node = new Node(item); - do { node.Next = this.head.Next; } - while (Interlocked.CompareExchange(ref this.head.Next, node, node.Next) != node.Next); + do { node.Next = _head.Next; } + while (Interlocked.CompareExchange(ref _head.Next, node, node.Next) != node.Next); } public bool TryPop(out TItem value) @@ -32,10 +32,10 @@ public bool TryPop(out TItem value) do { - node = head.Next; + node = _head.Next; if (node == null) return false; } - while (Interlocked.CompareExchange(ref head.Next, node.Next, node) != node); + while (Interlocked.CompareExchange(ref _head.Next, node.Next, node) != node); value = node.Value; @@ -51,7 +51,7 @@ private class Node public Node(TItem value) { - this.Value = value; + Value = value; } } diff --git a/src/Enyim.Caching/Logging/DiagnosticsLog.cs b/src/Enyim.Caching/Logging/DiagnosticsLog.cs index f9a35a02..30c4c1a3 100644 --- a/src/Enyim.Caching/Logging/DiagnosticsLog.cs +++ b/src/Enyim.Caching/Logging/DiagnosticsLog.cs @@ -7,287 +7,287 @@ namespace Enyim.Caching { - public class DiagnosticsLogFactory : ILogFactory - { - private TextWriter writer; - - public DiagnosticsLogFactory() : this(@"C:\temp\EnyimMemcached.log") { } - - public DiagnosticsLogFactory(string logPath) - { - if (String.IsNullOrEmpty(logPath)) - throw new ArgumentNullException( - "Log path must be defined. Add the following to configuration/appSettings: or specify a valid path in in the constructor."); - - this.writer = new StreamWriter(new FileStream(logPath, FileMode.OpenOrCreate)); - } - - ILog ILogFactory.GetLogger(string name) - { - return new TextWriterLog(name, this.writer); - } - - ILog ILogFactory.GetLogger(Type type) - { - return new TextWriterLog(type.FullName, this.writer); - } - } - - public class ConsoleLogFactory : ILogFactory - { - ILog ILogFactory.GetLogger(string name) - { - return new TextWriterLog(name, Console.Out); - } - - ILog ILogFactory.GetLogger(Type type) - { - return new TextWriterLog(type.FullName, Console.Out); - } - } - - #region [ ILog implementation ] - - internal class TextWriterLog : ILog - { - private const string PrefixDebug = "DEBUG"; - private const string PrefixInfo = "INFO"; - private const string PrefixWarn = "WARN"; - private const string PrefixError = "ERROR"; - private const string PrefixFatal = "FATAL"; - - private TextWriter writer; - private string name; - - public TextWriterLog(string name, TextWriter writer) - { - this.name = name; - this.writer = writer; - } - - private void Dump(string prefix, string message, params object[] args) - { - var line = String.Format("{0:yyyy-MM-dd' 'HH:mm:ss} [{1}] {2} {3} - ", DateTime.Now, prefix, Thread.CurrentThread.ManagedThreadId, this.name) + String.Format(message, args); - - lock (this.writer) - { - this.writer.WriteLine(line); - this.writer.Flush(); - } - } - - private void Dump(string prefix, object message) - { - var line = String.Format("{0:yyyy-MM-dd' 'HH:mm:ss} [{1}] {2} {3} - {4}", DateTime.Now, prefix, Thread.CurrentThread.ManagedThreadId, this.name, message); - - lock (this.writer) - { - this.writer.WriteLine(line); - this.writer.Flush(); - } - } - - bool ILog.IsDebugEnabled - { - get { return true; } - } - - bool ILog.IsInfoEnabled - { - get { return true; } - } - - bool ILog.IsWarnEnabled - { - get { return true; } - } - - bool ILog.IsErrorEnabled - { - get { return true; } - } - - bool ILog.IsFatalEnabled - { - get { return true; } - } - - void ILog.Debug(object message) - { - this.Dump(PrefixDebug, message); - } - - void ILog.Debug(object message, Exception exception) - { - this.Dump(PrefixDebug, message + " - " + exception); - } - - void ILog.DebugFormat(string format, object arg0) - { - this.Dump(PrefixDebug, format, arg0); - } - - void ILog.DebugFormat(string format, object arg0, object arg1) - { - this.Dump(PrefixDebug, format, arg0, arg1); - } - - void ILog.DebugFormat(string format, object arg0, object arg1, object arg2) - { - this.Dump(PrefixDebug, format, arg0, arg1, arg2); - } - - void ILog.DebugFormat(string format, params object[] args) - { - this.Dump(PrefixDebug, format, args); - } - - void ILog.DebugFormat(IFormatProvider provider, string format, params object[] args) - { - this.Dump(PrefixDebug, String.Format(provider, format, args)); - } - - void ILog.Info(object message) - { - this.Dump(PrefixInfo, message); - } - - void ILog.Info(object message, Exception exception) - { - this.Dump(PrefixInfo, message + " - " + exception); - } - - void ILog.InfoFormat(string format, object arg0) - { - this.Dump(PrefixInfo, format, arg0); - } - - void ILog.InfoFormat(string format, object arg0, object arg1) - { - this.Dump(PrefixInfo, format, arg0, arg1); - } - - void ILog.InfoFormat(string format, object arg0, object arg1, object arg2) - { - this.Dump(PrefixInfo, format, arg0, arg1, arg2); - } - - void ILog.InfoFormat(string format, params object[] args) - { - this.Dump(PrefixInfo, format, args); - } - - void ILog.InfoFormat(IFormatProvider provider, string format, params object[] args) - { - this.Dump(PrefixInfo, String.Format(provider, format, args)); - } - - void ILog.Warn(object message) - { - this.Dump(PrefixWarn, message); - } - - void ILog.Warn(object message, Exception exception) - { - this.Dump(PrefixWarn, message + " - " + exception); - } - - void ILog.WarnFormat(string format, object arg0) - { - this.Dump(PrefixWarn, format, arg0); - } - - void ILog.WarnFormat(string format, object arg0, object arg1) - { - this.Dump(PrefixWarn, format, arg0, arg1); - } - - void ILog.WarnFormat(string format, object arg0, object arg1, object arg2) - { - this.Dump(PrefixWarn, format, arg0, arg1, arg2); - } - - void ILog.WarnFormat(string format, params object[] args) - { - this.Dump(PrefixWarn, format, args); - } - - void ILog.WarnFormat(IFormatProvider provider, string format, params object[] args) - { - this.Dump(PrefixWarn, String.Format(provider, format, args)); - } - - void ILog.Error(object message) - { - this.Dump(PrefixError, message); - } - - void ILog.Error(object message, Exception exception) - { - this.Dump(PrefixError, message + " - " + exception); - } - - void ILog.ErrorFormat(string format, object arg0) - { - this.Dump(PrefixError, format, arg0); - } - - void ILog.ErrorFormat(string format, object arg0, object arg1) - { - this.Dump(PrefixError, format, arg0, arg1); - } - - void ILog.ErrorFormat(string format, object arg0, object arg1, object arg2) - { - this.Dump(PrefixError, format, arg0, arg1, arg2); - } - - void ILog.ErrorFormat(string format, params object[] args) - { - this.Dump(PrefixError, format, args); - } - - void ILog.ErrorFormat(IFormatProvider provider, string format, params object[] args) - { - this.Dump(PrefixError, String.Format(provider, format, args)); - } - - void ILog.Fatal(object message) - { - this.Dump(PrefixFatal, message); - } - - void ILog.Fatal(object message, Exception exception) - { - this.Dump(PrefixFatal, message + " - " + exception); - } - - void ILog.FatalFormat(string format, object arg0) - { - this.Dump(PrefixFatal, format, arg0); - } - - void ILog.FatalFormat(string format, object arg0, object arg1) - { - this.Dump(PrefixFatal, format, arg0, arg1); - } - - void ILog.FatalFormat(string format, object arg0, object arg1, object arg2) - { - this.Dump(PrefixFatal, format, arg0, arg1, arg2); - } - - void ILog.FatalFormat(string format, params object[] args) - { - this.Dump(PrefixFatal, format, args); - } - - void ILog.FatalFormat(IFormatProvider provider, string format, params object[] args) - { - this.Dump(PrefixFatal, String.Format(provider, format, args)); - } - } - - #endregion + public class DiagnosticsLogFactory : ILogFactory + { + private TextWriter _writer; + + public DiagnosticsLogFactory() : this(@"C:\temp\EnyimMemcached.log") { } + + public DiagnosticsLogFactory(string logPath) + { + if (string.IsNullOrEmpty(logPath)) + throw new ArgumentNullException( + "Log path must be defined. Add the following to configuration/appSettings: or specify a valid path in in the constructor."); + + _writer = new StreamWriter(new FileStream(logPath, FileMode.OpenOrCreate)); + } + + ILog ILogFactory.GetLogger(string name) + { + return new TextWriterLog(name, _writer); + } + + ILog ILogFactory.GetLogger(Type type) + { + return new TextWriterLog(type.FullName, _writer); + } + } + + public class ConsoleLogFactory : ILogFactory + { + ILog ILogFactory.GetLogger(string name) + { + return new TextWriterLog(name, Console.Out); + } + + ILog ILogFactory.GetLogger(Type type) + { + return new TextWriterLog(type.FullName, Console.Out); + } + } + + #region [ ILog implementation ] + + internal class TextWriterLog : ILog + { + private const string PrefixDebug = "DEBUG"; + private const string PrefixInfo = "INFO"; + private const string PrefixWarn = "WARN"; + private const string PrefixError = "ERROR"; + private const string PrefixFatal = "FATAL"; + + private TextWriter _writer; + private string _name; + + public TextWriterLog(string name, TextWriter writer) + { + _name = name; + _writer = writer; + } + + private void Dump(string prefix, string message, params object[] args) + { + var line = string.Format("{0:yyyy-MM-dd' 'HH:mm:ss} [{1}] {2} {3} - ", DateTime.Now, prefix, Thread.CurrentThread.ManagedThreadId, _name) + String.Format(message, args); + + lock (_writer) + { + _writer.WriteLine(line); + _writer.Flush(); + } + } + + private void Dump(string prefix, object message) + { + var line = string.Format("{0:yyyy-MM-dd' 'HH:mm:ss} [{1}] {2} {3} - {4}", DateTime.Now, prefix, Thread.CurrentThread.ManagedThreadId, _name, message); + + lock (_writer) + { + _writer.WriteLine(line); + _writer.Flush(); + } + } + + bool ILog.IsDebugEnabled + { + get { return true; } + } + + bool ILog.IsInfoEnabled + { + get { return true; } + } + + bool ILog.IsWarnEnabled + { + get { return true; } + } + + bool ILog.IsErrorEnabled + { + get { return true; } + } + + bool ILog.IsFatalEnabled + { + get { return true; } + } + + void ILog.Debug(object message) + { + Dump(PrefixDebug, message); + } + + void ILog.Debug(object message, Exception exception) + { + Dump(PrefixDebug, message + " - " + exception); + } + + void ILog.DebugFormat(string format, object arg0) + { + Dump(PrefixDebug, format, arg0); + } + + void ILog.DebugFormat(string format, object arg0, object arg1) + { + Dump(PrefixDebug, format, arg0, arg1); + } + + void ILog.DebugFormat(string format, object arg0, object arg1, object arg2) + { + Dump(PrefixDebug, format, arg0, arg1, arg2); + } + + void ILog.DebugFormat(string format, params object[] args) + { + Dump(PrefixDebug, format, args); + } + + void ILog.DebugFormat(IFormatProvider provider, string format, params object[] args) + { + Dump(PrefixDebug, string.Format(provider, format, args)); + } + + void ILog.Info(object message) + { + Dump(PrefixInfo, message); + } + + void ILog.Info(object message, Exception exception) + { + Dump(PrefixInfo, message + " - " + exception); + } + + void ILog.InfoFormat(string format, object arg0) + { + Dump(PrefixInfo, format, arg0); + } + + void ILog.InfoFormat(string format, object arg0, object arg1) + { + Dump(PrefixInfo, format, arg0, arg1); + } + + void ILog.InfoFormat(string format, object arg0, object arg1, object arg2) + { + Dump(PrefixInfo, format, arg0, arg1, arg2); + } + + void ILog.InfoFormat(string format, params object[] args) + { + Dump(PrefixInfo, format, args); + } + + void ILog.InfoFormat(IFormatProvider provider, string format, params object[] args) + { + Dump(PrefixInfo, String.Format(provider, format, args)); + } + + void ILog.Warn(object message) + { + Dump(PrefixWarn, message); + } + + void ILog.Warn(object message, Exception exception) + { + Dump(PrefixWarn, message + " - " + exception); + } + + void ILog.WarnFormat(string format, object arg0) + { + Dump(PrefixWarn, format, arg0); + } + + void ILog.WarnFormat(string format, object arg0, object arg1) + { + Dump(PrefixWarn, format, arg0, arg1); + } + + void ILog.WarnFormat(string format, object arg0, object arg1, object arg2) + { + Dump(PrefixWarn, format, arg0, arg1, arg2); + } + + void ILog.WarnFormat(string format, params object[] args) + { + Dump(PrefixWarn, format, args); + } + + void ILog.WarnFormat(IFormatProvider provider, string format, params object[] args) + { + Dump(PrefixWarn, String.Format(provider, format, args)); + } + + void ILog.Error(object message) + { + Dump(PrefixError, message); + } + + void ILog.Error(object message, Exception exception) + { + Dump(PrefixError, message + " - " + exception); + } + + void ILog.ErrorFormat(string format, object arg0) + { + Dump(PrefixError, format, arg0); + } + + void ILog.ErrorFormat(string format, object arg0, object arg1) + { + Dump(PrefixError, format, arg0, arg1); + } + + void ILog.ErrorFormat(string format, object arg0, object arg1, object arg2) + { + Dump(PrefixError, format, arg0, arg1, arg2); + } + + void ILog.ErrorFormat(string format, params object[] args) + { + Dump(PrefixError, format, args); + } + + void ILog.ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + Dump(PrefixError, String.Format(provider, format, args)); + } + + void ILog.Fatal(object message) + { + Dump(PrefixFatal, message); + } + + void ILog.Fatal(object message, Exception exception) + { + Dump(PrefixFatal, message + " - " + exception); + } + + void ILog.FatalFormat(string format, object arg0) + { + Dump(PrefixFatal, format, arg0); + } + + void ILog.FatalFormat(string format, object arg0, object arg1) + { + Dump(PrefixFatal, format, arg0, arg1); + } + + void ILog.FatalFormat(string format, object arg0, object arg1, object arg2) + { + Dump(PrefixFatal, format, arg0, arg1, arg2); + } + + void ILog.FatalFormat(string format, params object[] args) + { + Dump(PrefixFatal, format, args); + } + + void ILog.FatalFormat(IFormatProvider provider, string format, params object[] args) + { + Dump(PrefixFatal, String.Format(provider, format, args)); + } + } + + #endregion } diff --git a/src/Enyim.Caching/Memcached/Authentication/PlainTextAuthenticator.cs b/src/Enyim.Caching/Memcached/Authentication/PlainTextAuthenticator.cs index 789a86a0..a67ceff7 100644 --- a/src/Enyim.Caching/Memcached/Authentication/PlainTextAuthenticator.cs +++ b/src/Enyim.Caching/Memcached/Authentication/PlainTextAuthenticator.cs @@ -4,36 +4,36 @@ namespace Enyim.Caching.Memcached { - /// - /// Implements the default plain text ("PLAIN") Memcached authentication. - /// - /// Either use the parametrized constructor, or pass the "userName" and "password" parameters during initalization. - public sealed class PlainTextAuthenticator : ISaslAuthenticationProvider - { - private byte[] authData; + /// + /// Implements the default plain text ("PLAIN") Memcached authentication. + /// + /// Either use the parametrized constructor, or pass the "userName" and "password" parameters during initalization. + public sealed class PlainTextAuthenticator : ISaslAuthenticationProvider + { + private byte[] _authData; - public PlainTextAuthenticator() { } + public PlainTextAuthenticator() { } - public PlainTextAuthenticator(string zone, string userName, string password) - { - this.authData = CreateAuthData(zone, userName, password); - } + public PlainTextAuthenticator(string zone, string userName, string password) + { + _authData = CreateAuthData(zone, userName, password); + } - string ISaslAuthenticationProvider.Type - { - get { return "PLAIN"; } - } + string ISaslAuthenticationProvider.Type + { + get { return "PLAIN"; } + } - void ISaslAuthenticationProvider.Initialize(Dictionary parameters) - { - if (parameters != null) - { - this.authData = CreateAuthData( - GetParameter(parameters, "zone"), - GetParameter(parameters, "userName"), + void ISaslAuthenticationProvider.Initialize(Dictionary parameters) + { + if (parameters != null) + { + _authData = CreateAuthData( + GetParameter(parameters, "zone"), + GetParameter(parameters, "userName"), GetParameter(parameters, "password")); } - } + } private string GetParameter(Dictionary parameters, string key) { @@ -47,26 +47,26 @@ private string GetParameter(Dictionary parameters, string key) } } - byte[] ISaslAuthenticationProvider.Authenticate() - { - return this.authData; - } + byte[] ISaslAuthenticationProvider.Authenticate() + { + return _authData; + } - byte[] ISaslAuthenticationProvider.Continue(byte[] data) - { - return null; - } + byte[] ISaslAuthenticationProvider.Continue(byte[] data) + { + return null; + } - private static byte[] CreateAuthData(string zone, string userName, string password) - { - //message = [authzid] UTF8NUL authcid UTF8NUL passwd - //authcid = 1*SAFE ; MUST accept up to 255 octets - //authzid = 1*SAFE ; MUST accept up to 255 octets - //passwd = 1*SAFE ; MUST accept up to 255 octets - //UTF8NUL = %x00 ; UTF-8 encoded NUL character - return System.Text.Encoding.UTF8.GetBytes(zone + "\0" + userName + "\0" + password); - } - } + private static byte[] CreateAuthData(string zone, string userName, string password) + { + //message = [authzid] UTF8NUL authcid UTF8NUL passwd + //authcid = 1*SAFE ; MUST accept up to 255 octets + //authzid = 1*SAFE ; MUST accept up to 255 octets + //passwd = 1*SAFE ; MUST accept up to 255 octets + //UTF8NUL = %x00 ; UTF-8 encoded NUL character + return System.Text.Encoding.UTF8.GetBytes(zone + "\0" + userName + "\0" + password); + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/DefaultServerPool.cs b/src/Enyim.Caching/Memcached/DefaultServerPool.cs index 2eb90c18..3bb1854c 100644 --- a/src/Enyim.Caching/Memcached/DefaultServerPool.cs +++ b/src/Enyim.Caching/Memcached/DefaultServerPool.cs @@ -13,18 +13,18 @@ public class DefaultServerPool : IServerPool, IDisposable { private readonly ILogger _logger; - private IMemcachedNode[] allNodes; + private IMemcachedNode[] _allNodes; - private readonly IMemcachedClientConfiguration configuration; - private readonly IOperationFactory factory; - private IMemcachedNodeLocator nodeLocator; + private readonly IMemcachedClientConfiguration _configuration; + private readonly IOperationFactory _factory; + private IMemcachedNodeLocator _nodeLocator; private readonly object DeadSync = new Object(); - private System.Threading.Timer resurrectTimer; - private bool isTimerActive; - private readonly int deadTimeoutMsec; - private bool isDisposed; - private event Action nodeFailed; + private Timer _resurrectTimer; + private bool _isTimerActive; + private readonly int _deadTimeoutMsec; + private bool _isDisposed; + private event Action _nodeFailed; public DefaultServerPool( IMemcachedClientConfiguration configuration, @@ -34,10 +34,10 @@ public DefaultServerPool( if (configuration == null) throw new ArgumentNullException("socketConfig"); if (opFactory == null) throw new ArgumentNullException("opFactory"); - this.configuration = configuration; - this.factory = opFactory; + _configuration = configuration; + _factory = opFactory; - this.deadTimeoutMsec = (int)this.configuration.SocketPool.DeadTimeout.TotalMilliseconds; + _deadTimeoutMsec = (int)_configuration.SocketPool.DeadTimeout.TotalMilliseconds; _logger = logger; } @@ -50,7 +50,7 @@ public DefaultServerPool( protected virtual IMemcachedNode CreateNode(EndPoint endpoint) { - return new MemcachedNode(endpoint, this.configuration.SocketPool, _logger, this.configuration.UseSslStream); + return new MemcachedNode(endpoint, _configuration.SocketPool, _logger, _configuration.UseSslStream); } private void rezCallback(object state) @@ -73,9 +73,9 @@ private void rezCallback(object state) // 6. if at least one server is still down (Ping() == false), we restart the timer // 7. if all servers are up, we set isRunning to false, so the timer is suspended // 8. GOTO 2 - lock (this.DeadSync) + lock (DeadSync) { - if (this.isDisposed) + if (_isDisposed) { if (_logger.IsEnabled(LogLevel.Warning)) _logger.LogWarning("IsAlive timer was triggered but the pool is already disposed. Ignoring."); @@ -83,7 +83,7 @@ private void rezCallback(object state) return; } - var nodes = this.allNodes; + var nodes = _allNodes; var aliveList = new List(nodes.Length); var changed = false; var deadCount = 0; @@ -122,7 +122,7 @@ private void rezCallback(object state) { if (isDebug) _logger.LogDebug("Reinitializing the locator."); - this.nodeLocator.Initialize(aliveList); + _nodeLocator.Initialize(aliveList); } // stop or restart the timer @@ -130,13 +130,13 @@ private void rezCallback(object state) { if (isDebug) _logger.LogDebug("deadCount == 0, stopping the timer."); - this.isTimerActive = false; + _isTimerActive = false; } else { if (isDebug) _logger.LogDebug("deadCount == {0}, starting the timer.", deadCount); - this.resurrectTimer.Change(this.deadTimeoutMsec, Timeout.Infinite); + _resurrectTimer.Change(_deadTimeoutMsec, Timeout.Infinite); } } } @@ -148,9 +148,9 @@ private void NodeFail(IMemcachedNode node) // the timer is stopped until we encounter the first dead server // when we have one, we trigger it and it will run after DeadTimeout has elapsed - lock (this.DeadSync) + lock (DeadSync) { - if (this.isDisposed) + if (_isDisposed) { if (_logger.IsEnabled(LogLevel.Warning)) _logger.LogWarning("Got a node fail but the pool is already disposed. Ignoring."); @@ -158,27 +158,27 @@ private void NodeFail(IMemcachedNode node) } // bubble up the fail event to the client - var fail = this.nodeFailed; + var fail = _nodeFailed; if (fail != null) fail(node); // re-initialize the locator - var newLocator = this.configuration.CreateNodeLocator(); - newLocator.Initialize(allNodes.Where(n => n.IsAlive).ToArray()); - Interlocked.Exchange(ref this.nodeLocator, newLocator); + var newLocator = _configuration.CreateNodeLocator(); + newLocator.Initialize(_allNodes.Where(n => n.IsAlive).ToArray()); + Interlocked.Exchange(ref _nodeLocator, newLocator); // the timer is stopped until we encounter the first dead server // when we have one, we trigger it and it will run after DeadTimeout has elapsed - if (!this.isTimerActive) + if (!_isTimerActive) { if (isDebug) _logger.LogDebug("Starting the recovery timer."); - if (this.resurrectTimer == null) - this.resurrectTimer = new Timer(this.rezCallback, null, this.deadTimeoutMsec, Timeout.Infinite); + if (_resurrectTimer == null) + _resurrectTimer = new Timer(rezCallback, null, _deadTimeoutMsec, Timeout.Infinite); else - this.resurrectTimer.Change(this.deadTimeoutMsec, Timeout.Infinite); + _resurrectTimer.Change(_deadTimeoutMsec, Timeout.Infinite); - this.isTimerActive = true; + _isTimerActive = true; if (isDebug) _logger.LogDebug("Timer started."); } @@ -189,44 +189,44 @@ private void NodeFail(IMemcachedNode node) IMemcachedNode IServerPool.Locate(string key) { - var node = this.nodeLocator.Locate(key); + var node = _nodeLocator.Locate(key); return node; } IOperationFactory IServerPool.OperationFactory { - get { return this.factory; } + get { return _factory; } } IEnumerable IServerPool.GetWorkingNodes() { - return this.nodeLocator.GetWorkingNodes(); + return _nodeLocator.GetWorkingNodes(); } void IServerPool.Start() { - this.allNodes = this.configuration.Servers. + _allNodes = _configuration.Servers. Select(ep => { - var node = this.CreateNode(ep); - node.Failed += this.NodeFail; + var node = CreateNode(ep); + node.Failed += NodeFail; return node; }). ToArray(); // initialize the locator - var locator = this.configuration.CreateNodeLocator(); - locator.Initialize(allNodes); + var locator = _configuration.CreateNodeLocator(); + locator.Initialize(_allNodes); - this.nodeLocator = locator; + _nodeLocator = locator; } event Action IServerPool.NodeFailed { - add { this.nodeFailed += value; } - remove { this.nodeFailed -= value; } + add { _nodeFailed += value; } + remove { _nodeFailed -= value; } } #endregion @@ -236,32 +236,32 @@ void IDisposable.Dispose() { GC.SuppressFinalize(this); - lock (this.DeadSync) + lock (DeadSync) { - if (this.isDisposed) return; + if (_isDisposed) return; - this.isDisposed = true; + _isDisposed = true; // dispose the locator first, maybe it wants to access // the nodes one last time - var nd = this.nodeLocator as IDisposable; + var nd = _nodeLocator as IDisposable; if (nd != null) try { nd.Dispose(); } catch (Exception e) { _logger.LogError(nameof(DefaultServerPool), e); } - this.nodeLocator = null; + _nodeLocator = null; - for (var i = 0; i < this.allNodes.Length; i++) - try { this.allNodes[i].Dispose(); } + for (var i = 0; i < _allNodes.Length; i++) + try { _allNodes[i].Dispose(); } catch (Exception e) { _logger.LogError(nameof(DefaultServerPool), e); } // stop the timer - if (this.resurrectTimer != null) - using (this.resurrectTimer) - this.resurrectTimer.Change(Timeout.Infinite, Timeout.Infinite); + if (_resurrectTimer != null) + using (_resurrectTimer) + _resurrectTimer.Change(Timeout.Infinite, Timeout.Infinite); - this.allNodes = null; - this.resurrectTimer = null; + _allNodes = null; + _resurrectTimer = null; } } diff --git a/src/Enyim.Caching/Memcached/FailurePolicy/ThrottlingFailurePolicy.cs b/src/Enyim.Caching/Memcached/FailurePolicy/ThrottlingFailurePolicy.cs index efc5a125..9bedd586 100644 --- a/src/Enyim.Caching/Memcached/FailurePolicy/ThrottlingFailurePolicy.cs +++ b/src/Enyim.Caching/Memcached/FailurePolicy/ThrottlingFailurePolicy.cs @@ -6,123 +6,123 @@ namespace Enyim.Caching.Memcached { - /// - /// Fails a node when the specified number of failures happen in a specified time window. - /// - public class ThrottlingFailurePolicy : INodeFailurePolicy - { - private static readonly ILog log = LogManager.GetLogger(typeof(ThrottlingFailurePolicy)); - private static readonly bool LogIsDebugEnabled = log.IsDebugEnabled; - - private int resetAfter; - private int failureThreshold; - private DateTime lastFailed; - private int failCounter; - - /// - /// Creates a new instance of . - /// - /// Specifies the time in milliseconds how long a node should function properly to reset its failure counter. - /// Specifies the number of failures that must occur in the specified time window to fail a node. - public ThrottlingFailurePolicy(int resetAfter, int failureThreshold) - { - this.resetAfter = resetAfter; - this.failureThreshold = failureThreshold; - } - - bool INodeFailurePolicy.ShouldFail() - { - var now = DateTime.UtcNow; - - if (lastFailed == DateTime.MinValue) - { - if (LogIsDebugEnabled) log.Debug("Setting fail counter to 1."); - - failCounter = 1; - } - else - { - var diff = (int)(now - lastFailed).TotalMilliseconds; - if (LogIsDebugEnabled) log.DebugFormat("Last fail was {0} msec ago with counter {1}.", diff, this.failCounter); - - if (diff <= this.resetAfter) - this.failCounter++; - else - { - this.failCounter = 1; - } - } - - lastFailed = now; - - if (this.failCounter == this.failureThreshold) - { - if (LogIsDebugEnabled) log.DebugFormat("Threshold reached, node will fail."); - - this.lastFailed = DateTime.MinValue; - this.failCounter = 0; - - return true; - } - - if (LogIsDebugEnabled) log.DebugFormat("Current counter is {0}, threshold not reached.", this.failCounter); - - return false; - } - } - - /// - /// Creates instances of . - /// - public class ThrottlingFailurePolicyFactory : INodeFailurePolicyFactory, IProviderFactory - { - public ThrottlingFailurePolicyFactory(int failureThreshold, TimeSpan resetAfter) - : this(failureThreshold, (int)resetAfter.TotalMilliseconds) { } - - public ThrottlingFailurePolicyFactory(int failureThreshold, int resetAfter) - { - this.ResetAfter = resetAfter; - this.FailureThreshold = failureThreshold; - } - - // used by the config files - internal ThrottlingFailurePolicyFactory() { } - - /// - /// Gets or sets the amount of time of in milliseconds after the failure counter is reset. - /// - public int ResetAfter { get; private set; } - - /// - /// Gets or sets the number of failures that must happen in a time window to make a node marked as failed. - /// - public int FailureThreshold { get; private set; } - - INodeFailurePolicy INodeFailurePolicyFactory.Create(IMemcachedNode node) - { - return new ThrottlingFailurePolicy(this.ResetAfter, this.FailureThreshold); - } - - INodeFailurePolicyFactory IProviderFactory.Create() - { - return new ThrottlingFailurePolicyFactory(this.FailureThreshold, this.ResetAfter); - } - - void IProvider.Initialize(Dictionary parameters) - { - int failureThreshold; - ConfigurationHelper.TryGetAndRemove(parameters, "failureThreshold", out failureThreshold, true); - - if (failureThreshold < 1) throw new InvalidOperationException("failureThreshold must be > 0"); - this.FailureThreshold = failureThreshold; - - TimeSpan reset; - ConfigurationHelper.TryGetAndRemove(parameters, "resetAfter", out reset, true); - if (reset <= TimeSpan.Zero) throw new InvalidOperationException("resetAfter must be > 0msec"); - - this.ResetAfter = (int)reset.TotalMilliseconds; - } - } + /// + /// Fails a node when the specified number of failures happen in a specified time window. + /// + public class ThrottlingFailurePolicy : INodeFailurePolicy + { + private static readonly ILog _log = LogManager.GetLogger(typeof(ThrottlingFailurePolicy)); + private static readonly bool _logIsDebugEnabled = _log.IsDebugEnabled; + + private int _resetAfter; + private int _failureThreshold; + private DateTime _lastFailed; + private int _failCounter; + + /// + /// Creates a new instance of . + /// + /// Specifies the time in milliseconds how long a node should function properly to reset its failure counter. + /// Specifies the number of failures that must occur in the specified time window to fail a node. + public ThrottlingFailurePolicy(int resetAfter, int failureThreshold) + { + _resetAfter = resetAfter; + _failureThreshold = failureThreshold; + } + + bool INodeFailurePolicy.ShouldFail() + { + var now = DateTime.UtcNow; + + if (_lastFailed == DateTime.MinValue) + { + if (_logIsDebugEnabled) _log.Debug("Setting fail counter to 1."); + + _failCounter = 1; + } + else + { + var diff = (int)(now - _lastFailed).TotalMilliseconds; + if (_logIsDebugEnabled) _log.DebugFormat("Last fail was {0} msec ago with counter {1}.", diff, _failCounter); + + if (diff <= _resetAfter) + _failCounter++; + else + { + _failCounter = 1; + } + } + + _lastFailed = now; + + if (_failCounter == _failureThreshold) + { + if (_logIsDebugEnabled) _log.DebugFormat("Threshold reached, node will fail."); + + _lastFailed = DateTime.MinValue; + _failCounter = 0; + + return true; + } + + if (_logIsDebugEnabled) _log.DebugFormat("Current counter is {0}, threshold not reached.", _failCounter); + + return false; + } + } + + /// + /// Creates instances of . + /// + public class ThrottlingFailurePolicyFactory : INodeFailurePolicyFactory, IProviderFactory + { + public ThrottlingFailurePolicyFactory(int failureThreshold, TimeSpan resetAfter) + : this(failureThreshold, (int)resetAfter.TotalMilliseconds) { } + + public ThrottlingFailurePolicyFactory(int failureThreshold, int resetAfter) + { + ResetAfter = resetAfter; + FailureThreshold = failureThreshold; + } + + // used by the config files + internal ThrottlingFailurePolicyFactory() { } + + /// + /// Gets or sets the amount of time of in milliseconds after the failure counter is reset. + /// + public int ResetAfter { get; private set; } + + /// + /// Gets or sets the number of failures that must happen in a time window to make a node marked as failed. + /// + public int FailureThreshold { get; private set; } + + INodeFailurePolicy INodeFailurePolicyFactory.Create(IMemcachedNode node) + { + return new ThrottlingFailurePolicy(ResetAfter, FailureThreshold); + } + + INodeFailurePolicyFactory IProviderFactory.Create() + { + return new ThrottlingFailurePolicyFactory(FailureThreshold, ResetAfter); + } + + void IProvider.Initialize(Dictionary parameters) + { + int failureThreshold; + ConfigurationHelper.TryGetAndRemove(parameters, "failureThreshold", out failureThreshold, true); + + if (failureThreshold < 1) throw new InvalidOperationException("failureThreshold must be > 0"); + FailureThreshold = failureThreshold; + + TimeSpan reset; + ConfigurationHelper.TryGetAndRemove(parameters, "resetAfter", out reset, true); + if (reset <= TimeSpan.Zero) throw new InvalidOperationException("resetAfter must be > 0msec"); + + ResetAfter = (int)reset.TotalMilliseconds; + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/KeyTransformers/KeyTransformerBase.cs b/src/Enyim.Caching/Memcached/KeyTransformers/KeyTransformerBase.cs index 3c647e75..d21d76e2 100755 --- a/src/Enyim.Caching/Memcached/KeyTransformers/KeyTransformerBase.cs +++ b/src/Enyim.Caching/Memcached/KeyTransformers/KeyTransformerBase.cs @@ -1,15 +1,15 @@ namespace Enyim.Caching.Memcached { - public abstract class KeyTransformerBase : IMemcachedKeyTransformer - { - public abstract string Transform(string key); + public abstract class KeyTransformerBase : IMemcachedKeyTransformer + { + public abstract string Transform(string key); - string IMemcachedKeyTransformer.Transform(string key) - { - return this.Transform(key); - } - } + string IMemcachedKeyTransformer.Transform(string key) + { + return Transform(key); + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/Locators/SingleNodeLocator.cs b/src/Enyim.Caching/Memcached/Locators/SingleNodeLocator.cs index 510db917..1c01094b 100644 --- a/src/Enyim.Caching/Memcached/Locators/SingleNodeLocator.cs +++ b/src/Enyim.Caching/Memcached/Locators/SingleNodeLocator.cs @@ -4,30 +4,30 @@ namespace Enyim.Caching.Memcached { - /// - /// This is a simple node locator with no computation overhead, always returns the first server from the list. Use only in single server deployments. - /// - public sealed class SingleNodeLocator : IMemcachedNodeLocator - { - private IMemcachedNode node; - private bool isInitialized; - private object initLock = new Object(); + /// + /// This is a simple node locator with no computation overhead, always returns the first server from the list. Use only in single server deployments. + /// + public sealed class SingleNodeLocator : IMemcachedNodeLocator + { + private IMemcachedNode _node; + private bool _isInitialized; + private object initLock = new Object(); - void IMemcachedNodeLocator.Initialize(IList nodes) - { + void IMemcachedNodeLocator.Initialize(IList nodes) + { if (nodes.Count > 0) { - node = nodes[0]; + _node = nodes[0]; } - this.isInitialized = true; - /*if (this.isInitialized) + _isInitialized = true; + /*if (_isInitialized) return; // locking on this is rude but easy lock (initLock) { - if (this.isInitialized) + if (_isInitialized) return; if (nodes.Count > 0) @@ -35,27 +35,27 @@ void IMemcachedNodeLocator.Initialize(IList nodes) node = nodes[0]; } - this.isInitialized = true; + _isInitialized = true; }*/ } - IMemcachedNode IMemcachedNodeLocator.Locate(string key) - { - if (!this.isInitialized) - throw new InvalidOperationException("You must call Initialize first"); + IMemcachedNode IMemcachedNodeLocator.Locate(string key) + { + if (!_isInitialized) + throw new InvalidOperationException("You must call Initialize first"); - if (this.node == null) return null; + if (_node == null) return null; - return this.node; - } + return _node; + } - IEnumerable IMemcachedNodeLocator.GetWorkingNodes() - { - return this.node.IsAlive - ? new IMemcachedNode[] { this.node } - : Enumerable.Empty(); - } - } + IEnumerable IMemcachedNodeLocator.GetWorkingNodes() + { + return _node.IsAlive + ? new IMemcachedNode[] { _node } + : Enumerable.Empty(); + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/MemcachedNode.cs b/src/Enyim.Caching/Memcached/MemcachedNode.cs index c54d9166..b9ce131c 100755 --- a/src/Enyim.Caching/Memcached/MemcachedNode.cs +++ b/src/Enyim.Caching/Memcached/MemcachedNode.cs @@ -26,13 +26,11 @@ public class MemcachedNode : IMemcachedNode { private readonly ILogger _logger; private static readonly object SyncRoot = new Object(); - - private bool isDisposed; - + private bool _isDisposed; private readonly EndPoint _endPoint; private readonly ISocketPoolConfiguration _config; - private InternalPoolImpl internalPoolImpl; - private bool isInitialized = false; + private InternalPoolImpl _internalPoolImpl; + private bool _isInitialized = false; private SemaphoreSlim poolInitSemaphore = new SemaphoreSlim(1, 1); private readonly TimeSpan _initPoolTimeout; private bool _useSslStream; @@ -61,15 +59,15 @@ public MemcachedNode( } _logger = logger; - this.internalPoolImpl = new InternalPoolImpl(this, socketPoolConfig, _logger); + _internalPoolImpl = new InternalPoolImpl(this, socketPoolConfig, _logger); } public event Action Failed; - private INodeFailurePolicy failurePolicy; + private INodeFailurePolicy _failurePolicy; protected INodeFailurePolicy FailurePolicy { - get { return this.failurePolicy ?? (this.failurePolicy = _config.FailurePolicyFactory.Create(this)); } + get { return _failurePolicy ?? (_failurePolicy = _config.FailurePolicyFactory.Create(this)); } } /// @@ -89,7 +87,7 @@ public EndPoint EndPoint /// Used by the to quickly check if the server's state is valid. public bool IsAlive { - get { return this.internalPoolImpl.IsAlive; } + get { return _internalPoolImpl.IsAlive; } } /// @@ -101,7 +99,7 @@ public bool IsAlive public bool Ping() { // is the server working? - if (this.internalPoolImpl.IsAlive) + if (_internalPoolImpl.IsAlive) return true; // this codepath is (should be) called very rarely @@ -112,22 +110,22 @@ public bool Ping() // we could connect to the server, let's recreate the socket pool lock (SyncRoot) { - if (this.isDisposed) return false; + if (_isDisposed) return false; // try to connect to the server - using (var socket = this.CreateSocket()) + using (var socket = CreateSocket()) { } - if (this.internalPoolImpl.IsAlive) + if (_internalPoolImpl.IsAlive) return true; // it's easier to create a new pool than reinitializing a dead one // rewrite-then-dispose to avoid a race condition with Acquire (which does no locking) - var oldPool = this.internalPoolImpl; + var oldPool = _internalPoolImpl; var newPool = new InternalPoolImpl(this, _config, _logger); - Interlocked.Exchange(ref this.internalPoolImpl, newPool); + Interlocked.Exchange(ref _internalPoolImpl, newPool); try { oldPool.Dispose(); } catch { } @@ -146,7 +144,7 @@ public bool Ping() public IPooledSocketResult Acquire() { var result = new PooledSocketResult(); - if (!this.isInitialized) + if (!_isInitialized) { if (!poolInitSemaphore.Wait(_initPoolTimeout)) { @@ -155,11 +153,11 @@ public IPooledSocketResult Acquire() try { - if (!this.isInitialized) + if (!_isInitialized) { var startTime = DateTime.Now; - this.internalPoolImpl.InitPool(); - this.isInitialized = true; + _internalPoolImpl.InitPool(); + _isInitialized = true; _logger.LogInformation("MemcachedInitPool-cost: {0}ms", (DateTime.Now - startTime).TotalMilliseconds); } } @@ -171,7 +169,7 @@ public IPooledSocketResult Acquire() try { - return this.internalPoolImpl.Acquire(); + return _internalPoolImpl.Acquire(); } catch (Exception e) { @@ -190,7 +188,7 @@ public IPooledSocketResult Acquire() public async Task AcquireAsync() { var result = new PooledSocketResult(); - if (!this.isInitialized) + if (!_isInitialized) { if (!await poolInitSemaphore.WaitAsync(_initPoolTimeout)) { @@ -199,11 +197,11 @@ public async Task AcquireAsync() try { - if (!this.isInitialized) + if (!_isInitialized) { var startTime = DateTime.Now; - await this.internalPoolImpl.InitPoolAsync(); - this.isInitialized = true; + await _internalPoolImpl.InitPoolAsync(); + _isInitialized = true; _logger.LogInformation("MemcachedInitPool-cost: {0}ms", (DateTime.Now - startTime).TotalMilliseconds); } } @@ -215,7 +213,7 @@ public async Task AcquireAsync() try { - return await this.internalPoolImpl.AcquireAsync(); + return await _internalPoolImpl.AcquireAsync(); } catch (Exception e) { @@ -237,7 +235,7 @@ public async Task AcquireAsync() /// public void Dispose() { - if (this.isDisposed) return; + if (_isDisposed) return; GC.SuppressFinalize(this); @@ -247,17 +245,17 @@ public void Dispose() // this should not kill any kittens lock (SyncRoot) { - if (this.isDisposed) return; + if (_isDisposed) return; - this.isDisposed = true; - this.internalPoolImpl.Dispose(); - this.poolInitSemaphore.Dispose(); + _isDisposed = true; + _internalPoolImpl.Dispose(); + poolInitSemaphore.Dispose(); } } void IDisposable.Dispose() { - this.Dispose(); + Dispose(); } #region [ InternalPoolImpl ] @@ -272,16 +270,16 @@ private class InternalPoolImpl : IDisposable /// private ConcurrentStack _freeItems; - private bool isDisposed; - private bool isAlive; - private DateTime markedAsDeadUtc; + private bool _isDisposed; + private bool _isAlive; + private DateTime _markedAsDeadUtc; - private readonly int minItems; - private readonly int maxItems; + private readonly int _minItems; + private readonly int _maxItems; - private MemcachedNode ownerNode; + private MemcachedNode _ownerNode; private readonly EndPoint _endPoint; - private readonly TimeSpan queueTimeout; + private readonly TimeSpan _queueTimeout; private readonly TimeSpan _receiveTimeout; private SemaphoreSlim _semaphore; @@ -301,16 +299,16 @@ internal InternalPoolImpl( if (config.ReceiveTimeout < TimeSpan.Zero) throw new InvalidOperationException("ReceiveTimeout must be >= TimeSpan.Zero", null); - this.ownerNode = ownerNode; - this.isAlive = true; + _ownerNode = ownerNode; + _isAlive = true; _endPoint = ownerNode.EndPoint; - this.queueTimeout = config.QueueTimeout; + _queueTimeout = config.QueueTimeout; _receiveTimeout = config.ReceiveTimeout; - this.minItems = config.MinPoolSize; - this.maxItems = config.MaxPoolSize; + _minItems = config.MinPoolSize; + _maxItems = config.MaxPoolSize; - _semaphore = new SemaphoreSlim(maxItems, maxItems); + _semaphore = new SemaphoreSlim(_maxItems, _maxItems); _freeItems = new ConcurrentStack(); _logger = logger; @@ -321,9 +319,9 @@ internal void InitPool() { try { - if (this.minItems > 0) + if (_minItems > 0) { - for (int i = 0; i < this.minItems; i++) + for (int i = 0; i < _minItems; i++) { try { @@ -335,20 +333,20 @@ internal void InitPool() } // cannot connect to the server - if (!this.isAlive) + if (!_isAlive) break; } } if (_logger.IsEnabled(LogLevel.Debug)) - _logger.LogDebug("Pool has been inited for {0} with {1} sockets", _endPoint, this.minItems); + _logger.LogDebug("Pool has been inited for {0} with {1} sockets", _endPoint, _minItems); } catch (Exception e) { _logger.LogError("Could not init pool.", new EventId(0), e); - this.MarkAsDead(); + MarkAsDead(); } } @@ -356,9 +354,9 @@ internal async Task InitPoolAsync() { try { - if (this.minItems > 0) + if (_minItems > 0) { - for (int i = 0; i < this.minItems; i++) + for (int i = 0; i < _minItems; i++) { try { @@ -370,47 +368,47 @@ internal async Task InitPoolAsync() } // cannot connect to the server - if (!this.isAlive) + if (!_isAlive) break; } } if (_logger.IsEnabled(LogLevel.Debug)) - _logger.LogDebug("Pool has been inited for {0} with {1} sockets", _endPoint, this.minItems); + _logger.LogDebug("Pool has been inited for {0} with {1} sockets", _endPoint, _minItems); } catch (Exception e) { _logger.LogError("Could not init pool.", new EventId(0), e); - this.MarkAsDead(); + MarkAsDead(); } } private async Task CreateSocketAsync() { - var ps = await this.ownerNode.CreateSocketAsync(); - ps.CleanupCallback = this.ReleaseSocket; + var ps = await _ownerNode.CreateSocketAsync(); + ps.CleanupCallback = ReleaseSocket; return ps; } private PooledSocket CreateSocket() { - var ps = this.ownerNode.CreateSocket(); - ps.CleanupCallback = this.ReleaseSocket; + var ps = _ownerNode.CreateSocket(); + ps.CleanupCallback = ReleaseSocket; return ps; } public bool IsAlive { - get { return this.isAlive; } + get { return _isAlive; } } public DateTime MarkedAsDeadUtc { - get { return this.markedAsDeadUtc; } + get { return _markedAsDeadUtc; } } /// @@ -424,7 +422,7 @@ public IPooledSocketResult Acquire() if (_isDebugEnabled) _logger.LogDebug($"Acquiring stream from pool on node '{_endPoint}'"); - if (!this.isAlive || this.isDisposed) + if (!_isAlive || _isDisposed) { message = "Pool is dead or disposed, returning null. " + _endPoint; result.Fail(message); @@ -436,7 +434,7 @@ public IPooledSocketResult Acquire() PooledSocket retval = null; - if (!_semaphore.Wait(this.queueTimeout)) + if (!_semaphore.Wait(_queueTimeout)) { message = "Pool is full, timeouting. " + _endPoint; if (_isDebugEnabled) _logger.LogDebug(message); @@ -447,7 +445,7 @@ public IPooledSocketResult Acquire() } // maybe we died while waiting - if (!this.isAlive) + if (!_isAlive) { _semaphore.Release(); @@ -479,7 +477,7 @@ public IPooledSocketResult Acquire() message = "Failed to reset an acquired socket."; _logger.LogError(message, e); - this.MarkAsDead(); + MarkAsDead(); _semaphore.Release(); result.Fail(message, e); @@ -497,7 +495,7 @@ public IPooledSocketResult Acquire() { // okay, create the new item var startTime = DateTime.Now; - retval = this.CreateSocket(); + retval = CreateSocket(); _logger.LogInformation("MemcachedAcquire-CreateSocket: {0}ms", (DateTime.Now - startTime).TotalMilliseconds); result.Value = retval; result.Pass(); @@ -513,7 +511,7 @@ public IPooledSocketResult Acquire() // while the FP pretends that the pool is healthy) _semaphore.Release(); - this.MarkAsDead(); + MarkAsDead(); result.Fail(message); return result; } @@ -534,7 +532,7 @@ public async Task AcquireAsync() if (_isDebugEnabled) _logger.LogDebug("Acquiring stream from pool. " + _endPoint); - if (!this.isAlive || this.isDisposed) + if (!_isAlive || _isDisposed) { message = "Pool is dead or disposed, returning null. " + _endPoint; result.Fail(message); @@ -546,7 +544,7 @@ public async Task AcquireAsync() PooledSocket retval = null; - if (!await _semaphore.WaitAsync(this.queueTimeout)) + if (!await _semaphore.WaitAsync(_queueTimeout)) { message = "Pool is full, timeouting. " + _endPoint; if (_isDebugEnabled) _logger.LogDebug(message); @@ -557,7 +555,7 @@ public async Task AcquireAsync() } // maybe we died while waiting - if (!this.isAlive) + if (!_isAlive) { _semaphore.Release(); @@ -621,7 +619,7 @@ public async Task AcquireAsync() { // okay, create the new item var startTime = DateTime.Now; - retval = await this.CreateSocketAsync(); + retval = await CreateSocketAsync(); _logger.LogInformation("MemcachedAcquire-CreateSocket: {0}ms", (DateTime.Now - startTime).TotalMilliseconds); result.Value = retval; result.Pass(); @@ -637,7 +635,7 @@ public async Task AcquireAsync() // while the FP pretends that the pool is healthy) _semaphore.Release(); - this.MarkAsDead(); + MarkAsDead(); result.Fail(message); return result; } @@ -651,7 +649,7 @@ private void MarkAsDead() { if (_isDebugEnabled) _logger.LogDebug("Mark as dead was requested for {0}", _endPoint); - var shouldFail = ownerNode.FailurePolicy.ShouldFail(); + var shouldFail = _ownerNode.FailurePolicy.ShouldFail(); if (_isDebugEnabled) _logger.LogDebug("FailurePolicy.ShouldFail(): " + shouldFail); @@ -659,13 +657,13 @@ private void MarkAsDead() { if (_logger.IsEnabled(LogLevel.Warning)) _logger.LogWarning("Marking node {0} as dead", _endPoint); - this.isAlive = false; - this.markedAsDeadUtc = DateTime.UtcNow; + _isAlive = false; + _markedAsDeadUtc = DateTime.UtcNow; - var f = this.ownerNode.Failed; + var f = _ownerNode.Failed; if (f != null) - f(this.ownerNode); + f(_ownerNode); } } @@ -678,10 +676,10 @@ private void ReleaseSocket(PooledSocket socket) if (_isDebugEnabled) { _logger.LogDebug("Releasing socket " + socket.InstanceId); - _logger.LogDebug("Are we alive? " + this.isAlive); + _logger.LogDebug("Are we alive? " + _isAlive); } - if (this.isAlive) + if (_isAlive) { // is it still working (i.e. the server is still connected) if (socket.IsAlive) @@ -708,7 +706,7 @@ private void ReleaseSocket(PooledSocket socket) socket.Destroy(); // mark ourselves as not working for a while - this.MarkAsDead(); + MarkAsDead(); } finally { @@ -755,10 +753,10 @@ public void Dispose() // if someone uses a pooled item then 99% that an exception will be thrown // somewhere. But since the dispose is mostly used when everyone else is finished // this should not kill any kittens - if (!this.isDisposed) + if (!_isDisposed) { - this.isAlive = false; - this.isDisposed = true; + _isAlive = false; + _isDisposed = true; PooledSocket ps; @@ -768,7 +766,7 @@ public void Dispose() catch { } } - this.ownerNode = null; + _ownerNode = null; _semaphore.Dispose(); _semaphore = null; _freeItems = null; @@ -777,7 +775,7 @@ public void Dispose() void IDisposable.Dispose() { - this.Dispose(); + Dispose(); } } @@ -840,7 +838,7 @@ protected internal virtual async Task CreateSocketAsync() protected virtual IPooledSocketResult ExecuteOperation(IOperation op) { - var result = this.Acquire(); + var result = Acquire(); if (result.Success && result.HasValue) { try @@ -890,7 +888,7 @@ protected virtual async Task ExecuteOperationAsync(IOperati { _logger.LogDebug($"ExecuteOperationAsync({op})"); - var result = await this.AcquireAsync(); + var result = await AcquireAsync(); if (result.Success && result.HasValue) { try @@ -961,7 +959,7 @@ protected virtual async Task ExecuteOperationAsync(IOperati protected virtual async Task ExecuteOperationAsync(IOperation op, Action next) { - var socket = (await this.AcquireAsync()).Value; + var socket = (await AcquireAsync()).Value; if (socket == null) return false; //key(string) to buffer(btye[]) @@ -1007,12 +1005,12 @@ EndPoint IMemcachedNode.EndPoint bool IMemcachedNode.IsAlive { - get { return this.IsAlive; } + get { return IsAlive; } } bool IMemcachedNode.Ping() { - return this.Ping(); + return Ping(); } IOperationResult IMemcachedNode.Execute(IOperation op) @@ -1032,8 +1030,8 @@ async Task IMemcachedNode.ExecuteAsync(IOperation op, Action next) event Action IMemcachedNode.Failed { - add { this.Failed += value; } - remove { this.Failed -= value; } + add { Failed += value; } + remove { Failed -= value; } } #endregion diff --git a/src/Enyim.Caching/Memcached/PooledSocket.cs b/src/Enyim.Caching/Memcached/PooledSocket.cs index ec98791a..33f20d80 100755 --- a/src/Enyim.Caching/Memcached/PooledSocket.cs +++ b/src/Enyim.Caching/Memcached/PooledSocket.cs @@ -239,14 +239,14 @@ public bool IsAlive /// Use the IDisposable.Dispose method if you want to release this instance back into the pool. public void Destroy() { - this.Dispose(true); + Dispose(true); } ~PooledSocket() { try { - this.Dispose(true); + Dispose(true); } catch { @@ -279,7 +279,7 @@ protected void Dispose(bool disposing) _inputStream = null; _sslStream = null; _socket = null; - this.CleanupCallback = null; + CleanupCallback = null; } catch (Exception e) { @@ -288,7 +288,7 @@ protected void Dispose(bool disposing) } else { - Action cc = this.CleanupCallback; + Action cc = CleanupCallback; if (cc != null) cc(this); @@ -297,7 +297,7 @@ protected void Dispose(bool disposing) void IDisposable.Dispose() { - this.Dispose(false); + Dispose(false); } private void CheckDisposed() @@ -312,7 +312,7 @@ private void CheckDisposed() /// This method blocks and will not return until the value is read. public int ReadByte() { - this.CheckDisposed(); + CheckDisposed(); try { @@ -331,7 +331,7 @@ public int ReadByte() public int ReadByteAsync() { - this.CheckDisposed(); + CheckDisposed(); try { @@ -349,7 +349,7 @@ public int ReadByteAsync() public async Task ReadAsync(byte[] buffer, int offset, int count) { - this.CheckDisposed(); + CheckDisposed(); int read = 0; int shouldRead = count; @@ -389,7 +389,7 @@ public async Task ReadAsync(byte[] buffer, int offset, int count) /// This method blocks and will not return until the specified amount of bytes are read. public void Read(byte[] buffer, int offset, int count) { - this.CheckDisposed(); + CheckDisposed(); int read = 0; int shouldRead = count; @@ -421,7 +421,7 @@ public void Read(byte[] buffer, int offset, int count) public void Write(byte[] data, int offset, int length) { - this.CheckDisposed(); + CheckDisposed(); if (_useSslStream) { @@ -429,7 +429,7 @@ public void Write(byte[] data, int offset, int length) { _sslStream.Write(data, offset, length); _sslStream.Flush(); - } + } catch (Exception ex) { if (ex is IOException || ex is SocketException) @@ -456,7 +456,7 @@ public void Write(byte[] data, int offset, int length) public void Write(IList> buffers) { - this.CheckDisposed(); + CheckDisposed(); SocketError status; @@ -501,7 +501,7 @@ public async Task WriteAsync(IList> buffers) { foreach (var buf in buffers) { - await _sslStream.WriteAsync(buf.Array,0,buf.Count); + await _sslStream.WriteAsync(buf.Array, 0, buf.Count); } await _sslStream.FlushAsync(); } diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryMultiItemOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryMultiItemOperation.cs index d0103da5..0082b4a1 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryMultiItemOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryMultiItemOperation.cs @@ -11,11 +11,11 @@ public BinaryMultiItemOperation(IList keys) : base(keys) { } protected internal override IList> GetBuffer() { - var keys = this.Keys; + var keys = Keys; var retval = new List>(keys.Count * 2); foreach (var k in keys) - this.Build(k).CreateBuffer(retval); + Build(k).CreateBuffer(retval); return retval; } diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryNode.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryNode.cs index d7191b16..8a6a9410 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryNode.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryNode.cs @@ -17,7 +17,7 @@ namespace Enyim.Caching.Memcached.Protocol.Binary public class BinaryNode : MemcachedNode { private readonly ILogger _logger; - readonly ISaslAuthenticationProvider authenticationProvider; + readonly ISaslAuthenticationProvider _authenticationProvider; public BinaryNode( EndPoint endpoint, @@ -27,7 +27,7 @@ public BinaryNode( bool useSslStream) : base(endpoint, config, logger, useSslStream) { - this.authenticationProvider = authenticationProvider; + _authenticationProvider = authenticationProvider; _logger = logger; } @@ -38,11 +38,11 @@ protected internal override PooledSocket CreateSocket() { var retval = base.CreateSocket(); - if (this.authenticationProvider != null && !Auth(retval)) + if (_authenticationProvider != null && !Auth(retval)) { - _logger.LogError("Authentication failed: " + this.EndPoint); + _logger.LogError("Authentication failed: " + EndPoint); - throw new SecurityException("auth failed: " + this.EndPoint); + throw new SecurityException("auth failed: " + EndPoint); } return retval; @@ -52,11 +52,11 @@ protected internal override async Task CreateSocketAsync() { var retval = await base.CreateSocketAsync(); - if (this.authenticationProvider != null && !(await AuthAsync(retval))) + if (_authenticationProvider != null && !(await AuthAsync(retval))) { - _logger.LogError("Authentication failed: " + this.EndPoint); + _logger.LogError("Authentication failed: " + EndPoint); - throw new SecurityException("auth failed: " + this.EndPoint); + throw new SecurityException("auth failed: " + EndPoint); } return retval; @@ -69,7 +69,7 @@ protected internal override async Task CreateSocketAsync() /// private bool Auth(PooledSocket socket) { - SaslStep currentStep = new SaslStart(this.authenticationProvider); + SaslStep currentStep = new SaslStart(_authenticationProvider); socket.Write(currentStep.GetBuffer()); @@ -78,7 +78,7 @@ private bool Auth(PooledSocket socket) // challenge-response authentication if (currentStep.StatusCode == 0x21) { - currentStep = new SaslContinue(this.authenticationProvider, currentStep.Data); + currentStep = new SaslContinue(_authenticationProvider, currentStep.Data); socket.Write(currentStep.GetBuffer()); } else @@ -95,7 +95,7 @@ private bool Auth(PooledSocket socket) private async Task AuthAsync(PooledSocket socket) { - SaslStep currentStep = new SaslStart(this.authenticationProvider); + SaslStep currentStep = new SaslStart(_authenticationProvider); await socket.WriteAsync(currentStep.GetBuffer()); @@ -104,7 +104,7 @@ private async Task AuthAsync(PooledSocket socket) // challenge-response authentication if (currentStep.StatusCode == 0x21) { - currentStep = new SaslContinue(this.authenticationProvider, currentStep.Data); + currentStep = new SaslContinue(_authenticationProvider, currentStep.Data); await socket.WriteAsync(currentStep.GetBuffer()); } else diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryOperation.cs index 9868a773..b02eb382 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryOperation.cs @@ -10,7 +10,7 @@ public abstract class BinaryOperation : Operation protected internal override IList> GetBuffer() { - return this.Build().CreateBuffer(); + return Build().CreateBuffer(); } protected internal override Task ReadResponseAsync(PooledSocket socket, System.Action next) diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryPool.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryPool.cs index d134eff3..63c6c912 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryPool.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryPool.cs @@ -15,21 +15,21 @@ namespace Enyim.Caching.Memcached.Protocol.Binary /// public class BinaryPool : DefaultServerPool { - readonly ISaslAuthenticationProvider authenticationProvider; - readonly IMemcachedClientConfiguration configuration; + readonly ISaslAuthenticationProvider _authenticationProvider; + readonly IMemcachedClientConfiguration _configuration; private readonly ILogger _logger; public BinaryPool(IMemcachedClientConfiguration configuration, ILogger logger) : base(configuration, new BinaryOperationFactory(logger), logger) { - this.authenticationProvider = GetProvider(configuration); - this.configuration = configuration; + _authenticationProvider = GetProvider(configuration); + _configuration = configuration; _logger = logger; } protected override IMemcachedNode CreateNode(EndPoint endpoint) { - return new BinaryNode(endpoint, this.configuration.SocketPool, this.authenticationProvider, _logger, this.configuration.UseSslStream); + return new BinaryNode(endpoint, _configuration.SocketPool, _authenticationProvider, _logger, _configuration.UseSslStream); } private static ISaslAuthenticationProvider GetProvider(IMemcachedClientConfiguration configuration) diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryRequest.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryRequest.cs index 0ce4f9c0..105cd71d 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryRequest.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryRequest.cs @@ -7,8 +7,8 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { public class BinaryRequest { - private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(BinaryRequest)); - private static int InstanceCounter; + private static readonly ILog _log = LogManager.GetLogger(typeof(BinaryRequest)); + private static int _instanceCounter; public byte Operation; public readonly int CorrelationId; @@ -20,9 +20,9 @@ public BinaryRequest(OpCode operation) : this((byte)operation) { } public BinaryRequest(byte commandCode) { - this.Operation = commandCode; + Operation = commandCode; // session id - this.CorrelationId = Interlocked.Increment(ref InstanceCounter); + CorrelationId = Interlocked.Increment(ref _instanceCounter); } public IList> CreateBuffer() @@ -33,18 +33,18 @@ public IList> CreateBuffer() public IList> CreateBuffer(IList> appendTo) { // key size - byte[] keyData = BinaryConverter.EncodeKey(this.Key); + byte[] keyData = BinaryConverter.EncodeKey(Key); int keyLength = keyData == null ? 0 : keyData.Length; if (keyLength > 0xffff) throw new InvalidOperationException("KeyTooLong"); // extra size - ArraySegment extras = this.Extra; + ArraySegment extras = Extra; int extraLength = extras.Array == null ? 0 : extras.Count; if (extraLength > 0xff) throw new InvalidOperationException("ExtraTooLong"); // body size - ArraySegment body = this.Data; + ArraySegment body = Data; int bodyLength = body.Array == null ? 0 : body.Count; // total payload size @@ -54,7 +54,7 @@ public IList> CreateBuffer(IList> appendTo Span header = stackalloc byte[24]; header[0x00] = 0x80; // magic - header[0x01] = this.Operation; + header[0x01] = Operation; // key length header[0x02] = (byte)(keyLength >> 8); @@ -66,8 +66,8 @@ public IList> CreateBuffer(IList> appendTo // 5 -- data type, 0 (RAW) // 6,7 -- reserved, always 0 - header[0x06] = (byte)(this.Reserved >> 8); - header[0x07] = (byte)(this.Reserved & 255); + header[0x06] = (byte)(Reserved >> 8); + header[0x07] = (byte)(Reserved & 255); // body length header[0x08] = (byte)(totalLength >> 24); @@ -75,12 +75,12 @@ public IList> CreateBuffer(IList> appendTo header[0x0a] = (byte)(totalLength >> 8); header[0x0b] = (byte)(totalLength & 255); - header[0x0c] = (byte)(this.CorrelationId >> 24); - header[0x0d] = (byte)(this.CorrelationId >> 16); - header[0x0e] = (byte)(this.CorrelationId >> 8); - header[0x0f] = (byte)(this.CorrelationId & 255); + header[0x0c] = (byte)(CorrelationId >> 24); + header[0x0d] = (byte)(CorrelationId >> 16); + header[0x0e] = (byte)(CorrelationId >> 8); + header[0x0f] = (byte)(CorrelationId & 255); - ulong cas = this.Cas; + ulong cas = Cas; // CAS if (cas > 0) { diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryResponse.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryResponse.cs index bae64016..b5edb281 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryResponse.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/BinaryResponse.cs @@ -36,20 +36,20 @@ public class BinaryResponse public BinaryResponse() { - this.StatusCode = -1; + StatusCode = -1; } public string GetStatusMessage() { - return this.Data.Array == null + return Data.Array == null ? null - : (this.responseMessage - ?? (this.responseMessage = Encoding.ASCII.GetString(this.Data.Array, this.Data.Offset, this.Data.Count))); + : (responseMessage + ?? (responseMessage = Encoding.ASCII.GetString(Data.Array, Data.Offset, Data.Count))); } public unsafe bool Read(PooledSocket socket) { - this.StatusCode = -1; + StatusCode = -1; if (!socket.IsAlive) return false; @@ -66,16 +66,16 @@ public unsafe bool Read(PooledSocket socket) var data = new byte[dataLength]; socket.Read(data, 0, dataLength); - this.Extra = new ArraySegment(data, 0, extraLength); - this.Data = new ArraySegment(data, extraLength, data.Length - extraLength); + Extra = new ArraySegment(data, 0, extraLength); + Data = new ArraySegment(data, extraLength, data.Length - extraLength); } - return this.StatusCode == 0; + return StatusCode == 0; } public async Task ReadAsync(PooledSocket socket) { - this.StatusCode = -1; + StatusCode = -1; if (!socket.IsAlive) return false; @@ -91,11 +91,11 @@ public async Task ReadAsync(PooledSocket socket) var data = new byte[dataLength]; await socket.ReadAsync(data, 0, dataLength); - this.Extra = new ArraySegment(data, 0, extraLength); - this.Data = new ArraySegment(data, extraLength, data.Length - extraLength); + Extra = new ArraySegment(data, 0, extraLength); + Data = new ArraySegment(data, extraLength, data.Length - extraLength); } - return this.StatusCode == 0; + return StatusCode == 0; } private unsafe void DeserializeHeader(byte[] header, out int dataLength, out int extraLength) @@ -105,13 +105,13 @@ private unsafe void DeserializeHeader(byte[] header, out int dataLength, out int if (buffer[0] != MAGIC_VALUE) throw new InvalidOperationException("Expected magic value " + MAGIC_VALUE + ", received: " + buffer[0]); - this.DataType = buffer[HEADER_DATATYPE]; - this.Opcode = buffer[HEADER_OPCODE]; - this.StatusCode = BinaryConverter.DecodeUInt16(buffer, HEADER_STATUS); + DataType = buffer[HEADER_DATATYPE]; + Opcode = buffer[HEADER_OPCODE]; + StatusCode = BinaryConverter.DecodeUInt16(buffer, HEADER_STATUS); - this.KeyLength = BinaryConverter.DecodeUInt16(buffer, HEADER_KEY); - this.CorrelationId = BinaryConverter.DecodeInt32(buffer, HEADER_OPAQUE); - this.CAS = BinaryConverter.DecodeUInt64(buffer, HEADER_CAS); + KeyLength = BinaryConverter.DecodeUInt16(buffer, HEADER_KEY); + CorrelationId = BinaryConverter.DecodeInt32(buffer, HEADER_OPAQUE); + CAS = BinaryConverter.DecodeUInt64(buffer, HEADER_CAS); dataLength = BinaryConverter.DecodeInt32(buffer, HEADER_BODY); extraLength = buffer[HEADER_EXTRA]; diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/BinarySingleItemOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/BinarySingleItemOperation.cs index 7c3fea70..f3f6324f 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/BinarySingleItemOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/BinarySingleItemOperation.cs @@ -14,7 +14,7 @@ protected BinarySingleItemOperation(string key) : base(key) { } protected internal override IList> GetBuffer() { - return this.Build().CreateBuffer(); + return Build().CreateBuffer(); } protected abstract IOperationResult ProcessResponse(BinaryResponse response); @@ -24,18 +24,18 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) var response = new BinaryResponse(); var retval = response.Read(socket); - this.Cas = response.CAS; - this.StatusCode = response.StatusCode; + Cas = response.CAS; + StatusCode = response.StatusCode; var result = new BinaryOperationResult() { Success = retval, - Cas = this.Cas, - StatusCode = this.StatusCode + Cas = Cas, + StatusCode = StatusCode }; IOperationResult responseResult; - if (!(responseResult = this.ProcessResponse(response)).Success) + if (!(responseResult = ProcessResponse(response)).Success) { result.InnerResult = responseResult; responseResult.Combine(result); @@ -49,18 +49,18 @@ protected internal override async ValueTask ReadResponseAsync( var response = new BinaryResponse(); var retval = await response.ReadAsync(socket); - this.Cas = response.CAS; - this.StatusCode = response.StatusCode; + Cas = response.CAS; + StatusCode = response.StatusCode; var result = new BinaryOperationResult() { Success = retval, - Cas = this.Cas, - StatusCode = this.StatusCode + Cas = Cas, + StatusCode = StatusCode }; IOperationResult responseResult; - if (!(responseResult = this.ProcessResponse(response)).Success) + if (!(responseResult = ProcessResponse(response)).Success) { result.InnerResult = responseResult; responseResult.Combine(result); diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/ConcatOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/ConcatOperation.cs index 7082dfa4..41473246 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/ConcatOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/ConcatOperation.cs @@ -10,23 +10,23 @@ namespace Enyim.Caching.Memcached.Protocol.Binary /// public class ConcatOperation : BinarySingleItemOperation, IConcatOperation { - private readonly ArraySegment data; - private readonly ConcatenationMode mode; + private readonly ArraySegment _data; + private readonly ConcatenationMode _mode; public ConcatOperation(ConcatenationMode mode, string key, ArraySegment data) : base(key) { - this.data = data; - this.mode = mode; + _data = data; + _mode = mode; } protected override BinaryRequest Build() { - var request = new BinaryRequest((OpCode)this.mode) + var request = new BinaryRequest((OpCode)_mode) { - Key = this.Key, - Cas = this.Cas, - Data = this.data + Key = Key, + Cas = Cas, + Data = _data }; return request; @@ -39,7 +39,7 @@ protected override IOperationResult ProcessResponse(BinaryResponse response) ConcatenationMode IConcatOperation.Mode { - get { return this.mode; } + get { return _mode; } } } } diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/DeleteOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/DeleteOperation.cs index b9e0e90a..35b77385 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/DeleteOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/DeleteOperation.cs @@ -6,43 +6,43 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { - public class DeleteOperation : BinarySingleItemOperation, IDeleteOperation - { - private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(DeleteOperation)); - public DeleteOperation(string key) : base(key) { } + public class DeleteOperation : BinarySingleItemOperation, IDeleteOperation + { + private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(DeleteOperation)); + public DeleteOperation(string key) : base(key) { } - protected override BinaryRequest Build() - { - var request = new BinaryRequest(OpCode.Delete) - { - Key = this.Key, - Cas = this.Cas - }; + protected override BinaryRequest Build() + { + var request = new BinaryRequest(OpCode.Delete) + { + Key = Key, + Cas = Cas + }; - return request; - } + return request; + } - protected override IOperationResult ProcessResponse(BinaryResponse response) - { - var result = new BinaryOperationResult(); + protected override IOperationResult ProcessResponse(BinaryResponse response) + { + var result = new BinaryOperationResult(); #if EVEN_MORE_LOGGING if (log.IsDebugEnabled) if (response.StatusCode == 0) - log.DebugFormat("Delete succeeded for key '{0}'.", this.Key); + log.DebugFormat("Delete succeeded for key '{0}'.", Key); else - log.DebugFormat("Delete failed for key '{0}'. Reason: {1}", this.Key, Encoding.ASCII.GetString(response.Data.Array, response.Data.Offset, response.Data.Count)); + log.DebugFormat("Delete failed for key '{0}'. Reason: {1}", Key, Encoding.ASCII.GetString(response.Data.Array, response.Data.Offset, response.Data.Count)); #endif - if (response.StatusCode == 0) - { - return result.Pass(); - } - else - { - var message = ResultHelper.ProcessResponseData(response.Data); - return result.Fail(message); - } - } - } + if (response.StatusCode == 0) + { + return result.Pass(); + } + else + { + var message = ResultHelper.ProcessResponseData(response.Data); + return result.Fail(message); + } + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/FlushOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/FlushOperation.cs index 4c9d5d7e..efbed09b 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/FlushOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/FlushOperation.cs @@ -22,11 +22,11 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) var response = new BinaryResponse(); var retval = response.Read(socket); - this.StatusCode = StatusCode; + StatusCode = StatusCode; var result = new BinaryOperationResult() { Success = retval, - StatusCode = this.StatusCode + StatusCode = StatusCode }; result.PassOrFail(retval, "Failed to read response"); @@ -38,11 +38,11 @@ protected internal override async ValueTask ReadResponseAsync( var response = new BinaryResponse(); var retval = await response.ReadAsync(socket); - this.StatusCode = StatusCode; + StatusCode = StatusCode; var result = new BinaryOperationResult() { Success = retval, - StatusCode = this.StatusCode + StatusCode = StatusCode }; result.PassOrFail(retval, "Failed to read response"); diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/GetOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/GetOperation.cs index 6439ce30..df56350e 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/GetOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/GetOperation.cs @@ -10,7 +10,7 @@ namespace Enyim.Caching.Memcached.Protocol.Binary public class GetOperation : BinarySingleItemOperation, IGetOperation { private readonly ILogger _logger; - private CacheItem result; + private CacheItem _result; public GetOperation(string key, ILogger logger) : base(key) { @@ -21,8 +21,8 @@ protected override BinaryRequest Build() { var request = new BinaryRequest(OpCode.Get) { - Key = this.Key, - Cas = this.Cas + Key = Key, + Cas = Cas }; return request; @@ -33,27 +33,27 @@ protected override IOperationResult ProcessResponse(BinaryResponse response) var status = response.StatusCode; var result = new BinaryOperationResult(); - this.StatusCode = status; + StatusCode = status; if (status == 0) { int flags = BinaryConverter.DecodeInt32(response.Extra, 0); - this.result = new CacheItem((ushort)flags, response.Data); - this.Cas = response.CAS; + _result = new CacheItem((ushort)flags, response.Data); + Cas = response.CAS; #if EVEN_MORE_LOGGING if(_logger.IsEnabled(LogLevel.Debug)) - _logger.LogDebug("Get succeeded for key '{0}'.", this.Key); + _logger.LogDebug("Get succeeded for key '{0}'.", Key); #endif return result.Pass(); } - this.Cas = 0; + Cas = 0; #if EVEN_MORE_LOGGING if(_logger.IsEnabled(LogLevel.Debug)) - _logger.LogDebug("Get failed for key '{0}'. Reason: {1}", this.Key, Encoding.ASCII.GetString(response.Data.Array, response.Data.Offset, response.Data.Count)); + _logger.LogDebug("Get failed for key '{0}'. Reason: {1}", Key, Encoding.ASCII.GetString(response.Data.Array, response.Data.Offset, response.Data.Count)); #endif var message = ResultHelper.ProcessResponseData(response.Data); @@ -62,7 +62,7 @@ protected override IOperationResult ProcessResponse(BinaryResponse response) CacheItem IGetOperation.Result { - get { return this.result; } + get { return _result; } } } } diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/MultiGetOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/MultiGetOperation.cs index 537df93d..5f5ac58d 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/MultiGetOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/MultiGetOperation.cs @@ -11,11 +11,11 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { public class MultiGetOperation : BinaryMultiItemOperation, IMultiGetOperation { - private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(MultiGetOperation)); + private static readonly ILog _log = LogManager.GetLogger(typeof(MultiGetOperation)); - private Dictionary result; - private Dictionary idToKey; - private int noopId; + private Dictionary _result; + private Dictionary _idToKey; + private int _noopId; public MultiGetOperation(IList keys) : base(keys) { } @@ -31,38 +31,38 @@ protected override BinaryRequest Build(string key) protected internal override IList> GetBuffer() { - var keys = this.Keys; + var keys = Keys; if (keys == null || keys.Count == 0) { - if (log.IsWarnEnabled) log.Warn("Empty multiget!"); + if (_log.IsWarnEnabled) _log.Warn("Empty multiget!"); return new ArraySegment[0]; } - if (log.IsDebugEnabled) - log.DebugFormat("Building multi-get for {0} keys", keys.Count); + if (_log.IsDebugEnabled) + _log.DebugFormat("Building multi-get for {0} keys", keys.Count); // map the command's correlationId to the item key, // so we can use GetQ (which only returns the item data) - this.idToKey = new Dictionary(); + _idToKey = new Dictionary(); // get ops have 2 segments, header + key var buffers = new List>(keys.Count * 2); foreach (var key in keys) { - var request = this.Build(key); + var request = Build(key); request.CreateBuffer(buffers); // we use this to map the responses to the keys - idToKey[request.CorrelationId] = key; + _idToKey[request.CorrelationId] = key; } // uncork the server var noop = new BinaryRequest(OpCode.NoOp); - this.noopId = noop.CorrelationId; + _noopId = noop.CorrelationId; noop.CreateBuffer(buffers); @@ -88,56 +88,56 @@ private void StoreResult(BinaryResponse reader) string key; // find the key to the response - if (!this.idToKey.TryGetValue(reader.CorrelationId, out key)) + if (!_idToKey.TryGetValue(reader.CorrelationId, out key)) { // we're not supposed to get here tho - log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", reader.CorrelationId); + _log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", reader.CorrelationId); } else { - if (log.IsDebugEnabled) log.DebugFormat("Reading item {0}", key); + if (_log.IsDebugEnabled) _log.DebugFormat("Reading item {0}", key); // deserialize the response var flags = (ushort)BinaryConverter.DecodeInt32(reader.Extra, 0); - this.result[key] = new CacheItem(flags, reader.Data); - this.Cas[key] = reader.CAS; + _result[key] = new CacheItem(flags, reader.Data); + Cas[key] = reader.CAS; } } protected internal override IOperationResult ReadResponse(PooledSocket socket) { - this.result = new Dictionary(); - this.Cas = new Dictionary(); + _result = new Dictionary(); + Cas = new Dictionary(); var result = new TextOperationResult(); var response = new BinaryResponse(); while (response.Read(socket)) { - this.StatusCode = response.StatusCode; + StatusCode = response.StatusCode; // found the noop, quit - if (response.CorrelationId == this.noopId) + if (response.CorrelationId == _noopId) return result.Pass(); string key; // find the key to the response - if (!this.idToKey.TryGetValue(response.CorrelationId, out key)) + if (!_idToKey.TryGetValue(response.CorrelationId, out key)) { // we're not supposed to get here tho - log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); + _log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); continue; } - if (log.IsDebugEnabled) log.DebugFormat("Reading item {0}", key); + if (_log.IsDebugEnabled) _log.DebugFormat("Reading item {0}", key); // deserialize the response int flags = BinaryConverter.DecodeInt32(response.Extra, 0); - this.result[key] = new CacheItem((ushort)flags, response.Data); - this.Cas[key] = response.CAS; + _result[key] = new CacheItem((ushort)flags, response.Data); + Cas[key] = response.CAS; } // finished reading but we did not find the NOOP @@ -146,37 +146,37 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) protected internal override async ValueTask ReadResponseAsync(PooledSocket socket) { - this.result = new Dictionary(); - this.Cas = new Dictionary(); + _result = new Dictionary(); + Cas = new Dictionary(); var result = new TextOperationResult(); var response = new BinaryResponse(); while (await response.ReadAsync(socket)) { - this.StatusCode = response.StatusCode; + StatusCode = response.StatusCode; // found the noop, quit - if (response.CorrelationId == this.noopId) + if (response.CorrelationId == _noopId) return result.Pass(); string key; // find the key to the response - if (!this.idToKey.TryGetValue(response.CorrelationId, out key)) + if (!_idToKey.TryGetValue(response.CorrelationId, out key)) { // we're not supposed to get here tho - log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); + _log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); continue; } - if (log.IsDebugEnabled) log.DebugFormat("Reading item {0}", key); + if (_log.IsDebugEnabled) _log.DebugFormat("Reading item {0}", key); // deserialize the response int flags = BinaryConverter.DecodeInt32(response.Extra, 0); - this.result[key] = new CacheItem((ushort)flags, response.Data); - this.Cas[key] = response.CAS; + _result[key] = new CacheItem((ushort)flags, response.Data); + Cas[key] = response.CAS; } // finished reading but we did not find the NOOP @@ -185,12 +185,12 @@ protected internal override async ValueTask ReadResponseAsync( public Dictionary Result { - get { return this.result; } + get { return _result; } } Dictionary IMultiGetOperation.Result { - get { return this.result; } + get { return _result; } } } } diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/MutatorOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/MutatorOperation.cs index 0eb67a75..bd14218c 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/MutatorOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/MutatorOperation.cs @@ -8,29 +8,29 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { public class MutatorOperation : BinarySingleItemOperation, IMutatorOperation { - private readonly ulong defaultValue; - private readonly ulong delta; - private readonly uint expires; - private readonly MutationMode mode; - private ulong result; + private readonly ulong _defaultValue; + private readonly ulong _delta; + private readonly uint _expires; + private readonly MutationMode _mode; + private ulong _result; public MutatorOperation(MutationMode mode, string key, ulong defaultValue, ulong delta, uint expires) : base(key) { if (delta < 0) throw new ArgumentOutOfRangeException("delta", "delta must be >= 0"); - this.defaultValue = defaultValue; - this.delta = delta; - this.expires = expires; - this.mode = mode; + _defaultValue = defaultValue; + _delta = delta; + _expires = expires; + _mode = mode; } protected unsafe void UpdateExtra(BinaryRequest request) { - if (mode == MutationMode.Touch) + if (_mode == MutationMode.Touch) { Span extra = stackalloc byte[4]; - BinaryPrimitives.WriteUInt32BigEndian(extra, this.expires); + BinaryPrimitives.WriteUInt32BigEndian(extra, _expires); request.Extra = new ArraySegment(extra.ToArray()); } else @@ -39,10 +39,10 @@ protected unsafe void UpdateExtra(BinaryRequest request) fixed (byte* buffer = extra) { - BinaryConverter.EncodeUInt64(this.delta, buffer, 0); + BinaryConverter.EncodeUInt64(_delta, buffer, 0); - BinaryConverter.EncodeUInt64(this.defaultValue, buffer, 8); - BinaryConverter.EncodeUInt32(this.expires, buffer, 16); + BinaryConverter.EncodeUInt64(_defaultValue, buffer, 8); + BinaryConverter.EncodeUInt32(_expires, buffer, 16); } request.Extra = new ArraySegment(extra); @@ -51,13 +51,13 @@ protected unsafe void UpdateExtra(BinaryRequest request) protected override BinaryRequest Build() { - var request = new BinaryRequest((OpCode)this.mode) + var request = new BinaryRequest((OpCode)_mode) { - Key = this.Key, - Cas = this.Cas + Key = Key, + Cas = Cas }; - this.UpdateExtra(request); + UpdateExtra(request); return request; } @@ -66,17 +66,17 @@ protected override IOperationResult ProcessResponse(BinaryResponse response) { var result = new BinaryOperationResult(); var status = response.StatusCode; - this.StatusCode = status; + StatusCode = status; if (status == 0) { - if (mode != MutationMode.Touch) + if (_mode != MutationMode.Touch) { var data = response.Data; if (data.Count != 8) return result.Fail("Result must be 8 bytes long, received: " + data.Count, new InvalidOperationException()); - this.result = BinaryConverter.DecodeUInt64(data.Array, data.Offset); + _result = BinaryConverter.DecodeUInt64(data.Array, data.Offset); } return result.Pass(); @@ -88,12 +88,12 @@ protected override IOperationResult ProcessResponse(BinaryResponse response) MutationMode IMutatorOperation.Mode { - get { return this.mode; } + get { return _mode; } } ulong IMutatorOperation.Result { - get { return this.result; } + get { return _result; } } } } diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/SaslContinue.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/SaslContinue.cs index 306f2844..a48b4a09 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/SaslContinue.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/SaslContinue.cs @@ -4,30 +4,30 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { - /// - /// SASL auth step. - /// - public class SaslContinue : SaslStep - { - private byte[] continuation; + /// + /// SASL auth step. + /// + public class SaslContinue : SaslStep + { + private byte[] _continuation; - public SaslContinue(ISaslAuthenticationProvider provider, byte[] continuation) - : base(provider) - { - this.continuation = continuation; - } + public SaslContinue(ISaslAuthenticationProvider provider, byte[] continuation) + : base(provider) + { + _continuation = continuation; + } - protected override BinaryRequest Build() - { - var request = new BinaryRequest(OpCode.SaslStep) - { - Key = this.Provider.Type, - Data = new ArraySegment(this.Provider.Continue(this.continuation)) - }; + protected override BinaryRequest Build() + { + var request = new BinaryRequest(OpCode.SaslStep) + { + Key = Provider.Type, + Data = new ArraySegment(Provider.Continue(_continuation)) + }; - return request; - } - } + return request; + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStart.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStart.cs index 28d78b14..1c9f8f60 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStart.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStart.cs @@ -4,25 +4,25 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { - /// - /// Starts the SASL auth sequence. - /// - public class SaslStart : SaslStep - { - public SaslStart(ISaslAuthenticationProvider provider) : base(provider) { } + /// + /// Starts the SASL auth sequence. + /// + public class SaslStart : SaslStep + { + public SaslStart(ISaslAuthenticationProvider provider) : base(provider) { } - protected override BinaryRequest Build() - { - // create a Sasl Start command - var request = new BinaryRequest(OpCode.SaslStart) - { - Key = this.Provider.Type, - Data = new ArraySegment(this.Provider.Authenticate()) - }; + protected override BinaryRequest Build() + { + // create a Sasl Start command + var request = new BinaryRequest(OpCode.SaslStart) + { + Key = Provider.Type, + Data = new ArraySegment(Provider.Authenticate()) + }; - return request; - } - } + return request; + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStep.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStep.cs index dc294ea0..f83aba63 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStep.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/SaslStep.cs @@ -11,7 +11,7 @@ public abstract class SaslStep : BinaryOperation { protected SaslStep(ISaslAuthenticationProvider provider) { - this.Provider = provider; + Provider = provider; } protected ISaslAuthenticationProvider Provider { get; private set; } @@ -22,12 +22,12 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) var retval = response.Read(socket); - this.StatusCode = response.StatusCode; - this.Data = response.Data.Array; + StatusCode = response.StatusCode; + Data = response.Data.Array; var result = new BinaryOperationResult { - StatusCode = this.StatusCode + StatusCode = StatusCode }; result.PassOrFail(retval, "Failed to read response"); @@ -40,12 +40,12 @@ protected internal override async ValueTask ReadResponseAsync( var retval = await response.ReadAsync(socket); - this.StatusCode = response.StatusCode; - this.Data = response.Data.Array; + StatusCode = response.StatusCode; + Data = response.Data.Array; var result = new BinaryOperationResult { - StatusCode = this.StatusCode + StatusCode = StatusCode }; result.PassOrFail(retval, "Failed to read response"); diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/StatsOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/StatsOperation.cs index 264f3cbd..57035e30 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/StatsOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/StatsOperation.cs @@ -10,21 +10,21 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { public class StatsOperation : BinaryOperation, IStatsOperation { - private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(StatsOperation)); + private static readonly ILog _log = LogManager.GetLogger(typeof(StatsOperation)); - private readonly string type; - private Dictionary result; + private readonly string _type; + private Dictionary _result; public StatsOperation(string type) { - this.type = type; + _type = type; } protected override BinaryRequest Build() { var request = new BinaryRequest(OpCode.Stat); - if (!String.IsNullOrEmpty(this.type)) - request.Key = this.type; + if (!string.IsNullOrEmpty(_type)) + request.Key = _type; return request; } @@ -46,8 +46,8 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) serverData[key] = value; } - this.result = serverData; - this.StatusCode = response.StatusCode; + _result = serverData; + StatusCode = response.StatusCode; var result = new BinaryOperationResult() { @@ -75,8 +75,8 @@ protected internal override async ValueTask ReadResponseAsync( serverData[key] = value; } - this.result = serverData; - this.StatusCode = response.StatusCode; + _result = serverData; + StatusCode = response.StatusCode; var result = new BinaryOperationResult() { @@ -89,7 +89,7 @@ protected internal override async ValueTask ReadResponseAsync( Dictionary IStatsOperation.Result { - get { return this.result; } + get { return _result; } } } } diff --git a/src/Enyim.Caching/Memcached/Protocol/Binary/StoreOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Binary/StoreOperation.cs index e66ed92c..53c48854 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Binary/StoreOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Binary/StoreOperation.cs @@ -9,40 +9,40 @@ namespace Enyim.Caching.Memcached.Protocol.Binary { public class StoreOperation : BinarySingleItemOperation, IStoreOperation { - private readonly StoreMode mode; - private CacheItem value; - private readonly uint expires; + private readonly StoreMode _mode; + private CacheItem _value; + private readonly uint _expires; public StoreOperation(StoreMode mode, string key, CacheItem value, uint expires) : base(key) { - this.mode = mode; - this.value = value; - this.expires = expires; + _mode = mode; + _value = value; + _expires = expires; } protected override BinaryRequest Build() { OpCode op; - switch (this.mode) + switch (_mode) { case StoreMode.Add: op = OpCode.Add; break; case StoreMode.Set: op = OpCode.Set; break; case StoreMode.Replace: op = OpCode.Replace; break; - default: throw new ArgumentOutOfRangeException("mode", mode + " is not supported"); + default: throw new ArgumentOutOfRangeException("mode", _mode + " is not supported"); } var extra = new byte[8]; - BinaryConverter.EncodeUInt32((uint)this.value.Flags, extra, 0); - BinaryConverter.EncodeUInt32(expires, extra, 4); + BinaryConverter.EncodeUInt32((uint)_value.Flags, extra, 0); + BinaryConverter.EncodeUInt32(_expires, extra, 4); var request = new BinaryRequest(op) { - Key = this.Key, - Cas = this.Cas, + Key = Key, + Cas = Cas, Extra = new ArraySegment(extra), - Data = this.value.Data + Data = _value.Data }; return request; @@ -52,7 +52,7 @@ protected override IOperationResult ProcessResponse(BinaryResponse response) { var result = new BinaryOperationResult(); - this.StatusCode = response.StatusCode; + StatusCode = response.StatusCode; if (response.StatusCode == 0) { return result.Pass(); @@ -66,12 +66,12 @@ protected override IOperationResult ProcessResponse(BinaryResponse response) StoreMode IStoreOperation.Mode { - get { return this.mode; } + get { return _mode; } } protected internal override Task ReadResponseAsync(PooledSocket socket, System.Action next) { - throw new System.NotSupportedException(); + throw new NotSupportedException(); } } } diff --git a/src/Enyim.Caching/Memcached/Protocol/ItemOperation.cs b/src/Enyim.Caching/Memcached/Protocol/ItemOperation.cs index 50a0222f..a8dae56e 100644 --- a/src/Enyim.Caching/Memcached/Protocol/ItemOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/ItemOperation.cs @@ -10,7 +10,7 @@ public abstract class SingleItemOperation : Operation, ISingleItemOperation { protected SingleItemOperation(string key) { - this.Key = key; + Key = key; } public string Key { get; private set; } @@ -22,12 +22,12 @@ protected SingleItemOperation(string key) /// string ISingleItemOperation.Key { - get { return this.Key; } + get { return Key; } } ulong ISingleItemOperation.CasValue { - get { return this.Cas; } + get { return Cas; } } } } diff --git a/src/Enyim.Caching/Memcached/Protocol/MultiItemOperation.cs b/src/Enyim.Caching/Memcached/Protocol/MultiItemOperation.cs index 6247efe1..405e33fa 100644 --- a/src/Enyim.Caching/Memcached/Protocol/MultiItemOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/MultiItemOperation.cs @@ -4,24 +4,24 @@ namespace Enyim.Caching.Memcached.Protocol { - /// - /// Base class for implementing operations working with multiple items. - /// - public abstract class MultiItemOperation : Operation, IMultiItemOperation - { - public MultiItemOperation(IList keys) - { - this.Keys = keys; - } + /// + /// Base class for implementing operations working with multiple items. + /// + public abstract class MultiItemOperation : Operation, IMultiItemOperation + { + public MultiItemOperation(IList keys) + { + Keys = keys; + } - //Input - public IList Keys { get; private set; } - // Output - public Dictionary Cas { get; protected set; } + //Input + public IList Keys { get; private set; } + // Output + public Dictionary Cas { get; protected set; } - IList IMultiItemOperation.Keys { get { return this.Keys; } } - Dictionary IMultiItemOperation.Cas { get { return this.Cas; } } - } + IList IMultiItemOperation.Keys { get { return Keys; } } + Dictionary IMultiItemOperation.Cas { get { return Cas; } } + } } diff --git a/src/Enyim.Caching/Memcached/Protocol/Operation.cs b/src/Enyim.Caching/Memcached/Protocol/Operation.cs index 08e34818..976a578b 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Operation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Operation.cs @@ -19,17 +19,17 @@ protected Operation() { } IList> IOperation.GetBuffer() { - return this.GetBuffer(); + return GetBuffer(); } IOperationResult IOperation.ReadResponse(PooledSocket socket) { - return this.ReadResponse(socket); + return ReadResponse(socket); } async Task IOperation.ReadResponseAsync(PooledSocket socket) { - return await this.ReadResponseAsync(socket); + return await ReadResponseAsync(socket); } async Task IOperation.ReadResponseAsync(PooledSocket socket, Action next) @@ -39,7 +39,7 @@ async Task IOperation.ReadResponseAsync(PooledSocket socket, Action int IOperation.StatusCode { - get { return this.StatusCode; } + get { return StatusCode; } } public int StatusCode { get; protected set; } diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/ConcateOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Text/ConcateOperation.cs index f3fe98c0..d1b46607 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/ConcateOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/ConcateOperation.cs @@ -8,19 +8,19 @@ namespace Enyim.Caching.Memcached.Protocol.Text { public class ConcateOperation : StoreOperationBase, IConcatOperation { - private readonly ConcatenationMode mode; + private readonly ConcatenationMode _mode; internal ConcateOperation(ConcatenationMode mode, string key, ArraySegment data) : base(mode == ConcatenationMode.Append ? StoreCommand.Append : StoreCommand.Prepend, key, new CacheItem() { Data = data, Flags = 0 }, 0, 0) { - this.mode = mode; + _mode = mode; } ConcatenationMode IConcatOperation.Mode { - get { return this.mode; } + get { return _mode; } } protected internal override Task ReadResponseAsync(PooledSocket socket, System.Action next) diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/DeleteOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Text/DeleteOperation.cs index 5346c9b8..0640c500 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/DeleteOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/DeleteOperation.cs @@ -11,7 +11,7 @@ internal DeleteOperation(string key) : base(key) { } protected internal override System.Collections.Generic.IList> GetBuffer() { - var command = "delete " + this.Key + TextSocketHelper.CommandTerminator; + var command = "delete " + Key + TextSocketHelper.CommandTerminator; return TextSocketHelper.GetCommandBuffer(command); } diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/GetHelper.cs b/src/Enyim.Caching/Memcached/Protocol/Text/GetHelper.cs index ddc15e35..ffb50a8c 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/GetHelper.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/GetHelper.cs @@ -3,85 +3,85 @@ namespace Enyim.Caching.Memcached.Protocol.Text { - internal static class GetHelper - { - private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(GetHelper)); - - public static void FinishCurrent(PooledSocket socket) - { - string response = TextSocketHelper.ReadResponse(socket); - - if (String.Compare(response, "END", StringComparison.Ordinal) != 0) - throw new MemcachedClientException("No END was received."); - } - - public static GetResponse ReadItem(PooledSocket socket) - { - string description = TextSocketHelper.ReadResponse(socket); - - if (String.Compare(description, "END", StringComparison.Ordinal) == 0) - return null; - - if (description.Length < 6 || String.Compare(description, 0, "VALUE ", 0, 6, StringComparison.Ordinal) != 0) - throw new MemcachedClientException("No VALUE response received.\r\n" + description); - - ulong cas = 0; - string[] parts = description.Split(' '); - - // response is: - // VALUE [] - // 0 1 2 3 4 - // - // cas only exists in 1.2.4+ - // - if (parts.Length == 5) - { - if (!UInt64.TryParse(parts[4], out cas)) - throw new MemcachedClientException("Invalid CAS VALUE received."); - - } - else if (parts.Length < 4) - { - throw new MemcachedClientException("Invalid VALUE response received: " + description); - } - - ushort flags = UInt16.Parse(parts[2], CultureInfo.InvariantCulture); - int length = Int32.Parse(parts[3], CultureInfo.InvariantCulture); - - byte[] allData = new byte[length]; - byte[] eod = new byte[2]; - - socket.Read(allData, 0, length); - socket.Read(eod, 0, 2); // data is terminated by \r\n - - GetResponse retval = new GetResponse(parts[1], flags, cas, allData); - - if (log.IsDebugEnabled) - log.DebugFormat("Received value. Data type: {0}, size: {1}.", retval.Item.Flags, retval.Item.Data.Count); - - return retval; - } - } - - #region [ T:GetResponse ] - public class GetResponse - { - private GetResponse() { } - public GetResponse(string key, ushort flags, ulong casValue, byte[] data) : this(key, flags, casValue, data, 0, data.Length) { } - - public GetResponse(string key, ushort flags, ulong casValue, byte[] data, int offset, int count) - { - this.Key = key; - this.CasValue = casValue; - - this.Item = new CacheItem(flags, new ArraySegment(data, offset, count)); - } - - public readonly string Key; - public readonly ulong CasValue; - public readonly CacheItem Item; - } - #endregion + internal static class GetHelper + { + private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(GetHelper)); + + public static void FinishCurrent(PooledSocket socket) + { + string response = TextSocketHelper.ReadResponse(socket); + + if (String.Compare(response, "END", StringComparison.Ordinal) != 0) + throw new MemcachedClientException("No END was received."); + } + + public static GetResponse ReadItem(PooledSocket socket) + { + string description = TextSocketHelper.ReadResponse(socket); + + if (String.Compare(description, "END", StringComparison.Ordinal) == 0) + return null; + + if (description.Length < 6 || String.Compare(description, 0, "VALUE ", 0, 6, StringComparison.Ordinal) != 0) + throw new MemcachedClientException("No VALUE response received.\r\n" + description); + + ulong cas = 0; + string[] parts = description.Split(' '); + + // response is: + // VALUE [] + // 0 1 2 3 4 + // + // cas only exists in 1.2.4+ + // + if (parts.Length == 5) + { + if (!UInt64.TryParse(parts[4], out cas)) + throw new MemcachedClientException("Invalid CAS VALUE received."); + + } + else if (parts.Length < 4) + { + throw new MemcachedClientException("Invalid VALUE response received: " + description); + } + + ushort flags = UInt16.Parse(parts[2], CultureInfo.InvariantCulture); + int length = Int32.Parse(parts[3], CultureInfo.InvariantCulture); + + byte[] allData = new byte[length]; + byte[] eod = new byte[2]; + + socket.Read(allData, 0, length); + socket.Read(eod, 0, 2); // data is terminated by \r\n + + GetResponse retval = new GetResponse(parts[1], flags, cas, allData); + + if (log.IsDebugEnabled) + log.DebugFormat("Received value. Data type: {0}, size: {1}.", retval.Item.Flags, retval.Item.Data.Count); + + return retval; + } + } + + #region [ T:GetResponse ] + public class GetResponse + { + private GetResponse() { } + public GetResponse(string key, ushort flags, ulong casValue, byte[] data) : this(key, flags, casValue, data, 0, data.Length) { } + + public GetResponse(string key, ushort flags, ulong casValue, byte[] data, int offset, int count) + { + Key = key; + CasValue = casValue; + + Item = new CacheItem(flags, new ArraySegment(data, offset, count)); + } + + public readonly string Key; + public readonly ulong CasValue; + public readonly CacheItem Item; + } + #endregion } diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/GetOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Text/GetOperation.cs index d4d4c6f3..6eee85d4 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/GetOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/GetOperation.cs @@ -6,13 +6,13 @@ namespace Enyim.Caching.Memcached.Protocol.Text { public class GetOperation : SingleItemOperation, IGetOperation { - private CacheItem result; + private CacheItem _result; internal GetOperation(string key) : base(key) { } protected internal override System.Collections.Generic.IList> GetBuffer() { - var command = "get " + this.Key + TextSocketHelper.CommandTerminator; + var command = "get " + Key + TextSocketHelper.CommandTerminator; return TextSocketHelper.GetCommandBuffer(command); } @@ -24,8 +24,8 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) if (r == null) return result.Fail("Failed to read response"); - this.result = r.Item; - this.Cas = r.CasValue; + _result = r.Item; + Cas = r.CasValue; GetHelper.FinishCurrent(socket); @@ -34,7 +34,7 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) CacheItem IGetOperation.Result { - get { return this.result; } + get { return _result; } } protected internal override ValueTask ReadResponseAsync(PooledSocket socket) @@ -44,8 +44,8 @@ protected internal override ValueTask ReadResponseAsync(Pooled if (r == null) return new ValueTask(result.Fail("Failed to read response")); - this.result = r.Item; - this.Cas = r.CasValue; + _result = r.Item; + Cas = r.CasValue; GetHelper.FinishCurrent(socket); diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/MultiGetOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Text/MultiGetOperation.cs index 2cfac4bc..5d233773 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/MultiGetOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/MultiGetOperation.cs @@ -10,9 +10,9 @@ namespace Enyim.Caching.Memcached.Protocol.Text { public class MultiGetOperation : MultiItemOperation, IMultiGetOperation { - private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(MultiGetOperation)); + private static readonly ILog _log = LogManager.GetLogger(typeof(MultiGetOperation)); - private Dictionary result; + private Dictionary _result; public MultiGetOperation(IList keys) : base(keys) { } @@ -48,18 +48,18 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) } catch (Exception e) { - log.Error(e); + _log.Error(e); } - this.result = retval; - this.Cas = cas; + _result = retval; + Cas = cas; return new TextOperationResult().Pass(); } Dictionary IMultiGetOperation.Result { - get { return this.result; } + get { return _result; } } protected internal override ValueTask ReadResponseAsync(PooledSocket socket) @@ -85,11 +85,11 @@ protected internal override ValueTask ReadResponseAsync(Pooled } catch (Exception e) { - log.Error(e); + _log.Error(e); } - this.result = retval; - this.Cas = cas; + _result = retval; + Cas = cas; return new ValueTask(new TextOperationResult().Pass()); } diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/MutatorOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Text/MutatorOperation.cs index 4a30c153..6e752a7b 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/MutatorOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/MutatorOperation.cs @@ -10,28 +10,28 @@ namespace Enyim.Caching.Memcached.Protocol.Text { public class MutatorOperation : SingleItemOperation, IMutatorOperation { - private readonly MutationMode mode; - private readonly ulong delta; - private ulong result; + private readonly MutationMode _mode; + private readonly ulong _delta; + private ulong _result; internal MutatorOperation(MutationMode mode, string key, ulong delta) : base(key) { - this.delta = delta; - this.mode = mode; + _delta = delta; + _mode = mode; } public ulong Result { - get { return this.result; } + get { return _result; } } protected internal override IList> GetBuffer() { - var command = (this.mode == MutationMode.Increment ? "incr " : "decr ") - + this.Key + var command = (_mode == MutationMode.Increment ? "incr " : "decr ") + + Key + " " - + this.delta.ToString(CultureInfo.InvariantCulture) + + _delta.ToString(CultureInfo.InvariantCulture) + TextSocketHelper.CommandTerminator; return TextSocketHelper.GetCommandBuffer(command); @@ -47,18 +47,18 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) return result.Fail("Failed to read response. Item not found"); result.Success = - UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result); + UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out _result); return result; } MutationMode IMutatorOperation.Mode { - get { return this.mode; } + get { return _mode; } } ulong IMutatorOperation.Result { - get { return this.result; } + get { return _result; } } protected internal override ValueTask ReadResponseAsync(PooledSocket socket) @@ -71,7 +71,7 @@ protected internal override ValueTask ReadResponseAsync(Pooled return new ValueTask(result.Fail("Failed to read response. Item not found")); result.Success = - UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result); + UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out _result); return new ValueTask(result); } diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/StatsOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Text/StatsOperation.cs index cda8ffef..eac82cd3 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/StatsOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/StatsOperation.cs @@ -9,21 +9,21 @@ namespace Enyim.Caching.Memcached.Protocol.Text { public class StatsOperation : Operation, IStatsOperation { - private static Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(StatsOperation)); + private static ILog _log = LogManager.GetLogger(typeof(StatsOperation)); - private readonly string type; - private Dictionary result; + private readonly string _type; + private Dictionary _result; public StatsOperation(string type) { - this.type = type; + _type = type; } protected internal override IList> GetBuffer() { - var command = String.IsNullOrEmpty(this.type) + var command = string.IsNullOrEmpty(_type) ? "stats" + TextSocketHelper.CommandTerminator - : "stats " + this.type + TextSocketHelper.CommandTerminator; + : "stats " + _type + TextSocketHelper.CommandTerminator; return TextSocketHelper.GetCommandBuffer(command); } @@ -43,8 +43,8 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) // expected response is STAT item_name item_value if (line.Length < 6 || String.Compare(line, 0, "STAT ", 0, 5, StringComparison.Ordinal) != 0) { - if (log.IsWarnEnabled) - log.Warn("Unknow response: " + line); + if (_log.IsWarnEnabled) + _log.Warn("Unknow response: " + line); continue; } @@ -53,8 +53,8 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) string[] parts = line.Remove(0, 5).Split(' '); if (parts.Length != 2) { - if (log.IsWarnEnabled) - log.Warn("Unknow response: " + line); + if (_log.IsWarnEnabled) + _log.Warn("Unknow response: " + line); continue; } @@ -63,14 +63,14 @@ protected internal override IOperationResult ReadResponse(PooledSocket socket) serverData[parts[0]] = parts[1]; } - this.result = serverData; + _result = serverData; return new TextOperationResult().Pass(); } Dictionary IStatsOperation.Result { - get { return result; } + get { return _result; } } protected internal override ValueTask ReadResponseAsync(PooledSocket socket) @@ -88,8 +88,8 @@ protected internal override ValueTask ReadResponseAsync(Pooled // expected response is STAT item_name item_value if (line.Length < 6 || String.Compare(line, 0, "STAT ", 0, 5, StringComparison.Ordinal) != 0) { - if (log.IsWarnEnabled) - log.Warn("Unknow response: " + line); + if (_log.IsWarnEnabled) + _log.Warn("Unknow response: " + line); continue; } @@ -98,8 +98,8 @@ protected internal override ValueTask ReadResponseAsync(Pooled string[] parts = line.Remove(0, 5).Split(' '); if (parts.Length != 2) { - if (log.IsWarnEnabled) - log.Warn("Unknow response: " + line); + if (_log.IsWarnEnabled) + _log.Warn("Unknow response: " + line); continue; } @@ -108,7 +108,7 @@ protected internal override ValueTask ReadResponseAsync(Pooled serverData[parts[0]] = parts[1]; } - this.result = serverData; + _result = serverData; return new ValueTask(new TextOperationResult().Pass()); } diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperation.cs b/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperation.cs index 3aa41eb7..44d6fdd2 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperation.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperation.cs @@ -5,21 +5,21 @@ namespace Enyim.Caching.Memcached.Protocol.Text { - public class StoreOperation : StoreOperationBase, IStoreOperation - { - private StoreMode mode; + public class StoreOperation : StoreOperationBase, IStoreOperation + { + private StoreMode _mode; - internal StoreOperation(StoreMode mode, string key, CacheItem value, uint expires) - : base((StoreCommand)mode, key, value, expires, 0) - { - this.mode = mode; - } + internal StoreOperation(StoreMode mode, string key, CacheItem value, uint expires) + : base((StoreCommand)mode, key, value, expires, 0) + { + _mode = mode; + } - StoreMode IStoreOperation.Mode - { - get { return this.mode; } - } - } + StoreMode IStoreOperation.Mode + { + get { return _mode; } + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperationBase.cs b/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperationBase.cs index 545545de..248d8786 100644 --- a/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperationBase.cs +++ b/src/Enyim.Caching/Memcached/Protocol/Text/StoreOperationBase.cs @@ -9,19 +9,19 @@ namespace Enyim.Caching.Memcached.Protocol.Text { public class StoreOperationBase : SingleItemOperation { - private static readonly ArraySegment DataTerminator = new ArraySegment(new byte[2] { (byte)'\r', (byte)'\n' }); - private readonly StoreCommand command; - private CacheItem value; - private readonly uint expires; - private readonly ulong cas; + private static readonly ArraySegment _dataTerminator = new ArraySegment(new byte[2] { (byte)'\r', (byte)'\n' }); + private readonly StoreCommand _command; + private CacheItem _value; + private readonly uint _expires; + private readonly ulong _cas; internal StoreOperationBase(StoreCommand mode, string key, CacheItem value, uint expires, ulong cas) : base(key) { - this.command = mode; - this.value = value; - this.expires = expires; - this.cas = cas; + _command = mode; + _value = value; + _expires = expires; + _cas = cas; } protected internal override System.Collections.Generic.IList> GetBuffer() @@ -30,7 +30,7 @@ protected internal override System.Collections.Generic.IList> var sb = new StringBuilder(128); var buffers = new List>(3); - switch (this.command) + switch (_command) { case StoreCommand.Add: sb.Append("add "); break; case StoreCommand.Replace: sb.Append("replace "); break; @@ -38,30 +38,30 @@ protected internal override System.Collections.Generic.IList> case StoreCommand.Append: sb.Append("append "); break; case StoreCommand.Prepend: sb.Append("prepend "); break; case StoreCommand.CheckAndSet: sb.Append("cas "); break; - default: throw new MemcachedClientException(command + " is not supported."); + default: throw new MemcachedClientException(_command + " is not supported."); } - sb.Append(this.Key); + sb.Append(Key); sb.Append(" "); - sb.Append(this.value.Flags.ToString(CultureInfo.InvariantCulture)); + sb.Append(_value.Flags.ToString(CultureInfo.InvariantCulture)); sb.Append(" "); - sb.Append(this.expires.ToString(CultureInfo.InvariantCulture)); + sb.Append(_expires.ToString(CultureInfo.InvariantCulture)); sb.Append(" "); - var data = this.value.Data; + var data = _value.Data; sb.Append(Convert.ToString(data.Count, CultureInfo.InvariantCulture)); - if (command == StoreCommand.CheckAndSet) + if (_command == StoreCommand.CheckAndSet) { sb.Append(" "); - sb.Append(Convert.ToString(this.cas, CultureInfo.InvariantCulture)); + sb.Append(Convert.ToString(_cas, CultureInfo.InvariantCulture)); } sb.Append(TextSocketHelper.CommandTerminator); TextSocketHelper.GetCommandBuffer(sb.ToString(), buffers); buffers.Add(data); - buffers.Add(StoreOperationBase.DataTerminator); + buffers.Add(StoreOperationBase._dataTerminator); return buffers; } diff --git a/src/Enyim.Caching/Memcached/ServerStats.cs b/src/Enyim.Caching/Memcached/ServerStats.cs index 24deacc3..4e1d8460 100755 --- a/src/Enyim.Caching/Memcached/ServerStats.cs +++ b/src/Enyim.Caching/Memcached/ServerStats.cs @@ -5,175 +5,175 @@ namespace Enyim.Caching.Memcached { - /// - /// Represents the statistics of a Memcached node. - /// - public sealed class ServerStats - { - private const int OpAllowsSum = 1; - private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(ServerStats)); - - /// - /// Defines a value which indicates that the statstics should be retrieved for all servers in the pool. - /// - public static readonly EndPoint All = new IPEndPoint(IPAddress.Any, 0); - #region [ readonly int[] Optable ] - // defines which values can be summed and which not - private static readonly int[] Optable = - { - 0, 0, 0, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1 - }; - #endregion - #region [ readonly string[] StatKeys ] - private static readonly string[] StatKeys = - { - "uptime", - "time", - "version", - "curr_items", - "total_items", - "curr_connections", - "total_connections", - "connection_structures", - "cmd_get", - "cmd_set", - "get_hits", - "get_misses", - "bytes", - "bytes_read", - "bytes_written", - "limit_maxbytes", - }; - #endregion - - private Dictionary> results; - - internal ServerStats(Dictionary> results) - { - this.results = results; - } - - /// - /// Gets a stat value for the specified server. - /// - /// The adress of the server. If is specified it will return the sum of all server stat values. - /// The stat to be returned - /// The value of the specified stat item - public long GetValue(IPEndPoint server, StatItem item) - { - // asked for a specific server - if (server.Address != IPAddress.Any) - { - // error check - string tmp = GetRaw(server, item); - if (String.IsNullOrEmpty(tmp)) - throw new ArgumentException("Item was not found: " + item); - - long value; - // return the value - if (Int64.TryParse(tmp, out value)) - return value; - - throw new ArgumentException("Invalid value string was returned: " + tmp); - } - - // check if we can sum the value for all servers - if ((Optable[(int)item] & OpAllowsSum) != OpAllowsSum) - throw new ArgumentException("The " + item + " values cannot be summarized"); - - long retval = 0; - - // sum & return - foreach (IPEndPoint ep in this.results.Keys) - { - retval += this.GetValue(ep, item); - } - - return retval; - } - - /// - /// Returns the server of memcached running on the specified server. - /// - /// The adress of the server - /// The version of memcached - public Version GetVersion(IPEndPoint server) - { - string version = GetRaw(server, StatItem.Version); - if (String.IsNullOrEmpty(version)) - throw new ArgumentException("No version found for the server " + server); - - return new Version(version); - } - - /// - /// Returns the uptime of the specific server. - /// - /// The adress of the server - /// A value indicating how long the server is running - public TimeSpan GetUptime(IPEndPoint server) - { - string uptime = GetRaw(server, StatItem.Uptime); - if (String.IsNullOrEmpty(uptime)) - throw new ArgumentException("No uptime found for the server " + server); - - long value; - if (!Int64.TryParse(uptime, out value)) - throw new ArgumentException("Invalid uptime string was returned: " + uptime); - - return TimeSpan.FromSeconds(value); - } - - /// - /// Returns the stat value for a specific server. The value is not converted but returned as the server returned it. - /// - /// The adress of the server - /// The name of the stat value - /// The value of the stat item - public string GetRaw(IPEndPoint server, string key) - { - Dictionary serverValues; - string retval; - - if (this.results.TryGetValue(server, out serverValues)) - { - if (serverValues.TryGetValue(key, out retval)) - return retval; - - if (log.IsDebugEnabled) - log.DebugFormat("The stat item {0} does not exist for {1}", key, server); - } - else - { - if (log.IsDebugEnabled) - log.DebugFormat("No stats are stored for {0}", server); - } - - return null; - } - - /// - /// Returns the stat value for a specific server. The value is not converted but returned as the server returned it. - /// - /// The adress of the server - /// The stat value to be returned - /// The value of the stat item - public string GetRaw(IPEndPoint server, StatItem item) - { - if ((int)item < StatKeys.Length && (int)item >= 0) - return GetRaw(server, StatKeys[(int)item]); - - throw new ArgumentOutOfRangeException("item"); - } - - public IEnumerable> GetRaw(string key) - { - string tmp; - - return this.results.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.TryGetValue(key, out tmp) ? tmp : null)).ToList(); - } - } + /// + /// Represents the statistics of a Memcached node. + /// + public sealed class ServerStats + { + private const int _opAllowsSum = 1; + private static readonly ILog _log = LogManager.GetLogger(typeof(ServerStats)); + + /// + /// Defines a value which indicates that the statstics should be retrieved for all servers in the pool. + /// + public static readonly EndPoint All = new IPEndPoint(IPAddress.Any, 0); + #region [ readonly int[] Optable ] + // defines which values can be summed and which not + private static readonly int[] Optable = + { + 0, 0, 0, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1 + }; + #endregion + #region [ readonly string[] StatKeys ] + private static readonly string[] StatKeys = + { + "uptime", + "time", + "version", + "curr_items", + "total_items", + "curr_connections", + "total_connections", + "connection_structures", + "cmd_get", + "cmd_set", + "get_hits", + "get_misses", + "bytes", + "bytes_read", + "bytes_written", + "limit_maxbytes", + }; + #endregion + + private Dictionary> _results; + + internal ServerStats(Dictionary> results) + { + _results = results; + } + + /// + /// Gets a stat value for the specified server. + /// + /// The adress of the server. If is specified it will return the sum of all server stat values. + /// The stat to be returned + /// The value of the specified stat item + public long GetValue(IPEndPoint server, StatItem item) + { + // asked for a specific server + if (server.Address != IPAddress.Any) + { + // error check + string tmp = GetRaw(server, item); + if (String.IsNullOrEmpty(tmp)) + throw new ArgumentException("Item was not found: " + item); + + long value; + // return the value + if (Int64.TryParse(tmp, out value)) + return value; + + throw new ArgumentException("Invalid value string was returned: " + tmp); + } + + // check if we can sum the value for all servers + if ((Optable[(int)item] & _opAllowsSum) != _opAllowsSum) + throw new ArgumentException("The " + item + " values cannot be summarized"); + + long retval = 0; + + // sum & return + foreach (IPEndPoint ep in _results.Keys) + { + retval += GetValue(ep, item); + } + + return retval; + } + + /// + /// Returns the server of memcached running on the specified server. + /// + /// The adress of the server + /// The version of memcached + public Version GetVersion(IPEndPoint server) + { + string version = GetRaw(server, StatItem.Version); + if (String.IsNullOrEmpty(version)) + throw new ArgumentException("No version found for the server " + server); + + return new Version(version); + } + + /// + /// Returns the uptime of the specific server. + /// + /// The adress of the server + /// A value indicating how long the server is running + public TimeSpan GetUptime(IPEndPoint server) + { + string uptime = GetRaw(server, StatItem.Uptime); + if (String.IsNullOrEmpty(uptime)) + throw new ArgumentException("No uptime found for the server " + server); + + long value; + if (!Int64.TryParse(uptime, out value)) + throw new ArgumentException("Invalid uptime string was returned: " + uptime); + + return TimeSpan.FromSeconds(value); + } + + /// + /// Returns the stat value for a specific server. The value is not converted but returned as the server returned it. + /// + /// The adress of the server + /// The name of the stat value + /// The value of the stat item + public string GetRaw(IPEndPoint server, string key) + { + Dictionary serverValues; + string retval; + + if (_results.TryGetValue(server, out serverValues)) + { + if (serverValues.TryGetValue(key, out retval)) + return retval; + + if (_log.IsDebugEnabled) + _log.DebugFormat("The stat item {0} does not exist for {1}", key, server); + } + else + { + if (_log.IsDebugEnabled) + _log.DebugFormat("No stats are stored for {0}", server); + } + + return null; + } + + /// + /// Returns the stat value for a specific server. The value is not converted but returned as the server returned it. + /// + /// The adress of the server + /// The stat value to be returned + /// The value of the stat item + public string GetRaw(IPEndPoint server, StatItem item) + { + if ((int)item < StatKeys.Length && (int)item >= 0) + return GetRaw(server, StatKeys[(int)item]); + + throw new ArgumentOutOfRangeException("item"); + } + + public IEnumerable> GetRaw(string key) + { + string tmp; + + return _results.Select(kvp => new KeyValuePair(kvp.Key, kvp.Value.TryGetValue(key, out tmp) ? tmp : null)).ToList(); + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/SlidingBuffer.cs b/src/Enyim.Caching/Memcached/SlidingBuffer.cs index 265e0cfb..fcbebb1d 100644 --- a/src/Enyim.Caching/Memcached/SlidingBuffer.cs +++ b/src/Enyim.Caching/Memcached/SlidingBuffer.cs @@ -5,137 +5,137 @@ namespace Enyim.Caching.Memcached { - /// - /// Supports exactly one reader and writer, but they can access the buffer concurrently. - /// - internal class SlidingBuffer - { - private readonly InterlockedQueue buffers; - private readonly int chunkSize; - private Segment lastSegment; - private int available; - - public SlidingBuffer(int chunkSize) - { - this.chunkSize = chunkSize; - this.buffers = new InterlockedQueue(); - } - - public int Available { get { return this.available; } } - - public int Read(byte[] buffer, int offset, int count) - { - var read = 0; - Segment segment; - - while (read < count && this.buffers.Peek(out segment)) - { - var available = Math.Min(segment.WriteOffset - segment.ReadOffset, count - read); - - if (available > 0) - { - System.Buffer.BlockCopy(segment.Data, segment.ReadOffset, buffer, offset + read, available); - - read += available; - segment.ReadOffset += available; - } - - // are we at the end of the segment? - if (segment.ReadOffset == segment.WriteOffset) - { - // we can dispose the current segment if it's not the last - // (which is probably being written by the receiver) - if (this.lastSegment != segment) - { - this.buffers.Dequeue(out segment); - //Debug.Assert(success, "Could peek but could not dequeue?"); - - //bufferManager.ReturnBuffer(segment.Data); - } - } - } - - Interlocked.Add(ref this.available, -read); - - return read; - } - - public void Append(byte[] buffer, int offset, int count) - { - if (buffer == null || buffer.Length == 0 || count == 0) return; - - // try to append the data to the last segment - // if the data is larger than the ChunkSize we copy it and append it as one chunk - // if the data does not fit into the last segment we allocate a new - // so data is never split (at the price of some wasted bytes) - var last = this.lastSegment; - var shouldQueue = false; - - if (count > this.chunkSize) - { - // big data, append it - last = new Segment(new byte[count]);// bufferManager.TakeBuffer(count)); - shouldQueue = true; - } - else - { - var remaining = (last == null) - ? 0 - : last.Data.Length - last.WriteOffset; - - // no space, create a new chunk - if (remaining < count) - { - last = new Segment(new byte[this.chunkSize]);//bufferManager.TakeBuffer(this.chunkSize)); - shouldQueue = true; - } - } - - System.Buffer.BlockCopy(buffer, offset, last.Data, last.WriteOffset, count); - - // first we update the lastSegment reference, then we enque the new segment - // this way Read can safely dequeue (discard) the last item it processed and - // continue on the next one - // doing it in reverse would make Read dequeue the current segment (the one we just inserted) - if (shouldQueue) - { - Interlocked.Exchange(ref this.lastSegment, last); - this.buffers.Enqueue(last); - } - - // advertise that we have more data available for reading - // we have to use Interlocked because in the same time the reader - // can remove data and will decrease the value of Available - Interlocked.Add(ref last.WriteOffset, count); - Interlocked.Add(ref this.available, count); - } - - public void UnsafeClear() - { - Segment tmp; - - this.lastSegment = null; - while (this.buffers.Dequeue(out tmp)) ; - - this.available = 0; - } - - #region [ Segment ] - - private class Segment - { - public Segment(byte[] data) - { - this.Data = data; - } - - public readonly byte[] Data; - public int WriteOffset; - public int ReadOffset; - } - - #endregion - } + /// + /// Supports exactly one reader and writer, but they can access the buffer concurrently. + /// + internal class SlidingBuffer + { + private readonly InterlockedQueue _buffers; + private readonly int _chunkSize; + private Segment _lastSegment; + private int _available; + + public SlidingBuffer(int chunkSize) + { + _chunkSize = chunkSize; + _buffers = new InterlockedQueue(); + } + + public int Available { get { return _available; } } + + public int Read(byte[] buffer, int offset, int count) + { + var read = 0; + Segment segment; + + while (read < count && _buffers.Peek(out segment)) + { + var available = Math.Min(segment.WriteOffset - segment.ReadOffset, count - read); + + if (available > 0) + { + System.Buffer.BlockCopy(segment.Data, segment.ReadOffset, buffer, offset + read, available); + + read += available; + segment.ReadOffset += available; + } + + // are we at the end of the segment? + if (segment.ReadOffset == segment.WriteOffset) + { + // we can dispose the current segment if it's not the last + // (which is probably being written by the receiver) + if (_lastSegment != segment) + { + _buffers.Dequeue(out segment); + //Debug.Assert(success, "Could peek but could not dequeue?"); + + //bufferManager.ReturnBuffer(segment.Data); + } + } + } + + Interlocked.Add(ref _available, -read); + + return read; + } + + public void Append(byte[] buffer, int offset, int count) + { + if (buffer == null || buffer.Length == 0 || count == 0) return; + + // try to append the data to the last segment + // if the data is larger than the ChunkSize we copy it and append it as one chunk + // if the data does not fit into the last segment we allocate a new + // so data is never split (at the price of some wasted bytes) + var last = _lastSegment; + var shouldQueue = false; + + if (count > _chunkSize) + { + // big data, append it + last = new Segment(new byte[count]);// bufferManager.TakeBuffer(count)); + shouldQueue = true; + } + else + { + var remaining = (last == null) + ? 0 + : last.Data.Length - last.WriteOffset; + + // no space, create a new chunk + if (remaining < count) + { + last = new Segment(new byte[_chunkSize]); // bufferManager.TakeBuffer(_chunkSize)); + shouldQueue = true; + } + } + + System.Buffer.BlockCopy(buffer, offset, last.Data, last.WriteOffset, count); + + // first we update the lastSegment reference, then we enque the new segment + // this way Read can safely dequeue (discard) the last item it processed and + // continue on the next one + // doing it in reverse would make Read dequeue the current segment (the one we just inserted) + if (shouldQueue) + { + Interlocked.Exchange(ref _lastSegment, last); + _buffers.Enqueue(last); + } + + // advertise that we have more data available for reading + // we have to use Interlocked because in the same time the reader + // can remove data and will decrease the value of Available + Interlocked.Add(ref last.WriteOffset, count); + Interlocked.Add(ref _available, count); + } + + public void UnsafeClear() + { + Segment tmp; + + _lastSegment = null; + while (_buffers.Dequeue(out tmp)) ; + + _available = 0; + } + + #region [ Segment ] + + private class Segment + { + public Segment(byte[] data) + { + Data = data; + } + + public readonly byte[] Data; + public int WriteOffset; + public int ReadOffset; + } + + #endregion + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/Transcoders/CacheItem.cs b/src/Enyim.Caching/Memcached/Transcoders/CacheItem.cs index fc1e680a..d1fe6122 100755 --- a/src/Enyim.Caching/Memcached/Transcoders/CacheItem.cs +++ b/src/Enyim.Caching/Memcached/Transcoders/CacheItem.cs @@ -2,44 +2,44 @@ namespace Enyim.Caching.Memcached { - /// - /// Represents an object either being retrieved from the cache - /// or being sent to the cache. - /// - public struct CacheItem - { - private ArraySegment data; - private uint flags; + /// + /// Represents an object either being retrieved from the cache + /// or being sent to the cache. + /// + public struct CacheItem + { + private ArraySegment _data; + private uint _flags; - /// - /// Initializes a new instance of . - /// - /// Custom item data. - /// The serialized item. - public CacheItem(uint flags, ArraySegment data) - { - this.data = data; - this.flags = flags; - } + /// + /// Initializes a new instance of . + /// + /// Custom item data. + /// The serialized item. + public CacheItem(uint flags, ArraySegment data) + { + _data = data; + _flags = flags; + } - /// - /// The data representing the item being stored/retireved. - /// - public ArraySegment Data - { - get { return this.data; } - set { this.data = value; } - } + /// + /// The data representing the item being stored/retireved. + /// + public ArraySegment Data + { + get { return _data; } + set { _data = value; } + } - /// - /// Flags set for this instance. - /// - public uint Flags - { - get { return this.flags; } - set { this.flags = value; } - } - } + /// + /// Flags set for this instance. + /// + public uint Flags + { + get { return _flags; } + set { _flags = value; } + } + } } #region [ License information ] diff --git a/src/Enyim.Caching/Memcached/Transcoders/DefaultTranscoder.cs b/src/Enyim.Caching/Memcached/Transcoders/DefaultTranscoder.cs index e8e64c7f..ceaad0b2 100755 --- a/src/Enyim.Caching/Memcached/Transcoders/DefaultTranscoder.cs +++ b/src/Enyim.Caching/Memcached/Transcoders/DefaultTranscoder.cs @@ -20,12 +20,12 @@ public class DefaultTranscoder : ITranscoder CacheItem ITranscoder.Serialize(object value) { - return this.Serialize(value); + return Serialize(value); } object ITranscoder.Deserialize(CacheItem item) { - return this.Deserialize(item); + return Deserialize(item); } public virtual T Deserialize(CacheItem item) @@ -37,7 +37,7 @@ public virtual T Deserialize(CacheItem item) { if (typeof(T) == typeof(Guid)) { - return (T)(object)new Guid((string)value); + return (T)(object)new Guid((string)value); } else { @@ -89,24 +89,24 @@ protected virtual CacheItem Serialize(object value) switch (code) { - case (TypeCode)2: data = this.SerializeNull(); break; // TypeCode.DBNull - case TypeCode.String: data = this.SerializeString(value.ToString()); break; - case TypeCode.Boolean: data = this.SerializeBoolean((Boolean)value); break; - case TypeCode.SByte: data = this.SerializeSByte((SByte)value); break; - case TypeCode.Byte: data = this.SerializeByte((Byte)value); break; - case TypeCode.Int16: data = this.SerializeInt16((Int16)value); break; - case TypeCode.Int32: data = this.SerializeInt32((Int32)value); break; - case TypeCode.Int64: data = this.SerializeInt64((Int64)value); break; - case TypeCode.UInt16: data = this.SerializeUInt16((UInt16)value); break; - case TypeCode.UInt32: data = this.SerializeUInt32((UInt32)value); break; - case TypeCode.UInt64: data = this.SerializeUInt64((UInt64)value); break; - case TypeCode.Char: data = this.SerializeChar((Char)value); break; - case TypeCode.DateTime: data = this.SerializeDateTime((DateTime)value); break; - case TypeCode.Double: data = this.SerializeDouble((Double)value); break; - case TypeCode.Single: data = this.SerializeSingle((Single)value); break; + case (TypeCode)2: data = SerializeNull(); break; // TypeCode.DBNull + case TypeCode.String: data = SerializeString(value.ToString()); break; + case TypeCode.Boolean: data = SerializeBoolean((Boolean)value); break; + case TypeCode.SByte: data = SerializeSByte((SByte)value); break; + case TypeCode.Byte: data = SerializeByte((Byte)value); break; + case TypeCode.Int16: data = SerializeInt16((Int16)value); break; + case TypeCode.Int32: data = SerializeInt32((Int32)value); break; + case TypeCode.Int64: data = SerializeInt64((Int64)value); break; + case TypeCode.UInt16: data = SerializeUInt16((UInt16)value); break; + case TypeCode.UInt32: data = SerializeUInt32((UInt32)value); break; + case TypeCode.UInt64: data = SerializeUInt64((UInt64)value); break; + case TypeCode.Char: data = SerializeChar((Char)value); break; + case TypeCode.DateTime: data = SerializeDateTime((DateTime)value); break; + case TypeCode.Double: data = SerializeDouble((Double)value); break; + case TypeCode.Single: data = SerializeSingle((Single)value); break; default: code = TypeCode.Object; - data = this.SerializeObject(value); + data = SerializeObject(value); break; } @@ -163,26 +163,26 @@ protected virtual object Deserialize(CacheItem item) : DeserializeString(data); case (TypeCode)2: return null; // TypeCode.DBNull - case TypeCode.String: return this.DeserializeString(data); - case TypeCode.Boolean: return this.DeserializeBoolean(data); - case TypeCode.Int16: return this.DeserializeInt16(data); - case TypeCode.Int32: return this.DeserializeInt32(data); - case TypeCode.Int64: return this.DeserializeInt64(data); - case TypeCode.UInt16: return this.DeserializeUInt16(data); - case TypeCode.UInt32: return this.DeserializeUInt32(data); - case TypeCode.UInt64: return this.DeserializeUInt64(data); - case TypeCode.Char: return this.DeserializeChar(data); - case TypeCode.DateTime: return this.DeserializeDateTime(data); - case TypeCode.Double: return this.DeserializeDouble(data); - case TypeCode.Single: return this.DeserializeSingle(data); - case TypeCode.Byte: return this.DeserializeByte(data); - case TypeCode.SByte: return this.DeserializeSByte(data); + case TypeCode.String: return DeserializeString(data); + case TypeCode.Boolean: return DeserializeBoolean(data); + case TypeCode.Int16: return DeserializeInt16(data); + case TypeCode.Int32: return DeserializeInt32(data); + case TypeCode.Int64: return DeserializeInt64(data); + case TypeCode.UInt16: return DeserializeUInt16(data); + case TypeCode.UInt32: return DeserializeUInt32(data); + case TypeCode.UInt64: return DeserializeUInt64(data); + case TypeCode.Char: return DeserializeChar(data); + case TypeCode.DateTime: return DeserializeDateTime(data); + case TypeCode.Double: return DeserializeDouble(data); + case TypeCode.Single: return DeserializeSingle(data); + case TypeCode.Byte: return DeserializeByte(data); + case TypeCode.SByte: return DeserializeSByte(data); // backward compatibility // earlier versions serialized decimals with TypeCode.Decimal // even though they were saved by BinaryFormatter case TypeCode.Decimal: - case TypeCode.Object: return this.DeserializeObject(data); + case TypeCode.Object: return DeserializeObject(data); default: throw new InvalidOperationException("Unknown TypeCode was returned: " + code); } } diff --git a/src/Enyim.Caching/MemcachedClient.Results.cs b/src/Enyim.Caching/MemcachedClient.Results.cs index eebf1afd..086b4d7b 100644 --- a/src/Enyim.Caching/MemcachedClient.Results.cs +++ b/src/Enyim.Caching/MemcachedClient.Results.cs @@ -10,141 +10,141 @@ namespace Enyim.Caching { - public partial class MemcachedClient : IMemcachedClient, IMemcachedResultsClient - { - #region [ Store ] - - /// - /// Inserts an item into the cache with a cache key to reference its location. - /// - /// Defines how the item is stored in the cache. - /// The key used to reference the item. - /// The object to be inserted into the cache. - /// The item does not expire unless it is removed due memory pressure. - /// true if the item was successfully stored in the cache; false otherwise. - public IStoreOperationResult ExecuteStore(StoreMode mode, string key, object value) - { - ulong tmp = 0; - int status; - - return this.PerformStore(mode, key, value, 0, ref tmp, out status); - } - - /// - /// Inserts an item into the cache with a cache key to reference its location. - /// - /// Defines how the item is stored in the cache. - /// The key used to reference the item. - /// The object to be inserted into the cache. - /// The interval after the item is invalidated in the cache. - /// true if the item was successfully stored in the cache; false otherwise. - public IStoreOperationResult ExecuteStore(StoreMode mode, string key, object value, TimeSpan validFor) - { - ulong tmp = 0; - int status; - - return this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), ref tmp, out status); - } - - /// - /// Inserts an item into the cache with a cache key to reference its location. - /// - /// Defines how the item is stored in the cache. - /// The key used to reference the item. - /// The object to be inserted into the cache. - /// The time when the item is invalidated in the cache. - /// true if the item was successfully stored in the cache; false otherwise. - public IStoreOperationResult ExecuteStore(StoreMode mode, string key, object value, DateTime expiresAt) - { - ulong tmp = 0; - int status; - - return this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), ref tmp, out status); - } - - #endregion - - #region [ Cas ] - /// - /// Inserts an item into the cache with a cache key to reference its location and returns its version. - /// - /// Defines how the item is stored in the cache. - /// The key used to reference the item. - /// The object to be inserted into the cache. - /// The item does not expire unless it is removed due memory pressure. The text protocol does not support this operation, you need to Store then GetWithCas. - /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). - public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value) - { - return this.PerformStore(mode, key, value, 0, 0); - } - - /// - /// Inserts an item into the cache with a cache key to reference its location and returns its version. - /// - /// Defines how the item is stored in the cache. - /// The key used to reference the item. - /// The object to be inserted into the cache. - /// The item does not expire unless it is removed due memory pressure. - /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). - public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value, ulong cas) - { - return this.PerformStore(mode, key, value, 0, cas); - } - - /// - /// Inserts an item into the cache with a cache key to reference its location and returns its version. - /// - /// Defines how the item is stored in the cache. - /// The key used to reference the item. - /// The object to be inserted into the cache. - /// The interval after the item is invalidated in the cache. - /// The cas value which must match the item's version. - /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). - public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value, TimeSpan validFor, ulong cas) - { - return this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), cas); - } - - /// - /// Inserts an item into the cache with a cache key to reference its location and returns its version. - /// - /// Defines how the item is stored in the cache. - /// The key used to reference the item. - /// The object to be inserted into the cache. - /// The time when the item is invalidated in the cache. - /// The cas value which must match the item's version. - /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). - public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value, DateTime expiresAt, ulong cas) - { - return this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), cas); - } - #endregion - - #region [ Get ] - - /// - /// Retrieves the specified item from the cache. - /// - /// The identifier for the item to retrieve. - /// The retrieved item, or null if the key was not found. - public IGetOperationResult ExecuteGet(string key) - { - object tmp; - - return this.ExecuteTryGet(key, out tmp); - } - - /// - /// Tries to get an item from the cache. - /// - /// The identifier for the item to retrieve. - /// The retrieved item or null if not found. - /// The true if the item was successfully retrieved. - public IGetOperationResult ExecuteTryGet(string key, out object value) - { - ulong cas = 0; - - return this.PerformTryGet(key, out cas, out value); + public partial class MemcachedClient : IMemcachedClient, IMemcachedResultsClient + { + #region [ Store ] + + /// + /// Inserts an item into the cache with a cache key to reference its location. + /// + /// Defines how the item is stored in the cache. + /// The key used to reference the item. + /// The object to be inserted into the cache. + /// The item does not expire unless it is removed due memory pressure. + /// true if the item was successfully stored in the cache; false otherwise. + public IStoreOperationResult ExecuteStore(StoreMode mode, string key, object value) + { + ulong tmp = 0; + int status; + + return PerformStore(mode, key, value, 0, ref tmp, out status); + } + + /// + /// Inserts an item into the cache with a cache key to reference its location. + /// + /// Defines how the item is stored in the cache. + /// The key used to reference the item. + /// The object to be inserted into the cache. + /// The interval after the item is invalidated in the cache. + /// true if the item was successfully stored in the cache; false otherwise. + public IStoreOperationResult ExecuteStore(StoreMode mode, string key, object value, TimeSpan validFor) + { + ulong tmp = 0; + int status; + + return PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), ref tmp, out status); + } + + /// + /// Inserts an item into the cache with a cache key to reference its location. + /// + /// Defines how the item is stored in the cache. + /// The key used to reference the item. + /// The object to be inserted into the cache. + /// The time when the item is invalidated in the cache. + /// true if the item was successfully stored in the cache; false otherwise. + public IStoreOperationResult ExecuteStore(StoreMode mode, string key, object value, DateTime expiresAt) + { + ulong tmp = 0; + int status; + + return PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), ref tmp, out status); + } + + #endregion + + #region [ Cas ] + /// + /// Inserts an item into the cache with a cache key to reference its location and returns its version. + /// + /// Defines how the item is stored in the cache. + /// The key used to reference the item. + /// The object to be inserted into the cache. + /// The item does not expire unless it is removed due memory pressure. The text protocol does not support this operation, you need to Store then GetWithCas. + /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). + public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value) + { + return PerformStore(mode, key, value, 0, 0); + } + + /// + /// Inserts an item into the cache with a cache key to reference its location and returns its version. + /// + /// Defines how the item is stored in the cache. + /// The key used to reference the item. + /// The object to be inserted into the cache. + /// The item does not expire unless it is removed due memory pressure. + /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). + public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value, ulong cas) + { + return PerformStore(mode, key, value, 0, cas); + } + + /// + /// Inserts an item into the cache with a cache key to reference its location and returns its version. + /// + /// Defines how the item is stored in the cache. + /// The key used to reference the item. + /// The object to be inserted into the cache. + /// The interval after the item is invalidated in the cache. + /// The cas value which must match the item's version. + /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). + public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value, TimeSpan validFor, ulong cas) + { + return PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), cas); + } + + /// + /// Inserts an item into the cache with a cache key to reference its location and returns its version. + /// + /// Defines how the item is stored in the cache. + /// The key used to reference the item. + /// The object to be inserted into the cache. + /// The time when the item is invalidated in the cache. + /// The cas value which must match the item's version. + /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). + public IStoreOperationResult ExecuteCas(StoreMode mode, string key, object value, DateTime expiresAt, ulong cas) + { + return PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), cas); + } + #endregion + + #region [ Get ] + + /// + /// Retrieves the specified item from the cache. + /// + /// The identifier for the item to retrieve. + /// The retrieved item, or null if the key was not found. + public IGetOperationResult ExecuteGet(string key) + { + object tmp; + + return ExecuteTryGet(key, out tmp); + } + + /// + /// Tries to get an item from the cache. + /// + /// The identifier for the item to retrieve. + /// The retrieved item or null if not found. + /// The true if the item was successfully retrieved. + public IGetOperationResult ExecuteTryGet(string key, out object value) + { + ulong cas = 0; + + return PerformTryGet(key, out cas, out value); } /// @@ -157,7 +157,7 @@ public IGetOperationResult ExecuteTryGet(string key, out T value) { ulong cas = 0; - return this.PerformTryGet(key, out cas, out value); + return PerformTryGet(key, out cas, out value); } /// @@ -166,332 +166,332 @@ public IGetOperationResult ExecuteTryGet(string key, out T value) /// The identifier for the item to retrieve. /// The retrieved item, or default(T) if the key was not found. public IGetOperationResult ExecuteGet(string key) - { + { T tmp; - var result = new DefaultGetOperationResultFactory().Create(); - - var tryGetResult = ExecuteTryGet(key, out tmp); - if (tryGetResult.Success) - { - if (tryGetResult.Value is T) - { - //HACK: this isn't optimal - tryGetResult.Copy(result); - - result.Value = (T)tmp; - result.Cas = tryGetResult.Cas; - } - else - { - result.Value = default(T); - result.Fail("Type mismatch", new InvalidCastException()); - } - return result; - } - tryGetResult.Combine(result); - return result; - } - - /// - /// Retrieves multiple items from the cache. - /// - /// The list of identifiers for the items to retrieve. - /// a Dictionary holding all items indexed by their key. - public IDictionary ExecuteGet(IEnumerable keys) - { - return PerformMultiGet(keys, (mget, kvp) => - { - var result = GetOperationResultFactory.Create(); - result.Value = this.transcoder.Deserialize(kvp.Value); - result.Cas = mget.Cas[kvp.Key]; - result.Success = true; - return result; - }); - } - - #endregion - - #region [ Mutate ] - /// - /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to increase the item. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta) - { - return this.PerformMutate(MutationMode.Increment, key, defaultValue, delta, 0); - } - - /// - /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to increase the item. - /// The interval after the item is invalidated in the cache. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor) - { - return this.PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)); - } - - /// - /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to increase the item. - /// The time when the item is invalidated in the cache. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt) - { - return this.PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)); - } - - /// - /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to increase the item. - /// The cas value which must match the item's version. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, ulong cas) - { - return this.CasMutate(MutationMode.Increment, key, defaultValue, delta, 0, cas); - } - - /// - /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to increase the item. - /// The interval after the item is invalidated in the cache. - /// The cas value which must match the item's version. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas) - { - return this.CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); - } - - /// - /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to increase the item. - /// The time when the item is invalidated in the cache. - /// The cas value which must match the item's version. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas) - { - return this.CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); - } - - /// - /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to decrease the item. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta) - { - return this.PerformMutate(MutationMode.Decrement, key, defaultValue, delta, 0); - } - - /// - /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to decrease the item. - /// The interval after the item is invalidated in the cache. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor) - { - return this.PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)); - } - - /// - /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to decrease the item. - /// The time when the item is invalidated in the cache. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt) - { - return this.PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)); - } - - /// - /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to decrease the item. - /// The cas value which must match the item's version. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, ulong cas) - { - return this.CasMutate(MutationMode.Decrement, key, defaultValue, delta, 0, cas); - } - - /// - /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to decrease the item. - /// The interval after the item is invalidated in the cache. - /// The cas value which must match the item's version. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas) - { - return this.CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); - } - - /// - /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. - /// - /// The key used to reference the item. - /// The value which will be stored by the server if the specified item was not found. - /// The amount by which the client wants to decrease the item. - /// The time when the item is invalidated in the cache. - /// The cas value which must match the item's version. - /// The new value of the item or defaultValue if the key was not found. - /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. - public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas) - { - return this.CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); - } - #endregion - - #region [ Concatenate ] - - /// - /// Appends the data to the end of the specified item's data on the server. - /// - /// The key used to reference the item. - /// The data to be appended to the item. - /// true if the data was successfully stored; false otherwise. - public IConcatOperationResult ExecuteAppend(string key, ArraySegment data) - { - ulong cas = 0; - - return this.PerformConcatenate(ConcatenationMode.Append, key, ref cas, data); - } - - /// - /// Appends the data to the end of the specified item's data on the server, but only if the item's version matches the CAS value provided. - /// - /// The key used to reference the item. - /// The cas value which must match the item's version. - /// The data to be prepended to the item. - /// true if the data was successfully stored; false otherwise. - public IConcatOperationResult ExecuteAppend(string key, ulong cas, ArraySegment data) - { - ulong tmp = cas; - var result = PerformConcatenate(ConcatenationMode.Append, key, ref tmp, data); - if (result.Success) - { - result.Cas = tmp; - } - return result; - } - - /// - /// Inserts the data before the specified item's data on the server. - /// - /// true if the data was successfully stored; false otherwise. - public IConcatOperationResult ExecutePrepend(string key, ArraySegment data) - { - ulong cas = 0; - - return this.PerformConcatenate(ConcatenationMode.Prepend, key, ref cas, data); - } - - /// - /// Inserts the data before the specified item's data on the server, but only if the item's version matches the CAS value provided. - /// - /// The key used to reference the item. - /// The cas value which must match the item's version. - /// The data to be prepended to the item. - /// true if the data was successfully stored; false otherwise. - public IConcatOperationResult ExecutePrepend(string key, ulong cas, ArraySegment data) - { - ulong tmp = cas; - var result = PerformConcatenate(ConcatenationMode.Prepend, key, ref tmp, data); - - if (result.Success) - { - result.Cas = tmp; - } - return result; - } - - #endregion - - #region [ Remove ] - - /// - /// Removes the specified item from the cache. - /// - /// The identifier for the item to delete. - /// true if the item was successfully removed from the cache; false otherwise. - public IRemoveOperationResult ExecuteRemove(string key) - { - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); - var result = RemoveOperationResultFactory.Create(); - - if (node != null) - { - var command = this.pool.OperationFactory.Delete(hashedKey, 0); - var commandResult = node.Execute(command); - - if (commandResult.Success) - { - result.Pass(); - } - else - { - result.InnerResult = commandResult; - result.Fail("Failed to remove item, see InnerResult or StatusCode for details"); - } - - return result; - } - - result.Fail("Unable to locate node"); - return result; - } + var result = new DefaultGetOperationResultFactory().Create(); + + var tryGetResult = ExecuteTryGet(key, out tmp); + if (tryGetResult.Success) + { + if (tryGetResult.Value is T) + { + //HACK: this isn't optimal + tryGetResult.Copy(result); + + result.Value = (T)tmp; + result.Cas = tryGetResult.Cas; + } + else + { + result.Value = default(T); + result.Fail("Type mismatch", new InvalidCastException()); + } + return result; + } + tryGetResult.Combine(result); + return result; + } + + /// + /// Retrieves multiple items from the cache. + /// + /// The list of identifiers for the items to retrieve. + /// a Dictionary holding all items indexed by their key. + public IDictionary ExecuteGet(IEnumerable keys) + { + return PerformMultiGet(keys, (mget, kvp) => + { + var result = GetOperationResultFactory.Create(); + result.Value = _transcoder.Deserialize(kvp.Value); + result.Cas = mget.Cas[kvp.Key]; + result.Success = true; + return result; + }); + } + + #endregion + + #region [ Mutate ] + /// + /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to increase the item. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta) + { + return PerformMutate(MutationMode.Increment, key, defaultValue, delta, 0); + } + + /// + /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to increase the item. + /// The interval after the item is invalidated in the cache. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor) + { + return PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)); + } + + /// + /// Increments the value of the specified key by the given amount. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to increase the item. + /// The time when the item is invalidated in the cache. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt) + { + return PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)); + } + + /// + /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to increase the item. + /// The cas value which must match the item's version. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, ulong cas) + { + return CasMutate(MutationMode.Increment, key, defaultValue, delta, 0, cas); + } + + /// + /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to increase the item. + /// The interval after the item is invalidated in the cache. + /// The cas value which must match the item's version. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas) + { + return CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); + } + + /// + /// Increments the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to increase the item. + /// The time when the item is invalidated in the cache. + /// The cas value which must match the item's version. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteIncrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas) + { + return CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); + } + + /// + /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to decrease the item. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta) + { + return PerformMutate(MutationMode.Decrement, key, defaultValue, delta, 0); + } + + /// + /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to decrease the item. + /// The interval after the item is invalidated in the cache. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor) + { + return PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)); + } + + /// + /// Decrements the value of the specified key by the given amount. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to decrease the item. + /// The time when the item is invalidated in the cache. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt) + { + return PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)); + } + + /// + /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to decrease the item. + /// The cas value which must match the item's version. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, ulong cas) + { + return CasMutate(MutationMode.Decrement, key, defaultValue, delta, 0, cas); + } + + /// + /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to decrease the item. + /// The interval after the item is invalidated in the cache. + /// The cas value which must match the item's version. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas) + { + return CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); + } + + /// + /// Decrements the value of the specified key by the given amount, but only if the item's version matches the CAS value provided. The operation is atomic and happens on the server. + /// + /// The key used to reference the item. + /// The value which will be stored by the server if the specified item was not found. + /// The amount by which the client wants to decrease the item. + /// The time when the item is invalidated in the cache. + /// The cas value which must match the item's version. + /// The new value of the item or defaultValue if the key was not found. + /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. + public IMutateOperationResult ExecuteDecrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas) + { + return CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); + } + #endregion + + #region [ Concatenate ] + + /// + /// Appends the data to the end of the specified item's data on the server. + /// + /// The key used to reference the item. + /// The data to be appended to the item. + /// true if the data was successfully stored; false otherwise. + public IConcatOperationResult ExecuteAppend(string key, ArraySegment data) + { + ulong cas = 0; + + return PerformConcatenate(ConcatenationMode.Append, key, ref cas, data); + } + + /// + /// Appends the data to the end of the specified item's data on the server, but only if the item's version matches the CAS value provided. + /// + /// The key used to reference the item. + /// The cas value which must match the item's version. + /// The data to be prepended to the item. + /// true if the data was successfully stored; false otherwise. + public IConcatOperationResult ExecuteAppend(string key, ulong cas, ArraySegment data) + { + ulong tmp = cas; + var result = PerformConcatenate(ConcatenationMode.Append, key, ref tmp, data); + if (result.Success) + { + result.Cas = tmp; + } + return result; + } + + /// + /// Inserts the data before the specified item's data on the server. + /// + /// true if the data was successfully stored; false otherwise. + public IConcatOperationResult ExecutePrepend(string key, ArraySegment data) + { + ulong cas = 0; + + return PerformConcatenate(ConcatenationMode.Prepend, key, ref cas, data); + } + + /// + /// Inserts the data before the specified item's data on the server, but only if the item's version matches the CAS value provided. + /// + /// The key used to reference the item. + /// The cas value which must match the item's version. + /// The data to be prepended to the item. + /// true if the data was successfully stored; false otherwise. + public IConcatOperationResult ExecutePrepend(string key, ulong cas, ArraySegment data) + { + ulong tmp = cas; + var result = PerformConcatenate(ConcatenationMode.Prepend, key, ref tmp, data); + + if (result.Success) + { + result.Cas = tmp; + } + return result; + } + + #endregion + + #region [ Remove ] + + /// + /// Removes the specified item from the cache. + /// + /// The identifier for the item to delete. + /// true if the item was successfully removed from the cache; false otherwise. + public IRemoveOperationResult ExecuteRemove(string key) + { + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); + var result = RemoveOperationResultFactory.Create(); + + if (node != null) + { + var command = _pool.OperationFactory.Delete(hashedKey, 0); + var commandResult = node.Execute(command); + + if (commandResult.Success) + { + result.Pass(); + } + else + { + result.InnerResult = commandResult; + result.Fail("Failed to remove item, see InnerResult or StatusCode for details"); + } + + return result; + } + + result.Fail("Unable to locate node"); + return result; + } public async Task ExecuteRemoveAsync(string key) { - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = RemoveOperationResultFactory.Create(); if (node != null) { - var command = this.pool.OperationFactory.Delete(hashedKey, 0); + var command = _pool.OperationFactory.Delete(hashedKey, 0); var commandResult = await node.ExecuteAsync(command); if (commandResult.Success) diff --git a/src/Enyim.Caching/MemcachedClient.cs b/src/Enyim.Caching/MemcachedClient.cs index 86242e66..b7bff193 100755 --- a/src/Enyim.Caching/MemcachedClient.cs +++ b/src/Enyim.Caching/MemcachedClient.cs @@ -25,13 +25,12 @@ public partial class MemcachedClient : IMemcachedClient, IMemcachedResultsClient /// Represents a value which indicates that an item should never expire. /// public static readonly TimeSpan Infinite = TimeSpan.Zero; - //internal static readonly MemcachedClientSection DefaultSettings = ConfigurationManager.GetSection("enyim.com/memcached") as MemcachedClientSection; private ILogger _logger; private bool _suppressException; - private IServerPool pool; - private IMemcachedKeyTransformer keyTransformer; - private ITranscoder transcoder; + private IServerPool _pool; + private IMemcachedKeyTransformer _keyTransformer; + private ITranscoder _transcoder; public IStoreOperationResultFactory StoreOperationResultFactory { get; set; } public IGetOperationResultFactory GetOperationResultFactory { get; set; } @@ -39,9 +38,9 @@ public partial class MemcachedClient : IMemcachedClient, IMemcachedResultsClient public IConcatOperationResultFactory ConcatOperationResultFactory { get; set; } public IRemoveOperationResultFactory RemoveOperationResultFactory { get; set; } - protected IServerPool Pool { get { return this.pool; } } - protected IMemcachedKeyTransformer KeyTransformer { get { return this.keyTransformer; } } - protected ITranscoder Transcoder { get { return this.transcoder; } } + protected IServerPool Pool { get { return _pool; } } + protected IMemcachedKeyTransformer KeyTransformer { get { return _keyTransformer; } } + protected ITranscoder Transcoder { get { return _transcoder; } } public MemcachedClient(ILoggerFactory loggerFactory, IMemcachedClientConfiguration configuration) { @@ -53,11 +52,11 @@ public MemcachedClient(ILoggerFactory loggerFactory, IMemcachedClientConfigurati } _suppressException = configuration.SuppressException; - this.keyTransformer = configuration.CreateKeyTransformer() ?? new DefaultKeyTransformer(); - this.transcoder = configuration.CreateTranscoder() ?? new DefaultTranscoder(); + _keyTransformer = configuration.CreateKeyTransformer() ?? new DefaultKeyTransformer(); + _transcoder = configuration.CreateTranscoder() ?? new DefaultTranscoder(); - this.pool = configuration.CreatePool(); - this.StartPool(); + _pool = configuration.CreatePool(); + StartPool(); StoreOperationResultFactory = new DefaultStoreOperationResultFactory(); GetOperationResultFactory = new DefaultGetOperationResultFactory(); @@ -73,17 +72,17 @@ private MemcachedClient(IServerPool pool, IMemcachedKeyTransformer keyTransforme if (keyTransformer == null) throw new ArgumentNullException("keyTransformer"); if (transcoder == null) throw new ArgumentNullException("transcoder"); - this.keyTransformer = keyTransformer; - this.transcoder = transcoder; + _keyTransformer = keyTransformer; + _transcoder = transcoder; - this.pool = pool; - this.StartPool(); + _pool = pool; + StartPool(); } private void StartPool() { - this.pool.NodeFailed += (n) => { var f = this.NodeFailed; if (f != null) f(n); }; - this.pool.Start(); + _pool.NodeFailed += (n) => { var f = NodeFailed; if (f != null) f(n); }; + _pool.Start(); } public event Action NodeFailed; @@ -187,7 +186,7 @@ public object Get(string key) { object tmp; - return this.TryGet(key, out tmp) ? tmp : null; + return TryGet(key, out tmp) ? tmp : null; } /// @@ -228,9 +227,9 @@ public IGetOperationResult PerformGet(string key) private bool CreateGetCommand(string key, out IGetOperationResult result, out IMemcachedNode node, out IGetOperation command) { result = new DefaultGetOperationResultFactory().Create(); - var hashedKey = this.keyTransformer.Transform(key); + var hashedKey = _keyTransformer.Transform(key); - node = this.pool.Locate(hashedKey); + node = _pool.Locate(hashedKey); if (node == null) { var errorMessage = $"Unable to locate node with \"{key}\" key"; @@ -240,16 +239,16 @@ private bool CreateGetCommand(string key, out IGetOperationResult result, out IM return false; } - command = this.pool.OperationFactory.Get(hashedKey); + command = _pool.OperationFactory.Get(hashedKey); return true; } private bool CreateGetCommand(string key, out IGetOperationResult result, out IMemcachedNode node, out IGetOperation command) { result = new DefaultGetOperationResultFactory().Create(); - var hashedKey = this.keyTransformer.Transform(key); + var hashedKey = _keyTransformer.Transform(key); - node = this.pool.Locate(hashedKey); + node = _pool.Locate(hashedKey); if (node == null) { var errorMessage = $"Unable to locate node with \"{key}\" key"; @@ -259,7 +258,7 @@ private bool CreateGetCommand(string key, out IGetOperationResult result, return false; } - command = this.pool.OperationFactory.Get(hashedKey); + command = _pool.OperationFactory.Get(hashedKey); return true; } @@ -267,7 +266,7 @@ private IGetOperationResult BuildGetCommandResult(IGetOperationResult result, IG { if (commandResult.Success) { - result.Value = transcoder.Deserialize(command.Result); + result.Value = _transcoder.Deserialize(command.Result); result.Cas = command.CasValue; result.Pass(); } @@ -283,7 +282,7 @@ private IGetOperationResult BuildGetCommandResult(IGetOperationResult r { if (commandResult.Success) { - result.Value = transcoder.Deserialize(command.Result); + result.Value = _transcoder.Deserialize(command.Result); result.Cas = command.CasValue; result.Pass(); } @@ -385,7 +384,7 @@ public bool TryGet(string key, out object value) { ulong cas = 0; - return this.PerformTryGet(key, out cas, out value).Success; + return PerformTryGet(key, out cas, out value).Success; } /// @@ -398,19 +397,19 @@ public bool TryGet(string key, out T value) { ulong cas = 0; - return this.PerformTryGet(key, out cas, out value).Success; + return PerformTryGet(key, out cas, out value).Success; } public CasResult GetWithCas(string key) { - return this.GetWithCas(key); + return GetWithCas(key); } public CasResult GetWithCas(string key) { CasResult tmp; - return this.TryGetWithCas(key, out tmp) + return TryGetWithCas(key, out tmp) ? new CasResult { Cas = tmp.Cas, Result = tmp.Result } : new CasResult { Cas = tmp.Cas, Result = default }; } @@ -420,7 +419,7 @@ public bool TryGetWithCas(string key, out CasResult value) object tmp; ulong cas; - var retval = this.PerformTryGet(key, out cas, out tmp); + var retval = PerformTryGet(key, out cas, out tmp); value = new CasResult { Cas = cas, Result = tmp }; @@ -438,8 +437,8 @@ public bool TryGetWithCas(string key, out CasResult value) protected virtual IGetOperationResult PerformTryGet(string key, out ulong cas, out object value) { - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = GetOperationResultFactory.Create(); cas = 0; @@ -447,12 +446,12 @@ protected virtual IGetOperationResult PerformTryGet(string key, out ulong cas, o if (node != null) { - var command = this.pool.OperationFactory.Get(hashedKey); + var command = _pool.OperationFactory.Get(hashedKey); var commandResult = node.Execute(command); if (commandResult.Success) { - result.Value = value = this.transcoder.Deserialize(command.Result); + result.Value = value = _transcoder.Deserialize(command.Result); result.Cas = cas = command.CasValue; result.Pass(); @@ -474,8 +473,8 @@ protected virtual IGetOperationResult PerformTryGet(string key, out ulong cas, o protected virtual IGetOperationResult PerformTryGet(string key, out ulong cas, out T value) { - var hashedKey = keyTransformer.Transform(key); - var node = pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = GetOperationResultFactory.Create(); cas = 0; @@ -483,12 +482,12 @@ protected virtual IGetOperationResult PerformTryGet(string key, out ulong cas if (node != null) { - var command = pool.OperationFactory.Get(hashedKey); + var command = _pool.OperationFactory.Get(hashedKey); var commandResult = node.Execute(command); if (commandResult.Success) { - result.Value = value = transcoder.Deserialize(command.Result); + result.Value = value = _transcoder.Deserialize(command.Result); result.Cas = cas = command.CasValue; result.Pass(); @@ -522,7 +521,7 @@ public bool Store(StoreMode mode, string key, object value) ulong tmp = 0; int status; - return this.PerformStore(mode, key, value, 0, ref tmp, out status).Success; + return PerformStore(mode, key, value, 0, ref tmp, out status).Success; } /// @@ -538,17 +537,17 @@ public bool Store(StoreMode mode, string key, object value, TimeSpan validFor) ulong tmp = 0; int status; - return this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), ref tmp, out status).Success; + return PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), ref tmp, out status).Success; } public async Task StoreAsync(StoreMode mode, string key, object value, DateTime expiresAt) { - return (await this.PerformStoreAsync(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt))).Success; + return (await PerformStoreAsync(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt))).Success; } public async Task StoreAsync(StoreMode mode, string key, object value, TimeSpan validFor) { - return (await this.PerformStoreAsync(mode, key, value, MemcachedClient.GetExpiration(validFor, null))).Success; + return (await PerformStoreAsync(mode, key, value, MemcachedClient.GetExpiration(validFor, null))).Success; } /// @@ -564,7 +563,7 @@ public bool Store(StoreMode mode, string key, object value, DateTime expiresAt) ulong tmp = 0; int status; - return this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), ref tmp, out status).Success; + return PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), ref tmp, out status).Success; } /// @@ -577,7 +576,7 @@ public bool Store(StoreMode mode, string key, object value, DateTime expiresAt) /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). public CasResult Cas(StoreMode mode, string key, object value, ulong cas) { - var result = this.PerformStore(mode, key, value, 0, cas); + var result = PerformStore(mode, key, value, 0, cas); return new CasResult { Cas = result.Cas, Result = result.Success, StatusCode = result.StatusCode.Value }; } @@ -593,7 +592,7 @@ public CasResult Cas(StoreMode mode, string key, object value, ulong cas) /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). public CasResult Cas(StoreMode mode, string key, object value, TimeSpan validFor, ulong cas) { - var result = this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), cas); + var result = PerformStore(mode, key, value, MemcachedClient.GetExpiration(validFor, null), cas); return new CasResult { Cas = result.Cas, Result = result.Success, StatusCode = result.StatusCode.Value }; } @@ -608,7 +607,7 @@ public CasResult Cas(StoreMode mode, string key, object value, TimeSpan va /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). public CasResult Cas(StoreMode mode, string key, object value, DateTime expiresAt, ulong cas) { - var result = this.PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), cas); + var result = PerformStore(mode, key, value, MemcachedClient.GetExpiration(null, expiresAt), cas); return new CasResult { Cas = result.Cas, Result = result.Success, StatusCode = result.StatusCode.Value }; } @@ -622,7 +621,7 @@ public CasResult Cas(StoreMode mode, string key, object value, DateTime ex /// A CasResult object containing the version of the item and the result of the operation (true if the item was successfully stored in the cache; false otherwise). public CasResult Cas(StoreMode mode, string key, object value) { - var result = this.PerformStore(mode, key, value, 0, 0); + var result = PerformStore(mode, key, value, 0, 0); return new CasResult { Cas = result.Cas, Result = result.Success, StatusCode = result.StatusCode.Value }; } @@ -631,7 +630,7 @@ private IStoreOperationResult PerformStore(StoreMode mode, string key, object va ulong tmp = cas; int status; - var retval = this.PerformStore(mode, key, value, expires, ref tmp, out status); + var retval = PerformStore(mode, key, value, expires, ref tmp, out status); retval.StatusCode = status; if (retval.Success) @@ -643,8 +642,8 @@ private IStoreOperationResult PerformStore(StoreMode mode, string key, object va protected virtual IStoreOperationResult PerformStore(StoreMode mode, string key, object value, uint expires, ref ulong cas, out int statusCode) { - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = StoreOperationResultFactory.Create(); statusCode = -1; @@ -660,7 +659,7 @@ protected virtual IStoreOperationResult PerformStore(StoreMode mode, string key, { CacheItem item; - try { item = this.transcoder.Serialize(value); } + try { item = _transcoder.Serialize(value); } catch (Exception e) { _logger.LogError("PerformStore", e); @@ -670,7 +669,7 @@ protected virtual IStoreOperationResult PerformStore(StoreMode mode, string key, return result; } - var command = this.pool.OperationFactory.Store(mode, hashedKey, item, expires, cas); + var command = _pool.OperationFactory.Store(mode, hashedKey, item, expires, cas); var commandResult = node.Execute(command); result.Cas = cas = command.CasValue; @@ -686,7 +685,7 @@ protected virtual IStoreOperationResult PerformStore(StoreMode mode, string key, return result; } - //if (this.performanceMonitor != null) this.performanceMonitor.Store(mode, 1, false); + //if (performanceMonitor != null) performanceMonitor.Store(mode, 1, false); result.Fail("Unable to locate node"); return result; @@ -694,8 +693,8 @@ protected virtual IStoreOperationResult PerformStore(StoreMode mode, string key, protected async virtual Task PerformStoreAsync(StoreMode mode, string key, object value, uint expires) { - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = StoreOperationResultFactory.Create(); int statusCode = -1; @@ -710,7 +709,7 @@ protected async virtual Task PerformStoreAsync(StoreMode { CacheItem item; - try { item = this.transcoder.Serialize(value); } + try { item = _transcoder.Serialize(value); } catch (Exception e) { _logger.LogError(new EventId(), e, $"{nameof(PerformStoreAsync)} for '{key}' key"); @@ -719,7 +718,7 @@ protected async virtual Task PerformStoreAsync(StoreMode return result; } - var command = this.pool.OperationFactory.Store(mode, hashedKey, item, expires, cas); + var command = _pool.OperationFactory.Store(mode, hashedKey, item, expires, cas); var commandResult = await node.ExecuteAsync(command); result.Cas = cas = command.CasValue; @@ -735,7 +734,7 @@ protected async virtual Task PerformStoreAsync(StoreMode return result; } - //if (this.performanceMonitor != null) this.performanceMonitor.Store(mode, 1, false); + //if (performanceMonitor != null) performanceMonitor.Store(mode, 1, false); result.Fail("Unable to locate memcached node"); return result; @@ -756,7 +755,7 @@ protected async virtual Task PerformStoreAsync(StoreMode /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public ulong Increment(string key, ulong defaultValue, ulong delta) { - return this.PerformMutate(MutationMode.Increment, key, defaultValue, delta, 0).Value; + return PerformMutate(MutationMode.Increment, key, defaultValue, delta, 0).Value; } /// @@ -770,7 +769,7 @@ public ulong Increment(string key, ulong defaultValue, ulong delta) /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public ulong Increment(string key, ulong defaultValue, ulong delta, TimeSpan validFor) { - return this.PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)).Value; + return PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)).Value; } /// @@ -784,7 +783,7 @@ public ulong Increment(string key, ulong defaultValue, ulong delta, TimeSpan val /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public ulong Increment(string key, ulong defaultValue, ulong delta, DateTime expiresAt) { - return this.PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)).Value; + return PerformMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)).Value; } /// @@ -798,7 +797,7 @@ public ulong Increment(string key, ulong defaultValue, ulong delta, DateTime exp /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public CasResult Increment(string key, ulong defaultValue, ulong delta, ulong cas) { - var result = this.CasMutate(MutationMode.Increment, key, defaultValue, delta, 0, cas); + var result = CasMutate(MutationMode.Increment, key, defaultValue, delta, 0, cas); return new CasResult { Cas = result.Cas, Result = result.Value, StatusCode = result.StatusCode.Value }; } @@ -814,7 +813,7 @@ public CasResult Increment(string key, ulong defaultValue, ulong delta, u /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public CasResult Increment(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas) { - var result = this.CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); + var result = CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); return new CasResult { Cas = result.Cas, Result = result.Value, StatusCode = result.StatusCode.Value }; } @@ -830,7 +829,7 @@ public CasResult Increment(string key, ulong defaultValue, ulong delta, T /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public CasResult Increment(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas) { - var result = this.CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); + var result = CasMutate(MutationMode.Increment, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); return new CasResult { Cas = result.Cas, Result = result.Value, StatusCode = result.StatusCode.Value }; } @@ -846,7 +845,7 @@ public CasResult Increment(string key, ulong defaultValue, ulong delta, D /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public ulong Decrement(string key, ulong defaultValue, ulong delta) { - return this.PerformMutate(MutationMode.Decrement, key, defaultValue, delta, 0).Value; + return PerformMutate(MutationMode.Decrement, key, defaultValue, delta, 0).Value; } /// @@ -860,7 +859,7 @@ public ulong Decrement(string key, ulong defaultValue, ulong delta) /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public ulong Decrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor) { - return this.PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)).Value; + return PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null)).Value; } /// @@ -874,7 +873,7 @@ public ulong Decrement(string key, ulong defaultValue, ulong delta, TimeSpan val /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public ulong Decrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt) { - return this.PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)).Value; + return PerformMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt)).Value; } /// @@ -888,7 +887,7 @@ public ulong Decrement(string key, ulong defaultValue, ulong delta, DateTime exp /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public CasResult Decrement(string key, ulong defaultValue, ulong delta, ulong cas) { - var result = this.CasMutate(MutationMode.Decrement, key, defaultValue, delta, 0, cas); + var result = CasMutate(MutationMode.Decrement, key, defaultValue, delta, 0, cas); return new CasResult { Cas = result.Cas, Result = result.Value, StatusCode = result.StatusCode.Value }; } @@ -904,7 +903,7 @@ public CasResult Decrement(string key, ulong defaultValue, ulong delta, u /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public CasResult Decrement(string key, ulong defaultValue, ulong delta, TimeSpan validFor, ulong cas) { - var result = this.CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); + var result = CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(validFor, null), cas); return new CasResult { Cas = result.Cas, Result = result.Value, StatusCode = result.StatusCode.Value }; } @@ -920,7 +919,7 @@ public CasResult Decrement(string key, ulong defaultValue, ulong delta, T /// If the client uses the Text protocol, the item must be inserted into the cache before it can be changed. It must be inserted as a . Moreover the Text protocol only works with values, so return value -1 always indicates that the item was not found. public CasResult Decrement(string key, ulong defaultValue, ulong delta, DateTime expiresAt, ulong cas) { - var result = this.CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); + var result = CasMutate(MutationMode.Decrement, key, defaultValue, delta, MemcachedClient.GetExpiration(null, expiresAt), cas); return new CasResult { Cas = result.Cas, Result = result.Value, StatusCode = result.StatusCode.Value }; } @@ -955,13 +954,13 @@ private IMutateOperationResult CasMutate(MutationMode mode, string key, ulong de protected virtual IMutateOperationResult PerformMutate(MutationMode mode, string key, ulong defaultValue, ulong delta, uint expires, ref ulong cas) { - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = MutateOperationResultFactory.Create(); if (node != null) { - var command = this.pool.OperationFactory.Mutate(mode, hashedKey, defaultValue, delta, expires, cas); + var command = _pool.OperationFactory.Mutate(mode, hashedKey, defaultValue, delta, expires, cas); var commandResult = node.Execute(command); result.Cas = cas = command.CasValue; @@ -989,13 +988,13 @@ protected virtual IMutateOperationResult PerformMutate(MutationMode mode, string protected virtual async Task PerformMutateAsync(MutationMode mode, string key, ulong defaultValue, ulong delta, uint expires) { ulong cas = 0; - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = MutateOperationResultFactory.Create(); if (node != null) { - var command = this.pool.OperationFactory.Mutate(mode, hashedKey, defaultValue, delta, expires, cas); + var command = _pool.OperationFactory.Mutate(mode, hashedKey, defaultValue, delta, expires, cas); var commandResult = await node.ExecuteAsync(command); result.Cas = cas = command.CasValue; @@ -1034,7 +1033,7 @@ public bool Append(string key, ArraySegment data) { ulong cas = 0; - return this.PerformConcatenate(ConcatenationMode.Append, key, ref cas, data).Success; + return PerformConcatenate(ConcatenationMode.Append, key, ref cas, data).Success; } /// @@ -1045,7 +1044,7 @@ public bool Prepend(string key, ArraySegment data) { ulong cas = 0; - return this.PerformConcatenate(ConcatenationMode.Prepend, key, ref cas, data).Success; + return PerformConcatenate(ConcatenationMode.Prepend, key, ref cas, data).Success; } /// @@ -1080,13 +1079,13 @@ public CasResult Prepend(string key, ulong cas, ArraySegment data) protected virtual IConcatOperationResult PerformConcatenate(ConcatenationMode mode, string key, ref ulong cas, ArraySegment data) { - var hashedKey = this.keyTransformer.Transform(key); - var node = this.pool.Locate(hashedKey); + var hashedKey = _keyTransformer.Transform(key); + var node = _pool.Locate(hashedKey); var result = ConcatOperationResultFactory.Create(); if (node != null) { - var command = this.pool.OperationFactory.Concat(mode, hashedKey, cas, data); + var command = _pool.OperationFactory.Concat(mode, hashedKey, cas, data); var commandResult = node.Execute(command); if (commandResult.Success) @@ -1115,9 +1114,9 @@ protected virtual IConcatOperationResult PerformConcatenate(ConcatenationMode mo /// public void FlushAll() { - foreach (var node in this.pool.GetWorkingNodes()) + foreach (var node in _pool.GetWorkingNodes()) { - var command = this.pool.OperationFactory.Flush(); + var command = _pool.OperationFactory.Flush(); node.Execute(command); } @@ -1127,9 +1126,9 @@ public async Task FlushAllAsync() { var tasks = new List(); - foreach (var node in this.pool.GetWorkingNodes()) + foreach (var node in _pool.GetWorkingNodes()) { - var command = this.pool.OperationFactory.Flush(); + var command = _pool.OperationFactory.Flush(); tasks.Add(node.ExecuteAsync(command)); } @@ -1143,7 +1142,7 @@ public async Task FlushAllAsync() /// public ServerStats Stats() { - return this.Stats(null); + return Stats(null); } public ServerStats Stats(string type) @@ -1151,9 +1150,9 @@ public ServerStats Stats(string type) var results = new Dictionary>(); var tasks = new List(); - foreach (var node in this.pool.GetWorkingNodes()) + foreach (var node in _pool.GetWorkingNodes()) { - var cmd = this.pool.OperationFactory.Stats(type); + var cmd = _pool.OperationFactory.Stats(type); var action = new Func(node.Execute); var endpoint = node.EndPoint; @@ -1219,19 +1218,19 @@ public async Task RemoveMultiAsync(params string[] keys) /// a Dictionary holding all items indexed by their key. public IDictionary Get(IEnumerable keys) { - return PerformMultiGet(keys, (mget, kvp) => this.transcoder.Deserialize(kvp.Value)); + return PerformMultiGet(keys, (mget, kvp) => _transcoder.Deserialize(kvp.Value)); } public async Task> GetAsync(IEnumerable keys) { - return await PerformMultiGetAsync(keys, (mget, kvp) => this.transcoder.Deserialize(kvp.Value)); + return await PerformMultiGetAsync(keys, (mget, kvp) => _transcoder.Deserialize(kvp.Value)); } public IDictionary> GetWithCas(IEnumerable keys) { return PerformMultiGet(keys, (mget, kvp) => new CasResult { - Result = this.transcoder.Deserialize(kvp.Value), + Result = _transcoder.Deserialize(kvp.Value), Cas = mget.Cas[kvp.Key] }); } @@ -1240,7 +1239,7 @@ public async Task>> GetWithCasAsync(IEnume { return await PerformMultiGetAsync(keys, (mget, kvp) => new CasResult { - Result = this.transcoder.Deserialize(kvp.Value), + Result = _transcoder.Deserialize(kvp.Value), Cas = mget.Cas[kvp.Key] }); } @@ -1250,7 +1249,7 @@ protected virtual IDictionary PerformMultiGet(IEnumerable // transform the keys and index them by hashed => original // the mget results will be mapped using this index var hashed = new Dictionary(); - foreach (var key in keys) hashed[this.keyTransformer.Transform(key)] = key; + foreach (var key in keys) hashed[_keyTransformer.Transform(key)] = key; var byServer = GroupByServer(hashed.Keys); @@ -1263,7 +1262,7 @@ protected virtual IDictionary PerformMultiGet(IEnumerable var node = slice.Key; var nodeKeys = slice.Value; - var mget = this.pool.OperationFactory.MultiGet(nodeKeys); + var mget = _pool.OperationFactory.MultiGet(nodeKeys); // run gets in parallel var action = new Func(node.Execute); @@ -1313,7 +1312,7 @@ protected virtual async Task> PerformMultiGetAsync(IEn var hashed = new Dictionary(); foreach (var key in keys) { - hashed[this.keyTransformer.Transform(key)] = key; + hashed[_keyTransformer.Transform(key)] = key; } var byServer = GroupByServer(hashed.Keys); @@ -1326,7 +1325,7 @@ protected virtual async Task> PerformMultiGetAsync(IEn { var node = slice.Key; var nodeKeys = slice.Value; - var mget = this.pool.OperationFactory.MultiGet(nodeKeys); + var mget = _pool.OperationFactory.MultiGet(nodeKeys); var task = Task.Run(async () => { if ((await node.ExecuteAsync(mget)).Success) @@ -1354,7 +1353,7 @@ protected Dictionary> GroupByServer(IEnumerable list; @@ -1455,7 +1454,7 @@ protected static uint GetExpiration( void IDisposable.Dispose() { - this.Dispose(); + Dispose(); } /// @@ -1466,10 +1465,10 @@ public void Dispose() { GC.SuppressFinalize(this); - if (this.pool != null) + if (_pool != null) { - try { this.pool.Dispose(); } - finally { this.pool = null; } + try { _pool.Dispose(); } + finally { _pool = null; } } } diff --git a/src/Enyim.Caching/TigerHash.cs b/src/Enyim.Caching/TigerHash.cs index f25caa36..09a20df5 100755 --- a/src/Enyim.Caching/TigerHash.cs +++ b/src/Enyim.Caching/TigerHash.cs @@ -3,534 +3,534 @@ namespace Enyim { - /// - /// Implements the Tiger hash. (http://www.cs.technion.ac.il/~biham/Reports/Tiger/) - /// - /// Ported (and cleaned&sped up) from the Tiger.NET VB code. (http://www.hotpixel.net/software.html) - /// - public sealed class TigerHash : HashAlgorithm - { - const int PASSES = 3; - const int BLOCKSIZE = 64; + /// + /// Implements the Tiger hash. (http://www.cs.technion.ac.il/~biham/Reports/Tiger/) + /// + /// Ported (and cleaned&sped up) from the Tiger.NET VB code. (http://www.hotpixel.net/software.html) + /// + public sealed class TigerHash : HashAlgorithm + { + private const int PASSES = 3; + private const int BLOCKSIZE = 64; - long totalLength; - ulong a; - ulong b; - ulong c; + private long _totalLength; + private ulong _a; + private ulong _b; + private ulong _c; - byte[] internalDataBuffer; - int bufferPosition; + private byte[] _internalDataBuffer; + private int _bufferPosition; - ulong[] block = new ulong[8]; + private ulong[] _block = new ulong[8]; - /// - /// Initializes a new instance of the class. - /// - public TigerHash() - { - this.internalDataBuffer = new byte[BLOCKSIZE]; - //this.HashSizeValue = 3 * 8 * 8; - - this.Initialize(); - } - - /// - /// Initializes an instance of . - /// - public override void Initialize() - { - this.a = 0x123456789ABCDEF; - this.b = 0xFEDCBA9876543210; - this.c = 0xF096A5B4C3B2E187; - - this.bufferPosition = 0; - this.totalLength = 0; - } - - - /// Routes data written to the object into the hash algorithm for computing the hash. - /// The input data. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the array to use as data. - protected override void HashCore(byte[] array, int ibStart, int cbSize) - { - this.totalLength += cbSize; - - byte[] buffer = this.internalDataBuffer; - - int offset = this.bufferPosition; - int end = ibStart + cbSize; - - while (ibStart < end) - { - int count = BLOCKSIZE - offset; - - if (count > cbSize) - { - count = cbSize; - } - - Buffer.BlockCopy(array, ibStart, buffer, offset, count); - - ibStart += count; - offset += count; - cbSize -= count; - - if (BLOCKSIZE > offset) - break; - - this.ProcessBlock(); - - offset = 0; - } - - this.bufferPosition = offset; - } - - /// - /// Returns the computed hash value after all data has been written to the object. - /// - /// The computed hash code. - protected override byte[] HashFinal() - { - int bufferOffset = this.bufferPosition; - byte[] buffer = this.internalDataBuffer; - - buffer[bufferOffset] = 1; - bufferOffset += 1; - - if ((BLOCKSIZE - 8) <= bufferOffset) - { - Array.Clear(buffer, bufferOffset, BLOCKSIZE - bufferOffset); - - this.ProcessBlock(); - bufferOffset = 0; - } - - Array.Clear(buffer, bufferOffset, BLOCKSIZE - bufferOffset - 8); - - TigerHash.LongToBytes(((ulong)this.totalLength) << 3, buffer, BLOCKSIZE - 8); - - this.ProcessBlock(); - - byte[] retval = new byte[24]; - - TigerHash.LongToBytes(this.a, retval, 0); - TigerHash.LongToBytes(this.b, retval, 8); - TigerHash.LongToBytes(this.c, retval, 16); - - return retval; - } - - private unsafe void ProcessBlock() - { - #region [ Original code for reference ] - //int blockIndex = 0; - //ulong[] block = this.block; - //byte[] buffer = this.internalDataBuffer; - - //for (int offset = 0; offset < BLOCKSIZE; offset += 8) - //{ - // block[blockIndex] = - // (((ulong)buffer[offset + 7]) << 56) | - // ((((ulong)buffer[offset + 6]) & 0xFF) << 48) | - // ((((ulong)buffer[offset + 5]) & 0xFF) << 40) | - // ((((ulong)buffer[offset + 4]) & 0xFF) << 32) | - // ((((ulong)buffer[offset + 3]) & 0xFF) << 24) | - // ((((ulong)buffer[offset + 2]) & 0xFF) << 16) | - // ((((ulong)buffer[offset + 1]) & 0xFF) << 8) | - // (((ulong)buffer[offset]) & 0xFF); - - // blockIndex++; - //} - #endregion - - Buffer.BlockCopy(this.internalDataBuffer, 0, this.block, 0, BLOCKSIZE); - - this.Compress(); - } - - private void Compress() - { - ulong aa, bb, cc; - ulong[] tmpBlock; - - aa = this.a; - bb = this.b; - cc = this.c; - - tmpBlock = this.block; - - this.RoundABC(tmpBlock[0], 5); - this.RoundBCA(tmpBlock[1], 5); - this.RoundCAB(tmpBlock[2], 5); - this.RoundABC(tmpBlock[3], 5); - this.RoundBCA(tmpBlock[4], 5); - this.RoundCAB(tmpBlock[5], 5); - this.RoundABC(tmpBlock[6], 5); - this.RoundBCA(tmpBlock[7], 5); - - TigerHash.Schedule(tmpBlock); - - this.RoundCAB(tmpBlock[0], 7); - this.RoundABC(tmpBlock[1], 7); - this.RoundBCA(tmpBlock[2], 7); - this.RoundCAB(tmpBlock[3], 7); - this.RoundABC(tmpBlock[4], 7); - this.RoundBCA(tmpBlock[5], 7); - this.RoundCAB(tmpBlock[6], 7); - this.RoundABC(tmpBlock[7], 7); - - TigerHash.Schedule(tmpBlock); - - this.RoundBCA(tmpBlock[0], 9); - this.RoundCAB(tmpBlock[1], 9); - this.RoundABC(tmpBlock[2], 9); - this.RoundBCA(tmpBlock[3], 9); - this.RoundCAB(tmpBlock[4], 9); - this.RoundABC(tmpBlock[5], 9); - this.RoundBCA(tmpBlock[6], 9); - this.RoundCAB(tmpBlock[7], 9); - - this.a = this.a ^ aa; - this.b -= bb; - this.c += cc; - } - - private static void Schedule(ulong[] x) - { - x[0] -= x[7] ^ 0xA5A5A5A5A5A5A5A5; - x[1] = x[1] ^ x[0]; - x[2] += x[1]; - x[3] -= x[2] ^ ((~x[1]) << 19); - x[4] = x[4] ^ x[3]; - x[5] += x[4]; - x[6] -= x[5] ^ (((~x[4]) >> 23) & 0x1FFFFFFFFFF); - x[7] = x[7] ^ x[6]; - x[0] += x[7]; - x[1] -= x[0] ^ ((~x[7]) << 19); - x[2] = x[2] ^ x[1]; - x[3] += x[2]; - x[4] -= x[3] ^ (((~x[2]) >> 23) & 0x1FFFFFFFFFF); - x[5] = x[5] ^ x[4]; - x[6] += x[5]; - x[7] -= x[6] ^ 0x123456789ABCDEF; - } - - private void RoundABC(ulong x, uint mul) - { - ulong[] T = TigerHash.T; - - ulong tmpC = this.c ^ x; - int ch = (int)(tmpC >> 32); - int cl = (int)(tmpC); - - this.a -= T[cl & 0xFF] ^ T[((cl >> 16) & 0xFF) + 0x100] ^ T[(ch & 0xFF) + 0x200] ^ T[((ch >> 16) & 0xFF) + 0x300]; - this.b += T[((cl >> 8) & 0xFF) + 0x300] ^ T[((cl >> 24) & 0xFF) + 0x200] ^ T[((ch >> 8) & 0xFF) + 0x100] ^ T[(ch >> 24) & 0xFF]; - - this.b *= mul; - - this.c = tmpC; - } - - private void RoundBCA(ulong x, uint mul) - { - ulong[] T = TigerHash.T; - - ulong tmpA = this.a ^ x; - int ah = (int)(tmpA >> 32); - int al = (int)(tmpA); - - this.b -= T[al & 0xFF] ^ T[((al >> 16) & 0xFF) + 0x100] ^ T[(ah & 0xFF) + 0x200] ^ T[((ah >> 16) & 0xFF) + 0x300]; - this.c += T[((al >> 8) & 0xFF) + 0x300] ^ T[((al >> 24) & 0xFF) + 0x200] ^ T[((ah >> 8) & 0xFF) + 0x100] ^ T[(ah >> 24) & 0xFF]; - this.c *= mul; - - this.a = tmpA; - } - - private void RoundCAB(ulong x, uint mul) - { - ulong[] T = TigerHash.T; - - ulong tmpB = this.b ^ x; - int bh = (int)(tmpB >> 32); - int bl = (int)(tmpB); - - this.c -= T[bl & 0xFF] ^ T[((bl >> 16) & 0xFF) + 0x100] ^ T[(bh & 0xFF) + 0x200] ^ T[((bh >> 16) & 0xFF) + 0x300]; - this.a += T[((bl >> 8) & 0xFF) + 0x300] ^ T[((bl >> 24) & 0xFF) + 0x200] ^ T[((bh >> 8) & 0xFF) + 0x100] ^ T[(bh >> 24) & 0xFF]; - this.a *= mul; - - this.b = tmpB; - } - - private static unsafe void LongToBytes(ulong value, byte[] buffer, int offset) - { - fixed (byte* numRef = buffer) - { - *((ulong*)(numRef + offset)) = value; - } - } - - #region [ static readonly ulong[] T ] - private static readonly ulong[] T = - { - 0x2AAB17CF7E90C5E, 0xAC424B03E243A8EC, 0x72CD5BE30DD5FCD3, 0x6D019B93F6F97F3A, - 0xCD9978FFD21F9193, 0x7573A1C9708029E2, 0xB164326B922A83C3, 0x46883EEE04915870, - 0xEAACE3057103ECE6, 0xC54169B808A3535C, 0x4CE754918DDEC47C, 0xAA2F4DFDC0DF40C, - 0x10B76F18A74DBEFA, 0xC6CCB6235AD1AB6A, 0x13726121572FE2FF, 0x1A488C6F199D921E, - 0x4BC9F9F4DA0007CA, 0x26F5E6F6E85241C7, 0x859079DBEA5947B6, 0x4F1885C5C99E8C92, - 0xD78E761EA96F864B, 0x8E36428C52B5C17D, 0x69CF6827373063C1, 0xB607C93D9BB4C56E, - 0x7D820E760E76B5EA, 0x645C9CC6F07FDC42, 0xBF38A078243342E0, 0x5F6B343C9D2E7D04, - 0xF2C28AEB600B0EC6, 0x6C0ED85F7254BCAC, 0x71592281A4DB4FE5, 0x1967FA69CE0FED9F, - 0xFD5293F8B96545DB, 0xC879E9D7F2A7600B, 0x860248920193194E, 0xA4F9533B2D9CC0B3, - 0x9053836C15957613, 0xDB6DCF8AFC357BF1, 0x18BEEA7A7A370F57, 0x37117CA50B99066, - 0x6AB30A9774424A35, 0xF4E92F02E325249B, 0x7739DB07061CCAE1, 0xD8F3B49CECA42A05, - 0xBD56BE3F51382F73, 0x45FAED5843B0BB28, 0x1C813D5C11BF1F83, 0x8AF0E4B6D75FA169, - 0x33EE18A487AD9999, 0x3C26E8EAB1C94410, 0xB510102BC0A822F9, 0x141EEF310CE6123B, - 0xFC65B90059DDB154, 0xE0158640C5E0E607, 0x884E079826C3A3CF, 0x930D0D9523C535FD, - 0x35638D754E9A2B00, 0x4085FCCF40469DD5, 0xC4B17AD28BE23A4C, 0xCAB2F0FC6A3E6A2E, - 0x2860971A6B943FCD, 0x3DDE6EE212E30446, 0x6222F32AE01765AE, 0x5D550BB5478308FE, - 0xA9EFA98DA0EDA22A, 0xC351A71686C40DA7, 0x1105586D9C867C84, 0xDCFFEE85FDA22853, - 0xCCFBD0262C5EEF76, 0xBAF294CB8990D201, 0xE69464F52AFAD975, 0x94B013AFDF133E14, - 0x6A7D1A32823C958, 0x6F95FE5130F61119, 0xD92AB34E462C06C0, 0xED7BDE33887C71D2, - 0x79746D6E6518393E, 0x5BA419385D713329, 0x7C1BA6B948A97564, 0x31987C197BFDAC67, - 0xDE6C23C44B053D02, 0x581C49FED002D64D, 0xDD474D6338261571, 0xAA4546C3E473D062, - 0x928FCE349455F860, 0x48161BBACAAB94D9, 0x63912430770E6F68, 0x6EC8A5E602C6641C, - 0x87282515337DDD2B, 0x2CDA6B42034B701B, 0xB03D37C181CB096D, 0xE108438266C71C6F, - 0x2B3180C7EB51B255, 0xDF92B82F96C08BBC, 0x5C68C8C0A632F3BA, 0x5504CC861C3D0556, - 0xABBFA4E55FB26B8F, 0x41848B0AB3BACEB4, 0xB334A273AA445D32, 0xBCA696F0A85AD881, - 0x24F6EC65B528D56C, 0xCE1512E90F4524A, 0x4E9DD79D5506D35A, 0x258905FAC6CE9779, - 0x2019295B3E109B33, 0xF8A9478B73A054CC, 0x2924F2F934417EB0, 0x3993357D536D1BC4, - 0x38A81AC21DB6FF8B, 0x47C4FBF17D6016BF, 0x1E0FAADD7667E3F5, 0x7ABCFF62938BEB96, - 0xA78DAD948FC179C9, 0x8F1F98B72911E50D, 0x61E48EAE27121A91, 0x4D62F7AD31859808, - 0xECEBA345EF5CEAEB, 0xF5CEB25EBC9684CE, 0xF633E20CB7F76221, 0xA32CDF06AB8293E4, - 0x985A202CA5EE2CA4, 0xCF0B8447CC8A8FB1, 0x9F765244979859A3, 0xA8D516B1A1240017, - 0xBD7BA3EBB5DC726, 0xE54BCA55B86ADB39, 0x1D7A3AFD6C478063, 0x519EC608E7669EDD, - 0xE5715A2D149AA23, 0x177D4571848FF194, 0xEEB55F3241014C22, 0xF5E5CA13A6E2EC2, - 0x8029927B75F5C361, 0xAD139FABC3D6E436, 0xD5DF1A94CCF402F, 0x3E8BD948BEA5DFC8, - 0xA5A0D357BD3FF77E, 0xA2D12E251F74F645, 0x66FD9E525E81A082, 0x2E0C90CE7F687A49, - 0xC2E8BCBEBA973BC5, 0x1BCE509745F, 0x423777BBE6DAB3D6, 0xD1661C7EAEF06EB5, - 0xA1781F354DAACFD8, 0x2D11284A2B16AFFC, 0xF1FC4F67FA891D1F, 0x73ECC25DCB920ADA, - 0xAE610C22C2A12651, 0x96E0A810D356B78A, 0x5A9A381F2FE7870F, 0xD5AD62EDE94E5530, - 0xD225E5E8368D1427, 0x65977B70C7AF4631, 0x99F889B2DE39D74F, 0x233F30BF54E1D143, - 0x9A9675D3D9A63C97, 0x5470554FF334F9A8, 0x166ACB744A4F5688, 0x70C74CAAB2E4AEAD, - 0xF0D091646F294D12, 0x57B82A89684031D1, 0xEFD95A5A61BE0B6B, 0x2FBD12E969F2F29A, - 0x9BD37013FEFF9FE8, 0x3F9B0404D6085A06, 0x4940C1F3166CFE15, 0x9542C4DCDF3DEFB, - 0xB4C5218385CD5CE3, 0xC935B7DC4462A641, 0x3417F8A68ED3B63F, 0xB80959295B215B40, - 0xF99CDAEF3B8C8572, 0x18C0614F8FCB95D, 0x1B14ACCD1A3ACDF3, 0x84D471F200BB732D, - 0xC1A3110E95E8DA16, 0x430A7220BF1A82B8, 0xB77E090D39DF210E, 0x5EF4BD9F3CD05E9D, - 0x9D4FF6DA7E57A444, 0xDA1D60E183D4A5F8, 0xB287C38417998E47, 0xFE3EDC121BB31886, - 0xC7FE3CCC980CCBEF, 0xE46FB590189BFD03, 0x3732FD469A4C57DC, 0x7EF700A07CF1AD65, - 0x59C64468A31D8859, 0x762FB0B4D45B61F6, 0x155BAED099047718, 0x68755E4C3D50BAA6, - 0xE9214E7F22D8B4DF, 0x2ADDBF532EAC95F4, 0x32AE3909B4BD0109, 0x834DF537B08E3450, - 0xFA209DA84220728D, 0x9E691D9B9EFE23F7, 0x446D288C4AE8D7F, 0x7B4CC524E169785B, - 0x21D87F0135CA1385, 0xCEBB400F137B8AA5, 0x272E2B66580796BE, 0x3612264125C2B0DE, - 0x57702BDAD1EFBB2, 0xD4BABB8EACF84BE9, 0x91583139641BC67B, 0x8BDC2DE08036E024, - 0x603C8156F49F68ED, 0xF7D236F7DBEF5111, 0x9727C4598AD21E80, 0xA08A0896670A5FD7, - 0xCB4A8F4309EBA9CB, 0x81AF564B0F7036A1, 0xC0B99AA778199ABD, 0x959F1EC83FC8E952, - 0x8C505077794A81B9, 0x3ACAAF8F056338F0, 0x7B43F50627A6778, 0x4A44AB49F5ECCC77, - 0x3BC3D6E4B679EE98, 0x9CC0D4D1CF14108C, 0x4406C00B206BC8A0, 0x82A18854C8D72D89, - 0x67E366B35C3C432C, 0xB923DD61102B37F2, 0x56AB2779D884271D, 0xBE83E1B0FF1525AF, - 0xFB7C65D4217E49A9, 0x6BDBE0E76D48E7D4, 0x8DF828745D9179E, 0x22EA6A9ADD53BD34, - 0xE36E141C5622200A, 0x7F805D1B8CB750EE, 0xAFE5C7A59F58E837, 0xE27F996A4FB1C23C, - 0xD3867DFB0775F0D0, 0xD0E673DE6E88891A, 0x123AEB9EAFB86C25, 0x30F1D5D5C145B895, - 0xBB434A2DEE7269E7, 0x78CB67ECF931FA38, 0xF33B0372323BBF9C, 0x52D66336FB279C74, - 0x505F33AC0AFB4EAA, 0xE8A5CD99A2CCE187, 0x534974801E2D30BB, 0x8D2D5711D5876D90, - 0x1F1A412891BC038E, 0xD6E2E71D82E56648, 0x74036C3A497732B7, 0x89B67ED96361F5AB, - 0xFFED95D8F1EA02A2, 0xE72B3BD61464D43D, 0xA6300F170BDC4820, 0xEBC18760ED78A77A, - 0xE6A6BE5A05A12138, 0xB5A122A5B4F87C98, 0x563C6089140B6990, 0x4C46CB2E391F5DD5, - 0xD932ADDBC9B79434, 0x8EA70E42015AFF5, 0xD765A6673E478CF1, 0xC4FB757EAB278D99, - 0xDF11C6862D6E0692, 0xDDEB84F10D7F3B16, 0x6F2EF604A665EA04, 0x4A8E0F0FF0E0DFB3, - 0xA5EDEEF83DBCBA51, 0xFC4F0A2A0EA4371E, 0xE83E1DA85CB38429, 0xDC8FF882BA1B1CE2, - 0xCD45505E8353E80D, 0x18D19A00D4DB0717, 0x34A0CFEDA5F38101, 0xBE77E518887CAF2, - 0x1E341438B3C45136, 0xE05797F49089CCF9, 0xFFD23F9DF2591D14, 0x543DDA228595C5CD, - 0x661F81FD99052A33, 0x8736E641DB0F7B76, 0x15227725418E5307, 0xE25F7F46162EB2FA, - 0x48A8B2126C13D9FE, 0xAFDC541792E76EEA, 0x3D912BFC6D1898F, 0x31B1AAFA1B83F51B, - 0xF1AC2796E42AB7D9, 0x40A3A7D7FCD2EBAC, 0x1056136D0AFBBCC5, 0x7889E1DD9A6D0C85, - 0xD33525782A7974AA, 0xA7E25D09078AC09B, 0xBD4138B3EAC6EDD0, 0x920ABFBE71EB9E70, - 0xA2A5D0F54FC2625C, 0xC054E36B0B1290A3, 0xF6DD59FF62FE932B, 0x3537354511A8AC7D, - 0xCA845E9172FADCD4, 0x84F82B60329D20DC, 0x79C62CE1CD672F18, 0x8B09A2ADD124642C, - 0xD0C1E96A19D9E726, 0x5A786A9B4BA9500C, 0xE020336634C43F3, 0xC17B474AEB66D822, - 0x6A731AE3EC9BAAC2, 0x8226667AE0840258, 0x67D4567691CAECA5, 0x1D94155C4875ADB5, - 0x6D00FD985B813FDF, 0x51286EFCB774CD06, 0x5E8834471FA744AF, 0xF72CA0AEE761AE2E, - 0xBE40E4CDAEE8E09A, 0xE9970BBB5118F665, 0x726E4BEB33DF1964, 0x703B000729199762, - 0x4631D816F5EF30A7, 0xB880B5B51504A6BE, 0x641793C37ED84B6C, 0x7B21ED77F6E97D96, - 0x776306312EF96B73, 0xAE528948E86FF3F4, 0x53DBD7F286A3F8F8, 0x16CADCE74CFC1063, - 0x5C19BDFA52C6DD, 0x68868F5D64D46AD3, 0x3A9D512CCF1E186A, 0x367E62C2385660AE, - 0xE359E7EA77DCB1D7, 0x526C0773749ABE6E, 0x735AE5F9D09F734B, 0x493FC7CC8A558BA8, - 0xB0B9C1533041AB45, 0x321958BA470A59BD, 0x852DB00B5F46C393, 0x91209B2BD336B0E5, - 0x6E604F7D659EF19F, 0xB99A8AE2782CCB24, 0xCCF52AB6C814C4C7, 0x4727D9AFBE11727B, - 0x7E950D0C0121B34D, 0x756F435670AD471F, 0xF5ADD442615A6849, 0x4E87E09980B9957A, - 0x2ACFA1DF50AEE355, 0xD898263AFD2FD556, 0xC8F4924DD80C8FD6, 0xCF99CA3D754A173A, - 0xFE477BACAF91BF3C, 0xED5371F6D690C12D, 0x831A5C285E687094, 0xC5D3C90A3708A0A4, - 0xF7F903717D06580, 0x19F9BB13B8FDF27F, 0xB1BD6F1B4D502843, 0x1C761BA38FFF4012, - 0xD1530C4E2E21F3B, 0x8943CE69A7372C8A, 0xE5184E11FEB5CE66, 0x618BDB80BD736621, - 0x7D29BAD68B574D0B, 0x81BB613E25E6FE5B, 0x71C9C10BC07913F, 0xC7BEEB7909AC2D97, - 0xC3E58D353BC5D757, 0xEB017892F38F61E8, 0xD4EFFB9C9B1CC21A, 0x99727D26F494F7AB, - 0xA3E063A2956B3E03, 0x9D4A8B9A4AA09C30, 0x3F6AB7D500090FB4, 0x9CC0F2A057268AC0, - 0x3DEE9D2DEDBF42D1, 0x330F49C87960A972, 0xC6B2720287421B41, 0xAC59EC07C00369C, - 0xEF4EAC49CB353425, 0xF450244EEF0129D8, 0x8ACC46E5CAF4DEB6, 0x2FFEAB63989263F7, - 0x8F7CB9FE5D7A4578, 0x5BD8F7644E634635, 0x427A7315BF2DC900, 0x17D0C4AA2125261C, - 0x3992486C93518E50, 0xB4CBFEE0A2D7D4C3, 0x7C75D6202C5DDD8D, 0xDBC295D8E35B6C61, - 0x60B369D302032B19, 0xCE42685FDCE44132, 0x6F3DDB9DDF65610, 0x8EA4D21DB5E148F0, - 0x20B0FCE62FCD496F, 0x2C1B912358B0EE31, 0xB28317B818F5A308, 0xA89C1E189CA6D2CF, - 0xC6B18576AAADBC8, 0xB65DEAA91299FAE3, 0xFB2B794B7F1027E7, 0x4E4317F443B5BEB, - 0x4B852D325939D0A6, 0xD5AE6BEEFB207FFC, 0x309682B281C7D374, 0xBAE309A194C3B475, - 0x8CC3F97B13B49F05, 0x98A9422FF8293967, 0x244B16B01076FF7C, 0xF8BF571C663D67EE, - 0x1F0D6758EEE30DA1, 0xC9B611D97ADEB9B7, 0xB7AFD5887B6C57A2, 0x6290AE846B984FE1, - 0x94DF4CDEACC1A5FD, 0x58A5BD1C5483AFF, 0x63166CC142BA3C37, 0x8DB8526EB2F76F40, - 0xE10880036F0D6D4E, 0x9E0523C9971D311D, 0x45EC2824CC7CD691, 0x575B8359E62382C9, - 0xFA9E400DC4889995, 0xD1823ECB45721568, 0xDAFD983B8206082F, 0xAA7D29082386A8CB, - 0x269FCD4403B87588, 0x1B91F5F728BDD1E0, 0xE4669F39040201F6, 0x7A1D7C218CF04ADE, - 0x65623C29D79CE5CE, 0x2368449096C00BB1, 0xAB9BF1879DA503BA, 0xBC23ECB1A458058E, - 0x9A58DF01BB401ECC, 0xA070E868A85F143D, 0x4FF188307DF2239E, 0x14D565B41A641183, - 0xEE13337452701602, 0x950E3DCF3F285E09, 0x59930254B9C80953, 0x3BF299408930DA6D, - 0xA955943F53691387, 0xA15EDECAA9CB8784, 0x29142127352BE9A0, 0x76F0371FFF4E7AFB, - 0x239F450274F2228, 0xBB073AF01D5E868B, 0xBFC80571C10E96C1, 0xD267088568222E23, - 0x9671A3D48E80B5B0, 0x55B5D38AE193BB81, 0x693AE2D0A18B04B8, 0x5C48B4ECADD5335F, - 0xFD743B194916A1CA, 0x2577018134BE98C4, 0xE77987E83C54A4AD, 0x28E11014DA33E1B9, - 0x270CC59E226AA213, 0x71495F756D1A5F60, 0x9BE853FB60AFEF77, 0xADC786A7F7443DBF, - 0x904456173B29A82, 0x58BC7A66C232BD5E, 0xF306558C673AC8B2, 0x41F639C6B6C9772A, - 0x216DEFE99FDA35DA, 0x11640CC71C7BE615, 0x93C43694565C5527, 0xEA038E6246777839, - 0xF9ABF3CE5A3E2469, 0x741E768D0FD312D2, 0x144B883CED652C6, 0xC20B5A5BA33F8552, - 0x1AE69633C3435A9D, 0x97A28CA4088CFDEC, 0x8824A43C1E96F420, 0x37612FA66EEEA746, - 0x6B4CB165F9CF0E5A, 0x43AA1C06A0ABFB4A, 0x7F4DC26FF162796B, 0x6CBACC8E54ED9B0F, - 0xA6B7FFEFD2BB253E, 0x2E25BC95B0A29D4F, 0x86D6A58BDEF1388C, 0xDED74AC576B6F054, - 0x8030BDBC2B45805D, 0x3C81AF70E94D9289, 0x3EFF6DDA9E3100DB, 0xB38DC39FDFCC8847, - 0x123885528D17B87E, 0xF2DA0ED240B1B642, 0x44CEFADCD54BF9A9, 0x1312200E433C7EE6, - 0x9FFCC84F3A78C748, 0xF0CD1F72248576BB, 0xEC6974053638CFE4, 0x2BA7B67C0CEC4E4C, - 0xAC2F4DF3E5CE32ED, 0xCB33D14326EA4C11, 0xA4E9044CC77E58BC, 0x5F513293D934FCEF, - 0x5DC9645506E55444, 0x50DE418F317DE40A, 0x388CB31A69DDE259, 0x2DB4A83455820A86, - 0x9010A91E84711AE9, 0x4DF7F0B7B1498371, 0xD62A2EABC0977179, 0x22FAC097AA8D5C0E, - 0xF49FCC2FF1DAF39B, 0x487FD5C66FF29281, 0xE8A30667FCDCA83F, 0x2C9B4BE3D2FCCE63, - 0xDA3FF74B93FBBBC2, 0x2FA165D2FE70BA66, 0xA103E279970E93D4, 0xBECDEC77B0E45E71, - 0xCFB41E723985E497, 0xB70AAA025EF75017, 0xD42309F03840B8E0, 0x8EFC1AD035898579, - 0x96C6920BE2B2ABC5, 0x66AF4163375A9172, 0x2174ABDCCA7127FB, 0xB33CCEA64A72FF41, - 0xF04A4933083066A5, 0x8D970ACDD7289AF5, 0x8F96E8E031C8C25E, 0xF3FEC02276875D47, - 0xEC7BF310056190DD, 0xF5ADB0AEBB0F1491, 0x9B50F8850FD58892, 0x4975488358B74DE8, - 0xA3354FF691531C61, 0x702BBE481D2C6EE, 0x89FB24057DEDED98, 0xAC3075138596E902, - 0x1D2D3580172772ED, 0xEB738FC28E6BC30D, 0x5854EF8F63044326, 0x9E5C52325ADD3BBE, - 0x90AA53CF325C4623, 0xC1D24D51349DD067, 0x2051CFEEA69EA624, 0x13220F0A862E7E4F, - 0xCE39399404E04864, 0xD9C42CA47086FCB7, 0x685AD2238A03E7CC, 0x66484B2AB2FF1DB, - 0xFE9D5D70EFBF79EC, 0x5B13B9DD9C481854, 0x15F0D475ED1509AD, 0xBEBCD060EC79851, - 0xD58C6791183AB7F8, 0xD1187C5052F3EEE4, 0xC95D1192E54E82FF, 0x86EEA14CB9AC6CA2, - 0x3485BEB153677D5D, 0xDD191D781F8C492A, 0xF60866BAA784EBF9, 0x518F643BA2D08C74, - 0x8852E956E1087C22, 0xA768CB8DC410AE8D, 0x38047726BFEC8E1A, 0xA67738B4CD3B45AA, - 0xAD16691CEC0DDE19, 0xC6D4319380462E07, 0xC5A5876D0BA61938, 0x16B9FA1FA58FD840, - 0x188AB1173CA74F18, 0xABDA2F98C99C021F, 0x3E0580AB134AE816, 0x5F3B05B773645ABB, - 0x2501A2BE5575F2F6, 0x1B2F74004E7E8BA9, 0x1CD7580371E8D953, 0x7F6ED89562764E30, - 0xB15926FF596F003D, 0x9F65293DA8C5D6B9, 0x6ECEF04DD690F84C, 0x4782275FFF33AF88, - 0xE41433083F820801, 0xFD0DFE409A1AF9B5, 0x4325A3342CDB396B, 0x8AE77E62B301B252, - 0xC36F9E9F6655615A, 0x85455A2D92D32C09, 0xF2C7DEA949477485, 0x63CFB4C133A39EBA, - 0x83B040CC6EBC5462, 0x3B9454C8FDB326B0, 0x56F56A9E87FFD78C, 0x2DC2940D99F42BC6, - 0x98F7DF096B096E2D, 0x19A6E01E3AD852BF, 0x42A99CCBDBD4B40B, 0xA59998AF45E9C559, - 0x366295E807D93186, 0x6B48181BFAA1F773, 0x1FEC57E2157A0A1D, 0x4667446AF6201AD5, - 0xE615EBCACFB0F075, 0xB8F31F4F68290778, 0x22713ED6CE22D11E, 0x3057C1A72EC3C93B, - 0xCB46ACC37C3F1F2F, 0xDBB893FD02AAF50E, 0x331FD92E600B9FCF, 0xA498F96148EA3AD6, - 0xA8D8426E8B6A83EA, 0xA089B274B7735CDC, 0x87F6B3731E524A11, 0x118808E5CBC96749, - 0x9906E4C7B19BD394, 0xAFED7F7E9B24A20C, 0x6509EADEEB3644A7, 0x6C1EF1D3E8EF0EDE, - 0xB9C97D43E9798FB4, 0xA2F2D784740C28A3, 0x7B8496476197566F, 0x7A5BE3E6B65F069D, - 0xF96330ED78BE6F10, 0xEEE60DE77A076A15, 0x2B4BEE4AA08B9BD0, 0x6A56A63EC7B8894E, - 0x2121359BA34FEF4, 0x4CBF99F8283703FC, 0x398071350CAF30C8, 0xD0A77A89F017687A, - 0xF1C1A9EB9E423569, 0x8C7976282DEE8199, 0x5D1737A5DD1F7ABD, 0x4F53433C09A9FA80, - 0xFA8B0C53DF7CA1D9, 0x3FD9DCBC886CCB77, 0xC040917CA91B4720, 0x7DD00142F9D1DCDF, - 0x8476FC1D4F387B58, 0x23F8E7C5F3316503, 0x32A2244E7E37339, 0x5C87A5D750F5A74B, - 0x82B4CC43698992E, 0xDF917BECB858F63C, 0x3270B8FC5BF86DDA, 0x10AE72BB29B5DD76, - 0x576AC94E7700362B, 0x1AD112DAC61EFB8F, 0x691BC30EC5FAA427, 0xFF246311CC327143, - 0x3142368E30E53206, 0x71380E31E02CA396, 0x958D5C960AAD76F1, 0xF8D6F430C16DA536, - 0xC8FFD13F1BE7E1D2, 0x7578AE66004DDBE1, 0x5833F01067BE646, 0xBB34B5AD3BFE586D, - 0x95F34C9A12B97F0, 0x247AB64525D60CA8, 0xDCDBC6F3017477D1, 0x4A2E14D4DECAD24D, - 0xBDB5E6D9BE0A1EEB, 0x2A7E70F7794301AB, 0xDEF42D8A270540FD, 0x1078EC0A34C22C1, - 0xE5DE511AF4C16387, 0x7EBB3A52BD9A330A, 0x77697857AA7D6435, 0x4E831603AE4C32, - 0xE7A21020AD78E312, 0x9D41A70C6AB420F2, 0x28E06C18EA1141E6, 0xD2B28CBD984F6B28, - 0x26B75F6C446E9D83, 0xBA47568C4D418D7F, 0xD80BADBFE6183D8E, 0xE206D7F5F166044, - 0xE258A43911CBCA3E, 0x723A1746B21DC0BC, 0xC7CAA854F5D7CDD3, 0x7CAC32883D261D9C, - 0x7690C26423BA942C, 0x17E55524478042B8, 0xE0BE477656A2389F, 0x4D289B5E67AB2DA0, - 0x44862B9C8FBBFD31, 0xB47CC8049D141365, 0x822C1B362B91C793, 0x4EB14655FB13DFD8, - 0x1ECBBA0714E2A97B, 0x6143459D5CDE5F14, 0x53A8FBF1D5F0AC89, 0x97EA04D81C5E5B00, - 0x622181A8D4FDB3F3, 0xE9BCD341572A1208, 0x1411258643CCE58A, 0x9144C5FEA4C6E0A4, - 0xD33D06565CF620F, 0x54A48D489F219CA1, 0xC43E5EAC6D63C821, 0xA9728B3A72770DAF, - 0xD7934E7B20DF87EF, 0xE35503B61A3E86E5, 0xCAE321FBC819D504, 0x129A50B3AC60BFA6, - 0xCD5E68EA7E9FB6C3, 0xB01C90199483B1C7, 0x3DE93CD5C295376C, 0xAED52EDF2AB9AD13, - 0x2E60F512C0A07884, 0xBC3D86A3E36210C9, 0x35269D9B163951CE, 0xC7D6E2AD0CDB5FA, - 0x59E86297D87F5733, 0x298EF221898DB0E7, 0x55000029D1A5AA7E, 0x8BC08AE1B5061B45, - 0xC2C31C2B6C92703A, 0x94CC596BAF25EF42, 0xA1D73DB22540456, 0x4B6A0F9D9C4179A, - 0xEFFDAFA2AE3D3C60, 0xF7C8075BB49496C4, 0x9CC5C7141D1CD4E3, 0x78BD1638218E5534, - 0xB2F11568F850246A, 0xEDFABCFA9502BC29, 0x796CE5F2DA23051B, 0xAAE128B0DC93537C, - 0x3A493DA0EE4B29AE, 0xB5DF6B2C416895D7, 0xFCABBD25122D7F37, 0x70810B58105DC4B1, - 0xE10FDD37F7882A90, 0x524DCAB5518A3F5C, 0x3C9E85878451255B, 0x4029828119BD34E2, - 0x74A05B6F5D3CECCB, 0xB610021542E13ECA, 0xFF979D12F59E2AC, 0x6037DA27E4F9CC50, - 0x5E92975A0DF1847D, 0xD66DE190D3E623FE, 0x5032D6B87B568048, 0x9A36B7CE8235216E, - 0x80272A7A24F64B4A, 0x93EFED8B8C6916F7, 0x37DDBFF44CCE1555, 0x4B95DB5D4B99BD25, - 0x92D3FDA169812FC0, 0xFB1A4A9A90660BB6, 0x730C196946A4B9B2, 0x81E289AA7F49DA68, - 0x64669A0F83B1A05F, 0x27B3FF7D9644F48B, 0xCC6B615C8DB675B3, 0x674F20B9BCEBBE95, - 0x6F31238275655982, 0x5AE488713E45CF05, 0xBF619F9954C21157, 0xEABAC46040A8EAE9, - 0x454C6FE9F2C0C1CD, 0x419CF6496412691C, 0xD3DC3BEF265B0F70, 0x6D0E60F5C3578A9E, - 0x5B0E608526323C55, 0x1A46C1A9FA1B59F5, 0xA9E245A17C4C8FFA, 0x65CA5159DB2955D7, - 0x5DB0A76CE35AFC2, 0x81EAC77EA9113D45, 0x528EF88AB6AC0A0D, 0xA09EA253597BE3FF, - 0x430DDFB3AC48CD56, 0xC4B3A67AF45CE46F, 0x4ECECFD8FBE2D05E, 0x3EF56F10B39935F0, - 0xB22D6829CD619C6, 0x17FD460A74DF2069, 0x6CF8CC8E8510ED40, 0xD6C824BF3A6ECAA7, - 0x61243D581A817049, 0x48BACB6BBC163A2, 0xD9A38AC27D44CC32, 0x7FDDFF5BAAF410AB, - 0xAD6D495AA804824B, 0xE1A6A74F2D8C9F94, 0xD4F7851235DEE8E3, 0xFD4B7F886540D893, - 0x247C20042AA4BFDA, 0x96EA1C517D1327C, 0xD56966B4361A6685, 0x277DA5C31221057D, - 0x94D59893A43ACFF7, 0x64F0C51CCDC02281, 0x3D33BCC4FF6189DB, 0xE005CB184CE66AF1, - 0xFF5CCD1D1DB99BEA, 0xB0B854A7FE42980F, 0x7BD46A6A718D4B9F, 0xD10FA8CC22A5FD8C, - 0xD31484952BE4BD31, 0xC7FA975FCB243847, 0x4886ED1E5846C407, 0x28CDDB791EB70B04, - 0xC2B00BE2F573417F, 0x5C9590452180F877, 0x7A6BDDFFF370EB00, 0xCE509E38D6D9D6A4, - 0xEBEB0F00647FA702, 0x1DCC06CF76606F06, 0xE4D9F28BA286FF0A, 0xD85A305DC918C262, - 0x475B1D8732225F54, 0x2D4FB51668CCB5FE, 0xA679B9D9D72BBA20, 0x53841C0D912D43A5, - 0x3B7EAA48BF12A4E8, 0x781E0E47F22F1DDF, 0xEFF20CE60AB50973, 0x20D261D19DFFB742, - 0x16A12B03062A2E39, 0x1960EB2239650495, 0x251C16FED50EB8B8, 0x9AC0C330F826016E, - 0xED152665953E7671, 0x2D63194A6369570, 0x5074F08394B1C987, 0x70BA598C90B25CE1, - 0x794A15810B9742F6, 0xD5925E9FCAF8C6C, 0x3067716CD868744E, 0x910AB077E8D7731B, - 0x6A61BBDB5AC42F61, 0x93513EFBF0851567, 0xF494724B9E83E9D5, 0xE887E1985C09648D, - 0x34B1D3C675370CFD, 0xDC35E433BC0D255D, 0xD0AAB84234131BE0, 0x8042A50B48B7EAF, - 0x9997C4EE44A3AB35, 0x829A7B49201799D0, 0x263B8307B7C54441, 0x752F95F4FD6A6CA6, - 0x927217402C08C6E5, 0x2A8AB754A795D9EE, 0xA442F7552F72943D, 0x2C31334E19781208, - 0x4FA98D7CEAEE6291, 0x55C3862F665DB309, 0xBD0610175D53B1F3, 0x46FE6CB840413F27, - 0x3FE03792DF0CFA59, 0xCFE700372EB85E8F, 0xA7BE29E7ADBCE118, 0xE544EE5CDE8431DD, - 0x8A781B1B41F1873E, 0xA5C94C78A0D2F0E7, 0x39412E2877B60728, 0xA1265EF3AFC9A62C, - 0xBCC2770C6A2506C5, 0x3AB66DD5DCE1CE12, 0xE65499D04A675B37, 0x7D8F523481BFD216, - 0xF6F64FCEC15F389, 0x74EFBE618B5B13C8, 0xACDC82B714273E1D, 0xDD40BFE003199D17, - 0x37E99257E7E061F8, 0xFA52626904775AAA, 0x8BBBF63A463D56F9, 0xF0013F1543A26E64, - 0xA8307E9F879EC898, 0xCC4C27A4150177CC, 0x1B432F2CCA1D3348, 0xDE1D1F8F9F6FA013, - 0x606602A047A7DDD6, 0xD237AB64CC1CB2C7, 0x9B938E7225FCD1D3, 0xEC4E03708E0FF476, - 0xFEB2FBDA3D03C12D, 0xAE0BCED2EE43889A, 0x22CB8923EBFB4F43, 0x69360D013CF7396D, - 0x855E3602D2D4E022, 0x73805BAD01F784C, 0x33E17A133852F546, 0xDF4874058AC7B638, - 0xBA92B29C678AA14A, 0xCE89FC76CFAADCD, 0x5F9D4E0908339E34, 0xF1AFE9291F5923B9, - 0x6E3480F60F4A265F, 0xEEBF3A2AB29B841C, 0xE21938A88F91B4AD, 0x57DFEFF845C6D3C3, - 0x2F006B0BF62CAAF2, 0x62F479EF6F75EE78, 0x11A55AD41C8916A9, 0xF229D29084FED453, - 0x42F1C27B16B000E6, 0x2B1F76749823C074, 0x4B76ECA3C2745360, 0x8C98F463B91691BD, - 0x14BCC93CF1ADE66A, 0x8885213E6D458397, 0x8E177DF0274D4711, 0xB49B73B5503F2951, - 0x10168168C3F96B6B, 0xE3D963B63CAB0AE, 0x8DFC4B5655A1DB14, 0xF789F1356E14DE5C, - 0x683E68AF4E51DAC1, 0xC9A84F9D8D4B0FD9, 0x3691E03F52A0F9D1, 0x5ED86E46E1878E80, - 0x3C711A0E99D07150, 0x5A0865B20C4E9310, 0x56FBFC1FE4F0682E, 0xEA8D5DE3105EDF9B, - 0x71ABFDB12379187A, 0x2EB99DE1BEE77B9C, 0x21ECC0EA33CF4523, 0x59A4D7521805C7A1, - 0x3896F5EB56AE7C72, 0xAA638F3DB18F75DC, 0x9F39358DABE9808E, 0xB7DEFA91C00B72AC, - 0x6B5541FD62492D92, 0x6DC6DEE8F92E4D5B, 0x353F57ABC4BEEA7E, 0x735769D6DA5690CE, - 0xA234AA642391484, 0xF6F9508028F80D9D, 0xB8E319A27AB3F215, 0x31AD9C1151341A4D, - 0x773C22A57BEF5805, 0x45C7561A07968633, 0xF913DA9E249DBE36, 0xDA652D9B78A64C68, - 0x4C27A97F3BC334EF, 0x76621220E66B17F4, 0x967743899ACD7D0B, 0xF3EE5BCAE0ED6782, - 0x409F753600C879FC, 0x6D09A39B5926DB6, 0x6F83AEB0317AC588, 0x1E6CA4A86381F21, - 0x66FF3462D19F3025, 0x72207C24DDFD3BFB, 0x4AF6B6D3E2ECE2EB, 0x9C994DBEC7EA08DE, - 0x49ACE597B09A8BC4, 0xB38C4766CF0797BA, 0x131B9373C57C2A75, 0xB1822CCE61931E58, - 0x9D7555B909BA1C0C, 0x127FAFDD937D11D2, 0x29DA3BADC66D92E4, 0xA2C1D57154C2ECBC, - 0x58C5134D82F6FE24, 0x1C3AE3515B62274F, 0xE907C82E01CB8126, 0xF8ED091913E37FCB, - 0x3249D8F9C80046C9, 0x80CF9BEDE388FB63, 0x1881539A116CF19E, 0x5103F3F76BD52457, - 0x15B7E6F5AE47F7A8, 0xDBD7C6DED47E9CCF, 0x44E55C410228BB1A, 0xB647D4255EDB4E99, - 0x5D11882BB8AAFC30, 0xF5098BBB29D3212A, 0x8FB5EA14E90296B3, 0x677B942157DD025A, - 0xFB58E7C0A390ACB5, 0x89D3674C83BD4A01, 0x9E2DA4DF4BF3B93B, 0xFCC41E328CAB4829, - 0x3F38C96BA582C52, 0xCAD1BDBD7FD85DB2, 0xBBB442C16082AE83, 0xB95FE86BA5DA9AB0, - 0xB22E04673771A93F, 0x845358C9493152D8, 0xBE2A488697B4541E, 0x95A2DC2DD38E6966, - 0xC02C11AC923C852B, 0x2388B1990DF2A87B, 0x7C8008FA1B4F37BE, 0x1F70D0C84D54E503, - 0x5490ADEC7ECE57D4, 0x2B3C27D9063A3A, 0x7EAEA3848030A2BF, 0xC602326DED2003C0, - 0x83A7287D69A94086, 0xC57A5FCB30F57A8A, 0xB56844E479EBE779, 0xA373B40F05DCBCE9, - 0xD71A786E88570EE2, 0x879CBACDBDE8F6A0, 0x976AD1BCC164A32F, 0xAB21E25E9666D78B, - 0x901063AAE5E5C33C, 0x9818B34448698D90, 0xE36487AE3E1E8ABB, 0xAFBDF931893BDCB4, - 0x6345A0DC5FBBD519, 0x8628FE269B9465CA, 0x1E5D01603F9C51EC, 0x4DE44006A15049B7, - 0xBF6C70E5F776CBB1, 0x411218F2EF552BED, 0xCB0C0708705A36A3, 0xE74D14754F986044, - 0xCD56D9430EA8280E, 0xC12591D7535F5065, 0xC83223F1720AEF96, 0xC3A0396F7363A51F - }; - #endregion - } + /// + /// Initializes a new instance of the class. + /// + public TigerHash() + { + _internalDataBuffer = new byte[BLOCKSIZE]; + //HashSizeValue = 3 * 8 * 8; + + Initialize(); + } + + /// + /// Initializes an instance of . + /// + public override void Initialize() + { + _a = 0x123456789ABCDEF; + _b = 0xFEDCBA9876543210; + _c = 0xF096A5B4C3B2E187; + + _bufferPosition = 0; + _totalLength = 0; + } + + + /// Routes data written to the object into the hash algorithm for computing the hash. + /// The input data. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the array to use as data. + protected override void HashCore(byte[] array, int ibStart, int cbSize) + { + _totalLength += cbSize; + + byte[] buffer = _internalDataBuffer; + + int offset = _bufferPosition; + int end = ibStart + cbSize; + + while (ibStart < end) + { + int count = BLOCKSIZE - offset; + + if (count > cbSize) + { + count = cbSize; + } + + Buffer.BlockCopy(array, ibStart, buffer, offset, count); + + ibStart += count; + offset += count; + cbSize -= count; + + if (BLOCKSIZE > offset) + break; + + ProcessBlock(); + + offset = 0; + } + + _bufferPosition = offset; + } + + /// + /// Returns the computed hash value after all data has been written to the object. + /// + /// The computed hash code. + protected override byte[] HashFinal() + { + int bufferOffset = _bufferPosition; + byte[] buffer = _internalDataBuffer; + + buffer[bufferOffset] = 1; + bufferOffset += 1; + + if ((BLOCKSIZE - 8) <= bufferOffset) + { + Array.Clear(buffer, bufferOffset, BLOCKSIZE - bufferOffset); + + ProcessBlock(); + bufferOffset = 0; + } + + Array.Clear(buffer, bufferOffset, BLOCKSIZE - bufferOffset - 8); + + TigerHash.LongToBytes(((ulong)_totalLength) << 3, buffer, BLOCKSIZE - 8); + + ProcessBlock(); + + byte[] retval = new byte[24]; + + TigerHash.LongToBytes(_a, retval, 0); + TigerHash.LongToBytes(_b, retval, 8); + TigerHash.LongToBytes(_c, retval, 16); + + return retval; + } + + private unsafe void ProcessBlock() + { + #region [ Original code for reference ] + //int blockIndex = 0; + //ulong[] block = _block; + //byte[] buffer = _internalDataBuffer; + + //for (int offset = 0; offset < BLOCKSIZE; offset += 8) + //{ + // block[blockIndex] = + // (((ulong)buffer[offset + 7]) << 56) | + // ((((ulong)buffer[offset + 6]) & 0xFF) << 48) | + // ((((ulong)buffer[offset + 5]) & 0xFF) << 40) | + // ((((ulong)buffer[offset + 4]) & 0xFF) << 32) | + // ((((ulong)buffer[offset + 3]) & 0xFF) << 24) | + // ((((ulong)buffer[offset + 2]) & 0xFF) << 16) | + // ((((ulong)buffer[offset + 1]) & 0xFF) << 8) | + // (((ulong)buffer[offset]) & 0xFF); + + // blockIndex++; + //} + #endregion + + Buffer.BlockCopy(_internalDataBuffer, 0, _block, 0, BLOCKSIZE); + + Compress(); + } + + private void Compress() + { + ulong aa, bb, cc; + ulong[] tmpBlock; + + aa = _a; + bb = _b; + cc = _c; + + tmpBlock = _block; + + RoundABC(tmpBlock[0], 5); + RoundBCA(tmpBlock[1], 5); + RoundCAB(tmpBlock[2], 5); + RoundABC(tmpBlock[3], 5); + RoundBCA(tmpBlock[4], 5); + RoundCAB(tmpBlock[5], 5); + RoundABC(tmpBlock[6], 5); + RoundBCA(tmpBlock[7], 5); + + TigerHash.Schedule(tmpBlock); + + RoundCAB(tmpBlock[0], 7); + RoundABC(tmpBlock[1], 7); + RoundBCA(tmpBlock[2], 7); + RoundCAB(tmpBlock[3], 7); + RoundABC(tmpBlock[4], 7); + RoundBCA(tmpBlock[5], 7); + RoundCAB(tmpBlock[6], 7); + RoundABC(tmpBlock[7], 7); + + TigerHash.Schedule(tmpBlock); + + RoundBCA(tmpBlock[0], 9); + RoundCAB(tmpBlock[1], 9); + RoundABC(tmpBlock[2], 9); + RoundBCA(tmpBlock[3], 9); + RoundCAB(tmpBlock[4], 9); + RoundABC(tmpBlock[5], 9); + RoundBCA(tmpBlock[6], 9); + RoundCAB(tmpBlock[7], 9); + + _a = _a ^ aa; + _b -= bb; + _c += cc; + } + + private static void Schedule(ulong[] x) + { + x[0] -= x[7] ^ 0xA5A5A5A5A5A5A5A5; + x[1] = x[1] ^ x[0]; + x[2] += x[1]; + x[3] -= x[2] ^ ((~x[1]) << 19); + x[4] = x[4] ^ x[3]; + x[5] += x[4]; + x[6] -= x[5] ^ (((~x[4]) >> 23) & 0x1FFFFFFFFFF); + x[7] = x[7] ^ x[6]; + x[0] += x[7]; + x[1] -= x[0] ^ ((~x[7]) << 19); + x[2] = x[2] ^ x[1]; + x[3] += x[2]; + x[4] -= x[3] ^ (((~x[2]) >> 23) & 0x1FFFFFFFFFF); + x[5] = x[5] ^ x[4]; + x[6] += x[5]; + x[7] -= x[6] ^ 0x123456789ABCDEF; + } + + private void RoundABC(ulong x, uint mul) + { + ulong[] T = TigerHash.T; + + ulong tmpC = _c ^ x; + int ch = (int)(tmpC >> 32); + int cl = (int)(tmpC); + + _a -= T[cl & 0xFF] ^ T[((cl >> 16) & 0xFF) + 0x100] ^ T[(ch & 0xFF) + 0x200] ^ T[((ch >> 16) & 0xFF) + 0x300]; + _b += T[((cl >> 8) & 0xFF) + 0x300] ^ T[((cl >> 24) & 0xFF) + 0x200] ^ T[((ch >> 8) & 0xFF) + 0x100] ^ T[(ch >> 24) & 0xFF]; + + _b *= mul; + + _c = tmpC; + } + + private void RoundBCA(ulong x, uint mul) + { + ulong[] T = TigerHash.T; + + ulong tmpA = _a ^ x; + int ah = (int)(tmpA >> 32); + int al = (int)(tmpA); + + _b -= T[al & 0xFF] ^ T[((al >> 16) & 0xFF) + 0x100] ^ T[(ah & 0xFF) + 0x200] ^ T[((ah >> 16) & 0xFF) + 0x300]; + _c += T[((al >> 8) & 0xFF) + 0x300] ^ T[((al >> 24) & 0xFF) + 0x200] ^ T[((ah >> 8) & 0xFF) + 0x100] ^ T[(ah >> 24) & 0xFF]; + _c *= mul; + + _a = tmpA; + } + + private void RoundCAB(ulong x, uint mul) + { + ulong[] T = TigerHash.T; + + ulong tmpB = _b ^ x; + int bh = (int)(tmpB >> 32); + int bl = (int)(tmpB); + + _c -= T[bl & 0xFF] ^ T[((bl >> 16) & 0xFF) + 0x100] ^ T[(bh & 0xFF) + 0x200] ^ T[((bh >> 16) & 0xFF) + 0x300]; + _a += T[((bl >> 8) & 0xFF) + 0x300] ^ T[((bl >> 24) & 0xFF) + 0x200] ^ T[((bh >> 8) & 0xFF) + 0x100] ^ T[(bh >> 24) & 0xFF]; + _a *= mul; + + _b = tmpB; + } + + private static unsafe void LongToBytes(ulong value, byte[] buffer, int offset) + { + fixed (byte* numRef = buffer) + { + *((ulong*)(numRef + offset)) = value; + } + } + + #region [ static readonly ulong[] T ] + private static readonly ulong[] T = + { + 0x2AAB17CF7E90C5E, 0xAC424B03E243A8EC, 0x72CD5BE30DD5FCD3, 0x6D019B93F6F97F3A, + 0xCD9978FFD21F9193, 0x7573A1C9708029E2, 0xB164326B922A83C3, 0x46883EEE04915870, + 0xEAACE3057103ECE6, 0xC54169B808A3535C, 0x4CE754918DDEC47C, 0xAA2F4DFDC0DF40C, + 0x10B76F18A74DBEFA, 0xC6CCB6235AD1AB6A, 0x13726121572FE2FF, 0x1A488C6F199D921E, + 0x4BC9F9F4DA0007CA, 0x26F5E6F6E85241C7, 0x859079DBEA5947B6, 0x4F1885C5C99E8C92, + 0xD78E761EA96F864B, 0x8E36428C52B5C17D, 0x69CF6827373063C1, 0xB607C93D9BB4C56E, + 0x7D820E760E76B5EA, 0x645C9CC6F07FDC42, 0xBF38A078243342E0, 0x5F6B343C9D2E7D04, + 0xF2C28AEB600B0EC6, 0x6C0ED85F7254BCAC, 0x71592281A4DB4FE5, 0x1967FA69CE0FED9F, + 0xFD5293F8B96545DB, 0xC879E9D7F2A7600B, 0x860248920193194E, 0xA4F9533B2D9CC0B3, + 0x9053836C15957613, 0xDB6DCF8AFC357BF1, 0x18BEEA7A7A370F57, 0x37117CA50B99066, + 0x6AB30A9774424A35, 0xF4E92F02E325249B, 0x7739DB07061CCAE1, 0xD8F3B49CECA42A05, + 0xBD56BE3F51382F73, 0x45FAED5843B0BB28, 0x1C813D5C11BF1F83, 0x8AF0E4B6D75FA169, + 0x33EE18A487AD9999, 0x3C26E8EAB1C94410, 0xB510102BC0A822F9, 0x141EEF310CE6123B, + 0xFC65B90059DDB154, 0xE0158640C5E0E607, 0x884E079826C3A3CF, 0x930D0D9523C535FD, + 0x35638D754E9A2B00, 0x4085FCCF40469DD5, 0xC4B17AD28BE23A4C, 0xCAB2F0FC6A3E6A2E, + 0x2860971A6B943FCD, 0x3DDE6EE212E30446, 0x6222F32AE01765AE, 0x5D550BB5478308FE, + 0xA9EFA98DA0EDA22A, 0xC351A71686C40DA7, 0x1105586D9C867C84, 0xDCFFEE85FDA22853, + 0xCCFBD0262C5EEF76, 0xBAF294CB8990D201, 0xE69464F52AFAD975, 0x94B013AFDF133E14, + 0x6A7D1A32823C958, 0x6F95FE5130F61119, 0xD92AB34E462C06C0, 0xED7BDE33887C71D2, + 0x79746D6E6518393E, 0x5BA419385D713329, 0x7C1BA6B948A97564, 0x31987C197BFDAC67, + 0xDE6C23C44B053D02, 0x581C49FED002D64D, 0xDD474D6338261571, 0xAA4546C3E473D062, + 0x928FCE349455F860, 0x48161BBACAAB94D9, 0x63912430770E6F68, 0x6EC8A5E602C6641C, + 0x87282515337DDD2B, 0x2CDA6B42034B701B, 0xB03D37C181CB096D, 0xE108438266C71C6F, + 0x2B3180C7EB51B255, 0xDF92B82F96C08BBC, 0x5C68C8C0A632F3BA, 0x5504CC861C3D0556, + 0xABBFA4E55FB26B8F, 0x41848B0AB3BACEB4, 0xB334A273AA445D32, 0xBCA696F0A85AD881, + 0x24F6EC65B528D56C, 0xCE1512E90F4524A, 0x4E9DD79D5506D35A, 0x258905FAC6CE9779, + 0x2019295B3E109B33, 0xF8A9478B73A054CC, 0x2924F2F934417EB0, 0x3993357D536D1BC4, + 0x38A81AC21DB6FF8B, 0x47C4FBF17D6016BF, 0x1E0FAADD7667E3F5, 0x7ABCFF62938BEB96, + 0xA78DAD948FC179C9, 0x8F1F98B72911E50D, 0x61E48EAE27121A91, 0x4D62F7AD31859808, + 0xECEBA345EF5CEAEB, 0xF5CEB25EBC9684CE, 0xF633E20CB7F76221, 0xA32CDF06AB8293E4, + 0x985A202CA5EE2CA4, 0xCF0B8447CC8A8FB1, 0x9F765244979859A3, 0xA8D516B1A1240017, + 0xBD7BA3EBB5DC726, 0xE54BCA55B86ADB39, 0x1D7A3AFD6C478063, 0x519EC608E7669EDD, + 0xE5715A2D149AA23, 0x177D4571848FF194, 0xEEB55F3241014C22, 0xF5E5CA13A6E2EC2, + 0x8029927B75F5C361, 0xAD139FABC3D6E436, 0xD5DF1A94CCF402F, 0x3E8BD948BEA5DFC8, + 0xA5A0D357BD3FF77E, 0xA2D12E251F74F645, 0x66FD9E525E81A082, 0x2E0C90CE7F687A49, + 0xC2E8BCBEBA973BC5, 0x1BCE509745F, 0x423777BBE6DAB3D6, 0xD1661C7EAEF06EB5, + 0xA1781F354DAACFD8, 0x2D11284A2B16AFFC, 0xF1FC4F67FA891D1F, 0x73ECC25DCB920ADA, + 0xAE610C22C2A12651, 0x96E0A810D356B78A, 0x5A9A381F2FE7870F, 0xD5AD62EDE94E5530, + 0xD225E5E8368D1427, 0x65977B70C7AF4631, 0x99F889B2DE39D74F, 0x233F30BF54E1D143, + 0x9A9675D3D9A63C97, 0x5470554FF334F9A8, 0x166ACB744A4F5688, 0x70C74CAAB2E4AEAD, + 0xF0D091646F294D12, 0x57B82A89684031D1, 0xEFD95A5A61BE0B6B, 0x2FBD12E969F2F29A, + 0x9BD37013FEFF9FE8, 0x3F9B0404D6085A06, 0x4940C1F3166CFE15, 0x9542C4DCDF3DEFB, + 0xB4C5218385CD5CE3, 0xC935B7DC4462A641, 0x3417F8A68ED3B63F, 0xB80959295B215B40, + 0xF99CDAEF3B8C8572, 0x18C0614F8FCB95D, 0x1B14ACCD1A3ACDF3, 0x84D471F200BB732D, + 0xC1A3110E95E8DA16, 0x430A7220BF1A82B8, 0xB77E090D39DF210E, 0x5EF4BD9F3CD05E9D, + 0x9D4FF6DA7E57A444, 0xDA1D60E183D4A5F8, 0xB287C38417998E47, 0xFE3EDC121BB31886, + 0xC7FE3CCC980CCBEF, 0xE46FB590189BFD03, 0x3732FD469A4C57DC, 0x7EF700A07CF1AD65, + 0x59C64468A31D8859, 0x762FB0B4D45B61F6, 0x155BAED099047718, 0x68755E4C3D50BAA6, + 0xE9214E7F22D8B4DF, 0x2ADDBF532EAC95F4, 0x32AE3909B4BD0109, 0x834DF537B08E3450, + 0xFA209DA84220728D, 0x9E691D9B9EFE23F7, 0x446D288C4AE8D7F, 0x7B4CC524E169785B, + 0x21D87F0135CA1385, 0xCEBB400F137B8AA5, 0x272E2B66580796BE, 0x3612264125C2B0DE, + 0x57702BDAD1EFBB2, 0xD4BABB8EACF84BE9, 0x91583139641BC67B, 0x8BDC2DE08036E024, + 0x603C8156F49F68ED, 0xF7D236F7DBEF5111, 0x9727C4598AD21E80, 0xA08A0896670A5FD7, + 0xCB4A8F4309EBA9CB, 0x81AF564B0F7036A1, 0xC0B99AA778199ABD, 0x959F1EC83FC8E952, + 0x8C505077794A81B9, 0x3ACAAF8F056338F0, 0x7B43F50627A6778, 0x4A44AB49F5ECCC77, + 0x3BC3D6E4B679EE98, 0x9CC0D4D1CF14108C, 0x4406C00B206BC8A0, 0x82A18854C8D72D89, + 0x67E366B35C3C432C, 0xB923DD61102B37F2, 0x56AB2779D884271D, 0xBE83E1B0FF1525AF, + 0xFB7C65D4217E49A9, 0x6BDBE0E76D48E7D4, 0x8DF828745D9179E, 0x22EA6A9ADD53BD34, + 0xE36E141C5622200A, 0x7F805D1B8CB750EE, 0xAFE5C7A59F58E837, 0xE27F996A4FB1C23C, + 0xD3867DFB0775F0D0, 0xD0E673DE6E88891A, 0x123AEB9EAFB86C25, 0x30F1D5D5C145B895, + 0xBB434A2DEE7269E7, 0x78CB67ECF931FA38, 0xF33B0372323BBF9C, 0x52D66336FB279C74, + 0x505F33AC0AFB4EAA, 0xE8A5CD99A2CCE187, 0x534974801E2D30BB, 0x8D2D5711D5876D90, + 0x1F1A412891BC038E, 0xD6E2E71D82E56648, 0x74036C3A497732B7, 0x89B67ED96361F5AB, + 0xFFED95D8F1EA02A2, 0xE72B3BD61464D43D, 0xA6300F170BDC4820, 0xEBC18760ED78A77A, + 0xE6A6BE5A05A12138, 0xB5A122A5B4F87C98, 0x563C6089140B6990, 0x4C46CB2E391F5DD5, + 0xD932ADDBC9B79434, 0x8EA70E42015AFF5, 0xD765A6673E478CF1, 0xC4FB757EAB278D99, + 0xDF11C6862D6E0692, 0xDDEB84F10D7F3B16, 0x6F2EF604A665EA04, 0x4A8E0F0FF0E0DFB3, + 0xA5EDEEF83DBCBA51, 0xFC4F0A2A0EA4371E, 0xE83E1DA85CB38429, 0xDC8FF882BA1B1CE2, + 0xCD45505E8353E80D, 0x18D19A00D4DB0717, 0x34A0CFEDA5F38101, 0xBE77E518887CAF2, + 0x1E341438B3C45136, 0xE05797F49089CCF9, 0xFFD23F9DF2591D14, 0x543DDA228595C5CD, + 0x661F81FD99052A33, 0x8736E641DB0F7B76, 0x15227725418E5307, 0xE25F7F46162EB2FA, + 0x48A8B2126C13D9FE, 0xAFDC541792E76EEA, 0x3D912BFC6D1898F, 0x31B1AAFA1B83F51B, + 0xF1AC2796E42AB7D9, 0x40A3A7D7FCD2EBAC, 0x1056136D0AFBBCC5, 0x7889E1DD9A6D0C85, + 0xD33525782A7974AA, 0xA7E25D09078AC09B, 0xBD4138B3EAC6EDD0, 0x920ABFBE71EB9E70, + 0xA2A5D0F54FC2625C, 0xC054E36B0B1290A3, 0xF6DD59FF62FE932B, 0x3537354511A8AC7D, + 0xCA845E9172FADCD4, 0x84F82B60329D20DC, 0x79C62CE1CD672F18, 0x8B09A2ADD124642C, + 0xD0C1E96A19D9E726, 0x5A786A9B4BA9500C, 0xE020336634C43F3, 0xC17B474AEB66D822, + 0x6A731AE3EC9BAAC2, 0x8226667AE0840258, 0x67D4567691CAECA5, 0x1D94155C4875ADB5, + 0x6D00FD985B813FDF, 0x51286EFCB774CD06, 0x5E8834471FA744AF, 0xF72CA0AEE761AE2E, + 0xBE40E4CDAEE8E09A, 0xE9970BBB5118F665, 0x726E4BEB33DF1964, 0x703B000729199762, + 0x4631D816F5EF30A7, 0xB880B5B51504A6BE, 0x641793C37ED84B6C, 0x7B21ED77F6E97D96, + 0x776306312EF96B73, 0xAE528948E86FF3F4, 0x53DBD7F286A3F8F8, 0x16CADCE74CFC1063, + 0x5C19BDFA52C6DD, 0x68868F5D64D46AD3, 0x3A9D512CCF1E186A, 0x367E62C2385660AE, + 0xE359E7EA77DCB1D7, 0x526C0773749ABE6E, 0x735AE5F9D09F734B, 0x493FC7CC8A558BA8, + 0xB0B9C1533041AB45, 0x321958BA470A59BD, 0x852DB00B5F46C393, 0x91209B2BD336B0E5, + 0x6E604F7D659EF19F, 0xB99A8AE2782CCB24, 0xCCF52AB6C814C4C7, 0x4727D9AFBE11727B, + 0x7E950D0C0121B34D, 0x756F435670AD471F, 0xF5ADD442615A6849, 0x4E87E09980B9957A, + 0x2ACFA1DF50AEE355, 0xD898263AFD2FD556, 0xC8F4924DD80C8FD6, 0xCF99CA3D754A173A, + 0xFE477BACAF91BF3C, 0xED5371F6D690C12D, 0x831A5C285E687094, 0xC5D3C90A3708A0A4, + 0xF7F903717D06580, 0x19F9BB13B8FDF27F, 0xB1BD6F1B4D502843, 0x1C761BA38FFF4012, + 0xD1530C4E2E21F3B, 0x8943CE69A7372C8A, 0xE5184E11FEB5CE66, 0x618BDB80BD736621, + 0x7D29BAD68B574D0B, 0x81BB613E25E6FE5B, 0x71C9C10BC07913F, 0xC7BEEB7909AC2D97, + 0xC3E58D353BC5D757, 0xEB017892F38F61E8, 0xD4EFFB9C9B1CC21A, 0x99727D26F494F7AB, + 0xA3E063A2956B3E03, 0x9D4A8B9A4AA09C30, 0x3F6AB7D500090FB4, 0x9CC0F2A057268AC0, + 0x3DEE9D2DEDBF42D1, 0x330F49C87960A972, 0xC6B2720287421B41, 0xAC59EC07C00369C, + 0xEF4EAC49CB353425, 0xF450244EEF0129D8, 0x8ACC46E5CAF4DEB6, 0x2FFEAB63989263F7, + 0x8F7CB9FE5D7A4578, 0x5BD8F7644E634635, 0x427A7315BF2DC900, 0x17D0C4AA2125261C, + 0x3992486C93518E50, 0xB4CBFEE0A2D7D4C3, 0x7C75D6202C5DDD8D, 0xDBC295D8E35B6C61, + 0x60B369D302032B19, 0xCE42685FDCE44132, 0x6F3DDB9DDF65610, 0x8EA4D21DB5E148F0, + 0x20B0FCE62FCD496F, 0x2C1B912358B0EE31, 0xB28317B818F5A308, 0xA89C1E189CA6D2CF, + 0xC6B18576AAADBC8, 0xB65DEAA91299FAE3, 0xFB2B794B7F1027E7, 0x4E4317F443B5BEB, + 0x4B852D325939D0A6, 0xD5AE6BEEFB207FFC, 0x309682B281C7D374, 0xBAE309A194C3B475, + 0x8CC3F97B13B49F05, 0x98A9422FF8293967, 0x244B16B01076FF7C, 0xF8BF571C663D67EE, + 0x1F0D6758EEE30DA1, 0xC9B611D97ADEB9B7, 0xB7AFD5887B6C57A2, 0x6290AE846B984FE1, + 0x94DF4CDEACC1A5FD, 0x58A5BD1C5483AFF, 0x63166CC142BA3C37, 0x8DB8526EB2F76F40, + 0xE10880036F0D6D4E, 0x9E0523C9971D311D, 0x45EC2824CC7CD691, 0x575B8359E62382C9, + 0xFA9E400DC4889995, 0xD1823ECB45721568, 0xDAFD983B8206082F, 0xAA7D29082386A8CB, + 0x269FCD4403B87588, 0x1B91F5F728BDD1E0, 0xE4669F39040201F6, 0x7A1D7C218CF04ADE, + 0x65623C29D79CE5CE, 0x2368449096C00BB1, 0xAB9BF1879DA503BA, 0xBC23ECB1A458058E, + 0x9A58DF01BB401ECC, 0xA070E868A85F143D, 0x4FF188307DF2239E, 0x14D565B41A641183, + 0xEE13337452701602, 0x950E3DCF3F285E09, 0x59930254B9C80953, 0x3BF299408930DA6D, + 0xA955943F53691387, 0xA15EDECAA9CB8784, 0x29142127352BE9A0, 0x76F0371FFF4E7AFB, + 0x239F450274F2228, 0xBB073AF01D5E868B, 0xBFC80571C10E96C1, 0xD267088568222E23, + 0x9671A3D48E80B5B0, 0x55B5D38AE193BB81, 0x693AE2D0A18B04B8, 0x5C48B4ECADD5335F, + 0xFD743B194916A1CA, 0x2577018134BE98C4, 0xE77987E83C54A4AD, 0x28E11014DA33E1B9, + 0x270CC59E226AA213, 0x71495F756D1A5F60, 0x9BE853FB60AFEF77, 0xADC786A7F7443DBF, + 0x904456173B29A82, 0x58BC7A66C232BD5E, 0xF306558C673AC8B2, 0x41F639C6B6C9772A, + 0x216DEFE99FDA35DA, 0x11640CC71C7BE615, 0x93C43694565C5527, 0xEA038E6246777839, + 0xF9ABF3CE5A3E2469, 0x741E768D0FD312D2, 0x144B883CED652C6, 0xC20B5A5BA33F8552, + 0x1AE69633C3435A9D, 0x97A28CA4088CFDEC, 0x8824A43C1E96F420, 0x37612FA66EEEA746, + 0x6B4CB165F9CF0E5A, 0x43AA1C06A0ABFB4A, 0x7F4DC26FF162796B, 0x6CBACC8E54ED9B0F, + 0xA6B7FFEFD2BB253E, 0x2E25BC95B0A29D4F, 0x86D6A58BDEF1388C, 0xDED74AC576B6F054, + 0x8030BDBC2B45805D, 0x3C81AF70E94D9289, 0x3EFF6DDA9E3100DB, 0xB38DC39FDFCC8847, + 0x123885528D17B87E, 0xF2DA0ED240B1B642, 0x44CEFADCD54BF9A9, 0x1312200E433C7EE6, + 0x9FFCC84F3A78C748, 0xF0CD1F72248576BB, 0xEC6974053638CFE4, 0x2BA7B67C0CEC4E4C, + 0xAC2F4DF3E5CE32ED, 0xCB33D14326EA4C11, 0xA4E9044CC77E58BC, 0x5F513293D934FCEF, + 0x5DC9645506E55444, 0x50DE418F317DE40A, 0x388CB31A69DDE259, 0x2DB4A83455820A86, + 0x9010A91E84711AE9, 0x4DF7F0B7B1498371, 0xD62A2EABC0977179, 0x22FAC097AA8D5C0E, + 0xF49FCC2FF1DAF39B, 0x487FD5C66FF29281, 0xE8A30667FCDCA83F, 0x2C9B4BE3D2FCCE63, + 0xDA3FF74B93FBBBC2, 0x2FA165D2FE70BA66, 0xA103E279970E93D4, 0xBECDEC77B0E45E71, + 0xCFB41E723985E497, 0xB70AAA025EF75017, 0xD42309F03840B8E0, 0x8EFC1AD035898579, + 0x96C6920BE2B2ABC5, 0x66AF4163375A9172, 0x2174ABDCCA7127FB, 0xB33CCEA64A72FF41, + 0xF04A4933083066A5, 0x8D970ACDD7289AF5, 0x8F96E8E031C8C25E, 0xF3FEC02276875D47, + 0xEC7BF310056190DD, 0xF5ADB0AEBB0F1491, 0x9B50F8850FD58892, 0x4975488358B74DE8, + 0xA3354FF691531C61, 0x702BBE481D2C6EE, 0x89FB24057DEDED98, 0xAC3075138596E902, + 0x1D2D3580172772ED, 0xEB738FC28E6BC30D, 0x5854EF8F63044326, 0x9E5C52325ADD3BBE, + 0x90AA53CF325C4623, 0xC1D24D51349DD067, 0x2051CFEEA69EA624, 0x13220F0A862E7E4F, + 0xCE39399404E04864, 0xD9C42CA47086FCB7, 0x685AD2238A03E7CC, 0x66484B2AB2FF1DB, + 0xFE9D5D70EFBF79EC, 0x5B13B9DD9C481854, 0x15F0D475ED1509AD, 0xBEBCD060EC79851, + 0xD58C6791183AB7F8, 0xD1187C5052F3EEE4, 0xC95D1192E54E82FF, 0x86EEA14CB9AC6CA2, + 0x3485BEB153677D5D, 0xDD191D781F8C492A, 0xF60866BAA784EBF9, 0x518F643BA2D08C74, + 0x8852E956E1087C22, 0xA768CB8DC410AE8D, 0x38047726BFEC8E1A, 0xA67738B4CD3B45AA, + 0xAD16691CEC0DDE19, 0xC6D4319380462E07, 0xC5A5876D0BA61938, 0x16B9FA1FA58FD840, + 0x188AB1173CA74F18, 0xABDA2F98C99C021F, 0x3E0580AB134AE816, 0x5F3B05B773645ABB, + 0x2501A2BE5575F2F6, 0x1B2F74004E7E8BA9, 0x1CD7580371E8D953, 0x7F6ED89562764E30, + 0xB15926FF596F003D, 0x9F65293DA8C5D6B9, 0x6ECEF04DD690F84C, 0x4782275FFF33AF88, + 0xE41433083F820801, 0xFD0DFE409A1AF9B5, 0x4325A3342CDB396B, 0x8AE77E62B301B252, + 0xC36F9E9F6655615A, 0x85455A2D92D32C09, 0xF2C7DEA949477485, 0x63CFB4C133A39EBA, + 0x83B040CC6EBC5462, 0x3B9454C8FDB326B0, 0x56F56A9E87FFD78C, 0x2DC2940D99F42BC6, + 0x98F7DF096B096E2D, 0x19A6E01E3AD852BF, 0x42A99CCBDBD4B40B, 0xA59998AF45E9C559, + 0x366295E807D93186, 0x6B48181BFAA1F773, 0x1FEC57E2157A0A1D, 0x4667446AF6201AD5, + 0xE615EBCACFB0F075, 0xB8F31F4F68290778, 0x22713ED6CE22D11E, 0x3057C1A72EC3C93B, + 0xCB46ACC37C3F1F2F, 0xDBB893FD02AAF50E, 0x331FD92E600B9FCF, 0xA498F96148EA3AD6, + 0xA8D8426E8B6A83EA, 0xA089B274B7735CDC, 0x87F6B3731E524A11, 0x118808E5CBC96749, + 0x9906E4C7B19BD394, 0xAFED7F7E9B24A20C, 0x6509EADEEB3644A7, 0x6C1EF1D3E8EF0EDE, + 0xB9C97D43E9798FB4, 0xA2F2D784740C28A3, 0x7B8496476197566F, 0x7A5BE3E6B65F069D, + 0xF96330ED78BE6F10, 0xEEE60DE77A076A15, 0x2B4BEE4AA08B9BD0, 0x6A56A63EC7B8894E, + 0x2121359BA34FEF4, 0x4CBF99F8283703FC, 0x398071350CAF30C8, 0xD0A77A89F017687A, + 0xF1C1A9EB9E423569, 0x8C7976282DEE8199, 0x5D1737A5DD1F7ABD, 0x4F53433C09A9FA80, + 0xFA8B0C53DF7CA1D9, 0x3FD9DCBC886CCB77, 0xC040917CA91B4720, 0x7DD00142F9D1DCDF, + 0x8476FC1D4F387B58, 0x23F8E7C5F3316503, 0x32A2244E7E37339, 0x5C87A5D750F5A74B, + 0x82B4CC43698992E, 0xDF917BECB858F63C, 0x3270B8FC5BF86DDA, 0x10AE72BB29B5DD76, + 0x576AC94E7700362B, 0x1AD112DAC61EFB8F, 0x691BC30EC5FAA427, 0xFF246311CC327143, + 0x3142368E30E53206, 0x71380E31E02CA396, 0x958D5C960AAD76F1, 0xF8D6F430C16DA536, + 0xC8FFD13F1BE7E1D2, 0x7578AE66004DDBE1, 0x5833F01067BE646, 0xBB34B5AD3BFE586D, + 0x95F34C9A12B97F0, 0x247AB64525D60CA8, 0xDCDBC6F3017477D1, 0x4A2E14D4DECAD24D, + 0xBDB5E6D9BE0A1EEB, 0x2A7E70F7794301AB, 0xDEF42D8A270540FD, 0x1078EC0A34C22C1, + 0xE5DE511AF4C16387, 0x7EBB3A52BD9A330A, 0x77697857AA7D6435, 0x4E831603AE4C32, + 0xE7A21020AD78E312, 0x9D41A70C6AB420F2, 0x28E06C18EA1141E6, 0xD2B28CBD984F6B28, + 0x26B75F6C446E9D83, 0xBA47568C4D418D7F, 0xD80BADBFE6183D8E, 0xE206D7F5F166044, + 0xE258A43911CBCA3E, 0x723A1746B21DC0BC, 0xC7CAA854F5D7CDD3, 0x7CAC32883D261D9C, + 0x7690C26423BA942C, 0x17E55524478042B8, 0xE0BE477656A2389F, 0x4D289B5E67AB2DA0, + 0x44862B9C8FBBFD31, 0xB47CC8049D141365, 0x822C1B362B91C793, 0x4EB14655FB13DFD8, + 0x1ECBBA0714E2A97B, 0x6143459D5CDE5F14, 0x53A8FBF1D5F0AC89, 0x97EA04D81C5E5B00, + 0x622181A8D4FDB3F3, 0xE9BCD341572A1208, 0x1411258643CCE58A, 0x9144C5FEA4C6E0A4, + 0xD33D06565CF620F, 0x54A48D489F219CA1, 0xC43E5EAC6D63C821, 0xA9728B3A72770DAF, + 0xD7934E7B20DF87EF, 0xE35503B61A3E86E5, 0xCAE321FBC819D504, 0x129A50B3AC60BFA6, + 0xCD5E68EA7E9FB6C3, 0xB01C90199483B1C7, 0x3DE93CD5C295376C, 0xAED52EDF2AB9AD13, + 0x2E60F512C0A07884, 0xBC3D86A3E36210C9, 0x35269D9B163951CE, 0xC7D6E2AD0CDB5FA, + 0x59E86297D87F5733, 0x298EF221898DB0E7, 0x55000029D1A5AA7E, 0x8BC08AE1B5061B45, + 0xC2C31C2B6C92703A, 0x94CC596BAF25EF42, 0xA1D73DB22540456, 0x4B6A0F9D9C4179A, + 0xEFFDAFA2AE3D3C60, 0xF7C8075BB49496C4, 0x9CC5C7141D1CD4E3, 0x78BD1638218E5534, + 0xB2F11568F850246A, 0xEDFABCFA9502BC29, 0x796CE5F2DA23051B, 0xAAE128B0DC93537C, + 0x3A493DA0EE4B29AE, 0xB5DF6B2C416895D7, 0xFCABBD25122D7F37, 0x70810B58105DC4B1, + 0xE10FDD37F7882A90, 0x524DCAB5518A3F5C, 0x3C9E85878451255B, 0x4029828119BD34E2, + 0x74A05B6F5D3CECCB, 0xB610021542E13ECA, 0xFF979D12F59E2AC, 0x6037DA27E4F9CC50, + 0x5E92975A0DF1847D, 0xD66DE190D3E623FE, 0x5032D6B87B568048, 0x9A36B7CE8235216E, + 0x80272A7A24F64B4A, 0x93EFED8B8C6916F7, 0x37DDBFF44CCE1555, 0x4B95DB5D4B99BD25, + 0x92D3FDA169812FC0, 0xFB1A4A9A90660BB6, 0x730C196946A4B9B2, 0x81E289AA7F49DA68, + 0x64669A0F83B1A05F, 0x27B3FF7D9644F48B, 0xCC6B615C8DB675B3, 0x674F20B9BCEBBE95, + 0x6F31238275655982, 0x5AE488713E45CF05, 0xBF619F9954C21157, 0xEABAC46040A8EAE9, + 0x454C6FE9F2C0C1CD, 0x419CF6496412691C, 0xD3DC3BEF265B0F70, 0x6D0E60F5C3578A9E, + 0x5B0E608526323C55, 0x1A46C1A9FA1B59F5, 0xA9E245A17C4C8FFA, 0x65CA5159DB2955D7, + 0x5DB0A76CE35AFC2, 0x81EAC77EA9113D45, 0x528EF88AB6AC0A0D, 0xA09EA253597BE3FF, + 0x430DDFB3AC48CD56, 0xC4B3A67AF45CE46F, 0x4ECECFD8FBE2D05E, 0x3EF56F10B39935F0, + 0xB22D6829CD619C6, 0x17FD460A74DF2069, 0x6CF8CC8E8510ED40, 0xD6C824BF3A6ECAA7, + 0x61243D581A817049, 0x48BACB6BBC163A2, 0xD9A38AC27D44CC32, 0x7FDDFF5BAAF410AB, + 0xAD6D495AA804824B, 0xE1A6A74F2D8C9F94, 0xD4F7851235DEE8E3, 0xFD4B7F886540D893, + 0x247C20042AA4BFDA, 0x96EA1C517D1327C, 0xD56966B4361A6685, 0x277DA5C31221057D, + 0x94D59893A43ACFF7, 0x64F0C51CCDC02281, 0x3D33BCC4FF6189DB, 0xE005CB184CE66AF1, + 0xFF5CCD1D1DB99BEA, 0xB0B854A7FE42980F, 0x7BD46A6A718D4B9F, 0xD10FA8CC22A5FD8C, + 0xD31484952BE4BD31, 0xC7FA975FCB243847, 0x4886ED1E5846C407, 0x28CDDB791EB70B04, + 0xC2B00BE2F573417F, 0x5C9590452180F877, 0x7A6BDDFFF370EB00, 0xCE509E38D6D9D6A4, + 0xEBEB0F00647FA702, 0x1DCC06CF76606F06, 0xE4D9F28BA286FF0A, 0xD85A305DC918C262, + 0x475B1D8732225F54, 0x2D4FB51668CCB5FE, 0xA679B9D9D72BBA20, 0x53841C0D912D43A5, + 0x3B7EAA48BF12A4E8, 0x781E0E47F22F1DDF, 0xEFF20CE60AB50973, 0x20D261D19DFFB742, + 0x16A12B03062A2E39, 0x1960EB2239650495, 0x251C16FED50EB8B8, 0x9AC0C330F826016E, + 0xED152665953E7671, 0x2D63194A6369570, 0x5074F08394B1C987, 0x70BA598C90B25CE1, + 0x794A15810B9742F6, 0xD5925E9FCAF8C6C, 0x3067716CD868744E, 0x910AB077E8D7731B, + 0x6A61BBDB5AC42F61, 0x93513EFBF0851567, 0xF494724B9E83E9D5, 0xE887E1985C09648D, + 0x34B1D3C675370CFD, 0xDC35E433BC0D255D, 0xD0AAB84234131BE0, 0x8042A50B48B7EAF, + 0x9997C4EE44A3AB35, 0x829A7B49201799D0, 0x263B8307B7C54441, 0x752F95F4FD6A6CA6, + 0x927217402C08C6E5, 0x2A8AB754A795D9EE, 0xA442F7552F72943D, 0x2C31334E19781208, + 0x4FA98D7CEAEE6291, 0x55C3862F665DB309, 0xBD0610175D53B1F3, 0x46FE6CB840413F27, + 0x3FE03792DF0CFA59, 0xCFE700372EB85E8F, 0xA7BE29E7ADBCE118, 0xE544EE5CDE8431DD, + 0x8A781B1B41F1873E, 0xA5C94C78A0D2F0E7, 0x39412E2877B60728, 0xA1265EF3AFC9A62C, + 0xBCC2770C6A2506C5, 0x3AB66DD5DCE1CE12, 0xE65499D04A675B37, 0x7D8F523481BFD216, + 0xF6F64FCEC15F389, 0x74EFBE618B5B13C8, 0xACDC82B714273E1D, 0xDD40BFE003199D17, + 0x37E99257E7E061F8, 0xFA52626904775AAA, 0x8BBBF63A463D56F9, 0xF0013F1543A26E64, + 0xA8307E9F879EC898, 0xCC4C27A4150177CC, 0x1B432F2CCA1D3348, 0xDE1D1F8F9F6FA013, + 0x606602A047A7DDD6, 0xD237AB64CC1CB2C7, 0x9B938E7225FCD1D3, 0xEC4E03708E0FF476, + 0xFEB2FBDA3D03C12D, 0xAE0BCED2EE43889A, 0x22CB8923EBFB4F43, 0x69360D013CF7396D, + 0x855E3602D2D4E022, 0x73805BAD01F784C, 0x33E17A133852F546, 0xDF4874058AC7B638, + 0xBA92B29C678AA14A, 0xCE89FC76CFAADCD, 0x5F9D4E0908339E34, 0xF1AFE9291F5923B9, + 0x6E3480F60F4A265F, 0xEEBF3A2AB29B841C, 0xE21938A88F91B4AD, 0x57DFEFF845C6D3C3, + 0x2F006B0BF62CAAF2, 0x62F479EF6F75EE78, 0x11A55AD41C8916A9, 0xF229D29084FED453, + 0x42F1C27B16B000E6, 0x2B1F76749823C074, 0x4B76ECA3C2745360, 0x8C98F463B91691BD, + 0x14BCC93CF1ADE66A, 0x8885213E6D458397, 0x8E177DF0274D4711, 0xB49B73B5503F2951, + 0x10168168C3F96B6B, 0xE3D963B63CAB0AE, 0x8DFC4B5655A1DB14, 0xF789F1356E14DE5C, + 0x683E68AF4E51DAC1, 0xC9A84F9D8D4B0FD9, 0x3691E03F52A0F9D1, 0x5ED86E46E1878E80, + 0x3C711A0E99D07150, 0x5A0865B20C4E9310, 0x56FBFC1FE4F0682E, 0xEA8D5DE3105EDF9B, + 0x71ABFDB12379187A, 0x2EB99DE1BEE77B9C, 0x21ECC0EA33CF4523, 0x59A4D7521805C7A1, + 0x3896F5EB56AE7C72, 0xAA638F3DB18F75DC, 0x9F39358DABE9808E, 0xB7DEFA91C00B72AC, + 0x6B5541FD62492D92, 0x6DC6DEE8F92E4D5B, 0x353F57ABC4BEEA7E, 0x735769D6DA5690CE, + 0xA234AA642391484, 0xF6F9508028F80D9D, 0xB8E319A27AB3F215, 0x31AD9C1151341A4D, + 0x773C22A57BEF5805, 0x45C7561A07968633, 0xF913DA9E249DBE36, 0xDA652D9B78A64C68, + 0x4C27A97F3BC334EF, 0x76621220E66B17F4, 0x967743899ACD7D0B, 0xF3EE5BCAE0ED6782, + 0x409F753600C879FC, 0x6D09A39B5926DB6, 0x6F83AEB0317AC588, 0x1E6CA4A86381F21, + 0x66FF3462D19F3025, 0x72207C24DDFD3BFB, 0x4AF6B6D3E2ECE2EB, 0x9C994DBEC7EA08DE, + 0x49ACE597B09A8BC4, 0xB38C4766CF0797BA, 0x131B9373C57C2A75, 0xB1822CCE61931E58, + 0x9D7555B909BA1C0C, 0x127FAFDD937D11D2, 0x29DA3BADC66D92E4, 0xA2C1D57154C2ECBC, + 0x58C5134D82F6FE24, 0x1C3AE3515B62274F, 0xE907C82E01CB8126, 0xF8ED091913E37FCB, + 0x3249D8F9C80046C9, 0x80CF9BEDE388FB63, 0x1881539A116CF19E, 0x5103F3F76BD52457, + 0x15B7E6F5AE47F7A8, 0xDBD7C6DED47E9CCF, 0x44E55C410228BB1A, 0xB647D4255EDB4E99, + 0x5D11882BB8AAFC30, 0xF5098BBB29D3212A, 0x8FB5EA14E90296B3, 0x677B942157DD025A, + 0xFB58E7C0A390ACB5, 0x89D3674C83BD4A01, 0x9E2DA4DF4BF3B93B, 0xFCC41E328CAB4829, + 0x3F38C96BA582C52, 0xCAD1BDBD7FD85DB2, 0xBBB442C16082AE83, 0xB95FE86BA5DA9AB0, + 0xB22E04673771A93F, 0x845358C9493152D8, 0xBE2A488697B4541E, 0x95A2DC2DD38E6966, + 0xC02C11AC923C852B, 0x2388B1990DF2A87B, 0x7C8008FA1B4F37BE, 0x1F70D0C84D54E503, + 0x5490ADEC7ECE57D4, 0x2B3C27D9063A3A, 0x7EAEA3848030A2BF, 0xC602326DED2003C0, + 0x83A7287D69A94086, 0xC57A5FCB30F57A8A, 0xB56844E479EBE779, 0xA373B40F05DCBCE9, + 0xD71A786E88570EE2, 0x879CBACDBDE8F6A0, 0x976AD1BCC164A32F, 0xAB21E25E9666D78B, + 0x901063AAE5E5C33C, 0x9818B34448698D90, 0xE36487AE3E1E8ABB, 0xAFBDF931893BDCB4, + 0x6345A0DC5FBBD519, 0x8628FE269B9465CA, 0x1E5D01603F9C51EC, 0x4DE44006A15049B7, + 0xBF6C70E5F776CBB1, 0x411218F2EF552BED, 0xCB0C0708705A36A3, 0xE74D14754F986044, + 0xCD56D9430EA8280E, 0xC12591D7535F5065, 0xC83223F1720AEF96, 0xC3A0396F7363A51F + }; + #endregion + } }