From 93b606da2c4ce082dd619abc47b3bdcd2bb7629d Mon Sep 17 00:00:00 2001 From: Paul Chote Date: Fri, 31 May 2013 19:32:59 +1200 Subject: [PATCH] Add stream extensions for reading basic types. --- OpenRA.FileFormats/StreamExts.cs | 63 ++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/OpenRA.FileFormats/StreamExts.cs b/OpenRA.FileFormats/StreamExts.cs index 1d9c3bfe50..0604cc25f6 100755 --- a/OpenRA.FileFormats/StreamExts.cs +++ b/OpenRA.FileFormats/StreamExts.cs @@ -11,11 +11,74 @@ using System; using System.Collections.Generic; using System.IO; +using System.Text; namespace OpenRA { public static class StreamExts { + public static byte[] ReadBytes(this Stream s, int count) + { + if (count < 0) + throw new ArgumentOutOfRangeException("count", "Non-negative number required."); + + var buf = new byte[count]; + if (s.Read(buf, 0, count) < count) + throw new EndOfStreamException(); + + return buf; + } + + public static int Peek(this Stream s) + { + var buf = new byte[1]; + if (s.Read(buf, 0, 1) == 0) + return -1; + + s.Seek(s.Position - 1, SeekOrigin.Begin); + return buf[0]; + } + + public static byte ReadUInt8(this Stream s) + { + return s.ReadBytes(1)[0]; + } + + public static ushort ReadUInt16(this Stream s) + { + return BitConverter.ToUInt16(s.ReadBytes(2), 0); + } + + public static short ReadInt16(this Stream s) + { + return BitConverter.ToInt16(s.ReadBytes(2), 0); + } + + public static uint ReadUInt32(this Stream s) + { + return BitConverter.ToUInt32(s.ReadBytes(4), 0); + } + + public static int ReadInt32(this Stream s) + { + return BitConverter.ToInt32(s.ReadBytes(4), 0); + } + + public static float ReadFloat(this Stream s) + { + return BitConverter.ToSingle(s.ReadBytes(4), 0); + } + + public static double ReadDouble(this Stream s) + { + return BitConverter.ToDouble(s.ReadBytes(8), 0); + } + + public static string ReadASCII(this Stream s, int length) + { + return new string(Encoding.ASCII.GetChars(s.ReadBytes(length))); + } + public static string ReadAllText(this Stream s) { using (s)