Skip to content

Commit

Permalink
PPather: BinaryReaderExtensions: ReadVector3 avoid allocating on the …
Browse files Browse the repository at this point in the history
…stack - allow unsafe
  • Loading branch information
Xian55 committed Sep 8, 2024
1 parent 23fb744 commit f61cc88
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions PPather/Extensions/BinaryReaderExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,35 @@
using System;
using System.IO;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace PPather.Extensions;

public static class BinaryReaderExtensions
{
public static Vector3 ReadVector3(this BinaryReader b)
[SkipLocalsInit]
public static unsafe Vector3 ReadVector3(this BinaryReader b)
{
Span<float> v3 = stackalloc float[3];
b.Read(MemoryMarshal.Cast<float, byte>(v3));
return new(v3);
Vector3 v;
Span<byte> buffer = new(&v, sizeof(Vector3));
b.Read(buffer);
return v;

}

[SkipLocalsInit]
public static Vector3 ReadVector3_XZY(this BinaryReader b)
{
Span<float> v3 = stackalloc float[3];
b.Read(MemoryMarshal.Cast<float, byte>(v3));
Vector3 v3 = ReadVector3(b);

// from format
// X Z -Y
// to format
// X Y Z
(v3[1], v3[2]) = (-v3[2], v3[1]);

return new(v3);
return v3;
}

public static bool EOF(this BinaryReader b)
Expand Down

0 comments on commit f61cc88

Please sign in to comment.