Encoder.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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.Diagnostics;
  5. using System.Runtime.InteropServices;
  6. namespace System.Text
  7. {
  8. // An Encoder is used to encode a sequence of blocks of characters into
  9. // a sequence of blocks of bytes. Following instantiation of an encoder,
  10. // sequential blocks of characters are converted into blocks of bytes through
  11. // calls to the GetBytes method. The encoder maintains state between the
  12. // conversions, allowing it to correctly encode character sequences that span
  13. // adjacent blocks.
  14. //
  15. // Instances of specific implementations of the Encoder abstract base
  16. // class are typically obtained through calls to the GetEncoder method
  17. // of Encoding objects.
  18. //
  19. public abstract class Encoder
  20. {
  21. internal EncoderFallback? _fallback = null;
  22. internal EncoderFallbackBuffer? _fallbackBuffer = null;
  23. protected Encoder()
  24. {
  25. // We don't call default reset because default reset probably isn't good if we aren't initialized.
  26. }
  27. public EncoderFallback? Fallback
  28. {
  29. get => _fallback;
  30. set
  31. {
  32. if (value == null)
  33. throw new ArgumentNullException(nameof(value));
  34. // Can't change fallback if buffer is wrong
  35. if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0)
  36. throw new ArgumentException(
  37. SR.Argument_FallbackBufferNotEmpty, nameof(value));
  38. _fallback = value;
  39. _fallbackBuffer = null;
  40. }
  41. }
  42. // Note: we don't test for threading here because async access to Encoders and Decoders
  43. // doesn't work anyway.
  44. public EncoderFallbackBuffer FallbackBuffer
  45. {
  46. get
  47. {
  48. if (_fallbackBuffer == null)
  49. {
  50. if (_fallback != null)
  51. _fallbackBuffer = _fallback.CreateFallbackBuffer();
  52. else
  53. _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
  54. }
  55. return _fallbackBuffer;
  56. }
  57. }
  58. internal bool InternalHasFallbackBuffer => _fallbackBuffer != null;
  59. // Reset the Encoder
  60. //
  61. // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This
  62. // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
  63. //
  64. // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset().
  65. //
  66. // Virtual implementation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
  67. // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
  68. public virtual void Reset()
  69. {
  70. char[] charTemp = Array.Empty<char>();
  71. byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
  72. GetBytes(charTemp, 0, 0, byteTemp, 0, true);
  73. if (_fallbackBuffer != null)
  74. _fallbackBuffer.Reset();
  75. }
  76. // Returns the number of bytes the next call to GetBytes will
  77. // produce if presented with the given range of characters and the given
  78. // value of the flush parameter. The returned value takes into
  79. // account the state in which the encoder was left following the last call
  80. // to GetBytes. The state of the encoder is not affected by a call
  81. // to this method.
  82. //
  83. public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
  84. // We expect this to be the workhorse for NLS encodings
  85. // unfortunately for existing overrides, it has to call the [] version,
  86. // which is really slow, so avoid this method if you might be calling external encodings.
  87. [CLSCompliant(false)]
  88. public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
  89. {
  90. // Validate input parameters
  91. if (chars == null)
  92. throw new ArgumentNullException(nameof(chars),
  93. SR.ArgumentNull_Array);
  94. if (count < 0)
  95. throw new ArgumentOutOfRangeException(nameof(count),
  96. SR.ArgumentOutOfRange_NeedNonNegNum);
  97. char[] arrChar = new char[count];
  98. int index;
  99. for (index = 0; index < count; index++)
  100. arrChar[index] = chars[index];
  101. return GetByteCount(arrChar, 0, count, flush);
  102. }
  103. public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars, bool flush)
  104. {
  105. fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
  106. {
  107. return GetByteCount(charsPtr, chars.Length, flush);
  108. }
  109. }
  110. // Encodes a range of characters in a character array into a range of bytes
  111. // in a byte array. The method encodes charCount characters from
  112. // chars starting at index charIndex, storing the resulting
  113. // bytes in bytes starting at index byteIndex. The encoding
  114. // takes into account the state in which the encoder was left following the
  115. // last call to this method. The flush parameter indicates whether
  116. // the encoder should flush any shift-states and partial characters at the
  117. // end of the conversion. To ensure correct termination of a sequence of
  118. // blocks of encoded bytes, the last call to GetBytes should specify
  119. // a value of true for the flush parameter.
  120. //
  121. // An exception occurs if the byte array is not large enough to hold the
  122. // complete encoding of the characters. The GetByteCount method can
  123. // be used to determine the exact number of bytes that will be produced for
  124. // a given range of characters. Alternatively, the GetMaxByteCount
  125. // method of the Encoding that produced this encoder can be used to
  126. // determine the maximum number of bytes that will be produced for a given
  127. // number of characters, regardless of the actual character values.
  128. //
  129. public abstract int GetBytes(char[] chars, int charIndex, int charCount,
  130. byte[] bytes, int byteIndex, bool flush);
  131. // We expect this to be the workhorse for NLS Encodings, but for existing
  132. // ones we need a working (if slow) default implementation)
  133. //
  134. // WARNING WARNING WARNING
  135. //
  136. // WARNING: If this breaks it could be a security threat. Obviously we
  137. // call this internally, so you need to make sure that your pointers, counts
  138. // and indexes are correct when you call this method.
  139. //
  140. // In addition, we have internal code, which will be marked as "safe" calling
  141. // this code. However this code is dependent upon the implementation of an
  142. // external GetBytes() method, which could be overridden by a third party and
  143. // the results of which cannot be guaranteed. We use that result to copy
  144. // the byte[] to our byte* output buffer. If the result count was wrong, we
  145. // could easily overflow our output buffer. Therefore we do an extra test
  146. // when we copy the buffer so that we don't overflow byteCount either.
  147. [CLSCompliant(false)]
  148. public virtual unsafe int GetBytes(char* chars, int charCount,
  149. byte* bytes, int byteCount, bool flush)
  150. {
  151. // Validate input parameters
  152. if (bytes == null || chars == null)
  153. throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
  154. SR.ArgumentNull_Array);
  155. if (charCount < 0 || byteCount < 0)
  156. throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount),
  157. SR.ArgumentOutOfRange_NeedNonNegNum);
  158. // Get the char array to convert
  159. char[] arrChar = new char[charCount];
  160. int index;
  161. for (index = 0; index < charCount; index++)
  162. arrChar[index] = chars[index];
  163. // Get the byte array to fill
  164. byte[] arrByte = new byte[byteCount];
  165. // Do the work
  166. int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
  167. Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
  168. // Copy the byte array
  169. // WARNING: We MUST make sure that we don't copy too many bytes. We can't
  170. // rely on result because it could be a 3rd party implementation. We need
  171. // to make sure we never copy more than byteCount bytes no matter the value
  172. // of result
  173. if (result < byteCount)
  174. byteCount = result;
  175. // Don't copy too many bytes!
  176. for (index = 0; index < byteCount; index++)
  177. bytes[index] = arrByte[index];
  178. return byteCount;
  179. }
  180. public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush)
  181. {
  182. fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
  183. fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
  184. {
  185. return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush);
  186. }
  187. }
  188. // This method is used to avoid running out of output buffer space.
  189. // It will encode until it runs out of chars, and then it will return
  190. // true if it the entire input was converted. In either case it
  191. // will also return the number of converted chars and output bytes used.
  192. // It will only throw a buffer overflow exception if the entire lenght of bytes[] is
  193. // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings)
  194. // We're done processing this buffer only if completed returns true.
  195. //
  196. // Might consider checking Max...Count to avoid the extra counting step.
  197. //
  198. // Note that if all of the input chars are not consumed, then we'll do a /2, which means
  199. // that its likely that we didn't consume as many chars as we could have. For some
  200. // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
  201. public virtual void Convert(char[] chars, int charIndex, int charCount,
  202. byte[] bytes, int byteIndex, int byteCount, bool flush,
  203. out int charsUsed, out int bytesUsed, out bool completed)
  204. {
  205. // Validate parameters
  206. if (chars == null || bytes == null)
  207. throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
  208. SR.ArgumentNull_Array);
  209. if (charIndex < 0 || charCount < 0)
  210. throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount),
  211. SR.ArgumentOutOfRange_NeedNonNegNum);
  212. if (byteIndex < 0 || byteCount < 0)
  213. throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount),
  214. SR.ArgumentOutOfRange_NeedNonNegNum);
  215. if (chars.Length - charIndex < charCount)
  216. throw new ArgumentOutOfRangeException(nameof(chars),
  217. SR.ArgumentOutOfRange_IndexCountBuffer);
  218. if (bytes.Length - byteIndex < byteCount)
  219. throw new ArgumentOutOfRangeException(nameof(bytes),
  220. SR.ArgumentOutOfRange_IndexCountBuffer);
  221. charsUsed = charCount;
  222. // Its easy to do if it won't overrun our buffer.
  223. // Note: We don't want to call unsafe version because that might be an untrusted version
  224. // which could be really unsafe and we don't want to mix it up.
  225. while (charsUsed > 0)
  226. {
  227. if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount)
  228. {
  229. bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush);
  230. completed = (charsUsed == charCount &&
  231. (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
  232. return;
  233. }
  234. // Try again with 1/2 the count, won't flush then 'cause won't read it all
  235. flush = false;
  236. charsUsed /= 2;
  237. }
  238. // Oops, we didn't have anything, we'll have to throw an overflow
  239. throw new ArgumentException(SR.Argument_ConversionOverflow);
  240. }
  241. // Same thing, but using pointers
  242. //
  243. // Might consider checking Max...Count to avoid the extra counting step.
  244. //
  245. // Note that if all of the input chars are not consumed, then we'll do a /2, which means
  246. // that its likely that we didn't consume as many chars as we could have. For some
  247. // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
  248. [CLSCompliant(false)]
  249. public virtual unsafe void Convert(char* chars, int charCount,
  250. byte* bytes, int byteCount, bool flush,
  251. out int charsUsed, out int bytesUsed, out bool completed)
  252. {
  253. // Validate input parameters
  254. if (bytes == null || chars == null)
  255. throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
  256. SR.ArgumentNull_Array);
  257. if (charCount < 0 || byteCount < 0)
  258. throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount),
  259. SR.ArgumentOutOfRange_NeedNonNegNum);
  260. // Get ready to do it
  261. charsUsed = charCount;
  262. // Its easy to do if it won't overrun our buffer.
  263. while (charsUsed > 0)
  264. {
  265. if (GetByteCount(chars, charsUsed, flush) <= byteCount)
  266. {
  267. bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush);
  268. completed = (charsUsed == charCount &&
  269. (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0));
  270. return;
  271. }
  272. // Try again with 1/2 the count, won't flush then 'cause won't read it all
  273. flush = false;
  274. charsUsed /= 2;
  275. }
  276. // Oops, we didn't have anything, we'll have to throw an overflow
  277. throw new ArgumentException(SR.Argument_ConversionOverflow);
  278. }
  279. public virtual unsafe void Convert(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed)
  280. {
  281. fixed (char* charsPtr = &MemoryMarshal.GetNonNullPinnableReference(chars))
  282. fixed (byte* bytesPtr = &MemoryMarshal.GetNonNullPinnableReference(bytes))
  283. {
  284. Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed);
  285. }
  286. }
  287. }
  288. }