// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tools.DotNETCommon { public static class BinaryReaderExtensions { /// /// Read an array of objects from a binary reader /// /// The element type for the array /// Reader to read data from /// Delegate to call to serialize each element /// Array of objects, as serialized. May be null. public static T[] ReadArray(this BinaryReader Reader, Func ReadElement) { int NumItems = Reader.ReadInt32(); if(NumItems < 0) { return null; } T[] Items = new T[NumItems]; for(int Idx = 0; Idx < NumItems; Idx++) { Items[Idx] = ReadElement(Reader); } return Items; } /// /// Read a list of objects from a binary reader /// /// The element type for the list /// Reader to read data from /// Delegate to call to serialize each element /// List of objects, as serialized. May be null. public static List ReadList(this BinaryReader Reader, Func ReadElement) { T[] Items = Reader.ReadArray(ReadElement); return (Items == null)? null : new List(Items); } /// /// Reads a value of a specific type from a binary reader /// /// Reader for input data /// Type of value to read /// The value read from the stream public static object ReadObject(this BinaryReader Reader, Type ObjectType) { if(ObjectType == typeof(string)) { return Reader.ReadString(); } else if(ObjectType == typeof(bool)) { return Reader.ReadBoolean(); } else if(ObjectType == typeof(int)) { return Reader.ReadInt32(); } else if(ObjectType == typeof(float)) { return Reader.ReadSingle(); } else if(ObjectType == typeof(double)) { return Reader.ReadDouble(); } else if(ObjectType == typeof(string[])) { return Reader.ReadArray(x => x.ReadString()); } else if(ObjectType.IsEnum) { return Enum.ToObject(ObjectType, Reader.ReadInt32()); } else { throw new Exception(String.Format("Reading binary objects of type '{0}' is not currently supported.", ObjectType.Name)); } } } }