using System;
using System.Runtime.InteropServices;
namespace Hast.Transformer.Abstractions.SimpleMemory
{
///
/// Represents a simplified memory model available on the FPGA for transformed algorithms. WARNING: SimpleMemory is
/// NOT thread-safe, there shouldn't be any concurrent access to it.
///
///
/// All read/write methods' name MUST follow the convention to begin with "Read" or "Write" respectively.
///
/// WARNING: changes here should be in sync with the VHDL library. The signatures of the methods of this class
/// mustn't be changed (i.e. no renames, new or re-ordered arguments) without making adequate changes to the VHDL
/// library too.
///
public class SimpleMemory
{
public const int MemoryCellSizeBytes = sizeof(int);
///
/// The number of extra cells used for header information like memberId or data length.
///
public int PrefixCellCount { get; internal set; } = 4;
///
/// This is the full memory including the cells of extra memory that is to be used
/// for passing in extra input parameters (like memberId) without having to copy the operative memory contents
/// into an auxiliary array.
///
internal Memory PrefixedMemory { get; set; }
///
/// Gets or sets the contents of the memory representation.
///
///
/// This is internal so the property can be read when handling communication with the FPGA but not by user code.
///
internal Memory Memory => PrefixedMemory.Slice(PrefixCellCount * MemoryCellSizeBytes);
///
/// Gets the number of bytes of this memory allocation.
///
public int ByteCount => Memory.Length;
///
/// Gets the number of cells of this memory allocation, indicating memory cells of size .
///
public int CellCount => Memory.Length / MemoryCellSizeBytes;
///
/// Gets the span of memory at the cellIndex, the length is .
///
/// The cell index where the memory span starts.
/// A span starting at cellIndex * MemoryCellSizeBytes.
private Span this[int cellIndex]
{
get => Memory.Slice(cellIndex * MemoryCellSizeBytes, MemoryCellSizeBytes).Span;
}
///
/// Constructs a new object that represents a simplified memory model available on
/// the FPGA for transformed algorithms.
///
///
/// The number of memory "cells". The memory is divided into independently accessible "cells"; the size of the
/// allocated memory space is calculated from the cell count and the cell size indicated in
/// .
///
public SimpleMemory(int cellCount)
{
PrefixedMemory = new byte[(cellCount + PrefixCellCount) * MemoryCellSizeBytes];
}
///
/// Constructs a new object that represents a simplified memory model available on
/// the FPGA for transformed algorithms from an existing byte array.
///
/// The source data.
/// The amount of cells for header data. See .
///
/// This constructor is internal only to avoid dependency issues where we have to include System.Memory package
/// everywhere where SimpleMemory is used even if it's created with the other constructors. Instead, you can use
/// to construct a from
/// .
///
internal SimpleMemory(Memory memory, int prefixCellCount)
{
PrefixedMemory = memory;
PrefixCellCount = prefixCellCount;
}
///
/// Constructs a new object that represents a simplified memory model available on
/// the FPGA for transformed algorithms from an existing byte array.
///
/// The source data.
/// The amount of cells for header data. See .
private SimpleMemory(byte[] memory, int prefixCellCount = 0) : this(memory.AsMemory(), prefixCellCount) { }
public void Write4Bytes(int cellIndex, byte[] bytes)
{
var target = this[cellIndex];
for (int i = 0; i < bytes.Length; i++) target[i] = bytes[i];
for (int i = bytes.Length; i < MemoryCellSizeBytes; i++) target[i] = 0;
}
public void Write4Bytes(int startCellIndex, byte[][] bytesMatrix)
{
for (int i = 0; i < bytesMatrix.Length; i++)
Write4Bytes(startCellIndex + i, bytesMatrix[i]);
}
public byte[] Read4Bytes(int cellIndex)
{
var output = new byte[MemoryCellSizeBytes];
this[cellIndex].CopyTo(output);
return output;
}
public byte[][] Read4Bytes(int startCellIndex, int count)
{
var bytesMatrix = new byte[count][];
for (int i = 0; i < count; i++)
{
bytesMatrix[i] = Read4Bytes(startCellIndex + i);
}
return bytesMatrix;
}
public void WriteUInt32(int cellIndex, uint number) => MemoryMarshal.Write(this[cellIndex], ref number);
public void WriteUInt32(int startCellIndex, params uint[] numbers) =>
MemoryMarshal.Cast(numbers)
.CopyTo(Memory.Slice(startCellIndex * MemoryCellSizeBytes, numbers.Length * sizeof(uint)).Span);
public uint ReadUInt32(int cellIndex) => MemoryMarshal.Read(this[cellIndex]);
public uint[] ReadUInt32(int startCellIndex, int count) =>
MemoryMarshal.Cast(Memory.Slice(startCellIndex * MemoryCellSizeBytes, count * sizeof(uint)).Span).ToArray();
public void WriteInt32(int cellIndex, int number) => Write4Bytes(cellIndex, BitConverter.GetBytes(number));
public void WriteInt32(int startCellIndex, params int[] numbers) =>
MemoryMarshal.Cast(numbers)
.CopyTo(Memory.Slice(startCellIndex * MemoryCellSizeBytes, numbers.Length * sizeof(int)).Span);
public int ReadInt32(int cellIndex) => MemoryMarshal.Read(this[cellIndex]);
///
/// Takes count integers at cellIndex.
///
/// The cell of the first integer
/// The amount of integers
/// The numbers in an array.
public int[] ReadInt32(int startCellIndex, int count) =>
MemoryMarshal.Cast(Memory.Slice(startCellIndex * MemoryCellSizeBytes, count * sizeof(int)).Span).ToArray();
public void WriteBoolean(int cellIndex, bool boolean) =>
// Since the implementation of a boolean can depend on the system rather hard-coding the expected values
// here so on the FPGA-side we can depend on it. Can't call MemoryMarshal.Write directly because its second
// parameter must be passed using "ref" and you can't pass in constants or expressions by reference.
WriteUInt32(cellIndex, boolean ? uint.MaxValue : uint.MinValue);
public void WriteBoolean(int startCellIndex, params bool[] booleans)
{
for (int i = 0; i < booleans.Length; i++)
WriteBoolean(startCellIndex + i, booleans[i]);
}
public bool ReadBoolean(int cellIndex) => MemoryMarshal.Read(this[cellIndex]) != uint.MinValue;
public bool[] ReadBoolean(int startCellIndex, int count)
{
var source = ReadUInt32(startCellIndex, count);
var booleans = new bool[count];
for (int i = 0; i < count; i++)
booleans[i] = source[i] == uint.MaxValue;
return booleans;
}
}
///
/// Extensions for older Framework features which don't support Memory or Span yet.
///
public static class MemoryExtensions
{
///
/// Gets the internal array to be used for .
///
/// The source.
/// The underlying array.
///
/// Once Stream.Read(Span) based overload is available, use that instead!
/// https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.read?view=netcore-2.2#System_IO_Stream_Read_System_Span_System_Byte__
///
public static ArraySegment GetUnderlyingArray(this Memory bytes) => GetUnderlyingArray((ReadOnlyMemory)bytes);
public static ArraySegment GetUnderlyingArray(this ReadOnlyMemory bytes)
{
if (!MemoryMarshal.TryGetArray(bytes, out var arraySegment)) throw new NotSupportedException("This Memory does not support exposing the underlying array.");
return arraySegment;
}
}
}