Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StreamHelpers: Remove ThreadStatic buffer and use stack allocated span instead #1371

Merged
merged 1 commit into from
Jun 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 21 additions & 30 deletions SteamKit2/SteamKit2/Util/StreamHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,69 +7,60 @@ namespace SteamKit2
{
internal static class StreamHelpers
{
[ThreadStatic]
static byte[]? data;

[MemberNotNull(nameof(data))]
static void EnsureInitialized()
{
data ??= new byte[ 8 ];
}

public static short ReadInt16(this Stream stream)
{
EnsureInitialized();
Span<byte> data = stackalloc byte[2];

stream.Read( data, 0, 2 );
return BitConverter.ToInt16( data, 0 );
stream.Read( data );
return BitConverter.ToInt16( data );
}

public static ushort ReadUInt16(this Stream stream)
{
EnsureInitialized();
Span<byte> data = stackalloc byte[2];

stream.Read( data, 0, 2 );
return BitConverter.ToUInt16( data, 0);
stream.Read( data );
return BitConverter.ToUInt16( data );
}

public static int ReadInt32(this Stream stream)
{
EnsureInitialized();
Span<byte> data = stackalloc byte[4];

stream.Read( data, 0, 4 );
return BitConverter.ToInt32( data, 0 );
stream.Read( data );
return BitConverter.ToInt32( data );
}

public static long ReadInt64(this Stream stream)
{
EnsureInitialized();
Span<byte> data = stackalloc byte[8];

stream.Read( data, 0, 8 );
return BitConverter.ToInt64( data, 0 );
stream.Read( data );
return BitConverter.ToInt64( data );
}

public static uint ReadUInt32(this Stream stream)
{
EnsureInitialized();
Span<byte> data = stackalloc byte[4];

stream.Read(data, 0, 4);
return BitConverter.ToUInt32( data, 0);
stream.Read( data );
return BitConverter.ToUInt32( data );
}

public static ulong ReadUInt64(this Stream stream)
{
EnsureInitialized();
Span<byte> data = stackalloc byte[8];

stream.Read( data, 0, 8 );
return BitConverter.ToUInt64( data, 0 );
stream.Read( data );
return BitConverter.ToUInt64( data );
}

public static float ReadFloat( this Stream stream )
{
EnsureInitialized();
Span<byte> data = stackalloc byte[4];

stream.Read( data, 0, 4 );
return BitConverter.ToSingle( data, 0 );
stream.Read( data );
return BitConverter.ToSingle( data );
}

public static string ReadNullTermString( this Stream stream, Encoding encoding )
Expand Down
Loading