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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace LLama.Extensions;
  5. internal static class EncodingExtensions
  6. {
  7. #if NETSTANDARD2_0
  8. public static int GetChars(this Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> output)
  9. {
  10. return GetCharsImpl(encoding, bytes, output);
  11. }
  12. public static int GetCharCount(this Encoding encoding, ReadOnlySpan<byte> bytes)
  13. {
  14. return GetCharCountImpl(encoding, bytes);
  15. }
  16. #endif
  17. internal static int GetCharsImpl(Encoding encoding, ReadOnlySpan<byte> bytes, Span<char> output)
  18. {
  19. if (bytes.Length == 0)
  20. return 0;
  21. unsafe
  22. {
  23. fixed (byte* bytePtr = bytes)
  24. fixed (char* charPtr = output)
  25. {
  26. return encoding.GetChars(bytePtr, bytes.Length, charPtr, output.Length);
  27. }
  28. }
  29. }
  30. internal static int GetCharCountImpl(Encoding encoding, ReadOnlySpan<byte> bytes)
  31. {
  32. unsafe
  33. {
  34. fixed (byte* bytePtr = bytes)
  35. {
  36. return encoding.GetCharCount(bytePtr, bytes.Length);
  37. }
  38. }
  39. }
  40. }