using System.Collections.Generic; using System; using System.IO; using System.Text; namespace MLAgents.SideChannels { /// /// Utility class for reading the data sent to the SideChannel. /// public class IncomingMessage : IDisposable { byte[] m_Data; Stream m_Stream; BinaryReader m_Reader; /// /// Construct an IncomingMessage from the byte array. /// /// public IncomingMessage(byte[] data) { m_Data = data; m_Stream = new MemoryStream(data); m_Reader = new BinaryReader(m_Stream); } /// /// Read a boolan value from the message. /// /// public bool ReadBoolean() { return m_Reader.ReadBoolean(); } /// /// Read an integer value from the message. /// /// public int ReadInt32() { return m_Reader.ReadInt32(); } /// /// Read a float value from the message. /// /// public float ReadFloat32() { return m_Reader.ReadSingle(); } /// /// Read a string value from the message. /// /// public string ReadString() { var strLength = ReadInt32(); var str = Encoding.ASCII.GetString(m_Reader.ReadBytes(strLength)); return str; } /// /// Reads a list of floats from the message. The length of the list is stored in the message. /// /// public IList ReadFloatList() { var len = ReadInt32(); var output = new float[len]; for (var i = 0; i < len; i++) { output[i] = ReadFloat32(); } return output; } /// /// Gets the original data of the message. Note that this will return all of the data, /// even if part of it has already been read. /// /// public byte[] GetRawBytes() { return m_Data; } /// /// Clean up the internal storage. /// public void Dispose() { m_Reader?.Dispose(); m_Stream?.Dispose(); } } }