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 1.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 GetChars(this Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> output)
  8. {
  9. return GetCharsImpl(encoding, bytes, output);
  10. }
  11. public static int GetCharCount(this Encoding encoding, ReadOnlySpan<byte> bytes)
  12. {
  13. return GetCharCountImpl(encoding, bytes);
  14. }
  15. #elif !NET6_0_OR_GREATER && !NETSTANDARD2_1_OR_GREATER
  16. #error Target framework not supported!
  17. #endif
  18. internal static int GetCharsImpl(Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> output)
  19. {
  20. if (bytes.Length == 0)
  21. return 0;
  22. unsafe
  23. {
  24. fixed (byte* bytePtr = bytes)
  25. fixed (char* charPtr = output)
  26. {
  27. return encoding.GetChars(bytePtr, bytes.Length, charPtr, output.Length);
  28. }
  29. }
  30. }
  31. internal static int GetCharCountImpl(Encoding encoding, ReadOnlySpan<byte> bytes)
  32. {
  33. if (bytes.Length == 0)
  34. return 0;
  35. unsafe
  36. {
  37. fixed (byte* bytePtr = bytes)
  38. {
  39. return encoding.GetCharCount(bytePtr, bytes.Length);
  40. }
  41. }
  42. }
  43. }