Skip to content

Instantly share code, notes, and snippets.

@korchoon
Created May 22, 2020 14:42
Show Gist options
  • Save korchoon/75672b243b5ebdf4e8d5e6bfca6b16f4 to your computer and use it in GitHub Desktop.
Save korchoon/75672b243b5ebdf4e8d5e6bfca6b16f4 to your computer and use it in GitHub Desktop.
public static unsafe class BinaryWriterExtensions {
public static void Write(this IBinaryWriter writer, byte value) {
writer.WriteBytes(&value, 1);
}
public static void Write(this IBinaryWriter writer, int value) {
writer.WriteBytes(&value, sizeof(int));
}
public static void Write(this IBinaryWriter writer, ulong value) {
writer.WriteBytes(&value, sizeof(ulong));
}
public static void Write(this IBinaryWriter writer, ushort value) {
writer.WriteBytes(&value, sizeof(ushort));
}
public static void Write(this IBinaryWriter writer, byte[] bytes) {
fixed (byte* p = bytes) {
writer.WriteBytes(p, bytes.Length);
}
}
public static void WriteArray<T>(this IBinaryWriter writer, NativeArray<T> data) where T : struct {
writer.WriteBytes(data.GetUnsafeReadOnlyPtr(), data.Length * UnsafeUtility.SizeOf<T>());
}
public static void WriteList<T>(this IBinaryWriter writer, NativeList<T> data) where T : struct {
writer.WriteBytes(data.GetUnsafePtr(), data.Length * UnsafeUtility.SizeOf<T>());
}
}
public static unsafe class BinaryReaderExtensions {
public static byte ReadByte(this IBinaryReader reader) {
byte value;
reader.ReadBytes(&value, 1);
return value;
}
public static int ReadInt(this IBinaryReader reader) {
int value;
reader.ReadBytes(&value, sizeof(int));
return value;
}
public static ushort ReadUShort(this IBinaryReader reader) {
ushort value;
reader.ReadBytes(&value, sizeof(ushort));
return value;
}
public static ulong ReadULong(this IBinaryReader reader) {
ulong value;
reader.ReadBytes(&value, sizeof(ulong));
return value;
}
public static void ReadBytes(this IBinaryReader writer, NativeArray<byte> elements, int count, int offset = 0) {
byte* destination = (byte*) elements.GetUnsafePtr() + offset;
writer.ReadBytes(destination, count);
}
public static void ReadArray<T>(this IBinaryReader reader, NativeArray<T> elements, int count) where T : struct {
reader.ReadBytes((byte*) elements.GetUnsafePtr(), count * UnsafeUtility.SizeOf<T>());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment