diff --git a/Directory.Packages.props b/Directory.Packages.props index ac86b65080..a1d51be208 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -50,7 +50,7 @@ major, so this is not a lagging pin to be bumped to 3.x/4.x when the others are refreshed --> - + diff --git a/src/RESPite.Benchmark/BenchmarkBase.cs b/src/RESPite.Benchmark/BenchmarkBase.cs index 92c3992325..6304079f09 100644 --- a/src/RESPite.Benchmark/BenchmarkBase.cs +++ b/src/RESPite.Benchmark/BenchmarkBase.cs @@ -437,19 +437,13 @@ private static string GetNameCore(Delegate underlyingAction, out string descript { string name = underlyingAction.Method.Name; - if (underlyingAction.Method.GetCustomAttribute(typeof(DisplayNameAttribute)) is DisplayNameAttribute - { - DisplayName: { Length: > 0 } - } dna) + if (underlyingAction.Method.GetCustomAttribute(typeof(DisplayNameAttribute)) is DisplayNameAttribute { DisplayName: { Length: > 0 } } dna) { name = dna.DisplayName; } description = ""; - if (underlyingAction.Method.GetCustomAttribute(typeof(DescriptionAttribute)) is DescriptionAttribute - { - Description: { Length: > 0 } - } da) + if (underlyingAction.Method.GetCustomAttribute(typeof(DescriptionAttribute)) is DescriptionAttribute { Description: { Length: > 0 } } da) { description = da.Description; } @@ -568,7 +562,7 @@ private async Task RunAsyncCore( $"{TotalOperations(divisor):###,###,##0} requests completed in {seconds:0.00} seconds, {rate:###,###,##0} ops/sec"); } - if (!Quiet & typeof(T) != typeof(DBNull)) + if (!Quiet & (typeof(T) != typeof(DBNull))) { const string format = "Typical result: {0}"; diff --git a/src/RESPite/Buffers/CycleBuffer.cs b/src/RESPite/Buffers/CycleBuffer.cs index c674e6bece..adc15c60e7 100644 --- a/src/RESPite/Buffers/CycleBuffer.cs +++ b/src/RESPite/Buffers/CycleBuffer.cs @@ -105,7 +105,7 @@ private void CopyDueToDiscardDuringWrite(int count) .CopyTo(full.Slice(targetOffset, count)); } } - public bool CommittedIsEmpty => ReferenceEquals(startSegment, endSegment) & endSegmentCommitted == 0; + public bool CommittedIsEmpty => ReferenceEquals(startSegment, endSegment) & (endSegmentCommitted == 0); /// /// Marks committed data as fully consumed; it will no longer appear in later calls to . @@ -117,8 +117,8 @@ public void DiscardCommitted(int count) // optimize for most common case, where we consume everything if (ReferenceEquals(startSegment, endSegment) - & count == endSegmentCommitted - & count > 0) + & (count == endSegmentCommitted) + & (count > 0)) { /* we are consuming all the data in the single segment; we can @@ -144,8 +144,8 @@ public void DiscardCommitted(long count) // optimize for most common case, where we consume everything if (ReferenceEquals(startSegment, endSegment) - & count == endSegmentCommitted - & count > 0) // checks sign *and* non-trimmed + & (count == endSegmentCommitted) + & (count > 0)) // checks sign *and* non-trimmed { // see for logic endSegmentCommitted = 0; @@ -339,7 +339,7 @@ public bool TryGetFirstCommittedMemory(int minBytes, out ReadOnlyMemory me // partial segment (and we know it isn't empty) memory = memory.Slice(start: 0, length: available); - return available >= minBytes & minBytes > 0; // last check here applies the -ve logic + return (available >= minBytes) & (minBytes > 0); // last check here applies the -ve logic } // multi-page; hand out the first page (which is, by definition: full) @@ -603,7 +603,7 @@ public int Untrim(bool expandBackwards = false) { _flags &= ~(Flags.StartTrim | Flags.EndTrim); Memory = fullMemory; - if (expandBackwards & RunningIndex >= delta) + if (expandBackwards & (RunningIndex >= delta)) { // push our origin earlier; only valid if // we're the first segment, otherwise diff --git a/src/RESPite/Internal/BlockBuffer.cs b/src/RESPite/Internal/BlockBuffer.cs index 752d74c8d3..efdcfaa77d 100644 --- a/src/RESPite/Internal/BlockBuffer.cs +++ b/src/RESPite/Internal/BlockBuffer.cs @@ -114,8 +114,8 @@ public static BlockBuffer GetBuffer(BlockBufferSerializer parent, int sizeHint) private int AvailableWithResetIfUseful() { if (_finalizedOffset != 0 // at least some chunks have been finalized - && Volatile.Read(ref _refCount) == 1 // all finalized chunks returned - & _writeOffset == _finalizedOffset) // we're not in the middle of serializing something new + && (Volatile.Read(ref _refCount) == 1) // all finalized chunks returned + & (_writeOffset == _finalizedOffset)) // we're not in the middle of serializing something new { _writeOffset = _finalizedOffset = 0; // swipe left } @@ -207,8 +207,8 @@ private void CopyFrom(Span source) private bool TryResizeFor(int extraBytes) { - if (_finalizedOffset == 0 & // we can only do this if there are no other messages in the buffer - Volatile.Read(ref _refCount) == 1) // and no-one else is looking (we already tried reset) + if ((_finalizedOffset == 0) & // we can only do this if there are no other messages in the buffer + (Volatile.Read(ref _refCount) == 1)) // and no-one else is looking (we already tried reset) { // we're already on the boundary - don't scrimp; just do the math from the end of the buffer byte[] newArray = _arrayPool.Rent(_array.Length + extraBytes); diff --git a/src/RESPite/Messages/RespFrameScanner.cs b/src/RESPite/Messages/RespFrameScanner.cs index 28cd92de7a..ac974aee58 100644 --- a/src/RESPite/Messages/RespFrameScanner.cs +++ b/src/RESPite/Messages/RespFrameScanner.cs @@ -98,7 +98,7 @@ private static OperationStatus TryFastRead(ReadOnlySpan data, ref RespScan lo = ((uint)UnsafeCpuUInt16(data, 4)) << 16; break; case 7: - lo = ((uint)UnsafeCpuUInt16(data, 4)) << 16 | ((uint)UnsafeCpuByte(data, 6)) << 8; + lo = (((uint)UnsafeCpuUInt16(data, 4)) << 16) | (((uint)UnsafeCpuByte(data, 6)) << 8); break; default: lo = UnsafeCpuUInt32(data, 4); @@ -123,7 +123,7 @@ private static OperationStatus TryFastRead(ReadOnlySpan data, ref RespScan /// public OperationStatus TryRead(ref RespScanState state, in ReadOnlySequence data) { - if (!_pubsub & state.TotalBytes == 0 & data.IsSingleSegment) + if (!_pubsub & (state.TotalBytes == 0) & data.IsSingleSegment) { var status = TryFastRead(data.FirstSpan, ref state); if (status != UseReader) return status; @@ -148,7 +148,7 @@ static OperationStatus TryReadViaReader(ref RespScanState state, in ReadOnlySequ /// public OperationStatus TryRead(ref RespScanState state, ReadOnlySpan data) { - if (!_pubsub & state.TotalBytes == 0) + if (!_pubsub & (state.TotalBytes == 0)) { #if NET var status = TryFastRead(data, ref state); diff --git a/src/RESPite/Messages/RespReader.Utils.cs b/src/RESPite/Messages/RespReader.Utils.cs index 4a504ec1fb..076b3ba28c 100644 --- a/src/RESPite/Messages/RespReader.Utils.cs +++ b/src/RESPite/Messages/RespReader.Utils.cs @@ -349,7 +349,7 @@ public readonly byte[] Serialize() target = target.Slice(span.Length); if (!reader.TryMoveToNextSegment()) break; } - if (remaining != 0 | !target.IsEmpty) ThrowEof(); + if ((remaining != 0) | !target.IsEmpty) ThrowEof(); return arr; } } diff --git a/src/RESPite/Messages/RespReader.cs b/src/RESPite/Messages/RespReader.cs index 80ab55a46c..c532da1432 100644 --- a/src/RESPite/Messages/RespReader.cs +++ b/src/RESPite/Messages/RespReader.cs @@ -240,7 +240,8 @@ private readonly bool ScalarLengthIsSlow(int expected) /// the API, using the API to update the outer reader. public readonly int AggregateLength() => (_flags & (RespFlags.IsAggregate | RespFlags.IsStreaming)) == RespFlags.IsAggregate - ? _length : AggregateLengthSlow(); + ? _length + : AggregateLengthSlow(); /// /// Indicates whether the number of child elements associated with an aggregate is exactly the specified value. @@ -250,7 +251,8 @@ public readonly int AggregateLength() => /// i.e. a map of the form %2\r\n... will report 4 as the length. public readonly bool AggregateLengthIs(int count) => (_flags & (RespFlags.IsAggregate | RespFlags.IsStreaming)) == RespFlags.IsAggregate - ? _length == count : AggregateLengthIsSlow(count); + ? _length == count + : AggregateLengthIsSlow(count); public delegate T Projection(ref RespReader value); @@ -385,7 +387,7 @@ internal readonly bool IsNonNullAggregate internal int Delta() => (_flags & (RespFlags.IsScalar | RespFlags.IsAggregate | RespFlags.IsStreaming | RespFlags.IsAttribute)) switch { - RespFlags.IsScalar | RespFlags.IsAggregate=> -1, // null has this + RespFlags.IsScalar | RespFlags.IsAggregate => -1, // null has this RespFlags.IsScalar => -1, RespFlags.IsAggregate => _length - 1, RespFlags.IsAggregate | RespFlags.IsAttribute => _length, @@ -423,7 +425,7 @@ private bool TryReadNextSkipAttributes(bool skipStreamTerminator) { SkipChildren(); } - else if (skipStreamTerminator & Prefix is RespPrefix.StreamTerminator) + else if (skipStreamTerminator & (Prefix is RespPrefix.StreamTerminator)) { // skip terminator } @@ -446,7 +448,7 @@ private bool TryReadNextProcessAttributes(RespAttributeReader respAttribut { respAttributeReader.Read(ref this, ref attributes); } - else if (skipStreamTerminator & Prefix is RespPrefix.StreamTerminator) + else if (skipStreamTerminator & (Prefix is RespPrefix.StreamTerminator)) { // skip terminator } @@ -1657,7 +1659,7 @@ internal readonly bool IsOK() // go mad with this, because it is used so often if (TryGetSpan(out var span) && span.Length == 2) { var u16 = Unsafe.ReadUnaligned(ref UnsafeCurrent); - return u16 == RespConstants.OKUInt16 | u16 == RespConstants.OKUInt16_LC; + return (u16 == RespConstants.OKUInt16) | (u16 == RespConstants.OKUInt16_LC); } return IsSlow(RespConstants.OKBytes, RespConstants.OKBytes_LC); @@ -1893,7 +1895,7 @@ public readonly bool TryReadInt64(out long value) var span = Buffer(stackalloc byte[RespConstants.MaxRawBytesInt64 + 1]); if (span.Length <= RespConstants.MaxRawBytesInt64) { - return Utf8Parser.TryParse(span, out value, out int bytes) & bytes == span.Length; + return Utf8Parser.TryParse(span, out value, out int bytes) & (bytes == span.Length); } value = 0; @@ -1927,7 +1929,7 @@ public readonly bool TryReadInt32(out int value) var span = Buffer(stackalloc byte[RespConstants.MaxRawBytesInt32 + 1]); if (span.Length <= RespConstants.MaxRawBytesInt32) { - return Utf8Parser.TryParse(span, out value, out int bytes) & bytes == span.Length; + return Utf8Parser.TryParse(span, out value, out int bytes) & (bytes == span.Length); } value = 0; @@ -2015,7 +2017,7 @@ internal readonly bool UnsafeTryReadShortAscii(out string value, int maxLength = foreach (var b in span) { // allow [SPACE]-thru-[DEL], plus CR/LF - if (!(b < 127 & (b >= 32 | (b is 12 or 13)))) + if (!((b < 127) & ((b >= 32) | (b is 12 or 13)))) { return false; } diff --git a/src/RESPite/Messages/RespScanState.cs b/src/RESPite/Messages/RespScanState.cs index 37cd3f8b65..ef5588ee65 100644 --- a/src/RESPite/Messages/RespScanState.cs +++ b/src/RESPite/Messages/RespScanState.cs @@ -127,7 +127,7 @@ private long ReadCore(ref RespReader reader, long startOffset = 0) #if DEBUG _elementCount++; #endif - if (!reader.IsAttribute & _prefix == RespPrefix.None) + if (!reader.IsAttribute & (_prefix == RespPrefix.None)) { _prefix = reader.Prefix; } diff --git a/src/RESPite/PublicAPI/PublicAPI.Unshipped.txt b/src/RESPite/PublicAPI/PublicAPI.Unshipped.txt index 7dc5c58110..555737f80f 100644 --- a/src/RESPite/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/RESPite/PublicAPI/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +*REMOVED*[SER004]override RESPite.AsciiHash.Equals(object? other) -> bool +[SER004]override RESPite.AsciiHash.Equals(object? obj) -> bool diff --git a/src/RESPite/Shared/AsciiHash.Comparers.cs b/src/RESPite/Shared/AsciiHash.Comparers.cs index 7b69a15a4b..bc3bd5ff77 100644 --- a/src/RESPite/Shared/AsciiHash.Comparers.cs +++ b/src/RESPite/Shared/AsciiHash.Comparers.cs @@ -13,7 +13,7 @@ private CaseSensitiveComparer() { } public bool Equals(AsciiHash x, AsciiHash y) { var len = x.Length; - return (len == y.Length & x._hashCS == y._hashCS) + return ((len == y.Length) & (x._hashCS == y._hashCS)) && (len <= MaxBytesHashed || x.Span.SequenceEqual(y.Span)); } @@ -28,7 +28,7 @@ private CaseInsensitiveComparer() { } public bool Equals(AsciiHash x, AsciiHash y) { var len = x.Length; - return (len == y.Length & x._hashUC == y._hashUC) + return ((len == y.Length) & (x._hashUC == y._hashUC)) && (len <= MaxBytesHashed || SequenceEqualsCI(x.Span, y.Span)); } diff --git a/src/RESPite/Shared/AsciiHash.Instance.cs b/src/RESPite/Shared/AsciiHash.Instance.cs index 93b8258cad..94a774f81e 100644 --- a/src/RESPite/Shared/AsciiHash.Instance.cs +++ b/src/RESPite/Shared/AsciiHash.Instance.cs @@ -37,13 +37,13 @@ public AsciiHash(string? value) : this(value is null ? [] : Encoding.ASCII.GetBy public override string ToString() => _length == 0 ? "" : Encoding.ASCII.GetString(_arr, _index, _length); /// - public override bool Equals(object? other) => other is AsciiHash hash && Equals(hash); + public override bool Equals(object? obj) => obj is AsciiHash hash && Equals(hash); /// [CLSCompliant(false)] public bool Equals(in AsciiHash other) { - return (_length == other.Length & _hashCS == other._hashCS) + return ((_length == other.Length) & (_hashCS == other._hashCS)) && (_length <= MaxBytesHashed || Span.SequenceEqual(other.Span)); } @@ -65,7 +65,7 @@ public bool IsCS(ReadOnlySpan value) { var cs = HashCS(value); var len = _length; - if (cs != _hashCS | value.Length != len) return false; + if ((cs != _hashCS) | (value.Length != len)) return false; return len <= MaxBytesHashed || Span.SequenceEqual(value); } @@ -73,7 +73,7 @@ public bool IsCI(ReadOnlySpan value) { var uc = HashUC(value); var len = _length; - if (uc != _hashUC | value.Length != len) return false; + if ((uc != _hashUC) | (value.Length != len)) return false; return len <= MaxBytesHashed || SequenceEqualsCI(Span, value); } diff --git a/src/RESPite/Shared/AsciiHash.cs b/src/RESPite/Shared/AsciiHash.cs index 15164c4faa..3fa732343f 100644 --- a/src/RESPite/Shared/AsciiHash.cs +++ b/src/RESPite/Shared/AsciiHash.cs @@ -106,7 +106,7 @@ public static unsafe bool SequenceEqualsCI(ReadOnlySpan first, ReadOnlySpa { byte x = firstPtr[i]; var xCI = x & CS_MASK; - if (xCI >= 'A' & xCI <= 'Z') + if ((xCI >= 'A') & (xCI <= 'Z')) { // alpha mismatch if (xCI != (secondPtr[i] & CS_MASK)) return false; @@ -171,7 +171,7 @@ public static unsafe bool SequenceEqualsCI(ReadOnlySpan first, ReadOnlySpa { int x = (byte)firstPtr[i]; var xCI = x & CS_MASK; - if (xCI >= 'A' & xCI <= 'Z') + if ((xCI >= 'A') & (xCI <= 'Z')) { // alpha mismatch if (xCI != (secondPtr[i] & CS_MASK)) return false; @@ -206,7 +206,7 @@ public static unsafe bool SequenceEqualsCI(ReadOnlySpan first, ReadOnlySpa { int x = (byte)firstPtr[i]; var xCI = x & CS_MASK; - if (xCI >= 'A' & xCI <= 'Z') + if ((xCI >= 'A') & (xCI <= 'Z')) { // alpha mismatch if (xCI != (secondPtr[i] & CS_MASK)) return false; diff --git a/src/StackExchange.Redis/ArrayGrepRequest.cs b/src/StackExchange.Redis/ArrayGrepRequest.cs index bf9e34f8fa..7f00cf147e 100644 --- a/src/StackExchange.Redis/ArrayGrepRequest.cs +++ b/src/StackExchange.Redis/ArrayGrepRequest.cs @@ -59,7 +59,10 @@ private void SetFlag(LocalFlags flag, bool value) /// public RedisArrayIndex? Start { - get => GetFlag(LocalFlags.StartSpecified) ? _start : null; + get + { + return GetFlag(LocalFlags.StartSpecified) ? _start : null; + } set { if (value.HasValue) @@ -84,7 +87,10 @@ public RedisArrayIndex? Start /// public RedisArrayIndex? End { - get => GetFlag(LocalFlags.EndSpecified) ? _end : null; + get + { + return GetFlag(LocalFlags.EndSpecified) ? _end : null; + } set { if (value.HasValue) @@ -110,7 +116,10 @@ public RedisArrayIndex? End /// Corresponds to the LIMIT parameter. public long? Limit { - get => GetFlag(LocalFlags.LimitSpecified) ? _limit : null; + get + { + return GetFlag(LocalFlags.LimitSpecified) ? _limit : null; + } set { if (value.HasValue) diff --git a/src/StackExchange.Redis/Availability/CircuitBreaker.cs b/src/StackExchange.Redis/Availability/CircuitBreaker.cs index ff232cf7b5..4b91a66753 100644 --- a/src/StackExchange.Redis/Availability/CircuitBreaker.cs +++ b/src/StackExchange.Redis/Availability/CircuitBreaker.cs @@ -77,11 +77,11 @@ public CircuitBreaker Create() if (MetricsWindowSize <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(MetricsWindowSize), MetricsWindowSize, "A positive window is required."); if (MetricsWindowSize.TotalSeconds > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(MetricsWindowSize), MetricsWindowSize, "The window is too large."); - if ((FailureRateThreshold is DefaultFailureRateThreshold + if (((FailureRateThreshold is DefaultFailureRateThreshold) #if NET8_0_OR_GREATER - & TimeProvider is null + & (TimeProvider is null) #endif - & MinimumNumberOfFailures is DefaultMinimumNumberOfFailures) + & (MinimumNumberOfFailures is DefaultMinimumNumberOfFailures)) && MetricsWindowSize == DefaultMetricsWindowSize) return DefaultInstance; @@ -181,7 +181,7 @@ private sealed class NulAccumulator : Accumulator { public static readonly NulAccumulator AccumulatorInstance = new(); private NulAccumulator() { } - public override void ObserveResult(in FaultContext context) { } + public override void ObserveResult(in FaultContext fault) { } public override bool IsHealthy() => true; public override void Reset() { } } @@ -298,7 +298,7 @@ public void Reset() } } - public override void ObserveResult(in FaultContext result) + public override void ObserveResult(in FaultContext fault) { // which time-slice are we in, and where does it live in the ring? long epoch = breaker.GetEpoch(); @@ -311,7 +311,7 @@ public override void ObserveResult(in FaultContext result) // only getting results one at a time, so we shouldn't be over-stomping much *anyway* Span buckets = _buckets; // *not* a payload copy; this is in-place over the data ref Bucket bucket = ref buckets[index]; - bucket.Count(epoch, success: !result.IsFault); + bucket.Count(epoch, success: !fault.IsFault); } public override bool IsHealthy() => Evaluate(breaker.GetEpoch()); @@ -336,7 +336,7 @@ private bool Evaluate(long epoch) } // don't act until we've seen enough failures to be statistically meaningful - if (total is 0 | failures < breaker._minimumNumberOfFailures) + if ((total is 0) | (failures < breaker._minimumNumberOfFailures)) { return true; } diff --git a/src/StackExchange.Redis/Availability/FaultContext.cs b/src/StackExchange.Redis/Availability/FaultContext.cs index 3c43f10f8c..7ec643082e 100644 --- a/src/StackExchange.Redis/Availability/FaultContext.cs +++ b/src/StackExchange.Redis/Availability/FaultContext.cs @@ -53,7 +53,7 @@ public FaultContext(Exception fault) NotApplied = IsKnownNotApplied(kind, status); - if (kind is not RedisErrorKind.None & _connectionFailureType is ConnectionFailureType.None) + if ((kind is not RedisErrorKind.None) & (_connectionFailureType is ConnectionFailureType.None)) { // fill in some blanks switch (kind) diff --git a/src/StackExchange.Redis/Availability/HealthCheck.Execute.cs b/src/StackExchange.Redis/Availability/HealthCheck.Execute.cs index 9869d63a9c..13ca8694df 100644 --- a/src/StackExchange.Redis/Availability/HealthCheck.Execute.cs +++ b/src/StackExchange.Redis/Availability/HealthCheck.Execute.cs @@ -11,9 +11,11 @@ public sealed partial class HealthCheck /// Evaluate the health of the specified multiplexer, by evaluating all endpoints. /// public Task CheckHealthAsync(IConnectionMultiplexer multiplexer) - => !IsEnabled ? HealthCheckProbe.InconclusiveTask - : multiplexer.IsConnected ? CheckHealthCoreAsync(multiplexer) - : HealthCheckProbe.UnhealthyTask; + => !IsEnabled + ? HealthCheckProbe.InconclusiveTask + : multiplexer.IsConnected + ? CheckHealthCoreAsync(multiplexer) + : HealthCheckProbe.UnhealthyTask; private async Task CheckHealthCoreAsync(IConnectionMultiplexer multiplexer) { @@ -171,9 +173,11 @@ internal static void PutReusablePending(ref Task[]? field, re /// Evaluate the health of an endpoint. /// public Task CheckHealthAsync(IServer server) - => !IsEnabled ? HealthCheckProbe.InconclusiveTask - : server.IsConnected ? CheckHealthCoreAsync(server) - : HealthCheckProbe.UnhealthyTask; + => !IsEnabled + ? HealthCheckProbe.InconclusiveTask + : server.IsConnected + ? CheckHealthCoreAsync(server) + : HealthCheckProbe.UnhealthyTask; private async Task CheckHealthCoreAsync(IServer server) { diff --git a/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs b/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs index 82b8ebc4d8..987f3ea936 100644 --- a/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs +++ b/src/StackExchange.Redis/Availability/MultiGroupMultiplexer.cs @@ -367,9 +367,11 @@ internal GroupConnectionChangedEventArgs.ChangeType UpdateState(HealthCheckResul var oldConnected = IsConnected; IsConnected = isConnected; - return isConnected == oldConnected ? GroupConnectionChangedEventArgs.ChangeType.Unknown - : isConnected ? GroupConnectionChangedEventArgs.ChangeType.Reconnected - : GroupConnectionChangedEventArgs.ChangeType.Disconnected; + return isConnected == oldConnected + ? GroupConnectionChangedEventArgs.ChangeType.Unknown + : isConnected + ? GroupConnectionChangedEventArgs.ChangeType.Reconnected + : GroupConnectionChangedEventArgs.ChangeType.Disconnected; } internal void UpdateLatency() @@ -643,7 +645,7 @@ static bool TryGetHealthCheck(object? target, out TimeSpan interval) // note the interval is a group-level concern (how often we re-evaluate the active // member), not a property of any individual health-check interval = typed._options.HealthCheckInterval; - return interval > TimeSpan.Zero & interval != TimeSpan.MaxValue; + return (interval > TimeSpan.Zero) & (interval != TimeSpan.MaxValue); } interval = TimeSpan.Zero; @@ -1249,7 +1251,7 @@ public ISubscriber GetSubscriber(object? asyncState = null) public IDatabase GetDatabase(int db = -1, object? asyncState = null) { - if (asyncState is null & db >= -1 & db <= ConnectionMultiplexer.MaxCachedDatabaseInstance) + if ((asyncState is null) & (db >= -1) & (db <= ConnectionMultiplexer.MaxCachedDatabaseInstance)) { return _databases[db + 1] ??= new MultiGroupDatabase(this, db, null); } diff --git a/src/StackExchange.Redis/Availability/RetryController.cs b/src/StackExchange.Redis/Availability/RetryController.cs index a47d79bbcc..f055d0b4e8 100644 --- a/src/StackExchange.Redis/Availability/RetryController.cs +++ b/src/StackExchange.Redis/Availability/RetryController.cs @@ -62,7 +62,7 @@ public Task WatchConflictDelayAsync() /// Whether it is ever worth capturing the next-failover token: only when there is more than one /// attempt and the failover threshold sits below the attempt cap. /// - public bool TracksFailover => _maxAttempts > 1 & _maxBeforeFailover < _maxAttempts; + public bool TracksFailover => (_maxAttempts > 1) & (_maxBeforeFailover < _maxAttempts); public bool CanRetry( int attempt, @@ -100,7 +100,7 @@ public bool CanRetry( // by count, we should really switch over to the failover now; is failover available *and* are we allowed? delay = failover; failover = CancellationToken.None; // only failover once - return delay.CanBeCanceled & (policy & RetryResult.FailoverServer) != 0; + return delay.CanBeCanceled & ((policy & RetryResult.FailoverServer) != 0); } // can we pause and retry on the same server? diff --git a/src/StackExchange.Redis/BufferReader.cs b/src/StackExchange.Redis/BufferReader.cs index 22b36ccb64..8b4d2b4b5b 100644 --- a/src/StackExchange.Redis/BufferReader.cs +++ b/src/StackExchange.Redis/BufferReader.cs @@ -78,7 +78,8 @@ public ConsumeResult TryConsumeCRLF() default: var offset = OffsetThisSpan; var result = _current[offset++] == (byte)'\r' && _current[offset] == (byte)'\n' - ? ConsumeResult.Success : ConsumeResult.Failure; + ? ConsumeResult.Success + : ConsumeResult.Failure; Consume(2); return result; } diff --git a/src/StackExchange.Redis/Configuration/AzureManagedRedisOptionsProvider.cs b/src/StackExchange.Redis/Configuration/AzureManagedRedisOptionsProvider.cs index 1ab612bea7..31177de715 100644 --- a/src/StackExchange.Redis/Configuration/AzureManagedRedisOptionsProvider.cs +++ b/src/StackExchange.Redis/Configuration/AzureManagedRedisOptionsProvider.cs @@ -59,7 +59,7 @@ private bool IsHostInDomains(string hostName, string[] domains) } /// - public override Task AfterConnectAsync(ConnectionMultiplexer muxer, Action log) + public override Task AfterConnectAsync(ConnectionMultiplexer multiplexer, Action log) => Task.CompletedTask; /// diff --git a/src/StackExchange.Redis/Configuration/AzureOptionsProvider.cs b/src/StackExchange.Redis/Configuration/AzureOptionsProvider.cs index ee577eb592..0f9810f1c4 100644 --- a/src/StackExchange.Redis/Configuration/AzureOptionsProvider.cs +++ b/src/StackExchange.Redis/Configuration/AzureOptionsProvider.cs @@ -61,8 +61,8 @@ private bool IsHostInDomains(string hostName, string[] domains) } /// - public override Task AfterConnectAsync(ConnectionMultiplexer muxer, Action log) - => AzureMaintenanceEvent.AddListenerAsync(muxer, log); + public override Task AfterConnectAsync(ConnectionMultiplexer multiplexer, Action log) + => AzureMaintenanceEvent.AddListenerAsync(multiplexer, log); /// public override bool GetDefaultSsl(EndPointCollection endPoints) diff --git a/src/StackExchange.Redis/Configuration/LoggingTunnel.cs b/src/StackExchange.Redis/Configuration/LoggingTunnel.cs index 3fb023c9f8..5321c49a0a 100644 --- a/src/StackExchange.Redis/Configuration/LoggingTunnel.cs +++ b/src/StackExchange.Redis/Configuration/LoggingTunnel.cs @@ -391,14 +391,16 @@ private void CreateLogFiles(EndPoint endpoint, ConnectionType connectionType, ou /// public override ValueTask BeforeSocketConnectAsync(EndPoint endPoint, ConnectionType connectionType, Socket? socket, CancellationToken cancellationToken) { - return _tail is null ? base.BeforeSocketConnectAsync(endPoint, connectionType, socket, cancellationToken) + return _tail is null + ? base.BeforeSocketConnectAsync(endPoint, connectionType, socket, cancellationToken) : _tail.BeforeSocketConnectAsync(endPoint, connectionType, socket, cancellationToken); } /// public override ValueTask GetSocketConnectEndpointAsync(EndPoint endpoint, CancellationToken cancellationToken) { - return _tail is null ? base.GetSocketConnectEndpointAsync(endpoint, cancellationToken) + return _tail is null + ? base.GetSocketConnectEndpointAsync(endpoint, cancellationToken) : _tail.GetSocketConnectEndpointAsync(endpoint, cancellationToken); } diff --git a/src/StackExchange.Redis/ConfigurationOptions.cs b/src/StackExchange.Redis/ConfigurationOptions.cs index 90e12c560a..45e2404d34 100644 --- a/src/StackExchange.Redis/ConfigurationOptions.cs +++ b/src/StackExchange.Redis/ConfigurationOptions.cs @@ -406,7 +406,10 @@ private void SetWithValue(OptionFlags hasValue, ref T storage, T value) where /// public DefaultOptionsProvider Defaults { - get => defaultOptions ??= DefaultOptionsProvider.GetProvider(EndPoints); + get + { + return defaultOptions ??= DefaultOptionsProvider.GetProvider(EndPoints); + } set { defaultOptions = value; @@ -710,7 +713,10 @@ public CommandMap CommandMap Proxy.Envoyproxy => CommandMap.Envoyproxy, _ => CommandMap.Default, }; - set => commandMap = value ?? throw new ArgumentNullException(nameof(value)); + set + { + commandMap = value ?? throw new ArgumentNullException(nameof(value)); + } } /// @@ -746,7 +752,10 @@ public int ConnectTimeout var defaultTimeout = Defaults.ConnectTimeout; return defaultTimeout.HasValue ? (int)defaultTimeout.GetValueOrDefault().TotalMilliseconds : Math.Max(5000, SyncTimeout); } - set => SetWithValue(OptionFlags.ConnectTimeoutHasValue, ref connectTimeout, value); + set + { + SetWithValue(OptionFlags.ConnectTimeoutHasValue, ref connectTimeout, value); + } } /// @@ -1306,7 +1315,8 @@ public string ToString(bool includePassword) commandMap?.AppendDeltas(sb); return sb.ToString(); - static string FormatProtocol(RedisProtocol protocol) => protocol switch { + static string FormatProtocol(RedisProtocol protocol) => protocol switch + { RedisProtocol.Resp2 => "resp2", RedisProtocol.Resp3 => "resp3", _ => protocol.ToString(), @@ -1686,7 +1696,10 @@ public MaintenanceEndpointType MaintenanceMovingEndpointType get => HasValue(OptionFlags.MaintenanceMovingEndpointTypeHasValue) ? _maintenanceMovingEndpointType : Defaults.MaintenanceMovingEndpointType; - set => SetWithValue(OptionFlags.MaintenanceMovingEndpointTypeHasValue, ref _maintenanceMovingEndpointType, value); + set + { + SetWithValue(OptionFlags.MaintenanceMovingEndpointTypeHasValue, ref _maintenanceMovingEndpointType, value); + } } /// @@ -1720,7 +1733,10 @@ public TimeSpan MaintenanceRelaxedWindowMax get => HasValue(OptionFlags.MaintenanceRelaxedWindowMaxHasValue) ? _maintenanceRelaxedWindowMax : Defaults.MaintenanceRelaxedWindowMax ?? Multiply(MaintenanceRelaxedTimeout, 3); - set => SetWithValue(OptionFlags.MaintenanceRelaxedWindowMaxHasValue, ref _maintenanceRelaxedWindowMax, value); + set + { + SetWithValue(OptionFlags.MaintenanceRelaxedWindowMaxHasValue, ref _maintenanceRelaxedWindowMax, value); + } } /// @@ -1739,7 +1755,10 @@ public TimeSpan MaintenancePostEventRelaxedDuration get => HasValue(OptionFlags.MaintenancePostEventRelaxedDurationHasValue) ? _maintenancePostEventRelaxedDuration : Defaults.MaintenancePostEventRelaxedDuration ?? Multiply(MaintenanceRelaxedTimeout, 2); - set => SetWithValue(OptionFlags.MaintenancePostEventRelaxedDurationHasValue, ref _maintenancePostEventRelaxedDuration, value); + set + { + SetWithValue(OptionFlags.MaintenancePostEventRelaxedDurationHasValue, ref _maintenancePostEventRelaxedDuration, value); + } } // TimeSpan * int is netstandard2.1+, so this is ticks arithmetic to keep the down-level TFMs building diff --git a/src/StackExchange.Redis/ConnectionMultiplexer.FeatureFlags.cs b/src/StackExchange.Redis/ConnectionMultiplexer.FeatureFlags.cs index b22d709f3e..41272197de 100644 --- a/src/StackExchange.Redis/ConnectionMultiplexer.FeatureFlags.cs +++ b/src/StackExchange.Redis/ConnectionMultiplexer.FeatureFlags.cs @@ -84,12 +84,12 @@ public static bool GetFeatureFlag(string flag) /// there is no separate subscription connection, so asking about answers /// about the shared one. /// - bool? IInternalConnectionMultiplexer.IsSyncReader(EndPoint endpoint, ConnectionType connectionType) - => GetPhysical(endpoint, connectionType)?.IsSyncReader; + bool? IInternalConnectionMultiplexer.IsSyncReader(EndPoint endPoint, ConnectionType type) + => GetPhysical(endPoint, type)?.IsSyncReader; /// As IsSyncReader, for the writer. - bool? IInternalConnectionMultiplexer.IsSyncWriter(EndPoint endpoint, ConnectionType connectionType) - => GetPhysical(endpoint, connectionType)?.IsSyncWriter; + bool? IInternalConnectionMultiplexer.IsSyncWriter(EndPoint endPoint, ConnectionType type) + => GetPhysical(endPoint, type)?.IsSyncWriter; private PhysicalConnection? GetPhysical(EndPoint endpoint, ConnectionType connectionType) => TryResolveServerEndPoint(endpoint)?.GetBridge(connectionType, create: false)?.Physical; diff --git a/src/StackExchange.Redis/ConnectionMultiplexer.cs b/src/StackExchange.Redis/ConnectionMultiplexer.cs index 14b2815b03..50c57162ac 100644 --- a/src/StackExchange.Redis/ConnectionMultiplexer.cs +++ b/src/StackExchange.Redis/ConnectionMultiplexer.cs @@ -95,8 +95,8 @@ public sealed partial class ConnectionMultiplexer : IInternalConnectionMultiplex private int _activeHeartbeatErrors, lastHeartbeatTicks; internal long LastHeartbeatSecondsAgo => pulse is null - ? -1 - : unchecked(Environment.TickCount - Volatile.Read(ref lastHeartbeatTicks)) / 1000; + ? -1 + : unchecked(Environment.TickCount - Volatile.Read(ref lastHeartbeatTicks)) / 1000; private static int lastGlobalHeartbeatTicks = Environment.TickCount; internal static long LastGlobalHeartbeatSecondsAgo => @@ -1003,7 +1003,8 @@ ServerEndPoint IInternalConnectionMultiplexer.GetServerEndPoint(EndPoint endpoin // a retired server may still be referenced by an alias for a moment; never hand one back, or the // caller receives something whose bridges are gone return _serverIdentities.TryGetValue(endpoint, out var byIdentity) && !byIdentity.IsDisposed - ? byIdentity : null; + ? byIdentity + : null; } // bumped once per applied cluster topology; absence is measured in these rather than in time, so a @@ -1483,7 +1484,8 @@ public IDatabase GetDatabase(int db = -1, object? asyncState = null) // if there's no async-state, and the DB is suitable, we can hand out a re-used instance return (asyncState == null && db <= MaxCachedDatabaseInstance) - ? GetCachedDatabaseInstance(db) : new RedisDatabase(this, db, asyncState); + ? GetCachedDatabaseInstance(db) + : new RedisDatabase(this, db, asyncState); } // DB zero is stored separately, since 0-only is a massively common use-case @@ -1565,8 +1567,8 @@ public IServer GetServer(string host, int port, object? asyncState = null) => /// The async state to pass into the resulting . public IServer GetServer(string hostAndPort, object? asyncState = null) => Format.TryParseEndPoint(hostAndPort, out var ep) - ? GetServer(ep, asyncState) - : throw new ArgumentException($"The specified host and port could not be parsed: {hostAndPort}", nameof(hostAndPort)); + ? GetServer(ep, asyncState) + : throw new ArgumentException($"The specified host and port could not be parsed: {hostAndPort}", nameof(hostAndPort)); /// /// Obtain a configuration API for an individual server. @@ -3020,8 +3022,8 @@ private Task[] QuitAllServers() return quits; } - long? IInternalConnectionMultiplexer.GetConnectionId(EndPoint endpoint, ConnectionType type) - => TryResolveServerEndPoint(endpoint)?.GetBridge(type)?.ConnectionId; + long? IInternalConnectionMultiplexer.GetConnectionId(EndPoint endPoint, ConnectionType type) + => TryResolveServerEndPoint(endPoint)?.GetBridge(type)?.ConnectionId; internal uint UpdateLatency() { diff --git a/src/StackExchange.Redis/CursorEnumerable.cs b/src/StackExchange.Redis/CursorEnumerable.cs index 670ab178d5..5f05e12ba0 100644 --- a/src/StackExchange.Redis/CursorEnumerable.cs +++ b/src/StackExchange.Redis/CursorEnumerable.cs @@ -108,7 +108,7 @@ public T Current [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - Debug.Assert(_pageOffset >= 0 & _pageOffset < _pageCount & _pageOversized!.Length >= _pageCount); + Debug.Assert((_pageOffset >= 0) & (_pageOffset < _pageCount) & (_pageOversized!.Length >= _pageCount)); return _pageOversized[_pageOffset]; } } diff --git a/src/StackExchange.Redis/Format.cs b/src/StackExchange.Redis/Format.cs index 8907182dfc..0c4e33272d 100644 --- a/src/StackExchange.Redis/Format.cs +++ b/src/StackExchange.Redis/Format.cs @@ -233,10 +233,10 @@ internal static bool TryParseUInt64(string s, out ulong value) => ulong.TryParse(s, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out value); internal static bool TryParseUInt64(ReadOnlySpan s, out ulong value) => - Utf8Parser.TryParse(s, out value, out int bytes, standardFormat: 'D') & bytes == s.Length; + Utf8Parser.TryParse(s, out value, out int bytes, standardFormat: 'D') & (bytes == s.Length); internal static bool TryParseInt64(ReadOnlySpan s, out long value) => - Utf8Parser.TryParse(s, out value, out int bytes, standardFormat: 'D') & bytes == s.Length; + Utf8Parser.TryParse(s, out value, out int bytes, standardFormat: 'D') & (bytes == s.Length); internal static bool CouldBeInteger(string s) { @@ -245,18 +245,18 @@ internal static bool CouldBeInteger(string s) for (int i = isSigned ? 1 : 0; i < s.Length; i++) { char c = s[i]; - if (c < '0' | c > '9') return false; + if ((c < '0') | (c > '9')) return false; } return true; } internal static bool CouldBeInteger(ReadOnlySpan s) { - if (s.IsEmpty | s.Length > Format.MaxInt64TextLen) return false; + if (s.IsEmpty | (s.Length > Format.MaxInt64TextLen)) return false; bool isSigned = s[0] == '-'; for (int i = isSigned ? 1 : 0; i < s.Length; i++) { byte c = s[i]; - if (c < (byte)'0' | c > (byte)'9') return false; + if ((c < (byte)'0') | (c > (byte)'9')) return false; } return true; } @@ -281,7 +281,7 @@ internal static bool TryParseDouble(ReadOnlySpan s, out double value) case 4 when s[0] == '-' && TryParseInfNaN(s.Slice(1), false, out value): return true; } - return Utf8Parser.TryParse(s, out value, out int bytes) & bytes == s.Length; + return Utf8Parser.TryParse(s, out value, out int bytes) & (bytes == s.Length); static bool TryParseInfNaN(ReadOnlySpan s, bool positive, out double value) { diff --git a/src/StackExchange.Redis/Interfaces/IDatabase.VectorSets.cs b/src/StackExchange.Redis/Interfaces/IDatabase.VectorSets.cs index 28f45851fe..66bebc55bb 100644 --- a/src/StackExchange.Redis/Interfaces/IDatabase.VectorSets.cs +++ b/src/StackExchange.Redis/Interfaces/IDatabase.VectorSets.cs @@ -4,9 +4,9 @@ // ReSharper disable once CheckNamespace namespace StackExchange.Redis; -/// -/// Describes functionality that is common to both standalone redis servers and redis clusters. -/// +/// +/// Vector set operations. +/// public partial interface IDatabase { // Vector Set operations diff --git a/src/StackExchange.Redis/Interfaces/IDatabaseAsync.VectorSets.cs b/src/StackExchange.Redis/Interfaces/IDatabaseAsync.VectorSets.cs index 64e8e38789..ffb04f8ebd 100644 --- a/src/StackExchange.Redis/Interfaces/IDatabaseAsync.VectorSets.cs +++ b/src/StackExchange.Redis/Interfaces/IDatabaseAsync.VectorSets.cs @@ -5,9 +5,9 @@ // ReSharper disable once CheckNamespace namespace StackExchange.Redis; -/// -/// Describes functionality that is common to both standalone redis servers and redis clusters. -/// +/// +/// Vector set operations. +/// public partial interface IDatabaseAsync { // Vector Set operations diff --git a/src/StackExchange.Redis/KeyNotification.cs b/src/StackExchange.Redis/KeyNotification.cs index 5550fe6e04..76bf877667 100644 --- a/src/StackExchange.Redis/KeyNotification.cs +++ b/src/StackExchange.Redis/KeyNotification.cs @@ -254,8 +254,9 @@ public int Database if (end <= 0) return -1; span = span.Slice(0, end); - return Utf8Parser.TryParse(span, out int database, out var bytes) - && bytes == end ? database : -1; + return Utf8Parser.TryParse(span, out int database, out var bytes) && bytes == end + ? database + : -1; } } @@ -276,7 +277,7 @@ public RedisKey GetKey() case KeyNotificationKind.KeyEvent: // Channel contains the event-type, payload contains the key byte[]? blob = _value; - if (_keyOffset != 0 & blob is not null) + if ((_keyOffset != 0) & (blob is not null)) { return blob.AsSpan(_keyOffset).ToArray(); } diff --git a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs index c420b7bdca..8584b2ceea 100644 --- a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs +++ b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixed.cs @@ -562,8 +562,8 @@ public Task SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, Comma public Task SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) => Inner.SortedSetAddAsync(ToInner(key), values, when, flags); - public Task SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, SortedSetWhen updateWhen = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => - Inner.SortedSetAddAsync(ToInner(key), values, updateWhen, flags); + public Task SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, SortedSetWhen when = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => + Inner.SortedSetAddAsync(ToInner(key), values, when, flags); public Task SortedSetAddAsync(RedisKey key, RedisValue member, double score, CommandFlags flags) => Inner.SortedSetAddAsync(ToInner(key), member, score, flags); @@ -571,8 +571,8 @@ public Task SortedSetAddAsync(RedisKey key, RedisValue member, double scor public Task SortedSetAddAsync(RedisKey key, RedisValue member, double score, When when = When.Always, CommandFlags flags = CommandFlags.None) => Inner.SortedSetAddAsync(ToInner(key), member, score, when, flags); - public Task SortedSetAddAsync(RedisKey key, RedisValue member, double score, SortedSetWhen updateWhen = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => - Inner.SortedSetAddAsync(ToInner(key), member, score, updateWhen, flags); + public Task SortedSetAddAsync(RedisKey key, RedisValue member, double score, SortedSetWhen when = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => + Inner.SortedSetAddAsync(ToInner(key), member, score, when, flags); public Task SortedSetCombineAsync(SetOperation operation, RedisKey[] keys, double[]? weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) => Inner.SortedSetCombineAsync(operation, ToInner(keys), weights, aggregate, flags); @@ -670,11 +670,11 @@ public Task SortedSetRemoveRangeByValueAsync(RedisKey key, RedisValue min, public IAsyncEnumerable SortedSetScanAsync(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags) => Inner.SortedSetScanAsync(ToInner(key), pattern, pageSize, cursor, pageOffset, flags); - public Task SortedSetUpdateAsync(RedisKey key, SortedSetEntry[] values, SortedSetWhen updateWhen = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => - Inner.SortedSetUpdateAsync(ToInner(key), values, updateWhen, flags); + public Task SortedSetUpdateAsync(RedisKey key, SortedSetEntry[] values, SortedSetWhen when = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => + Inner.SortedSetUpdateAsync(ToInner(key), values, when, flags); - public Task SortedSetUpdateAsync(RedisKey key, RedisValue member, double score, SortedSetWhen updateWhen = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => - Inner.SortedSetUpdateAsync(ToInner(key), member, score, updateWhen, flags); + public Task SortedSetUpdateAsync(RedisKey key, RedisValue member, double score, SortedSetWhen when = SortedSetWhen.Always, CommandFlags flags = CommandFlags.None) => + Inner.SortedSetUpdateAsync(ToInner(key), member, score, when, flags); public Task SortedSetPopAsync(RedisKey key, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) => Inner.SortedSetPopAsync(ToInner(key), order, flags); @@ -709,17 +709,17 @@ public Task StreamAddAsync(RedisKey key, RedisValue streamField, Red public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId, int? maxLength, bool useApproximateMaxLength, CommandFlags flags) => Inner.StreamAddAsync(ToInner(key), streamPairs, messageId, maxLength, useApproximateMaxLength, flags); - public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAddAsync(ToInner(key), streamField, streamValue, messageId, maxLength, useApproximateMaxLength, limit, mode, flags); + public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAddAsync(ToInner(key), streamField, streamValue, messageId, maxLength, useApproximateMaxLength, limit, trimMode, flags); - public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAddAsync(ToInner(key), streamPairs, messageId, maxLength, useApproximateMaxLength, limit, mode, flags); + public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAddAsync(ToInner(key), streamPairs, messageId, maxLength, useApproximateMaxLength, limit, trimMode, flags); - public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAddAsync(ToInner(key), streamField, streamValue, idempotentId, maxLength, useApproximateMaxLength, limit, mode, flags); + public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAddAsync(ToInner(key), streamField, streamValue, idempotentId, maxLength, useApproximateMaxLength, limit, trimMode, flags); - public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAddAsync(ToInner(key), streamPairs, idempotentId, maxLength, useApproximateMaxLength, limit, mode, flags); + public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAddAsync(ToInner(key), streamPairs, idempotentId, maxLength, useApproximateMaxLength, limit, trimMode, flags); public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamAddOptions options, CommandFlags flags = CommandFlags.None) => Inner.StreamAddAsync(ToInner(key), streamField, streamValue, options, flags); diff --git a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixedDatabase.cs b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixedDatabase.cs index 3353c0d6c0..8ca3bca485 100644 --- a/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixedDatabase.cs +++ b/src/StackExchange.Redis/KeyspaceIsolation/KeyPrefixedDatabase.cs @@ -583,8 +583,8 @@ public RedisValue[] SortedSetRangeByRank(RedisKey key, long start = 0, long stop Inner.SortedSetRangeByRank(ToInner(key), start, stop, order, flags); public long SortedSetRangeAndStore( - RedisKey destinationKey, RedisKey sourceKey, + RedisKey destinationKey, RedisValue start, RedisValue stop, SortedSetOrder sortedSetOrder = SortedSetOrder.ByRank, @@ -673,17 +673,17 @@ public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue str public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId, int? maxLength, bool useApproximateMaxLength, CommandFlags flags) => Inner.StreamAdd(ToInner(key), streamPairs, messageId, maxLength, useApproximateMaxLength, flags); - public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAdd(ToInner(key), streamField, streamValue, messageId, maxLength, useApproximateMaxLength, limit, mode, flags); + public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAdd(ToInner(key), streamField, streamValue, messageId, maxLength, useApproximateMaxLength, limit, trimMode, flags); - public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAdd(ToInner(key), streamPairs, messageId, maxLength, useApproximateMaxLength, limit, mode, flags); + public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAdd(ToInner(key), streamPairs, messageId, maxLength, useApproximateMaxLength, limit, trimMode, flags); - public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAdd(ToInner(key), streamField, streamValue, idempotentId, maxLength, useApproximateMaxLength, limit, mode, flags); + public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAdd(ToInner(key), streamField, streamValue, idempotentId, maxLength, useApproximateMaxLength, limit, trimMode, flags); - public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => - Inner.StreamAdd(ToInner(key), streamPairs, idempotentId, maxLength, useApproximateMaxLength, limit, mode, flags); + public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) => + Inner.StreamAdd(ToInner(key), streamPairs, idempotentId, maxLength, useApproximateMaxLength, limit, trimMode, flags); public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamAddOptions options, CommandFlags flags = CommandFlags.None) => Inner.StreamAdd(ToInner(key), streamField, streamValue, options, flags); diff --git a/src/StackExchange.Redis/Maintenance/MaintenanceFaultSurface.cs b/src/StackExchange.Redis/Maintenance/MaintenanceFaultSurface.cs index e7bb2044e8..84c69d943a 100644 --- a/src/StackExchange.Redis/Maintenance/MaintenanceFaultSurface.cs +++ b/src/StackExchange.Redis/Maintenance/MaintenanceFaultSurface.cs @@ -4,10 +4,10 @@ namespace StackExchange.Redis; -/// +/// /// Carries maintenance context on the faults a disruption can cause, so that a timeout during an announced /// migration is distinguishable from an ordinary one. -/// +/// /// /// This follows the established pattern on these types - Commandstatus and Flags on /// , FailureType on - rather diff --git a/src/StackExchange.Redis/MessageWriter.cs b/src/StackExchange.Redis/MessageWriter.cs index 82870f1a93..0949c44ae8 100644 --- a/src/StackExchange.Redis/MessageWriter.cs +++ b/src/StackExchange.Redis/MessageWriter.cs @@ -213,7 +213,7 @@ internal static void WriteMultiBulkHeader(IBufferWriter writer, long count internal static void WriteMultiBulkHeader(IBufferWriter writer, long count, RespPrefix prefix) { - if ((prefix is RespPrefix.Map or RespPrefix.Attribute) & count > 0) + if ((prefix is RespPrefix.Map or RespPrefix.Attribute) & (count > 0)) { if ((count & 1) != 0) Throw(prefix, count); count >>= 1; diff --git a/src/StackExchange.Redis/PhysicalBridge.cs b/src/StackExchange.Redis/PhysicalBridge.cs index 3ad0afb28e..ee3a7bfb2c 100644 --- a/src/StackExchange.Redis/PhysicalBridge.cs +++ b/src/StackExchange.Redis/PhysicalBridge.cs @@ -930,7 +930,7 @@ internal WriteResult WriteMessageTakingWriteLockSync(PhysicalConnection physical var result = WriteMessageInsideLock(physical, message); - if (result == WriteResult.Success & message.IsFlushRequiredSync) + if ((result == WriteResult.Success) & message.IsFlushRequiredSync) { physical.Flush(); } @@ -1433,7 +1433,7 @@ internal ValueTask WriteMessageTakingWriteLockAsync(PhysicalConnect if (!gotLock) return new ValueTask(TimedOutBeforeWrite(message)); } var result = WriteMessageInsideLock(physical, message); - if (result == WriteResult.Success & message.IsFlushRequiredAsync) + if ((result == WriteResult.Success) & message.IsFlushRequiredAsync) { physical.Flush(); } diff --git a/src/StackExchange.Redis/PhysicalConnection.Read.cs b/src/StackExchange.Redis/PhysicalConnection.Read.cs index 8aca7e41cb..4fe44624fb 100644 --- a/src/StackExchange.Redis/PhysicalConnection.Read.cs +++ b/src/StackExchange.Redis/PhysicalConnection.Read.cs @@ -291,7 +291,7 @@ private bool CommitAndParseFrames(int bytesRead) Debug.Assert( state is { - IsComplete: true, TotalBytes: >= RespScanState.MinBytes, Prefix: not RespPrefix.None + IsComplete: true, TotalBytes: >= RespScanState.MinBytes, Prefix: not RespPrefix.None, }, "Invalid RESP read state"); @@ -340,7 +340,7 @@ state is Debug.Assert( state is { - IsComplete: true, TotalBytes: >= RespScanState.MinBytes, Prefix: not RespPrefix.None + IsComplete: true, TotalBytes: >= RespScanState.MinBytes, Prefix: not RespPrefix.None, }, "Invalid RESP read state"); @@ -442,7 +442,7 @@ private void OnResponseFrame(RespPrefix prefix, ReadOnlySpan frame, ref IM switch (prefix) { case RespPrefix.Push: // explicit RESP3 push message - case RespPrefix.Array when (_protocol is RedisProtocol.Resp2 & connectionType is ConnectionType.Subscription) + case RespPrefix.Array when ((_protocol is RedisProtocol.Resp2) & (connectionType is ConnectionType.Subscription)) && !IsArrayPong(frame): // could be a RESP2 pub/sub payload // out-of-band; pub/sub etc switch (OnOutOfBand(frame, ref memoryOwner)) diff --git a/src/StackExchange.Redis/Profiling/ProfiledCommand.cs b/src/StackExchange.Redis/Profiling/ProfiledCommand.cs index 84ea23f08b..ecaaee7b5e 100644 --- a/src/StackExchange.Redis/Profiling/ProfiledCommand.cs +++ b/src/StackExchange.Redis/Profiling/ProfiledCommand.cs @@ -120,11 +120,16 @@ public void SetCompleted() } } - public override string ToString() => -$@"{Command} (DB: {Db}, Flags: {Flags}) + public override string ToString() + { + var retransmission = RetransmissionOf != null + ? @" + RetransmissionOf = " + RetransmissionOf + : ""; + return $@"{Command} (DB: {Db}, Flags: {Flags}) EndPoint = {EndPoint} ({ConnectionType}) Created = {CommandCreated:HH:mm:ss.ffff} - ElapsedTime = {ElapsedTime.TotalMilliseconds} ms (CreationToEnqueued: {CreationToEnqueued.TotalMilliseconds} ms, EnqueuedToSending: {EnqueuedToSending.TotalMilliseconds} ms, SentToResponse: {SentToResponse.TotalMilliseconds} ms, ResponseToCompletion = {ResponseToCompletion.TotalMilliseconds} ms){(RetransmissionOf != null ? @" - RetransmissionOf = " + RetransmissionOf : "")}"; + ElapsedTime = {ElapsedTime.TotalMilliseconds} ms (CreationToEnqueued: {CreationToEnqueued.TotalMilliseconds} ms, EnqueuedToSending: {EnqueuedToSending.TotalMilliseconds} ms, SentToResponse: {SentToResponse.TotalMilliseconds} ms, ResponseToCompletion = {ResponseToCompletion.TotalMilliseconds} ms){retransmission}"; + } } } diff --git a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt index 8cc5c21b9a..6d203b53f8 100644 --- a/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt +++ b/src/StackExchange.Redis/PublicAPI/PublicAPI.Unshipped.txt @@ -33,3 +33,7 @@ static StackExchange.Redis.Availability.HealthCheckProbe.LagAware(StackExchange. StackExchange.Redis.Availability.LagAwareOptions.ClientCertificate.get -> System.Security.Cryptography.X509Certificates.X509Certificate2? StackExchange.Redis.Availability.LagAwareOptions.ClientCertificate.set -> void StackExchange.Redis.Availability.LagAwareOptions.SetUserPfxCertificate(string! userCertificatePath, string? password = null) -> void +*REMOVED*override StackExchange.Redis.Configuration.AzureManagedRedisOptionsProvider.AfterConnectAsync(StackExchange.Redis.ConnectionMultiplexer! muxer, System.Action! log) -> System.Threading.Tasks.Task! +override StackExchange.Redis.Configuration.AzureManagedRedisOptionsProvider.AfterConnectAsync(StackExchange.Redis.ConnectionMultiplexer! multiplexer, System.Action! log) -> System.Threading.Tasks.Task! +*REMOVED*override StackExchange.Redis.Configuration.AzureOptionsProvider.AfterConnectAsync(StackExchange.Redis.ConnectionMultiplexer! muxer, System.Action! log) -> System.Threading.Tasks.Task! +override StackExchange.Redis.Configuration.AzureOptionsProvider.AfterConnectAsync(StackExchange.Redis.ConnectionMultiplexer! multiplexer, System.Action! log) -> System.Threading.Tasks.Task! diff --git a/src/StackExchange.Redis/RedisChannel.cs b/src/StackExchange.Redis/RedisChannel.cs index b917a2a62c..a9c3c10bcc 100644 --- a/src/StackExchange.Redis/RedisChannel.cs +++ b/src/StackExchange.Redis/RedisChannel.cs @@ -476,7 +476,7 @@ private static Span AppendAndAdvance(Span target, scoped ReadOnlySpa private static RedisChannel BuildKeySpaceChannel(in RedisKey key, int? database, RedisChannelOptions options, ReadOnlySpan suffix, bool appendStar, bool allowKeyPatterns, bool subkey) { int fullKeyLength = key.TotalLength() + suffix.Length + (appendStar ? 1 : 0); - if (appendStar & (options & RedisChannelOptions.Pattern) == 0) throw new ArgumentNullException(nameof(key)); + if (appendStar & ((options & RedisChannelOptions.Pattern) == 0)) throw new ArgumentNullException(nameof(key)); if (fullKeyLength == 0) throw new ArgumentOutOfRangeException(nameof(key)); var db = AppendDatabase(stackalloc byte[DatabaseScratchBufferSize], database, options); diff --git a/src/StackExchange.Redis/RedisDatabase.cs b/src/StackExchange.Redis/RedisDatabase.cs index cfe24f7aab..3c9c289185 100644 --- a/src/StackExchange.Redis/RedisDatabase.cs +++ b/src/StackExchange.Redis/RedisDatabase.cs @@ -36,7 +36,8 @@ DatabaseFeatureFlags IInternalDatabaseAsync.GetFeatures(out string name) // to fold in their own flag. Cluster is intrinsic to the underlying connection, so it lives here. private protected virtual DatabaseFeatureFlags GetDatabaseFeatures() => multiplexer.ServerSelectionStrategy.ServerType == ServerType.Cluster - ? DatabaseFeatureFlags.Cluster : DatabaseFeatureFlags.None; + ? DatabaseFeatureFlags.Cluster + : DatabaseFeatureFlags.None; public IBatch CreateBatch(object? asyncState) { @@ -126,9 +127,9 @@ public Task GeoRemoveAsync(RedisKey key, RedisValue member, CommandFlags f return ExecuteSync(msg, ResultProcessor.NullableDouble); } - public Task GeoDistanceAsync(RedisKey key, RedisValue value0, RedisValue value1, GeoUnit unit = GeoUnit.Meters, CommandFlags flags = CommandFlags.None) + public Task GeoDistanceAsync(RedisKey key, RedisValue member1, RedisValue member2, GeoUnit unit = GeoUnit.Meters, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.GEODIST, key, value0, value1, StackExchange.Redis.GeoPosition.GetRedisUnit(unit)); + var msg = Message.Create(Database, flags, RedisCommand.GEODIST, key, member1, member2, StackExchange.Redis.GeoPosition.GetRedisUnit(unit)); return ExecuteAsync(msg, ResultProcessor.NullableDouble); } @@ -860,28 +861,32 @@ public Task HashGetAsync(RedisKey key, RedisValue[] hashFields, Co public long HashIncrement(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None) { var msg = value == 0 && (flags & CommandFlags.FireAndForget) != 0 - ? null : Message.Create(Database, flags, RedisCommand.HINCRBY, key, hashField, value); + ? null + : Message.Create(Database, flags, RedisCommand.HINCRBY, key, hashField, value); return ExecuteSync(msg, ResultProcessor.Int64); } public double HashIncrement(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) { var msg = value == 0 && (flags & CommandFlags.FireAndForget) != 0 - ? null : Message.Create(Database, flags, RedisCommand.HINCRBYFLOAT, key, hashField, value); + ? null + : Message.Create(Database, flags, RedisCommand.HINCRBYFLOAT, key, hashField, value); return ExecuteSync(msg, ResultProcessor.Double); } public Task HashIncrementAsync(RedisKey key, RedisValue hashField, long value = 1, CommandFlags flags = CommandFlags.None) { var msg = value == 0 && (flags & CommandFlags.FireAndForget) != 0 - ? null : Message.Create(Database, flags, RedisCommand.HINCRBY, key, hashField, value); + ? null + : Message.Create(Database, flags, RedisCommand.HINCRBY, key, hashField, value); return ExecuteAsync(msg, ResultProcessor.Int64); } public Task HashIncrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) { var msg = value == 0 && (flags & CommandFlags.FireAndForget) != 0 - ? null : Message.Create(Database, flags, RedisCommand.HINCRBYFLOAT, key, hashField, value); + ? null + : Message.Create(Database, flags, RedisCommand.HINCRBYFLOAT, key, hashField, value); return ExecuteAsync(msg, ResultProcessor.Double); } @@ -1323,9 +1328,9 @@ public Task KeyExpireAsync(RedisKey key, TimeSpan? expiry, ExpireWhen when return ExecuteAsync(msg, ResultProcessor.Boolean, server: server); } - public Task KeyExpireAsync(RedisKey key, DateTime? expire, ExpireWhen when, CommandFlags flags = CommandFlags.None) + public Task KeyExpireAsync(RedisKey key, DateTime? expiry, ExpireWhen when, CommandFlags flags = CommandFlags.None) { - var msg = GetExpiryMessage(key, flags, expire, when, out ServerEndPoint? server); + var msg = GetExpiryMessage(key, flags, expiry, when, out ServerEndPoint? server); return ExecuteAsync(msg, ResultProcessor.Boolean, server: server); } @@ -1953,39 +1958,39 @@ public Task LockTakeAsync(RedisKey key, RedisValue value, TimeSpan expiry, return StringSetAsync(key, value, expiry, When.NotExists, flags); } - public string? StringLongestCommonSubsequence(RedisKey key1, RedisKey key2, CommandFlags flags = CommandFlags.None) + public string? StringLongestCommonSubsequence(RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.LCS, key1, key2); + var msg = Message.Create(Database, flags, RedisCommand.LCS, first, second); return ExecuteSync(msg, ResultProcessor.String); } - public Task StringLongestCommonSubsequenceAsync(RedisKey key1, RedisKey key2, CommandFlags flags = CommandFlags.None) + public Task StringLongestCommonSubsequenceAsync(RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.LCS, key1, key2); + var msg = Message.Create(Database, flags, RedisCommand.LCS, first, second); return ExecuteAsync(msg, ResultProcessor.String); } - public long StringLongestCommonSubsequenceLength(RedisKey key1, RedisKey key2, CommandFlags flags = CommandFlags.None) + public long StringLongestCommonSubsequenceLength(RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.LCS, key1, key2, RedisLiterals.LEN); + var msg = Message.Create(Database, flags, RedisCommand.LCS, first, second, RedisLiterals.LEN); return ExecuteSync(msg, ResultProcessor.Int64); } - public Task StringLongestCommonSubsequenceLengthAsync(RedisKey key1, RedisKey key2, CommandFlags flags = CommandFlags.None) + public Task StringLongestCommonSubsequenceLengthAsync(RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.LCS, key1, key2, RedisLiterals.LEN); + var msg = Message.Create(Database, flags, RedisCommand.LCS, first, second, RedisLiterals.LEN); return ExecuteAsync(msg, ResultProcessor.Int64); } - public LCSMatchResult StringLongestCommonSubsequenceWithMatches(RedisKey key1, RedisKey key2, long minSubMatchLength = 0, CommandFlags flags = CommandFlags.None) + public LCSMatchResult StringLongestCommonSubsequenceWithMatches(RedisKey first, RedisKey second, long minLength = 0, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.LCS, key1, key2, RedisLiterals.IDX, RedisLiterals.MINMATCHLEN, minSubMatchLength, RedisLiterals.WITHMATCHLEN); + var msg = Message.Create(Database, flags, RedisCommand.LCS, first, second, RedisLiterals.IDX, RedisLiterals.MINMATCHLEN, minLength, RedisLiterals.WITHMATCHLEN); return ExecuteSync(msg, ResultProcessor.LCSMatchResult); } - public Task StringLongestCommonSubsequenceWithMatchesAsync(RedisKey key1, RedisKey key2, long minSubMatchLength = 0, CommandFlags flags = CommandFlags.None) + public Task StringLongestCommonSubsequenceWithMatchesAsync(RedisKey first, RedisKey second, long minLength = 0, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.LCS, key1, key2, RedisLiterals.IDX, RedisLiterals.MINMATCHLEN, minSubMatchLength, RedisLiterals.WITHMATCHLEN); + var msg = Message.Create(Database, flags, RedisCommand.LCS, first, second, RedisLiterals.IDX, RedisLiterals.MINMATCHLEN, minLength, RedisLiterals.WITHMATCHLEN); return ExecuteAsync(msg, ResultProcessor.LCSMatchResult); } @@ -3015,16 +3020,16 @@ public Task StreamAcknowledgeAndDeleteAsync(RedisKey key, Re public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId, int? maxLength, bool useApproximateMaxLength, CommandFlags flags) => StreamAdd(key, streamField, streamValue, messageId, maxLength, useApproximateMaxLength, null, StreamTrimMode.KeepReferences, flags); - public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, new NameValueEntry(streamField, streamValue), flags); return ExecuteSync(msg, ResultProcessor.RedisValue); } - public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, new NameValueEntry(streamField, streamValue), flags); return ExecuteSync(msg, ResultProcessor.RedisValue); } @@ -3039,16 +3044,16 @@ public RedisValue StreamAdd(RedisKey key, RedisValue streamField, RedisValue str public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId, int? maxLength, bool useApproximateMaxLength, CommandFlags flags) => StreamAddAsync(key, streamField, streamValue, messageId, maxLength, useApproximateMaxLength, null, StreamTrimMode.KeepReferences, flags); - public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, new NameValueEntry(streamField, streamValue), flags); return ExecuteAsync(msg, ResultProcessor.RedisValue); } - public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public Task StreamAddAsync(RedisKey key, RedisValue streamField, RedisValue streamValue, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, new NameValueEntry(streamField, streamValue), flags); return ExecuteAsync(msg, ResultProcessor.RedisValue); } @@ -3063,16 +3068,16 @@ public Task StreamAddAsync(RedisKey key, RedisValue streamField, Red public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId, int? maxLength, bool useApproximateMaxLength, CommandFlags flags) => StreamAdd(key, streamPairs, messageId, maxLength, useApproximateMaxLength, null, StreamTrimMode.KeepReferences, flags); - public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, streamPairs, flags); return ExecuteSync(msg, ResultProcessor.RedisValue); } - public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, streamPairs, flags); return ExecuteSync(msg, ResultProcessor.RedisValue); } @@ -3087,16 +3092,16 @@ public RedisValue StreamAdd(RedisKey key, NameValueEntry[] streamPairs, StreamAd public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId, int? maxLength, bool useApproximateMaxLength, CommandFlags flags) => StreamAddAsync(key, streamPairs, messageId, maxLength, useApproximateMaxLength, null, StreamTrimMode.KeepReferences, flags); - public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, RedisValue? messageId = null, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(messageId, StreamIdempotentId.Empty, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, streamPairs, flags); return ExecuteAsync(msg, ResultProcessor.RedisValue); } - public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode mode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) + public Task StreamAddAsync(RedisKey key, NameValueEntry[] streamPairs, StreamIdempotentId idempotentId, long? maxLength = null, bool useApproximateMaxLength = false, long? limit = null, StreamTrimMode trimMode = StreamTrimMode.KeepReferences, CommandFlags flags = CommandFlags.None) { - var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, mode); + var options = LegacyStreamAddOptions(null, in idempotentId, maxLength, useApproximateMaxLength, limit, trimMode); var msg = GetStreamAddMessage(key, in options, streamPairs, flags); return ExecuteAsync(msg, ResultProcessor.RedisValue); } @@ -4099,7 +4104,8 @@ public long StringIncrement(RedisKey key, long value = 1, CommandFlags flags = C public double StringIncrement(RedisKey key, double value, CommandFlags flags = CommandFlags.None) { var msg = value == 0 && (flags & CommandFlags.FireAndForget) != 0 - ? null : Message.Create(Database, flags, RedisCommand.INCRBYFLOAT, key, value); + ? null + : Message.Create(Database, flags, RedisCommand.INCRBYFLOAT, key, value); return ExecuteSync(msg, ResultProcessor.Double); } @@ -4112,7 +4118,8 @@ public Task StringIncrementAsync(RedisKey key, long value = 1, CommandFlag public Task StringIncrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None) { var msg = value == 0 && (flags & CommandFlags.FireAndForget) != 0 - ? null : Message.Create(Database, flags, RedisCommand.INCRBYFLOAT, key, value); + ? null + : Message.Create(Database, flags, RedisCommand.INCRBYFLOAT, key, value); return ExecuteAsync(msg, ResultProcessor.Double); } @@ -4200,9 +4207,9 @@ public bool StringSetBit(RedisKey key, long offset, bool bit, CommandFlags flags return ExecuteSync(msg, ResultProcessor.Boolean); } - public Task StringSetBitAsync(RedisKey key, long offset, bool value, CommandFlags flags = CommandFlags.None) + public Task StringSetBitAsync(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None) { - var msg = Message.Create(Database, flags, RedisCommand.SETBIT, key, offset, value); + var msg = Message.Create(Database, flags, RedisCommand.SETBIT, key, offset, bit); return ExecuteAsync(msg, ResultProcessor.Boolean); } @@ -4943,12 +4950,14 @@ private Message GetSortedSetRangeByScoreMessage(RedisKey key, double start, doub RedisValue from = GetRange(start, exclude, true), to = GetRange(stop, exclude, false); if (withScores) { - return unlimited ? Message.Create(Database, flags, command, key, from, to, RedisLiterals.WITHSCORES) + return unlimited + ? Message.Create(Database, flags, command, key, from, to, RedisLiterals.WITHSCORES) : Message.Create(Database, flags, command, key, new[] { from, to, RedisLiterals.WITHSCORES, RedisLiterals.LIMIT, skip, take }); } else { - return unlimited ? Message.Create(Database, flags, command, key, from, to) + return unlimited + ? Message.Create(Database, flags, command, key, from, to) : Message.Create(Database, flags, command, key, new[] { from, to, RedisLiterals.LIMIT, skip, take }); } } @@ -5728,7 +5737,7 @@ internal Message GetStringSetMessage( expiry.GetTokenCount(allowEnx: false); - if (when is When.Always & expiry.IsRelative) + if ((when is When.Always) & expiry.IsRelative) { // special case to SETEX/PSETEX return expiry.IsSeconds @@ -6059,7 +6068,7 @@ private static int RemoveDbIfNotRequired(int suggestedDb, string adhocCommand, o { knownCommand = RedisCommand.UNKNOWN; } - if ((knownCommand is not RedisCommand.UNKNOWN & suggestedDb >= 0) && !Message.RequiresDatabase(knownCommand)) + if (((knownCommand is not RedisCommand.UNKNOWN) & (suggestedDb >= 0)) && !Message.RequiresDatabase(knownCommand)) { // strip the DB; historically we didn't enforce this when IDatabase was // used to issue known commands as strings, so: don't complain now @@ -6153,7 +6162,7 @@ private static int RemoveDbIfNotRequired(int suggestedDb, string adhocCommand, o { knownCommand = RedisCommand.UNKNOWN; } - if ((knownCommand is not RedisCommand.UNKNOWN & suggestedDb >= 0) && !Message.RequiresDatabase(knownCommand)) + if (((knownCommand is not RedisCommand.UNKNOWN) & (suggestedDb >= 0)) && !Message.RequiresDatabase(knownCommand)) { // strip the DB; historically we didn't enforce this when IDatabase was // used to issue known commands as strings, so: don't complain now diff --git a/src/StackExchange.Redis/RedisErrorKind.cs b/src/StackExchange.Redis/RedisErrorKind.cs index e4403778b9..ccee997f06 100644 --- a/src/StackExchange.Redis/RedisErrorKind.cs +++ b/src/StackExchange.Redis/RedisErrorKind.cs @@ -201,7 +201,7 @@ internal static bool TryParse(ReadOnlySpan value, out RedisErrorKind kind) if (TryParseFirstTokenCI(firstToken, out kind)) { // check for more specific "ERR ..." scenarios - if (kind is RedisErrorKind.UnknownError & space > 0) + if ((kind is RedisErrorKind.UnknownError) & (space > 0)) { // get the message text after "ERR " value = value.Slice(space + 1); diff --git a/src/StackExchange.Redis/RedisKey.cs b/src/StackExchange.Redis/RedisKey.cs index 85f9ced599..31abd7c9aa 100644 --- a/src/StackExchange.Redis/RedisKey.cs +++ b/src/StackExchange.Redis/RedisKey.cs @@ -342,9 +342,11 @@ internal static RedisKey WithPrefix(byte[]? prefix, RedisKey value) } int aLen = a?.Length ?? 0, - bLen = b == null ? 0 : (b is string bString - ? Encoding.UTF8.GetByteCount(bString) - : ((byte[])b).Length), + bLen = b == null + ? 0 + : b is string bString + ? Encoding.UTF8.GetByteCount(bString) + : ((byte[])b).Length, cLen = c?.Length ?? 0; var result = new byte[aLen + bLen + cLen]; diff --git a/src/StackExchange.Redis/RedisResult.cs b/src/StackExchange.Redis/RedisResult.cs index 1d496468fd..883e4738f6 100644 --- a/src/StackExchange.Redis/RedisResult.cs +++ b/src/StackExchange.Redis/RedisResult.cs @@ -44,8 +44,9 @@ public static RedisResult Create(RedisValue[] values) /// The explicit data type. /// new . public static RedisResult Create(RedisValue[] values, ResultType resultType) => - values == null ? NullArray : values.Length == 0 ? EmptyArray(resultType) : - new ArrayRedisResult(Array.ConvertAll(values, value => new SingleRedisResult(value, null)), resultType); + values == null ? NullArray : + values.Length == 0 ? EmptyArray(resultType) : + new ArrayRedisResult(Array.ConvertAll(values, value => new SingleRedisResult(value, null)), resultType); /// /// Create a new RedisResult representing an array of values. @@ -428,10 +429,11 @@ internal override bool AsBoolean() } internal override byte[][]? AsByteArrayArray() - => IsNull ? null - : _value!.Length == 0 - ? Array.Empty() - : Array.ConvertAll(_value, x => x.AsByteArray()!); + => IsNull + ? null + : _value!.Length == 0 + ? Array.Empty() + : Array.ConvertAll(_value, x => x.AsByteArray()!); private bool IsSingleton => _value?.Length == 1; private bool IsEmpty => _value?.Length == 0; @@ -442,9 +444,11 @@ internal override double AsDouble() } internal override double[]? AsDoubleArray() - => IsNull ? null - : IsEmpty ? Array.Empty() - : Array.ConvertAll(_value!, x => x.AsDouble()); + => IsNull + ? null + : IsEmpty + ? Array.Empty() + : Array.ConvertAll(_value!, x => x.AsDouble()); internal override int AsInt32() { @@ -453,9 +457,11 @@ internal override int AsInt32() } internal override int[]? AsInt32Array() - => IsNull ? null - : IsEmpty ? Array.Empty() - : Array.ConvertAll(_value!, x => x.AsInt32()); + => IsNull + ? null + : IsEmpty + ? Array.Empty() + : Array.ConvertAll(_value!, x => x.AsInt32()); internal override long AsInt64() { @@ -469,14 +475,18 @@ internal override ulong AsUInt64() } internal override long[]? AsInt64Array() - => IsNull ? null - : IsEmpty ? Array.Empty() - : Array.ConvertAll(_value!, x => x.AsInt64()); + => IsNull + ? null + : IsEmpty + ? Array.Empty() + : Array.ConvertAll(_value!, x => x.AsInt64()); internal override ulong[]? AsUInt64Array() - => IsNull ? null - : IsEmpty ? Array.Empty() - : Array.ConvertAll(_value!, x => x.AsUInt64()); + => IsNull + ? null + : IsEmpty + ? Array.Empty() + : Array.ConvertAll(_value!, x => x.AsUInt64()); internal override bool? AsNullableBoolean() { @@ -514,9 +524,11 @@ internal override RedisKey AsRedisKey() } internal override RedisKey[]? AsRedisKeyArray() - => IsNull ? null - : IsEmpty ? Array.Empty() - : Array.ConvertAll(_value!, x => x.AsRedisKey()); + => IsNull + ? null + : IsEmpty + ? Array.Empty() + : Array.ConvertAll(_value!, x => x.AsRedisKey()); internal override RedisResult[]? AsRedisResultArray() => _value; @@ -527,9 +539,11 @@ internal override RedisValue AsRedisValue() } internal override RedisValue[]? AsRedisValueArray() - => IsNull ? null - : IsEmpty ? Array.Empty() - : Array.ConvertAll(_value!, x => x.AsRedisValue()); + => IsNull + ? null + : IsEmpty + ? Array.Empty() + : Array.ConvertAll(_value!, x => x.AsRedisValue()); internal override string? AsString() { @@ -538,9 +552,11 @@ internal override RedisValue AsRedisValue() } internal override string?[]? AsStringArray() - => IsNull ? null - : IsEmpty ? Array.Empty() - : Array.ConvertAll(_value!, x => x.AsString()); + => IsNull + ? null + : IsEmpty + ? Array.Empty() + : Array.ConvertAll(_value!, x => x.AsString()); } /// diff --git a/src/StackExchange.Redis/RedisServer.cs b/src/StackExchange.Redis/RedisServer.cs index 94fb73065c..e6d9cb000c 100644 --- a/src/StackExchange.Redis/RedisServer.cs +++ b/src/StackExchange.Redis/RedisServer.cs @@ -587,14 +587,16 @@ public Task StringGetAsync(int db, RedisKey key, CommandFlags flags public RedisChannel[] SubscriptionChannels(RedisChannel pattern = default, CommandFlags flags = CommandFlags.None) { - var msg = pattern.IsNullOrEmpty ? Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.CHANNELS) + var msg = pattern.IsNullOrEmpty + ? Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.CHANNELS) : Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.CHANNELS, pattern); return ExecuteSync(msg, ResultProcessor.RedisChannelArrayLiteral, defaultValue: Array.Empty()); } public Task SubscriptionChannelsAsync(RedisChannel pattern = default, CommandFlags flags = CommandFlags.None) { - var msg = pattern.IsNullOrEmpty ? Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.CHANNELS) + var msg = pattern.IsNullOrEmpty + ? Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.CHANNELS) : Message.Create(-1, flags, RedisCommand.PUBSUB, RedisLiterals.CHANNELS, pattern); return ExecuteAsync(msg, ResultProcessor.RedisChannelArrayLiteral, defaultValue: Array.Empty()); } diff --git a/src/StackExchange.Redis/RedisSubscriber.cs b/src/StackExchange.Redis/RedisSubscriber.cs index ef9d42d226..d0741e5f5a 100644 --- a/src/StackExchange.Redis/RedisSubscriber.cs +++ b/src/StackExchange.Redis/RedisSubscriber.cs @@ -332,7 +332,7 @@ private bool UnregisterSubscription(in RedisChannel channel, Action value) /// Creates a new from an . /// /// The to convert to a . - public static implicit operator RedisValue(bool? value) => value == null ? Null + public static implicit operator RedisValue(bool? value) => value == null + ? Null : new(value.GetValueOrDefault() ? 1 : 0); /// diff --git a/src/StackExchange.Redis/RenderedArgs.cs b/src/StackExchange.Redis/RenderedArgs.cs index 43389744d1..3221d2faab 100644 --- a/src/StackExchange.Redis/RenderedArgs.cs +++ b/src/StackExchange.Redis/RenderedArgs.cs @@ -124,7 +124,8 @@ public static RenderedArgs Create(ReadOnlySpan keys, ReadOnlySpan? pool) => new RenderedArgs { - _buffer = length == 0 ? Array.Empty() + _buffer = length == 0 + ? Array.Empty() : pool is null ? ArrayPool.Shared.Rent(length) : pool.Rent(length), _count = count, _length = length, diff --git a/src/StackExchange.Redis/RespReaderExtensions.cs b/src/StackExchange.Redis/RespReaderExtensions.cs index 1048d5e2cc..587ef32ec5 100644 --- a/src/StackExchange.Redis/RespReaderExtensions.cs +++ b/src/StackExchange.Redis/RespReaderExtensions.cs @@ -44,8 +44,7 @@ public static RedisValue ReadRedisValue(this in RespReader reader) // discontiguous payload. if (length <= RedisValue.MaxInlineBytes) { - return RedisValue.FromRaw(reader.TryGetSpan(out var buffer) ? - buffer : reader.Buffer(stackalloc byte[RedisValue.MaxInlineBytes])); + return RedisValue.FromRaw(reader.TryGetSpan(out var buffer) ? buffer : reader.Buffer(stackalloc byte[RedisValue.MaxInlineBytes])); } // Longer payloads: prefer a compact numeric storage kind when the text is the *canonical* @@ -148,7 +147,7 @@ static bool Failure(out RedisValue value) } // integer: canonical exactly when the round-trip text length matches (rules out leading zeros, a // leading '+', "-0", trailing junk, etc.) - so no need to re-emit and compare bytes - if (span.IsEmpty | span.Length > MaxCanonicalLength) return Failure(out value); + if (span.IsEmpty | (span.Length > MaxCanonicalLength)) return Failure(out value); // restrict to *just* basic number tokens, tracking the two facts that let us pick a single parse: // whether a '-' appeared (so we know whether the integer is signed), and whether a '.'/'e'/'E' diff --git a/src/StackExchange.Redis/ResultBox.cs b/src/StackExchange.Redis/ResultBox.cs index eeacae0f0f..26a72111bb 100644 --- a/src/StackExchange.Redis/ResultBox.cs +++ b/src/StackExchange.Redis/ResultBox.cs @@ -42,7 +42,7 @@ internal abstract class SimpleResultBox : IResultBox bool IResultBox.IsFaulted => _exception != null; bool IResultBox.IsCompleted => _completed; Exception? IResultBox.Fault => _exception; - void IResultBox.SetException(Exception exception) => _exception = exception ?? CancelledException; + void IResultBox.SetException(Exception ex) => _exception = ex ?? CancelledException; void IResultBox.Cancel() => _exception = CancelledException; void IResultBox.ActivateContinuations() @@ -131,7 +131,7 @@ private TaskResultBox(object? asyncState, TaskCreationOptions creationOptions) : void IResultBox.SetResult(T value) => _value = value; - T? IResultBox.GetResult(out Exception? ex, bool unused) + T? IResultBox.GetResult(out Exception? ex, bool canRecycle) { ex = _exception; return _value; diff --git a/src/StackExchange.Redis/ResultProcessor.cs b/src/StackExchange.Redis/ResultProcessor.cs index e985b10f26..9b21803012 100644 --- a/src/StackExchange.Redis/ResultProcessor.cs +++ b/src/StackExchange.Redis/ResultProcessor.cs @@ -1277,7 +1277,8 @@ when helloFromInteractive // a known non-Redis server: "version" is the vendor's own version, and the Redis API version // (if the server reports one at all) comes from INFO's redis_version var productVersion = vendorVariant == fromServer && !string.IsNullOrWhiteSpace(vendorVersion) - ? vendorVersion! : helloVersion.IsScalar ? helloVersion.ReadString() : null; + ? vendorVersion! + : helloVersion.IsScalar ? helloVersion.ReadString() : null; if (!string.IsNullOrWhiteSpace(productVersion)) { server.SetProductVariant(fromServer, productVersion!); diff --git a/src/StackExchange.Redis/ServerEndPoint.cs b/src/StackExchange.Redis/ServerEndPoint.cs index eb9d9fa020..0768dbcb7d 100644 --- a/src/StackExchange.Redis/ServerEndPoint.cs +++ b/src/StackExchange.Redis/ServerEndPoint.cs @@ -111,8 +111,8 @@ public ServerEndPoint(ConnectionMultiplexer multiplexer, EndPoint endpoint, Serv private RedisServer? _defaultServer; public RedisServer GetRedisServer(object? asyncState) => asyncState is null - ? (_defaultServer ??= new RedisServer(this, null)) // reuse and memoize - : new RedisServer(this, asyncState); + ? (_defaultServer ??= new RedisServer(this, null)) // reuse and memoize + : new RedisServer(this, asyncState); public EndPoint EndPoint { get; } @@ -249,7 +249,10 @@ public bool ReplicaReadOnly public bool AllowReplicaWrites { - get => allowReplicaWrites; + get + { + return allowReplicaWrites; + } set { allowReplicaWrites = value; @@ -789,7 +792,10 @@ internal void FlushScriptCache() private string? runId; internal string? RunId { - get => runId; + get + { + return runId; + } set { // We only care about changes diff --git a/src/StackExchange.Redis/ServerSelectionStrategy.cs b/src/StackExchange.Redis/ServerSelectionStrategy.cs index a3ea96c2d3..7fed58e531 100644 --- a/src/StackExchange.Redis/ServerSelectionStrategy.cs +++ b/src/StackExchange.Redis/ServerSelectionStrategy.cs @@ -113,7 +113,8 @@ public int HashSlot(in RedisChannel channel) ReadOnlySpan routingSpan = channel.RoutingSpan; byte[] prefix; return channel.IgnoreChannelPrefix || (prefix = ChannelPrefix).Length == 0 - ? GetClusterSlot(routingSpan) : GetClusterSlotWithPrefix(prefix, routingSpan); + ? GetClusterSlot(routingSpan) + : GetClusterSlotWithPrefix(prefix, routingSpan); static int GetClusterSlotWithPrefix(byte[] prefixRaw, ReadOnlySpan routingSpan) { diff --git a/src/StackExchange.Redis/Subscription.cs b/src/StackExchange.Redis/Subscription.cs index cb924a29a4..767ab0a143 100644 --- a/src/StackExchange.Redis/Subscription.cs +++ b/src/StackExchange.Redis/Subscription.cs @@ -153,7 +153,7 @@ public bool Remove(Action? handler, ChannelMessageQueu ChannelMessageQueue.Remove(ref _queues, queue); } - return _handlers == null & _queues == null; + return (_handlers == null) & (_queues == null); } public ICompletable? ForInvoke(in RedisChannel channel, in RedisValue message, out ChannelMessageQueue? queues) @@ -445,7 +445,7 @@ internal override int EnsureSubscribedToServer( { // exclude sentinel, and only use replicas if we're explicitly asking for them bool useReplica = (Flags & CommandFlags.DemandReplica) != 0; - bool shouldBeConnected = server.ServerType != ServerType.Sentinel & server.IsReplica == useReplica; + bool shouldBeConnected = (server.ServerType != ServerType.Sentinel) & (server.IsReplica == useReplica); if (shouldBeConnected == IsConnectedTo(server.EndPoint)) { return null; diff --git a/src/StackExchange.Redis/ValueCondition.cs b/src/StackExchange.Redis/ValueCondition.cs index f035551b6b..d1579b71d1 100644 --- a/src/StackExchange.Redis/ValueCondition.cs +++ b/src/StackExchange.Redis/ValueCondition.cs @@ -231,9 +231,9 @@ public static ValueCondition ParseDigest(ReadOnlySpan digest) private static byte ParseNibble(int b) { - if (b >= '0' & b <= '9') return (byte)(b - '0'); - if (b >= 'a' & b <= 'f') return (byte)(b - 'a' + 10); - if (b >= 'A' & b <= 'F') return (byte)(b - 'A' + 10); + if ((b >= '0') & (b <= '9')) return (byte)(b - '0'); + if ((b >= 'a') & (b <= 'f')) return (byte)(b - 'a' + 10); + if ((b >= 'A') & (b <= 'F')) return (byte)(b - 'A' + 10); return ThrowInvalidBytes(); static byte ThrowInvalidBytes() => throw new ArgumentException("Invalid digest bytes"); @@ -264,9 +264,9 @@ public static ValueCondition ParseDigest(ReadOnlySpan digest) static byte ToNibble(int b) { - if (b >= '0' & b <= '9') return (byte)(b - '0'); - if (b >= 'a' & b <= 'f') return (byte)(b - 'a' + 10); - if (b >= 'A' & b <= 'F') return (byte)(b - 'A' + 10); + if ((b >= '0') & (b <= '9')) return (byte)(b - '0'); + if ((b >= 'a') & (b <= 'f')) return (byte)(b - 'a' + 10); + if ((b >= 'A') & (b <= 'F')) return (byte)(b - 'A' + 10); return ThrowInvalidBytes(); } diff --git a/src/StackExchange.Redis/VectorSetSimilaritySearchMessage.cs b/src/StackExchange.Redis/VectorSetSimilaritySearchMessage.cs index 1c495cde57..816ce66006 100644 --- a/src/StackExchange.Redis/VectorSetSimilaritySearchMessage.cs +++ b/src/StackExchange.Redis/VectorSetSimilaritySearchMessage.cs @@ -30,8 +30,7 @@ internal sealed class VectorSetSimilaritySearchBySingleVectorMessage( int searchExplorationFactor, string? filterExpression, int maxFilteringEffort, - bool useFp32) : VectorSetSimilaritySearchMessage(db, flags, vsimFlags, key, count, epsilon, - searchExplorationFactor, filterExpression, maxFilteringEffort, useFp32) + bool useFp32) : VectorSetSimilaritySearchMessage(db, flags, vsimFlags, key, count, epsilon, searchExplorationFactor, filterExpression, maxFilteringEffort, useFp32) { internal override int GetSearchTargetArgCount() => UseFp32 ? 2 : (2 + vector.Length); // FP32 {vector} or VALUES {num} {vector} @@ -67,8 +66,7 @@ internal sealed class VectorSetSimilaritySearchByMemberMessage( int searchExplorationFactor, string? filterExpression, int maxFilteringEffort, - bool useFp32) : VectorSetSimilaritySearchMessage(db, flags, vsimFlags, key, count, epsilon, - searchExplorationFactor, filterExpression, maxFilteringEffort, useFp32) + bool useFp32) : VectorSetSimilaritySearchMessage(db, flags, vsimFlags, key, count, epsilon, searchExplorationFactor, filterExpression, maxFilteringEffort, useFp32) { internal override int GetSearchTargetArgCount() => 2; // ELE {member} diff --git a/src/StackExchange.Redis/VectorSetSimilaritySearchRequest.cs b/src/StackExchange.Redis/VectorSetSimilaritySearchRequest.cs index c48004d8f1..adfeefc08e 100644 --- a/src/StackExchange.Redis/VectorSetSimilaritySearchRequest.cs +++ b/src/StackExchange.Redis/VectorSetSimilaritySearchRequest.cs @@ -92,7 +92,10 @@ private void SetFlag(VsimFlags flag, bool value) /// public int? Count { - get => HasFlag(VsimFlags.Count) ? _count : null; + get + { + return HasFlag(VsimFlags.Count) ? _count : null; + } set { if (value.HasValue) @@ -130,7 +133,10 @@ public bool WithAttributes /// public double? Epsilon { - get => HasFlag(VsimFlags.Epsilon) ? _epsilon : null; + get + { + return HasFlag(VsimFlags.Epsilon) ? _epsilon : null; + } set { if (value.HasValue) @@ -150,7 +156,10 @@ public double? Epsilon /// public int? SearchExplorationFactor { - get => HasFlag(VsimFlags.SearchExplorationFactor) ? _searchExplorationFactor : null; + get + { + return HasFlag(VsimFlags.SearchExplorationFactor) ? _searchExplorationFactor : null; + } set { if (value.HasValue) @@ -170,7 +179,10 @@ public int? SearchExplorationFactor /// public int? MaxFilteringEffort { - get => HasFlag(VsimFlags.MaxFilteringEffort) ? _maxFilteringEffort : null; + get + { + return HasFlag(VsimFlags.MaxFilteringEffort) ? _maxFilteringEffort : null; + } set { if (value.HasValue) @@ -192,7 +204,10 @@ public int? MaxFilteringEffort /// public string? FilterExpression { - get => _filterExpression; + get + { + return _filterExpression; + } set { _filterExpression = value; diff --git a/tests/StackExchange.Redis.Tests/WithKeyPrefixTests.cs b/tests/StackExchange.Redis.Tests/WithKeyPrefixTests.cs index b70d215ee1..772ed68231 100644 --- a/tests/StackExchange.Redis.Tests/WithKeyPrefixTests.cs +++ b/tests/StackExchange.Redis.Tests/WithKeyPrefixTests.cs @@ -131,4 +131,27 @@ public async Task ConditionTest() i = (int)raw.StringGet(prefix + "i"); Assert.Equal(1, i); } + + [Fact] + public async Task SortedSetRangeAndStoreUsesTheRightKeys() + { + // the sync prefixed overload declared its first two parameters as (destination, source) against the + // interface's (source, destination) and then forwarded them by name, so it read from the destination + // and wrote into (and so wiped) the source + await using var conn = Create(require: RedisFeatures.v6_2_0); + + var raw = conn.GetDatabase(); + var prefix = Me() + ":"; + var prefixed = raw.WithKeyPrefix(prefix); + raw.KeyDelete([prefix + "source", prefix + "destination"], CommandFlags.FireAndForget); + prefixed.SortedSetAdd("source", [new SortedSetEntry("a", 1), new SortedSetEntry("b", 2)], CommandFlags.FireAndForget); + + Assert.Equal(2, prefixed.SortedSetRangeAndStore("source", "destination", 0, -1)); + Assert.Equal(2, raw.SortedSetLength(prefix + "destination")); + Assert.Equal(2, raw.SortedSetLength(prefix + "source")); + + raw.KeyDelete(prefix + "destination", CommandFlags.FireAndForget); + Assert.Equal(2, await prefixed.SortedSetRangeAndStoreAsync("source", "destination", 0, -1)); + Assert.Equal(2, raw.SortedSetLength(prefix + "destination")); + } }