Skip to content

Commit

Permalink
Use binary size when writing strings
Browse files Browse the repository at this point in the history
  • Loading branch information
ArchLeaders committed Jan 28, 2024
1 parent 8a67946 commit 0d4a0a2
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Revrs/RevrsWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Buffers.Binary;
using System.Runtime.InteropServices.Marshalling;
using System.Runtime.InteropServices;
using System.Text;

namespace Revrs;

Expand Down Expand Up @@ -136,7 +137,7 @@ public unsafe void Write<T, R>(T value) where T : unmanaged where R : IStructRev
public unsafe void WriteStringUtf8(string value)
{
byte* ptr = Utf8StringMarshaller.ConvertToUnmanaged(value);
Span<byte> buffer = new(ptr, value.Length);
Span<byte> buffer = new(ptr, Encoding.UTF8.GetByteCount(value));
_stream.Write(buffer);
}

Expand All @@ -147,14 +148,15 @@ public unsafe void WriteStringUtf8(string value)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteStringUtf16(string value)
{
int length = Encoding.Unicode.GetByteCount(value) / 2;
ushort* ptr = Utf16StringMarshaller.ConvertToUnmanaged(value);
if (Endianness.IsNotSystemEndianness()) {
for (int i = 0; i < value.Length; i++) {
for (int i = 0; i < length; i++) {
ptr[i] = BinaryPrimitives.ReverseEndianness(ptr[i]);
}
}

Span<ushort> buffer = new(ptr, value.Length);
Span<ushort> buffer = new(ptr, length);
_stream.Write(MemoryMarshal.Cast<ushort, byte>(buffer));
}
}

0 comments on commit 0d4a0a2

Please sign in to comment.