BinaryWriter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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.Diagnostics;
  6. using System.Buffers;
  7. using System.Threading.Tasks;
  8. namespace System.IO
  9. {
  10. // This abstract base class represents a writer that can write
  11. // primitives to an arbitrary stream. A subclass can override methods to
  12. // give unique encodings.
  13. //
  14. public class BinaryWriter : IDisposable, IAsyncDisposable
  15. {
  16. public static readonly BinaryWriter Null = new BinaryWriter();
  17. protected Stream OutStream;
  18. private byte[] _buffer; // temp space for writing primitives to.
  19. private Encoding _encoding;
  20. private Encoder _encoder;
  21. private bool _leaveOpen;
  22. // Perf optimization stuff
  23. private byte[] _largeByteBuffer; // temp space for writing chars.
  24. private int _maxChars; // max # of chars we can put in _largeByteBuffer
  25. // Size should be around the max number of chars/string * Encoding's max bytes/char
  26. private const int LargeByteBufferSize = 256;
  27. // Protected default constructor that sets the output stream
  28. // to a null stream (a bit bucket).
  29. protected BinaryWriter()
  30. {
  31. OutStream = Stream.Null;
  32. _buffer = new byte[16];
  33. _encoding = EncodingCache.UTF8NoBOM;
  34. _encoder = _encoding.GetEncoder();
  35. }
  36. public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, false)
  37. {
  38. }
  39. public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false)
  40. {
  41. }
  42. public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
  43. {
  44. if (output == null)
  45. throw new ArgumentNullException(nameof(output));
  46. if (encoding == null)
  47. throw new ArgumentNullException(nameof(encoding));
  48. if (!output.CanWrite)
  49. throw new ArgumentException(SR.Argument_StreamNotWritable);
  50. OutStream = output;
  51. _buffer = new byte[16];
  52. _encoding = encoding;
  53. _encoder = _encoding.GetEncoder();
  54. _leaveOpen = leaveOpen;
  55. }
  56. // Closes this writer and releases any system resources associated with the
  57. // writer. Following a call to Close, any operations on the writer
  58. // may raise exceptions.
  59. public virtual void Close()
  60. {
  61. Dispose(true);
  62. }
  63. protected virtual void Dispose(bool disposing)
  64. {
  65. if (disposing)
  66. {
  67. if (_leaveOpen)
  68. OutStream.Flush();
  69. else
  70. OutStream.Close();
  71. }
  72. }
  73. public void Dispose()
  74. {
  75. Dispose(true);
  76. }
  77. public virtual ValueTask DisposeAsync()
  78. {
  79. try
  80. {
  81. if (GetType() == typeof(BinaryWriter))
  82. {
  83. if (_leaveOpen)
  84. {
  85. return new ValueTask(OutStream.FlushAsync());
  86. }
  87. OutStream.Close();
  88. }
  89. else
  90. {
  91. // Since this is a derived BinaryWriter, delegate to whatever logic
  92. // the derived implementation already has in Dispose.
  93. Dispose();
  94. }
  95. return default;
  96. }
  97. catch (Exception exc)
  98. {
  99. return new ValueTask(Task.FromException(exc));
  100. }
  101. }
  102. // Returns the stream associated with the writer. It flushes all pending
  103. // writes before returning. All subclasses should override Flush to
  104. // ensure that all buffered data is sent to the stream.
  105. public virtual Stream BaseStream
  106. {
  107. get
  108. {
  109. Flush();
  110. return OutStream;
  111. }
  112. }
  113. // Clears all buffers for this writer and causes any buffered data to be
  114. // written to the underlying device.
  115. public virtual void Flush()
  116. {
  117. OutStream.Flush();
  118. }
  119. public virtual long Seek(int offset, SeekOrigin origin)
  120. {
  121. return OutStream.Seek(offset, origin);
  122. }
  123. // Writes a boolean to this stream. A single byte is written to the stream
  124. // with the value 0 representing false or the value 1 representing true.
  125. //
  126. public virtual void Write(bool value)
  127. {
  128. _buffer[0] = (byte)(value ? 1 : 0);
  129. OutStream.Write(_buffer, 0, 1);
  130. }
  131. // Writes a byte to this stream. The current position of the stream is
  132. // advanced by one.
  133. //
  134. public virtual void Write(byte value)
  135. {
  136. OutStream.WriteByte(value);
  137. }
  138. // Writes a signed byte to this stream. The current position of the stream
  139. // is advanced by one.
  140. //
  141. [CLSCompliant(false)]
  142. public virtual void Write(sbyte value)
  143. {
  144. OutStream.WriteByte((byte)value);
  145. }
  146. // Writes a byte array to this stream.
  147. //
  148. // This default implementation calls the Write(Object, int, int)
  149. // method to write the byte array.
  150. //
  151. public virtual void Write(byte[] buffer)
  152. {
  153. if (buffer == null)
  154. throw new ArgumentNullException(nameof(buffer));
  155. OutStream.Write(buffer, 0, buffer.Length);
  156. }
  157. // Writes a section of a byte array to this stream.
  158. //
  159. // This default implementation calls the Write(Object, int, int)
  160. // method to write the byte array.
  161. //
  162. public virtual void Write(byte[] buffer, int index, int count)
  163. {
  164. OutStream.Write(buffer, index, count);
  165. }
  166. // Writes a character to this stream. The current position of the stream is
  167. // advanced by two.
  168. // Note this method cannot handle surrogates properly in UTF-8.
  169. //
  170. public unsafe virtual void Write(char ch)
  171. {
  172. if (char.IsSurrogate(ch))
  173. throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar);
  174. Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
  175. int numBytes = 0;
  176. fixed (byte* pBytes = &_buffer[0])
  177. {
  178. numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
  179. }
  180. OutStream.Write(_buffer, 0, numBytes);
  181. }
  182. // Writes a character array to this stream.
  183. //
  184. // This default implementation calls the Write(Object, int, int)
  185. // method to write the character array.
  186. //
  187. public virtual void Write(char[] chars)
  188. {
  189. if (chars == null)
  190. throw new ArgumentNullException(nameof(chars));
  191. byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
  192. OutStream.Write(bytes, 0, bytes.Length);
  193. }
  194. // Writes a section of a character array to this stream.
  195. //
  196. // This default implementation calls the Write(Object, int, int)
  197. // method to write the character array.
  198. //
  199. public virtual void Write(char[] chars, int index, int count)
  200. {
  201. byte[] bytes = _encoding.GetBytes(chars, index, count);
  202. OutStream.Write(bytes, 0, bytes.Length);
  203. }
  204. // Writes a double to this stream. The current position of the stream is
  205. // advanced by eight.
  206. //
  207. public unsafe virtual void Write(double value)
  208. {
  209. ulong TmpValue = *(ulong*)&value;
  210. _buffer[0] = (byte)TmpValue;
  211. _buffer[1] = (byte)(TmpValue >> 8);
  212. _buffer[2] = (byte)(TmpValue >> 16);
  213. _buffer[3] = (byte)(TmpValue >> 24);
  214. _buffer[4] = (byte)(TmpValue >> 32);
  215. _buffer[5] = (byte)(TmpValue >> 40);
  216. _buffer[6] = (byte)(TmpValue >> 48);
  217. _buffer[7] = (byte)(TmpValue >> 56);
  218. OutStream.Write(_buffer, 0, 8);
  219. }
  220. public virtual void Write(decimal value)
  221. {
  222. decimal.GetBytes(value, _buffer);
  223. OutStream.Write(_buffer, 0, 16);
  224. }
  225. // Writes a two-byte signed integer to this stream. The current position of
  226. // the stream is advanced by two.
  227. //
  228. public virtual void Write(short value)
  229. {
  230. _buffer[0] = (byte)value;
  231. _buffer[1] = (byte)(value >> 8);
  232. OutStream.Write(_buffer, 0, 2);
  233. }
  234. // Writes a two-byte unsigned integer to this stream. The current position
  235. // of the stream is advanced by two.
  236. //
  237. [CLSCompliant(false)]
  238. public virtual void Write(ushort value)
  239. {
  240. _buffer[0] = (byte)value;
  241. _buffer[1] = (byte)(value >> 8);
  242. OutStream.Write(_buffer, 0, 2);
  243. }
  244. // Writes a four-byte signed integer to this stream. The current position
  245. // of the stream is advanced by four.
  246. //
  247. public virtual void Write(int value)
  248. {
  249. _buffer[0] = (byte)value;
  250. _buffer[1] = (byte)(value >> 8);
  251. _buffer[2] = (byte)(value >> 16);
  252. _buffer[3] = (byte)(value >> 24);
  253. OutStream.Write(_buffer, 0, 4);
  254. }
  255. // Writes a four-byte unsigned integer to this stream. The current position
  256. // of the stream is advanced by four.
  257. //
  258. [CLSCompliant(false)]
  259. public virtual void Write(uint value)
  260. {
  261. _buffer[0] = (byte)value;
  262. _buffer[1] = (byte)(value >> 8);
  263. _buffer[2] = (byte)(value >> 16);
  264. _buffer[3] = (byte)(value >> 24);
  265. OutStream.Write(_buffer, 0, 4);
  266. }
  267. // Writes an eight-byte signed integer to this stream. The current position
  268. // of the stream is advanced by eight.
  269. //
  270. public virtual void Write(long value)
  271. {
  272. _buffer[0] = (byte)value;
  273. _buffer[1] = (byte)(value >> 8);
  274. _buffer[2] = (byte)(value >> 16);
  275. _buffer[3] = (byte)(value >> 24);
  276. _buffer[4] = (byte)(value >> 32);
  277. _buffer[5] = (byte)(value >> 40);
  278. _buffer[6] = (byte)(value >> 48);
  279. _buffer[7] = (byte)(value >> 56);
  280. OutStream.Write(_buffer, 0, 8);
  281. }
  282. // Writes an eight-byte unsigned integer to this stream. The current
  283. // position of the stream is advanced by eight.
  284. //
  285. [CLSCompliant(false)]
  286. public virtual void Write(ulong value)
  287. {
  288. _buffer[0] = (byte)value;
  289. _buffer[1] = (byte)(value >> 8);
  290. _buffer[2] = (byte)(value >> 16);
  291. _buffer[3] = (byte)(value >> 24);
  292. _buffer[4] = (byte)(value >> 32);
  293. _buffer[5] = (byte)(value >> 40);
  294. _buffer[6] = (byte)(value >> 48);
  295. _buffer[7] = (byte)(value >> 56);
  296. OutStream.Write(_buffer, 0, 8);
  297. }
  298. // Writes a float to this stream. The current position of the stream is
  299. // advanced by four.
  300. //
  301. public unsafe virtual void Write(float value)
  302. {
  303. uint TmpValue = *(uint*)&value;
  304. _buffer[0] = (byte)TmpValue;
  305. _buffer[1] = (byte)(TmpValue >> 8);
  306. _buffer[2] = (byte)(TmpValue >> 16);
  307. _buffer[3] = (byte)(TmpValue >> 24);
  308. OutStream.Write(_buffer, 0, 4);
  309. }
  310. // Writes a length-prefixed string to this stream in the BinaryWriter's
  311. // current Encoding. This method first writes the length of the string as
  312. // a four-byte unsigned integer, and then writes that many characters
  313. // to the stream.
  314. //
  315. public unsafe virtual void Write(string value)
  316. {
  317. if (value == null)
  318. throw new ArgumentNullException(nameof(value));
  319. int len = _encoding.GetByteCount(value);
  320. Write7BitEncodedInt(len);
  321. if (_largeByteBuffer == null)
  322. {
  323. _largeByteBuffer = new byte[LargeByteBufferSize];
  324. _maxChars = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1);
  325. }
  326. if (len <= _largeByteBuffer.Length)
  327. {
  328. //Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
  329. _encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
  330. OutStream.Write(_largeByteBuffer, 0, len);
  331. }
  332. else
  333. {
  334. // Aggressively try to not allocate memory in this loop for
  335. // runtime performance reasons. Use an Encoder to write out
  336. // the string correctly (handling surrogates crossing buffer
  337. // boundaries properly).
  338. int charStart = 0;
  339. int numLeft = value.Length;
  340. #if DEBUG
  341. int totalBytes = 0;
  342. #endif
  343. while (numLeft > 0)
  344. {
  345. // Figure out how many chars to process this round.
  346. int charCount = (numLeft > _maxChars) ? _maxChars : numLeft;
  347. int byteLen;
  348. checked
  349. {
  350. if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount)
  351. {
  352. throw new ArgumentOutOfRangeException(nameof(charCount));
  353. }
  354. fixed (char* pChars = value)
  355. {
  356. fixed (byte* pBytes = &_largeByteBuffer[0])
  357. {
  358. byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, _largeByteBuffer.Length, charCount == numLeft);
  359. }
  360. }
  361. }
  362. #if DEBUG
  363. totalBytes += byteLen;
  364. Debug.Assert(totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
  365. #endif
  366. OutStream.Write(_largeByteBuffer, 0, byteLen);
  367. charStart += charCount;
  368. numLeft -= charCount;
  369. }
  370. #if DEBUG
  371. Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
  372. #endif
  373. }
  374. }
  375. public virtual void Write(ReadOnlySpan<byte> buffer)
  376. {
  377. if (GetType() == typeof(BinaryWriter))
  378. {
  379. OutStream.Write(buffer);
  380. }
  381. else
  382. {
  383. byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length);
  384. try
  385. {
  386. buffer.CopyTo(array);
  387. Write(array, 0, buffer.Length);
  388. }
  389. finally
  390. {
  391. ArrayPool<byte>.Shared.Return(array);
  392. }
  393. }
  394. }
  395. public virtual void Write(ReadOnlySpan<char> chars)
  396. {
  397. byte[] bytes = ArrayPool<byte>.Shared.Rent(_encoding.GetMaxByteCount(chars.Length));
  398. try
  399. {
  400. int bytesWritten = _encoding.GetBytes(chars, bytes);
  401. Write(bytes, 0, bytesWritten);
  402. }
  403. finally
  404. {
  405. ArrayPool<byte>.Shared.Return(bytes);
  406. }
  407. }
  408. protected void Write7BitEncodedInt(int value)
  409. {
  410. // Write out an int 7 bits at a time. The high bit of the byte,
  411. // when on, tells reader to continue reading more bytes.
  412. uint v = (uint)value; // support negative numbers
  413. while (v >= 0x80)
  414. {
  415. Write((byte)(v | 0x80));
  416. v >>= 7;
  417. }
  418. Write((byte)v);
  419. }
  420. }
  421. }