TextWriter.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Text;
  5. using System.Threading;
  6. using System.Globalization;
  7. using System.Threading.Tasks;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. using System.Buffers;
  11. using System.Diagnostics.CodeAnalysis;
  12. namespace System.IO
  13. {
  14. // This abstract base class represents a writer that can write a sequential
  15. // stream of characters. A subclass must minimally implement the
  16. // Write(char) method.
  17. //
  18. // This class is intended for character output, not bytes.
  19. // There are methods on the Stream class for writing bytes.
  20. public abstract partial class TextWriter : MarshalByRefObject, IDisposable, IAsyncDisposable
  21. {
  22. public static readonly TextWriter Null = new NullTextWriter();
  23. // We don't want to allocate on every TextWriter creation, so cache the char array.
  24. private static readonly char[] s_coreNewLine = Environment.NewLineConst.ToCharArray();
  25. /// <summary>
  26. /// This is the 'NewLine' property expressed as a char[].
  27. /// It is exposed to subclasses as a protected field for read-only
  28. /// purposes. You should only modify it by using the 'NewLine' property.
  29. /// In particular you should never modify the elements of the array
  30. /// as they are shared among many instances of TextWriter.
  31. /// </summary>
  32. protected char[] CoreNewLine = s_coreNewLine;
  33. private string CoreNewLineStr = Environment.NewLineConst;
  34. // Can be null - if so, ask for the Thread's CurrentCulture every time.
  35. private readonly IFormatProvider? _internalFormatProvider;
  36. protected TextWriter()
  37. {
  38. _internalFormatProvider = null; // Ask for CurrentCulture all the time.
  39. }
  40. protected TextWriter(IFormatProvider? formatProvider)
  41. {
  42. _internalFormatProvider = formatProvider;
  43. }
  44. public virtual IFormatProvider FormatProvider
  45. {
  46. get
  47. {
  48. if (_internalFormatProvider == null)
  49. {
  50. return CultureInfo.CurrentCulture;
  51. }
  52. else
  53. {
  54. return _internalFormatProvider;
  55. }
  56. }
  57. }
  58. public virtual void Close()
  59. {
  60. Dispose(true);
  61. GC.SuppressFinalize(this);
  62. }
  63. protected virtual void Dispose(bool disposing)
  64. {
  65. }
  66. public void Dispose()
  67. {
  68. Dispose(true);
  69. GC.SuppressFinalize(this);
  70. }
  71. public virtual ValueTask DisposeAsync()
  72. {
  73. try
  74. {
  75. Dispose();
  76. return default;
  77. }
  78. catch (Exception exc)
  79. {
  80. return new ValueTask(Task.FromException(exc));
  81. }
  82. }
  83. // Clears all buffers for this TextWriter and causes any buffered data to be
  84. // written to the underlying device. This default method is empty, but
  85. // descendant classes can override the method to provide the appropriate
  86. // functionality.
  87. public virtual void Flush()
  88. {
  89. }
  90. public abstract Encoding Encoding
  91. {
  92. get;
  93. }
  94. /// <summary>
  95. /// Returns the line terminator string used by this TextWriter. The default line
  96. /// terminator string is Environment.NewLine, which is platform specific.
  97. /// On Windows this is a carriage return followed by a line feed ("\r\n").
  98. /// On OSX and Linux this is a line feed ("\n").
  99. /// </summary>
  100. /// <remarks>
  101. /// The line terminator string is written to the text stream whenever one of the
  102. /// WriteLine methods are called. In order for text written by
  103. /// the TextWriter to be readable by a TextReader, only one of the following line
  104. /// terminator strings should be used: "\r", "\n", or "\r\n".
  105. /// </remarks>
  106. [AllowNull]
  107. public virtual string NewLine
  108. {
  109. get => CoreNewLineStr;
  110. set
  111. {
  112. if (value == null)
  113. {
  114. value = Environment.NewLineConst;
  115. }
  116. CoreNewLineStr = value;
  117. CoreNewLine = value.ToCharArray();
  118. }
  119. }
  120. // Writes a character to the text stream. This default method is empty,
  121. // but descendant classes can override the method to provide the
  122. // appropriate functionality.
  123. //
  124. public virtual void Write(char value)
  125. {
  126. }
  127. // Writes a character array to the text stream. This default method calls
  128. // Write(char) for each of the characters in the character array.
  129. // If the character array is null, nothing is written.
  130. //
  131. public virtual void Write(char[]? buffer)
  132. {
  133. if (buffer != null)
  134. {
  135. Write(buffer, 0, buffer.Length);
  136. }
  137. }
  138. // Writes a range of a character array to the text stream. This method will
  139. // write count characters of data into this TextWriter from the
  140. // buffer character array starting at position index.
  141. //
  142. public virtual void Write(char[] buffer, int index, int count)
  143. {
  144. if (buffer == null)
  145. {
  146. throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
  147. }
  148. if (index < 0)
  149. {
  150. throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
  151. }
  152. if (count < 0)
  153. {
  154. throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
  155. }
  156. if (buffer.Length - index < count)
  157. {
  158. throw new ArgumentException(SR.Argument_InvalidOffLen);
  159. }
  160. for (int i = 0; i < count; i++) Write(buffer[index + i]);
  161. }
  162. // Writes a span of characters to the text stream.
  163. //
  164. public virtual void Write(ReadOnlySpan<char> buffer)
  165. {
  166. char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
  167. try
  168. {
  169. buffer.CopyTo(new Span<char>(array));
  170. Write(array, 0, buffer.Length);
  171. }
  172. finally
  173. {
  174. ArrayPool<char>.Shared.Return(array);
  175. }
  176. }
  177. // Writes the text representation of a boolean to the text stream. This
  178. // method outputs either bool.TrueString or bool.FalseString.
  179. //
  180. public virtual void Write(bool value)
  181. {
  182. Write(value ? "True" : "False");
  183. }
  184. // Writes the text representation of an integer to the text stream. The
  185. // text representation of the given value is produced by calling the
  186. // int.ToString() method.
  187. //
  188. public virtual void Write(int value)
  189. {
  190. Write(value.ToString(FormatProvider));
  191. }
  192. // Writes the text representation of an integer to the text stream. The
  193. // text representation of the given value is produced by calling the
  194. // uint.ToString() method.
  195. //
  196. [CLSCompliant(false)]
  197. public virtual void Write(uint value)
  198. {
  199. Write(value.ToString(FormatProvider));
  200. }
  201. // Writes the text representation of a long to the text stream. The
  202. // text representation of the given value is produced by calling the
  203. // long.ToString() method.
  204. //
  205. public virtual void Write(long value)
  206. {
  207. Write(value.ToString(FormatProvider));
  208. }
  209. // Writes the text representation of an unsigned long to the text
  210. // stream. The text representation of the given value is produced
  211. // by calling the ulong.ToString() method.
  212. //
  213. [CLSCompliant(false)]
  214. public virtual void Write(ulong value)
  215. {
  216. Write(value.ToString(FormatProvider));
  217. }
  218. // Writes the text representation of a float to the text stream. The
  219. // text representation of the given value is produced by calling the
  220. // float.ToString(float) method.
  221. //
  222. public virtual void Write(float value)
  223. {
  224. Write(value.ToString(FormatProvider));
  225. }
  226. // Writes the text representation of a double to the text stream. The
  227. // text representation of the given value is produced by calling the
  228. // double.ToString(double) method.
  229. //
  230. public virtual void Write(double value)
  231. {
  232. Write(value.ToString(FormatProvider));
  233. }
  234. public virtual void Write(decimal value)
  235. {
  236. Write(value.ToString(FormatProvider));
  237. }
  238. // Writes a string to the text stream. If the given string is null, nothing
  239. // is written to the text stream.
  240. //
  241. public virtual void Write(string? value)
  242. {
  243. if (value != null)
  244. {
  245. Write(value.ToCharArray());
  246. }
  247. }
  248. // Writes the text representation of an object to the text stream. If the
  249. // given object is null, nothing is written to the text stream.
  250. // Otherwise, the object's ToString method is called to produce the
  251. // string representation, and the resulting string is then written to the
  252. // output stream.
  253. //
  254. public virtual void Write(object? value)
  255. {
  256. if (value != null)
  257. {
  258. if (value is IFormattable f)
  259. {
  260. Write(f.ToString(null, FormatProvider));
  261. }
  262. else
  263. Write(value.ToString());
  264. }
  265. }
  266. /// <summary>
  267. /// Equivalent to Write(stringBuilder.ToString()) however it uses the
  268. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  269. /// </summary>
  270. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  271. public virtual void Write(StringBuilder? value)
  272. {
  273. if (value != null)
  274. {
  275. foreach (ReadOnlyMemory<char> chunk in value.GetChunks())
  276. Write(chunk.Span);
  277. }
  278. }
  279. // Writes out a formatted string. Uses the same semantics as
  280. // string.Format.
  281. //
  282. public virtual void Write(string format, object? arg0)
  283. {
  284. Write(string.Format(FormatProvider, format, arg0));
  285. }
  286. // Writes out a formatted string. Uses the same semantics as
  287. // string.Format.
  288. //
  289. public virtual void Write(string format, object? arg0, object? arg1)
  290. {
  291. Write(string.Format(FormatProvider, format, arg0, arg1));
  292. }
  293. // Writes out a formatted string. Uses the same semantics as
  294. // string.Format.
  295. //
  296. public virtual void Write(string format, object? arg0, object? arg1, object? arg2)
  297. {
  298. Write(string.Format(FormatProvider, format, arg0, arg1, arg2));
  299. }
  300. // Writes out a formatted string. Uses the same semantics as
  301. // string.Format.
  302. //
  303. public virtual void Write(string format, params object?[] arg)
  304. {
  305. Write(string.Format(FormatProvider, format, arg));
  306. }
  307. // Writes a line terminator to the text stream. The default line terminator
  308. // is Environment.NewLine, but this value can be changed by setting the NewLine property.
  309. //
  310. public virtual void WriteLine()
  311. {
  312. Write(CoreNewLine);
  313. }
  314. // Writes a character followed by a line terminator to the text stream.
  315. //
  316. public virtual void WriteLine(char value)
  317. {
  318. Write(value);
  319. WriteLine();
  320. }
  321. // Writes an array of characters followed by a line terminator to the text
  322. // stream.
  323. //
  324. public virtual void WriteLine(char[]? buffer)
  325. {
  326. Write(buffer);
  327. WriteLine();
  328. }
  329. // Writes a range of a character array followed by a line terminator to the
  330. // text stream.
  331. //
  332. public virtual void WriteLine(char[] buffer, int index, int count)
  333. {
  334. Write(buffer, index, count);
  335. WriteLine();
  336. }
  337. public virtual void WriteLine(ReadOnlySpan<char> buffer)
  338. {
  339. char[] array = ArrayPool<char>.Shared.Rent(buffer.Length);
  340. try
  341. {
  342. buffer.CopyTo(new Span<char>(array));
  343. WriteLine(array, 0, buffer.Length);
  344. }
  345. finally
  346. {
  347. ArrayPool<char>.Shared.Return(array);
  348. }
  349. }
  350. // Writes the text representation of a boolean followed by a line
  351. // terminator to the text stream.
  352. //
  353. public virtual void WriteLine(bool value)
  354. {
  355. Write(value);
  356. WriteLine();
  357. }
  358. // Writes the text representation of an integer followed by a line
  359. // terminator to the text stream.
  360. //
  361. public virtual void WriteLine(int value)
  362. {
  363. Write(value);
  364. WriteLine();
  365. }
  366. // Writes the text representation of an unsigned integer followed by
  367. // a line terminator to the text stream.
  368. //
  369. [CLSCompliant(false)]
  370. public virtual void WriteLine(uint value)
  371. {
  372. Write(value);
  373. WriteLine();
  374. }
  375. // Writes the text representation of a long followed by a line terminator
  376. // to the text stream.
  377. //
  378. public virtual void WriteLine(long value)
  379. {
  380. Write(value);
  381. WriteLine();
  382. }
  383. // Writes the text representation of an unsigned long followed by
  384. // a line terminator to the text stream.
  385. //
  386. [CLSCompliant(false)]
  387. public virtual void WriteLine(ulong value)
  388. {
  389. Write(value);
  390. WriteLine();
  391. }
  392. // Writes the text representation of a float followed by a line terminator
  393. // to the text stream.
  394. //
  395. public virtual void WriteLine(float value)
  396. {
  397. Write(value);
  398. WriteLine();
  399. }
  400. // Writes the text representation of a double followed by a line terminator
  401. // to the text stream.
  402. //
  403. public virtual void WriteLine(double value)
  404. {
  405. Write(value);
  406. WriteLine();
  407. }
  408. public virtual void WriteLine(decimal value)
  409. {
  410. Write(value);
  411. WriteLine();
  412. }
  413. // Writes a string followed by a line terminator to the text stream.
  414. //
  415. public virtual void WriteLine(string? value)
  416. {
  417. if (value != null)
  418. {
  419. Write(value);
  420. }
  421. Write(CoreNewLineStr);
  422. }
  423. /// <summary>
  424. /// Equivalent to WriteLine(stringBuilder.ToString()) however it uses the
  425. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  426. /// </summary>
  427. public virtual void WriteLine(StringBuilder? value)
  428. {
  429. Write(value);
  430. WriteLine();
  431. }
  432. // Writes the text representation of an object followed by a line
  433. // terminator to the text stream.
  434. //
  435. public virtual void WriteLine(object? value)
  436. {
  437. if (value == null)
  438. {
  439. WriteLine();
  440. }
  441. else
  442. {
  443. // Call WriteLine(value.ToString), not Write(Object), WriteLine().
  444. // This makes calls to WriteLine(Object) atomic.
  445. if (value is IFormattable f)
  446. {
  447. WriteLine(f.ToString(null, FormatProvider));
  448. }
  449. else
  450. {
  451. WriteLine(value.ToString());
  452. }
  453. }
  454. }
  455. // Writes out a formatted string and a new line. Uses the same
  456. // semantics as string.Format.
  457. //
  458. public virtual void WriteLine(string format, object? arg0)
  459. {
  460. WriteLine(string.Format(FormatProvider, format, arg0));
  461. }
  462. // Writes out a formatted string and a new line. Uses the same
  463. // semantics as string.Format.
  464. //
  465. public virtual void WriteLine(string format, object? arg0, object? arg1)
  466. {
  467. WriteLine(string.Format(FormatProvider, format, arg0, arg1));
  468. }
  469. // Writes out a formatted string and a new line. Uses the same
  470. // semantics as string.Format.
  471. //
  472. public virtual void WriteLine(string format, object? arg0, object? arg1, object? arg2)
  473. {
  474. WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2));
  475. }
  476. // Writes out a formatted string and a new line. Uses the same
  477. // semantics as string.Format.
  478. //
  479. public virtual void WriteLine(string format, params object?[] arg)
  480. {
  481. WriteLine(string.Format(FormatProvider, format, arg));
  482. }
  483. #region Task based Async APIs
  484. public virtual Task WriteAsync(char value)
  485. {
  486. var tuple = new Tuple<TextWriter, char>(this, value);
  487. return Task.Factory.StartNew(state =>
  488. {
  489. var t = (Tuple<TextWriter, char>)state!;
  490. t.Item1.Write(t.Item2);
  491. },
  492. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  493. }
  494. public virtual Task WriteAsync(string? value)
  495. {
  496. var tuple = new Tuple<TextWriter, string?>(this, value);
  497. return Task.Factory.StartNew(state =>
  498. {
  499. var t = (Tuple<TextWriter, string?>)state!;
  500. t.Item1.Write(t.Item2);
  501. },
  502. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  503. }
  504. /// <summary>
  505. /// Equivalent to WriteAsync(stringBuilder.ToString()) however it uses the
  506. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  507. /// </summary>
  508. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  509. public virtual Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default)
  510. {
  511. return
  512. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  513. value == null ? Task.CompletedTask :
  514. WriteAsyncCore(value, cancellationToken);
  515. async Task WriteAsyncCore(StringBuilder sb, CancellationToken ct)
  516. {
  517. foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
  518. {
  519. await WriteAsync(chunk, ct).ConfigureAwait(false);
  520. }
  521. }
  522. }
  523. public Task WriteAsync(char[]? buffer)
  524. {
  525. if (buffer == null)
  526. {
  527. return Task.CompletedTask;
  528. }
  529. return WriteAsync(buffer, 0, buffer.Length);
  530. }
  531. public virtual Task WriteAsync(char[] buffer, int index, int count)
  532. {
  533. var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
  534. return Task.Factory.StartNew(state =>
  535. {
  536. var t = (Tuple<TextWriter, char[], int, int>)state!;
  537. t.Item1.Write(t.Item2, t.Item3, t.Item4);
  538. },
  539. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  540. }
  541. public virtual Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
  542. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  543. MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
  544. WriteAsync(array.Array!, array.Offset, array.Count) :
  545. Task.Factory.StartNew(state =>
  546. {
  547. var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state!;
  548. t.Item1.Write(t.Item2.Span);
  549. }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  550. public virtual Task WriteLineAsync(char value)
  551. {
  552. var tuple = new Tuple<TextWriter, char>(this, value);
  553. return Task.Factory.StartNew(state =>
  554. {
  555. var t = (Tuple<TextWriter, char>)state!;
  556. t.Item1.WriteLine(t.Item2);
  557. },
  558. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  559. }
  560. public virtual Task WriteLineAsync(string? value)
  561. {
  562. var tuple = new Tuple<TextWriter, string?>(this, value);
  563. return Task.Factory.StartNew(state =>
  564. {
  565. var t = (Tuple<TextWriter, string?>)state!;
  566. t.Item1.WriteLine(t.Item2);
  567. },
  568. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  569. }
  570. /// <summary>
  571. /// Equivalent to WriteLineAsync(stringBuilder.ToString()) however it uses the
  572. /// StringBuilder.GetChunks() method to avoid creating the intermediate string
  573. /// </summary>
  574. /// <param name="value">The string (as a StringBuilder) to write to the stream</param>
  575. public virtual Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default)
  576. {
  577. return
  578. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  579. value == null ? WriteAsync(CoreNewLine, cancellationToken) :
  580. WriteLineAsyncCore(value, cancellationToken);
  581. async Task WriteLineAsyncCore(StringBuilder sb, CancellationToken ct)
  582. {
  583. foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
  584. {
  585. await WriteAsync(chunk, ct).ConfigureAwait(false);
  586. }
  587. await WriteAsync(CoreNewLine, ct).ConfigureAwait(false);
  588. }
  589. }
  590. public Task WriteLineAsync(char[]? buffer)
  591. {
  592. if (buffer == null)
  593. {
  594. return WriteLineAsync();
  595. }
  596. return WriteLineAsync(buffer, 0, buffer.Length);
  597. }
  598. public virtual Task WriteLineAsync(char[] buffer, int index, int count)
  599. {
  600. var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count);
  601. return Task.Factory.StartNew(state =>
  602. {
  603. var t = (Tuple<TextWriter, char[], int, int>)state!;
  604. t.Item1.WriteLine(t.Item2, t.Item3, t.Item4);
  605. },
  606. tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  607. }
  608. public virtual Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) =>
  609. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
  610. MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ?
  611. WriteLineAsync(array.Array!, array.Offset, array.Count) :
  612. Task.Factory.StartNew(state =>
  613. {
  614. var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state!;
  615. t.Item1.WriteLine(t.Item2.Span);
  616. }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  617. public virtual Task WriteLineAsync()
  618. {
  619. return WriteAsync(CoreNewLine);
  620. }
  621. public virtual Task FlushAsync()
  622. {
  623. return Task.Factory.StartNew(state => ((TextWriter)state!).Flush(), this,
  624. CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  625. }
  626. #endregion
  627. private sealed class NullTextWriter : TextWriter
  628. {
  629. internal NullTextWriter() : base(CultureInfo.InvariantCulture)
  630. {
  631. }
  632. public override Encoding Encoding => Encoding.Unicode;
  633. public override void Write(char[] buffer, int index, int count)
  634. {
  635. }
  636. public override void Write(string? value)
  637. {
  638. }
  639. // Not strictly necessary, but for perf reasons
  640. public override void WriteLine()
  641. {
  642. }
  643. // Not strictly necessary, but for perf reasons
  644. public override void WriteLine(string? value)
  645. {
  646. }
  647. public override void WriteLine(object? value)
  648. {
  649. }
  650. public override void Write(char value)
  651. {
  652. }
  653. }
  654. public static TextWriter Synchronized(TextWriter writer)
  655. {
  656. if (writer == null)
  657. throw new ArgumentNullException(nameof(writer));
  658. return writer is SyncTextWriter ? writer : new SyncTextWriter(writer);
  659. }
  660. internal sealed class SyncTextWriter : TextWriter, IDisposable
  661. {
  662. private readonly TextWriter _out;
  663. internal SyncTextWriter(TextWriter t) : base(t.FormatProvider)
  664. {
  665. _out = t;
  666. }
  667. public override Encoding Encoding => _out.Encoding;
  668. public override IFormatProvider FormatProvider => _out.FormatProvider;
  669. [AllowNull]
  670. public override string NewLine
  671. {
  672. [MethodImpl(MethodImplOptions.Synchronized)]
  673. get => _out.NewLine;
  674. [MethodImpl(MethodImplOptions.Synchronized)]
  675. set => _out.NewLine = value;
  676. }
  677. [MethodImpl(MethodImplOptions.Synchronized)]
  678. public override void Close() => _out.Close();
  679. [MethodImpl(MethodImplOptions.Synchronized)]
  680. protected override void Dispose(bool disposing)
  681. {
  682. // Explicitly pick up a potentially methodimpl'ed Dispose
  683. if (disposing)
  684. ((IDisposable)_out).Dispose();
  685. }
  686. [MethodImpl(MethodImplOptions.Synchronized)]
  687. public override void Flush() => _out.Flush();
  688. [MethodImpl(MethodImplOptions.Synchronized)]
  689. public override void Write(char value) => _out.Write(value);
  690. [MethodImpl(MethodImplOptions.Synchronized)]
  691. public override void Write(char[]? buffer) => _out.Write(buffer);
  692. [MethodImpl(MethodImplOptions.Synchronized)]
  693. public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count);
  694. [MethodImpl(MethodImplOptions.Synchronized)]
  695. public override void Write(ReadOnlySpan<char> buffer) => _out.Write(buffer);
  696. [MethodImpl(MethodImplOptions.Synchronized)]
  697. public override void Write(bool value) => _out.Write(value);
  698. [MethodImpl(MethodImplOptions.Synchronized)]
  699. public override void Write(int value) => _out.Write(value);
  700. [MethodImpl(MethodImplOptions.Synchronized)]
  701. public override void Write(uint value) => _out.Write(value);
  702. [MethodImpl(MethodImplOptions.Synchronized)]
  703. public override void Write(long value) => _out.Write(value);
  704. [MethodImpl(MethodImplOptions.Synchronized)]
  705. public override void Write(ulong value) => _out.Write(value);
  706. [MethodImpl(MethodImplOptions.Synchronized)]
  707. public override void Write(float value) => _out.Write(value);
  708. [MethodImpl(MethodImplOptions.Synchronized)]
  709. public override void Write(double value) => _out.Write(value);
  710. [MethodImpl(MethodImplOptions.Synchronized)]
  711. public override void Write(decimal value) => _out.Write(value);
  712. [MethodImpl(MethodImplOptions.Synchronized)]
  713. public override void Write(string? value) => _out.Write(value);
  714. [MethodImpl(MethodImplOptions.Synchronized)]
  715. public override void Write(StringBuilder? value) => _out.Write(value);
  716. [MethodImpl(MethodImplOptions.Synchronized)]
  717. public override void Write(object? value) => _out.Write(value);
  718. [MethodImpl(MethodImplOptions.Synchronized)]
  719. public override void Write(string format, object? arg0) => _out.Write(format, arg0);
  720. [MethodImpl(MethodImplOptions.Synchronized)]
  721. public override void Write(string format, object? arg0, object? arg1) => _out.Write(format, arg0, arg1);
  722. [MethodImpl(MethodImplOptions.Synchronized)]
  723. public override void Write(string format, object? arg0, object? arg1, object? arg2) => _out.Write(format, arg0, arg1, arg2);
  724. [MethodImpl(MethodImplOptions.Synchronized)]
  725. public override void Write(string format, object?[] arg) => _out.Write(format, arg);
  726. [MethodImpl(MethodImplOptions.Synchronized)]
  727. public override void WriteLine() => _out.WriteLine();
  728. [MethodImpl(MethodImplOptions.Synchronized)]
  729. public override void WriteLine(char value) => _out.WriteLine(value);
  730. [MethodImpl(MethodImplOptions.Synchronized)]
  731. public override void WriteLine(decimal value) => _out.WriteLine(value);
  732. [MethodImpl(MethodImplOptions.Synchronized)]
  733. public override void WriteLine(char[]? buffer) => _out.WriteLine(buffer);
  734. [MethodImpl(MethodImplOptions.Synchronized)]
  735. public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count);
  736. [MethodImpl(MethodImplOptions.Synchronized)]
  737. public override void WriteLine(ReadOnlySpan<char> buffer) => _out.WriteLine(buffer);
  738. [MethodImpl(MethodImplOptions.Synchronized)]
  739. public override void WriteLine(bool value) => _out.WriteLine(value);
  740. [MethodImpl(MethodImplOptions.Synchronized)]
  741. public override void WriteLine(int value) => _out.WriteLine(value);
  742. [MethodImpl(MethodImplOptions.Synchronized)]
  743. public override void WriteLine(uint value) => _out.WriteLine(value);
  744. [MethodImpl(MethodImplOptions.Synchronized)]
  745. public override void WriteLine(long value) => _out.WriteLine(value);
  746. [MethodImpl(MethodImplOptions.Synchronized)]
  747. public override void WriteLine(ulong value) => _out.WriteLine(value);
  748. [MethodImpl(MethodImplOptions.Synchronized)]
  749. public override void WriteLine(float value) => _out.WriteLine(value);
  750. [MethodImpl(MethodImplOptions.Synchronized)]
  751. public override void WriteLine(double value) => _out.WriteLine(value);
  752. [MethodImpl(MethodImplOptions.Synchronized)]
  753. public override void WriteLine(string? value) => _out.WriteLine(value);
  754. [MethodImpl(MethodImplOptions.Synchronized)]
  755. public override void WriteLine(StringBuilder? value) => _out.WriteLine(value);
  756. [MethodImpl(MethodImplOptions.Synchronized)]
  757. public override void WriteLine(object? value) => _out.WriteLine(value);
  758. [MethodImpl(MethodImplOptions.Synchronized)]
  759. public override void WriteLine(string format, object? arg0) => _out.WriteLine(format, arg0);
  760. [MethodImpl(MethodImplOptions.Synchronized)]
  761. public override void WriteLine(string format, object? arg0, object? arg1) => _out.WriteLine(format, arg0, arg1);
  762. [MethodImpl(MethodImplOptions.Synchronized)]
  763. public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) => _out.WriteLine(format, arg0, arg1, arg2);
  764. [MethodImpl(MethodImplOptions.Synchronized)]
  765. public override void WriteLine(string format, object?[] arg) => _out.WriteLine(format, arg);
  766. //
  767. // On SyncTextWriter all APIs should run synchronously, even the async ones.
  768. //
  769. [MethodImpl(MethodImplOptions.Synchronized)]
  770. public override ValueTask DisposeAsync()
  771. {
  772. Dispose();
  773. return default;
  774. }
  775. [MethodImpl(MethodImplOptions.Synchronized)]
  776. public override Task WriteAsync(char value)
  777. {
  778. Write(value);
  779. return Task.CompletedTask;
  780. }
  781. [MethodImpl(MethodImplOptions.Synchronized)]
  782. public override Task WriteAsync(string? value)
  783. {
  784. Write(value);
  785. return Task.CompletedTask;
  786. }
  787. [MethodImpl(MethodImplOptions.Synchronized)]
  788. public override Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default)
  789. {
  790. if (cancellationToken.IsCancellationRequested)
  791. {
  792. return Task.FromCanceled(cancellationToken);
  793. }
  794. Write(value);
  795. return Task.CompletedTask;
  796. }
  797. [MethodImpl(MethodImplOptions.Synchronized)]
  798. public override Task WriteAsync(char[] buffer, int index, int count)
  799. {
  800. Write(buffer, index, count);
  801. return Task.CompletedTask;
  802. }
  803. [MethodImpl(MethodImplOptions.Synchronized)]
  804. public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
  805. {
  806. if (cancellationToken.IsCancellationRequested)
  807. {
  808. return Task.FromCanceled(cancellationToken);
  809. }
  810. Write(buffer.Span);
  811. return Task.CompletedTask;
  812. }
  813. [MethodImpl(MethodImplOptions.Synchronized)]
  814. public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
  815. {
  816. if (cancellationToken.IsCancellationRequested)
  817. {
  818. return Task.FromCanceled(cancellationToken);
  819. }
  820. WriteLine(buffer.Span);
  821. return Task.CompletedTask;
  822. }
  823. [MethodImpl(MethodImplOptions.Synchronized)]
  824. public override Task WriteLineAsync(char value)
  825. {
  826. WriteLine(value);
  827. return Task.CompletedTask;
  828. }
  829. [MethodImpl(MethodImplOptions.Synchronized)]
  830. public override Task WriteLineAsync()
  831. {
  832. WriteLine();
  833. return Task.CompletedTask;
  834. }
  835. [MethodImpl(MethodImplOptions.Synchronized)]
  836. public override Task WriteLineAsync(string? value)
  837. {
  838. WriteLine(value);
  839. return Task.CompletedTask;
  840. }
  841. [MethodImpl(MethodImplOptions.Synchronized)]
  842. public override Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default)
  843. {
  844. if (cancellationToken.IsCancellationRequested)
  845. {
  846. return Task.FromCanceled(cancellationToken);
  847. }
  848. WriteLine(value);
  849. return Task.CompletedTask;
  850. }
  851. [MethodImpl(MethodImplOptions.Synchronized)]
  852. public override Task WriteLineAsync(char[] buffer, int index, int count)
  853. {
  854. WriteLine(buffer, index, count);
  855. return Task.CompletedTask;
  856. }
  857. [MethodImpl(MethodImplOptions.Synchronized)]
  858. public override Task FlushAsync()
  859. {
  860. Flush();
  861. return Task.CompletedTask;
  862. }
  863. }
  864. }
  865. }