FileNameDecoder.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Text;
  2. namespace SharpCompress.Common.Rar.Headers
  3. {
  4. /// <summary>
  5. /// This is for the crazy Rar encoding that I don't understand
  6. /// </summary>
  7. internal static class FileNameDecoder
  8. {
  9. internal static int GetChar(byte[] name, int pos)
  10. {
  11. return name[pos] & 0xff;
  12. }
  13. internal static string Decode(byte[] name, int encPos)
  14. {
  15. int decPos = 0;
  16. int flags = 0;
  17. int flagBits = 0;
  18. int low = 0;
  19. int high = 0;
  20. int highByte = GetChar(name, encPos++);
  21. StringBuilder buf = new StringBuilder();
  22. while (encPos < name.Length)
  23. {
  24. if (flagBits == 0)
  25. {
  26. flags = GetChar(name, encPos++);
  27. flagBits = 8;
  28. }
  29. switch (flags >> 6)
  30. {
  31. case 0:
  32. buf.Append((char)(GetChar(name, encPos++)));
  33. ++decPos;
  34. break;
  35. case 1:
  36. buf.Append((char)(GetChar(name, encPos++) + (highByte << 8)));
  37. ++decPos;
  38. break;
  39. case 2:
  40. low = GetChar(name, encPos);
  41. high = GetChar(name, encPos + 1);
  42. buf.Append((char)((high << 8) + low));
  43. ++decPos;
  44. encPos += 2;
  45. break;
  46. case 3:
  47. int length = GetChar(name, encPos++);
  48. if ((length & 0x80) != 0)
  49. {
  50. int correction = GetChar(name, encPos++);
  51. for (length = (length & 0x7f) + 2; length > 0 && decPos < name.Length; length--, decPos++)
  52. {
  53. low = (GetChar(name, decPos) + correction) & 0xff;
  54. buf.Append((char)((highByte << 8) + low));
  55. }
  56. }
  57. else
  58. {
  59. for (length += 2; length > 0 && decPos < name.Length; length--, decPos++)
  60. {
  61. buf.Append((char)(GetChar(name, decPos)));
  62. }
  63. }
  64. break;
  65. }
  66. flags = (flags << 2) & 0xff;
  67. flagBits -= 2;
  68. }
  69. return buf.ToString();
  70. }
  71. }
  72. }