FileSystem.StringData.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //------------------------------------------------------------
  2. // Game Framework
  3. // Copyright © 2013-2021 loyalsoft. All rights reserved.
  4. // Homepage: http://www.game7000.com/
  5. // Feedback: http://www.game7000.com/
  6. //------------------------------------------------------------
  7. using System;
  8. using System.Runtime.InteropServices;
  9. namespace GameFramework.FileSystem
  10. {
  11. internal sealed partial class FileSystem : IFileSystem
  12. {
  13. /// <summary>
  14. /// 字符串数据。
  15. /// </summary>
  16. [StructLayout(LayoutKind.Sequential)]
  17. private struct StringData
  18. {
  19. private static readonly byte[] s_CachedBytes = new byte[byte.MaxValue + 1];
  20. private readonly byte m_Length;
  21. [MarshalAs(UnmanagedType.ByValArray, SizeConst = byte.MaxValue)]
  22. private readonly byte[] m_Bytes;
  23. public StringData(byte length, byte[] bytes)
  24. {
  25. m_Length = length;
  26. m_Bytes = bytes;
  27. }
  28. public string GetString(byte[] encryptBytes)
  29. {
  30. if (m_Length <= 0)
  31. {
  32. return null;
  33. }
  34. Array.Copy(m_Bytes, 0, s_CachedBytes, 0, m_Length);
  35. Utility.Encryption.GetSelfXorBytes(s_CachedBytes, 0, m_Length, encryptBytes);
  36. return Utility.Converter.GetString(s_CachedBytes, 0, m_Length);
  37. }
  38. public StringData SetString(string value, byte[] encryptBytes)
  39. {
  40. if (string.IsNullOrEmpty(value))
  41. {
  42. return Clear();
  43. }
  44. int length = Utility.Converter.GetBytes(value, s_CachedBytes);
  45. if (length > byte.MaxValue)
  46. {
  47. throw new GameFrameworkException(Utility.Text.Format("String '{0}' is too long.", value));
  48. }
  49. Utility.Encryption.GetSelfXorBytes(s_CachedBytes, encryptBytes);
  50. Array.Copy(s_CachedBytes, 0, m_Bytes, 0, length);
  51. return new StringData((byte)length, m_Bytes);
  52. }
  53. public StringData Clear()
  54. {
  55. return new StringData(0, m_Bytes);
  56. }
  57. }
  58. }
  59. }