StreamReader.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. //
  2. // System.IO.StreamReader.cs
  3. //
  4. // Author:
  5. // Dietmar Maurer ([email protected])
  6. // Miguel de Icaza ([email protected])
  7. // Marek Safar ([email protected])
  8. //
  9. // (C) Ximian, Inc. http://www.ximian.com
  10. // Copyright (C) 2004 Novell (http://www.novell.com)
  11. //
  12. //
  13. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  14. //
  15. // Permission is hereby granted, free of charge, to any person obtaining
  16. // a copy of this software and associated documentation files (the
  17. // "Software"), to deal in the Software without restriction, including
  18. // without limitation the rights to use, copy, modify, merge, publish,
  19. // distribute, sublicense, and/or sell copies of the Software, and to
  20. // permit persons to whom the Software is furnished to do so, subject to
  21. // the following conditions:
  22. //
  23. // The above copyright notice and this permission notice shall be
  24. // included in all copies or substantial portions of the Software.
  25. //
  26. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  27. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  29. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  30. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  31. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  32. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  33. //
  34. using System;
  35. using System.Text;
  36. using System.Runtime.InteropServices;
  37. namespace System.IO {
  38. [Serializable]
  39. [ComVisible (true)]
  40. public class StreamReader : TextReader {
  41. const int DefaultBufferSize = 1024;
  42. const int DefaultFileBufferSize = 4096;
  43. const int MinimumBufferSize = 128;
  44. //
  45. // The input buffer
  46. //
  47. byte [] input_buffer;
  48. // Input buffer ready for recycling
  49. static byte [] input_buffer_recycle;
  50. static object input_buffer_recycle_lock = new object ();
  51. //
  52. // The decoded buffer from the above input buffer
  53. //
  54. char [] decoded_buffer;
  55. static char[] decoded_buffer_recycle;
  56. //
  57. // Decoded bytes in decoded_buffer.
  58. //
  59. int decoded_count;
  60. //
  61. // Current position in the decoded_buffer
  62. //
  63. int pos;
  64. //
  65. // The buffer size that we are using
  66. //
  67. int buffer_size;
  68. int do_checks;
  69. Encoding encoding;
  70. Decoder decoder;
  71. Stream base_stream;
  72. bool mayBlock;
  73. StringBuilder line_builder;
  74. private class NullStreamReader : StreamReader {
  75. public override int Peek ()
  76. {
  77. return -1;
  78. }
  79. public override int Read ()
  80. {
  81. return -1;
  82. }
  83. public override int Read ([In, Out] char[] buffer, int index, int count)
  84. {
  85. return 0;
  86. }
  87. public override string ReadLine ()
  88. {
  89. return null;
  90. }
  91. public override string ReadToEnd ()
  92. {
  93. return String.Empty;
  94. }
  95. public override Stream BaseStream
  96. {
  97. get { return Stream.Null; }
  98. }
  99. public override Encoding CurrentEncoding
  100. {
  101. get { return Encoding.Unicode; }
  102. }
  103. }
  104. public new static readonly StreamReader Null = new NullStreamReader ();
  105. internal StreamReader() {}
  106. public StreamReader(Stream stream)
  107. : this (stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
  108. public StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)
  109. : this (stream, Encoding.UTF8Unmarked, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
  110. public StreamReader(Stream stream, Encoding encoding)
  111. : this (stream, encoding, true, DefaultBufferSize) { }
  112. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
  113. : this (stream, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
  114. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  115. {
  116. Initialize (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
  117. }
  118. public StreamReader(string path)
  119. : this (path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
  120. public StreamReader(string path, bool detectEncodingFromByteOrderMarks)
  121. : this (path, Encoding.UTF8Unmarked, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
  122. public StreamReader(string path, Encoding encoding)
  123. : this (path, encoding, true, DefaultFileBufferSize) { }
  124. public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
  125. : this (path, encoding, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
  126. public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  127. {
  128. if (null == path)
  129. throw new ArgumentNullException("path");
  130. if (String.Empty == path)
  131. throw new ArgumentException("Empty path not allowed");
  132. if (path.IndexOfAny (Path.InvalidPathChars) != -1)
  133. throw new ArgumentException("path contains invalid characters");
  134. if (null == encoding)
  135. throw new ArgumentNullException ("encoding");
  136. if (bufferSize <= 0)
  137. throw new ArgumentOutOfRangeException ("bufferSize", "The minimum size of the buffer must be positive");
  138. Stream stream = (Stream) File.OpenRead (path);
  139. Initialize (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
  140. }
  141. internal void Initialize (Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  142. {
  143. if (null == stream)
  144. throw new ArgumentNullException ("stream");
  145. if (null == encoding)
  146. throw new ArgumentNullException ("encoding");
  147. if (!stream.CanRead)
  148. throw new ArgumentException ("Cannot read stream");
  149. if (bufferSize <= 0)
  150. throw new ArgumentOutOfRangeException ("bufferSize", "The minimum size of the buffer must be positive");
  151. if (bufferSize < MinimumBufferSize)
  152. bufferSize = MinimumBufferSize;
  153. // since GetChars() might add flushed character, it
  154. // should have additional char buffer for extra 1
  155. // (probably 1 is ok, but might be insufficient. I'm not sure)
  156. var decoded_buffer_size = encoding.GetMaxCharCount (bufferSize) + 1;
  157. //
  158. // Instead of allocating a new default buffer use the
  159. // last one if there is any available
  160. //
  161. if (bufferSize <= DefaultBufferSize && input_buffer_recycle != null) {
  162. lock (input_buffer_recycle_lock) {
  163. if (input_buffer_recycle != null) {
  164. input_buffer = input_buffer_recycle;
  165. input_buffer_recycle = null;
  166. }
  167. if (decoded_buffer_recycle != null && decoded_buffer_size <= decoded_buffer_recycle.Length) {
  168. decoded_buffer = decoded_buffer_recycle;
  169. decoded_buffer_recycle = null;
  170. }
  171. }
  172. }
  173. if (input_buffer == null)
  174. input_buffer = new byte [bufferSize];
  175. else
  176. Array.Clear (input_buffer, 0, bufferSize);
  177. if (decoded_buffer == null)
  178. decoded_buffer = new char [decoded_buffer_size];
  179. else
  180. Array.Clear (decoded_buffer, 0, decoded_buffer_size);
  181. base_stream = stream;
  182. this.buffer_size = bufferSize;
  183. this.encoding = encoding;
  184. decoder = encoding.GetDecoder ();
  185. byte [] preamble = encoding.GetPreamble ();
  186. do_checks = detectEncodingFromByteOrderMarks ? 1 : 0;
  187. do_checks += (preamble.Length == 0) ? 0 : 2;
  188. decoded_count = 0;
  189. pos = 0;
  190. }
  191. public virtual Stream BaseStream
  192. {
  193. get {
  194. return base_stream;
  195. }
  196. }
  197. public virtual Encoding CurrentEncoding
  198. {
  199. get {
  200. if (encoding == null)
  201. throw new Exception ();
  202. return encoding;
  203. }
  204. }
  205. public bool EndOfStream {
  206. get { return Peek () < 0; }
  207. }
  208. public override void Close ()
  209. {
  210. Dispose (true);
  211. }
  212. protected override void Dispose (bool disposing)
  213. {
  214. if (disposing && base_stream != null)
  215. base_stream.Close ();
  216. if (input_buffer != null && input_buffer.Length == DefaultBufferSize && input_buffer_recycle == null) {
  217. lock (input_buffer_recycle_lock) {
  218. if (input_buffer_recycle == null) {
  219. input_buffer_recycle = input_buffer;
  220. }
  221. if (decoded_buffer_recycle == null) {
  222. decoded_buffer_recycle = decoded_buffer;
  223. }
  224. }
  225. }
  226. input_buffer = null;
  227. decoded_buffer = null;
  228. encoding = null;
  229. decoder = null;
  230. base_stream = null;
  231. base.Dispose (disposing);
  232. }
  233. //
  234. // Provides auto-detection of the encoding, as well as skipping over
  235. // byte marks at the beginning of a stream.
  236. //
  237. int DoChecks (int count)
  238. {
  239. if ((do_checks & 2) == 2){
  240. byte [] preamble = encoding.GetPreamble ();
  241. int c = preamble.Length;
  242. if (count >= c){
  243. int i;
  244. for (i = 0; i < c; i++)
  245. if (input_buffer [i] != preamble [i])
  246. break;
  247. if (i == c)
  248. return i;
  249. }
  250. }
  251. if ((do_checks & 1) == 1){
  252. if (count < 2)
  253. return 0;
  254. if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff){
  255. this.encoding = Encoding.BigEndianUnicode;
  256. return 2;
  257. }
  258. if (count < 3)
  259. return 0;
  260. if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf){
  261. this.encoding = Encoding.UTF8Unmarked;
  262. return 3;
  263. }
  264. if (count < 4) {
  265. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe && input_buffer [2] != 0) {
  266. this.encoding = Encoding.Unicode;
  267. return 2;
  268. }
  269. return 0;
  270. }
  271. if (input_buffer [0] == 0 && input_buffer [1] == 0
  272. && input_buffer [2] == 0xfe && input_buffer [3] == 0xff)
  273. {
  274. this.encoding = Encoding.BigEndianUTF32;
  275. return 4;
  276. }
  277. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe) {
  278. if (input_buffer [2] == 0 && input_buffer[3] == 0) {
  279. this.encoding = Encoding.UTF32;
  280. return 4;
  281. }
  282. this.encoding = Encoding.Unicode;
  283. return 2;
  284. }
  285. }
  286. return 0;
  287. }
  288. public void DiscardBufferedData ()
  289. {
  290. pos = decoded_count = 0;
  291. mayBlock = false;
  292. // Discard internal state of the decoder too.
  293. decoder = encoding.GetDecoder ();
  294. }
  295. // the buffer is empty, fill it again
  296. private int ReadBuffer ()
  297. {
  298. pos = 0;
  299. int cbEncoded = 0;
  300. // keep looping until the decoder gives us some chars
  301. decoded_count = 0;
  302. int parse_start = 0;
  303. do
  304. {
  305. cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
  306. if (cbEncoded <= 0)
  307. return 0;
  308. mayBlock = (cbEncoded < buffer_size);
  309. if (do_checks > 0){
  310. Encoding old = encoding;
  311. parse_start = DoChecks (cbEncoded);
  312. if (old != encoding){
  313. decoder = encoding.GetDecoder ();
  314. }
  315. do_checks = 0;
  316. cbEncoded -= parse_start;
  317. }
  318. decoded_count += decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
  319. parse_start = 0;
  320. } while (decoded_count == 0);
  321. return decoded_count;
  322. }
  323. //
  324. // Peek can block:
  325. // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=96484
  326. //
  327. public override int Peek ()
  328. {
  329. if (base_stream == null)
  330. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  331. if (pos >= decoded_count && ReadBuffer () == 0)
  332. return -1;
  333. return decoded_buffer [pos];
  334. }
  335. //
  336. // Used internally by our console, as it previously depended on Peek() being a
  337. // routine that would not block.
  338. //
  339. internal bool DataAvailable ()
  340. {
  341. return pos < decoded_count;
  342. }
  343. public override int Read ()
  344. {
  345. if (base_stream == null)
  346. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  347. if (pos >= decoded_count && ReadBuffer () == 0)
  348. return -1;
  349. return decoded_buffer [pos++];
  350. }
  351. public override int Read ([In, Out] char[] buffer, int index, int count)
  352. {
  353. if (base_stream == null)
  354. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  355. if (buffer == null)
  356. throw new ArgumentNullException ("buffer");
  357. if (index < 0)
  358. throw new ArgumentOutOfRangeException ("index", "< 0");
  359. if (count < 0)
  360. throw new ArgumentOutOfRangeException ("count", "< 0");
  361. // re-ordered to avoid possible integer overflow
  362. if (index > buffer.Length - count)
  363. throw new ArgumentException ("index + count > buffer.Length");
  364. int chars_read = 0;
  365. while (count > 0)
  366. {
  367. if (pos >= decoded_count && ReadBuffer () == 0)
  368. return chars_read > 0 ? chars_read : 0;
  369. int cch = Math.Min (decoded_count - pos, count);
  370. Array.Copy (decoded_buffer, pos, buffer, index, cch);
  371. pos += cch;
  372. index += cch;
  373. count -= cch;
  374. chars_read += cch;
  375. if (mayBlock)
  376. break;
  377. }
  378. return chars_read;
  379. }
  380. bool foundCR;
  381. int FindNextEOL ()
  382. {
  383. char c = '\0';
  384. for (; pos < decoded_count; pos++) {
  385. c = decoded_buffer [pos];
  386. if (c == '\n') {
  387. pos++;
  388. int res = (foundCR) ? (pos - 2) : (pos - 1);
  389. if (res < 0)
  390. res = 0; // if a new buffer starts with a \n and there was a \r at
  391. // the end of the previous one, we get here.
  392. foundCR = false;
  393. return res;
  394. } else if (foundCR) {
  395. foundCR = false;
  396. if (pos == 0)
  397. return -2; // Need to flush the current buffered line.
  398. // This is a \r at the end of the previous decoded buffer that
  399. // is not followed by a \n in the current decoded buffer.
  400. return pos - 1;
  401. }
  402. foundCR = (c == '\r');
  403. }
  404. return -1;
  405. }
  406. public override string ReadLine()
  407. {
  408. if (base_stream == null)
  409. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  410. if (pos >= decoded_count && ReadBuffer () == 0)
  411. return null;
  412. int begin = pos;
  413. int end = FindNextEOL ();
  414. if (end < decoded_count && end >= begin)
  415. return new string (decoded_buffer, begin, end - begin);
  416. else if (end == -2)
  417. return line_builder.ToString (0, line_builder.Length);
  418. if (line_builder == null)
  419. line_builder = new StringBuilder ();
  420. else
  421. line_builder.Length = 0;
  422. while (true) {
  423. if (foundCR) // don't include the trailing CR if present
  424. decoded_count--;
  425. line_builder.Append (decoded_buffer, begin, decoded_count - begin);
  426. if (ReadBuffer () == 0) {
  427. if (line_builder.Capacity > 32768) {
  428. StringBuilder sb = line_builder;
  429. line_builder = null;
  430. return sb.ToString (0, sb.Length);
  431. }
  432. return line_builder.ToString (0, line_builder.Length);
  433. }
  434. begin = pos;
  435. end = FindNextEOL ();
  436. if (end < decoded_count && end >= begin) {
  437. line_builder.Append (decoded_buffer, begin, end - begin);
  438. if (line_builder.Capacity > 32768) {
  439. StringBuilder sb = line_builder;
  440. line_builder = null;
  441. return sb.ToString (0, sb.Length);
  442. }
  443. return line_builder.ToString (0, line_builder.Length);
  444. } else if (end == -2)
  445. return line_builder.ToString (0, line_builder.Length);
  446. }
  447. }
  448. public override string ReadToEnd()
  449. {
  450. if (base_stream == null)
  451. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  452. StringBuilder text = new StringBuilder ();
  453. int size = decoded_buffer.Length;
  454. char [] buffer = new char [size];
  455. int len;
  456. while ((len = Read (buffer, 0, size)) > 0)
  457. text.Append (buffer, 0, len);
  458. return text.ToString ();
  459. }
  460. }
  461. }