public void BytesToStructArrayTest() { var Data = new byte[] { 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x01, 0x01, 0x02, 0x01, 0x03, 0x01, 0x01, 0x02, 0x02, 0x02, 0x03, 0x02, }; var TestShorts = StructUtils.BytesToStructArray <TestShorts>(Data); Assert.AreEqual("TestShorts(0x0001, 0x0002, 0x0003)", TestShorts[0].ToString()); Assert.AreEqual("TestShorts(0x0101, 0x0102, 0x0103)", TestShorts[1].ToString()); Assert.AreEqual("TestShorts(0x0201, 0x0202, 0x0203)", TestShorts[2].ToString()); }
/// <summary> /// /// </summary> /// <typeparam name="TType"></typeparam> /// <param name="Stream"></param> /// <param name="Count"></param> /// <param name="EntrySize"></param> /// <param name="AllowReadLess"></param> /// <returns></returns> public static TType[] ReadStructVector <TType>(this Stream Stream, uint Count, int EntrySize = -1, bool AllowReadLess = false) where TType : struct { if (Count == 0) { return(new TType[0]); } var ItemSize = Marshal.SizeOf(typeof(TType)); var SkipSize = (EntrySize == -1) ? (0) : (EntrySize - ItemSize); var MaxCount = (uint)(Stream.Length / (ItemSize + SkipSize)); if (AllowReadLess) { Count = Math.Min(MaxCount, Count); } if (SkipSize < 0) { throw (new Exception("Invalid Size")); } else if (SkipSize == 0) { return(StructUtils.BytesToStructArray <TType>(Stream.ReadBytes((int)(ItemSize * Count)))); } else { TType[] Vector = new TType[Count]; for (int n = 0; n < Count; n++) { Vector[n] = ReadStruct <TType>(Stream); Stream.Skip(SkipSize); } return(Vector); } }
/// <summary> /// /// </summary> /// <typeparam name="TType"></typeparam> /// <param name="stream"></param> /// <param name="count"></param> /// <param name="entrySize"></param> /// <param name="allowReadLess"></param> /// <returns></returns> public static TType[] ReadStructVector <TType>(this Stream stream, uint count, int entrySize = -1, bool allowReadLess = false) where TType : struct { if (count == 0) { return(new TType[0]); } var itemSize = Marshal.SizeOf(typeof(TType)); var skipSize = (entrySize == -1) ? (0) : (entrySize - itemSize); var maxCount = (uint)(stream.Length / (itemSize + skipSize)); if (allowReadLess) { count = Math.Min(maxCount, count); } if (skipSize < 0) { throw (new Exception("Invalid Size")); } if (skipSize == 0) { return(StructUtils.BytesToStructArray <TType>(stream.ReadBytes((int)(itemSize * count)))); } var vector = new TType[count]; for (var n = 0; n < count; n++) { vector[n] = ReadStruct <TType>(stream); stream.Skip(skipSize); } return(vector); }