Skip to content

Commit

Permalink
fix: NinjaWS code smells (#272)
Browse files Browse the repository at this point in the history
* fix: code smell - remove unused code

* fix: code smell - remove redundant array type

* fix: code smell - mark constants

* fix: code smell - wrap with nameof

* fix: code smell - mark class as static

* fix: code smell - move static init

* fix: code smell - remove default init

* fix: code smell - remove unused code
  • Loading branch information
uweeby committed Jul 13, 2020
1 parent 19b0bed commit 71d9428
Show file tree
Hide file tree
Showing 10 changed files with 19 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ public PublicBufferMemoryStream(byte[] buffer, BufferPool bufferPool) : base(new
_ms = new MemoryStream(buffer, 0, buffer.Length, true, true);
}

public override long Length => base.Length;

public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return _ms.BeginRead(buffer, offset, count, callback, state);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

namespace Ninja.WebSockets
{
public class HttpHelper
public static class HttpHelper
{
const string HTTP_GET_HEADER_REGEX = @"^GET(.*)HTTP\/1\.1";

Expand Down Expand Up @@ -77,7 +77,7 @@ public static string ComputeSocketAcceptString(string secWebSocketKey)
public static async Task<string> ReadHttpHeaderAsync(Stream stream, CancellationToken token)
{
// 16KB buffer more than enough for http header
int length = 1024 * 16;
const int length = 1024 * 16;
byte[] buffer = new byte[length];
int offset = 0;
int bytesRead = 0;
Expand Down Expand Up @@ -159,7 +159,7 @@ public static IList<string> GetSubProtocols(string httpHeader)

// extract a csv list of sub protocols (in order of highest preference first)
string csv = match.Groups["protocols"].Value.Trim();
return csv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
return csv.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.ToList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@

namespace Ninja.WebSockets.Internal
{
internal class BinaryReaderWriter
internal static class BinaryReaderWriter
{
public static async Task ReadExactly(int length, Stream stream, ArraySegment<byte> buffer, CancellationToken cancellationToken)
{
if (buffer.Count < length)
{
// This will happen if the calling function supplied a buffer that was too small to fit the payload of the websocket frame.
// Note that this can happen on the close handshake where the message size can be larger than the regular payload
throw new InternalBufferOverflowException($"Unable to read {length} bytes into buffer (offset: {buffer.Offset} size: {buffer.Count}). Use a larger read buffer");
throw new InternalBufferOverflowException($"Unable to read {length} bytes into buffer (offset: {nameof(buffer.Offset)} size: {nameof(buffer.Count)}). Use a larger read buffer");
}

int offset = 0;
Expand All @@ -59,7 +59,7 @@ public static async Task ReadExactly(int length, Stream stream, ArraySegment<byt

if (bytesRead == 0)
{
throw new EndOfStreamException(string.Format("Unexpected end of stream encountered whilst attempting to read {0:#,##0} bytes", length));
throw new EndOfStreamException(string.Format($"Unexpected end of {nameof(stream)} encountered whilst attempting to read {0:#,##0} bytes", length));
}

offset += bytesRead;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static void ToggleMask(ArraySegment<byte> maskKey, ArraySegment<byte> pay
{
if (maskKey.Count != MaskKeyLength)
{
throw new Exception($"MaskKey key must be {MaskKeyLength} bytes");
throw new InvalidOperationException($"MaskKey key must be {nameof(MaskKeyLength)} bytes");
}

byte[] buffer = payload.Array;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ public static async Task<WebSocketFrame> ReadAsync(Stream fromStream, ArraySegme
byte byte2 = smallBuffer.Array[1];

// process first byte
byte finBitFlag = 0x80;
byte opCodeFlag = 0x0F;
const byte finBitFlag = 0x80;
const byte opCodeFlag = 0x0F;
bool isFinBitSet = (byte1 & finBitFlag) == finBitFlag;
var opCode = (WebSocketOpCode)(byte1 & opCodeFlag);

// read and process second byte
byte maskFlag = 0x80;
const byte maskFlag = 0x80;
bool isMaskBitSet = (byte2 & maskFlag) == maskFlag;
uint len = await ReadLength(byte2, smallBuffer, fromStream, cancellationToken);
int count = (int)len;
Expand Down Expand Up @@ -143,7 +143,7 @@ static WebSocketFrame DecodeCloseFrame(bool isFinBitSet, WebSocketOpCode opCode,
/// </summary>
static async Task<uint> ReadLength(byte byte2, ArraySegment<byte> smallBuffer, Stream fromStream, CancellationToken cancellationToken)
{
byte payloadLenFlag = 0x7F;
const byte payloadLenFlag = 0x7F;
uint len = (uint)(byte2 & payloadLenFlag);

// read a short length or a long length depending on the value of len
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ internal static class WebSocketFrameWriter
/// This is used for data masking so that web proxies don't cache the data
/// Therefore, there are no cryptographic concerns
/// </summary>
static readonly Random _random;
static readonly Random _random = new Random((int)DateTime.Now.Ticks);

static WebSocketFrameWriter()
{
_random = new Random((int)DateTime.Now.Ticks);

}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public class WebSocketImplementation : WebSocket
WebSocketState _state;
bool _isContinuationFrame;
WebSocketMessageType _continuationFrameMessageType = WebSocketMessageType.Binary;
readonly bool _usePerMessageDeflate = false;
bool _tryGetBufferFailureLogged = false;
readonly bool _usePerMessageDeflate;
bool _tryGetBufferFailureLogged;
const int MAX_PING_PONG_PAYLOAD_LEN = 125;
WebSocketCloseStatus? _closeStatus;
string _closeStatusDescription;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ public class PingPongManager : IPingPongManager
readonly WebSocketImplementation _webSocket;
readonly Guid _guid;
readonly TimeSpan _keepAliveInterval;
readonly Task _pingTask;
readonly CancellationToken _cancellationToken;
Stopwatch _stopwatch;
long _pingSentTicks;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ async Task<WebSocket> ConnectAsync(Guid guid, Stream responseStream, string secW
string GetSubProtocolFromHeader(string response)
{
// make sure we escape the accept string which could contain special regex characters
string regexPattern = "Sec-WebSocket-Protocol: (.*)";
const string regexPattern = "Sec-WebSocket-Protocol: (.*)";
var regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
Match match = regex.Match(response);
if (match.Success)
Expand All @@ -166,7 +166,7 @@ string GetSubProtocolFromHeader(string response)
void ThrowIfInvalidAcceptString(Guid guid, string response, string secWebSocketKey)
{
// make sure we escape the accept string which could contain special regex characters
string regexPattern = "Sec-WebSocket-Accept: (.*)";
const string regexPattern = "Sec-WebSocket-Accept: (.*)";
var regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
string actualAcceptString = regex.Match(response).Groups[1].Value.Trim();

Expand All @@ -189,7 +189,7 @@ void ThrowIfInvalidResponseCode(string responseHeader)
string responseCode = HttpHelper.ReadHttpResponseCode(responseHeader);
if (!string.Equals(responseCode, "101 Switching Protocols", StringComparison.InvariantCultureIgnoreCase))
{
string[] lines = responseHeader.Split(new string[] { "\r\n" }, StringSplitOptions.None);
string[] lines = responseHeader.Split(new [] { "\r\n" }, StringSplitOptions.None);

for (int i = 0; i < lines.Length; i++)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public async Task<WebSocket> AcceptWebSocketAsync(WebSocketHttpContext context,
Events.Log.AcceptWebSocketStarted(guid);
await PerformHandshakeAsync(guid, context.HttpHeader, options.SubProtocol, context.Stream, token);
Events.Log.ServerHandshakeSuccess(guid);
string secWebSocketExtensions = null;
const string secWebSocketExtensions = null;
var websocket = new WebSocketImplementation(guid, _bufferFactory, context.Stream, options.KeepAliveInterval, secWebSocketExtensions, options.IncludeExceptionInCloseResponse, false, options.SubProtocol)
{
TcpClient = context.Client
Expand Down

0 comments on commit 71d9428

Please sign in to comment.