Skip to content

Commit

Permalink
Reduces heap allocations for the some byte[] uses (#1272)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobslusser authored Dec 11, 2023
1 parent f172ac5 commit f4371ff
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Renci.SshNet/Common/SshData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ protected ushort ReadUInt16()
/// <exception cref="InvalidOperationException">Attempt to read past the end of the stream.</exception>
protected uint ReadUInt32()
{
return Pack.BigEndianToUInt32(ReadBytes(4));
return _stream.ReadUInt32();
}

/// <summary>
Expand All @@ -233,7 +233,7 @@ protected uint ReadUInt32()
/// <exception cref="InvalidOperationException">Attempt to read past the end of the stream.</exception>
protected ulong ReadUInt64()
{
return Pack.BigEndianToUInt64(ReadBytes(8));
return _stream.ReadUInt64();
}

/// <summary>
Expand Down
28 changes: 28 additions & 0 deletions src/Renci.SshNet/Common/SshDataStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,14 @@ public BigInteger ReadBigInt()
/// </returns>
public uint ReadUInt32()
{
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
Span<byte> span = stackalloc byte[4];
ReadBytes(span);
return System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(span);
#else
var data = ReadBytes(4);
return Pack.BigEndianToUInt32(data);
#endif // NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
}

/// <summary>
Expand All @@ -200,8 +206,14 @@ public uint ReadUInt32()
/// </returns>
public ulong ReadUInt64()
{
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
Span<byte> span = stackalloc byte[8];
ReadBytes(span);
return System.Buffers.Binary.BinaryPrimitives.ReadUInt64BigEndian(span);
#else
var data = ReadBytes(8);
return Pack.BigEndianToUInt64(data);
#endif // NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
}

/// <summary>
Expand Down Expand Up @@ -264,5 +276,21 @@ private byte[] ReadBytes(int length)

return data;
}

#if NETSTANDARD2_1 || NET6_0_OR_GREATER
/// <summary>
/// Reads data into the specified <paramref name="buffer" />.
/// </summary>
/// <param name="buffer">The buffer to read into.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="buffer"/> is larger than the total of bytes available.</exception>
private void ReadBytes(Span<byte> buffer)
{
var bytesRead = Read(buffer);
if (bytesRead < buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(buffer), string.Format(CultureInfo.InvariantCulture, "The requested length ({0}) is greater than the actual number of bytes read ({1}).", buffer.Length, bytesRead));
}
}
#endif // NETSTANDARD2_1 || NET6_0_OR_GREATER
}
}

0 comments on commit f4371ff

Please sign in to comment.