Utf32Buffer.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // RichTextKit
  2. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. // not use this product except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. using Topten.RichTextKit.Utils;
  21. namespace Topten.RichTextKit.Utils
  22. {
  23. /// <summary>
  24. /// Represents a buffer of UTF-32 encoded code point data
  25. /// </summary>
  26. public class Utf32Buffer : Buffer<int>
  27. {
  28. /// <summary>
  29. /// Constructs a new Utf32Buffer
  30. /// </summary>
  31. public Utf32Buffer()
  32. {
  33. }
  34. /// <summary>
  35. /// Constructs a Utf32 buffer with an initial string
  36. /// </summary>
  37. /// <param name="str">The string to initialize with</param>
  38. public Utf32Buffer(string str)
  39. {
  40. Add(str);
  41. }
  42. /// <summary>
  43. /// Clears this buffer.
  44. /// </summary>
  45. public new void Clear()
  46. {
  47. _surrogatePositionsValid = false;
  48. base.Clear();
  49. }
  50. /// <summary>
  51. /// Appends utf32 data to this buffer
  52. /// </summary>
  53. /// <param name="data">The UTF32 data to be appended</param>
  54. /// <returns>A slice representing the added UTF-32 data.</returns>
  55. public new Slice<int> Add(Slice<int> data)
  56. {
  57. _surrogatePositionsValid = false;
  58. return base.Add(data);
  59. }
  60. /// <summary>
  61. /// Appends text to this buffer, converting from UTF-16 to UTF-32
  62. /// </summary>
  63. /// <param name="str">The string of text to be inserted</param>
  64. /// <returns>A slice representing the added UTF-32 data.</returns>
  65. public Slice<int> Add(string str)
  66. {
  67. return Insert(Length, str);
  68. }
  69. /// <summary>
  70. /// Appends text to this buffer, converting from UTF-16 to UTF-32
  71. /// </summary>
  72. /// <param name="str">The string of text to be inserted</param>
  73. /// <returns>A slice representing the added UTF-32 data.</returns>
  74. public Slice<int> Add(ReadOnlySpan<char> str)
  75. {
  76. return Insert(Length, str);
  77. }
  78. /// <summary>
  79. /// Appends utf32 data to this buffer
  80. /// </summary>
  81. /// <param name="position">Position to insert the string</param>
  82. /// <param name="data">The string of text to be appended</param>
  83. /// <returns>A slice representing the added UTF-32 data.</returns>
  84. public new Slice<int> Insert(int position, Slice<int> data)
  85. {
  86. _surrogatePositionsValid = false;
  87. return base.Insert(position, data);
  88. }
  89. /// <summary>
  90. /// Inserts text to this buffer, converting from UTF-16 to UTF-32
  91. /// </summary>
  92. /// <param name="position">The position to insert the string</param>
  93. /// <param name="str">The string of text to be inserted</param>
  94. /// <returns>A slice representing the added UTF-32 data.</returns>
  95. public Slice<int> Insert(int position, string str)
  96. {
  97. return Insert(position, str.AsSpan());
  98. }
  99. /// <summary>
  100. /// Inserts text to this buffer, converting from UTF-16 to UTF-32
  101. /// </summary>
  102. /// <param name="position">The position to insert the string</param>
  103. /// <param name="str">The string of text to be inserted</param>
  104. /// <returns>A slice representing the added UTF-32 data.</returns>
  105. public Slice<int> Insert(int position, ReadOnlySpan<char> str)
  106. {
  107. // Remember old length
  108. int oldLength = Length;
  109. // Invalidate surrogate positions
  110. _surrogatePositionsValid = false;
  111. // For performance reasons and to save copying to intermediate arrays if we use
  112. // (Encoding.UTF32), we do our own utf16 to utf32 decoding directly to our
  113. // internal code point buffer. Also stores the indicies of any surrogate pairs
  114. // for later back conversion.
  115. // Also use pointers for performance reasons too (maybe)
  116. Slice<int> codePointBuffer = base.Insert(position, str.Length);
  117. int convertedLength;
  118. unsafe
  119. {
  120. fixed (int* pDestBuf = codePointBuffer.Underlying)
  121. fixed (char* pSrcBuf = str)
  122. {
  123. int* pDestStart = pDestBuf + codePointBuffer.Start;
  124. int* pDest = pDestStart;
  125. char* pSrc = pSrcBuf;
  126. char* pSrcEnd = pSrcBuf + str.Length;
  127. while (pSrc < pSrcEnd)
  128. {
  129. char ch = *pSrc++;
  130. if (ch >= 0xD800 && ch <= 0xDFFF)
  131. {
  132. if (ch <= 0xDBFF)
  133. {
  134. // High surrogate
  135. var chL = pSrc < pSrcEnd ? (*pSrc++) : 0;
  136. *pDest++ = 0x10000 | ((ch - 0xD800) << 10) | (chL - 0xDC00);
  137. }
  138. else
  139. {
  140. // Single low surrogte?
  141. *pDest++ = 0x10000 + ch - 0xDC00;
  142. }
  143. }
  144. else
  145. {
  146. *pDest++ = ch;
  147. }
  148. }
  149. // Work out the converted length
  150. convertedLength = (int)(pDest - pDestStart);
  151. }
  152. }
  153. // If converted length was shorter due to surrogates, then remove
  154. // the extra space that was allocated
  155. if (convertedLength < str.Length)
  156. {
  157. base.Delete(position + convertedLength, str.Length - convertedLength);
  158. }
  159. // Return the encapsulating slice
  160. return SubSlice(position, convertedLength);
  161. }
  162. /// <summary>
  163. /// Delete a section of the buffer
  164. /// </summary>
  165. /// <param name="from">The position to delete from</param>
  166. /// <param name="length">The length to of the deletion</param>
  167. public new void Delete(int from, int length)
  168. {
  169. _surrogatePositionsValid = false;
  170. base.Delete(from, length);
  171. }
  172. /// <summary>
  173. /// Convers an offset into this buffer to a UTF-16 offset in the originally
  174. /// added string.
  175. /// </summary>
  176. /// <remarks>
  177. /// This function assumes the was text added to the buffer as UTF-16
  178. /// and hasn't been modified in any way since.
  179. /// </remarks>
  180. /// <param name="utf32Offset">The UTF-3232 offset to convert</param>
  181. /// <returns>The converted UTF-16 character offset</returns>
  182. public int Utf32OffsetToUtf16Offset(int utf32Offset)
  183. {
  184. // Make sure surrorgate positions are valid
  185. BuildSurrogatePositions();
  186. // How many surrogate pairs were there before this utf32 offset?
  187. int pos = _surrogatePositions.BinarySearch(utf32Offset);
  188. if (pos < 0)
  189. {
  190. pos = ~pos;
  191. }
  192. return utf32Offset + pos;
  193. }
  194. /// <summary>
  195. /// Converts an offset in the original UTF-16 string, a code point index into
  196. /// this UTF-32 buffer.
  197. /// </summary>
  198. /// <param name="utf16Offset">The utf-16 character index</param>
  199. /// <returns>The utf-32 code point index</returns>
  200. public int Utf16OffsetToUtf32Offset(int utf16Offset)
  201. {
  202. // Make sure surrorgate positions are valid
  203. BuildSurrogatePositions();
  204. var pos = utf16Offset;
  205. for (int i = 0; i < _surrogatePositions.Count; i++)
  206. {
  207. var sp = _surrogatePositions[i];
  208. if (sp < pos)
  209. pos--;
  210. if (sp > pos)
  211. return pos;
  212. }
  213. return pos;
  214. }
  215. /// <summary>
  216. /// Gets the enture buffer's content as a string.
  217. /// </summary>
  218. /// <returns></returns>
  219. public override string ToString()
  220. {
  221. return Utf32Utils.FromUtf32(AsSlice());
  222. }
  223. /// <summary>
  224. /// Gets a part of the buffer as a string.
  225. /// </summary>
  226. /// <param name="start">The UTF-32 code point index of the first character to retrieve</param>
  227. /// <param name="length">The number of code points in the string to be retrieved</param>
  228. /// <returns>A string equivalent to the specified code point range.</returns>
  229. public string GetString(int start, int length)
  230. {
  231. return Utf32Utils.FromUtf32(SubSlice(start, length));
  232. }
  233. /// <summary>
  234. /// Indicies of all code points in the in the buffer
  235. /// that were decoded from a surrogate pair
  236. /// </summary>
  237. List<int> _surrogatePositions = new List<int>();
  238. bool _surrogatePositionsValid = false;
  239. /// <summary>
  240. /// Build an array indicies to all characters that require surrogates
  241. /// when converted to utf16.
  242. /// </summary>
  243. void BuildSurrogatePositions()
  244. {
  245. if (_surrogatePositionsValid)
  246. return;
  247. _surrogatePositionsValid = true;
  248. _surrogatePositions.Clear();
  249. unsafe
  250. {
  251. fixed (int* pBuf = this.Underlying)
  252. {
  253. int* pEnd = pBuf + this.Length;
  254. int* p = pBuf;
  255. while (p < pEnd)
  256. {
  257. if (p[0] >= 0x10000)
  258. _surrogatePositions.Add((int)(p - pBuf));
  259. p++;
  260. }
  261. }
  262. }
  263. }
  264. }
  265. }