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

Plug System.IO.UnmanagedMemoryStream #2450

Merged
merged 2 commits into from
Oct 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions source/Cosmos.System2_Plugs/Cosmos.System2_Plugs.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<RootNamespace>Cosmos.System_Plugs</RootNamespace>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Configurations>Debug;Release;TEST</Configurations>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
Expand Down
66 changes: 66 additions & 0 deletions source/Cosmos.System2_Plugs/System/IO/UnmanagedMemoryStreamImpl.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using IL2CPU.API.Attribs;
using System.IO;

namespace Cosmos.System_Plugs.System.IO
{
[Plug(Target = typeof(UnmanagedMemoryStream))]
public unsafe static class UnmanagedMemoryStreamImpl
{
public static void WriteCore(this UnmanagedMemoryStream aStream, ReadOnlySpan<byte> aSpan)
{
for (int I = 0; I < aSpan.Length; I++)
{
aStream.WriteByte(aSpan[I]);
}
}
public static int ReadCore(this UnmanagedMemoryStream aStream, Span<byte> aSpan)
{
long n = Math.Min(aStream.Length - aStream.Position, aSpan.Length);
if (n <= 0)
{
return 0;
}

int nInt = (int)n; // Safe because n <= count, which is an Int32
if (nInt < 0)
{
return 0; // _position could be beyond EOF
}

unsafe
{
if (aSpan != null)
{
byte* pointer = null;

try
{
for (int I = 0; I < nInt; I++)
{
aSpan[I] = *(pointer + aStream.Position + aStream.Capacity);
}
}
catch { }
}
else
{
for (int I = 0; I < nInt; I++)
{
aSpan[I] = *(aStream.PositionPointer + aStream.Position);
}
}
}

aStream.Position += n;
return nInt;
}
public static void WriteByte(this UnmanagedMemoryStream aStream, byte aValue)
{
aStream.PositionPointer[aStream.Position++] = aValue;
}
public static int ReadByte(this UnmanagedMemoryStream aStream)
{
return aStream.PositionPointer[aStream.Position++];
}
}
}