config_resource.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2012-2025 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: MIT
  4. */
  5. #include "config.h"
  6. #include "core/filesystem/file.h"
  7. #include "core/filesystem/filesystem.h"
  8. #include "core/json/json_object.inl"
  9. #include "core/json/sjson.h"
  10. #include "core/memory/allocator.h"
  11. #include "core/memory/temp_allocator.inl"
  12. #include "core/strings/dynamic_string.inl"
  13. #include "resource/compile_options.inl"
  14. #include "resource/config_resource.h"
  15. #include "resource/types.h"
  16. namespace crown
  17. {
  18. namespace config_resource_internal
  19. {
  20. void *load(File &file, Allocator &a)
  21. {
  22. const u32 size = file.size();
  23. char *res = (char *)a.allocate(size + 1);
  24. file.read(res, size);
  25. res[size] = '\0';
  26. return res;
  27. }
  28. void unload(Allocator &a, void *resource)
  29. {
  30. a.deallocate(resource);
  31. }
  32. } // namespace config_resource_internal
  33. #if CROWN_CAN_COMPILE
  34. namespace config_resource_internal
  35. {
  36. s32 compile(CompileOptions &opts)
  37. {
  38. Buffer buf = opts.read();
  39. TempAllocator1024 ta;
  40. JsonObject boot(ta);
  41. RETURN_IF_ERROR(sjson::parse(boot, buf), opts);
  42. const char *boot_script_json = boot["boot_script"];
  43. const char *boot_package_json = boot["boot_package"];
  44. DATA_COMPILER_ASSERT(boot_script_json != NULL, opts, "'boot_script' must be specified.");
  45. DATA_COMPILER_ASSERT(boot_package_json != NULL, opts, "'boot_package' must be specified.");
  46. DynamicString boot_script(ta);
  47. DynamicString boot_package(ta);
  48. RETURN_IF_ERROR(sjson::parse_string(boot_script, boot_script_json), opts);
  49. RETURN_IF_ERROR(sjson::parse_string(boot_package, boot_package_json), opts);
  50. DATA_COMPILER_ASSERT_RESOURCE_EXISTS("lua", boot_script.c_str(), opts);
  51. DATA_COMPILER_ASSERT_RESOURCE_EXISTS("package", boot_package.c_str(), opts);
  52. if (opts._bundle) {
  53. TempAllocator256 ta;
  54. DynamicString dest(ta);
  55. destination_path(dest, opts._resource_id);
  56. File *config = opts._data_filesystem.open(dest.c_str(), FileOpenMode::READ);
  57. file::copy(opts._file, *config, config->size());
  58. opts._data_filesystem.close(*config);
  59. } else {
  60. opts.write(buf);
  61. }
  62. return 0;
  63. }
  64. } // namespace config_resource_internal
  65. #endif // if CROWN_CAN_COMPILE
  66. } // namespace crown