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

General cleanup

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