Files
Aaru/Aaru.Helpers/Marshal.cs

304 lines
14 KiB
C#
Raw Permalink Normal View History

2019-02-27 08:49:42 +00:00
// /***************************************************************************
2020-02-27 12:31:23 +00:00
// Aaru Data Preservation Suite
2019-02-27 08:49:42 +00:00
// ----------------------------------------------------------------------------
//
// Filename : Marshal.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Helpers.
//
// --[ Description ] ----------------------------------------------------------
//
// Provides marshalling for binary data.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
2024-12-19 10:45:18 +00:00
// Copyright © 2011-2025 Natalia Portillo
2019-02-27 08:49:42 +00:00
// ****************************************************************************/
using System;
2021-08-17 16:27:42 +01:00
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
2019-02-27 08:49:42 +00:00
using System.Runtime.InteropServices;
namespace Aaru.Helpers;
2022-03-06 13:29:37 +00:00
/// <summary>Provides methods to marshal binary data into C# structs</summary>
2023-10-05 01:05:21 +01:00
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
2022-03-06 13:29:37 +00:00
public static class Marshal
2019-02-27 08:49:42 +00:00
{
2022-03-06 13:29:37 +00:00
/// <summary>Returns the size of an unmanaged type in bytes.</summary>
/// <typeparam name="T">The type whose size is to be returned.</typeparam>
/// <returns>The size, in bytes, of the type that is specified by the <see cref="T" /> generic type parameter.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int SizeOf<T>() => System.Runtime.InteropServices.Marshal.SizeOf<T>();
/// <summary>Marshal little-endian binary data to a structure</summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ByteArrayToStructureLittleEndian<T>(byte[] bytes) where T : struct
2019-02-27 08:49:42 +00:00
{
2022-03-06 13:29:37 +00:00
var ptr = GCHandle.Alloc(bytes, GCHandleType.Pinned);
2019-11-25 00:54:39 +00:00
2022-03-17 00:46:26 +00:00
var str = (T)(System.Runtime.InteropServices.Marshal.PtrToStructure(ptr.AddrOfPinnedObject(), typeof(T)) ??
default(T));
2019-11-25 00:54:39 +00:00
2022-03-06 13:29:37 +00:00
ptr.Free();
2019-11-25 00:54:39 +00:00
2022-03-06 13:29:37 +00:00
return str;
}
2019-02-27 08:49:42 +00:00
2022-03-06 13:29:37 +00:00
/// <summary>Marshal little-endian binary data to a structure</summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <param name="start">Start on the array where the structure begins</param>
/// <param name="length">Length of the structure in bytes</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ByteArrayToStructureLittleEndian<T>(byte[] bytes, int start, int length) where T : struct
{
Span<byte> span = bytes;
2019-11-25 00:54:39 +00:00
2022-03-06 13:29:37 +00:00
return ByteArrayToStructureLittleEndian<T>(span.Slice(start, length).ToArray());
}
/// <summary>
/// Marshal big-endian binary data to a structure using compile-time generated swap method.
/// </summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <typeparam name="T">Type of the structure to marshal (must be marked with [SwapEndian] attribute)</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ByteArrayToStructureBigEndian<T>(byte[] bytes) where T : struct, ISwapEndian<T>
{
T str = ByteArrayToStructureLittleEndian<T>(bytes);
return str.SwapEndian();
}
/// <summary>
/// Marshal big-endian binary data to a structure using compile-time generated swap method.
/// </summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <param name="start">Start on the array where the structure begins</param>
/// <param name="length">Length of the structure in bytes</param>
/// <typeparam name="T">Type of the structure to marshal (must be marked with [SwapEndian] attribute)</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ByteArrayToStructureBigEndian<T>(byte[] bytes, int start, int length)
where T : struct, ISwapEndian<T>
{
Span<byte> span = bytes;
2022-03-06 13:29:37 +00:00
return ByteArrayToStructureBigEndian<T>(span.Slice(start, length).ToArray());
}
2022-03-06 13:29:37 +00:00
/// <summary>Marshal PDP-11 binary data to a structure</summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ByteArrayToStructurePdpEndian<T>(byte[] bytes) where T : struct, ISwapPdpEndian<T>
2022-03-06 13:29:37 +00:00
{
T str = ByteArrayToStructureLittleEndian<T>(bytes);
2019-11-25 00:54:39 +00:00
return str.SwapPdpEndian();
2022-03-06 13:29:37 +00:00
}
2019-02-27 08:49:42 +00:00
2022-03-06 13:29:37 +00:00
/// <summary>Marshal PDP-11 binary data to a structure</summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <param name="start">Start on the array where the structure begins</param>
/// <param name="length">Length of the structure in bytes</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ByteArrayToStructurePdpEndian<T>(byte[] bytes, int start, int length)
where T : struct, ISwapPdpEndian<T>
2022-03-06 13:29:37 +00:00
{
Span<byte> span = bytes;
2019-11-25 00:54:39 +00:00
2022-03-06 13:29:37 +00:00
return ByteArrayToStructurePdpEndian<T>(span.Slice(start, length).ToArray());
}
2022-03-06 13:29:37 +00:00
/// <summary>
/// Marshal little-endian binary data to a structure. If the structure type contains any non value type, this
/// method will crash.
/// </summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T SpanToStructureLittleEndian<T>(ReadOnlySpan<byte> bytes) where T : struct =>
MemoryMarshal.Read<T>(bytes);
/// <summary>
/// Marshal little-endian binary data to a structure. If the structure type contains any non value type, this
/// method will crash.
/// </summary>
/// <param name="bytes">Byte span containing the binary data</param>
/// <param name="start">Start on the span where the structure begins</param>
/// <param name="length">Length of the structure in bytes</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2022-03-07 07:36:42 +00:00
public static T SpanToStructureLittleEndian<T>(ReadOnlySpan<byte> bytes, int start, int length) where T : struct =>
MemoryMarshal.Read<T>(bytes.Slice(start, length));
2022-03-06 13:29:37 +00:00
/// <summary>
/// Marshal big-endian binary data to a structure using compile-time generated swap method.
/// If the structure type contains any non value type, this method will crash.
/// </summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <typeparam name="T">Type of the structure to marshal (must be marked with [SwapEndian] attribute)</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T SpanToStructureBigEndian<T>(ReadOnlySpan<byte> bytes) where T : struct, ISwapEndian<T>
{
T str = SpanToStructureLittleEndian<T>(bytes);
return str.SwapEndian();
}
/// <summary>
/// Marshal big-endian binary data to a structure using compile-time generated swap method.
/// If the structure type contains any non value type, this method will crash.
2022-03-06 13:29:37 +00:00
/// </summary>
/// <param name="bytes">Byte span containing the binary data</param>
/// <param name="start">Start on the span where the structure begins</param>
/// <param name="length">Length of the structure in bytes</param>
/// <typeparam name="T">Type of the structure to marshal (must be marked with [SwapEndian] attribute)</typeparam>
2022-03-06 13:29:37 +00:00
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T SpanToStructureBigEndian<T>(ReadOnlySpan<byte> bytes, int start, int length)
where T : struct, ISwapEndian<T>
2022-03-06 13:29:37 +00:00
{
T str = SpanToStructureLittleEndian<T>(bytes.Slice(start, length));
2019-11-25 00:54:39 +00:00
return str.SwapEndian();
2022-03-06 13:29:37 +00:00
}
2022-03-06 13:29:37 +00:00
/// <summary>
/// Marshal PDP-11 binary data to a structure. If the structure type contains any non value type, this method will
/// crash.
/// </summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T SpanToStructurePdpEndian<T>(ReadOnlySpan<byte> bytes) where T : struct, ISwapPdpEndian<T>
2022-03-06 13:29:37 +00:00
{
T str = SpanToStructureLittleEndian<T>(bytes);
2019-11-25 00:54:39 +00:00
return str.SwapPdpEndian();
2022-03-06 13:29:37 +00:00
}
2019-02-27 08:49:42 +00:00
2022-03-06 13:29:37 +00:00
/// <summary>
/// Marshal PDP-11 binary data to a structure. If the structure type contains any non value type, this method will
/// crash.
/// </summary>
/// <param name="bytes">Byte array containing the binary data</param>
/// <param name="start">Start on the span where the structure begins</param>
/// <param name="length">Length of the structure in bytes</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The binary data marshalled in a structure with the specified type</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T SpanToStructurePdpEndian<T>(ReadOnlySpan<byte> bytes, int start, int length)
where T : struct, ISwapPdpEndian<T>
2022-03-06 13:29:37 +00:00
{
T str = SpanToStructureLittleEndian<T>(bytes.Slice(start, length));
2019-11-25 00:54:39 +00:00
return str.SwapPdpEndian();
2022-03-06 13:29:37 +00:00
}
2022-03-06 13:29:37 +00:00
/// <summary>Marshal a structure to little-endian binary data</summary>
/// <param name="str">The structure you want to marshal to binary</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The byte array representing the given structure</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] StructureToByteArrayLittleEndian<T>(T str) where T : struct
{
2023-10-03 23:25:24 +01:00
var buf = new byte[SizeOf<T>()];
var ptr = GCHandle.Alloc(buf, GCHandleType.Pinned);
2022-03-06 13:29:37 +00:00
System.Runtime.InteropServices.Marshal.StructureToPtr(str, ptr.AddrOfPinnedObject(), false);
ptr.Free();
2022-03-06 13:29:37 +00:00
return buf;
}
2022-03-06 13:29:37 +00:00
/// <summary>Marshal a structure to little-endian binary data</summary>
/// <param name="str">The structure you want to marshal to binary</param>
/// <typeparam name="T">Type of the structure to marshal</typeparam>
/// <returns>The byte array representing the given structure</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte[] StructureToByteArrayBigEndian<T>(T str) where T : struct, ISwapEndian<T> =>
StructureToByteArrayLittleEndian(str.SwapEndian());
2022-03-06 13:29:37 +00:00
/// <summary>Converts a hexadecimal string into a byte array</summary>
/// <param name="hex">Hexadecimal string</param>
/// <param name="outBuf">Resulting byte array</param>
/// <returns>Number of output bytes processed</returns>
public static int ConvertFromHexAscii(string hex, out byte[] outBuf)
{
outBuf = null;
2024-05-01 04:05:22 +01:00
if(hex is null or "") return -1;
2023-10-03 23:25:24 +01:00
var off = 0;
2024-05-01 04:05:22 +01:00
if(hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) off = 2;
2022-03-06 13:29:37 +00:00
outBuf = new byte[(hex.Length - off) / 2];
2023-10-03 23:25:24 +01:00
var count = 0;
2022-03-06 13:29:37 +00:00
for(int i = off; i < hex.Length; i += 2)
{
char c = hex[i];
2024-05-01 04:05:22 +01:00
if(c is < '0' or > '9' and < 'A' or > 'F' and < 'a' or > 'f') break;
c -= c switch
2023-10-03 23:25:24 +01:00
{
>= 'a' and <= 'f' => '\u0057',
>= 'A' and <= 'F' => '\u0037',
_ => '\u0030'
};
2022-03-06 13:29:37 +00:00
outBuf[(i - off) / 2] = (byte)(c << 4);
2022-03-06 13:29:37 +00:00
c = hex[i + 1];
2024-05-01 04:05:22 +01:00
if(c is < '0' or > '9' and < 'A' or > 'F' and < 'a' or > 'f') break;
c -= c switch
2023-10-03 23:25:24 +01:00
{
>= 'a' and <= 'f' => '\u0057',
>= 'A' and <= 'F' => '\u0037',
_ => '\u0030'
};
2022-03-06 13:29:37 +00:00
outBuf[(i - off) / 2] += (byte)c;
2022-03-06 13:29:37 +00:00
count++;
}
2022-03-06 13:29:37 +00:00
return count;
2019-02-27 08:49:42 +00:00
}
}