#ifndef THIRD_PARTY_UPB_WASM_ABI_TEST_TEST_UTIL_H_
#define THIRD_PARTY_UPB_WASM_ABI_TEST_TEST_UTIL_H_

#include <cstddef>
#include <utility>
#include <vector>

#include "upb/mem/arena.h"
#include "upb/mem/arena.hpp"
#include "upb/mini_table/extension.h"
#include "upb/mini_table/extension_registry.h"
#include "upb/mini_table/message.h"
#include "wasm_abi/mini_table/container.h"
#include "wasm_abi/mini_table/container.hpp"

namespace upb::wasm {

// Creates a MiniTableContainer from a list of mini-tables and extensions for
// testing.
inline MiniTableContainer CreateMiniTableContainer(
    const std::vector<const upb_MiniTable*>& messages_list,
    const std::vector<const upb_MiniTableExtension*>& extensions_list = {}) {
  upb::Arena arena;
  upb_MiniTableContainer* container = (upb_MiniTableContainer*)upb_Arena_Malloc(
      arena.ptr(), sizeof(upb_MiniTableContainer));
  container->message_count = messages_list.size();
  container->enum_count = 0;
  container->extension_count = extensions_list.size();
  container->enums = nullptr;

  if (!messages_list.empty()) {
    upb_MiniTable** messages = (upb_MiniTable**)upb_Arena_Malloc(
        arena.ptr(), messages_list.size() * sizeof(upb_MiniTable*));
    for (size_t i = 0; i < messages_list.size(); ++i) {
      messages[i] = (upb_MiniTable*)messages_list[i];
    }
    container->messages = messages;
  } else {
    container->messages = nullptr;
  }

  if (!extensions_list.empty()) {
    upb_MiniTableExtension** extensions =
        (upb_MiniTableExtension**)upb_Arena_Malloc(
            arena.ptr(),
            extensions_list.size() * sizeof(upb_MiniTableExtension*));
    container->registry = upb_ExtensionRegistry_New(arena.ptr());
    for (size_t i = 0; i < extensions_list.size(); ++i) {
      extensions[i] = (upb_MiniTableExtension*)extensions_list[i];
      upb_ExtensionRegistry_Add(container->registry, extensions[i]);
    }
    container->extensions = extensions;
  } else {
    container->extensions = nullptr;
    container->registry = nullptr;
  }

  return MiniTableContainer(container, std::move(arena));
}

}  // namespace upb::wasm

#endif  // THIRD_PARTY_UPB_WASM_ABI_TEST_TEST_UTIL_H_
