Commit 567cdf73 authored by Nick Craver's avatar Nick Craver

Code cleanup and C#6 feature use

parent 470898c9
...@@ -46,7 +46,7 @@ public ResponseException(string code) ...@@ -46,7 +46,7 @@ public ResponseException(string code)
public Redis(string host, int port) public Redis(string host, int port)
{ {
if (host == null) if (host == null)
throw new ArgumentNullException("host"); throw new ArgumentNullException(nameof(host));
Host = host; Host = host;
Port = port; Port = port;
...@@ -94,9 +94,9 @@ public int Db ...@@ -94,9 +94,9 @@ public int Db
public void Set(string key, string value) public void Set(string key, string value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
Set(key, Encoding.UTF8.GetBytes(value)); Set(key, Encoding.UTF8.GetBytes(value));
} }
...@@ -104,12 +104,12 @@ public void Set(string key, string value) ...@@ -104,12 +104,12 @@ public void Set(string key, string value)
public void Set(string key, byte[] value) public void Set(string key, byte[] value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824) if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value"); throw new ArgumentException("value exceeds 1G", nameof(value));
if (!SendDataCommand(value, "SET {0} {1}\r\n", key, value.Length)) if (!SendDataCommand(value, "SET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect"); throw new Exception("Unable to connect");
...@@ -119,9 +119,9 @@ public void Set(string key, byte[] value) ...@@ -119,9 +119,9 @@ public void Set(string key, byte[] value)
public bool SetNX(string key, string value) public bool SetNX(string key, string value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
return SetNX(key, Encoding.UTF8.GetBytes(value)); return SetNX(key, Encoding.UTF8.GetBytes(value));
} }
...@@ -129,12 +129,12 @@ public bool SetNX(string key, string value) ...@@ -129,12 +129,12 @@ public bool SetNX(string key, string value)
public bool SetNX(string key, byte[] value) public bool SetNX(string key, byte[] value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824) if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value"); throw new ArgumentException("value exceeds 1G", nameof(value));
return SendDataExpectInt(value, "SETNX {0} {1}\r\n", key, value.Length) > 0 ? true : false; return SendDataExpectInt(value, "SETNX {0} {1}\r\n", key, value.Length) > 0 ? true : false;
} }
...@@ -147,7 +147,7 @@ public void Set(IDictionary<string, string> dict) ...@@ -147,7 +147,7 @@ public void Set(IDictionary<string, string> dict)
public void Set(IDictionary<string, byte[]> dict) public void Set(IDictionary<string, byte[]> dict)
{ {
if (dict == null) if (dict == null)
throw new ArgumentNullException("dict"); throw new ArgumentNullException(nameof(dict));
var nl = Encoding.UTF8.GetBytes("\r\n"); var nl = Encoding.UTF8.GetBytes("\r\n");
...@@ -173,14 +173,14 @@ public void Set(IDictionary<string, byte[]> dict) ...@@ -173,14 +173,14 @@ public void Set(IDictionary<string, byte[]> dict)
public byte[] Get(string key) public byte[] Get(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectData(null, "GET " + key + "\r\n"); return SendExpectData(null, "GET " + key + "\r\n");
} }
public string GetString(string key) public string GetString(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return Encoding.UTF8.GetString(Get(key)); return Encoding.UTF8.GetString(Get(key));
} }
...@@ -192,12 +192,12 @@ public byte[][] Sort(SortOptions options) ...@@ -192,12 +192,12 @@ public byte[][] Sort(SortOptions options)
public byte[] GetSet(string key, byte[] value) public byte[] GetSet(string key, byte[] value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
if (value.Length > 1073741824) if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value"); throw new ArgumentException("value exceeds 1G", nameof(value));
if (!SendDataCommand(value, "GETSET {0} {1}\r\n", key, value.Length)) if (!SendDataCommand(value, "GETSET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect"); throw new Exception("Unable to connect");
...@@ -208,9 +208,9 @@ public byte[] GetSet(string key, byte[] value) ...@@ -208,9 +208,9 @@ public byte[] GetSet(string key, byte[] value)
public string GetSet(string key, string value) public string GetSet(string key, string value)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
if (value == null) if (value == null)
throw new ArgumentNullException("value"); throw new ArgumentNullException(nameof(value));
return Encoding.UTF8.GetString(GetSet(key, Encoding.UTF8.GetBytes(value))); return Encoding.UTF8.GetString(GetSet(key, Encoding.UTF8.GetBytes(value)));
} }
...@@ -466,56 +466,56 @@ byte[] ReadData() ...@@ -466,56 +466,56 @@ byte[] ReadData()
public bool ContainsKey(string key) public bool ContainsKey(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXISTS " + key + "\r\n") == 1; return SendExpectInt("EXISTS " + key + "\r\n") == 1;
} }
public bool Remove(string key) public bool Remove(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("DEL " + key + "\r\n", key) == 1; return SendExpectInt("DEL " + key + "\r\n", key) == 1;
} }
public int Remove(params string[] args) public int Remove(params string[] args)
{ {
if (args == null) if (args == null)
throw new ArgumentNullException("args"); throw new ArgumentNullException(nameof(args));
return SendExpectInt("DEL " + string.Join(" ", args) + "\r\n"); return SendExpectInt("DEL " + string.Join(" ", args) + "\r\n");
} }
public int Increment(string key) public int Increment(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("INCR " + key + "\r\n"); return SendExpectInt("INCR " + key + "\r\n");
} }
public int Increment(string key, int count) public int Increment(string key, int count)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("INCRBY {0} {1}\r\n", key, count); return SendExpectInt("INCRBY {0} {1}\r\n", key, count);
} }
public int Decrement(string key) public int Decrement(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("DECR " + key + "\r\n"); return SendExpectInt("DECR " + key + "\r\n");
} }
public int Decrement(string key, int count) public int Decrement(string key, int count)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("DECRBY {0} {1}\r\n", key, count); return SendExpectInt("DECRBY {0} {1}\r\n", key, count);
} }
public KeyType TypeOf(string key) public KeyType TypeOf(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
switch (SendExpectString("TYPE {0}\r\n", key)) switch (SendExpectString("TYPE {0}\r\n", key))
{ {
case "none": case "none":
...@@ -538,30 +538,30 @@ public string RandomKey() ...@@ -538,30 +538,30 @@ public string RandomKey()
public bool Rename(string oldKeyname, string newKeyname) public bool Rename(string oldKeyname, string newKeyname)
{ {
if (oldKeyname == null) if (oldKeyname == null)
throw new ArgumentNullException("oldKeyname"); throw new ArgumentNullException(nameof(oldKeyname));
if (newKeyname == null) if (newKeyname == null)
throw new ArgumentNullException("newKeyname"); throw new ArgumentNullException(nameof(newKeyname));
return SendGetString("RENAME {0} {1}\r\n", oldKeyname, newKeyname)[0] == '+'; return SendGetString("RENAME {0} {1}\r\n", oldKeyname, newKeyname)[0] == '+';
} }
public bool Expire(string key, int seconds) public bool Expire(string key, int seconds)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXPIRE {0} {1}\r\n", key, seconds) == 1; return SendExpectInt("EXPIRE {0} {1}\r\n", key, seconds) == 1;
} }
public bool ExpireAt(string key, int time) public bool ExpireAt(string key, int time)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("EXPIREAT {0} {1}\r\n", key, time) == 1; return SendExpectInt("EXPIREAT {0} {1}\r\n", key, time) == 1;
} }
public int TimeToLive(string key) public int TimeToLive(string key)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException("key"); throw new ArgumentNullException(nameof(key));
return SendExpectInt("TTL {0}\r\n", key); return SendExpectInt("TTL {0}\r\n", key);
} }
...@@ -778,13 +778,13 @@ public byte[][] GetUnionOfSets(params string[] keys) ...@@ -778,13 +778,13 @@ public byte[][] GetUnionOfSets(params string[] keys)
void StoreSetCommands(string cmd, string destKey, params string[] keys) void StoreSetCommands(string cmd, string destKey, params string[] keys)
{ {
if (String.IsNullOrEmpty(cmd)) if (String.IsNullOrEmpty(cmd))
throw new ArgumentNullException("cmd"); throw new ArgumentNullException(nameof(cmd));
if (String.IsNullOrEmpty(destKey)) if (String.IsNullOrEmpty(destKey))
throw new ArgumentNullException("destKey"); throw new ArgumentNullException(nameof(destKey));
if (keys == null) if (keys == null)
throw new ArgumentNullException("keys"); throw new ArgumentNullException(nameof(keys));
SendExpectSuccess("{0} {1} {2}\r\n", cmd, destKey, String.Join(" ", keys)); SendExpectSuccess("{0} {1} {2}\r\n", cmd, destKey, String.Join(" ", keys));
} }
......
using System; using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework; using NUnit.Framework;
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
......
#if FEATURE_MOQ #if FEATURE_MOQ
using System;
using Moq; using Moq;
using NUnit.Framework; using NUnit.Framework;
using StackExchange.Redis.KeyspaceIsolation; using StackExchange.Redis.KeyspaceIsolation;
......
using System.Linq; using NUnit.Framework;
using NUnit.Framework;
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
{ {
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
...@@ -555,7 +554,7 @@ public void GetFromRightNodeBasedOnFlags(CommandFlags flags, bool isSlave) ...@@ -555,7 +554,7 @@ public void GetFromRightNodeBasedOnFlags(CommandFlags flags, bool isSlave)
private static string Describe(EndPoint endpoint) private static string Describe(EndPoint endpoint)
{ {
return endpoint == null ? "(unknown)" : endpoint.ToString(); return endpoint?.ToString() ?? "(unknown)";
} }
class TestProfiler : IProfiler class TestProfiler : IProfiler
......
using System; using System.Threading;
using System.Threading;
using NUnit.Framework; using NUnit.Framework;
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
......
using NUnit.Framework; using NUnit.Framework;
using System;
using System.Diagnostics; using System.Diagnostics;
using System.Threading; using System.Threading;
......
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework; using NUnit.Framework;
using StackExchange.Redis;
namespace StackExchange.Redis.Tests.Issues namespace StackExchange.Redis.Tests.Issues
{ {
...@@ -32,7 +27,7 @@ public void ConfigurationOptions_UnspecifiedDefaultDb() ...@@ -32,7 +27,7 @@ public void ConfigurationOptions_UnspecifiedDefaultDb()
var log = new StringWriter(); var log = new StringWriter();
try try
{ {
using (var conn = ConnectionMultiplexer.Connect(string.Format("{0}:{1}", PrimaryServer, PrimaryPort), log)) { using (var conn = ConnectionMultiplexer.Connect($"{PrimaryServer}:{PrimaryPort}", log)) {
var db = conn.GetDatabase(); var db = conn.GetDatabase();
Assert.AreEqual(0, db.Database); Assert.AreEqual(0, db.Database);
} }
...@@ -49,7 +44,7 @@ public void ConfigurationOptions_SpecifiedDefaultDb() ...@@ -49,7 +44,7 @@ public void ConfigurationOptions_SpecifiedDefaultDb()
var log = new StringWriter(); var log = new StringWriter();
try try
{ {
using (var conn = ConnectionMultiplexer.Connect(string.Format("{0}:{1},defaultDatabase=3", PrimaryServer, PrimaryPort), log)) { using (var conn = ConnectionMultiplexer.Connect($"{PrimaryServer}:{PrimaryPort},defaultDatabase=3", log)) {
var db = conn.GetDatabase(); var db = conn.GetDatabase();
Assert.AreEqual(3, db.Database); Assert.AreEqual(3, db.Database);
} }
......
using System; namespace StackExchange.Redis.Tests.Issues
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis.Tests.Issues
{ {
class Issue118 class Issue118
{ {
......
using System; using System.Diagnostics;
using System.Diagnostics;
using System.Linq; using System.Linq;
using NUnit.Framework; using NUnit.Framework;
......
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
#if CORE_CLR #if CORE_CLR
using System.Reflection; using System.Reflection;
#endif #endif
......
...@@ -28,7 +28,7 @@ static TaskCompletionSource<T> Create<T>(SourceOrign origin) ...@@ -28,7 +28,7 @@ static TaskCompletionSource<T> Create<T>(SourceOrign origin)
case SourceOrign.NewTCS: return new TaskCompletionSource<T>(); case SourceOrign.NewTCS: return new TaskCompletionSource<T>();
case SourceOrign.Create: return TaskSource.Create<T>(null); case SourceOrign.Create: return TaskSource.Create<T>(null);
case SourceOrign.CreateDenyExec: return TaskSource.CreateDenyExecSync<T>(null); case SourceOrign.CreateDenyExec: return TaskSource.CreateDenyExecSync<T>(null);
default: throw new ArgumentOutOfRangeException("origin"); default: throw new ArgumentOutOfRangeException(nameof(origin));
} }
} }
[Test] [Test]
...@@ -78,7 +78,7 @@ public enum AttachMode ...@@ -78,7 +78,7 @@ public enum AttachMode
} }
class AwaitState class AwaitState
{ {
public int Thread { get { return continuationThread; } } public int Thread => continuationThread;
volatile int continuationThread = -1; volatile int continuationThread = -1;
private ManualResetEventSlim evt = new ManualResetEventSlim(); private ManualResetEventSlim evt = new ManualResetEventSlim();
public void Wait() public void Wait()
...@@ -99,7 +99,7 @@ public void Attach(Task task, AttachMode attachMode) ...@@ -99,7 +99,7 @@ public void Attach(Task task, AttachMode attachMode)
DoAwait(task); DoAwait(task);
break; break;
default: default:
throw new ArgumentOutOfRangeException("attachMode"); throw new ArgumentOutOfRangeException(nameof(attachMode));
} }
} }
private void Continue(Task task) private void Continue(Task task)
......
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OK/@EntryIndexedValue">OK</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PONG/@EntryIndexedValue">PONG</s:String></wpf:ResourceDictionary>
\ No newline at end of file
using System; using System;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
#if !STRONG_NAME
using System.Runtime.CompilerServices;
#endif
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
......
...@@ -9,9 +9,22 @@ namespace StackExchange.Redis ...@@ -9,9 +9,22 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class CommandMap public sealed class CommandMap
{ {
private static readonly CommandMap private readonly byte[][] map;
@default = CreateImpl(null, null),
twemproxy = CreateImpl(null, exclusions: new HashSet<RedisCommand> internal CommandMap(byte[][] map)
{
this.map = map;
}
/// <summary>
/// The default commands specified by redis
/// </summary>
public static CommandMap Default { get; } = CreateImpl(null, null);
/// <summary>
/// The commands available to <a href="twemproxy">https://github.com/twitter/twemproxy</a>
/// </summary>
/// <remarks>https://github.com/twitter/twemproxy/blob/master/notes/redis.md</remarks>
public static CommandMap Twemproxy { get; } = CreateImpl(null, exclusions: new HashSet<RedisCommand>
{ {
// see https://github.com/twitter/twemproxy/blob/master/notes/redis.md // see https://github.com/twitter/twemproxy/blob/master/notes/redis.md
RedisCommand.KEYS, RedisCommand.MIGRATE, RedisCommand.MOVE, RedisCommand.OBJECT, RedisCommand.RANDOMKEY, RedisCommand.KEYS, RedisCommand.MIGRATE, RedisCommand.MOVE, RedisCommand.OBJECT, RedisCommand.RANDOMKEY,
...@@ -38,45 +51,28 @@ private static readonly CommandMap ...@@ -38,45 +51,28 @@ private static readonly CommandMap
RedisCommand.BGREWRITEAOF, RedisCommand.BGSAVE, RedisCommand.CLIENT, RedisCommand.CLUSTER, RedisCommand.CONFIG, RedisCommand.DBSIZE, RedisCommand.BGREWRITEAOF, RedisCommand.BGSAVE, RedisCommand.CLIENT, RedisCommand.CLUSTER, RedisCommand.CONFIG, RedisCommand.DBSIZE,
RedisCommand.DEBUG, RedisCommand.FLUSHALL, RedisCommand.FLUSHDB, RedisCommand.INFO, RedisCommand.LASTSAVE, RedisCommand.MONITOR, RedisCommand.SAVE, RedisCommand.DEBUG, RedisCommand.FLUSHALL, RedisCommand.FLUSHDB, RedisCommand.INFO, RedisCommand.LASTSAVE, RedisCommand.MONITOR, RedisCommand.SAVE,
RedisCommand.SHUTDOWN, RedisCommand.SLAVEOF, RedisCommand.SLOWLOG, RedisCommand.SYNC, RedisCommand.TIME RedisCommand.SHUTDOWN, RedisCommand.SLAVEOF, RedisCommand.SLOWLOG, RedisCommand.SYNC, RedisCommand.TIME
}), ssdb = Create(new HashSet<string> { });
/// <summary>
/// The commands available to <a href="ssdb">http://www.ideawu.com/ssdb/</a>
/// </summary>
/// <remarks>http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html</remarks>
public static CommandMap SSDB { get; } = Create(new HashSet<string> {
// see http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html // see http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html
"ping", "ping",
"get", "set", "del", "incr", "incrby", "mget", "mset", "keys", "getset", "setnx", "get", "set", "del", "incr", "incrby", "mget", "mset", "keys", "getset", "setnx",
"hget", "hset", "hdel", "hincrby", "hkeys", "hvals", "hmget", "hmset", "hlen", "hget", "hset", "hdel", "hincrby", "hkeys", "hvals", "hmget", "hmset", "hlen",
"zscore", "zadd", "zrem", "zrange", "zrangebyscore", "zincrby", "zdecrby", "zcard", "zscore", "zadd", "zrem", "zrange", "zrangebyscore", "zincrby", "zdecrby", "zcard",
"llen", "lpush", "rpush", "lpop", "rpop", "lrange", "lindex" "llen", "lpush", "rpush", "lpop", "rpop", "lrange", "lindex"
}, true), }, true);
sentinel = Create(new HashSet<string> {
// see http://redis.io/topics/sentinel
"ping", "info", "sentinel", "subscribe", "psubscribe", "unsubscribe", "punsubscribe" }, true);
private readonly byte[][] map;
internal CommandMap(byte[][] map)
{
this.map = map;
}
/// <summary>
/// The default commands specified by redis
/// </summary>
public static CommandMap Default { get { return @default; } }
/// <summary>
/// The commands available to <a href="twemproxy">https://github.com/twitter/twemproxy</a>
/// </summary>
/// <remarks>https://github.com/twitter/twemproxy/blob/master/notes/redis.md</remarks>
public static CommandMap Twemproxy { get { return twemproxy; } }
/// <summary>
/// The commands available to <a href="ssdb">http://www.ideawu.com/ssdb/</a>
/// </summary>
/// <remarks>http://www.ideawu.com/ssdb/docs/redis-to-ssdb.html</remarks>
public static CommandMap SSDB { get { return ssdb; } }
/// <summary> /// <summary>
/// The commands available to <a href="Sentinel">http://redis.io/topics/sentinel</a> /// The commands available to <a href="Sentinel">http://redis.io/topics/sentinel</a>
/// </summary> /// </summary>
/// <remarks>http://redis.io/topics/sentinel</remarks> /// <remarks>http://redis.io/topics/sentinel</remarks>
public static CommandMap Sentinel { get { return sentinel; } } public static CommandMap Sentinel { get; } = Create(new HashSet<string> {
// see http://redis.io/topics/sentinel
"ping", "info", "sentinel", "subscribe", "psubscribe", "unsubscribe", "punsubscribe" }, true);
/// <summary> /// <summary>
/// Create a new CommandMap, customizing some commands /// Create a new CommandMap, customizing some commands
...@@ -208,13 +204,13 @@ private static CommandMap CreateImpl(Dictionary<string, string> caseInsensitiveO ...@@ -208,13 +204,13 @@ private static CommandMap CreateImpl(Dictionary<string, string> caseInsensitiveO
} }
} }
if (value != name) haveDelta = true; if (value != name) haveDelta = true;
// TODO: bug?
haveDelta = true; haveDelta = true;
byte[] val = string.IsNullOrWhiteSpace(value) ? null : Encoding.UTF8.GetBytes(value); byte[] val = string.IsNullOrWhiteSpace(value) ? null : Encoding.UTF8.GetBytes(value);
map[idx] = val; map[idx] = val;
} }
} }
if (!haveDelta && @default != null) return @default; if (!haveDelta && Default != null) return Default;
return new CommandMap(map); return new CommandMap(map);
} }
......
...@@ -11,13 +11,13 @@ public sealed class CommandTrace ...@@ -11,13 +11,13 @@ public sealed class CommandTrace
internal CommandTrace(long uniqueId, long time, long duration, RedisValue[] arguments) internal CommandTrace(long uniqueId, long time, long duration, RedisValue[] arguments)
{ {
this.UniqueId = uniqueId; UniqueId = uniqueId;
this.Time = RedisBase.UnixEpoch.AddSeconds(time); Time = RedisBase.UnixEpoch.AddSeconds(time);
// duration = The amount of time needed for its execution, in microseconds. // duration = The amount of time needed for its execution, in microseconds.
// A tick is equal to 100 nanoseconds, or one ten-millionth of a second. // A tick is equal to 100 nanoseconds, or one ten-millionth of a second.
// So 1 microsecond = 10 ticks // So 1 microsecond = 10 ticks
this.Duration = TimeSpan.FromTicks(duration * 10); Duration = TimeSpan.FromTicks(duration * 10);
this.Arguments = arguments; Arguments = arguments;
} }
/// <summary> /// <summary>
......
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
......
using System; namespace StackExchange.Redis
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis
{ {
internal static class VolatileWrapper internal static class VolatileWrapper
{ {
......
...@@ -4,7 +4,7 @@ namespace StackExchange.Redis ...@@ -4,7 +4,7 @@ namespace StackExchange.Redis
{ {
internal static class CompletedTask<T> internal static class CompletedTask<T>
{ {
private readonly static Task<T> @default = FromResult(default(T), null); private static readonly Task<T> @default = FromResult(default(T), null);
public static Task<T> Default(object asyncState) public static Task<T> Default(object asyncState)
{ {
......
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
...@@ -31,8 +27,8 @@ public struct Enumerator : IEnumerator<IProfiledCommand> ...@@ -31,8 +27,8 @@ public struct Enumerator : IEnumerator<IProfiledCommand>
ProfileStorage Head; ProfileStorage Head;
ProfileStorage CurrentBacker; ProfileStorage CurrentBacker;
bool IsEmpty { get { return Head == null; } } bool IsEmpty => Head == null;
bool IsUnstartedOrFinished { get { return CurrentBacker == null; } } bool IsUnstartedOrFinished => CurrentBacker == null;
internal Enumerator(ProfileStorage head) internal Enumerator(ProfileStorage head)
{ {
...@@ -43,15 +39,9 @@ internal Enumerator(ProfileStorage head) ...@@ -43,15 +39,9 @@ internal Enumerator(ProfileStorage head)
/// <summary> /// <summary>
/// The current element. /// The current element.
/// </summary> /// </summary>
public IProfiledCommand Current public IProfiledCommand Current => CurrentBacker;
{
get { return CurrentBacker; }
}
object System.Collections.IEnumerator.Current object System.Collections.IEnumerator.Current => CurrentBacker;
{
get { return CurrentBacker; }
}
/// <summary> /// <summary>
/// Advances the enumeration, returning true if there is a new element to consume and false /// Advances the enumeration, returning true if there is a new element to consume and false
......
...@@ -18,7 +18,7 @@ public abstract class Condition ...@@ -18,7 +18,7 @@ public abstract class Condition
/// </summary> /// </summary>
public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue value) public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue value)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
if (value.IsNull) return HashNotExists(key, hashField); if (value.IsNull) return HashNotExists(key, hashField);
return new EqualsCondition(key, hashField, true, value); return new EqualsCondition(key, hashField, true, value);
} }
...@@ -28,7 +28,7 @@ public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue ...@@ -28,7 +28,7 @@ public static Condition HashEqual(RedisKey key, RedisValue hashField, RedisValue
/// </summary> /// </summary>
public static Condition HashExists(RedisKey key, RedisValue hashField) public static Condition HashExists(RedisKey key, RedisValue hashField)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
return new ExistsCondition(key, hashField, true); return new ExistsCondition(key, hashField, true);
} }
...@@ -37,7 +37,7 @@ public static Condition HashExists(RedisKey key, RedisValue hashField) ...@@ -37,7 +37,7 @@ public static Condition HashExists(RedisKey key, RedisValue hashField)
/// </summary> /// </summary>
public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisValue value) public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisValue value)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
if (value.IsNull) return HashExists(key, hashField); if (value.IsNull) return HashExists(key, hashField);
return new EqualsCondition(key, hashField, false, value); return new EqualsCondition(key, hashField, false, value);
} }
...@@ -47,7 +47,7 @@ public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisVa ...@@ -47,7 +47,7 @@ public static Condition HashNotEqual(RedisKey key, RedisValue hashField, RedisVa
/// </summary> /// </summary>
public static Condition HashNotExists(RedisKey key, RedisValue hashField) public static Condition HashNotExists(RedisKey key, RedisValue hashField)
{ {
if (hashField.IsNull) throw new ArgumentNullException("hashField"); if (hashField.IsNull) throw new ArgumentNullException(nameof(hashField));
return new ExistsCondition(key, hashField, false); return new ExistsCondition(key, hashField, false);
} }
...@@ -136,7 +136,7 @@ public static Message CreateMessage(Condition condition, int db, CommandFlags fl ...@@ -136,7 +136,7 @@ public static Message CreateMessage(Condition condition, int db, CommandFlags fl
protected override bool SetResultCore(PhysicalConnection connection, Message message, RawResult result) protected override bool SetResultCore(PhysicalConnection connection, Message message, RawResult result)
{ {
var msg = message as ConditionMessage; var msg = message as ConditionMessage;
var condition = msg == null ? null : msg.Condition; var condition = msg?.Condition;
bool final; bool final;
if (condition != null && condition.TryValidate(result, out final)) if (condition != null && condition.TryValidate(result, out final))
{ {
...@@ -307,7 +307,7 @@ internal override Condition MapKeys(Func<RedisKey,RedisKey> map) ...@@ -307,7 +307,7 @@ internal override Condition MapKeys(Func<RedisKey,RedisKey> map)
private readonly RedisKey key; private readonly RedisKey key;
public ListCondition(RedisKey key, long index, bool expectedResult, RedisValue? expectedValue) public ListCondition(RedisKey key, long index, bool expectedResult, RedisValue? expectedValue)
{ {
if (key.IsNull) throw new ArgumentException("key"); if (key.IsNull) throw new ArgumentException(nameof(key));
this.key = key; this.key = key;
this.index = index; this.index = index;
this.expectedResult = expectedResult; this.expectedResult = expectedResult;
...@@ -371,7 +371,7 @@ internal override bool TryValidate(RawResult result, out bool value) ...@@ -371,7 +371,7 @@ internal override bool TryValidate(RawResult result, out bool value)
/// </summary> /// </summary>
public sealed class ConditionResult public sealed class ConditionResult
{ {
internal readonly Condition Condition; internal readonly Condition Condition;
private ResultBox<bool> resultBox; private ResultBox<bool> resultBox;
...@@ -386,7 +386,8 @@ internal ConditionResult(Condition condition) ...@@ -386,7 +386,8 @@ internal ConditionResult(Condition condition)
/// <summary> /// <summary>
/// Indicates whether the condition was satisfied /// Indicates whether the condition was satisfied
/// </summary> /// </summary>
public bool WasSatisfied { get { return wasSatisfied; } } public bool WasSatisfied => wasSatisfied;
internal IEnumerable<Message> CreateMessages(int db) internal IEnumerable<Message> CreateMessages(int db)
{ {
return Condition.CreateMessages(db, resultBox); return Condition.CreateMessages(db, resultBox);
......
...@@ -178,7 +178,7 @@ public CommandMap CommandMap ...@@ -178,7 +178,7 @@ public CommandMap CommandMap
if (commandMap != null) return commandMap; if (commandMap != null) return commandMap;
switch (Proxy) switch (Proxy)
{ {
case Redis.Proxy.Twemproxy: case Proxy.Twemproxy:
return CommandMap.Twemproxy; return CommandMap.Twemproxy;
default: default:
return CommandMap.Default; return CommandMap.Default;
...@@ -186,7 +186,7 @@ public CommandMap CommandMap ...@@ -186,7 +186,7 @@ public CommandMap CommandMap
} }
set set
{ {
if (value == null) throw new ArgumentNullException("value"); if (value == null) throw new ArgumentNullException(nameof(value));
commandMap = value; commandMap = value;
} }
} }
...@@ -215,7 +215,7 @@ public CommandMap CommandMap ...@@ -215,7 +215,7 @@ public CommandMap CommandMap
/// <summary> /// <summary>
/// The endpoints defined for this configuration /// The endpoints defined for this configuration
/// </summary> /// </summary>
public EndPointCollection EndPoints { get { return endpoints; } } public EndPointCollection EndPoints => endpoints;
/// <summary> /// <summary>
/// Use ThreadPriority.AboveNormal for SocketManager reader and writer threads (true by default). If false, ThreadPriority.Normal will be used. /// Use ThreadPriority.AboveNormal for SocketManager reader and writer threads (true by default). If false, ThreadPriority.Normal will be used.
...@@ -397,7 +397,7 @@ public override string ToString() ...@@ -397,7 +397,7 @@ public override string ToString()
Append(sb, OptionKeys.ConfigCheckSeconds, configCheckSeconds); Append(sb, OptionKeys.ConfigCheckSeconds, configCheckSeconds);
Append(sb, OptionKeys.ResponseTimeout, responseTimeout); Append(sb, OptionKeys.ResponseTimeout, responseTimeout);
Append(sb, OptionKeys.DefaultDatabase, defaultDatabase); Append(sb, OptionKeys.DefaultDatabase, defaultDatabase);
if (commandMap != null) commandMap.AppendDeltas(sb); commandMap?.AppendDeltas(sb);
return sb.ToString(); return sb.ToString();
} }
...@@ -466,8 +466,7 @@ static void Append(StringBuilder sb, object value) ...@@ -466,8 +466,7 @@ static void Append(StringBuilder sb, object value)
static void Append(StringBuilder sb, string prefix, object value) static void Append(StringBuilder sb, string prefix, object value)
{ {
if (value == null) return; string s = value?.ToString();
string s = value.ToString();
if (!string.IsNullOrWhiteSpace(s)) if (!string.IsNullOrWhiteSpace(s))
{ {
if (sb.Length != 0) sb.Append(','); if (sb.Length != 0) sb.Append(',');
...@@ -509,7 +508,7 @@ private void DoParse(string configuration, bool ignoreUnknown) ...@@ -509,7 +508,7 @@ private void DoParse(string configuration, bool ignoreUnknown)
{ {
if (configuration == null) if (configuration == null)
{ {
throw new ArgumentNullException("configuration"); throw new ArgumentNullException(nameof(configuration));
} }
if (string.IsNullOrWhiteSpace(configuration)) if (string.IsNullOrWhiteSpace(configuration))
...@@ -629,7 +628,7 @@ private void DoParse(string configuration, bool ignoreUnknown) ...@@ -629,7 +628,7 @@ private void DoParse(string configuration, bool ignoreUnknown)
} }
if (map != null && map.Count != 0) if (map != null && map.Count != 0)
{ {
this.CommandMap = CommandMap.Create(map); CommandMap = CommandMap.Create(map);
} }
} }
......
...@@ -7,11 +7,9 @@ namespace StackExchange.Redis ...@@ -7,11 +7,9 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public class ConnectionCounters public class ConnectionCounters
{ {
private readonly ConnectionType connectionType;
internal ConnectionCounters(ConnectionType connectionType) internal ConnectionCounters(ConnectionType connectionType)
{ {
this.connectionType = connectionType; ConnectionType = connectionType;
} }
/// <summary> /// <summary>
...@@ -27,7 +25,8 @@ internal ConnectionCounters(ConnectionType connectionType) ...@@ -27,7 +25,8 @@ internal ConnectionCounters(ConnectionType connectionType)
/// <summary> /// <summary>
/// The type of this connection /// The type of this connection
/// </summary> /// </summary>
public ConnectionType ConnectionType { get { return connectionType; } } public ConnectionType ConnectionType { get; }
/// <summary> /// <summary>
/// The number of operations that failed to complete asynchronously /// The number of operations that failed to complete asynchronously
/// </summary> /// </summary>
...@@ -36,10 +35,7 @@ internal ConnectionCounters(ConnectionType connectionType) ...@@ -36,10 +35,7 @@ internal ConnectionCounters(ConnectionType connectionType)
/// <summary> /// <summary>
/// Indicates if there are any pending items or failures on this connection /// Indicates if there are any pending items or failures on this connection
/// </summary> /// </summary>
public bool IsEmpty public bool IsEmpty => PendingUnsentItems == 0 && SentItemsAwaitingResponse == 0 && ResponsesAwaitingAsyncCompletion == 0 && FailedAsynchronously == 0;
{
get { return PendingUnsentItems == 0 && SentItemsAwaitingResponse == 0 && ResponsesAwaitingAsyncCompletion == 0 && FailedAsynchronously == 0; }
}
/// <summary> /// <summary>
/// Indicates the total number of messages despatched to a non-preferred endpoint, for example sent to a master /// Indicates the total number of messages despatched to a non-preferred endpoint, for example sent to a master
...@@ -80,7 +76,7 @@ public bool IsEmpty ...@@ -80,7 +76,7 @@ public bool IsEmpty
/// <summary> /// <summary>
/// Indicates the total number of outstanding items against this connection /// Indicates the total number of outstanding items against this connection
/// </summary> /// </summary>
public int TotalOutstanding { get { return PendingUnsentItems + SentItemsAwaitingResponse + ResponsesAwaitingAsyncCompletion; } } public int TotalOutstanding => PendingUnsentItems + SentItemsAwaitingResponse + ResponsesAwaitingAsyncCompletion;
/// <summary> /// <summary>
/// Indicates the total number of writers items against this connection /// Indicates the total number of writers items against this connection
...@@ -100,17 +96,17 @@ public override string ToString() ...@@ -100,17 +96,17 @@ public override string ToString()
internal void Add(ConnectionCounters other) internal void Add(ConnectionCounters other)
{ {
if (other == null) return; if (other == null) return;
this.CompletedAsynchronously += other.CompletedAsynchronously; CompletedAsynchronously += other.CompletedAsynchronously;
this.CompletedSynchronously += other.CompletedSynchronously; CompletedSynchronously += other.CompletedSynchronously;
this.FailedAsynchronously += other.FailedAsynchronously; FailedAsynchronously += other.FailedAsynchronously;
this.OperationCount += other.OperationCount; OperationCount += other.OperationCount;
this.PendingUnsentItems += other.PendingUnsentItems; PendingUnsentItems += other.PendingUnsentItems;
this.ResponsesAwaitingAsyncCompletion += other.ResponsesAwaitingAsyncCompletion; ResponsesAwaitingAsyncCompletion += other.ResponsesAwaitingAsyncCompletion;
this.SentItemsAwaitingResponse += other.SentItemsAwaitingResponse; SentItemsAwaitingResponse += other.SentItemsAwaitingResponse;
this.SocketCount += other.SocketCount; SocketCount += other.SocketCount;
this.Subscriptions += other.Subscriptions; Subscriptions += other.Subscriptions;
this.WriterCount += other.WriterCount; WriterCount += other.WriterCount;
this.NonPreferredEndpointCount += other.NonPreferredEndpointCount; NonPreferredEndpointCount += other.NonPreferredEndpointCount;
} }
internal bool Any() internal bool Any()
...@@ -135,5 +131,4 @@ internal void Append(StringBuilder sb) ...@@ -135,5 +131,4 @@ internal void Append(StringBuilder sb)
if (NonPreferredEndpointCount != 0) sb.Append(", non-pref=").Append(NonPreferredEndpointCount); if (NonPreferredEndpointCount != 0) sb.Append(", non-pref=").Append(NonPreferredEndpointCount);
} }
} }
} }
...@@ -9,57 +9,43 @@ namespace StackExchange.Redis ...@@ -9,57 +9,43 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class ConnectionFailedEventArgs : EventArgs, ICompletable public sealed class ConnectionFailedEventArgs : EventArgs, ICompletable
{ {
private readonly ConnectionType connectionType;
private readonly EndPoint endpoint;
private readonly Exception exception;
private readonly ConnectionFailureType failureType;
private readonly EventHandler<ConnectionFailedEventArgs> handler; private readonly EventHandler<ConnectionFailedEventArgs> handler;
private readonly object sender; private readonly object sender;
internal ConnectionFailedEventArgs(EventHandler<ConnectionFailedEventArgs> handler, object sender, EndPoint endPoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception) internal ConnectionFailedEventArgs(EventHandler<ConnectionFailedEventArgs> handler, object sender, EndPoint endPoint, ConnectionType connectionType, ConnectionFailureType failureType, Exception exception)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.endpoint = endPoint; EndPoint = endPoint;
this.connectionType = connectionType; ConnectionType = connectionType;
this.exception = exception; Exception = exception;
this.failureType = failureType; FailureType = failureType;
} }
/// <summary> /// <summary>
/// Gets the connection-type of the failing connection /// Gets the connection-type of the failing connection
/// </summary> /// </summary>
public ConnectionType ConnectionType public ConnectionType ConnectionType { get; }
{
get { return connectionType; }
}
/// <summary> /// <summary>
/// Gets the failing server-endpoint /// Gets the failing server-endpoint
/// </summary> /// </summary>
public EndPoint EndPoint public EndPoint EndPoint { get; }
{
get { return endpoint; }
}
/// <summary> /// <summary>
/// Gets the exception if available (this can be null) /// Gets the exception if available (this can be null)
/// </summary> /// </summary>
public Exception Exception public Exception Exception { get; }
{
get { return exception; }
}
/// <summary> /// <summary>
/// The type of failure /// The type of failure
/// </summary> /// </summary>
public ConnectionFailureType FailureType public ConnectionFailureType FailureType { get; }
{
get { return failureType; }
}
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, connection-failed: "); sb.Append("event, connection-failed: ");
if (endpoint == null) sb.Append("n/a"); if (EndPoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(endpoint)); else sb.Append(Format.ToString(EndPoint));
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
......
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
...@@ -24,7 +18,7 @@ partial class ConnectionMultiplexer ...@@ -24,7 +18,7 @@ partial class ConnectionMultiplexer
/// </summary> /// </summary>
public void RegisterProfiler(IProfiler profiler) public void RegisterProfiler(IProfiler profiler)
{ {
if (profiler == null) throw new ArgumentNullException("profiler"); if (profiler == null) throw new ArgumentNullException(nameof(profiler));
if (this.profiler != null) throw new InvalidOperationException("IProfiler already registered for this ConnectionMultiplexer"); if (this.profiler != null) throw new InvalidOperationException("IProfiler already registered for this ConnectionMultiplexer");
this.profiler = profiler; this.profiler = profiler;
...@@ -44,8 +38,8 @@ public void RegisterProfiler(IProfiler profiler) ...@@ -44,8 +38,8 @@ public void RegisterProfiler(IProfiler profiler)
public void BeginProfiling(object forContext) public void BeginProfiling(object forContext)
{ {
if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler"); if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler");
if (forContext == null) throw new ArgumentNullException("forContext"); if (forContext == null) throw new ArgumentNullException(nameof(forContext));
if (forContext is WeakReference) throw new ArgumentException("Context object cannot be a WeakReference", "forContext"); if (forContext is WeakReference) throw new ArgumentException("Context object cannot be a WeakReference", nameof(forContext));
if (!profiledCommands.TryCreate(forContext)) if (!profiledCommands.TryCreate(forContext))
{ {
...@@ -61,7 +55,7 @@ public void BeginProfiling(object forContext) ...@@ -61,7 +55,7 @@ public void BeginProfiling(object forContext)
public ProfiledCommandEnumerable FinishProfiling(object forContext, bool allowCleanupSweep = true) public ProfiledCommandEnumerable FinishProfiling(object forContext, bool allowCleanupSweep = true)
{ {
if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler"); if (profiler == null) throw new InvalidOperationException("Cannot begin profiling if no IProfiler has been registered with RegisterProfiler");
if (forContext == null) throw new ArgumentNullException("forContext"); if (forContext == null) throw new ArgumentNullException(nameof(forContext));
ProfiledCommandEnumerable ret; ProfiledCommandEnumerable ret;
if (!profiledCommands.TryRemove(forContext, out ret)) if (!profiledCommands.TryRemove(forContext, out ret))
......
...@@ -2,20 +2,20 @@ ...@@ -2,20 +2,20 @@
{ {
partial class ConnectionMultiplexer partial class ConnectionMultiplexer
{ {
internal SocketManager SocketManager { get { return socketManager; } } internal SocketManager SocketManager => socketManager;
private SocketManager socketManager; private SocketManager socketManager;
private bool ownsSocketManager; private bool ownsSocketManager;
partial void OnCreateReaderWriter(ConfigurationOptions configuration) partial void OnCreateReaderWriter(ConfigurationOptions configuration)
{ {
this.ownsSocketManager = configuration.SocketManager == null; ownsSocketManager = configuration.SocketManager == null;
this.socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads); socketManager = configuration.SocketManager ?? new SocketManager(ClientName, configuration.HighPrioritySocketThreads);
} }
partial void OnCloseReaderWriter() partial void OnCloseReaderWriter()
{ {
if (ownsSocketManager && socketManager != null) socketManager.Dispose(); if (ownsSocketManager) socketManager?.Dispose();
socketManager = null; socketManager = null;
} }
...@@ -30,7 +30,5 @@ internal void RequestWrite(PhysicalBridge bridge, bool forced) ...@@ -30,7 +30,5 @@ internal void RequestWrite(PhysicalBridge bridge, bool forced)
} }
} }
partial void OnWriterCreated(); partial void OnWriterCreated();
} }
} }
...@@ -17,7 +17,7 @@ public static long GetAllocationCount() ...@@ -17,7 +17,7 @@ public static long GetAllocationCount()
} }
static partial void OnAllocated() static partial void OnAllocated()
{ {
Interlocked.Increment(ref ResultBox.allocations); Interlocked.Increment(ref allocations);
} }
} }
partial interface IServer partial interface IServer
...@@ -103,17 +103,17 @@ partial class ServerEndPoint ...@@ -103,17 +103,17 @@ partial class ServerEndPoint
internal void SimulateConnectionFailure() internal void SimulateConnectionFailure()
{ {
var tmp = interactive; var tmp = interactive;
if (tmp != null) tmp.SimulateConnectionFailure(); tmp?.SimulateConnectionFailure();
tmp = subscription; tmp = subscription;
if (tmp != null) tmp.SimulateConnectionFailure(); tmp?.SimulateConnectionFailure();
} }
internal string ListPending(int maxCount) internal string ListPending(int maxCount)
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var tmp = interactive; var tmp = interactive;
if (tmp != null) tmp.ListPending(sb, maxCount); tmp?.ListPending(sb, maxCount);
tmp = subscription; tmp = subscription;
if (tmp != null) tmp.ListPending(sb, maxCount); tmp?.ListPending(sb, maxCount);
return sb.ToString(); return sb.ToString();
} }
} }
...@@ -231,12 +231,11 @@ partial class PhysicalBridge ...@@ -231,12 +231,11 @@ partial class PhysicalBridge
{ {
internal void SimulateConnectionFailure() internal void SimulateConnectionFailure()
{ {
if (!multiplexer.RawConfig.AllowAdmin) if (!Multiplexer.RawConfig.AllowAdmin)
{ {
throw ExceptionFactory.AdminModeNotEnabled(multiplexer.IncludeDetailInExceptions, RedisCommand.DEBUG, null, serverEndPoint); // close enough throw ExceptionFactory.AdminModeNotEnabled(Multiplexer.IncludeDetailInExceptions, RedisCommand.DEBUG, null, ServerEndPoint); // close enough
} }
var tmp = physical; physical?.RecordConnectionFailed(ConnectionFailureType.SocketFailure);
if (tmp != null) tmp.RecordConnectionFailed(ConnectionFailureType.SocketFailure);
} }
internal void ListPending(StringBuilder sb, int maxCount) internal void ListPending(StringBuilder sb, int maxCount)
{ {
...@@ -248,20 +247,18 @@ partial class PhysicalConnection ...@@ -248,20 +247,18 @@ partial class PhysicalConnection
{ {
partial void OnDebugAbort() partial void OnDebugAbort()
{ {
if (!multiplexer.AllowConnect) if (!Multiplexer.AllowConnect)
{ {
throw new RedisConnectionException(ConnectionFailureType.InternalFailure, "debugging"); throw new RedisConnectionException(ConnectionFailureType.InternalFailure, "debugging");
} }
} }
bool ISocketCallback.IgnoreConnect bool ISocketCallback.IgnoreConnect => Multiplexer.IgnoreConnect;
{
get { return multiplexer.IgnoreConnect; }
}
private volatile static bool emulateStaleConnection; private static volatile bool emulateStaleConnection;
public static bool EmulateStaleConnection public static bool EmulateStaleConnection
{ get {
get
{ {
return emulateStaleConnection; return emulateStaleConnection;
} }
......
...@@ -16,6 +16,7 @@ public sealed class EndPointCollection : Collection<EndPoint> ...@@ -16,6 +16,7 @@ public sealed class EndPointCollection : Collection<EndPoint>
public EndPointCollection() : base() public EndPointCollection() : base()
{ {
} }
/// <summary> /// <summary>
/// Create a new EndPointCollection /// Create a new EndPointCollection
/// </summary> /// </summary>
...@@ -64,15 +65,13 @@ public void Add(IPAddress host, int port) ...@@ -64,15 +65,13 @@ public void Add(IPAddress host, int port)
Add(new IPEndPoint(host, port)); Add(new IPEndPoint(host, port));
} }
/// <summary> /// <summary>
/// See Collection&lt;T&gt;.InsertItem() /// See Collection&lt;T&gt;.InsertItem()
/// </summary> /// </summary>
protected override void InsertItem(int index, EndPoint item) protected override void InsertItem(int index, EndPoint item)
{ {
if (item == null) throw new ArgumentNullException("item"); if (item == null) throw new ArgumentNullException(nameof(item));
if (Contains(item)) throw new ArgumentException("EndPoints must be unique", "item"); if (Contains(item)) throw new ArgumentException("EndPoints must be unique", nameof(item));
base.InsertItem(index, item); base.InsertItem(index, item);
} }
/// <summary> /// <summary>
...@@ -80,7 +79,7 @@ protected override void InsertItem(int index, EndPoint item) ...@@ -80,7 +79,7 @@ protected override void InsertItem(int index, EndPoint item)
/// </summary> /// </summary>
protected override void SetItem(int index, EndPoint item) protected override void SetItem(int index, EndPoint item)
{ {
if (item == null) throw new ArgumentNullException("item"); if (item == null) throw new ArgumentNullException(nameof(item));
int existingIndex; int existingIndex;
try try
{ {
...@@ -90,7 +89,7 @@ protected override void SetItem(int index, EndPoint item) ...@@ -90,7 +89,7 @@ protected override void SetItem(int index, EndPoint item)
// mono has a nasty bug in DnsEndPoint.Equals; if they do bad things here: sorry, I can't help // mono has a nasty bug in DnsEndPoint.Equals; if they do bad things here: sorry, I can't help
existingIndex = -1; existingIndex = -1;
} }
if (existingIndex >= 0 && existingIndex != index) throw new ArgumentException("EndPoints must be unique", "item"); if (existingIndex >= 0 && existingIndex != index) throw new ArgumentException("EndPoints must be unique", nameof(item));
base.SetItem(index, item); base.SetItem(index, item);
} }
...@@ -100,18 +99,13 @@ internal void SetDefaultPorts(int defaultPort) ...@@ -100,18 +99,13 @@ internal void SetDefaultPorts(int defaultPort)
{ {
var endpoint = this[i]; var endpoint = this[i];
var dns = endpoint as DnsEndPoint; var dns = endpoint as DnsEndPoint;
if (dns != null) if (dns?.Port == 0)
{
if (dns.Port == 0)
{ {
this[i] = new DnsEndPoint(dns.Host, defaultPort, dns.AddressFamily); this[i] = new DnsEndPoint(dns.Host, defaultPort, dns.AddressFamily);
continue; continue;
} }
}
var ip = endpoint as IPEndPoint; var ip = endpoint as IPEndPoint;
if (ip != null) if (ip?.Port == 0)
{
if (ip.Port == 0)
{ {
this[i] = new IPEndPoint(ip.Address, defaultPort); this[i] = new IPEndPoint(ip.Address, defaultPort);
continue; continue;
...@@ -119,5 +113,4 @@ internal void SetDefaultPorts(int defaultPort) ...@@ -119,5 +113,4 @@ internal void SetDefaultPorts(int defaultPort)
} }
} }
} }
}
} }
...@@ -9,28 +9,25 @@ namespace StackExchange.Redis ...@@ -9,28 +9,25 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public class EndPointEventArgs : EventArgs, ICompletable public class EndPointEventArgs : EventArgs, ICompletable
{ {
private readonly EndPoint endpoint;
private readonly EventHandler<EndPointEventArgs> handler; private readonly EventHandler<EndPointEventArgs> handler;
private readonly object sender; private readonly object sender;
internal EndPointEventArgs(EventHandler<EndPointEventArgs> handler, object sender, EndPoint endpoint) internal EndPointEventArgs(EventHandler<EndPointEventArgs> handler, object sender, EndPoint endpoint)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.endpoint = endpoint; EndPoint = endpoint;
} }
/// <summary> /// <summary>
/// The endpoint involved in this event (this can be null) /// The endpoint involved in this event (this can be null)
/// </summary> /// </summary>
public EndPoint EndPoint public EndPoint EndPoint { get; }
{
get { return endpoint; }
}
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, endpoint: "); sb.Append("event, endpoint: ");
if (endpoint == null) sb.Append("n/a"); if (EndPoint == null) sb.Append("n/a");
else sb.Append(Format.ToString(endpoint)); else sb.Append(Format.ToString(EndPoint));
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
......
...@@ -90,7 +90,7 @@ internal static string ToString(EndPoint endpoint) ...@@ -90,7 +90,7 @@ internal static string ToString(EndPoint endpoint)
if (ip.Port == 0) return ip.Address.ToString(); if (ip.Port == 0) return ip.Address.ToString();
return ip.Address.ToString() + ":" + Format.ToString(ip.Port); return ip.Address.ToString() + ":" + Format.ToString(ip.Port);
} }
return endpoint == null ? "" : endpoint.ToString(); return endpoint?.ToString() ?? "";
} }
internal static string ToStringHostOnly(EndPoint endpoint) internal static string ToStringHostOnly(EndPoint endpoint)
{ {
...@@ -118,7 +118,7 @@ internal static bool TryGetHostPort(EndPoint endpoint, out string host, out int ...@@ -118,7 +118,7 @@ internal static bool TryGetHostPort(EndPoint endpoint, out string host, out int
port = ip.Port; port = ip.Port;
return true; return true;
} }
else if (endpoint is DnsEndPoint) if (endpoint is DnsEndPoint)
{ {
DnsEndPoint dns = (DnsEndPoint)endpoint; DnsEndPoint dns = (DnsEndPoint)endpoint;
host = dns.Host; host = dns.Host;
......
...@@ -22,11 +22,12 @@ public HashEntry(RedisValue name, RedisValue value) ...@@ -22,11 +22,12 @@ public HashEntry(RedisValue name, RedisValue value)
/// <summary> /// <summary>
/// The name of the hash field /// The name of the hash field
/// </summary> /// </summary>
public RedisValue Name { get { return name; } } public RedisValue Name => name;
/// <summary> /// <summary>
/// The value of the hash field /// The value of the hash field
/// </summary> /// </summary>
public RedisValue Value{ get { return value; } } public RedisValue Value => value;
/// <summary> /// <summary>
/// The name of the hash field /// The name of the hash field
...@@ -79,7 +80,7 @@ public override bool Equals(object obj) ...@@ -79,7 +80,7 @@ public override bool Equals(object obj)
/// </summary> /// </summary>
public bool Equals(HashEntry value) public bool Equals(HashEntry value)
{ {
return this.name == value.name && this.value == value.value; return name == value.name && this.value == value.value;
} }
/// <summary> /// <summary>
/// Compares two values for equality /// Compares two values for equality
......
...@@ -9,31 +9,31 @@ namespace StackExchange.Redis ...@@ -9,31 +9,31 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class HashSlotMovedEventArgs : EventArgs, ICompletable public sealed class HashSlotMovedEventArgs : EventArgs, ICompletable
{ {
private readonly int hashSlot;
private readonly EndPoint old, @new;
private readonly object sender; private readonly object sender;
private readonly EventHandler<HashSlotMovedEventArgs> handler; private readonly EventHandler<HashSlotMovedEventArgs> handler;
/// <summary> /// <summary>
/// The hash-slot that was relocated /// The hash-slot that was relocated
/// </summary> /// </summary>
public int HashSlot { get { return hashSlot; } } public int HashSlot { get; }
/// <summary> /// <summary>
/// The old endpoint for this hash-slot (if known) /// The old endpoint for this hash-slot (if known)
/// </summary> /// </summary>
public EndPoint OldEndPoint { get { return old; } } public EndPoint OldEndPoint { get; }
/// <summary> /// <summary>
/// The new endpoint for this hash-slot (if known) /// The new endpoint for this hash-slot (if known)
/// </summary> /// </summary>
public EndPoint NewEndPoint { get { return @new; } } public EndPoint NewEndPoint { get; }
internal HashSlotMovedEventArgs(EventHandler<HashSlotMovedEventArgs> handler, object sender, internal HashSlotMovedEventArgs(EventHandler<HashSlotMovedEventArgs> handler, object sender,
int hashSlot, EndPoint old, EndPoint @new) int hashSlot, EndPoint old, EndPoint @new)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.hashSlot = hashSlot; HashSlot = hashSlot;
this.old = old; OldEndPoint = old;
this.@new = @new; NewEndPoint = @new;
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
...@@ -43,7 +43,7 @@ bool ICompletable.TryComplete(bool isAsync) ...@@ -43,7 +43,7 @@ bool ICompletable.TryComplete(bool isAsync)
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, slot-moved: ").Append(hashSlot); sb.Append("event, slot-moved: ").Append(HashSlot);
} }
} }
} }
...@@ -909,21 +909,20 @@ public interface IDatabaseAsync : IRedisAsync ...@@ -909,21 +909,20 @@ public interface IDatabaseAsync : IRedisAsync
/// </summary> /// </summary>
public struct RedisValueWithExpiry public struct RedisValueWithExpiry
{ {
private readonly TimeSpan? expiry;
private readonly RedisValue value;
internal RedisValueWithExpiry(RedisValue value, TimeSpan? expiry) internal RedisValueWithExpiry(RedisValue value, TimeSpan? expiry)
{ {
this.value = value; Value = value;
this.expiry = expiry; Expiry = expiry;
} }
/// <summary> /// <summary>
/// The expiry of this record /// The expiry of this record
/// </summary> /// </summary>
public TimeSpan? Expiry { get { return expiry; } } public TimeSpan? Expiry { get; }
/// <summary> /// <summary>
/// The value of this record /// The value of this record
/// </summary> /// </summary>
public RedisValue Value { get { return value; } } public RedisValue Value { get; }
} }
} }
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
internal interface IMultiMessage internal interface IMultiMessage
{ IEnumerable<Message> GetMessages(PhysicalConnection connection); {
IEnumerable<Message> GetMessages(PhysicalConnection connection);
} }
} }
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Net; using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
......
...@@ -43,7 +43,7 @@ internal class IgnoreNamePrefixAttribute : Attribute ...@@ -43,7 +43,7 @@ internal class IgnoreNamePrefixAttribute : Attribute
{ {
public IgnoreNamePrefixAttribute(bool ignoreEntireMethod = false) public IgnoreNamePrefixAttribute(bool ignoreEntireMethod = false)
{ {
this.IgnoreEntireMethod = ignoreEntireMethod; IgnoreEntireMethod = ignoreEntireMethod;
} }
public bool IgnoreEntireMethod { get; private set; } public bool IgnoreEntireMethod { get; private set; }
......
...@@ -9,55 +9,41 @@ namespace StackExchange.Redis ...@@ -9,55 +9,41 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public class InternalErrorEventArgs : EventArgs, ICompletable public class InternalErrorEventArgs : EventArgs, ICompletable
{ {
private readonly ConnectionType connectionType;
private readonly EndPoint endpoint;
private readonly Exception exception;
private readonly EventHandler<InternalErrorEventArgs> handler; private readonly EventHandler<InternalErrorEventArgs> handler;
private readonly string origin;
private readonly object sender; private readonly object sender;
internal InternalErrorEventArgs(EventHandler<InternalErrorEventArgs> handler, object sender, EndPoint endpoint, ConnectionType connectionType, Exception exception, string origin) internal InternalErrorEventArgs(EventHandler<InternalErrorEventArgs> handler, object sender, EndPoint endpoint, ConnectionType connectionType, Exception exception, string origin)
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.endpoint = endpoint; EndPoint = endpoint;
this.connectionType = connectionType; ConnectionType = connectionType;
this.exception = exception; Exception = exception;
this.origin = origin; Origin = origin;
} }
/// <summary> /// <summary>
/// Gets the connection-type of the failing connection /// Gets the connection-type of the failing connection
/// </summary> /// </summary>
public ConnectionType ConnectionType public ConnectionType ConnectionType { get; }
{
get { return connectionType; }
}
/// <summary> /// <summary>
/// Gets the failing server-endpoint (this can be null) /// Gets the failing server-endpoint (this can be null)
/// </summary> /// </summary>
public EndPoint EndPoint public EndPoint EndPoint { get; }
{
get { return endpoint; }
}
/// <summary> /// <summary>
/// Gets the exception if available (this can be null) /// Gets the exception if available (this can be null)
/// </summary> /// </summary>
public Exception Exception public Exception Exception { get; }
{
get { return exception; }
}
/// <summary> /// <summary>
/// The underlying origin of the error /// The underlying origin of the error
/// </summary> /// </summary>
public string Origin public string Origin { get; }
{
get { return origin; }
}
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, internal-error: ").Append(origin); sb.Append("event, internal-error: ").Append(Origin);
if (endpoint != null) sb.Append(", ").Append(Format.ToString(endpoint)); if (EndPoint != null) sb.Append(", ").Append(Format.ToString(EndPoint));
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
......
using System; using System.Text.RegularExpressions;
using System.Text.RegularExpressions; #if CORE_CLR
using System;
#endif
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
......
...@@ -2,14 +2,13 @@ ...@@ -2,14 +2,13 @@
{ {
internal sealed class BatchWrapper : WrapperBase<IBatch>, IBatch internal sealed class BatchWrapper : WrapperBase<IBatch>, IBatch
{ {
public BatchWrapper(IBatch inner, byte[] prefix) public BatchWrapper(IBatch inner, byte[] prefix) : base(inner, prefix)
: base(inner, prefix)
{ {
} }
public void Execute() public void Execute()
{ {
this.Inner.Execute(); Inner.Execute();
} }
} }
} }
...@@ -41,12 +41,12 @@ public static IDatabase WithKeyPrefix(this IDatabase database, RedisKey keyPrefi ...@@ -41,12 +41,12 @@ public static IDatabase WithKeyPrefix(this IDatabase database, RedisKey keyPrefi
{ {
if (database == null) if (database == null)
{ {
throw new ArgumentNullException("database"); throw new ArgumentNullException(nameof(database));
} }
if (keyPrefix.IsNull) if (keyPrefix.IsNull)
{ {
throw new ArgumentNullException("keyPrefix"); throw new ArgumentNullException(nameof(keyPrefix));
} }
if (keyPrefix.IsEmpty) if (keyPrefix.IsEmpty)
......
...@@ -4,29 +4,28 @@ namespace StackExchange.Redis.KeyspaceIsolation ...@@ -4,29 +4,28 @@ namespace StackExchange.Redis.KeyspaceIsolation
{ {
internal sealed class TransactionWrapper : WrapperBase<ITransaction>, ITransaction internal sealed class TransactionWrapper : WrapperBase<ITransaction>, ITransaction
{ {
public TransactionWrapper(ITransaction inner, byte[] prefix) public TransactionWrapper(ITransaction inner, byte[] prefix) : base(inner, prefix)
: base(inner, prefix)
{ {
} }
public ConditionResult AddCondition(Condition condition) public ConditionResult AddCondition(Condition condition)
{ {
return this.Inner.AddCondition(condition == null ? null : condition.MapKeys(GetMapFunction())); return Inner.AddCondition(condition?.MapKeys(GetMapFunction()));
} }
public bool Execute(CommandFlags flags = CommandFlags.None) public bool Execute(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.Execute(flags); return Inner.Execute(flags);
} }
public Task<bool> ExecuteAsync(CommandFlags flags = CommandFlags.None) public Task<bool> ExecuteAsync(CommandFlags flags = CommandFlags.None)
{ {
return this.Inner.ExecuteAsync(flags); return Inner.ExecuteAsync(flags);
} }
public void Execute() public void Execute()
{ {
this.Inner.Execute(); Inner.Execute();
} }
} }
} }
...@@ -37,7 +37,7 @@ public sealed class LuaScript ...@@ -37,7 +37,7 @@ public sealed class LuaScript
// Arguments are in the order they have to passed to the script in // Arguments are in the order they have to passed to the script in
internal string[] Arguments { get; private set; } internal string[] Arguments { get; private set; }
bool HasArguments { get { return Arguments != null && Arguments.Length > 0; } } bool HasArguments => Arguments != null && Arguments.Length > 0;
Hashtable ParameterMappers; Hashtable ParameterMappers;
...@@ -106,7 +106,7 @@ internal void ExtractParameters(object ps, RedisKey? keyPrefix, out RedisKey[] k ...@@ -106,7 +106,7 @@ internal void ExtractParameters(object ps, RedisKey? keyPrefix, out RedisKey[] k
{ {
if (HasArguments) if (HasArguments)
{ {
if (ps == null) throw new ArgumentNullException("ps", "Script requires parameters"); if (ps == null) throw new ArgumentNullException(nameof(ps), "Script requires parameters");
var psType = ps.GetType(); var psType = ps.GetType();
var mapper = (Func<object, RedisKey?, ScriptParameterMapper.ScriptParameters>)ParameterMappers[psType]; var mapper = (Func<object, RedisKey?, ScriptParameterMapper.ScriptParameters>)ParameterMappers[psType];
...@@ -179,7 +179,7 @@ public LoadedLuaScript Load(IServer server, CommandFlags flags = CommandFlags.No ...@@ -179,7 +179,7 @@ public LoadedLuaScript Load(IServer server, CommandFlags flags = CommandFlags.No
{ {
if (flags.HasFlag(CommandFlags.FireAndForget)) if (flags.HasFlag(CommandFlags.FireAndForget))
{ {
throw new ArgumentOutOfRangeException("flags", "Loading a script cannot be FireAndForget"); throw new ArgumentOutOfRangeException(nameof(flags), "Loading a script cannot be FireAndForget");
} }
var hash = server.ScriptLoad(ExecutableScript, flags); var hash = server.ScriptLoad(ExecutableScript, flags);
...@@ -197,7 +197,7 @@ public async Task<LoadedLuaScript> LoadAsync(IServer server, CommandFlags flags ...@@ -197,7 +197,7 @@ public async Task<LoadedLuaScript> LoadAsync(IServer server, CommandFlags flags
{ {
if (flags.HasFlag(CommandFlags.FireAndForget)) if (flags.HasFlag(CommandFlags.FireAndForget))
{ {
throw new ArgumentOutOfRangeException("flags", "Loading a script cannot be FireAndForget"); throw new ArgumentOutOfRangeException(nameof(flags), "Loading a script cannot be FireAndForget");
} }
var hash = await server.ScriptLoadAsync(ExecutableScript, flags); var hash = await server.ScriptLoadAsync(ExecutableScript, flags);
...@@ -228,12 +228,12 @@ public sealed class LoadedLuaScript ...@@ -228,12 +228,12 @@ public sealed class LoadedLuaScript
/// <summary> /// <summary>
/// The original script that was used to create this LoadedLuaScript. /// The original script that was used to create this LoadedLuaScript.
/// </summary> /// </summary>
public string OriginalScript { get { return Original.OriginalScript; } } public string OriginalScript => Original.OriginalScript;
/// <summary> /// <summary>
/// The script that will actually be sent to Redis for execution. /// The script that will actually be sent to Redis for execution.
/// </summary> /// </summary>
public string ExecutableScript { get { return Original.ExecutableScript; } } public string ExecutableScript => Original.ExecutableScript;
/// <summary> /// <summary>
/// The SHA1 hash of ExecutableScript. /// The SHA1 hash of ExecutableScript.
......
...@@ -9,7 +9,7 @@ sealed partial class MessageQueue ...@@ -9,7 +9,7 @@ sealed partial class MessageQueue
regular = new Queue<Message>(), regular = new Queue<Message>(),
high = new Queue<Message>(); high = new Queue<Message>();
public object SyncLock { get { return regular; } } public object SyncLock => regular;
public Message Dequeue() public Message Dequeue()
{ {
......
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
...@@ -140,7 +137,7 @@ public int GetHashCode(ProfileContextCell obj) ...@@ -140,7 +137,7 @@ public int GetHashCode(ProfileContextCell obj)
private long lastCleanupSweep; private long lastCleanupSweep;
private ConcurrentDictionary<ProfileContextCell, ConcurrentProfileStorageCollection> profiledCommands; private ConcurrentDictionary<ProfileContextCell, ConcurrentProfileStorageCollection> profiledCommands;
public int ContextCount { get { return profiledCommands.Count; } } public int ContextCount => profiledCommands.Count;
public ProfileContextTracker() public ProfileContextTracker()
{ {
......
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq;
using System.Net; using System.Net;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
namespace StackExchange.Redis namespace StackExchange.Redis
{ {
class ProfileStorage : IProfiledCommand class ProfileStorage : IProfiledCommand
{ {
#region IProfiledCommand Impl #region IProfiledCommand Impl
public EndPoint EndPoint public EndPoint EndPoint => Server.EndPoint;
{
get { return Server.EndPoint; }
}
public int Db public int Db => Message.Db;
{
get { return Message.Db; }
}
public string Command public string Command => Message.Command.ToString();
{
get { return Message.Command.ToString(); }
}
public CommandFlags Flags public CommandFlags Flags => Message.Flags;
{
get { return Message.Flags; }
}
public DateTime CommandCreated public DateTime CommandCreated => MessageCreatedDateTime;
{
get { return MessageCreatedDateTime; }
}
public TimeSpan CreationToEnqueued public TimeSpan CreationToEnqueued => TimeSpan.FromTicks(EnqueuedTimeStamp - MessageCreatedTimeStamp);
{
get { return TimeSpan.FromTicks(EnqueuedTimeStamp - MessageCreatedTimeStamp); }
}
public TimeSpan EnqueuedToSending public TimeSpan EnqueuedToSending => TimeSpan.FromTicks(RequestSentTimeStamp - EnqueuedTimeStamp);
{
get { return TimeSpan.FromTicks(RequestSentTimeStamp - EnqueuedTimeStamp); }
}
public TimeSpan SentToResponse public TimeSpan SentToResponse => TimeSpan.FromTicks(ResponseReceivedTimeStamp - RequestSentTimeStamp);
{
get { return TimeSpan.FromTicks(ResponseReceivedTimeStamp - RequestSentTimeStamp); }
}
public TimeSpan ResponseToCompletion public TimeSpan ResponseToCompletion => TimeSpan.FromTicks(CompletedTimeStamp - ResponseReceivedTimeStamp);
{
get { return TimeSpan.FromTicks(CompletedTimeStamp - ResponseReceivedTimeStamp); }
}
public TimeSpan ElapsedTime public TimeSpan ElapsedTime => TimeSpan.FromTicks(CompletedTimeStamp - MessageCreatedTimeStamp);
{
get { return TimeSpan.FromTicks(CompletedTimeStamp - MessageCreatedTimeStamp); }
}
public IProfiledCommand RetransmissionOf public IProfiledCommand RetransmissionOf => OriginalProfiling;
{
get { return OriginalProfiling; } public RetransmissionReasonType? RetransmissionReason { get; }
}
public RetransmissionReasonType? RetransmissionReason
{
get { return Reason; }
}
#endregion #endregion
public ProfileStorage NextElement { get; set; } public ProfileStorage NextElement { get; set; }
...@@ -79,7 +39,6 @@ public IProfiledCommand RetransmissionOf ...@@ -79,7 +39,6 @@ public IProfiledCommand RetransmissionOf
private Message Message; private Message Message;
private ServerEndPoint Server; private ServerEndPoint Server;
private ProfileStorage OriginalProfiling; private ProfileStorage OriginalProfiling;
private RetransmissionReasonType? Reason;
private DateTime MessageCreatedDateTime; private DateTime MessageCreatedDateTime;
private long MessageCreatedTimeStamp; private long MessageCreatedTimeStamp;
...@@ -95,7 +54,7 @@ private ProfileStorage(ConcurrentProfileStorageCollection pushTo, ServerEndPoint ...@@ -95,7 +54,7 @@ private ProfileStorage(ConcurrentProfileStorageCollection pushTo, ServerEndPoint
PushToWhenFinished = pushTo; PushToWhenFinished = pushTo;
OriginalProfiling = resentFor; OriginalProfiling = resentFor;
Server = server; Server = server;
Reason = reason; RetransmissionReason = reason;
} }
public static ProfileStorage NewWithContext(ConcurrentProfileStorageCollection pushTo, ServerEndPoint server) public static ProfileStorage NewWithContext(ConcurrentProfileStorageCollection pushTo, ServerEndPoint server)
...@@ -159,30 +118,17 @@ public void SetCompleted() ...@@ -159,30 +118,17 @@ public void SetCompleted()
public override string ToString() public override string ToString()
{ {
return return
string.Format( $@"EndPoint = {EndPoint}
@"EndPoint = {0} Db = {Db}
Db = {1} Command = {Command}
Command = {2} CommandCreated = {CommandCreated:u}
CommandCreated = {3:u} CreationToEnqueued = {CreationToEnqueued}
CreationToEnqueued = {4} EnqueuedToSending = {EnqueuedToSending}
EnqueuedToSending = {5} SentToResponse = {SentToResponse}
SentToResponse = {6} ResponseToCompletion = {ResponseToCompletion}
ResponseToCompletion = {7} ElapsedTime = {ElapsedTime}
ElapsedTime = {8} Flags = {Flags}
Flags = {9} RetransmissionOf = ({RetransmissionOf})";
RetransmissionOf = ({10})",
EndPoint,
Db,
Command,
CommandCreated,
CreationToEnqueued,
EnqueuedToSending,
SentToResponse,
ResponseToCompletion,
ElapsedTime,
Flags,
RetransmissionOf
);
} }
} }
} }
...@@ -11,7 +11,6 @@ internal struct RawResult ...@@ -11,7 +11,6 @@ internal struct RawResult
public static readonly RawResult Nil = new RawResult(); public static readonly RawResult Nil = new RawResult();
private static readonly byte[] emptyBlob = new byte[0]; private static readonly byte[] emptyBlob = new byte[0];
private readonly int offset, count; private readonly int offset, count;
private readonly ResultType resultType;
private Array arr; private Array arr;
public RawResult(ResultType resultType, byte[] buffer, int offset, int count) public RawResult(ResultType resultType, byte[] buffer, int offset, int count)
{ {
...@@ -23,29 +22,30 @@ public RawResult(ResultType resultType, byte[] buffer, int offset, int count) ...@@ -23,29 +22,30 @@ public RawResult(ResultType resultType, byte[] buffer, int offset, int count)
case ResultType.BulkString: case ResultType.BulkString:
break; break;
default: default:
throw new ArgumentOutOfRangeException("resultType"); throw new ArgumentOutOfRangeException(nameof(resultType));
} }
this.resultType = resultType; Type = resultType;
this.arr = buffer; arr = buffer;
this.offset = offset; this.offset = offset;
this.count = count; this.count = count;
} }
public RawResult(RawResult[] arr) public RawResult(RawResult[] arr)
{ {
if (arr == null) throw new ArgumentNullException("arr"); if (arr == null) throw new ArgumentNullException(nameof(arr));
this.resultType = ResultType.MultiBulk; Type = ResultType.MultiBulk;
this.offset = 0; offset = 0;
this.count = arr.Length; count = arr.Length;
this.arr = arr; this.arr = arr;
} }
public bool HasValue { get { return resultType != ResultType.None; } } public bool HasValue => Type != ResultType.None;
public bool IsError { get { return resultType == ResultType.Error; } } public bool IsError => Type == ResultType.Error;
public ResultType Type { get { return resultType; } } public ResultType Type { get; }
internal bool IsNull { get { return arr == null; } }
internal bool IsNull => arr == null;
public override string ToString() public override string ToString()
{ {
...@@ -53,23 +53,23 @@ public override string ToString() ...@@ -53,23 +53,23 @@ public override string ToString()
{ {
return "(null)"; return "(null)";
} }
switch (resultType) switch (Type)
{ {
case ResultType.SimpleString: case ResultType.SimpleString:
case ResultType.Integer: case ResultType.Integer:
case ResultType.Error: case ResultType.Error:
return string.Format("{0}: {1}", resultType, GetString()); return $"{Type}: {GetString()}";
case ResultType.BulkString: case ResultType.BulkString:
return string.Format("{0}: {1} bytes", resultType, count); return $"{Type}: {count} bytes";
case ResultType.MultiBulk: case ResultType.MultiBulk:
return string.Format("{0}: {1} items", resultType, count); return $"{Type}: {count} items";
default: default:
return "(unknown)"; return "(unknown)";
} }
} }
internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternMode mode) internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternMode mode)
{ {
switch (resultType) switch (Type)
{ {
case ResultType.SimpleString: case ResultType.SimpleString:
case ResultType.BulkString: case ResultType.BulkString:
...@@ -87,24 +87,24 @@ internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternM ...@@ -87,24 +87,24 @@ internal RedisChannel AsRedisChannel(byte[] channelPrefix, RedisChannel.PatternM
} }
return default(RedisChannel); return default(RedisChannel);
default: default:
throw new InvalidCastException("Cannot convert to RedisChannel: " + resultType); throw new InvalidCastException("Cannot convert to RedisChannel: " + Type);
} }
} }
internal RedisKey AsRedisKey() internal RedisKey AsRedisKey()
{ {
switch (resultType) switch (Type)
{ {
case ResultType.SimpleString: case ResultType.SimpleString:
case ResultType.BulkString: case ResultType.BulkString:
return (RedisKey)GetBlob(); return (RedisKey)GetBlob();
default: default:
throw new InvalidCastException("Cannot convert to RedisKey: " + resultType); throw new InvalidCastException("Cannot convert to RedisKey: " + Type);
} }
} }
internal RedisValue AsRedisValue() internal RedisValue AsRedisValue()
{ {
switch (resultType) switch (Type)
{ {
case ResultType.Integer: case ResultType.Integer:
long i64; long i64;
...@@ -114,12 +114,12 @@ internal RedisValue AsRedisValue() ...@@ -114,12 +114,12 @@ internal RedisValue AsRedisValue()
case ResultType.BulkString: case ResultType.BulkString:
return (RedisValue)GetBlob(); return (RedisValue)GetBlob();
} }
throw new InvalidCastException("Cannot convert to RedisValue: " + resultType); throw new InvalidCastException("Cannot convert to RedisValue: " + Type);
} }
internal unsafe bool IsEqual(byte[] expected) internal unsafe bool IsEqual(byte[] expected)
{ {
if (expected == null) throw new ArgumentNullException("expected"); if (expected == null) throw new ArgumentNullException(nameof(expected));
if (expected.Length != count) return false; if (expected.Length != count) return false;
var actual = arr as byte[]; var actual = arr as byte[];
if (actual == null) return false; if (actual == null) return false;
...@@ -146,7 +146,7 @@ internal unsafe bool IsEqual(byte[] expected) ...@@ -146,7 +146,7 @@ internal unsafe bool IsEqual(byte[] expected)
internal bool AssertStarts(byte[] expected) internal bool AssertStarts(byte[] expected)
{ {
if (expected == null) throw new ArgumentNullException("expected"); if (expected == null) throw new ArgumentNullException(nameof(expected));
if (expected.Length > count) return false; if (expected.Length > count) return false;
var actual = arr as byte[]; var actual = arr as byte[];
if (actual == null) return false; if (actual == null) return false;
...@@ -171,7 +171,7 @@ internal byte[] GetBlob() ...@@ -171,7 +171,7 @@ internal byte[] GetBlob()
internal bool GetBoolean() internal bool GetBoolean()
{ {
if (this.count != 1) throw new InvalidCastException(); if (count != 1) throw new InvalidCastException();
byte[] actual = arr as byte[]; byte[] actual = arr as byte[];
if (actual == null) throw new InvalidCastException(); if (actual == null) throw new InvalidCastException();
switch (actual[offset]) switch (actual[offset])
......
...@@ -16,7 +16,8 @@ internal RedisBase(ConnectionMultiplexer multiplexer, object asyncState) ...@@ -16,7 +16,8 @@ internal RedisBase(ConnectionMultiplexer multiplexer, object asyncState)
this.asyncState = asyncState; this.asyncState = asyncState;
} }
ConnectionMultiplexer IRedisAsync.Multiplexer { get { return multiplexer; } } ConnectionMultiplexer IRedisAsync.Multiplexer => multiplexer;
public virtual TimeSpan Ping(CommandFlags flags = CommandFlags.None) public virtual TimeSpan Ping(CommandFlags flags = CommandFlags.None)
{ {
var msg = GetTimerMessage(flags); var msg = GetTimerMessage(flags);
...@@ -163,14 +164,14 @@ internal abstract class CursorEnumerable<T> : IEnumerable<T>, IScanningCursor ...@@ -163,14 +164,14 @@ internal abstract class CursorEnumerable<T> : IEnumerable<T>, IScanningCursor
protected CursorEnumerable(RedisBase redis, ServerEndPoint server, int db, int pageSize, long cursor, int pageOffset, CommandFlags flags) protected CursorEnumerable(RedisBase redis, ServerEndPoint server, int db, int pageSize, long cursor, int pageOffset, CommandFlags flags)
{ {
if (pageOffset < 0) throw new ArgumentOutOfRangeException("pageOffset"); if (pageOffset < 0) throw new ArgumentOutOfRangeException(nameof(pageOffset));
this.redis = redis; this.redis = redis;
this.server = server; this.server = server;
this.db = db; this.db = db;
this.pageSize = pageSize; this.pageSize = pageSize;
this.flags = flags; this.flags = flags;
this.initialCursor = cursor; initialCursor = cursor;
this.initialOffset = pageOffset; initialOffset = pageOffset;
} }
public IEnumerator<T> GetEnumerator() public IEnumerator<T> GetEnumerator()
...@@ -187,8 +188,8 @@ internal struct ScanResult ...@@ -187,8 +188,8 @@ internal struct ScanResult
public readonly T[] Values; public readonly T[] Values;
public ScanResult(long cursor, T[] values) public ScanResult(long cursor, T[] values)
{ {
this.Cursor = cursor; Cursor = cursor;
this.Values = values; Values = values;
} }
} }
...@@ -199,12 +200,12 @@ public ScanResult(long cursor, T[] values) ...@@ -199,12 +200,12 @@ public ScanResult(long cursor, T[] values)
protected ScanResult GetNextPageSync(IScanningCursor obj, long cursor) protected ScanResult GetNextPageSync(IScanningCursor obj, long cursor)
{ {
this.activeCursor = obj; activeCursor = obj;
return redis.ExecuteSync(CreateMessage(cursor), Processor, server); return redis.ExecuteSync(CreateMessage(cursor), Processor, server);
} }
protected Task<ScanResult> GetNextPageAsync(IScanningCursor obj, long cursor) protected Task<ScanResult> GetNextPageAsync(IScanningCursor obj, long cursor)
{ {
this.activeCursor = obj; activeCursor = obj;
return redis.ExecuteAsync(CreateMessage(cursor), Processor, server); return redis.ExecuteAsync(CreateMessage(cursor), Processor, server);
} }
protected ScanResult Wait(Task<ScanResult> pending) protected ScanResult Wait(Task<ScanResult> pending)
...@@ -217,21 +218,15 @@ class CursorEnumerator : IEnumerator<T>, IScanningCursor ...@@ -217,21 +218,15 @@ class CursorEnumerator : IEnumerator<T>, IScanningCursor
private CursorEnumerable<T> parent; private CursorEnumerable<T> parent;
public CursorEnumerator(CursorEnumerable<T> parent) public CursorEnumerator(CursorEnumerable<T> parent)
{ {
if (parent == null) throw new ArgumentNullException("parent"); if (parent == null) throw new ArgumentNullException(nameof(parent));
this.parent = parent; this.parent = parent;
Reset(); Reset();
} }
public T Current public T Current => page[pageIndex];
{
get { return page[pageIndex]; }
}
void IDisposable.Dispose() { parent = null; state = State.Disposed; } void IDisposable.Dispose() { parent = null; state = State.Disposed; }
object System.Collections.IEnumerator.Current object System.Collections.IEnumerator.Current => page[pageIndex];
{
get { return page[pageIndex]; }
}
private void LoadNextPageAsync() private void LoadNextPageAsync()
{ {
...@@ -322,34 +317,23 @@ public void Reset() ...@@ -322,34 +317,23 @@ public void Reset()
pending = null; pending = null;
} }
long IScanningCursor.Cursor long IScanningCursor.Cursor => currentCursor;
{
get { return currentCursor; }
}
int IScanningCursor.PageSize int IScanningCursor.PageSize => parent.pageSize;
{
get { return parent.pageSize; }
}
int IScanningCursor.PageOffset int IScanningCursor.PageOffset => pageIndex;
{
get { return pageIndex; }
}
} }
long IScanningCursor.Cursor long IScanningCursor.Cursor
{ {
get { var tmp = activeCursor; return tmp == null ? initialCursor : tmp.Cursor; } get { var tmp = activeCursor; return tmp?.Cursor ?? initialCursor; }
} }
int IScanningCursor.PageSize int IScanningCursor.PageSize => pageSize;
{
get { return pageSize; }
}
int IScanningCursor.PageOffset int IScanningCursor.PageOffset
{ {
get { var tmp = activeCursor; return tmp == null ? initialOffset : tmp.PageOffset; } get { var tmp = activeCursor; return tmp?.PageOffset ?? initialOffset; }
} }
} }
} }
......
...@@ -8,7 +8,6 @@ namespace StackExchange.Redis ...@@ -8,7 +8,6 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public struct RedisChannel : IEquatable<RedisChannel> public struct RedisChannel : IEquatable<RedisChannel>
{ {
internal static readonly RedisChannel[] EmptyArray = new RedisChannel[0]; internal static readonly RedisChannel[] EmptyArray = new RedisChannel[0];
private readonly byte[] value; private readonly byte[] value;
...@@ -30,7 +29,7 @@ public RedisChannel(string value, PatternMode mode) : this(value == null ? null ...@@ -30,7 +29,7 @@ public RedisChannel(string value, PatternMode mode) : this(value == null ? null
private RedisChannel(byte[] value, bool isPatternBased) private RedisChannel(byte[] value, bool isPatternBased)
{ {
this.value = value; this.value = value;
this.IsPatternBased = isPatternBased; IsPatternBased = isPatternBased;
} }
private static bool DeterminePatternBased(byte[] value, PatternMode mode) private static bool DeterminePatternBased(byte[] value, PatternMode mode)
{ {
...@@ -41,27 +40,18 @@ private static bool DeterminePatternBased(byte[] value, PatternMode mode) ...@@ -41,27 +40,18 @@ private static bool DeterminePatternBased(byte[] value, PatternMode mode)
case PatternMode.Literal: return false; case PatternMode.Literal: return false;
case PatternMode.Pattern: return true; case PatternMode.Pattern: return true;
default: default:
throw new ArgumentOutOfRangeException("mode"); throw new ArgumentOutOfRangeException(nameof(mode));
} }
} }
/// <summary> /// <summary>
/// Indicates whether the channel-name is either null or a zero-length value /// Indicates whether the channel-name is either null or a zero-length value
/// </summary> /// </summary>
public bool IsNullOrEmpty public bool IsNullOrEmpty => value == null || value.Length == 0;
{
get
{
return value == null || value.Length == 0;
}
}
internal bool IsNull internal bool IsNull => value == null;
{
get { return value == null; }
}
internal byte[] Value { get { return value; } } internal byte[] Value => value;
/// <summary> /// <summary>
/// Indicate whether two channel names are not equal /// Indicate whether two channel names are not equal
...@@ -150,15 +140,15 @@ public override bool Equals(object obj) ...@@ -150,15 +140,15 @@ public override bool Equals(object obj)
{ {
if (obj is RedisChannel) if (obj is RedisChannel)
{ {
return RedisValue.Equals(this.value, ((RedisChannel)obj).value); return RedisValue.Equals(value, ((RedisChannel)obj).value);
} }
if (obj is string) if (obj is string)
{ {
return RedisValue.Equals(this.value, Encoding.UTF8.GetBytes((string)obj)); return RedisValue.Equals(value, Encoding.UTF8.GetBytes((string)obj));
} }
if (obj is byte[]) if (obj is byte[])
{ {
return RedisValue.Equals(this.value, (byte[])obj); return RedisValue.Equals(value, (byte[])obj);
} }
return false; return false;
} }
...@@ -168,8 +158,8 @@ public override bool Equals(object obj) ...@@ -168,8 +158,8 @@ public override bool Equals(object obj)
/// </summary> /// </summary>
public bool Equals(RedisChannel other) public bool Equals(RedisChannel other)
{ {
return this.IsPatternBased == other.IsPatternBased && return IsPatternBased == other.IsPatternBased &&
RedisValue.Equals(this.value, other.value); RedisValue.Equals(value, other.value);
} }
/// <summary> /// <summary>
...@@ -177,7 +167,7 @@ public bool Equals(RedisChannel other) ...@@ -177,7 +167,7 @@ public bool Equals(RedisChannel other)
/// </summary> /// </summary>
public override int GetHashCode() public override int GetHashCode()
{ {
return RedisValue.GetHashCode(this.value) + (IsPatternBased ? 1 : 0); return RedisValue.GetHashCode(value) + (IsPatternBased ? 1 : 0);
} }
/// <summary> /// <summary>
...@@ -204,7 +194,7 @@ internal void AssertNotNull() ...@@ -204,7 +194,7 @@ internal void AssertNotNull()
internal RedisChannel Clone() internal RedisChannel Clone()
{ {
byte[] clone = value == null ? null : (byte[])value.Clone(); byte[] clone = (byte[]) value?.Clone();
return clone; return clone;
} }
......
...@@ -9,9 +9,7 @@ namespace StackExchange.Redis ...@@ -9,9 +9,7 @@ namespace StackExchange.Redis
/// </summary> /// </summary>
public sealed class RedisErrorEventArgs : EventArgs, ICompletable public sealed class RedisErrorEventArgs : EventArgs, ICompletable
{ {
private readonly EndPoint endpoint;
private readonly EventHandler<RedisErrorEventArgs> handler; private readonly EventHandler<RedisErrorEventArgs> handler;
private readonly string message;
private readonly object sender; private readonly object sender;
internal RedisErrorEventArgs( internal RedisErrorEventArgs(
EventHandler<RedisErrorEventArgs> handler, object sender, EventHandler<RedisErrorEventArgs> handler, object sender,
...@@ -19,29 +17,28 @@ public sealed class RedisErrorEventArgs : EventArgs, ICompletable ...@@ -19,29 +17,28 @@ public sealed class RedisErrorEventArgs : EventArgs, ICompletable
{ {
this.handler = handler; this.handler = handler;
this.sender = sender; this.sender = sender;
this.message = message; Message = message;
this.endpoint = endpoint; EndPoint = endpoint;
} }
/// <summary> /// <summary>
/// The origin of the message /// The origin of the message
/// </summary> /// </summary>
public EndPoint EndPoint { get { return endpoint; } } public EndPoint EndPoint { get; }
/// <summary> /// <summary>
/// The message from the server /// The message from the server
/// </summary> /// </summary>
public string Message { get { return message; } } public string Message { get; }
void ICompletable.AppendStormLog(StringBuilder sb) void ICompletable.AppendStormLog(StringBuilder sb)
{ {
sb.Append("event, error: ").Append(message); sb.Append("event, error: ").Append(Message);
} }
bool ICompletable.TryComplete(bool isAsync) bool ICompletable.TryComplete(bool isAsync)
{ {
return ConnectionMultiplexer.TryCompleteHandler(handler, sender, this, isAsync); return ConnectionMultiplexer.TryCompleteHandler(handler, sender, this, isAsync);
} }
} }
} }
...@@ -21,10 +21,7 @@ internal RedisKey AsPrefix() ...@@ -21,10 +21,7 @@ internal RedisKey AsPrefix()
{ {
return new RedisKey((byte[])this, null); return new RedisKey((byte[])this, null);
} }
internal bool IsNull internal bool IsNull => keyPrefix == null && keyValue == null;
{
get { return keyPrefix == null && keyValue == null; }
}
internal bool IsEmpty internal bool IsEmpty
{ {
...@@ -37,8 +34,8 @@ internal bool IsEmpty ...@@ -37,8 +34,8 @@ internal bool IsEmpty
} }
} }
internal byte[] KeyPrefix { get { return keyPrefix; } } internal byte[] KeyPrefix => keyPrefix;
internal object KeyValue { get { return keyValue; } } internal object KeyValue => keyValue;
/// <summary> /// <summary>
/// Indicate whether two keys are not equal /// Indicate whether two keys are not equal
...@@ -164,7 +161,7 @@ private static bool CompositeEquals(byte[] keyPrefix0, object keyValue0, byte[] ...@@ -164,7 +161,7 @@ private static bool CompositeEquals(byte[] keyPrefix0, object keyValue0, byte[]
/// </summary> /// </summary>
public override int GetHashCode() public override int GetHashCode()
{ {
int chk0 = (keyPrefix == null) ? 0 : RedisValue.GetHashCode(this.keyPrefix), int chk0 = keyPrefix == null ? 0 : RedisValue.GetHashCode(this.keyPrefix),
chk1 = keyValue is string ? keyValue.GetHashCode() : RedisValue.GetHashCode((byte[])keyValue); chk1 = keyValue is string ? keyValue.GetHashCode() : RedisValue.GetHashCode((byte[])keyValue);
return unchecked((17 * chk0) + chk1); return unchecked((17 * chk0) + chk1);
...@@ -272,11 +269,11 @@ internal static byte[] ConcatenateBytes(byte[] a, object b, byte[] c) ...@@ -272,11 +269,11 @@ internal static byte[] ConcatenateBytes(byte[] a, object b, byte[] c)
return (byte[])b; return (byte[])b;
} }
int aLen = a == null ? 0 : a.Length, int aLen = a?.Length ?? 0,
bLen = b == null ? 0 : (b is string bLen = b == null ? 0 : (b is string
? Encoding.UTF8.GetByteCount((string)b) ? Encoding.UTF8.GetByteCount((string)b)
: ((byte[])b).Length), : ((byte[])b).Length),
cLen = c == null ? 0 : c.Length; cLen = c?.Length ?? 0;
byte[] result = new byte[aLen + bLen + cLen]; byte[] result = new byte[aLen + bLen + cLen];
if (aLen != 0) Buffer.BlockCopy(a, 0, result, 0, aLen); if (aLen != 0) Buffer.BlockCopy(a, 0, result, 0, aLen);
......
...@@ -102,7 +102,7 @@ internal static RedisValue Get(Bitwise operation) ...@@ -102,7 +102,7 @@ internal static RedisValue Get(Bitwise operation)
case Bitwise.Or: return OR; case Bitwise.Or: return OR;
case Bitwise.Xor: return XOR; case Bitwise.Xor: return XOR;
case Bitwise.Not: return NOT; case Bitwise.Not: return NOT;
default: throw new ArgumentOutOfRangeException("operation"); default: throw new ArgumentOutOfRangeException(nameof(operation));
} }
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment