Commit 8b7446a5 authored by Nick Craver's avatar Nick Craver

General cleanup

parent 267ec00d
...@@ -8,7 +8,7 @@ public class QueryTest ...@@ -8,7 +8,7 @@ public class QueryTest
public static Query GetQuery() => new Query("hello world"); public static Query GetQuery() => new Query("hello world");
[Fact] [Fact]
public void getNoContent() public void GetNoContent()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.False(query.NoContent); Assert.False(query.NoContent);
...@@ -17,7 +17,7 @@ public void getNoContent() ...@@ -17,7 +17,7 @@ public void getNoContent()
} }
[Fact] [Fact]
public void getWithScores() public void GetWithScores()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.False(query.WithScores); Assert.False(query.WithScores);
...@@ -26,7 +26,7 @@ public void getWithScores() ...@@ -26,7 +26,7 @@ public void getWithScores()
} }
[Fact] [Fact]
public void serializeRedisArgs() public void SerializeRedisArgs()
{ {
var query = new Query("hello world") var query = new Query("hello world")
{ {
...@@ -38,7 +38,6 @@ public void serializeRedisArgs() ...@@ -38,7 +38,6 @@ public void serializeRedisArgs()
WithScores = true WithScores = true
}; };
var args = new List<object>(); var args = new List<object>();
query.SerializeRedisArgs(args); query.SerializeRedisArgs(args);
...@@ -57,7 +56,7 @@ public void serializeRedisArgs() ...@@ -57,7 +56,7 @@ public void serializeRedisArgs()
} }
[Fact] [Fact]
public void limit() public void Limit()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.Equal(0, query._paging.Offset); Assert.Equal(0, query._paging.Offset);
...@@ -65,11 +64,10 @@ public void limit() ...@@ -65,11 +64,10 @@ public void limit()
Assert.Same(query, query.Limit(1, 30)); Assert.Same(query, query.Limit(1, 30));
Assert.Equal(1, query._paging.Offset); Assert.Equal(1, query._paging.Offset);
Assert.Equal(30, query._paging.Count); Assert.Equal(30, query._paging.Count);
} }
[Fact] [Fact]
public void addFilter() public void AddFilter()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.Empty(query._filters); Assert.Empty(query._filters);
...@@ -79,7 +77,7 @@ public void addFilter() ...@@ -79,7 +77,7 @@ public void addFilter()
} }
[Fact] [Fact]
public void setVerbatim() public void SetVerbatim()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.False(query.Verbatim); Assert.False(query.Verbatim);
...@@ -87,20 +85,17 @@ public void setVerbatim() ...@@ -87,20 +85,17 @@ public void setVerbatim()
Assert.True(query.Verbatim); Assert.True(query.Verbatim);
} }
[Fact] [Fact]
public void setNoStopwords() public void SetNoStopwords()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.False(query.NoStopwords); Assert.False(query.NoStopwords);
Assert.Same(query, query.SetNoStopwords()); Assert.Same(query, query.SetNoStopwords());
Assert.True(query.NoStopwords); Assert.True(query.NoStopwords);
} }
[Fact] [Fact]
public void setLanguage() public void SetLanguage()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.Null(query.Language); Assert.Null(query.Language);
...@@ -109,17 +104,16 @@ public void setLanguage() ...@@ -109,17 +104,16 @@ public void setLanguage()
} }
[Fact] [Fact]
public void limitFields() public void LimitFields()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.Null(query._fields); Assert.Null(query._fields);
Assert.Same(query, query.LimitFields("foo", "bar")); Assert.Same(query, query.LimitFields("foo", "bar"));
Assert.Equal(2, query._fields.Length); Assert.Equal(2, query._fields.Length);
} }
[Fact] [Fact]
public void highlightFields() public void HighlightFields()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.False(query._wantsHighlight); Assert.False(query._wantsHighlight);
...@@ -144,7 +138,7 @@ public void highlightFields() ...@@ -144,7 +138,7 @@ public void highlightFields()
} }
[Fact] [Fact]
public void summarizeFields() public void SummarizeFields()
{ {
var query = GetQuery(); var query = GetQuery();
Assert.False(query._wantsSummarize); Assert.False(query._wantsSummarize);
......
...@@ -242,11 +242,11 @@ private bool SendDataCommand(byte[] data, string cmd, params object[] args) ...@@ -242,11 +242,11 @@ private bool SendDataCommand(byte[] data, string cmd, params object[] args)
if (socket == null) if (socket == null)
return false; return false;
var s = args.Length > 0 ? String.Format(cmd, args) : cmd; var s = args.Length > 0 ? string.Format(cmd, args) : cmd;
byte[] r = Encoding.UTF8.GetBytes(s); byte[] r = Encoding.UTF8.GetBytes(s);
try try
{ {
Log("S: " + String.Format(cmd, args)); Log("S: " + string.Format(cmd, args));
socket.Send(r); socket.Send(r);
if (data != null) if (data != null)
{ {
...@@ -272,11 +272,11 @@ private bool SendCommand(string cmd, params object[] args) ...@@ -272,11 +272,11 @@ private bool SendCommand(string cmd, params object[] args)
if (socket == null) if (socket == null)
return false; return false;
var s = args?.Length > 0 ? String.Format(cmd, args) : cmd; var s = args?.Length > 0 ? string.Format(cmd, args) : cmd;
byte[] r = Encoding.UTF8.GetBytes(s); byte[] r = Encoding.UTF8.GetBytes(s);
try try
{ {
Log("S: " + String.Format(cmd, args)); Log("S: " + string.Format(cmd, args));
socket.Send(r); socket.Send(r);
} }
catch (SocketException) catch (SocketException)
...@@ -293,7 +293,7 @@ private bool SendCommand(string cmd, params object[] args) ...@@ -293,7 +293,7 @@ private bool SendCommand(string cmd, params object[] args)
[Conditional("DEBUG")] [Conditional("DEBUG")]
private void Log(string fmt, params object[] args) private void Log(string fmt, params object[] args)
{ {
Console.WriteLine("{0}", String.Format(fmt, args).Trim()); Console.WriteLine("{0}", string.Format(fmt, args).Trim());
} }
private void ExpectSuccess() private void ExpectSuccess()
...@@ -416,7 +416,7 @@ private byte[] ReadData() ...@@ -416,7 +416,7 @@ private byte[] ReadData()
if (r == "$-1") if (r == "$-1")
return null; return null;
if (Int32.TryParse(r.Substring(1), out int n)) if (int.TryParse(r.Substring(1), out int n))
{ {
var retbuf = new byte[n]; var retbuf = new byte[n];
...@@ -439,7 +439,7 @@ private byte[] ReadData() ...@@ -439,7 +439,7 @@ private byte[] ReadData()
//returns the number of matches //returns the number of matches
if (c == '*') if (c == '*')
{ {
if (Int32.TryParse(r.Substring(1), out int n)) if (int.TryParse(r.Substring(1), out int n))
return n <= 0 ? new byte[0] : ReadData(); return n <= 0 ? new byte[0] : ReadData();
throw new ResponseException("Unexpected length parameter" + r); throw new ResponseException("Unexpected length parameter" + r);
...@@ -759,16 +759,16 @@ public byte[][] GetUnionOfSets(params string[] keys) ...@@ -759,16 +759,16 @@ public byte[][] GetUnionOfSets(params string[] keys)
private void StoreSetCommands(string cmd, string destKey, params string[] keys) private void StoreSetCommands(string cmd, string destKey, params string[] keys)
{ {
if (String.IsNullOrEmpty(cmd)) if (string.IsNullOrEmpty(cmd))
throw new ArgumentNullException(nameof(cmd)); throw new ArgumentNullException(nameof(cmd));
if (String.IsNullOrEmpty(destKey)) if (string.IsNullOrEmpty(destKey))
throw new ArgumentNullException(nameof(destKey)); throw new ArgumentNullException(nameof(destKey));
if (keys == null) if (keys == null)
throw new ArgumentNullException(nameof(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));
} }
public void StoreUnionOfSets(string destKey, params string[] keys) public void StoreUnionOfSets(string destKey, params string[] keys)
...@@ -835,15 +835,15 @@ public class SortOptions ...@@ -835,15 +835,15 @@ public class SortOptions
public string Key { get; set; } public string Key { get; set; }
public bool Descending { get; set; } public bool Descending { get; set; }
public bool Lexographically { get; set; } public bool Lexographically { get; set; }
public Int32 LowerLimit { get; set; } public int LowerLimit { get; set; }
public Int32 UpperLimit { get; set; } public int UpperLimit { get; set; }
public string By { get; set; } public string By { get; set; }
public string StoreInKey { get; set; } public string StoreInKey { get; set; }
public string Get { get; set; } public string Get { get; set; }
public string ToCommand() public string ToCommand()
{ {
var command = "SORT " + this.Key; var command = "SORT " + Key;
if (LowerLimit != 0 || UpperLimit != 0) if (LowerLimit != 0 || UpperLimit != 0)
command += " LIMIT " + LowerLimit + " " + UpperLimit; command += " LIMIT " + LowerLimit + " " + UpperLimit;
if (Lexographically) if (Lexographically)
...@@ -857,4 +857,4 @@ public string ToCommand() ...@@ -857,4 +857,4 @@ public string ToCommand()
return command; return command;
} }
} }
} }
\ No newline at end of file
...@@ -43,7 +43,6 @@ public void QueryRangeAndLengthByLex() ...@@ -43,7 +43,6 @@ public void QueryRangeAndLengthByLex()
set = db.SortedSetRangeByValue(key, "aaa", "g", Exclude.Stop, 1, 3); set = db.SortedSetRangeByValue(key, "aaa", "g", Exclude.Stop, 1, 3);
Equate(set, set.Length, "c", "d", "e"); Equate(set, set.Length, "c", "d", "e");
set = db.SortedSetRangeByValue(key, "aaa", "g", Exclude.Stop, Order.Descending, 1, 3); set = db.SortedSetRangeByValue(key, "aaa", "g", Exclude.Stop, Order.Descending, 1, 3);
Equate(set, set.Length, "e", "d", "c"); Equate(set, set.Length, "e", "d", "c");
......
...@@ -22,10 +22,10 @@ public async Task MassiveBulkOpsAsync(bool withContinuation) ...@@ -22,10 +22,10 @@ public async Task MassiveBulkOpsAsync(bool withContinuation)
RedisKey key = "MBOA"; RedisKey key = "MBOA";
var conn = muxer.GetDatabase(); var conn = muxer.GetDatabase();
await conn.PingAsync().ForAwait(); await conn.PingAsync().ForAwait();
Action<Task> nonTrivial = delegate void nonTrivial(Task _)
{ {
Thread.SpinWait(5); Thread.SpinWait(5);
}; }
var watch = Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
for (int i = 0; i <= AsyncOpsQty; i++) for (int i = 0; i <= AsyncOpsQty; i++)
{ {
......
...@@ -20,7 +20,7 @@ public void Execute() ...@@ -20,7 +20,7 @@ public void Execute()
var received = new List<int>(); var received = new List<int>();
Log("Subscribing..."); Log("Subscribing...");
const int COUNT = 1000; const int COUNT = 1000;
sub.Subscribe("foo", (channel, message) => sub.Subscribe("foo", (_, message) =>
{ {
lock (received) lock (received)
{ {
......
...@@ -43,7 +43,6 @@ public void Simple() ...@@ -43,7 +43,6 @@ public void Simple()
{ {
Log("Command {0}: {1}", i++, cmd.ToString().Replace("\n", ", ")); Log("Command {0}: {1}", i++, cmd.ToString().Replace("\n", ", "));
} }
Assert.Equal(3, cmds.Count());
var set = cmds.SingleOrDefault(cmd => cmd.Command == "SET"); var set = cmds.SingleOrDefault(cmd => cmd.Command == "SET");
Assert.NotNull(set); Assert.NotNull(set);
...@@ -51,6 +50,7 @@ public void Simple() ...@@ -51,6 +50,7 @@ public void Simple()
Assert.NotNull(get); Assert.NotNull(get);
var eval = cmds.SingleOrDefault(cmd => cmd.Command == "EVAL"); var eval = cmds.SingleOrDefault(cmd => cmd.Command == "EVAL");
Assert.NotNull(eval); Assert.NotNull(eval);
Assert.Equal(3, cmds.Count());
Assert.True(set.CommandCreated <= get.CommandCreated); Assert.True(set.CommandCreated <= get.CommandCreated);
Assert.True(get.CommandCreated <= eval.CommandCreated); Assert.True(get.CommandCreated <= eval.CommandCreated);
...@@ -453,7 +453,7 @@ public void LowAllocationEnumerable() ...@@ -453,7 +453,7 @@ public void LowAllocationEnumerable()
Assert.True(object.ReferenceEquals(i, j)); Assert.True(object.ReferenceEquals(i, j));
} }
Assert.Equal(OuterLoop, res.Count(r => r.Command == "GET")); Assert.Equal(OuterLoop, res.Count(r => r.Command == "GET"));
Assert.Equal(OuterLoop, res.Count(r => r.Command == "SET")); Assert.Equal(OuterLoop, res.Count(r => r.Command == "SET"));
Assert.Equal(OuterLoop * 2, res.Count()); Assert.Equal(OuterLoop * 2, res.Count());
......
...@@ -563,8 +563,8 @@ public async Task TestMultipleSubscribersGetMessage() ...@@ -563,8 +563,8 @@ public async Task TestMultipleSubscribersGetMessage()
conn.GetDatabase().Ping(); conn.GetDatabase().Ping();
var pub = conn.GetSubscriber(); var pub = conn.GetSubscriber();
int gotA = 0, gotB = 0; int gotA = 0, gotB = 0;
var tA = listenA.SubscribeAsync(channel, (s, msg) => { if (msg == "message") Interlocked.Increment(ref gotA); }); var tA = listenA.SubscribeAsync(channel, (_, msg) => { if (msg == "message") Interlocked.Increment(ref gotA); });
var tB = listenB.SubscribeAsync(channel, (s, msg) => { if (msg == "message") Interlocked.Increment(ref gotB); }); var tB = listenB.SubscribeAsync(channel, (_, msg) => { if (msg == "message") Interlocked.Increment(ref gotB); });
listenA.Wait(tA); listenA.Wait(tA);
listenB.Wait(tB); listenB.Wait(tB);
Assert.Equal(2, pub.Publish(channel, "message")); Assert.Equal(2, pub.Publish(channel, "message"));
......
...@@ -53,6 +53,6 @@ private static void AnyOrderCompletionHandler(object state) ...@@ -53,6 +53,6 @@ private static void AnyOrderCompletionHandler(object state)
{ {
ConnectionMultiplexer.TraceWithoutContext("Async completion error: " + ex.Message); ConnectionMultiplexer.TraceWithoutContext("Async completion error: " + ex.Message);
} }
} }
} }
} }
...@@ -179,10 +179,13 @@ public static string TryNormalize(string value) ...@@ -179,10 +179,13 @@ public static string TryNormalize(string value)
/// <summary> /// <summary>
/// Create a certificate validation check that checks against the supplied issuer even if not known by the machine /// Create a certificate validation check that checks against the supplied issuer even if not known by the machine
/// </summary> /// </summary>
/// <param name="issuerCertificatePath">The file system path to find the certificate at.</param>
public void TrustIssuer(string issuerCertificatePath) => CertificateValidationCallback = TrustIssuerCallback(issuerCertificatePath); public void TrustIssuer(string issuerCertificatePath) => CertificateValidationCallback = TrustIssuerCallback(issuerCertificatePath);
/// <summary> /// <summary>
/// Create a certificate validation check that checks against the supplied issuer even if not known by the machine /// Create a certificate validation check that checks against the supplied issuer even if not known by the machine
/// </summary> /// </summary>
/// <param name="issuer">The issuer to trust.</param>
public void TrustIssuer(X509Certificate2 issuer) => CertificateValidationCallback = TrustIssuerCallback(issuer); public void TrustIssuer(X509Certificate2 issuer) => CertificateValidationCallback = TrustIssuerCallback(issuer);
internal static RemoteCertificateValidationCallback TrustIssuerCallback(string issuerCertificatePath) internal static RemoteCertificateValidationCallback TrustIssuerCallback(string issuerCertificatePath)
...@@ -195,7 +198,8 @@ private static RemoteCertificateValidationCallback TrustIssuerCallback(X509Certi ...@@ -195,7 +198,8 @@ private static RemoteCertificateValidationCallback TrustIssuerCallback(X509Certi
=> sslPolicyError == SslPolicyErrors.RemoteCertificateChainErrors && certificate is X509Certificate2 v2 => sslPolicyError == SslPolicyErrors.RemoteCertificateChainErrors && certificate is X509Certificate2 v2
&& CheckTrustedIssuer(v2, issuer); && CheckTrustedIssuer(v2, issuer);
} }
static bool CheckTrustedIssuer(X509Certificate2 certificateToValidate, X509Certificate2 authority)
private static bool CheckTrustedIssuer(X509Certificate2 certificateToValidate, X509Certificate2 authority)
{ {
// reference: https://stackoverflow.com/questions/6497040/how-do-i-validate-that-a-certificate-was-created-by-a-particular-certification-a // reference: https://stackoverflow.com/questions/6497040/how-do-i-validate-that-a-certificate-was-created-by-a-particular-certification-a
X509Chain chain = new X509Chain(); X509Chain chain = new X509Chain();
...@@ -208,7 +212,6 @@ static bool CheckTrustedIssuer(X509Certificate2 certificateToValidate, X509Certi ...@@ -208,7 +212,6 @@ static bool CheckTrustedIssuer(X509Certificate2 certificateToValidate, X509Certi
chain.ChainPolicy.ExtraStore.Add(authority); chain.ChainPolicy.ExtraStore.Add(authority);
return chain.Build(certificateToValidate); return chain.Build(certificateToValidate);
} }
/// <summary> /// <summary>
/// The client name to use for all connections /// The client name to use for all connections
...@@ -717,14 +720,8 @@ private void DoParse(string configuration, bool ignoreUnknown) ...@@ -717,14 +720,8 @@ private void DoParse(string configuration, bool ignoreUnknown)
} }
} }
private bool GetDefaultAbortOnConnectFailSetting() // Microsoft Azure team wants abortConnect=false by default
{ private bool GetDefaultAbortOnConnectFailSetting() => !IsAzureEndpoint();
// Microsoft Azure team wants abortConnect=false by default
if (IsAzureEndpoint())
return false;
return true;
}
private bool IsAzureEndpoint() private bool IsAzureEndpoint()
{ {
......
...@@ -452,7 +452,7 @@ internal void CheckMessage(Message message) ...@@ -452,7 +452,7 @@ internal void CheckMessage(Message message)
throw ExceptionFactory.AdminModeNotEnabled(IncludeDetailInExceptions, message.Command, message, null); throw ExceptionFactory.AdminModeNotEnabled(IncludeDetailInExceptions, message.Command, message, null);
CommandMap.AssertAvailable(message.Command); CommandMap.AssertAvailable(message.Command);
} }
const string NoContent = "(no content)"; private const string NoContent = "(no content)";
private static void WriteNormalizingLineEndings(string source, StreamWriter writer) private static void WriteNormalizingLineEndings(string source, StreamWriter writer)
{ {
if (source == null) if (source == null)
...@@ -794,13 +794,13 @@ private static ConnectionMultiplexer CreateMultiplexer(object configuration) ...@@ -794,13 +794,13 @@ private static ConnectionMultiplexer CreateMultiplexer(object configuration)
{ {
if (configuration == null) throw new ArgumentNullException(nameof(configuration)); if (configuration == null) throw new ArgumentNullException(nameof(configuration));
ConfigurationOptions config; ConfigurationOptions config;
if (configuration is string) if (configuration is string s)
{ {
config = ConfigurationOptions.Parse((string)configuration); config = ConfigurationOptions.Parse(s);
} }
else if (configuration is ConfigurationOptions) else if (configuration is ConfigurationOptions configurationOptions)
{ {
config = ((ConfigurationOptions)configuration).Clone(); config = (configurationOptions).Clone();
} }
else else
{ {
...@@ -867,7 +867,7 @@ private static ConnectionMultiplexer ConnectImpl(Func<ConnectionMultiplexer> mul ...@@ -867,7 +867,7 @@ private static ConnectionMultiplexer ConnectImpl(Func<ConnectionMultiplexer> mul
private readonly Hashtable servers = new Hashtable(); private readonly Hashtable servers = new Hashtable();
private volatile ServerSnapshot _serverSnapshot = ServerSnapshot.Empty; private volatile ServerSnapshot _serverSnapshot = ServerSnapshot.Empty;
internal ReadOnlySpan<ServerEndPoint> GetServerSnapshot() => _serverSnapshot.Span; internal ReadOnlySpan<ServerEndPoint> GetServerSnapshot() => _serverSnapshot.Span;
sealed class ServerSnapshot private sealed class ServerSnapshot
{ {
public static ServerSnapshot Empty { get; } = new ServerSnapshot(Array.Empty<ServerEndPoint>(), 0); public static ServerSnapshot Empty { get; } = new ServerSnapshot(Array.Empty<ServerEndPoint>(), 0);
private ServerSnapshot(ServerEndPoint[] arr, int count) private ServerSnapshot(ServerEndPoint[] arr, int count)
...@@ -875,8 +875,8 @@ private ServerSnapshot(ServerEndPoint[] arr, int count) ...@@ -875,8 +875,8 @@ private ServerSnapshot(ServerEndPoint[] arr, int count)
_arr = arr; _arr = arr;
_count = count; _count = count;
} }
private ServerEndPoint[] _arr; private readonly ServerEndPoint[] _arr;
private int _count; private readonly int _count;
public ReadOnlySpan<ServerEndPoint> Span => new ReadOnlySpan<ServerEndPoint>(_arr, 0, _count); public ReadOnlySpan<ServerEndPoint> Span => new ReadOnlySpan<ServerEndPoint>(_arr, 0, _count);
internal ServerSnapshot Add(ServerEndPoint value) internal ServerSnapshot Add(ServerEndPoint value)
...@@ -2243,8 +2243,10 @@ public Task<long> PublishReconfigureAsync(CommandFlags flags = CommandFlags.None ...@@ -2243,8 +2243,10 @@ public Task<long> PublishReconfigureAsync(CommandFlags flags = CommandFlags.None
/// <summary> /// <summary>
/// Get the hash-slot associated with a given key, if applicable; this can be useful for grouping operations /// Get the hash-slot associated with a given key, if applicable; this can be useful for grouping operations
/// </summary> /// </summary>
/// <param name="key">The <see cref="RedisKey"/> to determine the hash slot for.</param>
public int GetHashSlot(RedisKey key) => ServerSelectionStrategy.HashSlot(key); public int GetHashSlot(RedisKey key) => ServerSelectionStrategy.HashSlot(key);
} }
internal enum WriteResult internal enum WriteResult
{ {
Success, Success,
......
...@@ -831,13 +831,13 @@ protected ICollection<object> ToInner(ICollection<object> args) ...@@ -831,13 +831,13 @@ protected ICollection<object> ToInner(ICollection<object> args)
foreach(var oldArg in args) foreach(var oldArg in args)
{ {
object newArg; object newArg;
if (oldArg is RedisKey) if (oldArg is RedisKey key)
{ {
newArg = ToInner((RedisKey)oldArg); newArg = ToInner(key);
} }
else if (oldArg is RedisChannel) else if (oldArg is RedisChannel channel)
{ {
newArg = ToInner((RedisChannel)oldArg); newArg = ToInner(channel);
} }
else else
{ {
......
...@@ -2638,7 +2638,7 @@ private Message GetStreamAddMessage(RedisKey key, RedisValue messageId, int? max ...@@ -2638,7 +2638,7 @@ private Message GetStreamAddMessage(RedisKey key, RedisValue messageId, int? max
var offset = 0; var offset = 0;
values[offset++] = messageId; values[offset++] = messageId;
if (maxLength.HasValue) if (maxLength.HasValue)
{ {
values[offset++] = StreamConstants.MaxLen; values[offset++] = StreamConstants.MaxLen;
...@@ -3060,7 +3060,7 @@ public long SortedSetLengthByValue(RedisKey key, RedisValue min, RedisValue max, ...@@ -3060,7 +3060,7 @@ public long SortedSetLengthByValue(RedisKey key, RedisValue min, RedisValue max,
public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take, CommandFlags flags) public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take, CommandFlags flags)
=> SortedSetRangeByValue(key, min, max, exclude, Order.Ascending, skip, take, flags); => SortedSetRangeByValue(key, min, max, exclude, Order.Ascending, skip, take, flags);
static void ReverseLimits(Order order, ref Exclude exclude, ref RedisValue start, ref RedisValue stop) private static void ReverseLimits(Order order, ref Exclude exclude, ref RedisValue start, ref RedisValue stop)
{ {
bool reverseLimits = (order == Order.Ascending) == start.CompareTo(stop) > 0; bool reverseLimits = (order == Order.Ascending) == start.CompareTo(stop) > 0;
if (reverseLimits) if (reverseLimits)
...@@ -3097,6 +3097,7 @@ public Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, Redi ...@@ -3097,6 +3097,7 @@ public Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, Redi
public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take, CommandFlags flags) public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take, CommandFlags flags)
=> SortedSetRangeByValueAsync(key, min, max, exclude, Order.Ascending, skip, take, flags); => SortedSetRangeByValueAsync(key, min, max, exclude, Order.Ascending, skip, take, flags);
public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue),
Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None)
{ {
...@@ -3124,7 +3125,7 @@ internal class ScanIterator<T> : CursorEnumerable<T> ...@@ -3124,7 +3125,7 @@ internal class ScanIterator<T> : CursorEnumerable<T>
this.key = key; this.key = key;
this.pattern = pattern; this.pattern = pattern;
this.command = command; this.command = command;
this.Processor = processor; Processor = processor;
} }
protected override ResultProcessor<CursorEnumerable<T>.ScanResult> Processor { get; } protected override ResultProcessor<CursorEnumerable<T>.ScanResult> Processor { get; }
...@@ -3222,13 +3223,13 @@ protected override void WriteImpl(PhysicalConnection physical) ...@@ -3222,13 +3223,13 @@ protected override void WriteImpl(PhysicalConnection physical)
physical.WriteHeader(_command, args.Count); physical.WriteHeader(_command, args.Count);
foreach (object arg in args) foreach (object arg in args)
{ {
if (arg is RedisKey) if (arg is RedisKey key)
{ {
physical.Write((RedisKey)arg); physical.Write(key);
} }
else if (arg is RedisChannel) else if (arg is RedisChannel channel)
{ {
physical.Write((RedisChannel)arg); physical.Write(channel);
} }
else else
{ // recognises well-known types { // recognises well-known types
...@@ -3246,9 +3247,9 @@ public override int GetHashSlot(ServerSelectionStrategy serverSelectionStrategy) ...@@ -3246,9 +3247,9 @@ public override int GetHashSlot(ServerSelectionStrategy serverSelectionStrategy)
int slot = ServerSelectionStrategy.NoSlot; int slot = ServerSelectionStrategy.NoSlot;
foreach (object arg in args) foreach (object arg in args)
{ {
if (arg is RedisKey) if (arg is RedisKey key)
{ {
slot = serverSelectionStrategy.CombineSlot(slot, (RedisKey)arg); slot = serverSelectionStrategy.CombineSlot(slot, key);
} }
} }
return slot; return slot;
...@@ -3260,7 +3261,9 @@ private sealed class ScriptEvalMessage : Message, IMultiMessage ...@@ -3260,7 +3261,9 @@ private sealed class ScriptEvalMessage : Message, IMultiMessage
private readonly RedisKey[] keys; private readonly RedisKey[] keys;
private readonly string script; private readonly string script;
private readonly RedisValue[] values; private readonly RedisValue[] values;
private byte[] asciiHash, hexHash; private byte[] asciiHash;
private readonly byte[] hexHash;
public ScriptEvalMessage(int db, CommandFlags flags, string script, RedisKey[] keys, RedisValue[] values) public ScriptEvalMessage(int db, CommandFlags flags, string script, RedisKey[] keys, RedisValue[] values)
: this(db, flags, ResultProcessor.ScriptLoadProcessor.IsSHA1(script) ? RedisCommand.EVALSHA : RedisCommand.EVAL, script, null, keys, values) : this(db, flags, ResultProcessor.ScriptLoadProcessor.IsSHA1(script) ? RedisCommand.EVALSHA : RedisCommand.EVAL, script, null, keys, values)
{ {
......
...@@ -179,7 +179,7 @@ private class TransactionMessage : Message, IMultiMessage ...@@ -179,7 +179,7 @@ private class TransactionMessage : Message, IMultiMessage
public TransactionMessage(int db, CommandFlags flags, List<ConditionResult> conditions, List<QueuedMessage> operations) public TransactionMessage(int db, CommandFlags flags, List<ConditionResult> conditions, List<QueuedMessage> operations)
: base(db, flags, RedisCommand.EXEC) : base(db, flags, RedisCommand.EXEC)
{ {
this.InnerOperations = (operations == null || operations.Count == 0) ? Array.Empty<QueuedMessage>() : operations.ToArray(); InnerOperations = (operations == null || operations.Count == 0) ? Array.Empty<QueuedMessage>() : operations.ToArray();
this.conditions = (conditions == null || conditions.Count == 0) ? Array.Empty<ConditionResult>(): conditions.ToArray(); this.conditions = (conditions == null || conditions.Count == 0) ? Array.Empty<ConditionResult>(): conditions.ToArray();
} }
......
...@@ -644,7 +644,9 @@ private static string ToHex(ReadOnlySpan<byte> src) ...@@ -644,7 +644,9 @@ private static string ToHex(ReadOnlySpan<byte> src)
if (MemoryMarshal.TryGetArray(value._memory, out var segment) if (MemoryMarshal.TryGetArray(value._memory, out var segment)
&& segment.Offset == 0 && segment.Offset == 0
&& segment.Count == (segment.Array?.Length ?? -1)) && segment.Count == (segment.Array?.Length ?? -1))
{
return segment.Array; // the memory is backed by an array, and we're reading all of it return segment.Array; // the memory is backed by an array, and we're reading all of it
}
return value._memory.ToArray(); return value._memory.ToArray();
case StorageType.Int64: case StorageType.Int64:
...@@ -738,8 +740,7 @@ private RedisValue Simplify() ...@@ -738,8 +740,7 @@ private RedisValue Simplify()
case StorageType.Double: case StorageType.Double:
// is the double actually an integer? // is the double actually an integer?
f64 = OverlappedValueDouble; f64 = OverlappedValueDouble;
if (f64 >= long.MinValue && f64 <= long.MaxValue if (f64 >= long.MinValue && f64 <= long.MaxValue && (i64 = (long)f64) == f64) return i64;
&& (i64 = (long)f64) == f64) return i64;
break; break;
} }
return this; return this;
...@@ -749,6 +750,7 @@ private RedisValue Simplify() ...@@ -749,6 +750,7 @@ private RedisValue Simplify()
/// Create a RedisValue from a MemoryStream; it will *attempt* to use the internal buffer /// Create a RedisValue from a MemoryStream; it will *attempt* to use the internal buffer
/// directly, but if this isn't possibly it will fallback to ToArray /// directly, but if this isn't possibly it will fallback to ToArray
/// </summary> /// </summary>
/// <param name="stream">The <see cref="MemoryStream"/> to create a value from.</param>
public static RedisValue CreateFrom(MemoryStream stream) public static RedisValue CreateFrom(MemoryStream stream)
{ {
if (stream == null) return Null; if (stream == null) return Null;
...@@ -764,28 +766,28 @@ public static RedisValue CreateFrom(MemoryStream stream) ...@@ -764,28 +766,28 @@ public static RedisValue CreateFrom(MemoryStream stream)
} }
} }
/// <summary> /// <summary>
/// Indicates whether the current value has the supplied value as a prefix /// Indicates whether the current value has the supplied value as a prefix.
/// </summary> /// </summary>
/// <param name="value">The <see cref="RedisValue"/> to check.</param>
public bool StartsWith(RedisValue value) public bool StartsWith(RedisValue value)
{ {
if (this.IsNull || value.IsNull) return false; if (IsNull || value.IsNull) return false;
if (value.IsNullOrEmpty) return true; if (value.IsNullOrEmpty) return true;
if (this.IsNullOrEmpty) return false; if (IsNullOrEmpty) return false;
ReadOnlyMemory<byte> rawThis, rawOther; ReadOnlyMemory<byte> rawThis, rawOther;
var thisType = this.Type; var thisType = Type;
if (thisType == value.Type) // same? can often optimize if (thisType == value.Type) // same? can often optimize
{ {
switch(thisType) switch(thisType)
{ {
case StorageType.String: case StorageType.String:
var sThis = ((string)this._objectOrSentinel); var sThis = ((string)_objectOrSentinel);
var sOther = ((string)value._objectOrSentinel); var sOther = ((string)value._objectOrSentinel);
return sThis.StartsWith(sOther, StringComparison.Ordinal); return sThis.StartsWith(sOther, StringComparison.Ordinal);
case StorageType.Raw: case StorageType.Raw:
rawThis = this._memory; rawThis = _memory;
rawOther = value._memory; rawOther = value._memory;
return rawThis.Span.StartsWith(rawOther.Span); return rawThis.Span.StartsWith(rawOther.Span);
} }
...@@ -793,7 +795,7 @@ public bool StartsWith(RedisValue value) ...@@ -793,7 +795,7 @@ public bool StartsWith(RedisValue value)
byte[] arr0 = null, arr1 = null; byte[] arr0 = null, arr1 = null;
try try
{ {
rawThis = this.AsMemory(out arr0); rawThis = AsMemory(out arr0);
rawOther = value.AsMemory(out arr1); rawOther = value.AsMemory(out arr1);
return rawThis.Span.StartsWith(rawOther.Span); return rawThis.Span.StartsWith(rawOther.Span);
...@@ -830,7 +832,6 @@ private ReadOnlyMemory<byte> AsMemory(out byte[] leased) ...@@ -830,7 +832,6 @@ private ReadOnlyMemory<byte> AsMemory(out byte[] leased)
leased = ArrayPool<byte>.Shared.Rent(PhysicalConnection.MaxInt64TextLen + 2); // reused code has CRLF terminator leased = ArrayPool<byte>.Shared.Rent(PhysicalConnection.MaxInt64TextLen + 2); // reused code has CRLF terminator
len = PhysicalConnection.WriteRaw(leased, _overlappedValue64) - 2; // drop the CRLF len = PhysicalConnection.WriteRaw(leased, _overlappedValue64) - 2; // drop the CRLF
return new ReadOnlyMemory<byte>(leased, 0, len); return new ReadOnlyMemory<byte>(leased, 0, len);
} }
leased = null; leased = null;
return default; return default;
......
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