BinaryReader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. //
  2. // System.IO.BinaryReader
  3. //
  4. // Author:
  5. // Matt Kimball ([email protected])
  6. // Dick Porter ([email protected])
  7. //
  8. //
  9. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Text;
  32. using System.Globalization;
  33. using Mono.Security;
  34. using System.Runtime.InteropServices;
  35. namespace System.IO {
  36. [ComVisible (true)]
  37. public class BinaryReader : IDisposable {
  38. Stream m_stream;
  39. Encoding m_encoding;
  40. byte[] m_buffer;
  41. Decoder decoder;
  42. char [] charBuffer;
  43. //
  44. // 128 chars should cover most strings in one grab.
  45. //
  46. const int MaxBufferSize = 128;
  47. private bool m_disposed = false;
  48. public BinaryReader(Stream input) : this(input, Encoding.UTF8UnmarkedUnsafe) {
  49. }
  50. public BinaryReader(Stream input, Encoding encoding) {
  51. if (input == null || encoding == null)
  52. throw new ArgumentNullException(Locale.GetText ("Input or Encoding is a null reference."));
  53. if (!input.CanRead)
  54. throw new ArgumentException(Locale.GetText ("The stream doesn't support reading."));
  55. m_stream = input;
  56. m_encoding = encoding;
  57. decoder = encoding.GetDecoder ();
  58. m_buffer = new byte [32];
  59. }
  60. public virtual Stream BaseStream {
  61. get {
  62. return m_stream;
  63. }
  64. }
  65. public virtual void Close() {
  66. Dispose (true);
  67. m_disposed = true;
  68. }
  69. protected virtual void Dispose (bool disposing)
  70. {
  71. if (disposing && m_stream != null)
  72. m_stream.Close ();
  73. m_disposed = true;
  74. m_buffer = null;
  75. m_encoding = null;
  76. m_stream = null;
  77. charBuffer = null;
  78. }
  79. #if NET_4_0
  80. public void Dispose ()
  81. #else
  82. void IDisposable.Dispose()
  83. #endif
  84. {
  85. Dispose (true);
  86. }
  87. protected virtual void FillBuffer (int numBytes)
  88. {
  89. if (m_disposed)
  90. throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
  91. if (m_stream==null)
  92. throw new IOException("Stream is invalid");
  93. CheckBuffer(numBytes);
  94. /* Cope with partial reads */
  95. int pos=0;
  96. while(pos<numBytes) {
  97. int n=m_stream.Read(m_buffer, pos, numBytes-pos);
  98. if(n==0) {
  99. throw new EndOfStreamException();
  100. }
  101. pos+=n;
  102. }
  103. }
  104. public virtual int PeekChar() {
  105. if(m_stream==null) {
  106. if (m_disposed)
  107. throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
  108. throw new IOException("Stream is invalid");
  109. }
  110. if ( !m_stream.CanSeek )
  111. {
  112. return -1;
  113. }
  114. char[] result = new char[1];
  115. int bcount;
  116. int ccount = ReadCharBytes (result, 0, 1, out bcount);
  117. // Reposition the stream
  118. m_stream.Position -= bcount;
  119. // If we read 0 characters then return -1
  120. if (ccount == 0)
  121. {
  122. return -1;
  123. }
  124. // Return the single character we read
  125. return result[0];
  126. }
  127. public virtual int Read() {
  128. if (charBuffer == null)
  129. charBuffer = new char [MaxBufferSize];
  130. int count = Read (charBuffer, 0, 1);
  131. if(count == 0) {
  132. /* No chars available */
  133. return -1;
  134. }
  135. return charBuffer [0];
  136. }
  137. public virtual int Read(byte[] buffer, int index, int count) {
  138. if(m_stream==null) {
  139. if (m_disposed)
  140. throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
  141. throw new IOException("Stream is invalid");
  142. }
  143. if (buffer == null) {
  144. throw new ArgumentNullException("buffer is null");
  145. }
  146. if (index < 0) {
  147. throw new ArgumentOutOfRangeException("index is less than 0");
  148. }
  149. if (count < 0) {
  150. throw new ArgumentOutOfRangeException("count is less than 0");
  151. }
  152. if (buffer.Length - index < count) {
  153. throw new ArgumentException("buffer is too small");
  154. }
  155. int bytes_read=m_stream.Read(buffer, index, count);
  156. return(bytes_read);
  157. }
  158. public virtual int Read(char[] buffer, int index, int count) {
  159. if(m_stream==null) {
  160. if (m_disposed)
  161. throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
  162. throw new IOException("Stream is invalid");
  163. }
  164. if (buffer == null) {
  165. throw new ArgumentNullException("buffer is null");
  166. }
  167. if (index < 0) {
  168. throw new ArgumentOutOfRangeException("index is less than 0");
  169. }
  170. if (count < 0) {
  171. throw new ArgumentOutOfRangeException("count is less than 0");
  172. }
  173. if (buffer.Length - index < count) {
  174. throw new ArgumentException("buffer is too small");
  175. }
  176. int bytes_read;
  177. return ReadCharBytes (buffer, index, count, out bytes_read);
  178. }
  179. private int ReadCharBytes (char[] buffer, int index, int count, out int bytes_read)
  180. {
  181. int chars_read = 0;
  182. bytes_read = 0;
  183. while (chars_read < count) {
  184. int pos = 0;
  185. while (true) {
  186. CheckBuffer (pos + 1);
  187. int read_byte = m_stream.ReadByte ();
  188. if (read_byte == -1)
  189. /* EOF */
  190. return chars_read;
  191. m_buffer [pos ++] = (byte)read_byte;
  192. bytes_read ++;
  193. int n = m_encoding.GetChars (m_buffer, 0, pos, buffer, index + chars_read);
  194. if (n > 0)
  195. break;
  196. }
  197. chars_read ++;
  198. }
  199. return chars_read;
  200. }
  201. protected int Read7BitEncodedInt() {
  202. int ret = 0;
  203. int shift = 0;
  204. int len;
  205. byte b;
  206. for (len = 0; len < 5; ++len) {
  207. b = ReadByte();
  208. ret = ret | ((b & 0x7f) << shift);
  209. shift += 7;
  210. if ((b & 0x80) == 0)
  211. break;
  212. }
  213. if (len < 5)
  214. return ret;
  215. else
  216. throw new FormatException ("Too many bytes in what should have been a 7 bit encoded Int32.");
  217. }
  218. public virtual bool ReadBoolean() {
  219. // Return value:
  220. // true if the byte is non-zero; otherwise false.
  221. return ReadByte() != 0;
  222. }
  223. public virtual byte ReadByte() {
  224. if (m_stream == null) {
  225. if (m_disposed)
  226. throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
  227. throw new IOException ("Stream is invalid");
  228. }
  229. int val = m_stream.ReadByte ();
  230. if (val != -1)
  231. return (byte) val;
  232. throw new EndOfStreamException ();
  233. }
  234. public virtual byte[] ReadBytes(int count) {
  235. if(m_stream==null) {
  236. if (m_disposed)
  237. throw new ObjectDisposedException ("BinaryReader", "Cannot read from a closed BinaryReader.");
  238. throw new IOException("Stream is invalid");
  239. }
  240. if (count < 0) {
  241. throw new ArgumentOutOfRangeException("count is less than 0");
  242. }
  243. /* Can't use FillBuffer() here, because it's OK to
  244. * return fewer bytes than were requested
  245. */
  246. byte[] buf = new byte[count];
  247. int pos=0;
  248. while(pos < count)
  249. {
  250. int n=m_stream.Read(buf, pos, count-pos);
  251. if(n==0) {
  252. /* EOF */
  253. break;
  254. }
  255. pos+=n;
  256. }
  257. if (pos!=count) {
  258. byte[] new_buffer=new byte[pos];
  259. Buffer.BlockCopyInternal (buf, 0, new_buffer, 0, pos);
  260. return(new_buffer);
  261. }
  262. return(buf);
  263. }
  264. public virtual char ReadChar() {
  265. int ch=Read();
  266. if(ch==-1) {
  267. throw new EndOfStreamException();
  268. }
  269. return((char)ch);
  270. }
  271. public virtual char[] ReadChars(int count) {
  272. if (count < 0) {
  273. throw new ArgumentOutOfRangeException("count is less than 0");
  274. }
  275. if (count == 0)
  276. return new char [0];
  277. char[] full = new char[count];
  278. int chars = Read(full, 0, count);
  279. if (chars == 0) {
  280. throw new EndOfStreamException();
  281. } else if (chars != full.Length) {
  282. char[] ret = new char[chars];
  283. Array.Copy(full, 0, ret, 0, chars);
  284. return ret;
  285. } else {
  286. return full;
  287. }
  288. }
  289. unsafe public virtual decimal ReadDecimal() {
  290. FillBuffer(16);
  291. decimal ret;
  292. byte* ret_ptr = (byte *)&ret;
  293. /*
  294. * internal representation of decimal is
  295. * ss32, hi32, lo32, mi32,
  296. * but in stream it is
  297. * lo32, mi32, hi32, ss32
  298. * So we have to rerange this int32 values
  299. */
  300. if (BitConverter.IsLittleEndian) {
  301. for (int i = 0; i < 16; i++) {
  302. if (i < 4) {
  303. // lo 8 - 12
  304. ret_ptr [i + 8] = m_buffer [i];
  305. } else if (i < 8) {
  306. // mid 12 - 16
  307. ret_ptr [i + 8] = m_buffer [i];
  308. } else if (i < 12) {
  309. // hi 4 - 8
  310. ret_ptr [i - 4] = m_buffer [i];
  311. } else if (i < 16) {
  312. // ss 0 - 4
  313. ret_ptr [i - 12] = m_buffer [i];
  314. }
  315. }
  316. } else {
  317. for (int i = 0; i < 16; i++) {
  318. if (i < 4) {
  319. // lo 8 - 12
  320. ret_ptr [11 - i] = m_buffer [i];
  321. } else if (i < 8) {
  322. // mid 12 - 16
  323. ret_ptr [19 - i] = m_buffer [i];
  324. } else if (i < 12) {
  325. // hi 4 - 8
  326. ret_ptr [15 - i] = m_buffer [i];
  327. } else if (i < 16) {
  328. // ss 0 - 4
  329. ret_ptr [15 - i] = m_buffer [i];
  330. }
  331. }
  332. }
  333. return ret;
  334. }
  335. public virtual double ReadDouble() {
  336. FillBuffer(8);
  337. return(BitConverterLE.ToDouble(m_buffer, 0));
  338. }
  339. public virtual short ReadInt16() {
  340. FillBuffer(2);
  341. return((short) (m_buffer[0] | (m_buffer[1] << 8)));
  342. }
  343. public virtual int ReadInt32() {
  344. FillBuffer(4);
  345. return(m_buffer[0] | (m_buffer[1] << 8) |
  346. (m_buffer[2] << 16) | (m_buffer[3] << 24));
  347. }
  348. public virtual long ReadInt64() {
  349. FillBuffer(8);
  350. uint ret_low = (uint) (m_buffer[0] |
  351. (m_buffer[1] << 8) |
  352. (m_buffer[2] << 16) |
  353. (m_buffer[3] << 24)
  354. );
  355. uint ret_high = (uint) (m_buffer[4] |
  356. (m_buffer[5] << 8) |
  357. (m_buffer[6] << 16) |
  358. (m_buffer[7] << 24)
  359. );
  360. return (long) ((((ulong) ret_high) << 32) | ret_low);
  361. }
  362. [CLSCompliant(false)]
  363. public virtual sbyte ReadSByte() {
  364. return (sbyte) ReadByte ();
  365. }
  366. public virtual string ReadString() {
  367. /* Inspection of BinaryWriter-written files
  368. * shows that the length is given in bytes,
  369. * not chars
  370. */
  371. int len = Read7BitEncodedInt();
  372. if (len < 0)
  373. throw new IOException ("Invalid binary file (string len < 0)");
  374. if (len == 0)
  375. return String.Empty;
  376. if (charBuffer == null)
  377. charBuffer = new char [MaxBufferSize];
  378. //
  379. // We read the string here in small chunks. Also, we
  380. // Attempt to optimize the common case of short strings.
  381. //
  382. StringBuilder sb = null;
  383. do {
  384. int readLen = (len > MaxBufferSize)
  385. ? MaxBufferSize
  386. : len;
  387. FillBuffer (readLen);
  388. int cch = decoder.GetChars (m_buffer, 0, readLen, charBuffer, 0);
  389. if (sb == null && readLen == len) // ok, we got out the easy way, dont bother with the sb
  390. return new String (charBuffer, 0, cch);
  391. if (sb == null)
  392. // Len is a fairly good estimate of the number of chars in a string
  393. // Most of the time 1 byte == 1 char
  394. sb = new StringBuilder (len);
  395. sb.Append (charBuffer, 0, cch);
  396. len -= readLen;
  397. } while (len > 0);
  398. return sb.ToString();
  399. }
  400. public virtual float ReadSingle() {
  401. FillBuffer(4);
  402. return(BitConverterLE.ToSingle(m_buffer, 0));
  403. }
  404. [CLSCompliant(false)]
  405. public virtual ushort ReadUInt16() {
  406. FillBuffer(2);
  407. return((ushort) (m_buffer[0] | (m_buffer[1] << 8)));
  408. }
  409. [CLSCompliant(false)]
  410. public virtual uint ReadUInt32() {
  411. FillBuffer(4);
  412. return((uint) (m_buffer[0] |
  413. (m_buffer[1] << 8) |
  414. (m_buffer[2] << 16) |
  415. (m_buffer[3] << 24)));
  416. }
  417. [CLSCompliant(false)]
  418. public virtual ulong ReadUInt64() {
  419. FillBuffer(8);
  420. uint ret_low = (uint) (m_buffer[0] |
  421. (m_buffer[1] << 8) |
  422. (m_buffer[2] << 16) |
  423. (m_buffer[3] << 24)
  424. );
  425. uint ret_high = (uint) (m_buffer[4] |
  426. (m_buffer[5] << 8) |
  427. (m_buffer[6] << 16) |
  428. (m_buffer[7] << 24)
  429. );
  430. return (((ulong) ret_high) << 32) | ret_low;
  431. }
  432. /* Ensures that m_buffer is at least length bytes
  433. * long, growing it if necessary
  434. */
  435. private void CheckBuffer(int length)
  436. {
  437. if(m_buffer.Length <= length) {
  438. byte[] new_buffer=new byte[length];
  439. Buffer.BlockCopyInternal (m_buffer, 0, new_buffer, 0, m_buffer.Length);
  440. m_buffer=new_buffer;
  441. }
  442. }
  443. }
  444. }