ConsoleEncoding.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // --------------------------------------------------
  2. // UnityInjector - ConsoleEncoding.cs
  3. // Copyright (c) Usagirei 2015 - 2015
  4. // --------------------------------------------------
  5. using System;
  6. using System.Text;
  7. namespace UnityInjector.ConsoleUtil
  8. {
  9. // --------------------------------------------------
  10. // Code ported from
  11. // https://gist.github.com/asm256/9bfb88336a1433e2328a
  12. // Which in turn was seemingly ported from
  13. // http://jonskeet.uk/csharp/ebcdic/
  14. // using only safe (managed) code
  15. // --------------------------------------------------
  16. internal partial class ConsoleEncoding : Encoding
  17. {
  18. private readonly uint _codePage;
  19. public override int CodePage => (int) _codePage;
  20. public static uint ConsoleCodePage
  21. {
  22. get { return GetConsoleOutputCP(); }
  23. set { SetConsoleOutputCP(value); }
  24. }
  25. public static uint GetActiveCodePage()
  26. {
  27. return GetACP();
  28. }
  29. private ConsoleEncoding(uint codePage)
  30. {
  31. _codePage = codePage;
  32. }
  33. public static ConsoleEncoding GetEncoding(uint codePage)
  34. {
  35. return new ConsoleEncoding(codePage);
  36. }
  37. public override int GetByteCount(char[] chars, int index, int count)
  38. {
  39. WriteCharBuffer(chars, index, count);
  40. int result = WideCharToMultiByte(_codePage, 0, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero);
  41. return result;
  42. }
  43. public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
  44. {
  45. var byteCount = GetMaxByteCount(charCount);
  46. WriteCharBuffer(chars, charIndex, charCount);
  47. ExpandByteBuffer(byteCount);
  48. int result = WideCharToMultiByte(_codePage, 0, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero);
  49. ReadByteBuffer(bytes, byteIndex, byteCount);
  50. return result;
  51. }
  52. public override int GetCharCount(byte[] bytes, int index, int count)
  53. {
  54. WriteByteBuffer(bytes, index, count);
  55. int result = MultiByteToWideChar(_codePage, 0, bytes, count, _zeroChar, 0);
  56. return result;
  57. }
  58. public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
  59. {
  60. var charCount = GetMaxCharCount(byteCount);
  61. WriteByteBuffer(bytes, byteIndex, byteCount);
  62. ExpandCharBuffer(charCount);
  63. int result = MultiByteToWideChar(_codePage, 0, bytes, byteCount, _charBuffer, charCount);
  64. ReadCharBuffer(chars, charIndex, charCount);
  65. return result;
  66. }
  67. public override int GetMaxByteCount(int charCount) => charCount * 2;
  68. public override int GetMaxCharCount(int byteCount) => byteCount;
  69. }
  70. }