From d6d9a3c4c218c8503a29c254c05a10137e03f17b Mon Sep 17 00:00:00 2001 From: Meir Blachman Date: Wed, 14 Aug 2024 00:29:34 +0300 Subject: [PATCH] chore: Use collection expression (#577) * 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 <96085550+vazois@users.noreply.github.com> * chore: Use collection expression --------- Co-authored-by: Vasileios Zois <96085550+vazois@users.noreply.github.com> Co-authored-by: Badrish Chandramouli Co-authored-by: Tal Zaccai --- .editorconfig | 14 ++ .../Resp.benchmark/BenchmarkLoggerProvider.cs | 6 +- benchmark/Resp.benchmark/RespPerfBench.cs | 2 +- benchmark/Resp.benchmark/TxnPerfBench.cs | 2 +- .../GarnetClientClusterCommands.cs | 2 +- .../GarnetClientListCommands.cs | 4 +- libs/client/GarnetClientMetrics.cs | 8 +- libs/client/Utility.cs | 4 +- .../cluster/Server/ClusterManagerSlotState.cs | 10 +- libs/cluster/Server/GarnetServerNode.cs | 2 +- .../PrimaryOps/ReplicaSyncSession.cs | 4 +- .../Session/RespClusterBasicCommands.cs | 2 +- .../Configuration/GarnetCustomTransformers.cs | 2 +- libs/host/Configuration/OptionsValidators.cs | 26 +-- libs/host/ServerSettingsManager.cs | 4 +- libs/server/ACL/User.cs | 6 +- .../Auth/Aad/IssuerSigningTokenProvider.cs | 2 +- .../Custom/CustomCommandRegistration.cs | 2 +- libs/server/Metrics/Info/InfoCommand.cs | 2 +- .../Metrics/Latency/GarnetLatencyMetrics.cs | 2 +- .../Metrics/Latency/RespLatencyCommands.cs | 4 +- .../ItemBroker/CollectionItemBroker.cs | 2 +- libs/server/Resp/Bitmap/BitmapManager.cs | 2 +- libs/server/Resp/RespCommandInfoParser.cs | 2 +- libs/server/Resp/RespCommandsInfo.cs | 2 +- libs/server/Servers/MetricsApi.cs | 4 +- libs/server/Servers/ServerOptions.cs | 4 +- .../Storage/Session/ObjectStore/HashOps.cs | 2 +- .../YCSB.benchmark/SpanByteYcsbBenchmark.cs | 6 +- .../cs/benchmark/YCSB.benchmark/TestLoader.cs | 2 +- .../cs/src/core/Index/Recovery/Checkpoint.cs | 4 +- .../Revivification/FreeRecordPool.cs | 4 +- .../Revivification/RevivificationSettings.cs | 8 +- .../cs/src/core/TsavoriteLog/TsavoriteLog.cs | 4 +- .../Utilities/SafeConcurrentDictionary.cs | 2 +- .../cs/src/core/Utilities/Utility.cs | 4 +- .../Tsavorite/cs/test/ExpirationTests.cs | 6 +- .../Tsavorite/cs/test/NUnitLoggerProvider.cs | 6 +- .../Tsavorite/cs/test/ReadAddressTests.cs | 6 +- .../ClusterStress/ShardedRespOnlineBench.cs | 18 +- .../CommandInfoUpdater/CommandInfoUpdater.cs | 4 +- .../CommandInfoUpdater/SupportedCommand.cs | 207 +++++++++--------- .../PerformanceTestLoggerProvider.cs | 6 +- .../GarnetClientSample/GarnetClientSamples.cs | 8 +- .../ClientClusterConfig.cs | 6 +- .../ClusterMigrateTests.cs | 69 +++--- .../Garnet.test.cluster/ClusterTestContext.cs | 4 +- test/Garnet.test.cluster/ClusterTestUtils.cs | 22 +- .../ClusterSlotVerificationTests.cs | 3 +- test/Garnet.test/HyperLogLogTests.cs | 2 +- test/Garnet.test/RespBlockingListTests.cs | 6 +- test/Garnet.test/RespCommandTests.cs | 10 +- test/Garnet.test/RespCustomCommandTests.cs | 10 +- test/Garnet.test/RespHashTests.cs | 10 +- test/Garnet.test/RespListGarnetClientTests.cs | 2 +- test/Garnet.test/RespListTests.cs | 72 +++--- test/Garnet.test/RespMetricsTest.cs | 2 +- test/Garnet.test/RespSetTest.cs | 10 +- test/Garnet.test/RespSortedSetGeoTests.cs | 20 +- test/Garnet.test/RespSortedSetTests.cs | 2 +- 60 files changed, 338 insertions(+), 335 deletions(-) diff --git a/.editorconfig b/.editorconfig index 26c45345de..9546b179c5 100644 --- a/.editorconfig +++ b/.editorconfig @@ -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. diff --git a/benchmark/Resp.benchmark/BenchmarkLoggerProvider.cs b/benchmark/Resp.benchmark/BenchmarkLoggerProvider.cs index 1e2c5a6870..06ad62bd4a 100644 --- a/benchmark/Resp.benchmark/BenchmarkLoggerProvider.cs +++ b/benchmark/Resp.benchmark/BenchmarkLoggerProvider.cs @@ -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) { diff --git a/benchmark/Resp.benchmark/RespPerfBench.cs b/benchmark/Resp.benchmark/RespPerfBench.cs index b8a91f2017..1fc6898907 100644 --- a/benchmark/Resp.benchmark/RespPerfBench.cs +++ b/benchmark/Resp.benchmark/RespPerfBench.cs @@ -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; diff --git a/benchmark/Resp.benchmark/TxnPerfBench.cs b/benchmark/Resp.benchmark/TxnPerfBench.cs index 2bca9507d0..9670f8a5b7 100644 --- a/benchmark/Resp.benchmark/TxnPerfBench.cs +++ b/benchmark/Resp.benchmark/TxnPerfBench.cs @@ -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()]); } diff --git a/libs/client/GarnetClientAPI/GarnetClientClusterCommands.cs b/libs/client/GarnetClientAPI/GarnetClientClusterCommands.cs index 4375d3a3bd..cefcf00660 100644 --- a/libs/client/GarnetClientAPI/GarnetClientClusterCommands.cs +++ b/libs/client/GarnetClientAPI/GarnetClientClusterCommands.cs @@ -26,7 +26,7 @@ public async Task Failover(FailoverOption failoverOption = default, Cancel { var args = failoverOption == default ? new Memory[] { FAILOVER } : - new Memory[] { FAILOVER, FailoverUtils.GetRespFormattedFailoverOption(failoverOption) }; + [FAILOVER, FailoverUtils.GetRespFormattedFailoverOption(failoverOption)]; return await ExecuteForStringResultWithCancellationAsync(CLUSTER, args, token: cancellationToken).ConfigureAwait(false) == "OK"; } } diff --git a/libs/client/GarnetClientAPI/GarnetClientListCommands.cs b/libs/client/GarnetClientAPI/GarnetClientListCommands.cs index 7dda4768df..d6bcc203de 100644 --- a/libs/client/GarnetClientAPI/GarnetClientListCommands.cs +++ b/libs/client/GarnetClientAPI/GarnetClientListCommands.cs @@ -24,7 +24,7 @@ public sealed partial class GarnetClient /// An optional context to correlate request to callback. public void ListLeftPush(string key, string element, Action callback, long context = 0) { - ListLeftPush(key, new[] { element }, callback, context); + ListLeftPush(key, [element], callback, context); } /// @@ -78,7 +78,7 @@ public async Task ListLeftPushAsync(string key, params string[] elements) /// An optional context to correlate request to callback. public void ListRightPush(string key, string element, Action callback, long context = 0) { - ListRightPush(key, new[] { element }, callback, context); + ListRightPush(key, [element], callback, context); } /// diff --git a/libs/client/GarnetClientMetrics.cs b/libs/client/GarnetClientMetrics.cs index e15d135ab7..c9bce32db3 100644 --- a/libs/client/GarnetClientMetrics.cs +++ b/libs/client/GarnetClientMetrics.cs @@ -29,7 +29,7 @@ private MetricsItem[] GetPercentiles(LongHistogram longHistogram, double scaling if (histogram == null || histogram.TotalCount == 0) { histogram?.Return(); - return Array.Empty(); + return []; } var _min = (histogram.GetValueAtPercentile(0) / scaling).ToString("N2", CultureInfo.InvariantCulture); @@ -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), @@ -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; diff --git a/libs/client/Utility.cs b/libs/client/Utility.cs index a8124b0315..858e4eacbd 100644 --- a/libs/client/Utility.cs +++ b/libs/client/Utility.cs @@ -22,7 +22,7 @@ public static class Utility /// The number 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) { @@ -83,7 +83,7 @@ public static long PreviousPowerOf2(long v) /// 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) diff --git a/libs/cluster/Server/ClusterManagerSlotState.cs b/libs/cluster/Server/ClusterManagerSlotState.cs index 9f389c9ade..44fee256c6 100644 --- a/libs/cluster/Server/ClusterManagerSlotState.cs +++ b/libs/cluster/Server/ClusterManagerSlotState.cs @@ -48,7 +48,7 @@ public bool TryAddSlots(HashSet slots, out int slotAssigned) break; } FlushConfig(); - logger?.LogTrace("AddSlots {slots}", GetRange(slots.ToArray())); + logger?.LogTrace("AddSlots {slots}", GetRange([.. slots])); return true; } @@ -78,7 +78,7 @@ public bool TryRemoveSlots(HashSet slots, out int notLocalSlot) break; } FlushConfig(); - logger?.LogTrace("RemoveSlots {slots}", GetRange(slots.ToArray())); + logger?.LogTrace("RemoveSlots {slots}", GetRange([.. slots])); return true; } @@ -210,7 +210,7 @@ public bool TryPrepareSlotsForMigration(HashSet 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; } @@ -327,7 +327,7 @@ public bool TryPrepareSlotsForImport(HashSet 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; } @@ -415,7 +415,7 @@ public bool TryPrepareSlotsForOwnershipChange(HashSet 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; } diff --git a/libs/cluster/Server/GarnetServerNode.cs b/libs/cluster/Server/GarnetServerNode.cs index fd6f269d08..d79a19b2a2 100644 --- a/libs/cluster/Server/GarnetServerNode.cs +++ b/libs/cluster/Server/GarnetServerNode.cs @@ -151,7 +151,7 @@ private byte[] GetMostRecentConfig() } else { - byteArray = Array.Empty(); + byteArray = []; } return byteArray; } diff --git a/libs/cluster/Server/Replication/PrimaryOps/ReplicaSyncSession.cs b/libs/cluster/Server/Replication/PrimaryOps/ReplicaSyncSession.cs index e623fd3319..fec830be7d 100644 --- a/libs/cluster/Server/Replication/PrimaryOps/ReplicaSyncSession.cs +++ b/libs/cluster/Server/Replication/PrimaryOps/ReplicaSyncSession.cs @@ -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()).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); @@ -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()).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); diff --git a/libs/cluster/Session/RespClusterBasicCommands.cs b/libs/cluster/Session/RespClusterBasicCommands.cs index 874b71538b..71aa228c89 100644 --- a/libs/cluster/Session/RespClusterBasicCommands.cs +++ b/libs/cluster/Session/RespClusterBasicCommands.cs @@ -420,7 +420,7 @@ private bool NetworkClusterGossip(int count, out bool invalidParameters) } else { - while (!RespWriteUtils.WriteBulkString(Array.Empty(), ref dcurr, dend)) + while (!RespWriteUtils.WriteBulkString([], ref dcurr, dend)) SendAndReset(); } diff --git a/libs/host/Configuration/GarnetCustomTransformers.cs b/libs/host/Configuration/GarnetCustomTransformers.cs index e4c8eb4712..da18448808 100644 --- a/libs/host/Configuration/GarnetCustomTransformers.cs +++ b/libs/host/Configuration/GarnetCustomTransformers.cs @@ -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; } } diff --git a/libs/host/Configuration/OptionsValidators.cs b/libs/host/Configuration/OptionsValidators.cs index 8c05ca7fc8..64cc09a9d2 100644 --- a/libs/host/Configuration/OptionsValidators.cs +++ b/libs/host/Configuration/OptionsValidators.cs @@ -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]); } /// @@ -76,7 +76,7 @@ protected bool TryInitialValidation(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; } @@ -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; @@ -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; @@ -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; @@ -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; @@ -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; @@ -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]); } } @@ -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]); } } @@ -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]); } } @@ -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"]) { } diff --git a/libs/host/ServerSettingsManager.cs b/libs/host/ServerSettingsManager.cs index 25747c7de7..f8622da084 100644 --- a/libs/host/ServerSettingsManager.cs +++ b/libs/host/ServerSettingsManager.cs @@ -42,7 +42,7 @@ internal static bool TryParseCommandLineArguments(string[] args, out Options opt options = null; invalidOptions = new List(); - if (args == null) args = Array.Empty(); + if (args == null) args = []; // Initialize command line parser var parser = new Parser(settings => @@ -357,7 +357,7 @@ private static string[] ConsolidateFlagArguments(string[] args) } } - return consolidatedArgs.ToArray(); + return [.. consolidatedArgs]; } } } \ No newline at end of file diff --git a/libs/server/ACL/User.cs b/libs/server/ACL/User.cs index 81d715fd78..cc722907ba 100644 --- a/libs/server/ACL/User.cs +++ b/libs/server/ACL/User.cs @@ -94,7 +94,7 @@ public void AddCategory(RespAclCategories category) } else { - commandInfos = Array.Empty(); + commandInfos = []; descUpdate = null; } @@ -216,7 +216,7 @@ public void RemoveCategory(RespAclCategories category) } else { - commandInfos = Array.Empty(); + commandInfos = []; descUpdate = null; } @@ -455,7 +455,7 @@ internal static IEnumerable DetermineCommandDetails(IReadOnlyList private static string RationalizeACLDescription(CommandPermissionSet set, string description) { - List parts = description.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList(); + List parts = [.. description.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)]; while (true) { bool shrunk = false; diff --git a/libs/server/Auth/Aad/IssuerSigningTokenProvider.cs b/libs/server/Auth/Aad/IssuerSigningTokenProvider.cs index 261d550e98..10aeec5f50 100644 --- a/libs/server/Auth/Aad/IssuerSigningTokenProvider.cs +++ b/libs/server/Auth/Aad/IssuerSigningTokenProvider.cs @@ -64,7 +64,7 @@ private static IReadOnlyCollection RetrieveSigningTokens(string aut var configManager = new ConfigurationManager(configUrl, new OpenIdConnectConfigurationRetriever(), new HttpDocumentRetriever()); var doc = configManager.GetConfigurationAsync().GetAwaiter().GetResult(); - return doc.SigningKeys.ToList(); + return [.. doc.SigningKeys]; } /// diff --git a/libs/server/Custom/CustomCommandRegistration.cs b/libs/server/Custom/CustomCommandRegistration.cs index 0923cb6eaf..4c91e66ab2 100644 --- a/libs/server/Custom/CustomCommandRegistration.cs +++ b/libs/server/Custom/CustomCommandRegistration.cs @@ -117,7 +117,7 @@ internal abstract class RegisterCustomCommandProviderBase : IRegisterCustomComma } } - return supportedTypes.ToArray(); + return [.. supportedTypes]; }); public abstract void Register(CustomCommandManager customCommandManager); diff --git a/libs/server/Metrics/Info/InfoCommand.cs b/libs/server/Metrics/Info/InfoCommand.cs index b0445a18c1..e00f71b163 100644 --- a/libs/server/Metrics/Info/InfoCommand.cs +++ b/libs/server/Metrics/Info/InfoCommand.cs @@ -69,7 +69,7 @@ private bool NetworkINFO(int count) } else { - InfoMetricsType[] sectionsArr = sections == null ? GarnetInfoMetrics.defaultInfo : sections.ToArray(); + InfoMetricsType[] sectionsArr = sections == null ? GarnetInfoMetrics.defaultInfo : [.. sections]; GarnetInfoMetrics garnetInfo = new(); string info = garnetInfo.GetRespInfo(sectionsArr, storeWrapper); while (!RespWriteUtils.WriteAsciiBulkString(info, ref dcurr, dend)) diff --git a/libs/server/Metrics/Latency/GarnetLatencyMetrics.cs b/libs/server/Metrics/Latency/GarnetLatencyMetrics.cs index 6021670a17..b37c531018 100644 --- a/libs/server/Metrics/Latency/GarnetLatencyMetrics.cs +++ b/libs/server/Metrics/Latency/GarnetLatencyMetrics.cs @@ -18,7 +18,7 @@ internal sealed class GarnetLatencyMetrics public static readonly LatencyMetricsType[] defaultLatencyTypes = Enum.GetValues(); // Whether each latency type in LatencyMetricsType enum is in ticks or is a directly reported value - static readonly bool[] defaultLatencyTypesTicks = new bool[6] { true, true, true, false, false, true }; + static readonly bool[] defaultLatencyTypesTicks = [true, true, true, false, false, true]; public LatencyMetricsEntry[] metrics; diff --git a/libs/server/Metrics/Latency/RespLatencyCommands.cs b/libs/server/Metrics/Latency/RespLatencyCommands.cs index ee763a423f..b29b13c24c 100644 --- a/libs/server/Metrics/Latency/RespLatencyCommands.cs +++ b/libs/server/Metrics/Latency/RespLatencyCommands.cs @@ -67,7 +67,7 @@ private bool NetworkLatencyHistogram(int count) } else { - events = GarnetLatencyMetrics.defaultLatencyTypes.ToHashSet(); + events = [.. GarnetLatencyMetrics.defaultLatencyTypes]; } if (invalid) @@ -116,7 +116,7 @@ private bool NetworkLatencyReset(int count) } else { - events = GarnetLatencyMetrics.defaultLatencyTypes.ToHashSet(); + events = [.. GarnetLatencyMetrics.defaultLatencyTypes]; } if (invalid) diff --git a/libs/server/Objects/ItemBroker/CollectionItemBroker.cs b/libs/server/Objects/ItemBroker/CollectionItemBroker.cs index 2224728e65..065438e97f 100644 --- a/libs/server/Objects/ItemBroker/CollectionItemBroker.cs +++ b/libs/server/Objects/ItemBroker/CollectionItemBroker.cs @@ -76,7 +76,7 @@ internal async Task MoveCollectionItemAsync(RespCommand co RespServerSession session, double timeoutInSeconds, ArgSlice[] cmdArgs) { var observer = new CollectionItemObserver(session, command, cmdArgs); - return await this.GetCollectionItemAsync(observer, new[] { srcKey }, timeoutInSeconds); + return await this.GetCollectionItemAsync(observer, [srcKey], timeoutInSeconds); } private async Task GetCollectionItemAsync(CollectionItemObserver observer, byte[][] keys, diff --git a/libs/server/Resp/Bitmap/BitmapManager.cs b/libs/server/Resp/Bitmap/BitmapManager.cs index 7c1f4e39ee..603d1c728d 100644 --- a/libs/server/Resp/Bitmap/BitmapManager.cs +++ b/libs/server/Resp/Bitmap/BitmapManager.cs @@ -13,7 +13,7 @@ namespace Garnet.server /// public unsafe partial class BitmapManager { - static readonly byte[] lookup = { 0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf }; + static readonly byte[] lookup = [0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf]; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Index(long offset) => (int)(offset >> 3); diff --git a/libs/server/Resp/RespCommandInfoParser.cs b/libs/server/Resp/RespCommandInfoParser.cs index 6c6534e133..b79b259819 100644 --- a/libs/server/Resp/RespCommandInfoParser.cs +++ b/libs/server/Resp/RespCommandInfoParser.cs @@ -109,7 +109,7 @@ public static unsafe bool TryReadFromResp(ref byte* ptr, byte* end, IReadOnlyDic AclCategories = aclCategories, Tips = tips.Length == 0 ? null : tips, KeySpecifications = keySpecifications.Length == 0 ? null : keySpecifications, - SubCommands = subCommands.Count == 0 ? null : subCommands.OrderBy(sc => sc.Name).ToArray() + SubCommands = subCommands.Count == 0 ? null : [.. subCommands.OrderBy(sc => sc.Name)] }; return true; diff --git a/libs/server/Resp/RespCommandsInfo.cs b/libs/server/Resp/RespCommandsInfo.cs index 6e7073923e..79fb311fe3 100644 --- a/libs/server/Resp/RespCommandsInfo.cs +++ b/libs/server/Resp/RespCommandsInfo.cs @@ -224,7 +224,7 @@ static void SetupSubCommands(RespCommandsInfo cmd) AclCommandInfo = new ReadOnlyDictionary>( AllRespCommandsInfo - .SelectMany(static kv => (kv.Value.SubCommands ?? Array.Empty()).Append(kv.Value)) + .SelectMany(static kv => (kv.Value.SubCommands ?? []).Append(kv.Value)) .SelectMany(static c => IndividualAcls(c.AclCategories).Select(a => (Acl: a, CommandInfo: c))) .GroupBy(static t => t.Acl) .ToDictionary( diff --git a/libs/server/Servers/MetricsApi.cs b/libs/server/Servers/MetricsApi.cs index 8683cb4d5f..6c65e29715 100644 --- a/libs/server/Servers/MetricsApi.cs +++ b/libs/server/Servers/MetricsApi.cs @@ -79,7 +79,7 @@ public void ResetInfoMetrics(InfoMetricsType[] infoMetricsTypes = null) /// public MetricsItem[] GetLatencyMetrics(LatencyMetricsType latencyMetricsType) { - if (provider.StoreWrapper.monitor?.GlobalMetrics.globalLatencyMetrics == null) return Array.Empty(); + if (provider.StoreWrapper.monitor?.GlobalMetrics.globalLatencyMetrics == null) return []; return provider.StoreWrapper.monitor.GlobalMetrics.globalLatencyMetrics.GetLatencyMetrics(latencyMetricsType); } @@ -90,7 +90,7 @@ public MetricsItem[] GetLatencyMetrics(LatencyMetricsType latencyMetricsType) /// public IEnumerable<(LatencyMetricsType, MetricsItem[])> GetLatencyMetrics(LatencyMetricsType[] latencyMetricsTypes = null) { - if (provider.StoreWrapper.monitor?.GlobalMetrics.globalLatencyMetrics == null) return Array.Empty<(LatencyMetricsType, MetricsItem[])>(); + if (provider.StoreWrapper.monitor?.GlobalMetrics.globalLatencyMetrics == null) return []; latencyMetricsTypes ??= GarnetLatencyMetrics.defaultLatencyTypes; return provider.StoreWrapper.monitor?.GlobalMetrics.globalLatencyMetrics.GetLatencyMetrics(latencyMetricsTypes); } diff --git a/libs/server/Servers/ServerOptions.cs b/libs/server/Servers/ServerOptions.cs index 6c117175b6..8de7ddaa8f 100644 --- a/libs/server/Servers/ServerOptions.cs +++ b/libs/server/Servers/ServerOptions.cs @@ -225,7 +225,7 @@ public void GetSettings() /// protected 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) { @@ -255,7 +255,7 @@ protected static long ParseSize(string value) /// protected 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) diff --git a/libs/server/Storage/Session/ObjectStore/HashOps.cs b/libs/server/Storage/Session/ObjectStore/HashOps.cs index fa051e9af9..6e8eb4340c 100644 --- a/libs/server/Storage/Session/ObjectStore/HashOps.cs +++ b/libs/server/Storage/Session/ObjectStore/HashOps.cs @@ -118,7 +118,7 @@ public unsafe GarnetStatus HashSet(ArgSlice key, (ArgSlice field /// public GarnetStatus HashDelete(ArgSlice key, ArgSlice field, out int itemsDoneCount, ref TObjectContext objectStoreContext, bool nx = false) where TObjectContext : ITsavoriteContext - => HashDelete(key, new ArgSlice[] { field }, out itemsDoneCount, ref objectStoreContext); + => HashDelete(key, [field], out itemsDoneCount, ref objectStoreContext); /// /// Removes the specified fields from the hash key. diff --git a/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/SpanByteYcsbBenchmark.cs b/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/SpanByteYcsbBenchmark.cs index 1064a611c7..e19235e10c 100644 --- a/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/SpanByteYcsbBenchmark.cs +++ b/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/SpanByteYcsbBenchmark.cs @@ -69,15 +69,15 @@ internal SpanByteYcsbBenchmark(KeySpanByte[] i_keys_, KeySpanByte[] t_keys_, Tes RevivificationLevel.Chain => new RevivificationSettings(), RevivificationLevel.Full => new RevivificationSettings() { - FreeRecordBins = new[] - { + FreeRecordBins = + [ new RevivificationBin() { RecordSize = RecordInfo.GetLength() + kKeySize + kValueSize + 8, // extra to ensure rounding up of value NumberOfRecords = testLoader.Options.RevivBinRecordCount, BestFitScanLimit = RevivificationBin.UseFirstFit } - }, + ], }, _ => throw new ApplicationException("Invalid RevivificationLevel") }; diff --git a/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/TestLoader.cs b/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/TestLoader.cs index 166c338d02..1b7da927d8 100644 --- a/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/TestLoader.cs +++ b/libs/storage/Tsavorite/cs/benchmark/YCSB.benchmark/TestLoader.cs @@ -194,7 +194,7 @@ private unsafe void LoadDataFromFile(string filePath, string d // Uniform txn at current small-data counts has about a 1% hit rate in the init array, too low to fill the small-txn count, // so convert the init_key set to an array for random indexing get a random key from init_keys. - initKeyArray ??= initKeySet.ToArray(); + initKeyArray ??= [.. initKeySet]; key = initKeyArray[rng.Generate((uint)initKeySet.Count)]; } else diff --git a/libs/storage/Tsavorite/cs/src/core/Index/Recovery/Checkpoint.cs b/libs/storage/Tsavorite/cs/src/core/Index/Recovery/Checkpoint.cs index c93178126b..4f9b42d6c7 100644 --- a/libs/storage/Tsavorite/cs/src/core/Index/Recovery/Checkpoint.cs +++ b/libs/storage/Tsavorite/cs/src/core/Index/Recovery/Checkpoint.cs @@ -52,7 +52,7 @@ internal void WriteHybridLogMetaInfo() if (CommitCookie != null && CommitCookie.Length != 0) { var convertedCookie = Convert.ToBase64String(CommitCookie); - metadata = metadata.Concat(Encoding.Default.GetBytes(convertedCookie)).ToArray(); + metadata = [.. metadata, .. Encoding.Default.GetBytes(convertedCookie)]; } checkpointManager.CommitLogCheckpoint(_hybridLogCheckpointToken, metadata); Log.ShiftBeginAddress(_hybridLogCheckpoint.info.beginAddress, truncateLog: true); @@ -64,7 +64,7 @@ internal void WriteHybridLogIncrementalMetaInfo(DeltaLog deltaLog) if (CommitCookie != null && CommitCookie.Length != 0) { var convertedCookie = Convert.ToBase64String(CommitCookie); - metadata = metadata.Concat(Encoding.Default.GetBytes(convertedCookie)).ToArray(); + metadata = [.. metadata, .. Encoding.Default.GetBytes(convertedCookie)]; } checkpointManager.CommitLogIncrementalCheckpoint(_hybridLogCheckpointToken, _hybridLogCheckpoint.info.version, metadata, deltaLog); Log.ShiftBeginAddress(_hybridLogCheckpoint.info.beginAddress, truncateLog: true); diff --git a/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/FreeRecordPool.cs b/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/FreeRecordPool.cs index 3b6be29e63..92cea4dacf 100644 --- a/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/FreeRecordPool.cs +++ b/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/FreeRecordPool.cs @@ -467,7 +467,7 @@ internal FreeRecordPool(TsavoriteKV s if (IsFixedLength) { numBins = 1; - bins = new[] { new FreeRecordBin(ref settings.FreeRecordBins[0], fixedRecordLength, isFixedLength: true) }; + bins = [new FreeRecordBin(ref settings.FreeRecordBins[0], fixedRecordLength, isFixedLength: true)]; return; } @@ -495,7 +495,7 @@ internal FreeRecordPool(TsavoriteKV s binList.Add(bin); prevBinRecordSize = bin.maxRecordSize; } - bins = binList.ToArray(); + bins = [.. binList]; numBins = bins.Length; numberOfBinsToSearch = settings.NumberOfBinsToSearch; } diff --git a/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/RevivificationSettings.cs b/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/RevivificationSettings.cs index 1164490f6f..632036026b 100644 --- a/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/RevivificationSettings.cs +++ b/libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/Revivification/RevivificationSettings.cs @@ -78,14 +78,14 @@ public class RevivificationSettings /// public static RevivificationSettings DefaultFixedLength { get; } = new() { - FreeRecordBins = new[] - { + FreeRecordBins = + [ new RevivificationBin() { RecordSize = RevivificationBin.MaxRecordSize, BestFitScanLimit = RevivificationBin.UseFirstFit } - } + ] }; /// @@ -262,7 +262,7 @@ public PowerOf2BinsRevivificationSettings() : base() RecordSize = RevivificationBin.MaxRecordSize, NumberOfRecords = RevivificationBin.DefaultRecordsPerBin }); - FreeRecordBins = binList.ToArray(); + FreeRecordBins = [.. binList]; } } } \ No newline at end of file diff --git a/libs/storage/Tsavorite/cs/src/core/TsavoriteLog/TsavoriteLog.cs b/libs/storage/Tsavorite/cs/src/core/TsavoriteLog/TsavoriteLog.cs index 85ffe0ef52..e0f5419a35 100644 --- a/libs/storage/Tsavorite/cs/src/core/TsavoriteLog/TsavoriteLog.cs +++ b/libs/storage/Tsavorite/cs/src/core/TsavoriteLog/TsavoriteLog.cs @@ -334,7 +334,7 @@ public void CompleteLog(bool spinWait = false) // Ensure all currently started entries will enqueue before we declare log closed epoch.BumpCurrentEpoch(() => { - CommitInternal(out _, out _, false, Array.Empty(), long.MaxValue, null); + CommitInternal(out _, out _, false, [], long.MaxValue, null); }); } finally @@ -2536,7 +2536,7 @@ private Dictionary CompleteRestoreFromCommit(TsavoriteLogRecoveryI var recoveredIterators = info.Iterators; if (recoveredIterators != null) { - List keys = recoveredIterators.Keys.ToList(); + List keys = [.. recoveredIterators.Keys]; foreach (var key in keys) if (recoveredIterators[key] > SafeTailAddress) recoveredIterators[key] = SafeTailAddress; diff --git a/libs/storage/Tsavorite/cs/src/core/Utilities/SafeConcurrentDictionary.cs b/libs/storage/Tsavorite/cs/src/core/Utilities/SafeConcurrentDictionary.cs index 9c0b66f416..28674c6337 100644 --- a/libs/storage/Tsavorite/cs/src/core/Utilities/SafeConcurrentDictionary.cs +++ b/libs/storage/Tsavorite/cs/src/core/Utilities/SafeConcurrentDictionary.cs @@ -191,7 +191,7 @@ IEnumerator IEnumerable.GetEnumerator() [MethodImpl(MethodImplOptions.AggressiveInlining)] public KeyValuePair[] ToArray() { - return dictionary.ToArray(); + return [.. dictionary]; } /// diff --git a/libs/storage/Tsavorite/cs/src/core/Utilities/Utility.cs b/libs/storage/Tsavorite/cs/src/core/Utilities/Utility.cs index 6950f989f0..a639355487 100644 --- a/libs/storage/Tsavorite/cs/src/core/Utilities/Utility.cs +++ b/libs/storage/Tsavorite/cs/src/core/Utilities/Utility.cs @@ -35,7 +35,7 @@ public static class Utility /// The number 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) { @@ -95,7 +95,7 @@ internal static long PreviousPowerOf2(long v) /// 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) diff --git a/libs/storage/Tsavorite/cs/test/ExpirationTests.cs b/libs/storage/Tsavorite/cs/test/ExpirationTests.cs index 1592f66297..8c39585fd4 100644 --- a/libs/storage/Tsavorite/cs/test/ExpirationTests.cs +++ b/libs/storage/Tsavorite/cs/test/ExpirationTests.cs @@ -574,8 +574,7 @@ private unsafe void Populate(Random rng) private unsafe ExpirationOutput GetRecord(int key, Status expectedStatus, FlushMode flushMode) { - Span keySpan = stackalloc int[1]; - keySpan[0] = key; + Span keySpan = [key]; var keySpanByte = keySpan.AsSpanByte(); ExpirationOutput output = new(); @@ -593,8 +592,7 @@ private unsafe ExpirationOutput GetRecord(int key, Status expectedStatus, FlushM private unsafe ExpirationOutput ExecuteRMW(int key, ref ExpirationInput input, FlushMode flushMode, Status expectedStatus = default) { - Span keySpan = stackalloc int[1]; - keySpan[0] = key; + Span keySpan = [key]; var keySpanByte = keySpan.AsSpanByte(); ExpirationOutput output = new(); diff --git a/libs/storage/Tsavorite/cs/test/NUnitLoggerProvider.cs b/libs/storage/Tsavorite/cs/test/NUnitLoggerProvider.cs index 844565f128..25ed009217 100644 --- a/libs/storage/Tsavorite/cs/test/NUnitLoggerProvider.cs +++ b/libs/storage/Tsavorite/cs/test/NUnitLoggerProvider.cs @@ -13,15 +13,15 @@ public class NUnitLoggerProvider : ILoggerProvider private readonly TextWriter textWriter; private readonly string scope; - static readonly string[] lvl = new string[] - { + static readonly string[] lvl = + [ "trce", "dbug", "info", "warn", "errr", "crit", - }; + ]; public NUnitLoggerProvider(TextWriter textWriter, string scope = "") { diff --git a/libs/storage/Tsavorite/cs/test/ReadAddressTests.cs b/libs/storage/Tsavorite/cs/test/ReadAddressTests.cs index 8917c797c3..919a10be5e 100644 --- a/libs/storage/Tsavorite/cs/test/ReadAddressTests.cs +++ b/libs/storage/Tsavorite/cs/test/ReadAddressTests.cs @@ -516,8 +516,8 @@ internal struct ReadCopyOptionsMerge [Category("TsavoriteKV"), Category("Read")] public void ReadCopyOptionssMergeTest() { - ReadCopyOptionsMerge[] merges = new ReadCopyOptionsMerge[] - { + ReadCopyOptionsMerge[] merges = + [ new() { store = ReadCopyOptions.None, @@ -567,7 +567,7 @@ public void ReadCopyOptionssMergeTest() Read = new(ReadCopyFrom.AllImmutable, ReadCopyTo.ReadCache), Expected = new(ReadCopyFrom.AllImmutable, ReadCopyTo.ReadCache) }, - }; + ]; for (var ii = 0; ii < merges.Length; ++ii) { diff --git a/playground/ClusterStress/ShardedRespOnlineBench.cs b/playground/ClusterStress/ShardedRespOnlineBench.cs index ebcbd6b9ae..ba553ee9b8 100644 --- a/playground/ClusterStress/ShardedRespOnlineBench.cs +++ b/playground/ClusterStress/ShardedRespOnlineBench.cs @@ -179,8 +179,8 @@ private ClusterConfiguration GetClusterConfig() private void UpdateSlotMap(ClusterConfiguration clusterConfig) { var nodes = clusterConfig.Nodes.ToArray(); - primaryNodes = nodes.ToList().FindAll(p => !p.IsReplica).ToArray(); - replicaNodes = nodes.ToList().FindAll(p => p.IsReplica).ToArray(); + primaryNodes = [.. nodes.ToList().FindAll(p => !p.IsReplica)]; + replicaNodes = [.. nodes.ToList().FindAll(p => p.IsReplica)]; ushort j = 0; foreach (var node in nodes) { @@ -412,7 +412,7 @@ public void Run() Console.WriteLine($"Running benchmark using {opts.Client} client type"); // Initialize clients to nodes using the retrieved configuration - InitClients(clusterConfig.Nodes.ToArray()); + InitClients([.. clusterConfig.Nodes]); Thread[] workers = InitializeThreadWorkers(); // Start threads. @@ -641,13 +641,13 @@ public async void OpRunnerGarnetClientSession(int thread_id) switch (op) { case OpType.GET: - await _gcs[clientIdx].ExecuteAsync(new string[] { "GET", reqKey }); + await _gcs[clientIdx].ExecuteAsync(["GET", reqKey]); break; case OpType.SET: - await _gcs[clientIdx].ExecuteAsync(new string[] { "SET", reqKey, valueData }); + await _gcs[clientIdx].ExecuteAsync(["SET", reqKey, valueData]); break; case OpType.DEL: - await _gcs[clientIdx].ExecuteAsync(new string[] { "DEL", reqKey }); + await _gcs[clientIdx].ExecuteAsync(["DEL", reqKey]); break; default: throw new Exception($"opType: {op} benchmark not supported with {opts.Client} ClientType!"); @@ -690,13 +690,13 @@ public void OpRunnerGarnetClientSessionParallel(int thread_id, int parallel) switch (op) { case OpType.GET: - _gcs[clientIdx].ExecuteBatch(new string[] { "GET", reqKey }); + _gcs[clientIdx].ExecuteBatch(["GET", reqKey]); break; case OpType.SET: - _gcs[clientIdx].ExecuteBatch(new string[] { "SET", reqKey, valueData }); + _gcs[clientIdx].ExecuteBatch(["SET", reqKey, valueData]); break; case OpType.DEL: - _gcs[clientIdx].ExecuteBatch(new string[] { "DEL", reqKey }); + _gcs[clientIdx].ExecuteBatch(["DEL", reqKey]); break; default: throw new Exception($"opType: {op} benchmark not supported with {opts.Client} ClientType!"); diff --git a/playground/CommandInfoUpdater/CommandInfoUpdater.cs b/playground/CommandInfoUpdater/CommandInfoUpdater.cs index 3f43720f59..b4900f4cd6 100644 --- a/playground/CommandInfoUpdater/CommandInfoUpdater.cs +++ b/playground/CommandInfoUpdater/CommandInfoUpdater.cs @@ -166,7 +166,7 @@ private static (IDictionary, IDictionary GetUpdatedCommandsI { updatedSubCommands = existingCommandsInfo[command.Command].SubCommands == null ? new List() - : existingCommandsInfo[command.Command].SubCommands.ToList(); + : [.. existingCommandsInfo[command.Command].SubCommands]; // Add sub-commands with updated queried command info foreach (var subCommandToAdd in command.SubCommands!) diff --git a/playground/CommandInfoUpdater/SupportedCommand.cs b/playground/CommandInfoUpdater/SupportedCommand.cs index 3357e192a1..fb99e7220a 100644 --- a/playground/CommandInfoUpdater/SupportedCommand.cs +++ b/playground/CommandInfoUpdater/SupportedCommand.cs @@ -10,9 +10,9 @@ namespace CommandInfoUpdater /// public class SupportedCommand { - private static readonly SupportedCommand[] AllSupportedCommands = { - new("ACL", RespCommand.ACL, new[] - { + private static readonly SupportedCommand[] AllSupportedCommands = [ + new("ACL", RespCommand.ACL, + [ "ACL|CAT", "ACL|DELUSER", "ACL|LIST", @@ -21,7 +21,7 @@ public class SupportedCommand "ACL|SETUSER", "ACL|USERS", "ACL|WHOAMI", - }), + ]), new("APPEND", RespCommand.APPEND), new("ASKING", RespCommand.ASKING), new("ASYNC", RespCommand.ASYNC), @@ -36,8 +36,8 @@ public class SupportedCommand new("BRPOP", RespCommand.BRPOP), new("BLMOVE", RespCommand.BLMOVE), new("CLIENT", RespCommand.CLIENT), - new("CLUSTER", RespCommand.CLUSTER, new [] - { + new("CLUSTER", RespCommand.CLUSTER, + [ "CLUSTER|ADDSLOTS", "CLUSTER|ADDSLOTSRANGE", "CLUSTER|AOFSYNC", @@ -78,20 +78,19 @@ public class SupportedCommand "CLUSTER|SHARDS", "CLUSTER|SLOTS", "CLUSTER|SLOTSTATE", - - }), - new("COMMAND", RespCommand.COMMAND, new [] - { + ]), + new("COMMAND", RespCommand.COMMAND, + [ "COMMAND|INFO", "COMMAND|COUNT", - }), + ]), new("COMMITAOF", RespCommand.COMMITAOF), - new("CONFIG", RespCommand.CONFIG, new [] - { + new("CONFIG", RespCommand.CONFIG, + [ "CONFIG|GET", "CONFIG|SET", "CONFIG|REWRITE" - }), + ]), new("COSCAN", RespCommand.COSCAN), new("CustomRawStringCmd", RespCommand.CustomRawStringCmd), new("CustomObjCmd", RespCommand.CustomObjCmd), @@ -141,12 +140,12 @@ public class SupportedCommand new("INFO", RespCommand.INFO), new("KEYS", RespCommand.KEYS), new("LASTSAVE", RespCommand.LASTSAVE), - new("LATENCY", RespCommand.LATENCY, new [] - { + new("LATENCY", RespCommand.LATENCY, + [ "LATENCY|HELP", "LATENCY|HISTOGRAM", "LATENCY|RESET" - }), + ]), new("LINDEX", RespCommand.LINDEX), new("LINSERT", RespCommand.LINSERT), new("LLEN", RespCommand.LLEN), @@ -159,102 +158,102 @@ public class SupportedCommand new("LREM", RespCommand.LREM), new("LSET", RespCommand.LSET), new("LTRIM", RespCommand.LTRIM), - new("MEMORY", RespCommand.MEMORY, new [] - { + new("MEMORY", RespCommand.MEMORY, + [ "MEMORY|USAGE" - }), + ]), new("MGET", RespCommand.MGET), new("MIGRATE", RespCommand.MIGRATE), new("MODULE", RespCommand.MODULE, [ "MODULE|LOADCS", ]), - new ("MONITOR", RespCommand.MONITOR), - new ("MSET", RespCommand.MSET), - new ("MSETNX", RespCommand.MSETNX), - new ("MULTI", RespCommand.MULTI), - new ("PERSIST", RespCommand.PERSIST), - new ("PEXPIRE", RespCommand.PEXPIRE), - new ("PFADD", RespCommand.PFADD), - new ("PFCOUNT", RespCommand.PFCOUNT), - new ("PFMERGE", RespCommand.PFMERGE), - new ("PING", RespCommand.PING), - new ("PSETEX", RespCommand.PSETEX), - new ("PSUBSCRIBE", RespCommand.PSUBSCRIBE), - new ("PTTL", RespCommand.PTTL), - new ("PUBLISH", RespCommand.PUBLISH), - new ("PUNSUBSCRIBE", RespCommand.PUNSUBSCRIBE), - new ("REGISTERCS", RespCommand.REGISTERCS), - new ("QUIT", RespCommand.QUIT), - new ("READONLY", RespCommand.READONLY), - new ("READWRITE", RespCommand.READWRITE), - new ("RENAME", RespCommand.RENAME), - new ("REPLICAOF", RespCommand.REPLICAOF), - new ("RPOP", RespCommand.RPOP), - new ("RPOPLPUSH", RespCommand.RPOPLPUSH), - new ("RPUSH", RespCommand.RPUSH), - new ("RPUSHX", RespCommand.RPUSHX), - new ("RUNTXP", RespCommand.RUNTXP), - new ("SADD", RespCommand.SADD), - new ("SCARD", RespCommand.SCARD), - new ("SAVE", RespCommand.SAVE), - new ("SCAN", RespCommand.SCAN), - new ("SDIFF", RespCommand.SDIFF), - new ("SDIFFSTORE", RespCommand.SDIFFSTORE), - new ("SECONDARYOF", RespCommand.SECONDARYOF), - new ("SELECT", RespCommand.SELECT), - new ("SET", RespCommand.SET), - new ("SETBIT", RespCommand.SETBIT), - new ("SETEX", RespCommand.SETEX), - new ("SETRANGE", RespCommand.SETRANGE), - new ("SISMEMBER", RespCommand.SISMEMBER), - new ("SLAVEOF", RespCommand.SECONDARYOF), - new ("SMEMBERS", RespCommand.SMEMBERS), - new ("SMOVE", RespCommand.SMOVE), - new ("SPOP", RespCommand.SPOP), - new ("SRANDMEMBER", RespCommand.SRANDMEMBER), - new ("SREM", RespCommand.SREM), - new ("SSCAN", RespCommand.SSCAN), - new ("STRLEN", RespCommand.STRLEN), - new ("SUBSCRIBE", RespCommand.SUBSCRIBE), - new ("SUNION", RespCommand.SUNION), - new ("SUNIONSTORE", RespCommand.SUNIONSTORE), - new ("SINTER", RespCommand.SINTER), - new ("SINTERSTORE", RespCommand.SINTERSTORE), - new ("TIME", RespCommand.TIME), - new ("TTL", RespCommand.TTL), - new ("TYPE", RespCommand.TYPE), - new ("UNLINK", RespCommand.UNLINK), - new ("UNSUBSCRIBE", RespCommand.UNSUBSCRIBE), - new ("UNWATCH", RespCommand.UNWATCH), - new ("WATCH", RespCommand.WATCH, new [] - { + new("MONITOR", RespCommand.MONITOR), + new("MSET", RespCommand.MSET), + new("MSETNX", RespCommand.MSETNX), + new("MULTI", RespCommand.MULTI), + new("PERSIST", RespCommand.PERSIST), + new("PEXPIRE", RespCommand.PEXPIRE), + new("PFADD", RespCommand.PFADD), + new("PFCOUNT", RespCommand.PFCOUNT), + new("PFMERGE", RespCommand.PFMERGE), + new("PING", RespCommand.PING), + new("PSETEX", RespCommand.PSETEX), + new("PSUBSCRIBE", RespCommand.PSUBSCRIBE), + new("PTTL", RespCommand.PTTL), + new("PUBLISH", RespCommand.PUBLISH), + new("PUNSUBSCRIBE", RespCommand.PUNSUBSCRIBE), + new("REGISTERCS", RespCommand.REGISTERCS), + new("QUIT", RespCommand.QUIT), + new("READONLY", RespCommand.READONLY), + new("READWRITE", RespCommand.READWRITE), + new("RENAME", RespCommand.RENAME), + new("REPLICAOF", RespCommand.REPLICAOF), + new("RPOP", RespCommand.RPOP), + new("RPOPLPUSH", RespCommand.RPOPLPUSH), + new("RPUSH", RespCommand.RPUSH), + new("RPUSHX", RespCommand.RPUSHX), + new("RUNTXP", RespCommand.RUNTXP), + new("SADD", RespCommand.SADD), + new("SCARD", RespCommand.SCARD), + new("SAVE", RespCommand.SAVE), + new("SCAN", RespCommand.SCAN), + new("SDIFF", RespCommand.SDIFF), + new("SDIFFSTORE", RespCommand.SDIFFSTORE), + new("SECONDARYOF", RespCommand.SECONDARYOF), + new("SELECT", RespCommand.SELECT), + new("SET", RespCommand.SET), + new("SETBIT", RespCommand.SETBIT), + new("SETEX", RespCommand.SETEX), + new("SETRANGE", RespCommand.SETRANGE), + new("SISMEMBER", RespCommand.SISMEMBER), + new("SLAVEOF", RespCommand.SECONDARYOF), + new("SMEMBERS", RespCommand.SMEMBERS), + new("SMOVE", RespCommand.SMOVE), + new("SPOP", RespCommand.SPOP), + new("SRANDMEMBER", RespCommand.SRANDMEMBER), + new("SREM", RespCommand.SREM), + new("SSCAN", RespCommand.SSCAN), + new("STRLEN", RespCommand.STRLEN), + new("SUBSCRIBE", RespCommand.SUBSCRIBE), + new("SUNION", RespCommand.SUNION), + new("SUNIONSTORE", RespCommand.SUNIONSTORE), + new("SINTER", RespCommand.SINTER), + new("SINTERSTORE", RespCommand.SINTERSTORE), + new("TIME", RespCommand.TIME), + new("TTL", RespCommand.TTL), + new("TYPE", RespCommand.TYPE), + new("UNLINK", RespCommand.UNLINK), + new("UNSUBSCRIBE", RespCommand.UNSUBSCRIBE), + new("UNWATCH", RespCommand.UNWATCH), + new("WATCH", RespCommand.WATCH, + [ "WATCH|MS", "WATCH|OS", - }), - new ("ZADD", RespCommand.ZADD), - new ("ZCARD", RespCommand.ZCARD), - new ("ZCOUNT", RespCommand.ZCOUNT), - new ("ZDIFF", RespCommand.ZDIFF), - new ("ZINCRBY", RespCommand.ZINCRBY), - new ("ZLEXCOUNT", RespCommand.ZLEXCOUNT), - new ("ZMSCORE", RespCommand.ZMSCORE), - new ("ZPOPMAX", RespCommand.ZPOPMAX), - new ("ZPOPMIN", RespCommand.ZPOPMIN), - new ("ZRANDMEMBER", RespCommand.ZRANDMEMBER), - new ("ZRANGE", RespCommand.ZRANGE), - new ("ZRANGEBYSCORE", RespCommand.ZRANGEBYSCORE), - new ("ZRANK", RespCommand.ZRANK), - new ("ZREM", RespCommand.ZREM), - new ("ZREMRANGEBYLEX", RespCommand.ZREMRANGEBYLEX), - new ("ZREMRANGEBYRANK", RespCommand.ZREMRANGEBYRANK), - new ("ZREMRANGEBYSCORE", RespCommand.ZREMRANGEBYSCORE), - new ("ZREVRANGE", RespCommand.ZREVRANGE), - new ("ZREVRANGEBYSCORE", RespCommand.ZREVRANGEBYSCORE), - new ("ZREVRANK", RespCommand.ZREVRANK), - new ("ZSCAN", RespCommand.ZSCAN), - new ("ZSCORE", RespCommand.ZSCORE), - }; + ]), + new("ZADD", RespCommand.ZADD), + new("ZCARD", RespCommand.ZCARD), + new("ZCOUNT", RespCommand.ZCOUNT), + new("ZDIFF", RespCommand.ZDIFF), + new("ZINCRBY", RespCommand.ZINCRBY), + new("ZLEXCOUNT", RespCommand.ZLEXCOUNT), + new("ZMSCORE", RespCommand.ZMSCORE), + new("ZPOPMAX", RespCommand.ZPOPMAX), + new("ZPOPMIN", RespCommand.ZPOPMIN), + new("ZRANDMEMBER", RespCommand.ZRANDMEMBER), + new("ZRANGE", RespCommand.ZRANGE), + new("ZRANGEBYSCORE", RespCommand.ZRANGEBYSCORE), + new("ZRANK", RespCommand.ZRANK), + new("ZREM", RespCommand.ZREM), + new("ZREMRANGEBYLEX", RespCommand.ZREMRANGEBYLEX), + new("ZREMRANGEBYRANK", RespCommand.ZREMRANGEBYRANK), + new("ZREMRANGEBYSCORE", RespCommand.ZREMRANGEBYSCORE), + new("ZREVRANGE", RespCommand.ZREVRANGE), + new("ZREVRANGEBYSCORE", RespCommand.ZREVRANGEBYSCORE), + new("ZREVRANK", RespCommand.ZREVRANK), + new("ZSCAN", RespCommand.ZSCAN), + new("ZSCORE", RespCommand.ZSCORE), + ]; private static readonly Lazy> LazySupportedCommandsMap = new(() => diff --git a/playground/Embedded.perftest/PerformanceTestLoggerProvider.cs b/playground/Embedded.perftest/PerformanceTestLoggerProvider.cs index cdce812e9f..47351c0e69 100644 --- a/playground/Embedded.perftest/PerformanceTestLoggerProvider.cs +++ b/playground/Embedded.perftest/PerformanceTestLoggerProvider.cs @@ -16,15 +16,15 @@ public class PerformanceTestLoggerProvider : ILoggerProvider { private readonly TextWriter textWriter; - static readonly string[] lvl = new string[] - { + static readonly string[] lvl = + [ "trce", "dbug", "info", "warn", "errr", "crit", - }; + ]; public PerformanceTestLoggerProvider(TextWriter textWriter) { diff --git a/samples/GarnetClientSample/GarnetClientSamples.cs b/samples/GarnetClientSample/GarnetClientSamples.cs index 1c911fc565..19882557cb 100644 --- a/samples/GarnetClientSample/GarnetClientSamples.cs +++ b/samples/GarnetClientSample/GarnetClientSamples.cs @@ -120,7 +120,7 @@ async Task IncrByAsync(long nIncr) if (s != $"{nVal}") throw new Exception("IncrementByAsync: Error"); - long n = int.Parse(await db.ExecuteForStringResultAsync("INCRBY", new string[] { strKey, nIncr.ToString() })); + long n = int.Parse(await db.ExecuteForStringResultAsync("INCRBY", [strKey, nIncr.ToString()])); if (n != nVal + nIncr) throw new Exception("IncrementByAsync: Error"); @@ -145,7 +145,7 @@ async Task DecrByAsync(long nDecr) if (s != $"{nVal}") throw new Exception("DecrByAsync: Error"); - long n = int.Parse(await db.ExecuteForStringResultAsync("DECRBY", new string[] { strKey, nDecr.ToString() })); + long n = int.Parse(await db.ExecuteForStringResultAsync("DECRBY", [strKey, nDecr.ToString()])); if (n != nVal - nDecr) throw new Exception("DecrByAsync: Error"); @@ -206,7 +206,7 @@ async Task ExistsAsync() var strKey = "key1"; await db.StringSetAsync(strKey, $"{nVal}"); - bool fExists = int.Parse(await db.ExecuteForStringResultAsync("EXISTS", new string[] { strKey })) == 1 ? true : false; + bool fExists = int.Parse(await db.ExecuteForStringResultAsync("EXISTS", [strKey])) == 1 ? true : false; if (!fExists) throw new Exception("ExistsAsync: Error"); Console.WriteLine("ExistsAsync: Success"); @@ -223,7 +223,7 @@ async Task DeleteAsync() await db.StringSetAsync(strKey, $"{nVal}"); await db.KeyDeleteAsync(strKey); - bool fExists = int.Parse(await db.ExecuteForStringResultAsync("EXISTS", new string[] { strKey })) == 1 ? true : false; + bool fExists = int.Parse(await db.ExecuteForStringResultAsync("EXISTS", [strKey])) == 1 ? true : false; if (fExists) throw new Exception("DeleteAsync: Error"); Console.WriteLine("DeleteAsync: Success"); diff --git a/test/Garnet.test.cluster/ClientClusterConfig.cs b/test/Garnet.test.cluster/ClientClusterConfig.cs index b262a5a7bb..09b4800d1c 100644 --- a/test/Garnet.test.cluster/ClientClusterConfig.cs +++ b/test/Garnet.test.cluster/ClientClusterConfig.cs @@ -51,7 +51,7 @@ public ClientClusterNode(string raw) (slots ??= new List(parts.Length - i)).Add(range); } } - Slots = slots?.AsReadOnly() ?? (IList)Array.Empty(); + Slots = slots?.AsReadOnly() ?? (IList)[]; IsConnected = parts[7] == "connected"; // Can be "connected" or "disconnected" } @@ -188,7 +188,7 @@ public void AddWorker( config.Add((workers[i].Nodeid, GetNodeInfo(workerId: i))); } - config = config.OrderBy(x => x.Item1).ToList(); + config = [.. config.OrderBy(x => x.Item1)]; return config; } @@ -293,7 +293,7 @@ public bool EqualsConfig(string config, bool replicasAssigned = false) var nodeId = properties[0].Trim(); _orderedConfig.Add((nodeId, properties)); } - _orderedConfig = _orderedConfig.OrderBy(x => x.Item1).ToList(); + _orderedConfig = [.. _orderedConfig.OrderBy(x => x.Item1)]; if (_orderedConfig.Count != orderedConfig.Count) return false; diff --git a/test/Garnet.test.cluster/ClusterMigrateTests.cs b/test/Garnet.test.cluster/ClusterMigrateTests.cs index 227ed70733..eaf71d66bc 100644 --- a/test/Garnet.test.cluster/ClusterMigrateTests.cs +++ b/test/Garnet.test.cluster/ClusterMigrateTests.cs @@ -21,40 +21,31 @@ public unsafe class ClusterMigrateTests(bool UseTLS) { public (Action, string)[] GetUnitTests() { - (Action, string)[] x = new (Action, string)[11]; - //1 - x[0] = new(ClusterSimpleInitialize, "ClusterSimpleInitialize()"); - - //2 - x[1] = new(ClusterSimpleSlotInfo, "ClusterSimpleSlotInfo()"); - - //3 - x[2] = new(ClusterAddDelSlots, "ClusterAddDelSlots()"); - - //4 - x[3] = new(ClusterSlotChangeStatus, "ClusterSlotChangeStatus()"); - - //5 - x[4] = new(ClusterRedirectMessage, "ClusterRedirectMessage()"); - - //6 - x[5] = new(ClusterSimpleMigrateSlots, "ClusterSimpleMigrateSlots()"); - - //7 - x[6] = new(ClusterSimpleMigrateSlotsExpiry, "ClusterSimpleMigrateSlotsExpiry()"); - - //8 - x[7] = new(ClusterSimpleMigrateSlotsWithObjects, "ClusterSimpleMigrateSlotsWithObjects()"); - - //9 - x[8] = new(ClusterSimpleMigrateKeys, "ClusterSimpleMigrateKeys()"); - - //10 - x[9] = new(ClusterSimpleMigrateKeysWithObjects, "ClusterSimpleMigrateKeysWithObjects()"); - - //11 - x[10] = new(ClusterSimpleMigrateWithReadWrite, "ClusterSimpleMigrateWithReadWrite()"); - + (Action, string)[] x = + [ + //1 + new(ClusterSimpleInitialize, "ClusterSimpleInitialize()"), + //2 + new(ClusterSimpleSlotInfo, "ClusterSimpleSlotInfo()"), + //3 + new(ClusterAddDelSlots, "ClusterAddDelSlots()"), + //4 + new(ClusterSlotChangeStatus, "ClusterSlotChangeStatus()"), + //5 + new(ClusterRedirectMessage, "ClusterRedirectMessage()"), + //6 + new(ClusterSimpleMigrateSlots, "ClusterSimpleMigrateSlots()"), + //7 + new(ClusterSimpleMigrateSlotsExpiry, "ClusterSimpleMigrateSlotsExpiry()"), + //8 + new(ClusterSimpleMigrateSlotsWithObjects, "ClusterSimpleMigrateSlotsWithObjects()"), + //9 + new(ClusterSimpleMigrateKeys, "ClusterSimpleMigrateKeys()"), + //10 + new(ClusterSimpleMigrateKeysWithObjects, "ClusterSimpleMigrateKeysWithObjects()"), + //11 + new(ClusterSimpleMigrateWithReadWrite, "ClusterSimpleMigrateWithReadWrite()"), + ]; return x; } @@ -209,7 +200,7 @@ private void CreateMultiSlotData( } int j = 0; - List slots = slotsTokey.Keys.ToList(); + List slots = [.. slotsTokey.Keys]; for (int i = 0; i < keyCount; i++) { key = slotsTokey[slots[j]]; @@ -1139,7 +1130,7 @@ private void OperateOnSlotsTask(Dictionary> data var Port = TestUtils.Port; var Shards = defaultShards; var Ports = Enumerable.Range(Port, Shards).ToList(); - var connections = ClusterTestUtils.CreateLightRequestConnections(Ports.ToArray()); + var connections = ClusterTestUtils.CreateLightRequestConnections([.. Ports]); operatedOnData = []; foreach (var slot in data.Keys) @@ -1334,10 +1325,10 @@ public void ClusterSimpleTxn() } private static readonly object[] _slotranges = - { - new object[] { new List() { 5500, 5510} }, + [ + new object[] { new List() { 5500, 5510 } }, new object[] { new List() { 6000, 6015, 9020, 9050 } } - }; + ]; [Test, Order(13)] [Category("CLUSTER")] diff --git a/test/Garnet.test.cluster/ClusterTestContext.cs b/test/Garnet.test.cluster/ClusterTestContext.cs index c849de7478..5a48c75b50 100644 --- a/test/Garnet.test.cluster/ClusterTestContext.cs +++ b/test/Garnet.test.cluster/ClusterTestContext.cs @@ -369,7 +369,7 @@ public void PopulatePrimaryWithObjects(ref Dictionary> kvPairs else { var result = clusterTestUtils.Smembers(primaryIndex, key, logger); - Assert.IsTrue(result.ToHashSet().SetEquals(value.ToHashSet())); + Assert.IsTrue(result.ToHashSet().SetEquals(value)); } } } @@ -448,7 +448,7 @@ public void ValidateNodeObjects(ref Dictionary> kvPairsObj, in if (!set) Assert.AreEqual(elements, result); else - Assert.IsTrue(result.ToHashSet().SetEquals(result.ToHashSet())); + Assert.IsTrue(result.ToHashSet().SetEquals(result)); } } diff --git a/test/Garnet.test.cluster/ClusterTestUtils.cs b/test/Garnet.test.cluster/ClusterTestUtils.cs index cb90c9343a..4af03c247e 100644 --- a/test/Garnet.test.cluster/ClusterTestUtils.cs +++ b/test/Garnet.test.cluster/ClusterTestUtils.cs @@ -204,14 +204,14 @@ public List NodesAll(IPEndPoint endPoint, ClusterInfoTag[] tags, strin private async Task WaitForEpochSync(IPEndPoint endPoint) { var endpoints = GetEndpointsWithout(endPoint); - var configInfo = NodesMyself(endPoint, new[] { ClusterInfoTag.NODEID, ClusterInfoTag.CONFIG_EPOCH }); + var configInfo = NodesMyself(endPoint, [ClusterInfoTag.NODEID, ClusterInfoTag.CONFIG_EPOCH]); while (true) { await Task.Delay(endpoints.Length * 100); retry: foreach (var endpoint in endpoints) { - var _configInfo = NodesAll(endpoint, new[] { ClusterInfoTag.NODEID, ClusterInfoTag.CONFIG_EPOCH }, configInfo[0]); + var _configInfo = NodesAll(endpoint, [ClusterInfoTag.NODEID, ClusterInfoTag.CONFIG_EPOCH], configInfo[0]); if (_configInfo[0][0] == configInfo[1]) ThrowException($"WaitForEpochSync unexpected node id {_configInfo[0][0]} {configInfo[1]}"); @@ -742,7 +742,7 @@ public List RandomHset(int count, int maxVal) { hset.Add(r.Next(0, maxVal)); } - return hset.ToList(); + return [.. hset]; } public string RandomStr(int length, int startOffset = -1, int endOffset = -1) @@ -1557,7 +1557,7 @@ public string AddDelSlots(int nodeIndex, List slots, bool addslot, ILogger try { - return (string)server.Execute("cluster", objects.ToArray()); + return (string)server.Execute("cluster", [.. objects]); } catch (Exception e) { @@ -1576,7 +1576,7 @@ public string AddDelSlotsRange(int nodeIndex, List<(int, int)> ranges, bool adds try { - return (string)server.Execute("cluster", objects.ToArray()); + return (string)server.Execute("cluster", [.. objects]); } catch (Exception e) { @@ -2350,7 +2350,7 @@ public List Lrange(int nodeIndex, string key, ILogger logger = null) var args = new List() { key, "0", "-1" }; var result = server.Execute("LRANGE", args); - return ((int[])result).ToList(); + return [.. ((int[])result)]; } catch (Exception ex) { @@ -2387,7 +2387,7 @@ public List Smembers(int nodeIndex, string key, ILogger logger = null) var args = new List() { key }; var result = server.Execute("SMEMBERS", args); - return ((int[])result).ToList(); + return [.. ((int[])result)]; } catch (Exception ex) { @@ -2404,7 +2404,7 @@ public long GetStoreCurrentAofAddress(IPEndPoint endPoint, ILogger logger = null { try { - var storeCurrentSafeAofAddress = GetReplicationInfo(endPoint, new ReplicationInfoItem[] { ReplicationInfoItem.STORE_CURRENT_SAFE_AOF_ADDRESS }, logger)[0].Item2; + var storeCurrentSafeAofAddress = GetReplicationInfo(endPoint, [ReplicationInfoItem.STORE_CURRENT_SAFE_AOF_ADDRESS], logger)[0].Item2; return long.Parse(storeCurrentSafeAofAddress); } catch (Exception ex) @@ -2422,7 +2422,7 @@ public long GetStoreRecoveredAofAddress(IPEndPoint endPoint, ILogger logger = nu { try { - var storeRecoveredSafeAofAddress = GetReplicationInfo(endPoint, new[] { ReplicationInfoItem.STORE_RECOVERED_SAFE_AOF_ADDRESS }, logger)[0].Item2; + var storeRecoveredSafeAofAddress = GetReplicationInfo(endPoint, [ReplicationInfoItem.STORE_RECOVERED_SAFE_AOF_ADDRESS], logger)[0].Item2; return long.Parse(storeRecoveredSafeAofAddress); } catch (Exception ex) @@ -2440,7 +2440,7 @@ public long GetObjectStoreCurrentAofAddress(IPEndPoint endPoint, ILogger logger { try { - var objectStoreCurrentSafeAofAddress = GetReplicationInfo(endPoint, new[] { ReplicationInfoItem.OBJECT_STORE_CURRENT_SAFE_AOF_ADDRESS }, logger)[0].Item2; + var objectStoreCurrentSafeAofAddress = GetReplicationInfo(endPoint, [ReplicationInfoItem.OBJECT_STORE_CURRENT_SAFE_AOF_ADDRESS], logger)[0].Item2; return long.Parse(objectStoreCurrentSafeAofAddress); } catch (Exception ex) @@ -2458,7 +2458,7 @@ public long GetObjectStoreRecoveredAofAddress(IPEndPoint endPoint, ILogger logge { try { - var objectStoreRecoveredSafeAofAddress = GetReplicationInfo(endPoint, new ReplicationInfoItem[] { ReplicationInfoItem.OBJECT_STORE_RECOVERED_SAFE_AOF_ADDRESS }, logger)[0].Item2; + var objectStoreRecoveredSafeAofAddress = GetReplicationInfo(endPoint, [ReplicationInfoItem.OBJECT_STORE_RECOVERED_SAFE_AOF_ADDRESS], logger)[0].Item2; return long.Parse(objectStoreRecoveredSafeAofAddress); } catch (Exception ex) diff --git a/test/Garnet.test.cluster/RedirectTests/ClusterSlotVerificationTests.cs b/test/Garnet.test.cluster/RedirectTests/ClusterSlotVerificationTests.cs index e6cfeb3fc7..bbfe093a55 100644 --- a/test/Garnet.test.cluster/RedirectTests/ClusterSlotVerificationTests.cs +++ b/test/Garnet.test.cluster/RedirectTests/ClusterSlotVerificationTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using System.Collections.Generic; using Garnet.common; using Microsoft.Extensions.Logging; using NUnit.Framework; @@ -421,7 +422,7 @@ void SERedisTRYAGAINTest(BaseCommand command) ResetSlot(); try { - _ = context.clusterTestUtils.GetServer(requestNodeIndex).Execute("DEL", command.GetSingleSlotKeys.ToArray(), CommandFlags.NoRedirect); + _ = context.clusterTestUtils.GetServer(requestNodeIndex).Execute("DEL", (ICollection)command.GetSingleSlotKeys, CommandFlags.NoRedirect); } catch (Exception ex) { diff --git a/test/Garnet.test/HyperLogLogTests.cs b/test/Garnet.test/HyperLogLogTests.cs index bb61094350..7f58c760b2 100644 --- a/test/Garnet.test/HyperLogLogTests.cs +++ b/test/Garnet.test/HyperLogLogTests.cs @@ -501,7 +501,7 @@ public RedisValue[] RandomRedisValueSubseq(List list, int count) List rss = []; for (int i = 0; i < count; i++) rss.Add(list[r.Next(list.Count)]); - return rss.ToArray(); + return [.. rss]; } public static List ToList(RedisValue[] rss) diff --git a/test/Garnet.test/RespBlockingListTests.cs b/test/Garnet.test/RespBlockingListTests.cs index 6005960cfc..d7f333689c 100644 --- a/test/Garnet.test/RespBlockingListTests.cs +++ b/test/Garnet.test/RespBlockingListTests.cs @@ -72,7 +72,7 @@ public void BasicListBlockingPopTest(string blockingCmd) var timeout = TimeSpan.FromSeconds(5); try { - Task.WaitAll(new[] { blockingTask, releasingTask }, timeout); + Task.WaitAll([blockingTask, releasingTask], timeout); } catch (AggregateException) { @@ -134,7 +134,7 @@ public void BasicBlockingListMoveTest() var timeout = TimeSpan.FromSeconds(5); try { - Task.WaitAll(new[] { blockingTask, releasingTask }, timeout); + Task.WaitAll([blockingTask, releasingTask], timeout); } catch (AggregateException) { @@ -223,7 +223,7 @@ public void BlockingClientEventsTests(string blockingCmd) var timeout = TimeSpan.FromSeconds(5); try { - Task.WaitAll(new[] { blockingTask, releasingTask }, timeout); + Task.WaitAll([blockingTask, releasingTask], timeout); } catch (AggregateException) { diff --git a/test/Garnet.test/RespCommandTests.cs b/test/Garnet.test/RespCommandTests.cs index 5097605b59..7b83f89431 100644 --- a/test/Garnet.test/RespCommandTests.cs +++ b/test/Garnet.test/RespCommandTests.cs @@ -165,8 +165,8 @@ public void CommandUnknownSubcommandTest() /// Test COMMAND INFO [command-name [command-name ...]] /// [Test] - [TestCase(new object[] { "GET", "SET", "COSCAN" })] - [TestCase(new object[] { "get", "set", "coscan" })] + [TestCase(["GET", "SET", "COSCAN"])] + [TestCase(["get", "set", "coscan"])] public void CommandInfoWithCommandNamesTest(params string[] commands) { using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig()); @@ -191,8 +191,8 @@ public void CommandInfoWithCommandNamesTest(params string[] commands) /// Test COMMAND INFO with custom commands /// [Test] - [TestCase(new object[] { "SETIFPM", "MYDICTSET", "MGETIFPM", "READWRITETX", "MYDICTGET" })] - [TestCase(new object[] { "setifpm", "mydictset", "mgetifpm", "readwritetx", "mydictget" })] + [TestCase(["SETIFPM", "MYDICTSET", "MGETIFPM", "READWRITETX", "MYDICTGET"])] + [TestCase(["setifpm", "mydictset", "mgetifpm", "readwritetx", "mydictget"])] public void CommandInfoWithCustomCommandNamesTest(params string[] commands) { using var redis = ConnectionMultiplexer.Connect(TestUtils.GetConfig()); @@ -353,7 +353,7 @@ private string[] DynamicallyRegisterCustomCommands(IDatabase db) // Register select custom commands and transactions var result = (string)db.Execute($"REGISTERCS", - args.ToArray()); + [.. args]); Assert.AreEqual("OK", result); return registeredCommands; diff --git a/test/Garnet.test/RespCustomCommandTests.cs b/test/Garnet.test/RespCustomCommandTests.cs index c9c0806d7f..6160b25fb8 100644 --- a/test/Garnet.test/RespCustomCommandTests.cs +++ b/test/Garnet.test/RespCustomCommandTests.cs @@ -643,7 +643,7 @@ public void RegisterCustomCommandTest() // Register select custom commands and transactions var resp = (string)db.Execute($"REGISTERCS", - args.ToArray()); + [.. args]); // Test READWRITETX string key = "readkey"; @@ -725,7 +725,7 @@ public void RegisterCustomCommandErrorConditionsTest() try { - resp = (string)db.Execute($"REGISTERCS", args.ToArray()); + resp = (string)db.Execute($"REGISTERCS", [.. args]); } catch (RedisServerException rse) { @@ -746,7 +746,7 @@ public void RegisterCustomCommandErrorConditionsTest() try { - resp = (string)db.Execute($"REGISTERCS", args.ToArray()); + resp = (string)db.Execute($"REGISTERCS", [.. args]); } catch (RedisServerException rse) { @@ -767,7 +767,7 @@ .. libraryPaths.Skip(1), try { - resp = (string)db.Execute($"REGISTERCS", args.ToArray()); + resp = (string)db.Execute($"REGISTERCS", [.. args]); } catch (RedisServerException rse) { @@ -788,7 +788,7 @@ .. libraryPaths.Skip(1), try { - resp = (string)db.Execute($"REGISTERCS", args.ToArray()); + resp = (string)db.Execute($"REGISTERCS", [.. args]); } catch (RedisServerException rse) { diff --git a/test/Garnet.test/RespHashTests.cs b/test/Garnet.test/RespHashTests.cs index c8e91297b5..dafecfe18c 100644 --- a/test/Garnet.test/RespHashTests.cs +++ b/test/Garnet.test/RespHashTests.cs @@ -627,11 +627,11 @@ public void CheckHashOperationsOnWrongTypeObjectSE() var key1Values = new[] { new RedisValue("Hello"), new RedisValue("World") }; var key2Values = new[] { new RedisValue("Hola"), new RedisValue("Mundo") }; var values = new[] { key1Values, key2Values }; - var hashFields = new[] - { - new[] { new RedisValue("K1_H1"), new RedisValue("K1_H2") }, - new[] { new RedisValue("K2_H1"), new RedisValue("K2_H2") } - }; + RedisValue[][] hashFields = + [ + [new RedisValue("K1_H1"), new RedisValue("K1_H2")], + [new RedisValue("K2_H1"), new RedisValue("K2_H2")] + ]; var hashEntries = hashFields.Select((h, idx) => h .Zip(values[idx], (n, v) => new HashEntry(n, v)).ToArray()).ToArray(); diff --git a/test/Garnet.test/RespListGarnetClientTests.cs b/test/Garnet.test/RespListGarnetClientTests.cs index 62749a1a0b..42f2f5dcc4 100644 --- a/test/Garnet.test/RespListGarnetClientTests.cs +++ b/test/Garnet.test/RespListGarnetClientTests.cs @@ -208,7 +208,7 @@ public async Task AddElementsToTheListTail_WithAsync(string key, string[] elemen // Act & Assert var testKey = GetTestKey(key); - var actualListLength = await db.ListRightPushAsync(testKey, elements.ToArray()); + var actualListLength = await db.ListRightPushAsync(testKey, [.. elements]); Assert.AreEqual(expectedList.Length, actualListLength); await ValidateListContentAsync(db, testKey, expectedList); diff --git a/test/Garnet.test/RespListTests.cs b/test/Garnet.test/RespListTests.cs index c989068f91..476ef61d7c 100644 --- a/test/Garnet.test/RespListTests.cs +++ b/test/Garnet.test/RespListTests.cs @@ -119,22 +119,22 @@ public void MultiLPUSHAndLTRIMWithMemoryCheck() Assert.IsFalse(exists); } - private static object[] LTrimTestCases = { - new object[] {0, 0, new[] {0} }, - new object[] {-2, -1, new[] {8, 9} }, - new object[] {-2, -2, new[] {8} }, - new object[] {3, 5, new[] {3, 4, 5} }, - new object[] {-12, 0, new[] {0} }, - new object[] {-12, 2, new[] {0, 1, 2} }, - new object[] {-12, -7, new[] {0, 1, 2, 3} }, - new object[] {-15, -11, Array.Empty() }, - new object[] {8, 8, new[] {8} }, - new object[] {8, 12, new[] {8, 9} }, - new object[] {9, 12, new[] {9} }, - new object[] {10, 12, Array.Empty() }, - new object[] {5, 3, Array.Empty()}, - new object[] {-3, -5, Array.Empty()} - }; + private static object[] LTrimTestCases = [ + new object[] { 0, 0, new[] { 0 } }, + new object[] { -2, -1, new[] { 8, 9 } }, + new object[] { -2, -2, new[] { 8 } }, + new object[] { 3, 5, new[] { 3, 4, 5 } }, + new object[] { -12, 0, new[] { 0 } }, + new object[] { -12, 2, new[] { 0, 1, 2 } }, + new object[] { -12, -7, new[] { 0, 1, 2, 3 } }, + new object[] { -15, -11, Array.Empty() }, + new object[] { 8, 8, new[] { 8 } }, + new object[] { 8, 12, new[] { 8, 9 } }, + new object[] { 9, 12, new[] { 9 } }, + new object[] { 10, 12, Array.Empty() }, + new object[] { 5, 3, Array.Empty() }, + new object[] { -3, -5, Array.Empty() } + ]; [Test] [TestCaseSource(nameof(LTrimTestCases))] @@ -728,7 +728,7 @@ public async Task CanUseLMoveGC() // Test for Operation direction error. var exception = Assert.ThrowsAsync(async () => { - await db.ExecuteForStringResultAsync("LMOVE", new string[] { "mylist", "myotherlist", "right", "lef" }); + await db.ExecuteForStringResultAsync("LMOVE", ["mylist", "myotherlist", "right", "lef"]); }); Assert.AreEqual("ERR syntax error", exception.Message); @@ -781,30 +781,30 @@ public async Task CanUseLMoveWithCaseInsensitiveDirectionGC() using var db = TestUtils.GetGarnetClient(); db.Connect(); - await db.ExecuteForStringResultAsync("RPUSH", new string[] { "mylist", "one" }); - await db.ExecuteForStringResultAsync("RPUSH", new string[] { "mylist", "two" }); - await db.ExecuteForStringResultAsync("RPUSH", new string[] { "mylist", "three" }); + await db.ExecuteForStringResultAsync("RPUSH", ["mylist", "one"]); + await db.ExecuteForStringResultAsync("RPUSH", ["mylist", "two"]); + await db.ExecuteForStringResultAsync("RPUSH", ["mylist", "three"]); - var response = await db.ExecuteForStringResultAsync("LMOVE", new string[] { "mylist", "myotherlist", "right", "left" }); + var response = await db.ExecuteForStringResultAsync("LMOVE", ["mylist", "myotherlist", "right", "left"]); Assert.AreEqual("three", response); - var responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", new string[] { "mylist", "0", "-1" }); + var responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", ["mylist", "0", "-1"]); var expectedResponseArray = new string[] { "one", "two" }; Assert.AreEqual(expectedResponseArray, responseArray); - responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", new string[] { "myotherlist", "0", "-1" }); - expectedResponseArray = new string[] { "three" }; + responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", ["myotherlist", "0", "-1"]); + expectedResponseArray = ["three"]; Assert.AreEqual(expectedResponseArray, responseArray); - response = await db.ExecuteForStringResultAsync("LMOVE", new string[] { "mylist", "myotherlist", "LeFT", "RIghT" }); + response = await db.ExecuteForStringResultAsync("LMOVE", ["mylist", "myotherlist", "LeFT", "RIghT"]); Assert.AreEqual("one", response); - responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", new string[] { "mylist", "0", "-1" }); - expectedResponseArray = new string[] { "two" }; + responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", ["mylist", "0", "-1"]); + expectedResponseArray = ["two"]; Assert.AreEqual(expectedResponseArray, responseArray); - responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", new string[] { "myotherlist", "0", "-1" }); - expectedResponseArray = new string[] { "three", "one" }; + responseArray = await db.ExecuteForStringArrayResultAsync("LRANGE", ["myotherlist", "0", "-1"]); + expectedResponseArray = ["three", "one"]; Assert.AreEqual(expectedResponseArray, responseArray); } @@ -1318,17 +1318,17 @@ public void CanDoBasicLMPOP() pushed = db.ListRightPush(key2, key2Values); Assert.AreEqual(1, pushed); - var result = db.ListLeftPop(new[] { new RedisKey("test") }, 3); + var result = db.ListLeftPop([new RedisKey("test")], 3); Assert.True(result.IsNull); - result = db.ListRightPop(new[] { new RedisKey("test") }, 3); + result = db.ListRightPop([new RedisKey("test")], 3); Assert.True(result.IsNull); - result = db.ListLeftPop(new[] { key1, key2 }, 3); + result = db.ListLeftPop([key1, key2], 3); Assert.AreEqual(key1, result.Key); Assert.AreEqual(key1Values, result.Values); - result = db.ListRightPop(new[] { new RedisKey("test"), key2 }, 2); + result = db.ListRightPop([new RedisKey("test"), key2], 2); Assert.AreEqual(key2, result.Key); Assert.AreEqual(key2Values.Reverse(), result.Values); } @@ -1346,7 +1346,7 @@ public void CanDoLMPOPLeftWithoutCount() var response = db.Execute("LMPOP", "1", key1.ToString(), "LEFT"); - var result = response.Resp2Type == ResultType.Array ? (string[])response : Array.Empty(); + var result = response.Resp2Type == ResultType.Array ? (string[])response : []; Assert.AreEqual(new string[] { key1.ToString(), key1Values[0].ToString() }, result); } @@ -1365,12 +1365,12 @@ public void CanDoLMPOPRightMultipleTimes() for (var i = 0; i < key1Values.Length; i++) { - result = db.ListRightPop(new[] { key1 }, 1); + result = db.ListRightPop([key1], 1); Assert.AreEqual(key1, result.Key); Assert.AreEqual(key1Values[i], result.Values.FirstOrDefault()); } - result = db.ListRightPop(new[] { key1 }, 1); + result = db.ListRightPop([key1], 1); Assert.True(result.IsNull); } diff --git a/test/Garnet.test/RespMetricsTest.cs b/test/Garnet.test/RespMetricsTest.cs index 49874cd83b..ec6dad362e 100644 --- a/test/Garnet.test/RespMetricsTest.cs +++ b/test/Garnet.test/RespMetricsTest.cs @@ -117,7 +117,7 @@ public void MetricsEnabledTest() while (latencyMetrics.Length == 0) { Thread.Yield(); - latencyMetrics = server.Metrics.GetLatencyMetrics(LatencyMetricsType.NET_RS_LAT).ToArray(); + latencyMetrics = [.. server.Metrics.GetLatencyMetrics(LatencyMetricsType.NET_RS_LAT)]; } Assert.AreNotEqual(Array.Empty<(LatencyMetricsType, MetricsItem[])>(), latencyMetrics); Assert.AreEqual(8, latencyMetrics.Length); diff --git a/test/Garnet.test/RespSetTest.cs b/test/Garnet.test/RespSetTest.cs index 13a2db9c9f..3137424d4f 100644 --- a/test/Garnet.test/RespSetTest.cs +++ b/test/Garnet.test/RespSetTest.cs @@ -553,7 +553,7 @@ public void CanDoSdiff(string key1, string key2) addResult = db.SetAdd(key3, key3Value); Assert.AreEqual(3, addResult); - result = db.SetCombine(SetOperation.Difference, new[] { new RedisKey(key1), new RedisKey(key2), new RedisKey(key3) }); + result = db.SetCombine(SetOperation.Difference, [new RedisKey(key1), new RedisKey(key2), new RedisKey(key3)]); Assert.AreEqual(2, result.Length); strResult = result.Select(r => r.ToString()).ToArray(); expectedResult = ["b", "d"]; @@ -695,7 +695,7 @@ public void CanDoSRANDMEMBERWithCountCommandSE() Assert.AreEqual(expectedMessage, ex.Message); // Add items to set - var added = db.SetAdd(key, values.ToArray()); + var added = db.SetAdd(key, [.. values]); Assert.AreEqual(values.Count, added); // Check SRANDMEMBER without count @@ -1432,16 +1432,16 @@ public void CheckSetOperationsOnWrongTypeObjectSE() // SUNION RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => db.SetCombine(SetOperation.Union, keys[0], keys[1])); // SUNIONSTORE - RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => db.SetCombineAndStore(SetOperation.Union, keys[0], new[] { keys[1] })); + RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => db.SetCombineAndStore(SetOperation.Union, keys[0], [keys[1]])); // SDIFF RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => db.SetCombine(SetOperation.Difference, keys[0], keys[1])); // SDIFFSTORE RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => - db.SetCombineAndStore(SetOperation.Difference, keys[0], new[] { keys[1] })); + db.SetCombineAndStore(SetOperation.Difference, keys[0], [keys[1]])); // SINTER RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => db.SetCombine(SetOperation.Intersect, keys[0], keys[1])); // SINTERSTORE - RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => db.SetCombineAndStore(SetOperation.Intersect, keys[0], new[] { keys[1] })); + RespTestsUtils.CheckCommandOnWrongTypeObjectSE(() => db.SetCombineAndStore(SetOperation.Intersect, keys[0], [keys[1]])); } #endregion diff --git a/test/Garnet.test/RespSortedSetGeoTests.cs b/test/Garnet.test/RespSortedSetGeoTests.cs index cebc53f5fb..236bb9c636 100644 --- a/test/Garnet.test/RespSortedSetGeoTests.cs +++ b/test/Garnet.test/RespSortedSetGeoTests.cs @@ -244,16 +244,16 @@ public void CheckGeoSortedSetOperationsOnWrongTypeObjectSE() var db = redis.GetDatabase(0); var keys = new[] { new RedisKey("user1:obj1"), new RedisKey("user1:obj2") }; - var values = new[] - { - new[] { new RedisValue("Tel Aviv"), new RedisValue("Haifa") }, - new[] { new RedisValue("Athens"), new RedisValue("Thessaloniki") } - }; - var coords = new[] - { - new[] { new[] { 2.0853, 34.7818 }, new[] { 32.7940, 34.9896 } }, - new[] { new[] { 7.9838, 23.7275 }, new[] { 40.6401, 22.9444 } } - }; + RedisValue[][] values = + [ + [new RedisValue("Tel Aviv"), new RedisValue("Haifa")], + [new RedisValue("Athens"), new RedisValue("Thessaloniki")] + ]; + double[][][] coords = + [ + [[2.0853, 34.7818], [32.7940, 34.9896]], + [[7.9838, 23.7275], [40.6401, 22.9444]], + ]; var geoEntries = values.Select((h, idx) => h .Zip(coords[idx], (v, c) => new GeoEntry(c[0], c[1], v)).ToArray()).ToArray(); diff --git a/test/Garnet.test/RespSortedSetTests.cs b/test/Garnet.test/RespSortedSetTests.cs index e440c5d777..1890536a0c 100644 --- a/test/Garnet.test/RespSortedSetTests.cs +++ b/test/Garnet.test/RespSortedSetTests.cs @@ -810,7 +810,7 @@ public void CheckSortedSetOperationsOnWrongTypeObjectSE() var key1Values = new[] { new RedisValue("Hello"), new RedisValue("World") }; var key2Values = new[] { new RedisValue("Hola"), new RedisValue("Mundo") }; var values = new[] { key1Values, key2Values }; - var scores = new[] { new[] { 1.1, 1.2 }, new[] { 2.1, 2.2 } }; + double[][] scores = [[1.1, 1.2], [2.1, 2.2]]; var sortedSetEntries = values.Select((h, idx) => h .Zip(scores[idx], (n, v) => new SortedSetEntry(n, v)).ToArray()).ToArray();