Skip to content

Commit

Permalink
chore: Use collection expression (microsoft#577)
Browse files Browse the repository at this point in the history
* chore: Use collection expression

* chore: Use collection expression

* chore: Use collection expression

* chore: Use collection expression

* chore: Use collection expression

* Update test/Garnet.test.cluster/RedirectTests/ClusterSlotVerificationTests.cs

Co-authored-by: Vasileios Zois <[email protected]>

* chore: Use collection expression

---------

Co-authored-by: Vasileios Zois <[email protected]>
Co-authored-by: Badrish Chandramouli <[email protected]>
Co-authored-by: Tal Zaccai <[email protected]>
  • Loading branch information
4 people authored Aug 13, 2024
1 parent d6b01c0 commit d6d9a3c
Show file tree
Hide file tree
Showing 60 changed files with 338 additions and 335 deletions.
14 changes: 14 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,20 @@ dotnet_diagnostic.CA1867.severity = warning
# CA2254: Template should be a static expression
dotnet_diagnostic.CA2254.severity = warning

# Use collection expression for array
dotnet_diagnostic.IDE0300.severity = warning
dotnet_style_prefer_collection_expression = true
# Use collection expression for empty
dotnet_diagnostic.IDE0301.severity = warning
# Use collection expression for stackalloc
dotnet_diagnostic.IDE0302.severity = warning
# Use collection expression for `Create()
dotnet_diagnostic.IDE0303.severity = warning
# Use collection expression for builder
dotnet_diagnostic.IDE0304.severity = warning
# Use collection expression for fluent
dotnet_diagnostic.IDE0305.severity = warning

# Miscellaneous style rules
dotnet_separate_import_directive_groups = false
file_header_template = Copyright (c) Microsoft Corporation.\nLicensed under the MIT license.
Expand Down
6 changes: 3 additions & 3 deletions benchmark/Resp.benchmark/BenchmarkLoggerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ public class BenchmarkLoggerProvider : ILoggerProvider
{
private readonly TextWriter textWriter;

static readonly string[] lvl = new string[]
{
static readonly string[] lvl =
[
"trce",
"dbug",
"info",
"warn",
"errr",
"crit",
};
];

public BenchmarkLoggerProvider(TextWriter textWriter)
{
Expand Down
2 changes: 1 addition & 1 deletion benchmark/Resp.benchmark/RespPerfBench.cs
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ private void GarnetClientSessionOperateThreadRunner(int NumOps, OpType opType, R
{
var reqArgs = rg.GetRequestArgs();
reqArgs.Insert(0, "MSET");
c.Execute(reqArgs.ToArray());
c.Execute([.. reqArgs]);
c.CompletePending(true);
numReqs++;
if (numReqs == maxReqs) break;
Expand Down
2 changes: 1 addition & 1 deletion benchmark/Resp.benchmark/TxnPerfBench.cs
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ public void LoadData()
}

for (int key = 0; key < opts.DbSize; key++)
client.Execute(new string[] { "SET", req.GenerateExactKey(key), req.GenerateValue() });
client.Execute(["SET", req.GenerateExactKey(key), req.GenerateValue()]);
}


Expand Down
2 changes: 1 addition & 1 deletion libs/client/GarnetClientAPI/GarnetClientClusterCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public async Task<bool> Failover(FailoverOption failoverOption = default, Cancel
{
var args = failoverOption == default ?
new Memory<byte>[] { FAILOVER } :
new Memory<byte>[] { FAILOVER, FailoverUtils.GetRespFormattedFailoverOption(failoverOption) };
[FAILOVER, FailoverUtils.GetRespFormattedFailoverOption(failoverOption)];
return await ExecuteForStringResultWithCancellationAsync(CLUSTER, args, token: cancellationToken).ConfigureAwait(false) == "OK";
}
}
Expand Down
4 changes: 2 additions & 2 deletions libs/client/GarnetClientAPI/GarnetClientListCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public sealed partial class GarnetClient
/// <param name="context">An optional context to correlate request to callback.</param>
public void ListLeftPush(string key, string element, Action<long, long, string> callback, long context = 0)
{
ListLeftPush(key, new[] { element }, callback, context);
ListLeftPush(key, [element], callback, context);
}

/// <summary>
Expand Down Expand Up @@ -78,7 +78,7 @@ public async Task<long> ListLeftPushAsync(string key, params string[] elements)
/// <param name="context">An optional context to correlate request to callback.</param>
public void ListRightPush(string key, string element, Action<long, long, string> callback, long context = 0)
{
ListRightPush(key, new[] { element }, callback, context);
ListRightPush(key, [element], callback, context);
}

/// <summary>
Expand Down
8 changes: 4 additions & 4 deletions libs/client/GarnetClientMetrics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ private MetricsItem[] GetPercentiles(LongHistogram longHistogram, double scaling
if (histogram == null || histogram.TotalCount == 0)
{
histogram?.Return();
return Array.Empty<MetricsItem>();
return [];
}

var _min = (histogram.GetValueAtPercentile(0) / scaling).ToString("N2", CultureInfo.InvariantCulture);
Expand All @@ -40,8 +40,8 @@ private MetricsItem[] GetPercentiles(LongHistogram longHistogram, double scaling
var _99 = (histogram.GetValueAtPercentile(99) / scaling).ToString("N2", CultureInfo.InvariantCulture);
var _999 = (histogram.GetValueAtPercentile(99.9) / scaling).ToString("N2", CultureInfo.InvariantCulture);

MetricsItem[] percentiles = new MetricsItem[]
{
MetricsItem[] percentiles =
[
new("calls", latency.TotalCount.ToString()),
new("min", _min),
new("5th", _5),
Expand All @@ -50,7 +50,7 @@ private MetricsItem[] GetPercentiles(LongHistogram longHistogram, double scaling
new("95th", _95),
new("99th", _99),
new("99.9th", _999)
};
];

histogram.Return();
return percentiles;
Expand Down
4 changes: 2 additions & 2 deletions libs/client/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static class Utility
/// <returns>The number</returns>
public static long ParseSize(string value)
{
char[] suffix = new char[] { 'k', 'm', 'g', 't', 'p' };
char[] suffix = ['k', 'm', 'g', 't', 'p'];
long result = 0;
foreach (char c in value)
{
Expand Down Expand Up @@ -83,7 +83,7 @@ public static long PreviousPowerOf2(long v)
/// <returns></returns>
internal static string PrettySize(long value)
{
char[] suffix = new char[] { 'K', 'M', 'G', 'T', 'P' };
char[] suffix = ['K', 'M', 'G', 'T', 'P'];
double v = value;
int exp = 0;
while (v - Math.Floor(v) > 0)
Expand Down
10 changes: 5 additions & 5 deletions libs/cluster/Server/ClusterManagerSlotState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public bool TryAddSlots(HashSet<int> slots, out int slotAssigned)
break;
}
FlushConfig();
logger?.LogTrace("AddSlots {slots}", GetRange(slots.ToArray()));
logger?.LogTrace("AddSlots {slots}", GetRange([.. slots]));
return true;
}

Expand Down Expand Up @@ -78,7 +78,7 @@ public bool TryRemoveSlots(HashSet<int> slots, out int notLocalSlot)
break;
}
FlushConfig();
logger?.LogTrace("RemoveSlots {slots}", GetRange(slots.ToArray()));
logger?.LogTrace("RemoveSlots {slots}", GetRange([.. slots]));
return true;
}

Expand Down Expand Up @@ -210,7 +210,7 @@ public bool TryPrepareSlotsForMigration(HashSet<int> slots, string nodeid, out R
break;
}
FlushConfig();
logger?.LogTrace("SetSlotsRange MIGRATING {slot} TO {nodeId}", GetRange(slots.ToArray()), currentConfig.GetWorkerAddressFromNodeId(nodeid));
logger?.LogTrace("SetSlotsRange MIGRATING {slot} TO {nodeId}", GetRange([.. slots]), currentConfig.GetWorkerAddressFromNodeId(nodeid));
return true;
}

Expand Down Expand Up @@ -327,7 +327,7 @@ public bool TryPrepareSlotsForImport(HashSet<int> slots, string nodeid, out Read
break;
}
FlushConfig();
logger?.LogTrace("SetSlotsRange IMPORTING {slot} TO {nodeId}", GetRange(slots.ToArray()), currentConfig.GetWorkerAddressFromNodeId(nodeid));
logger?.LogTrace("SetSlotsRange IMPORTING {slot} TO {nodeId}", GetRange([.. slots]), currentConfig.GetWorkerAddressFromNodeId(nodeid));
return true;
}

Expand Down Expand Up @@ -415,7 +415,7 @@ public bool TryPrepareSlotsForOwnershipChange(HashSet<int> slots, string nodeid,
}

FlushConfig();
logger?.LogTrace("Slots {slot} IMPORTED TO {endpoint}", GetRange(slots.ToArray()), currentConfig.GetWorkerAddressFromNodeId(nodeid));
logger?.LogTrace("Slots {slot} IMPORTED TO {endpoint}", GetRange([.. slots]), currentConfig.GetWorkerAddressFromNodeId(nodeid));
return true;
}

Expand Down
2 changes: 1 addition & 1 deletion libs/cluster/Server/GarnetServerNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ private byte[] GetMostRecentConfig()
}
else
{
byteArray = Array.Empty<byte>();
byteArray = [];
}
return byteArray;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ private async Task SendFileSegments(GarnetClientSession gcs, Guid token, Checkpo
}

// Send last empty package to indicate end of transmission and let replica dispose IDevice
resp = await gcs.ExecuteSendFileSegments(fileTokenBytes, (int)type, startAddress, Array.Empty<byte>()).ConfigureAwait(false);
resp = await gcs.ExecuteSendFileSegments(fileTokenBytes, (int)type, startAddress, []).ConfigureAwait(false);
if (!resp.Equals("OK"))
{
logger?.LogError("Primary error at SendFileSegments {type} {resp}", type, resp);
Expand Down Expand Up @@ -477,7 +477,7 @@ private async Task SendObjectFiles(GarnetClientSession gcs, Guid token, Checkpoi
startAddress += readBytes;
}

resp = await gcs.ExecuteSendFileSegments(fileTokenBytes, (int)type, 0L, Array.Empty<byte>()).ConfigureAwait(false);
resp = await gcs.ExecuteSendFileSegments(fileTokenBytes, (int)type, 0L, []).ConfigureAwait(false);
if (!resp.Equals("OK"))
{
logger?.LogError("Primary error at SendFileSegments {type} {resp}", type, resp);
Expand Down
2 changes: 1 addition & 1 deletion libs/cluster/Session/RespClusterBasicCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ private bool NetworkClusterGossip(int count, out bool invalidParameters)
}
else
{
while (!RespWriteUtils.WriteBulkString(Array.Empty<byte>(), ref dcurr, dend))
while (!RespWriteUtils.WriteBulkString([], ref dcurr, dend))
SendAndReset();
}

Expand Down
2 changes: 1 addition & 1 deletion libs/host/Configuration/GarnetCustomTransformers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public bool Transform(T[] input, out T output, out string errorMessage)
public bool TransformBack(T input, out T[] output, out string errorMessage)
{
errorMessage = null;
output = new[] { input };
output = [input];
return true;
}
}
Expand Down
26 changes: 13 additions & 13 deletions libs/host/Configuration/OptionsValidators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali

var baseError = validationContext.MemberName != null ? base.FormatErrorMessage(validationContext.MemberName) : string.Empty;
var errorMessage = $"{baseError} Required value was not specified.";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

/// <summary>
Expand Down Expand Up @@ -76,7 +76,7 @@ protected bool TryInitialValidation<T>(object value, ValidationContext validatio
{
var baseError = validationContext.MemberName != null ? base.FormatErrorMessage(validationContext.MemberName) : string.Empty;
var errorMessage = $"{baseError} Invalid type. Expected: {typeof(T)}. Actual: {value?.GetType()}";
validationResult = new ValidationResult(errorMessage, new[] { validationContext.MemberName });
validationResult = new ValidationResult(errorMessage, [validationContext.MemberName]);
return true;
}

Expand Down Expand Up @@ -124,7 +124,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali
catch (Exception e) when (e is SecurityException or PathTooLongException)
{
var errorMessage = $"{baseError} An exception of type {e.GetType()} has occurred while trying to access directory. Directory path: {directoryPath}.";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

var options = (Options)validationContext.ObjectInstance;
Expand All @@ -138,7 +138,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali
if (this._mustExist && !directoryInfo.Exists)
{
var errorMessage = $"{baseError} Specified directory does not exist. Directory path: {directoryPath}.";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

return ValidationResult.Success;
Expand Down Expand Up @@ -188,7 +188,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali
if (!isValid)
{
var errorMessage = $"Error(s) validating one or more directories:{Environment.NewLine}{errorSb}";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

return ValidationResult.Success;
Expand Down Expand Up @@ -243,7 +243,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali
catch (Exception e) when (e is SecurityException or UnauthorizedAccessException or NotSupportedException or PathTooLongException)
{
var errorMessage = $"{baseError} An exception of type {e.GetType()} has occurred while trying to access file. File path: {filePath}.";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

var options = (Options)validationContext.ObjectInstance;
Expand All @@ -257,20 +257,20 @@ protected override ValidationResult IsValid(object value, ValidationContext vali
if (this._fileMustExist && !fileInfo.Exists)
{
var errorMessage = $"{baseError} Specified file does not exist. File path: {filePath}.";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

if (this._directoryMustExist && (fileInfo.Directory == null || !fileInfo.Directory.Exists))
{
var errorMessage = $"{baseError} Directory containing specified file does not exist. File path: {filePath}.";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

if (this._acceptedFileExtensions != null && !this._acceptedFileExtensions.Any(filePath.EndsWith))
{
var errorMessage =
$"{baseError} Unexpected extension for specified file. Expected: {string.Join(" / ", this._acceptedFileExtensions)}.";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}

return ValidationResult.Success;
Expand Down Expand Up @@ -305,7 +305,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali

var baseError = validationContext.MemberName != null ? base.FormatErrorMessage(validationContext.MemberName) : string.Empty;
var errorMessage = $"{baseError} Expected string in IPv4 / IPv6 format (e.g. 127.0.0.1 / 0:0:0:0:0:0:0:1) or 'localhost'. Actual value: {ipAddress}";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}
}

Expand Down Expand Up @@ -337,7 +337,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali

var baseError = validationContext.MemberName != null ? base.FormatErrorMessage(validationContext.MemberName) : string.Empty;
var errorMessage = $"{baseError} Expected string in memory size format (e.g. 1k, 1kb, 10m, 10mb, 50g, 50gb etc). Actual value: {memorySize}";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}
}

Expand Down Expand Up @@ -417,7 +417,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali

var baseError = validationContext.MemberName != null ? base.FormatErrorMessage(validationContext.MemberName) : string.Empty;
var errorMessage = $"{baseError} Expected to be in range {(this._includeMin ? "[" : "(")}{this._min}, {this._max}{(this._includeMax ? "]" : ")")}. Actual value: {value}";
return new ValidationResult(errorMessage, new[] { validationContext.MemberName });
return new ValidationResult(errorMessage, [validationContext.MemberName]);
}
}

Expand Down Expand Up @@ -507,7 +507,7 @@ protected override ValidationResult IsValid(object value, ValidationContext vali
internal sealed class CertFileValidationAttribute : FilePathValidationAttribute
{
internal CertFileValidationAttribute(bool fileMustExist, bool directoryMustExist, bool isRequired) : base(
fileMustExist, directoryMustExist, isRequired, new[] { ".pfx" })
fileMustExist, directoryMustExist, isRequired, [".pfx"])
{
}

Expand Down
4 changes: 2 additions & 2 deletions libs/host/ServerSettingsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ internal static bool TryParseCommandLineArguments(string[] args, out Options opt
options = null;
invalidOptions = new List<string>();

if (args == null) args = Array.Empty<string>();
if (args == null) args = [];

// Initialize command line parser
var parser = new Parser(settings =>
Expand Down Expand Up @@ -357,7 +357,7 @@ private static string[] ConsolidateFlagArguments(string[] args)
}
}

return consolidatedArgs.ToArray();
return [.. consolidatedArgs];
}
}
}
6 changes: 3 additions & 3 deletions libs/server/ACL/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public void AddCategory(RespAclCategories category)
}
else
{
commandInfos = Array.Empty<RespCommandsInfo>();
commandInfos = [];
descUpdate = null;
}

