StreamReader.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. //
  2. // System.IO.StreamReader.cs
  3. //
  4. // Authors:
  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. // Copyright 2011, 2013 Xamarin Inc.
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Text;
  34. using System.Runtime.InteropServices;
  35. #if NET_4_5
  36. using System.Threading.Tasks;
  37. #endif
  38. namespace System.IO {
  39. [Serializable]
  40. [ComVisible (true)]
  41. public class StreamReader : TextReader
  42. {
  43. sealed class NullStreamReader : StreamReader
  44. {
  45. public override int Peek ()
  46. {
  47. return -1;
  48. }
  49. public override int Read ()
  50. {
  51. return -1;
  52. }
  53. public override int Read ([In, Out] char[] buffer, int index, int count)
  54. {
  55. return 0;
  56. }
  57. public override string ReadLine ()
  58. {
  59. return null;
  60. }
  61. public override string ReadToEnd ()
  62. {
  63. return String.Empty;
  64. }
  65. public override Stream BaseStream {
  66. get { return Stream.Null; }
  67. }
  68. public override Encoding CurrentEncoding {
  69. get { return Encoding.Unicode; }
  70. }
  71. }
  72. const int DefaultBufferSize = 1024;
  73. const int DefaultFileBufferSize = 4096;
  74. const int MinimumBufferSize = 128;
  75. //
  76. // The input buffer
  77. //
  78. byte [] input_buffer;
  79. // Input buffer ready for recycling
  80. static byte [] input_buffer_recycle;
  81. static object input_buffer_recycle_lock = new object ();
  82. //
  83. // The decoded buffer from the above input buffer
  84. //
  85. char [] decoded_buffer;
  86. static char[] decoded_buffer_recycle;
  87. Encoding encoding;
  88. Decoder decoder;
  89. StringBuilder line_builder;
  90. Stream base_stream;
  91. //
  92. // Decoded bytes in decoded_buffer.
  93. //
  94. int decoded_count;
  95. //
  96. // Current position in the decoded_buffer
  97. //
  98. int pos;
  99. //
  100. // The buffer size that we are using
  101. //
  102. int buffer_size;
  103. int do_checks;
  104. bool mayBlock;
  105. #if NET_4_5
  106. IDecoupledTask async_task;
  107. readonly bool leave_open;
  108. #endif
  109. public new static readonly StreamReader Null = new NullStreamReader ();
  110. private StreamReader() {}
  111. public StreamReader(Stream stream)
  112. : this (stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
  113. public StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)
  114. : this (stream, Encoding.UTF8Unmarked, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
  115. public StreamReader(Stream stream, Encoding encoding)
  116. : this (stream, encoding, true, DefaultBufferSize) { }
  117. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
  118. : this (stream, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize) { }
  119. #if NET_4_5
  120. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  121. : this (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false)
  122. {
  123. }
  124. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)
  125. #else
  126. const bool leave_open = false;
  127. public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  128. #endif
  129. {
  130. #if NET_4_5
  131. leave_open = leaveOpen;
  132. #endif
  133. Initialize (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
  134. }
  135. public StreamReader(string path)
  136. : this (path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
  137. public StreamReader(string path, bool detectEncodingFromByteOrderMarks)
  138. : this (path, Encoding.UTF8Unmarked, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
  139. public StreamReader(string path, Encoding encoding)
  140. : this (path, encoding, true, DefaultFileBufferSize) { }
  141. public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
  142. : this (path, encoding, detectEncodingFromByteOrderMarks, DefaultFileBufferSize) { }
  143. public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  144. {
  145. if (null == path)
  146. throw new ArgumentNullException("path");
  147. if (String.Empty == path)
  148. throw new ArgumentException("Empty path not allowed");
  149. if (path.IndexOfAny (Path.InvalidPathChars) != -1)
  150. throw new ArgumentException("path contains invalid characters");
  151. if (null == encoding)
  152. throw new ArgumentNullException ("encoding");
  153. if (bufferSize <= 0)
  154. throw new ArgumentOutOfRangeException ("bufferSize", "The minimum size of the buffer must be positive");
  155. Stream stream = (Stream) File.OpenRead (path);
  156. Initialize (stream, encoding, detectEncodingFromByteOrderMarks, bufferSize);
  157. }
  158. internal void Initialize (Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
  159. {
  160. if (null == stream)
  161. throw new ArgumentNullException ("stream");
  162. if (null == encoding)
  163. throw new ArgumentNullException ("encoding");
  164. if (!stream.CanRead)
  165. throw new ArgumentException ("Cannot read stream");
  166. if (bufferSize <= 0)
  167. throw new ArgumentOutOfRangeException ("bufferSize", "The minimum size of the buffer must be positive");
  168. if (bufferSize < MinimumBufferSize)
  169. bufferSize = MinimumBufferSize;
  170. // since GetChars() might add flushed character, it
  171. // should have additional char buffer for extra 1
  172. // (probably 1 is ok, but might be insufficient. I'm not sure)
  173. var decoded_buffer_size = encoding.GetMaxCharCount (bufferSize) + 1;
  174. //
  175. // Instead of allocating a new default buffer use the
  176. // last one if there is any available
  177. //
  178. if (bufferSize <= DefaultBufferSize && input_buffer_recycle != null) {
  179. lock (input_buffer_recycle_lock) {
  180. if (input_buffer_recycle != null) {
  181. input_buffer = input_buffer_recycle;
  182. input_buffer_recycle = null;
  183. }
  184. if (decoded_buffer_recycle != null && decoded_buffer_size <= decoded_buffer_recycle.Length) {
  185. decoded_buffer = decoded_buffer_recycle;
  186. decoded_buffer_recycle = null;
  187. }
  188. }
  189. }
  190. if (input_buffer == null)
  191. input_buffer = new byte [bufferSize];
  192. else
  193. Array.Clear (input_buffer, 0, bufferSize);
  194. if (decoded_buffer == null)
  195. decoded_buffer = new char [decoded_buffer_size];
  196. else
  197. Array.Clear (decoded_buffer, 0, decoded_buffer_size);
  198. base_stream = stream;
  199. this.buffer_size = bufferSize;
  200. this.encoding = encoding;
  201. decoder = encoding.GetDecoder ();
  202. byte [] preamble = encoding.GetPreamble ();
  203. do_checks = detectEncodingFromByteOrderMarks ? 1 : 0;
  204. do_checks += (preamble.Length == 0) ? 0 : 2;
  205. decoded_count = 0;
  206. pos = 0;
  207. }
  208. public virtual Stream BaseStream {
  209. get {
  210. return base_stream;
  211. }
  212. }
  213. public virtual Encoding CurrentEncoding {
  214. get {
  215. if (encoding == null)
  216. throw new Exception ();
  217. return encoding;
  218. }
  219. }
  220. public bool EndOfStream {
  221. get { return Peek () < 0; }
  222. }
  223. public override void Close ()
  224. {
  225. Dispose (true);
  226. }
  227. protected override void Dispose (bool disposing)
  228. {
  229. if (disposing && base_stream != null && !leave_open)
  230. base_stream.Close ();
  231. if (input_buffer != null && input_buffer.Length == DefaultBufferSize && input_buffer_recycle == null) {
  232. lock (input_buffer_recycle_lock) {
  233. if (input_buffer_recycle == null) {
  234. input_buffer_recycle = input_buffer;
  235. }
  236. if (decoded_buffer_recycle == null) {
  237. decoded_buffer_recycle = decoded_buffer;
  238. }
  239. }
  240. }
  241. input_buffer = null;
  242. decoded_buffer = null;
  243. encoding = null;
  244. decoder = null;
  245. base_stream = null;
  246. base.Dispose (disposing);
  247. }
  248. //
  249. // Provides auto-detection of the encoding, as well as skipping over
  250. // byte marks at the beginning of a stream.
  251. //
  252. int DoChecks (int count)
  253. {
  254. if ((do_checks & 2) == 2){
  255. byte [] preamble = encoding.GetPreamble ();
  256. int c = preamble.Length;
  257. if (count >= c){
  258. int i;
  259. for (i = 0; i < c; i++)
  260. if (input_buffer [i] != preamble [i])
  261. break;
  262. if (i == c)
  263. return i;
  264. }
  265. }
  266. if ((do_checks & 1) == 1){
  267. if (count < 2)
  268. return 0;
  269. if (input_buffer [0] == 0xfe && input_buffer [1] == 0xff){
  270. this.encoding = Encoding.BigEndianUnicode;
  271. return 2;
  272. }
  273. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe && count < 4) {
  274. // If we don't have enough bytes we can't check for UTF32, so use Unicode
  275. this.encoding = Encoding.Unicode;
  276. return 2;
  277. }
  278. if (count < 3)
  279. return 0;
  280. if (input_buffer [0] == 0xef && input_buffer [1] == 0xbb && input_buffer [2] == 0xbf){
  281. this.encoding = Encoding.UTF8Unmarked;
  282. return 3;
  283. }
  284. if (count < 4) {
  285. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe && input_buffer [2] != 0) {
  286. this.encoding = Encoding.Unicode;
  287. return 2;
  288. }
  289. return 0;
  290. }
  291. if (input_buffer [0] == 0 && input_buffer [1] == 0
  292. && input_buffer [2] == 0xfe && input_buffer [3] == 0xff)
  293. {
  294. this.encoding = Encoding.BigEndianUTF32;
  295. return 4;
  296. }
  297. if (input_buffer [0] == 0xff && input_buffer [1] == 0xfe) {
  298. if (input_buffer [2] == 0 && input_buffer[3] == 0) {
  299. this.encoding = Encoding.UTF32;
  300. return 4;
  301. }
  302. this.encoding = Encoding.Unicode;
  303. return 2;
  304. }
  305. }
  306. return 0;
  307. }
  308. public void DiscardBufferedData ()
  309. {
  310. CheckState ();
  311. pos = decoded_count = 0;
  312. mayBlock = false;
  313. // Discard internal state of the decoder too.
  314. decoder = encoding.GetDecoder ();
  315. }
  316. // the buffer is empty, fill it again
  317. // Keep in sync with ReadBufferAsync
  318. int ReadBuffer ()
  319. {
  320. pos = 0;
  321. // keep looping until the decoder gives us some chars
  322. decoded_count = 0;
  323. do {
  324. var cbEncoded = base_stream.Read (input_buffer, 0, buffer_size);
  325. if (cbEncoded <= 0)
  326. return 0;
  327. decoded_count = ReadBufferCore (cbEncoded);
  328. } while (decoded_count == 0);
  329. return decoded_count;
  330. }
  331. int ReadBufferCore (int cbEncoded)
  332. {
  333. int parse_start;
  334. mayBlock = cbEncoded < buffer_size;
  335. if (do_checks > 0){
  336. Encoding old = encoding;
  337. parse_start = DoChecks (cbEncoded);
  338. if (old != encoding){
  339. int old_decoded_size = old.GetMaxCharCount (buffer_size) + 1;
  340. int new_decoded_size = encoding.GetMaxCharCount (buffer_size) + 1;
  341. if (old_decoded_size != new_decoded_size)
  342. decoded_buffer = new char [new_decoded_size];
  343. decoder = encoding.GetDecoder ();
  344. }
  345. do_checks = 0;
  346. cbEncoded -= parse_start;
  347. } else {
  348. parse_start = 0;
  349. }
  350. return decoder.GetChars (input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
  351. }
  352. //
  353. // Peek can block:
  354. // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=96484
  355. //
  356. public override int Peek ()
  357. {
  358. CheckState ();
  359. if (pos >= decoded_count && ReadBuffer () == 0)
  360. return -1;
  361. return decoded_buffer [pos];
  362. }
  363. //
  364. // Used internally by our console, as it previously depended on Peek() being a
  365. // routine that would not block.
  366. //
  367. internal bool DataAvailable ()
  368. {
  369. return pos < decoded_count;
  370. }
  371. public override int Read ()
  372. {
  373. CheckState ();
  374. if (pos >= decoded_count && ReadBuffer () == 0)
  375. return -1;
  376. return decoded_buffer [pos++];
  377. }
  378. // Keep in sync with ReadAsync
  379. public override int Read ([In, Out] char[] buffer, int index, int count)
  380. {
  381. if (buffer == null)
  382. throw new ArgumentNullException ("buffer");
  383. if (index < 0)
  384. throw new ArgumentOutOfRangeException ("index", "< 0");
  385. if (count < 0)
  386. throw new ArgumentOutOfRangeException ("count", "< 0");
  387. // re-ordered to avoid possible integer overflow
  388. if (index > buffer.Length - count)
  389. throw new ArgumentException ("index + count > buffer.Length");
  390. CheckState ();
  391. int chars_read = 0;
  392. while (count > 0) {
  393. if (pos >= decoded_count && ReadBuffer () == 0)
  394. return chars_read > 0 ? chars_read : 0;
  395. int cch = Math.Min (decoded_count - pos, count);
  396. Array.Copy (decoded_buffer, pos, buffer, index, cch);
  397. pos += cch;
  398. index += cch;
  399. count -= cch;
  400. chars_read += cch;
  401. if (mayBlock)
  402. break;
  403. }
  404. return chars_read;
  405. }
  406. bool foundCR;
  407. int FindNextEOL ()
  408. {
  409. char c = '\0';
  410. for (; pos < decoded_count; pos++) {
  411. c = decoded_buffer [pos];
  412. if (c == '\n') {
  413. pos++;
  414. int res = (foundCR) ? (pos - 2) : (pos - 1);
  415. if (res < 0)
  416. res = 0; // if a new buffer starts with a \n and there was a \r at
  417. // the end of the previous one, we get here.
  418. foundCR = false;
  419. return res;
  420. } else if (foundCR) {
  421. foundCR = false;
  422. if (pos == 0)
  423. return -2; // Need to flush the current buffered line.
  424. // This is a \r at the end of the previous decoded buffer that
  425. // is not followed by a \n in the current decoded buffer.
  426. return pos - 1;
  427. }
  428. foundCR = (c == '\r');
  429. }
  430. return -1;
  431. }
  432. // Keep in sync with ReadLineAsync
  433. public override string ReadLine()
  434. {
  435. CheckState ();
  436. if (pos >= decoded_count && ReadBuffer () == 0)
  437. return null;
  438. int begin = pos;
  439. int end = FindNextEOL ();
  440. if (end < decoded_count && end >= begin)
  441. return new string (decoded_buffer, begin, end - begin);
  442. if (end == -2)
  443. return line_builder.ToString (0, line_builder.Length);
  444. if (line_builder == null)
  445. line_builder = new StringBuilder ();
  446. else
  447. line_builder.Length = 0;
  448. while (true) {
  449. if (foundCR) // don't include the trailing CR if present
  450. decoded_count--;
  451. line_builder.Append (decoded_buffer, begin, decoded_count - begin);
  452. if (ReadBuffer () == 0) {
  453. if (line_builder.Capacity > 32768) {
  454. StringBuilder sb = line_builder;
  455. line_builder = null;
  456. return sb.ToString (0, sb.Length);
  457. }
  458. return line_builder.ToString (0, line_builder.Length);
  459. }
  460. begin = pos;
  461. end = FindNextEOL ();
  462. if (end < decoded_count && end >= begin) {
  463. line_builder.Append (decoded_buffer, begin, end - begin);
  464. if (line_builder.Capacity > 32768) {
  465. StringBuilder sb = line_builder;
  466. line_builder = null;
  467. return sb.ToString (0, sb.Length);
  468. }
  469. return line_builder.ToString (0, line_builder.Length);
  470. }
  471. if (end == -2)
  472. return line_builder.ToString (0, line_builder.Length);
  473. }
  474. }
  475. // Keep in sync with ReadToEndAsync
  476. public override string ReadToEnd()
  477. {
  478. CheckState ();
  479. StringBuilder text = new StringBuilder ();
  480. do {
  481. text.Append (decoded_buffer, pos, decoded_count - pos);
  482. } while (ReadBuffer () != 0);
  483. return text.ToString ();
  484. }
  485. void CheckState ()
  486. {
  487. if (base_stream == null)
  488. throw new ObjectDisposedException ("StreamReader", "Cannot read from a closed StreamReader");
  489. #if NET_4_5
  490. if (async_task != null && !async_task.IsCompleted)
  491. throw new InvalidOperationException ();
  492. #endif
  493. }
  494. #if NET_4_5
  495. public override int ReadBlock ([In, Out] char[] buffer, int index, int count)
  496. {
  497. if (buffer == null)
  498. throw new ArgumentNullException ("buffer");
  499. if (index < 0)
  500. throw new ArgumentOutOfRangeException ("index", "< 0");
  501. if (count < 0)
  502. throw new ArgumentOutOfRangeException ("count", "< 0");
  503. // re-ordered to avoid possible integer overflow
  504. if (index > buffer.Length - count)
  505. throw new ArgumentException ("index + count > buffer.Length");
  506. CheckState ();
  507. return base.ReadBlock (buffer, index, count);
  508. }
  509. public override Task<int> ReadAsync (char[] buffer, int index, int count)
  510. {
  511. if (buffer == null)
  512. throw new ArgumentNullException ("buffer");
  513. if (index < 0)
  514. throw new ArgumentOutOfRangeException ("index", "< 0");
  515. if (count < 0)
  516. throw new ArgumentOutOfRangeException ("count", "< 0");
  517. // re-ordered to avoid possible integer overflow
  518. if (index > buffer.Length - count)
  519. throw new ArgumentException ("index + count > buffer.Length");
  520. CheckState ();
  521. DecoupledTask<int> res;
  522. async_task = res = new DecoupledTask<int> (ReadAsyncCore (buffer, index, count));
  523. return res.Task;
  524. }
  525. async Task<int> ReadAsyncCore (char[] buffer, int index, int count)
  526. {
  527. int chars_read = 0;
  528. while (count > 0) {
  529. if (pos >= decoded_count && await ReadBufferAsync ().ConfigureAwait (false) == 0)
  530. return chars_read > 0 ? chars_read : 0;
  531. int cch = Math.Min (decoded_count - pos, count);
  532. Array.Copy (decoded_buffer, pos, buffer, index, cch);
  533. pos += cch;
  534. index += cch;
  535. count -= cch;
  536. chars_read += cch;
  537. if (mayBlock)
  538. break;
  539. }
  540. return chars_read;
  541. }
  542. public override Task<int> ReadBlockAsync (char[] buffer, int index, int count)
  543. {
  544. if (buffer == null)
  545. throw new ArgumentNullException ("buffer");
  546. if (index < 0)
  547. throw new ArgumentOutOfRangeException ("index", "< 0");
  548. if (count < 0)
  549. throw new ArgumentOutOfRangeException ("count", "< 0");
  550. // re-ordered to avoid possible integer overflow
  551. if (index > buffer.Length - count)
  552. throw new ArgumentException ("index + count > buffer.Length");
  553. CheckState ();
  554. DecoupledTask<int> res;
  555. async_task = res = new DecoupledTask<int> (ReadAsyncCore (buffer, index, count));
  556. return res.Task;
  557. }
  558. public override Task<string> ReadLineAsync ()
  559. {
  560. CheckState ();
  561. DecoupledTask<string> res;
  562. async_task = res = new DecoupledTask<string> (ReadLineAsyncCore ());
  563. return res.Task;
  564. }
  565. async Task<string> ReadLineAsyncCore ()
  566. {
  567. if (pos >= decoded_count && await ReadBufferAsync ().ConfigureAwait (false) == 0)
  568. return null;
  569. int begin = pos;
  570. int end = FindNextEOL ();
  571. if (end < decoded_count && end >= begin)
  572. return new string (decoded_buffer, begin, end - begin);
  573. if (end == -2)
  574. return line_builder.ToString (0, line_builder.Length);
  575. if (line_builder == null)
  576. line_builder = new StringBuilder ();
  577. else
  578. line_builder.Length = 0;
  579. while (true) {
  580. if (foundCR) // don't include the trailing CR if present
  581. decoded_count--;
  582. line_builder.Append (decoded_buffer, begin, decoded_count - begin);
  583. if (await ReadBufferAsync ().ConfigureAwait (false) == 0) {
  584. if (line_builder.Capacity > 32768) {
  585. StringBuilder sb = line_builder;
  586. line_builder = null;
  587. return sb.ToString (0, sb.Length);
  588. }
  589. return line_builder.ToString (0, line_builder.Length);
  590. }
  591. begin = pos;
  592. end = FindNextEOL ();
  593. if (end < decoded_count && end >= begin) {
  594. line_builder.Append (decoded_buffer, begin, end - begin);
  595. if (line_builder.Capacity > 32768) {
  596. StringBuilder sb = line_builder;
  597. line_builder = null;
  598. return sb.ToString (0, sb.Length);
  599. }
  600. return line_builder.ToString (0, line_builder.Length);
  601. }
  602. if (end == -2)
  603. return line_builder.ToString (0, line_builder.Length);
  604. }
  605. }
  606. public override Task<string> ReadToEndAsync ()
  607. {
  608. CheckState ();
  609. DecoupledTask<string> res;
  610. async_task = res = new DecoupledTask<string> (ReadToEndAsyncCore ());
  611. return res.Task;
  612. }
  613. async Task<string> ReadToEndAsyncCore ()
  614. {
  615. StringBuilder text = new StringBuilder ();
  616. do {
  617. text.Append (decoded_buffer, pos, decoded_count - pos);
  618. } while (await ReadBufferAsync () != 0);
  619. return text.ToString ();
  620. }
  621. async Task<int> ReadBufferAsync ()
  622. {
  623. pos = 0;
  624. // keep looping until the decoder gives us some chars
  625. decoded_count = 0;
  626. do {
  627. var cbEncoded = await base_stream.ReadAsync (input_buffer, 0, buffer_size).ConfigureAwait (false);
  628. if (cbEncoded <= 0)
  629. return 0;
  630. decoded_count = ReadBufferCore (cbEncoded);
  631. } while (decoded_count == 0);
  632. return decoded_count;
  633. }
  634. #endif
  635. }
  636. }