LuaFileContent.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Lua.IO;
  2. namespace Lua;
  3. public enum LuaFileContentType
  4. {
  5. Text,
  6. Binary
  7. }
  8. public readonly struct LuaFileContent
  9. {
  10. public LuaFileContentType Type => type;
  11. readonly LuaFileContentType type;
  12. readonly object referenceValue;
  13. public LuaFileContent(ReadOnlyMemory<char> memory)
  14. {
  15. type = LuaFileContentType.Text;
  16. referenceValue = memory;
  17. }
  18. public LuaFileContent(ReadOnlyMemory<byte> memory)
  19. {
  20. type = LuaFileContentType.Binary;
  21. referenceValue = new BinaryData(memory);
  22. }
  23. public LuaFileContent(IBinaryData data)
  24. {
  25. type = LuaFileContentType.Binary;
  26. referenceValue = data ?? throw new ArgumentNullException(nameof(data), "Binary data cannot be null.");
  27. }
  28. public LuaFileContent(string text)
  29. {
  30. type = LuaFileContentType.Text;
  31. referenceValue = text ?? throw new ArgumentNullException(nameof(text), "Text cannot be null.");
  32. }
  33. public ReadOnlyMemory<char> ReadText()
  34. {
  35. if (type != LuaFileContentType.Text) throw new InvalidOperationException("Cannot read text from a LuaFileContent of type Bytes.");
  36. if (referenceValue is string str) return str.AsMemory();
  37. return ((ReadOnlyMemory<char>)referenceValue);
  38. }
  39. public string ReadString()
  40. {
  41. if (type != LuaFileContentType.Text) throw new InvalidOperationException("Cannot read text from a LuaFileContent of type Bytes.");
  42. if (referenceValue is string str) return str;
  43. return ((ReadOnlyMemory<char>)referenceValue).ToString();
  44. }
  45. public ReadOnlyMemory<byte> ReadBytes()
  46. {
  47. if (type != LuaFileContentType.Binary) throw new InvalidOperationException("Cannot read bytes from a LuaFileContent of type Text.");
  48. return ((IBinaryData)referenceValue).Memory;
  49. }
  50. public LuaValue ToLuaValue()
  51. {
  52. if (type == LuaFileContentType.Binary)
  53. {
  54. return LuaValue.FromObject(referenceValue);
  55. }
  56. else
  57. {
  58. return ReadString();
  59. }
  60. }
  61. }