Expand Down Expand Up @@ -216,7 +216,7 @@ public void RemoveCategory(RespAclCategories category)
}
else
{
commandInfos = Array.Empty<RespCommandsInfo>();
commandInfos = [];
descUpdate = null;
}

Expand Down Expand Up @@ -455,7 +455,7 @@ internal static IEnumerable<RespCommand> DetermineCommandDetails(IReadOnlyList<R
/// </summary>
private static string RationalizeACLDescription(CommandPermissionSet set, string description)
{
List<string> parts = description.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
List<string> parts = [.. description.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)];
while (true)
{
bool shrunk = false;
Expand Down
2 changes: 1 addition & 1 deletion libs/server/Auth/Aad/IssuerSigningTokenProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ private static IReadOnlyCollection<SecurityKey> RetrieveSigningTokens(string aut
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(configUrl, new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever());
var doc = configManager.GetConfigurationAsync().GetAwaiter().GetResult();

return doc.SigningKeys.ToList();
return [.. doc.SigningKeys];
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion libs/server/Custom/CustomCommandRegistration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ internal abstract class RegisterCustomCommandProviderBase : IRegisterCustomComma
}
}
return supportedTypes.ToArray();
return [.. supportedTypes];
});

public abstract void Register(CustomCommandManager customCommandManager);
Expand Down
Loading

0 comments on commit d6d9a3c

Please sign in to comment.