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.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. #endif
  16. internal static int GetCharsImpl(Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> output)
  17. {
  18. if (bytes.Length == 0)
  19. return 0;
  20. unsafe
  21. {
  22. fixed (byte* bytePtr = bytes)
  23. fixed (char* charPtr = output)
  24. {
  25. return encoding.GetChars(bytePtr, bytes.Length, charPtr, output.Length);
  26. }
  27. }
  28. }
  29. internal static int GetCharCountImpl(Encoding encoding, ReadOnlySpan<byte> bytes)
  30. {
  31. if (bytes.Length == 0)
  32. return 0;
  33. unsafe
  34. {
  35. fixed (byte* bytePtr = bytes)
  36. {
  37. return encoding.GetCharCount(bytePtr, bytes.Length);
  38. }
  39. }
  40. }
  41. }