Decoder.cs 15 KB

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