Utf32Utils.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. /// Miscellaneous utility functions for working with UTF-32 data.
  25. /// </summary>
  26. public static class Utf32Utils
  27. {
  28. /// <summary>
  29. /// Convert a slice of UTF-32 integer code points to a string
  30. /// </summary>
  31. /// <param name="buffer">The code points to convert</param>
  32. /// <returns>A string</returns>
  33. public static string FromUtf32(Slice<int> buffer)
  34. {
  35. unsafe
  36. {
  37. fixed (int* p = buffer.Underlying)
  38. {
  39. var pBuf = p + buffer.Start;
  40. return new string((sbyte*)pBuf, 0, buffer.Length * sizeof(int), Encoding.UTF32);
  41. }
  42. }
  43. }
  44. /// <summary>
  45. /// Converts a string to an integer array of UTF-32 code points
  46. /// </summary>
  47. /// <param name="str">The string to convert</param>
  48. /// <returns>The converted code points</returns>
  49. public static int[] ToUtf32(string str)
  50. {
  51. unsafe
  52. {
  53. fixed (char* pstr = str)
  54. {
  55. // Get required byte count
  56. int byteCount = Encoding.UTF32.GetByteCount(pstr, str.Length);
  57. System.Diagnostics.Debug.Assert((byteCount % 4) == 0);
  58. // Allocate buffer
  59. int[] utf32 = new int[byteCount / sizeof(int)];
  60. fixed (int* putf32 = utf32)
  61. {
  62. // Convert
  63. Encoding.UTF32.GetBytes(pstr, str.Length, (byte*)putf32, byteCount);
  64. // Done
  65. return utf32;
  66. }
  67. }
  68. }
  69. }
  70. }
  71. }