FF8TextEncoder.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using FF8.Encoding.Tags;
  3. namespace FF8.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 Int32 GetMaxByteCount(Int32 charCount)
  13. {
  14. return charCount;
  15. }
  16. public Int32 GetByteCount(Char[] chars, Int32 index, Int32 count)
  17. {
  18. Int32 result = 0;
  19. Byte[] buff = new Byte[2];
  20. while (count > 0)
  21. {
  22. FF8TextTag tag = FF8TextTag.TryRead(chars, ref index, ref count);
  23. if (tag != null)
  24. {
  25. Int32 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 Int32 GetBytes(Char[] chars, Int32 charIndex, Int32 charCount, Byte[] bytes, Int32 byteIndex)
  38. {
  39. Int32 result = 0;
  40. while (charCount > 0)
  41. {
  42. FF8TextTag 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. }