FF8TextEncoder.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using OpenVIII.Encoding.Tags;
  3. namespace OpenVIII.Encoding
  4. {
  5. public sealed class FF8TextEncoder
  6. {
  7. private readonly FF8TextEncodingCodepage _codepage;
  8. public FF8TextEncoder(FF8TextEncodingCodepage codepage)
  9. {
  10. _codepage = codepage ?? throw new ArgumentNullException(nameof(codepage));
  11. }
  12. public int GetMaxByteCount(int charCount)
  13. {
  14. return charCount;
  15. }
  16. public int GetByteCount(char[] chars, int index, int count)
  17. {
  18. var result = 0;
  19. var buff = new byte[2];
  20. while (count > 0)
  21. {
  22. var tag = FF8TextTag.TryRead(chars, ref index, ref count);
  23. if (tag != null)
  24. {
  25. var offset = 0;
  26. result += tag.Write(buff, ref offset);
  27. }
  28. else if (FF8TextComment.TryRead(chars, ref index, ref count) == null)
  29. {
  30. count--;
  31. result++;
  32. index++;
  33. }
  34. }
  35. return result;
  36. }
  37. public int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
  38. {
  39. var result = 0;
  40. while (charCount > 0)
  41. {
  42. var tag = FF8TextTag.TryRead(chars, ref charIndex, ref charCount);
  43. if (tag != null)
  44. {
  45. result += tag.Write(bytes, ref byteIndex);
  46. }
  47. else if (FF8TextComment.TryRead(chars, ref charIndex, ref charCount) == null)
  48. {
  49. bytes[byteIndex++] = _codepage[chars[charIndex++]];
  50. charCount--;
  51. result++;
  52. }
  53. }
  54. return result;
  55. }
  56. }
  57. }