RAMBundleRegistry.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #include "RAMBundleRegistry.h"
  8. #include <folly/String.h>
  9. #include <memory>
  10. namespace facebook {
  11. namespace react {
  12. constexpr uint32_t RAMBundleRegistry::MAIN_BUNDLE_ID;
  13. std::unique_ptr<RAMBundleRegistry> RAMBundleRegistry::singleBundleRegistry(
  14. std::unique_ptr<JSModulesUnbundle> mainBundle) {
  15. return std::make_unique<RAMBundleRegistry>(std::move(mainBundle));
  16. }
  17. std::unique_ptr<RAMBundleRegistry> RAMBundleRegistry::multipleBundlesRegistry(
  18. std::unique_ptr<JSModulesUnbundle> mainBundle,
  19. std::function<std::unique_ptr<JSModulesUnbundle>(std::string)> factory) {
  20. return std::make_unique<RAMBundleRegistry>(
  21. std::move(mainBundle), std::move(factory));
  22. }
  23. RAMBundleRegistry::RAMBundleRegistry(
  24. std::unique_ptr<JSModulesUnbundle> mainBundle,
  25. std::function<std::unique_ptr<JSModulesUnbundle>(std::string)> factory)
  26. : m_factory(std::move(factory)) {
  27. m_bundles.emplace(MAIN_BUNDLE_ID, std::move(mainBundle));
  28. }
  29. void RAMBundleRegistry::registerBundle(
  30. uint32_t bundleId,
  31. std::string bundlePath) {
  32. m_bundlePaths.emplace(bundleId, std::move(bundlePath));
  33. }
  34. JSModulesUnbundle::Module RAMBundleRegistry::getModule(
  35. uint32_t bundleId,
  36. uint32_t moduleId) {
  37. if (m_bundles.find(bundleId) == m_bundles.end()) {
  38. if (!m_factory) {
  39. throw std::runtime_error(
  40. "You need to register factory function in order to "
  41. "support multiple RAM bundles.");
  42. }
  43. auto bundlePath = m_bundlePaths.find(bundleId);
  44. if (bundlePath == m_bundlePaths.end()) {
  45. throw std::runtime_error(
  46. "In order to fetch RAM bundle from the registry, its file "
  47. "path needs to be registered first.");
  48. }
  49. m_bundles.emplace(bundleId, m_factory(bundlePath->second));
  50. }
  51. auto module = getBundle(bundleId)->getModule(moduleId);
  52. if (bundleId == MAIN_BUNDLE_ID) {
  53. return module;
  54. }
  55. return {
  56. folly::to<std::string>("seg-", bundleId, '_', std::move(module.name)),
  57. std::move(module.code),
  58. };
  59. }
  60. JSModulesUnbundle *RAMBundleRegistry::getBundle(uint32_t bundleId) const {
  61. return m_bundles.at(bundleId).get();
  62. }
  63. } // namespace react
  64. } // namespace facebook