You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

EncodingExtensions.cs 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Text;
  3. namespace LLama.Extensions;
  4. internal static class EncodingExtensions
  5. {
  6. #if NETSTANDARD2_0
  7. public static int GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, Span<byte> output)
  8. {
  9. return GetBytesImpl(encoding, chars, output);
  10. }
  11. public static int GetChars(this Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> output)
  12. {
  13. return GetCharsImpl(encoding, bytes, output);
  14. }
  15. public static int GetCharCount(this Encoding encoding, ReadOnlySpan<byte> bytes)
  16. {
  17. return GetCharCountImpl(encoding, bytes);
  18. }
  19. #elif !NET6_0_OR_GREATER && !NETSTANDARD2_1_OR_GREATER
  20. #error Target framework not supported!
  21. #endif
  22. internal static int GetBytesImpl(Encoding encoding, ReadOnlySpan<char> chars, Span<byte> output)
  23. {
  24. if (chars.Length == 0)
  25. return 0;
  26. unsafe
  27. {
  28. fixed (char* charPtr = chars)
  29. fixed (byte* bytePtr = output)
  30. {
  31. return encoding.GetBytes(charPtr, chars.Length, bytePtr, output.Length);
  32. }
  33. }
  34. }
  35. internal static int GetCharsImpl(Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> output)
  36. {
  37. if (bytes.Length == 0)
  38. return 0;
  39. unsafe
  40. {
  41. fixed (byte* bytePtr = bytes)
  42. fixed (char* charPtr = output)
  43. {
  44. return encoding.GetChars(bytePtr, bytes.Length, charPtr, output.Length);
  45. }
  46. }
  47. }
  48. internal static int GetCharCountImpl(Encoding encoding, ReadOnlySpan<byte> bytes)
  49. {
  50. if (bytes.Length == 0)
  51. return 0;
  52. unsafe
  53. {
  54. fixed (byte* bytePtr = bytes)
  55. {
  56. return encoding.GetCharCount(bytePtr, bytes.Length);
  57. }
  58. }
  59. }
  60. internal static string GetStringFromSpan(this Encoding encoding, ReadOnlySpan<byte> bytes)
  61. {
  62. unsafe
  63. {
  64. fixed (byte* bytesPtr = bytes)
  65. {
  66. return encoding.GetString(bytesPtr, bytes.Length);
  67. }
  68. }
  69. }
  70. }