TextWriter.cs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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.NewLine.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.NewLine;
  34. // Can be null - if so, ask for the Thread's CurrentCulture every time.
  35. private 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 { return CoreNewLineStr; }
  110. set
  111. {
  112. if (value == null)
  113. {
  114. value = Environment.NewLine;
  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 =>
  624. {
  625. ((TextWriter)state!).Flush();
  626. },
  627. this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
  628. }
  629. #endregion
  630. private sealed class NullTextWriter : TextWriter
  631. {
  632. internal NullTextWriter() : base(CultureInfo.InvariantCulture)
  633. {
  634. }
  635. public override Encoding Encoding
  636. {
  637. get
  638. {
  639. return Encoding.Unicode;
  640. }
  641. }
  642. public override void Write(char[] buffer, int index, int count)
  643. {
  644. }
  645. public override void Write(string? value)
  646. {
  647. }
  648. // Not strictly necessary, but for perf reasons
  649. public override void WriteLine()
  650. {
  651. }
  652. // Not strictly necessary, but for perf reasons
  653. public override void WriteLine(string? value)
  654. {
  655. }
  656. public override void WriteLine(object? value)
  657. {
  658. }
  659. public override void Write(char value)
  660. {
  661. }
  662. }
  663. public static TextWriter Synchronized(TextWriter writer)
  664. {
  665. if (writer == null)
  666. throw new ArgumentNullException(nameof(writer));
  667. return writer is SyncTextWriter ? writer : new SyncTextWriter(writer);
  668. }
  669. internal sealed class SyncTextWriter : TextWriter, IDisposable
  670. {
  671. private readonly TextWriter _out;
  672. internal SyncTextWriter(TextWriter t) : base(t.FormatProvider)
  673. {
  674. _out = t;
  675. }
  676. public override Encoding Encoding => _out.Encoding;
  677. public override IFormatProvider FormatProvider => _out.FormatProvider;
  678. [AllowNull]
  679. public override string NewLine
  680. {
  681. [MethodImpl(MethodImplOptions.Synchronized)]
  682. get { return _out.NewLine; }
  683. [MethodImpl(MethodImplOptions.Synchronized)]
  684. set { _out.NewLine = value; }
  685. }
  686. [MethodImpl(MethodImplOptions.Synchronized)]
  687. public override void Close() => _out.Close();
  688. [MethodImpl(MethodImplOptions.Synchronized)]
  689. protected override void Dispose(bool disposing)
  690. {
  691. // Explicitly pick up a potentially methodimpl'ed Dispose
  692. if (disposing)
  693. ((IDisposable)_out).Dispose();
  694. }
  695. [MethodImpl(MethodImplOptions.Synchronized)]
  696. public override void Flush() => _out.Flush();
  697. [MethodImpl(MethodImplOptions.Synchronized)]
  698. public override void Write(char value) => _out.Write(value);
  699. [MethodImpl(MethodImplOptions.Synchronized)]
  700. public override void Write(char[]? buffer) => _out.Write(buffer);
  701. [MethodImpl(MethodImplOptions.Synchronized)]
  702. public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count);
  703. [MethodImpl(MethodImplOptions.Synchronized)]
  704. public override void Write(ReadOnlySpan<char> buffer) => _out.Write(buffer);
  705. [MethodImpl(MethodImplOptions.Synchronized)]
  706. public override void Write(bool value) => _out.Write(value);
  707. [MethodImpl(MethodImplOptions.Synchronized)]
  708. public override void Write(int value) => _out.Write(value);
  709. [MethodImpl(MethodImplOptions.Synchronized)]
  710. public override void Write(uint value) => _out.Write(value);
  711. [MethodImpl(MethodImplOptions.Synchronized)]
  712. public override void Write(long value) => _out.Write(value);
  713. [MethodImpl(MethodImplOptions.Synchronized)]
  714. public override void Write(ulong value) => _out.Write(value);
  715. [MethodImpl(MethodImplOptions.Synchronized)]
  716. public override void Write(float value) => _out.Write(value);
  717. [MethodImpl(MethodImplOptions.Synchronized)]
  718. public override void Write(double value) => _out.Write(value);
  719. [MethodImpl(MethodImplOptions.Synchronized)]
  720. public override void Write(decimal value) => _out.Write(value);
  721. [MethodImpl(MethodImplOptions.Synchronized)]
  722. public override void Write(string? value) => _out.Write(value);
  723. [MethodImpl(MethodImplOptions.Synchronized)]
  724. public override void Write(StringBuilder? value) => _out.Write(value);
  725. [MethodImpl(MethodImplOptions.Synchronized)]
  726. public override void Write(object? value) => _out.Write(value);
  727. [MethodImpl(MethodImplOptions.Synchronized)]
  728. public override void Write(string format, object? arg0) => _out.Write(format, arg0);
  729. [MethodImpl(MethodImplOptions.Synchronized)]
  730. public override void Write(string format, object? arg0, object? arg1) => _out.Write(format, arg0, arg1);
  731. [MethodImpl(MethodImplOptions.Synchronized)]
  732. public override void Write(string format, object? arg0, object? arg1, object? arg2) => _out.Write(format, arg0, arg1, arg2);
  733. [MethodImpl(MethodImplOptions.Synchronized)]
  734. public override void Write(string format, object?[] arg) => _out.Write(format, arg);
  735. [MethodImpl(MethodImplOptions.Synchronized)]
  736. public override void WriteLine() => _out.WriteLine();
  737. [MethodImpl(MethodImplOptions.Synchronized)]
  738. public override void WriteLine(char value) => _out.WriteLine(value);
  739. [MethodImpl(MethodImplOptions.Synchronized)]
  740. public override void WriteLine(decimal value) => _out.WriteLine(value);
  741. [MethodImpl(MethodImplOptions.Synchronized)]
  742. public override void WriteLine(char[]? buffer) => _out.WriteLine(buffer);
  743. [MethodImpl(MethodImplOptions.Synchronized)]
  744. public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count);
  745. [MethodImpl(MethodImplOptions.Synchronized)]
  746. public override void WriteLine(ReadOnlySpan<char> buffer) => _out.WriteLine(buffer);
  747. [MethodImpl(MethodImplOptions.Synchronized)]
  748. public override void WriteLine(bool value) => _out.WriteLine(value);
  749. [MethodImpl(MethodImplOptions.Synchronized)]
  750. public override void WriteLine(int value) => _out.WriteLine(value);
  751. [MethodImpl(MethodImplOptions.Synchronized)]
  752. public override void WriteLine(uint value) => _out.WriteLine(value);
  753. [MethodImpl(MethodImplOptions.Synchronized)]
  754. public override void WriteLine(long value) => _out.WriteLine(value);
  755. [MethodImpl(MethodImplOptions.Synchronized)]
  756. public override void WriteLine(ulong value) => _out.WriteLine(value);
  757. [MethodImpl(MethodImplOptions.Synchronized)]
  758. public override void WriteLine(float value) => _out.WriteLine(value);
  759. [MethodImpl(MethodImplOptions.Synchronized)]
  760. public override void WriteLine(double value) => _out.WriteLine(value);
  761. [MethodImpl(MethodImplOptions.Synchronized)]
  762. public override void WriteLine(string? value) => _out.WriteLine(value);
  763. [MethodImpl(MethodImplOptions.Synchronized)]
  764. public override void WriteLine(StringBuilder? value) => _out.WriteLine(value);
  765. [MethodImpl(MethodImplOptions.Synchronized)]
  766. public override void WriteLine(object? value) => _out.WriteLine(value);
  767. [MethodImpl(MethodImplOptions.Synchronized)]
  768. public override void WriteLine(string format, object? arg0) => _out.WriteLine(format, arg0);
  769. [MethodImpl(MethodImplOptions.Synchronized)]
  770. public override void WriteLine(string format, object? arg0, object? arg1) => _out.WriteLine(format, arg0, arg1);
  771. [MethodImpl(MethodImplOptions.Synchronized)]
  772. public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) => _out.WriteLine(format, arg0, arg1, arg2);
  773. [MethodImpl(MethodImplOptions.Synchronized)]
  774. public override void WriteLine(string format, object?[] arg) => _out.WriteLine(format, arg);
  775. //
  776. // On SyncTextWriter all APIs should run synchronously, even the async ones.
  777. //
  778. [MethodImpl(MethodImplOptions.Synchronized)]
  779. public override ValueTask DisposeAsync()
  780. {
  781. Dispose();
  782. return default;
  783. }
  784. [MethodImpl(MethodImplOptions.Synchronized)]
  785. public override Task WriteAsync(char value)
  786. {
  787. Write(value);
  788. return Task.CompletedTask;
  789. }
  790. [MethodImpl(MethodImplOptions.Synchronized)]
  791. public override Task WriteAsync(string? value)
  792. {
  793. Write(value);
  794. return Task.CompletedTask;
  795. }
  796. [MethodImpl(MethodImplOptions.Synchronized)]
  797. public override Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default)
  798. {
  799. if (cancellationToken.IsCancellationRequested)
  800. {
  801. return Task.FromCanceled(cancellationToken);
  802. }
  803. Write(value);
  804. return Task.CompletedTask;
  805. }
  806. [MethodImpl(MethodImplOptions.Synchronized)]
  807. public override Task WriteAsync(char[] buffer, int index, int count)
  808. {
  809. Write(buffer, index, count);
  810. return Task.CompletedTask;
  811. }
  812. [MethodImpl(MethodImplOptions.Synchronized)]
  813. public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
  814. {
  815. if (cancellationToken.IsCancellationRequested)
  816. {
  817. return Task.FromCanceled(cancellationToken);
  818. }
  819. Write(buffer.Span);
  820. return Task.CompletedTask;
  821. }
  822. [MethodImpl(MethodImplOptions.Synchronized)]
  823. public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default)
  824. {
  825. if (cancellationToken.IsCancellationRequested)
  826. {
  827. return Task.FromCanceled(cancellationToken);
  828. }
  829. WriteLine(buffer.Span);
  830. return Task.CompletedTask;
  831. }
  832. [MethodImpl(MethodImplOptions.Synchronized)]
  833. public override Task WriteLineAsync(char value)
  834. {
  835. WriteLine(value);
  836. return Task.CompletedTask;
  837. }
  838. [MethodImpl(MethodImplOptions.Synchronized)]
  839. public override Task WriteLineAsync()
  840. {
  841. WriteLine();
  842. return Task.CompletedTask;
  843. }
  844. [MethodImpl(MethodImplOptions.Synchronized)]
  845. public override Task WriteLineAsync(string? value)
  846. {
  847. WriteLine(value);
  848. return Task.CompletedTask;
  849. }
  850. [MethodImpl(MethodImplOptions.Synchronized)]
  851. public override Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default)
  852. {
  853. if (cancellationToken.IsCancellationRequested)
  854. {
  855. return Task.FromCanceled(cancellationToken);
  856. }
  857. WriteLine(value);
  858. return Task.CompletedTask;
  859. }
  860. [MethodImpl(MethodImplOptions.Synchronized)]
  861. public override Task WriteLineAsync(char[] buffer, int index, int count)
  862. {
  863. WriteLine(buffer, index, count);
  864. return Task.CompletedTask;
  865. }
  866. [MethodImpl(MethodImplOptions.Synchronized)]
  867. public override Task FlushAsync()
  868. {
  869. Flush();
  870. return Task.CompletedTask;
  871. }
  872. }
  873. }
  874. }