EncoderBestFitFallback.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. //
  5. // This is used internally to create best fit behavior as per the original windows best fit behavior.
  6. //
  7. using System.Diagnostics;
  8. using System.Globalization;
  9. using System.Threading;
  10. namespace System.Text
  11. {
  12. internal class InternalEncoderBestFitFallback : EncoderFallback
  13. {
  14. // Our variables
  15. internal Encoding _encoding;
  16. internal char[]? _arrayBestFit = null;
  17. internal InternalEncoderBestFitFallback(Encoding encoding)
  18. {
  19. // Need to load our replacement characters table.
  20. _encoding = encoding;
  21. }
  22. public override EncoderFallbackBuffer CreateFallbackBuffer() =>
  23. new InternalEncoderBestFitFallbackBuffer(this);
  24. // Maximum number of characters that this instance of this fallback could return
  25. public override int MaxCharCount => 1;
  26. public override bool Equals(object? value) =>
  27. value is InternalEncoderBestFitFallback that &&
  28. _encoding.CodePage == that._encoding.CodePage;
  29. public override int GetHashCode() => _encoding.CodePage;
  30. }
  31. internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
  32. {
  33. // Our variables
  34. private char _cBestFit = '\0';
  35. private readonly InternalEncoderBestFitFallback _oFallback;
  36. private int _iCount = -1;
  37. private int _iSize;
  38. // Private object for locking instead of locking on a public type for SQL reliability work.
  39. private static object? s_InternalSyncObject;
  40. private static object InternalSyncObject
  41. {
  42. get
  43. {
  44. if (s_InternalSyncObject == null)
  45. {
  46. object o = new object();
  47. Interlocked.CompareExchange<object?>(ref s_InternalSyncObject, o, null);
  48. }
  49. return s_InternalSyncObject;
  50. }
  51. }
  52. // Constructor
  53. public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
  54. {
  55. _oFallback = fallback;
  56. if (_oFallback._arrayBestFit == null)
  57. {
  58. // Lock so we don't confuse ourselves.
  59. lock (InternalSyncObject)
  60. {
  61. // Double check before we do it again.
  62. _oFallback._arrayBestFit ??= fallback._encoding.GetBestFitUnicodeToBytesData();
  63. }
  64. }
  65. }
  66. // Fallback methods
  67. public override bool Fallback(char charUnknown, int index)
  68. {
  69. // If we had a buffer already we're being recursive, throw, it's probably at the suspect
  70. // character in our array.
  71. // Shouldn't be able to get here for all of our code pages, table would have to be messed up.
  72. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
  73. _iCount = _iSize = 1;
  74. _cBestFit = TryBestFit(charUnknown);
  75. if (_cBestFit == '\0')
  76. _cBestFit = '?';
  77. return true;
  78. }
  79. public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
  80. {
  81. // Double check input surrogate pair
  82. if (!char.IsHighSurrogate(charUnknownHigh))
  83. throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
  84. SR.Format(SR.ArgumentOutOfRange_Range,
  85. 0xD800, 0xDBFF));
  86. if (!char.IsLowSurrogate(charUnknownLow))
  87. throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
  88. SR.Format(SR.ArgumentOutOfRange_Range,
  89. 0xDC00, 0xDFFF));
  90. // If we had a buffer already we're being recursive, throw, it's probably at the suspect
  91. // character in our array. 0 is processing last character, < 0 is not falling back
  92. // Shouldn't be able to get here, table would have to be messed up.
  93. Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
  94. // Go ahead and get our fallback, surrogates don't have best fit
  95. _cBestFit = '?';
  96. _iCount = _iSize = 2;
  97. return true;
  98. }
  99. // Default version is overridden in EncoderReplacementFallback.cs
  100. public override char GetNextChar()
  101. {
  102. // We want it to get < 0 because == 0 means that the current/last character is a fallback
  103. // and we need to detect recursion. We could have a flag but we already have this counter.
  104. _iCount--;
  105. // Do we have anything left? 0 is now last fallback char, negative is nothing left
  106. if (_iCount < 0)
  107. return '\0';
  108. // Need to get it out of the buffer.
  109. // Make sure it didn't wrap from the fast count-- path
  110. if (_iCount == int.MaxValue)
  111. {
  112. _iCount = -1;
  113. return '\0';
  114. }
  115. // Return the best fit character
  116. return _cBestFit;
  117. }
  118. public override bool MovePrevious()
  119. {
  120. // Exception fallback doesn't have anywhere to back up to.
  121. if (_iCount >= 0)
  122. _iCount++;
  123. // Return true if we could do it.
  124. return _iCount >= 0 && _iCount <= _iSize;
  125. }
  126. // How many characters left to output?
  127. public override int Remaining => (_iCount > 0) ? _iCount : 0;
  128. // Clear the buffer
  129. public override unsafe void Reset()
  130. {
  131. _iCount = -1;
  132. charStart = null;
  133. bFallingBack = false;
  134. }
  135. // private helper methods
  136. private char TryBestFit(char cUnknown)
  137. {
  138. // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
  139. int lowBound = 0;
  140. Debug.Assert(_oFallback._arrayBestFit != null);
  141. int highBound = _oFallback._arrayBestFit.Length;
  142. int index;
  143. // Binary search the array
  144. int iDiff;
  145. while ((iDiff = (highBound - lowBound)) > 6)
  146. {
  147. // Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
  148. // so we don't want index to be odd because we want to be on word boundaries.
  149. // Also note that index can never == highBound (because diff is rounded down)
  150. index = ((iDiff / 2) + lowBound) & 0xFFFE;
  151. char cTest = _oFallback._arrayBestFit[index];
  152. if (cTest == cUnknown)
  153. {
  154. // We found it
  155. Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length,
  156. "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
  157. return _oFallback._arrayBestFit[index + 1];
  158. }
  159. else if (cTest < cUnknown)
  160. {
  161. // We weren't high enough
  162. lowBound = index;
  163. }
  164. else
  165. {
  166. // We weren't low enough
  167. highBound = index;
  168. }
  169. }
  170. for (index = lowBound; index < highBound; index += 2)
  171. {
  172. if (_oFallback._arrayBestFit[index] == cUnknown)
  173. {
  174. // We found it
  175. Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length,
  176. "[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
  177. return _oFallback._arrayBestFit[index + 1];
  178. }
  179. }
  180. // Char wasn't in our table
  181. return '\0';
  182. }
  183. }
  184. }