<commit_before>/*
 * Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
 * All rights reserved.
 */
#include "gen.h"

#include "common.h"

extern "C"
{
  #include "lauxlib.h"
}

#define RC_TERRAIN_MODS_REGISTRY_NAME "Redcrane.Gen.Terrain_Mods"
#define RC_GEN_GRID_METATABLE_NAME "Redcrane.Gen.Grid.Metatable"

namespace game { namespace luaint
{
  void Terrain_Gen_Config::add_option(std::string const& name,
                                      double def) noexcept
  {
    Option opt;
    opt.name = name;
    opt.type = Option_Type::Double;
    opt.value.d_num = def;
    options_.push_back(opt);
  }

  void push_registry_table(lua_State* L, char const* const name) noexcept
  {
    lua_getfield(L, LUA_REGISTRYINDEX, name);
    if(lua_isnil(L, -1))
    {
      // Remove the nil
      lua_remove(L, -1);
      // Add a new table in it's place
      lua_newtable(L);

      // Add it to the registry
      lua_pushvalue(L, -1);
      lua_setfield(L, LUA_REGISTRYINDEX, name);
    }

    // We are left with the table in registry[name] on the top of the stack.
  }

  int unregister_terrain_algorithm(lua_State* L)
  {
    // Get our bound parameters
    auto* mod_list_ptr = lua_touserdata(L, lua_upvalueindex(1));
    auto& mod_list = *static_cast<Terrain_Gen_Mod_Vector*>(mod_list_ptr);

    auto* mod_ptr = lua_touserdata(L, lua_upvalueindex(2));
    auto& mod_ref = *static_cast<Terrain_Gen_Mod*>(mod_ptr);

    // Remove all the mods with this index, there should only be one.
    using std::begin; using std::end;
    auto new_end = std::remove_if(begin(mod_list), end(mod_list),
    [&mod_ref](auto const& mod)
    {
      return mod.table_index == mod_ref.table_index;
    });

    mod_list.erase(new_end, end(mod_list));

    return 0;
  }

  int register_terrain_algorithm(lua_State* L)
  {
    // Parameters
    // - Function
    // - Configuration object

    // Load the list of mods
    push_registry_table(L, RC_TERRAIN_MODS_REGISTRY_NAME);

    // Our list of mods is at the top of the stack
    auto table_index = lua_objlen(L, -1) + 1;

    // Set the value at that index to the function, the configuration object is
    // used to construct a C++ object.
    lua_pushvalue(L, 1);
    lua_rawseti(L, 3, table_index);

    auto* mod_list_ptr = lua_touserdata(L, lua_upvalueindex(1));
    auto& mod_list = *static_cast<Terrain_Gen_Mod_Vector*>(mod_list_ptr);

    Terrain_Gen_Config config;

    // Traverse the configuration object
    lua_pushnil(L);
    while(lua_next(L, 2) != 0)
    {
      if(lua_type(L, -2) == LUA_TSTRING && lua_type(L, -1) == LUA_TNUMBER)
      {
        auto key = lua_tostring(L, -2);
        auto value = lua_tonumber(L, -1);

        config.add_option(key, value);
      }

      // Pop the value, as the remaining key will then be used to find the next
      // one.
      lua_pop(L, 1);
    }

    mod_list.push_back({table_index, config});

    // Build the meta-table that includes an unregister function, for example

    Table ret;

    Function unregister_func{&unregister_terrain_algorithm,
                             {Userdata{true, &mod_list},
                              Userdata{true, &mod_list.back()}}};

    ret.values.emplace_back(String{"unregister"}, std::move(unregister_func));

    push_value(L, ret);
    return 1;
  }

  Table terrain_preload_table(Terrain_Gen_Mod_Vector& mod_v) noexcept
  {
    Table ret;

    ret.values.emplace_back(String{"register_terrain_algorithm"},
                            Function{&register_terrain_algorithm,
                                     {Userdata{true, &mod_v}}});

    return ret;
  }

  int grid_set_tile(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    char const* const opts[] =
    {
      "land",
      "water",
      NULL
    };

    auto vec = Vec<int>(x,y);

    int ind = luaL_checkoption(L, 3, NULL, opts);
    if(ind == 0)
    {
      grid.at(vec).type = gen::Cell_Type::Land;
    }
    else if(ind == 1)
    {
      grid.at(vec).type = gen::Cell_Type::Water;
    }

    return 0;
  }

  int grid_set_contents(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    auto vec = Vec<int>(x,y);

    if(grid.at(vec).type != gen::Cell_Type::Land)
    {
      return 0;
    }

    char const* const opts[] =
    {
      "none",
      "tree",
      NULL
    };
    int ind = luaL_checkoption(L, 3, NULL, opts);
    if(ind == 0)
    {
      grid.at(vec).contents = gen::Cell_Contents::None;
    }
    else if(ind == 1)
    {
      grid.at(vec).contents = gen::Cell_Contents::Tree;
    }

    return 0;
  }

  int grid_get_tile(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    auto vec = Vec<int>(x,y);

    switch(grid.at(vec).type)
    {
    case gen::Cell_Type::Land:
      lua_pushstring(L, "land");
      break;
    case gen::Cell_Type::Water:
      lua_pushstring(L, "water");
      break;
    default:
      lua_pushstring(L, "unknown");
      break;
    }

    return 1;
  }
  int grid_get_contents(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    auto vec = Vec<int>(x,y);

    auto const& grid_cell = grid.at(vec);
    if(grid_cell.type == gen::Cell_Type::Land)
    {
      switch(grid_cell.contents)
      {
      case gen::Cell_Contents::None:
        lua_pushstring(L, "none");
        break;
      case gen::Cell_Contents::Tree:
        lua_pushstring(L, "tree");
        break;
      default:
        lua_pushstring(L, "unknown");
        break;
      }
    }
    else
    {
      lua_pushstring(L, "none");
    }

    return 1;
  }

  void push_grid(lua_State* L, gen::Grid_Map& grid) noexcept
  {
    // New user data.
    auto ud = (gen::Grid_Map**) lua_newuserdata(L, sizeof(gen::Grid_Map**));
    *ud = &grid;

    // Set up the metatable.
    if(luaL_newmetatable(L, RC_GEN_GRID_METATABLE_NAME))
    {
      // Populate it, because it didn't exist before.

      // New table representing '__index'
      lua_newtable(L);

      // function(grid, pos, str type)
      set_field(L, "set_tile", Function{grid_set_tile});
      // function(grid, pos, str type)
      set_field(L, "set_contents", Function{grid_set_contents});
      // function(grid, pos)
      set_field(L, "get_tile", Function{grid_get_tile});
      // function(grid, pos)
      set_field(L, "get_contents", Function{grid_get_contents});

      lua_setfield(L, -2, "__index");
    }

    lua_setmetatable(L, -2);

    // We are left with the userdata at the top of the stack.
  }

  void run_mods(lua_State* L, Terrain_Gen_Mod_Vector const& ml,
                gen::Grid_Map& map)
  {
    // First push the grid map userdata once, we can repush it on top when it's
    // time to pass it in as a parameter.
    push_grid(L, map);

    // Push the function table in the registry

    lua_getfield(L, LUA_REGISTRYINDEX, RC_TERRAIN_MODS_REGISTRY_NAME);
    for(size_t i = 0; i < ml.size(); i++)
    {
      auto const& mod = ml[i];

      // Push the function
      lua_rawgeti(L, -1, mod.table_index);

      // Push the grid
      lua_pushvalue(L, -3);

      // Push the configuration object
      //push_config(L, mod.config);
      lua_pushstring(L, "Way to fucking go Luke");

      int err = lua_pcall(L, 2, 0, 0);
      if(handle_err(L, err, "calling mod #%", i)) return;

      // That's it
    }

    // Get rid of the boilerpot that we added
    lua_pop(L, 2);
  }
} }
<commit_msg>Fix warnings in not in initializing Function upvalues<commit_after>/*
 * Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
 * All rights reserved.
 */
#include "gen.h"

#include "common.h"

extern "C"
{
  #include "lauxlib.h"
}

#define RC_TERRAIN_MODS_REGISTRY_NAME "Redcrane.Gen.Terrain_Mods"
#define RC_GEN_GRID_METATABLE_NAME "Redcrane.Gen.Grid.Metatable"

namespace game { namespace luaint
{
  void Terrain_Gen_Config::add_option(std::string const& name,
                                      double def) noexcept
  {
    Option opt;
    opt.name = name;
    opt.type = Option_Type::Double;
    opt.value.d_num = def;
    options_.push_back(opt);
  }

  void push_registry_table(lua_State* L, char const* const name) noexcept
  {
    lua_getfield(L, LUA_REGISTRYINDEX, name);
    if(lua_isnil(L, -1))
    {
      // Remove the nil
      lua_remove(L, -1);
      // Add a new table in it's place
      lua_newtable(L);

      // Add it to the registry
      lua_pushvalue(L, -1);
      lua_setfield(L, LUA_REGISTRYINDEX, name);
    }

    // We are left with the table in registry[name] on the top of the stack.
  }

  int unregister_terrain_algorithm(lua_State* L)
  {
    // Get our bound parameters
    auto* mod_list_ptr = lua_touserdata(L, lua_upvalueindex(1));
    auto& mod_list = *static_cast<Terrain_Gen_Mod_Vector*>(mod_list_ptr);

    auto* mod_ptr = lua_touserdata(L, lua_upvalueindex(2));
    auto& mod_ref = *static_cast<Terrain_Gen_Mod*>(mod_ptr);

    // Remove all the mods with this index, there should only be one.
    using std::begin; using std::end;
    auto new_end = std::remove_if(begin(mod_list), end(mod_list),
    [&mod_ref](auto const& mod)
    {
      return mod.table_index == mod_ref.table_index;
    });

    mod_list.erase(new_end, end(mod_list));

    return 0;
  }

  int register_terrain_algorithm(lua_State* L)
  {
    // Parameters
    // - Function
    // - Configuration object

    // Load the list of mods
    push_registry_table(L, RC_TERRAIN_MODS_REGISTRY_NAME);

    // Our list of mods is at the top of the stack
    auto table_index = lua_objlen(L, -1) + 1;

    // Set the value at that index to the function, the configuration object is
    // used to construct a C++ object.
    lua_pushvalue(L, 1);
    lua_rawseti(L, 3, table_index);

    auto* mod_list_ptr = lua_touserdata(L, lua_upvalueindex(1));
    auto& mod_list = *static_cast<Terrain_Gen_Mod_Vector*>(mod_list_ptr);

    Terrain_Gen_Config config;

    // Traverse the configuration object
    lua_pushnil(L);
    while(lua_next(L, 2) != 0)
    {
      if(lua_type(L, -2) == LUA_TSTRING && lua_type(L, -1) == LUA_TNUMBER)
      {
        auto key = lua_tostring(L, -2);
        auto value = lua_tonumber(L, -1);

        config.add_option(key, value);
      }

      // Pop the value, as the remaining key will then be used to find the next
      // one.
      lua_pop(L, 1);
    }

    mod_list.push_back({table_index, config});

    // Build the meta-table that includes an unregister function, for example

    Table ret;

    Function unregister_func{&unregister_terrain_algorithm,
                             {Userdata{true, &mod_list},
                              Userdata{true, &mod_list.back()}}};

    ret.values.emplace_back(String{"unregister"}, std::move(unregister_func));

    push_value(L, ret);
    return 1;
  }

  Table terrain_preload_table(Terrain_Gen_Mod_Vector& mod_v) noexcept
  {
    Table ret;

    ret.values.emplace_back(String{"register_terrain_algorithm"},
                            Function{&register_terrain_algorithm,
                                     {Userdata{true, &mod_v}}});

    return ret;
  }

  int grid_set_tile(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    char const* const opts[] =
    {
      "land",
      "water",
      NULL
    };

    auto vec = Vec<int>(x,y);

    int ind = luaL_checkoption(L, 3, NULL, opts);
    if(ind == 0)
    {
      grid.at(vec).type = gen::Cell_Type::Land;
    }
    else if(ind == 1)
    {
      grid.at(vec).type = gen::Cell_Type::Water;
    }

    return 0;
  }

  int grid_set_contents(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    auto vec = Vec<int>(x,y);

    if(grid.at(vec).type != gen::Cell_Type::Land)
    {
      return 0;
    }

    char const* const opts[] =
    {
      "none",
      "tree",
      NULL
    };
    int ind = luaL_checkoption(L, 3, NULL, opts);
    if(ind == 0)
    {
      grid.at(vec).contents = gen::Cell_Contents::None;
    }
    else if(ind == 1)
    {
      grid.at(vec).contents = gen::Cell_Contents::Tree;
    }

    return 0;
  }

  int grid_get_tile(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    auto vec = Vec<int>(x,y);

    switch(grid.at(vec).type)
    {
    case gen::Cell_Type::Land:
      lua_pushstring(L, "land");
      break;
    case gen::Cell_Type::Water:
      lua_pushstring(L, "water");
      break;
    default:
      lua_pushstring(L, "unknown");
      break;
    }

    return 1;
  }
  int grid_get_contents(lua_State* L)
  {
    auto& grid = **(gen::Grid_Map**)
      luaL_checkudata(L, 1, RC_GEN_GRID_METATABLE_NAME);

    auto pos = get_table(L, 2);

    auto x = pos.get_number("x");
    auto y = pos.get_number("y");

    auto vec = Vec<int>(x,y);

    auto const& grid_cell = grid.at(vec);
    if(grid_cell.type == gen::Cell_Type::Land)
    {
      switch(grid_cell.contents)
      {
      case gen::Cell_Contents::None:
        lua_pushstring(L, "none");
        break;
      case gen::Cell_Contents::Tree:
        lua_pushstring(L, "tree");
        break;
      default:
        lua_pushstring(L, "unknown");
        break;
      }
    }
    else
    {
      lua_pushstring(L, "none");
    }

    return 1;
  }

  void push_grid(lua_State* L, gen::Grid_Map& grid) noexcept
  {
    // New user data.
    auto ud = (gen::Grid_Map**) lua_newuserdata(L, sizeof(gen::Grid_Map**));
    *ud = &grid;

    // Set up the metatable.
    if(luaL_newmetatable(L, RC_GEN_GRID_METATABLE_NAME))
    {
      // Populate it, because it didn't exist before.

      // New table representing '__index'
      lua_newtable(L);

      // function(grid, pos, str type)
      set_field(L, "set_tile", Function{grid_set_tile, {}});
      // function(grid, pos, str type)
      set_field(L, "set_contents", Function{grid_set_contents, {}});
      // function(grid, pos)
      set_field(L, "get_tile", Function{grid_get_tile, {}});
      // function(grid, pos)
      set_field(L, "get_contents", Function{grid_get_contents, {}});

      lua_setfield(L, -2, "__index");
    }

    lua_setmetatable(L, -2);

    // We are left with the userdata at the top of the stack.
  }

  void run_mods(lua_State* L, Terrain_Gen_Mod_Vector const& ml,
                gen::Grid_Map& map)
  {
    // First push the grid map userdata once, we can repush it on top when it's
    // time to pass it in as a parameter.
    push_grid(L, map);

    // Push the function table in the registry

    lua_getfield(L, LUA_REGISTRYINDEX, RC_TERRAIN_MODS_REGISTRY_NAME);
    for(size_t i = 0; i < ml.size(); i++)
    {
      auto const& mod = ml[i];

      // Push the function
      lua_rawgeti(L, -1, mod.table_index);

      // Push the grid
      lua_pushvalue(L, -3);

      // Push the configuration object
      //push_config(L, mod.config);
      lua_pushstring(L, "Way to fucking go Luke");

      int err = lua_pcall(L, 2, 0, 0);
      if(handle_err(L, err, "calling mod #%", i)) return;

      // That's it
    }

    // Get rid of the boilerpot that we added
    lua_pop(L, 2);
  }
} }
<|endoftext|>


<commit_before>//
//  src/macho/file.cc
//  tbd
//
//  Created by inoahdev on 4/24/17.
//  Copyright © 2017 inoahdev. All rights reserved.
//

#include <mach-o/swap.h>

#include <cerrno>
#include <cstdlib>

#include <fcntl.h>
#include <unistd.h>

#include "file.h"

namespace macho {
    file::file(const std::string &path)
    : file_(fopen(path.data(), "r")) {
        auto &file = file_;
        if (!file) {
            fprintf(stderr, "Failed to open mach-o file at path (%s), failing with error (%s)\n", path.data(), strerror(errno));
            exit(1);
        }

        this->validate();
    }

    file::~file() {
        fclose(file_);
    }

    bool file::is_valid_file(const std::string &path) noexcept {
        const auto descriptor = open(path.data(), O_RDONLY);
        if (descriptor == -1) {
            return false;
        }

        uint32_t magic;
        read(descriptor, &magic, sizeof(uint32_t));

        auto result = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64 || magic == FAT_MAGIC || magic == FAT_CIGAM || magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;

        close(descriptor);
        return result;
    }

    bool file::has_library_command(int descriptor, const struct mach_header &header) noexcept {
        auto should_swap = false;

        const auto header_magic_is_64_bit = header.magic == MH_MAGIC_64 || header.magic == MH_CIGAM_64;
        if (header_magic_is_64_bit) {
            lseek(descriptor, sizeof(uint32_t), SEEK_CUR);
        } else {
            const auto header_magic_is_32_bit = header.magic == MH_MAGIC || header.magic == MH_CIGAM;
            if (!header_magic_is_32_bit) {
                return false;
            }
        }

        const auto header_magic_is_big_endian = header.magic == MH_CIGAM_64 || header.magic == MH_CIGAM;
        if (header_magic_is_big_endian) {
            should_swap = true;
        }

        const auto load_commands = new char[header.sizeofcmds];
        read(descriptor, load_commands, header.sizeofcmds);

        auto index = 0;
        auto size_left = header.sizeofcmds;

        const auto &ncmds = header.ncmds;
        for (auto i = 0; i < ncmds; i++) {
            const auto load_cmd = (struct load_command *)&load_commands[index];
            if (should_swap) {
                swap_load_command(load_cmd, NX_LittleEndian);
            }

            auto cmdsize = load_cmd->cmdsize;

            const auto cmdsize_is_too_small = cmdsize < sizeof(struct load_command);
            const auto cmdsize_is_larger_than_load_command_space = cmdsize > size_left;
            const auto cmdsize_takes_up_rest_of_load_command_space = (cmdsize == size_left && i != ncmds - 1);

            if (cmdsize_is_too_small || cmdsize_is_larger_than_load_command_space || cmdsize_takes_up_rest_of_load_command_space) {
                delete[] load_commands;
                return false;
            }

            if (load_cmd->cmd == LC_ID_DYLIB) {
                delete[] load_commands;
                return true;
            }

            index += cmdsize;
        }

        delete[] load_commands;
        return false;
    };

    bool file::is_valid_library(const std::string &path) noexcept {
        const auto descriptor = open(path.data(), O_RDONLY);
        if (descriptor == -1) {
            return false;
        }

        uint32_t magic;
        read(descriptor, &magic, sizeof(uint32_t));

        const auto magic_is_fat_64 = magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;
        if (magic_is_fat_64) {
            uint32_t nfat_arch;
            read(descriptor, &nfat_arch, sizeof(uint32_t));

            const auto magic_is_64_bit = magic == FAT_CIGAM_64;
            if (magic_is_64_bit) {
                swap_value(nfat_arch);
            }

            auto architectures = new struct fat_arch_64[nfat_arch];
            read(descriptor, architectures, sizeof(struct fat_arch_64) * nfat_arch);

            if (magic_is_64_bit) {
                swap_fat_arch_64(architectures, nfat_arch, NX_LittleEndian);
            }

            for (auto i = 0; i < nfat_arch; i++) {
                const auto &architecture = architectures[i];
                struct mach_header header;

                lseek(descriptor, architecture.offset, SEEK_SET);
                read(descriptor, &header, sizeof(struct mach_header));

                if (!has_library_command(descriptor, header)) {
                    close(descriptor);
                    return false;
                }
            }

            delete[] architectures;
        } else {
            const auto magic_is_fat_32 = magic == FAT_MAGIC || magic == FAT_CIGAM;
            if (magic_is_fat_32) {
                uint32_t nfat_arch;
                read(descriptor, &nfat_arch, sizeof(uint32_t));

                swap_value(nfat_arch);

                auto architectures = new struct fat_arch[nfat_arch];
                read(descriptor, architectures, sizeof(struct fat_arch) * nfat_arch);

                const auto magic_is_big_endian = magic == FAT_CIGAM;
                if (magic_is_big_endian) {
                    swap_fat_arch(architectures, nfat_arch, NX_LittleEndian);
                }

                for (auto i = 0; i < nfat_arch; i++) {
                    const auto &architecture = architectures[i];
                    struct mach_header header;

                    lseek(descriptor, architecture.offset, SEEK_SET);
                    read(descriptor, &header, sizeof(struct mach_header));

                    if (!has_library_command(descriptor, header)) {
                        close(descriptor);
                        return false;
                    }
                }

                delete[] architectures;
            } else {
                const auto magic_is_thin = magic == MH_MAGIC_64 || magic == MH_CIGAM_64 || magic == MH_MAGIC || magic == MH_CIGAM;
                if (magic_is_thin) {
                    struct mach_header header;
                    header.magic = magic;

                    read(descriptor, &header.cputype, sizeof(struct mach_header) - sizeof(uint32_t));
                    if (!has_library_command(descriptor, header)) {
                        close(descriptor);
                        return false;
                    }
                } else {
                    close(descriptor);
                    return false;
                }
            }
        }

        close(descriptor);
        return true;
    }

    void file::validate() {
        auto &containers = containers_;
        auto &file = file_;
        auto &magic = magic_;

        fread(&magic, sizeof(uint32_t), 1, file);

        const auto magic_is_fat = magic == FAT_MAGIC || magic == FAT_CIGAM || magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;
        if (magic_is_fat) {
            uint32_t nfat_arch;
            fread(&nfat_arch, sizeof(uint32_t), 1, file);

            if (!nfat_arch) {
                fprintf(stderr, "Mach-o file has 0 architectures");
                exit(1);
            }

            auto should_swap = magic == FAT_CIGAM || magic == FAT_CIGAM_64;
            if (should_swap) {
                swap_value(nfat_arch);
            }

            containers.reserve(nfat_arch);

            const auto magic_is_fat_64 = magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;
            if (magic_is_fat_64) {
                const auto architectures = new struct fat_arch_64[nfat_arch];
                fread(architectures, sizeof(struct fat_arch_64) * nfat_arch, 1, file);

                if (should_swap) {
                    swap_fat_arch_64(architectures, nfat_arch, NX_LittleEndian);
                }

                for (auto i = 0; i < nfat_arch; i++) {
                    const auto &architecture = architectures[i];
                    containers.emplace_back(file, architecture.offset, architecture.size);
                }

                delete[] architectures;
            } else {
                const auto architectures = new struct fat_arch[nfat_arch];
                fread(architectures, sizeof(struct fat_arch) * nfat_arch, 1, file);

                if (should_swap) {
                    swap_fat_arch(architectures, nfat_arch, NX_LittleEndian);
                }

                for (auto i = 0; i < nfat_arch; i++) {
                    const auto &architecture = architectures[i];
                    containers.emplace_back(file, architecture.offset, architecture.size);
                }

                delete[] architectures;
            }
        } else {
            const auto magic_is_thin = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
            if (magic_is_thin) {
                containers.emplace_back(file, 0);
            } else {
                fputs("Mach-o file is invalid, does not have a valid magic-number", stderr);
                exit(1);
            }
        }
    }
}
<commit_msg>Use more variables in mach-o/file.cc<commit_after>//
//  src/macho/file.cc
//  tbd
//
//  Created by inoahdev on 4/24/17.
//  Copyright © 2017 inoahdev. All rights reserved.
//

#include <mach-o/swap.h>

#include <cerrno>
#include <cstdlib>

#include <fcntl.h>
#include <unistd.h>

#include "file.h"

namespace macho {
    file::file(const std::string &path)
    : file_(fopen(path.data(), "r")) {
        auto &file = file_;
        if (!file) {
            fprintf(stderr, "Failed to open mach-o file at path (%s), failing with error (%s)\n", path.data(), strerror(errno));
            exit(1);
        }

        this->validate();
    }

    file::~file() {
        fclose(file_);
    }

    bool file::is_valid_file(const std::string &path) noexcept {
        const auto descriptor = open(path.data(), O_RDONLY);
        if (descriptor == -1) {
            return false;
        }

        uint32_t magic;
        read(descriptor, &magic, sizeof(uint32_t));

        auto result = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64 || magic == FAT_MAGIC || magic == FAT_CIGAM || magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;

        close(descriptor);
        return result;
    }

    bool file::has_library_command(int descriptor, const struct mach_header &header) noexcept {
        auto should_swap = false;

        const auto header_magic_is_64_bit = header.magic == MH_MAGIC_64 || header.magic == MH_CIGAM_64;
        if (header_magic_is_64_bit) {
            lseek(descriptor, sizeof(uint32_t), SEEK_CUR);
        } else {
            const auto header_magic_is_32_bit = header.magic == MH_MAGIC || header.magic == MH_CIGAM;
            if (!header_magic_is_32_bit) {
                return false;
            }
        }

        const auto header_magic_is_big_endian = header.magic == MH_CIGAM_64 || header.magic == MH_CIGAM;
        if (header_magic_is_big_endian) {
            should_swap = true;
        }

        const auto load_commands = new char[header.sizeofcmds];
        read(descriptor, load_commands, header.sizeofcmds);

        auto index = 0;
        auto size_left = header.sizeofcmds;

        const auto &ncmds = header.ncmds;
        for (auto i = 0; i < ncmds; i++) {
            const auto load_cmd = (struct load_command *)&load_commands[index];
            if (should_swap) {
                swap_load_command(load_cmd, NX_LittleEndian);
            }

            auto cmdsize = load_cmd->cmdsize;

            const auto cmdsize_is_too_small = cmdsize < sizeof(struct load_command);
            const auto cmdsize_is_larger_than_load_command_space = cmdsize > size_left;
            const auto cmdsize_takes_up_rest_of_load_command_space = (cmdsize == size_left && i != ncmds - 1);

            if (cmdsize_is_too_small || cmdsize_is_larger_than_load_command_space || cmdsize_takes_up_rest_of_load_command_space) {
                delete[] load_commands;
                return false;
            }

            if (load_cmd->cmd == LC_ID_DYLIB) {
                delete[] load_commands;
                return true;
            }

            index += cmdsize;
        }

        delete[] load_commands;
        return false;
    };

    bool file::is_valid_library(const std::string &path) noexcept {
        const auto descriptor = open(path.data(), O_RDONLY);
        if (descriptor == -1) {
            return false;
        }

        uint32_t magic;
        read(descriptor, &magic, sizeof(uint32_t));

        const auto magic_is_fat_64 = magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;
        if (magic_is_fat_64) {
            uint32_t nfat_arch;
            read(descriptor, &nfat_arch, sizeof(uint32_t));

            const auto magic_is_64_bit = magic == FAT_CIGAM_64;
            if (magic_is_64_bit) {
                swap_value(nfat_arch);
            }

            const auto architectures = new struct fat_arch_64[nfat_arch];
            const auto architectures_size = sizeof(struct fat_arch_64) * nfat_arch;

            read(descriptor, architectures, architectures_size);

            if (magic_is_64_bit) {
                swap_fat_arch_64(architectures, nfat_arch, NX_LittleEndian);
            }

            for (auto i = 0; i < nfat_arch; i++) {
                const auto &architecture = architectures[i];
                struct mach_header header;

                lseek(descriptor, architecture.offset, SEEK_SET);
                read(descriptor, &header, sizeof(struct mach_header));

                if (!has_library_command(descriptor, header)) {
                    close(descriptor);
                    return false;
                }
            }

            delete[] architectures;
        } else {
            const auto magic_is_fat_32 = magic == FAT_MAGIC || magic == FAT_CIGAM;
            if (magic_is_fat_32) {
                uint32_t nfat_arch;
                read(descriptor, &nfat_arch, sizeof(uint32_t));

                swap_value(nfat_arch);

                const auto architectures = new struct fat_arch[nfat_arch];
                const auto architectures_size = sizeof(struct fat_arch) * nfat_arch;

                read(descriptor, architectures, architectures_size);

                const auto magic_is_big_endian = magic == FAT_CIGAM;
                if (magic_is_big_endian) {
                    swap_fat_arch(architectures, nfat_arch, NX_LittleEndian);
                }

                for (auto i = 0; i < nfat_arch; i++) {
                    const auto &architecture = architectures[i];
                    struct mach_header header;

                    lseek(descriptor, architecture.offset, SEEK_SET);
                    read(descriptor, &header, sizeof(struct mach_header));

                    if (!has_library_command(descriptor, header)) {
                        close(descriptor);
                        return false;
                    }
                }

                delete[] architectures;
            } else {
                const auto magic_is_thin = magic == MH_MAGIC_64 || magic == MH_CIGAM_64 || magic == MH_MAGIC || magic == MH_CIGAM;
                if (magic_is_thin) {
                    struct mach_header header;
                    header.magic = magic;

                    read(descriptor, &header.cputype, sizeof(struct mach_header) - sizeof(uint32_t));
                    if (!has_library_command(descriptor, header)) {
                        close(descriptor);
                        return false;
                    }
                } else {
                    close(descriptor);
                    return false;
                }
            }
        }

        close(descriptor);
        return true;
    }

    void file::validate() {
        auto &containers = containers_;
        auto &file = file_;
        auto &magic = magic_;

        fread(&magic, sizeof(uint32_t), 1, file);

        const auto magic_is_fat = magic == FAT_MAGIC || magic == FAT_CIGAM || magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;
        if (magic_is_fat) {
            uint32_t nfat_arch;
            fread(&nfat_arch, sizeof(uint32_t), 1, file);

            if (!nfat_arch) {
                fprintf(stderr, "Mach-o file has 0 architectures");
                exit(1);
            }

            auto should_swap = magic == FAT_CIGAM || magic == FAT_CIGAM_64;
            if (should_swap) {
                swap_value(nfat_arch);
            }

            containers.reserve(nfat_arch);

            const auto magic_is_fat_64 = magic == FAT_MAGIC_64 || magic == FAT_CIGAM_64;
            if (magic_is_fat_64) {
                const auto architectures = new struct fat_arch_64[nfat_arch];
                const auto architectures_size = sizeof(struct fat_arch_64) * nfat_arch;

                fread(architectures, architectures_size, 1, file);

                if (should_swap) {
                    swap_fat_arch_64(architectures, nfat_arch, NX_LittleEndian);
                }

                for (auto i = 0; i < nfat_arch; i++) {
                    const auto &architecture = architectures[i];
                    containers.emplace_back(file, architecture.offset, architecture.size);
                }

                delete[] architectures;
            } else {
                const auto architectures = new struct fat_arch[nfat_arch];
                fread(architectures, sizeof(struct fat_arch) * nfat_arch, 1, file);

                if (should_swap) {
                    swap_fat_arch(architectures, nfat_arch, NX_LittleEndian);
                }

                for (auto i = 0; i < nfat_arch; i++) {
                    const auto &architecture = architectures[i];
                    containers.emplace_back(file, architecture.offset, architecture.size);
                }

                delete[] architectures;
            }
        } else {
            const auto magic_is_thin = magic == MH_MAGIC || magic == MH_CIGAM || magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
            if (magic_is_thin) {
                containers.emplace_back(file, 0);
            } else {
                fputs("Mach-o file is invalid, does not have a valid magic-number", stderr);
                exit(1);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Replace last DEBUG occurrence with LLVM_DEBUG.<commit_after><|endoftext|>


<commit_before>/*
 * Implementation of color_set.h
 */

#include "color_set.h"

ColorSet::ColorSet(set<Color*> colors) {
    this->colors = colors;
    this->n = colors.size();
}

ColorSet::ColorSet(set<Color*> colors, unsigned int n) {
    this->colors = colors;
    if(n > 0) {
        this->n = n;
    }
    else if(n == 0) {
        this->n = colors.size();
    }
}

bool ColorSet::allContainsKmer(string& kmer) const {
    if(numContainsKmer(kmer) == colors.size()) {
        return true;
    }
    else {
        return false;
    }
}

bool ColorSet::nContainsKmer(string& kmer) const {
    if(numContainsKmer(kmer) >= n) {
        return true;
    }
    else {
        return false;
    }
}

int ColorSet::numContainsKmer(string& kmer) const {
    return containsKmer(kmer).getColors().size();
}

/// @todo determine if this method should be deleted...
ColorSet ColorSet::containsKmer(string& kmer) const {
    set<Color*> subColors;

    for(Color* color : colors) {
        if(color->isVertex(kmer)) {
            subColors.insert(color);
        }
    }

    /// @todo figure out where to get n from...
    return ColorSet(subColors, 0);
}

set<Color*> ColorSet::getColors() const {
    return colors;
}

set<Color*>::iterator ColorSet::getBeginIterator() const {
    return colors.begin();
}

set<Color*>::iterator ColorSet::getEndIterator() const {
    return colors.end();
}
<commit_msg>Added helpful comment to ColorSet.<commit_after>/*
 * Implementation of color_set.h
 */

#include "color_set.h"

ColorSet::ColorSet(set<Color*> colors) {
    this->colors = colors;
    this->n = colors.size();
}

ColorSet::ColorSet(set<Color*> colors, unsigned int n) {
    this->colors = colors;
    if(n > 0) {
        this->n = n;
    }
    else if(n == 0) { // an n of 0 indicates to n to be set to the size of colors
        this->n = colors.size();
    }
}

bool ColorSet::allContainsKmer(string& kmer) const {
    if(numContainsKmer(kmer) == colors.size()) {
        return true;
    }
    else {
        return false;
    }
}

bool ColorSet::nContainsKmer(string& kmer) const {
    if(numContainsKmer(kmer) >= n) {
        return true;
    }
    else {
        return false;
    }
}

int ColorSet::numContainsKmer(string& kmer) const {
    return containsKmer(kmer).getColors().size();
}

/// @todo determine if this method should be deleted...
ColorSet ColorSet::containsKmer(string& kmer) const {
    set<Color*> subColors;

    for(Color* color : colors) {
        if(color->isVertex(kmer)) {
            subColors.insert(color);
        }
    }

    /// @todo figure out where to get n from...
    return ColorSet(subColors, 0);
}

set<Color*> ColorSet::getColors() const {
    return colors;
}

set<Color*>::iterator ColorSet::getBeginIterator() const {
    return colors.begin();
}

set<Color*>::iterator ColorSet::getEndIterator() const {
    return colors.end();
}
<|endoftext|>


<commit_before>#ifndef HMLIB_LATTICES_POINT_INC
#define HMLIB_LATTICES_POINT_INC 100
#
#include<array>
#include<utility>
#include"../algorithm/compare.hpp"
#include"../euclidean.hpp"
namespace hmLib{
	namespace lattices{
		using index_type = int;
		using diff_type = int;
		using size_type = unsigned int;
		using size_diff_pair = std::pair<size_type, diff_type>;

		template<unsigned int dim_>
		using point = euclidean::point<index_type, dim_>;

		template<typename ...others>
		auto make_point(others... Others)->point<sizeof...(others)>{
			std::array<int,sizeof...(others)> Array{Others...};
			return point<sizeof...(others)>(Array.begin(),Array.end());
		}

		template<unsigned int dim_>
		auto make_filled_point(index_type Val)->point<dim_> { point<dim_> Pos; Pos.fill(Val); return Pos; }

		template<unsigned int dim_>
		point<dim_> index_to_point(index_type Index, const point<dim_>& Size) {
			point<dim_> Pos;
			for (unsigned int no = 0; no < dim_;++no) {
				Pos[no] = (Index%Size[no]);
				Index /= Size[no];
			}

			return Pos;
		}
		template<unsigned int dim_>
		index_type point_to_index(point<dim_> Point, const point<dim_>& Size) {
			diff_type Index = Point[0];
			for (unsigned int no = 1; no < dim_; ++no) {
				Index += Point[no]*Size[no-1];
			}

			return Index;
		}
		template<unsigned int dim_>
		point<dim_> make_torus_point(const point<dim_>& Point, const point<dim_>& Size){
			point<dim_> Ans = Point;
			for(unsigned int i = 0; i < dim_; ++i){
				Ans[i] = positive_mod(Ans[i], Size[i]);
			}
			return Ans;
		}
		template<unsigned int dim_>
		void torus_point(point<dim_>& Point, const point<dim_>& Size){
			for(unsigned int i = 0; i < dim_; ++i){
				Point[i] = positive_mod(Point[i], Size[i]);
			}
		}
	}
}
#
#endif
<commit_msg>Fix: lattice point is now cast.<commit_after>#ifndef HMLIB_LATTICES_POINT_INC
#define HMLIB_LATTICES_POINT_INC 100
#
#include<array>
#include<utility>
#include"../algorithm/compare.hpp"
#include"../euclidean.hpp"
namespace hmLib{
	namespace lattices{
		using index_type = int;
		using diff_type = int;
		using size_type = unsigned int;
		using size_diff_pair = std::pair<size_type, diff_type>;

		template<unsigned int dim_>
		using point = euclidean::point<index_type, dim_>;

		template<typename ...others>
		auto make_point(others... Others)->point<sizeof...(others)>{
			return point<sizeof...(others)>{static_cast<int>(Others)...};
		}

		template<unsigned int dim_>
		auto make_filled_point(index_type Val)->point<dim_> { point<dim_> Pos; Pos.fill(Val); return Pos; }

		template<unsigned int dim_>
		point<dim_> index_to_point(index_type Index, const point<dim_>& Size) {
			point<dim_> Pos;
			for (unsigned int no = 0; no < dim_;++no) {
				Pos[no] = (Index%Size[no]);
				Index /= Size[no];
			}

			return Pos;
		}
		template<unsigned int dim_>
		index_type point_to_index(point<dim_> Point, const point<dim_>& Size) {
			diff_type Index = Point[0];
			for (unsigned int no = 1; no < dim_; ++no) {
				Index += Point[no]*Size[no-1];
			}

			return Index;
		}
		template<unsigned int dim_>
		point<dim_> make_torus_point(const point<dim_>& Point, const point<dim_>& Size){
			point<dim_> Ans = Point;
			for(unsigned int i = 0; i < dim_; ++i){
				Ans[i] = positive_mod(Ans[i], Size[i]);
			}
			return Ans;
		}
		template<unsigned int dim_>
		void torus_point(point<dim_>& Point, const point<dim_>& Size){
			for(unsigned int i = 0; i < dim_; ++i){
				Point[i] = positive_mod(Point[i], Size[i]);
			}
		}
	}
}
#
#endif
<|endoftext|>


<commit_before>#pragma once

#include "parser.hpp"
#include "srcSupply.hpp"
#include "verifier.hpp"

namespace wrd {

    class _wout interpreter : public typeProvidable, public clonable {
        WRD(CLASS(interpreter))

    public:
        interpreter(): _isParsed(false), _isLogStructure(false), _isLogInterpreter(false) {}

    public:
        me& setReport(errReport& report) {
            _rpt.bind(report);
            return *this;
        }
        me& setPack(pack& pak) {
            _pak.bind(pak);
            return *this;
        }
        me& setSrcSupply(const srcSupply& supply) {
            _srcs.bind(supply);
            return *this;
        }
        me& setLogStructure(wbool enable) {
            _isLogStructure = enable;
            return *this;
        }
        me& setLogInterpreter(wbool enable) {
            _isLogInterpreter = enable;
            return *this;
        }
        wbool isParsed() const {
            return _isParsed;
        }

        wbool isVerified() const {
            return isParsed() && (_rpt && !_rpt->hasErr());
        }

        node& getSubPack() { return _pser.getSubPack(); }
        const node& getSubPack() const WRD_UNCONST_FUNC(getSubPack())

        pack& getPack() { return _pser.getPack(); }
        const pack& getPack() const WRD_UNCONST_FUNC(getPack())

        const errReport& getReport() const {
            return *_rpt;
        }

        pack& interpret() {
            if(!_srcs) {
                _rpt->add(err::newErr(NO_SRC));
                return *_pak;
            }

            _parse();
            tstr<frame> info;
            if(*_rpt)
                return *_pak;
            _verify(info);
            _logStructure(*info, _srcs->get());

            return *_pak;
        }

        void rel() {
            _isParsed = false;
            _rpt.rel();
            _veri.rel();
            _pser.rel();
            _srcs.rel();
            _pak.rel();
        }

        void log() const {
            if(!_rpt && !*_rpt) return;

            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(true);

            _rpt->log();

            l.loadStreamEnable();
        }

    private:
        wbool _isPackExist() {
            return !nul(_pser.getSubPack()) && _pak;
        }

        void _parse() {
            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(_isLogInterpreter);
            while(_srcs->next()) {
                _pser.rel(); // parser can only take 1 src.

                const char* buf = _srcs->get();
                WRD_DI("======================================");
                WRD_DI("                parse                 ");
                WRD_DI("======================================");

                _pser.setReport(*_rpt)
                     .setPack(*_pak)
                     .parse(buf);

                if(!_pak)
                    _pak.bind(_pser.getPack());
            }

            _isParsed = _isPackExist() && !_rpt->hasErr();
            l.loadStreamEnable();
        }

        void _verify(tstr<frame>& info ) {
            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(_isLogInterpreter);

            WRD_DI("======================================");
            WRD_DI("                verify                ");
            WRD_DI("======================================");

            if(!_pak) {
                WRD_E("_pak is null");
                return;
            }

            // make tray:
            packs* paks = new packs();
            paks->add(_pak->getManifest().name, *_pak);
            packChain tray(paks);
            tray.link(wrd::thread::get().getSystemPacks());

            // verify:
            _veri.setReport(*_rpt)
                 .setPacks(tray)
                 .setFrameInfo(info)
                 .verify(*_pak);
            l.loadStreamEnable();

        }

        void _logStructure(frame& info, const wchar* buf) {
            if(!_isLogStructure) return;

            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(true);
            platformAPI::updateConsoleFore(platformAPI::LIGHTGREEN);

            std::cout << " - frame:\n";
            _logFrame(info);
            std::cout << "\n";

            if(!nul(_pser.getSubPack()) && _pak) {
                std::cout << " - structure:\n";
                _logStructure(_pser.getSubPack(), _pak->getManifest().name, 0, 0, true, true);
                std::cout << "\n";
            }

            l.loadStreamEnable();
            platformAPI::updateConsoleFore(platformAPI::LIGHTGRAY);
        }

        void _logStructure(const node& n, const std::string& name, int idx, int level, bool isLast, bool isParentLast) const {
            if(nul(n)) {
                WRD_W("_logStructure(n == null)");
                return;
            }

            _logIndent(level, isParentLast);
            std::cout << (isLast ? "┗━[" : "┣━[") << idx << "]: " << n.getType().getName() << " \"" << name << "\"\n";

            int subN = -1;
            const bicontainable& subs = n.subs();
            for(auto e=subs.begin(); e ;++e) {
                subN++;
                _logStructure(e.getVal(), e.getKey(), subN, level + 2, subN == subs.len()-1, isLast);
            }

            const mgdFunc& f = n.cast<mgdFunc>();
            if(!nul(f)) {
                subN++;
                _logStructure(f.getBlock().getStmts(), subN, level+2, subN == subs.len(), isLast);
            }
        }

        void _logStructure(const narr& blk, int idx, int level, bool isLast, bool isParentLast) const {
            _logIndent(level, isParentLast);
            std::cout << (isLast ? "┗━[" : "┣━[") << idx << "]: block \n";

            int subN = -1;
            for(const auto& stmt: blk) {
                subN++;
                const blockExpr& blkExpr = stmt.cast<blockExpr>();
                if(!nul(blkExpr))
                    _logStructure(blkExpr.getStmts(), subN, level+2, subN == blk.len()-1, isLast);
                else
                    _logStructure(stmt, "", subN, level + 2, subN == blk.len()-1, isLast);
            }
        }

        void _logIndent(int level, bool isParentLast) const {
            std::cout << "  ";
            for(int n=0; n < level-1; n++)
                std::cout << (isParentLast ? "  " : "┃ ");
        }

        void _logFrame(const frame& info) const {
            if(nul(info)) {
                std::cout << "    null\n";
                return;
            }

            int n=0;
            for(auto e = info.subs().begin(); e ;++e)
                std::cout << "    [" << n++ << "]: '" << e.getKey() << "' " << e.getVal().getType().getName().c_str() << "\n";
        }

    private:
        tstr<errReport> _rpt;
        tstr<pack> _pak;
        verifier _veri;
        parser _pser;
        tstr<srcSupply> _srcs;
        wbool _isParsed;
        wbool _isLogStructure;
        wbool _isLogInterpreter;
    };
}
<commit_msg>indep: fix: console fore and back color can't be applied to<commit_after>#pragma once

#include "parser.hpp"
#include "srcSupply.hpp"
#include "verifier.hpp"

namespace wrd {

    class _wout interpreter : public typeProvidable, public clonable {
        WRD(CLASS(interpreter))

    public:
        interpreter(): _isParsed(false), _isLogStructure(false), _isLogInterpreter(false) {}

    public:
        me& setReport(errReport& report) {
            _rpt.bind(report);
            return *this;
        }
        me& setPack(pack& pak) {
            _pak.bind(pak);
            return *this;
        }
        me& setSrcSupply(const srcSupply& supply) {
            _srcs.bind(supply);
            return *this;
        }
        me& setLogStructure(wbool enable) {
            _isLogStructure = enable;
            return *this;
        }
        me& setLogInterpreter(wbool enable) {
            _isLogInterpreter = enable;
            return *this;
        }
        wbool isParsed() const {
            return _isParsed;
        }

        wbool isVerified() const {
            return isParsed() && (_rpt && !_rpt->hasErr());
        }

        node& getSubPack() { return _pser.getSubPack(); }
        const node& getSubPack() const WRD_UNCONST_FUNC(getSubPack())

        pack& getPack() { return _pser.getPack(); }
        const pack& getPack() const WRD_UNCONST_FUNC(getPack())

        const errReport& getReport() const {
            return *_rpt;
        }

        pack& interpret() {
            if(!_srcs) {
                _rpt->add(err::newErr(NO_SRC));
                return *_pak;
            }

            _parse();
            tstr<frame> info;
            if(*_rpt)
                return *_pak;
            _verify(info);
            _logStructure(*info, _srcs->get());

            return *_pak;
        }

        void rel() {
            _isParsed = false;
            _rpt.rel();
            _veri.rel();
            _pser.rel();
            _srcs.rel();
            _pak.rel();
        }

        void log() const {
            if(!_rpt && !*_rpt) return;

            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(true);

            _rpt->log();

            l.loadStreamEnable();
        }

    private:
        wbool _isPackExist() {
            return !nul(_pser.getSubPack()) && _pak;
        }

        void _parse() {
            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(_isLogInterpreter);
            while(_srcs->next()) {
                _pser.rel(); // parser can only take 1 src.

                const char* buf = _srcs->get();
                WRD_DI("======================================");
                WRD_DI("                parse                 ");
                WRD_DI("======================================");

                _pser.setReport(*_rpt)
                     .setPack(*_pak)
                     .parse(buf);

                if(!_pak)
                    _pak.bind(_pser.getPack());
            }

            _isParsed = _isPackExist() && !_rpt->hasErr();
            l.loadStreamEnable();
        }

        void _verify(tstr<frame>& info ) {
            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(_isLogInterpreter);

            WRD_DI("======================================");
            WRD_DI("                verify                ");
            WRD_DI("======================================");

            if(!_pak) {
                WRD_E("_pak is null");
                return;
            }

            // make tray:
            packs* paks = new packs();
            paks->add(_pak->getManifest().name, *_pak);
            packChain tray(paks);
            tray.link(wrd::thread::get().getSystemPacks());

            // verify:
            _veri.setReport(*_rpt)
                 .setPacks(tray)
                 .setFrameInfo(info)
                 .verify(*_pak);
            l.loadStreamEnable();

        }

        void _logStructure(frame& info, const wchar* buf) {
            if(!_isLogStructure) return;

            logger& l = logger::get();
            l.saveStreamEnable();
            l.setEnable(true);
            platformAPI::updateConsoleFore(platformAPI::LIGHTGREEN);

            std::cout << " - frame:\n";
            _logFrame(info);
            std::cout << "\n";

            if(!nul(_pser.getSubPack()) && _pak) {
                std::cout << " - structure:\n";
                std::vector<const char*> indents;
                indents.push_back("  ");
                _logStructure(indents, _pser.getSubPack(), _pak->getManifest().name, 0, true, true);
                std::cout << "\n";
            }

            l.loadStreamEnable();
            platformAPI::updateConsoleFore(platformAPI::LIGHTGRAY);
        }

        void _logStructure(std::vector<const char*>& indents, const node& n, const std::string& name, int idx, bool isLast, bool isParentLast) const {
            if(nul(n)) {
                WRD_W("_logStructure(n == null)");
                return;
            }

            indents.push_back((isParentLast ? "    " : "┃    "));
            _logIndent(indents, isParentLast);
            std::cout << (isLast ? "┗━[" : "┣━[") << idx << "]: " << n.getType().getName() << " \"" << name << "\"\n";

            int subN = -1;
            const bicontainable& subs = n.subs();
            for(auto e=subs.begin(); e ;++e) {
                subN++;
                _logStructure(indents, e.getVal(), e.getKey(), subN, subN == subs.len()-1, isLast);
            }

            const mgdFunc& f = n.cast<mgdFunc>();
            if(!nul(f)) {
                subN++;
                _logStructure(indents, f.getBlock().getStmts(), subN, subN == subs.len(), isLast);
            }
            indents.pop_back();
        }

        void _logStructure(std::vector<const char*>& indents, const narr& blk, int idx, bool isLast, bool isParentLast) const {
            indents.push_back(isParentLast ? "    " : "┃   ");
            _logIndent(indents, isParentLast);
            std::cout << (isLast ? "┗━[" : "┣━[") << idx << "]: block \n";

            int subN = -1;
            for(const auto& stmt: blk) {
                subN++;
                const blockExpr& blkExpr = stmt.cast<blockExpr>();
                if(!nul(blkExpr))
                    _logStructure(indents, blkExpr.getStmts(), subN, subN == blk.len()-1, isLast);
                else
                    _logStructure(indents, stmt, "", subN, subN == blk.len()-1, isLast);
            }
            indents.pop_back();
        }

        void _logIndent(const std::vector<const char*>& indents, bool isParentLast) const {
            for(int n=0; n < indents.size(); n++)
                std::cout << indents[n];
        }

        void _logFrame(const frame& info) const {
            if(nul(info)) {
                std::cout << "    null\n";
                return;
            }

            int n=0;
            for(auto e = info.subs().begin(); e ;++e)
                std::cout << "    [" << n++ << "]: '" << e.getKey() << "' " << e.getVal().getType().getName().c_str() << "\n";
        }

    private:
        tstr<errReport> _rpt;
        tstr<pack> _pak;
        verifier _veri;
        parser _pser;
        tstr<srcSupply> _srcs;
        wbool _isParsed;
        wbool _isLogStructure;
        wbool _isLogInterpreter;
    };
}
<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;
	int F = 0;
	int C = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){

				cout << Temp << endl << endl << endl << flush;
		for (int i = 0; i < Temp.length(); i++){
			if (Temp[i] == ','){
				C++;
				mapArray[X][Y] = stoi(Temp.substr(F,i-F));
				cout << mapArray[X][Y] << "  " << flush;
				X++;
				F = i + 1;
		cout << "C = " << C << flush;
			}
		}
		Y++;
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<commit_msg>Work in progress<commit_after>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;
	int F = 0;
	int C = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){

				cout << Temp << endl << endl << endl << flush;
		for (int i = 0; i < Temp.length(); i++){
			if (Temp[i] == ','){
				C++;
				mapArray[X][Y] = stoi(Temp.substr(F,i-F));
				cout << mapArray[X][Y] << "  " << flush;
				X++;
				F = i + 1;
			}
		}
		Y++;
		X = 0;
				cout << "C = " << C << flush;
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<|endoftext|>


<commit_before><?hh // decl
require_once '../../vendor/autoload.php';

use Usox\Sharesta\Exception;
use Usox\Sharesta\RequestInterface;
use Usox\Sharesta\Request;
use Usox\Sharesta\RequestBody;
use Usox\Sharesta\Router;
use Usox\Sharesta\Application;
use Usox\Sharesta\Response;

class HomeRoute implements \JsonSerializable {

	public function jsonSerialize(): string {
		return 'Welcome home';
	}
}

class GetSomeIdRoute implements \JsonSerializable {

	public function __construct(private RequestInterface $request): void {
	}

	public function doSomeFancyMagic(): void {
		$this->request_id = $this->request->getRouteParameters()->get('id');
	}

	public function jsonSerialize(): string {
		return 'Got '.$this->request_id;
	}
}

class Routes implements \Usox\Sharesta\RoutesInterface {

	public function registerRoutes(\Usox\Sharesta\RouterInterface $router): void {
		$router->get('/', function (Request $request) {
			return new HomeRoute();
		});
		$router->get('/get_some/:id', function (Request $request) {
			$route = new GetSomeIdRoute($request);
			$route->doSomeFancyMagic();
			return $route;
		});
	}
}

function init() {

	try {
		$request = new Request(
			'TEST/example/webroot',
			new Map($_SERVER),
			new Map($_GET),
			new RequestBody()
		);
		$app = new Usox\Sharesta\Application(
			$request,
			new Router(),
			new Routes()
		);
		$app->init();
		$app->execute();
	} catch (Exception\NotFoundException $e) {
		$response = new Response();
		$response->send(404, $e->getMessage());
	} catch (Exception\RequestException $e) {
		$response = new Response();
		$response->send(400, $e->getMessage());
	} catch (Exception\ServerException $e) {
		$response = new Response();
		$response->send(500, $e->getMessage());
	}
}
init();
<commit_msg>Add a namespace to the example file to avoid naming problems<commit_after><?hh // decl
namespace Usox\Sharesta\Example;

require_once '../../vendor/autoload.php';

use Usox\Sharesta\Exception;
use Usox\Sharesta\RequestInterface;
use Usox\Sharesta\Request;
use Usox\Sharesta\RequestBody;
use Usox\Sharesta\Router;
use Usox\Sharesta\Application;
use Usox\Sharesta\Response;

class HomeRoute implements \JsonSerializable {

	public function jsonSerialize(): string {
		return 'Welcome home';
	}
}

class GetSomeIdRoute implements \JsonSerializable {

	public function __construct(private RequestInterface $request): void {
	}

	public function doSomeFancyMagic(): void {
		$this->request_id = $this->request->getRouteParameters()->get('id');
	}

	public function jsonSerialize(): string {
		return 'Got '.$this->request_id;
	}
}

class Routes implements \Usox\Sharesta\RoutesInterface {

	public function registerRoutes(\Usox\Sharesta\RouterInterface $router): void {
		$router->get('/', function (Request $request) {
			return new HomeRoute();
		});
		$router->get('/get_some/:id', function (Request $request) {
			$route = new GetSomeIdRoute($request);
			$route->doSomeFancyMagic();
			return $route;
		});
	}
}

function init() {

	try {
		$request = new Request(
			'TEST/example/webroot',
			new Map($_SERVER),
			new Map($_GET),
			new RequestBody()
		);
		$app = new Usox\Sharesta\Application(
			$request,
			new Router(),
			new Routes()
		);
		$app->init();
		$app->execute();
	} catch (Exception\NotFoundException $e) {
		$response = new Response();
		$response->send(404, $e->getMessage());
	} catch (Exception\RequestException $e) {
		$response = new Response();
		$response->send(400, $e->getMessage());
	} catch (Exception\ServerException $e) {
		$response = new Response();
		$response->send(500, $e->getMessage());
	}
}
init();
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <iostream>
#include "dataproc.h"

#if 1
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

std::pair<std::pair<char const *, char const *>, std::uint32_t>
read_field(char const *record)
{
    return cdmh::data_processing::detail::read_field(record, record+strlen(record));
}

TEST_CASE("read_field/string fields", "Ensure reading of correct field types")
{
    REQUIRE(read_field("Hello").second == string_type);
    REQUIRE(read_field("\"Hello World\"").second == string_type);
    REQUIRE(read_field("\"Hello \\\"World\\\"!\"").second == string_type);
}

TEST_CASE("read_field/integer fields", "")
{
    REQUIRE(read_field("8374").second == integer_type);
    REQUIRE(read_field("837.4").second == double_type);
}

TEST_CASE("read_field/unary signs", "")
{
    REQUIRE(read_field("+8374").second == integer_type);
    REQUIRE(read_field("+837.4").second == double_type);
    REQUIRE(read_field("-8374").second == integer_type);
    REQUIRE(read_field("-837.4").second == double_type);
}

TEST_CASE("read_field/string fields starting with numerics", "")
{
    REQUIRE(read_field("83.7.4").second == string_type);
    REQUIRE(read_field("+83.7.4").second == string_type);
    REQUIRE(read_field("83a4").second == string_type);
    REQUIRE(read_field("8.3a4").second == string_type);
    REQUIRE(read_field("a8.34").second == string_type);
}

TEST_CASE("read_field/numerics with padding", "")
{
    REQUIRE(read_field("8374 ").second == integer_type);
    REQUIRE(read_field("+8374 ").second == integer_type);
    REQUIRE(read_field("-8374 ").second == integer_type);
    REQUIRE(read_field(" +8374").second == integer_type);
    REQUIRE(read_field(" +8374 ").second == integer_type);
}

TEST_CASE("read_field/comma separated fields with space padding", "")
{
    auto record = "      Hello, World   ";
    auto it = record;
    auto ite = record+strlen(record);
    auto field1 = cdmh::data_processing::detail::read_field(it, ite);
    auto field2 = cdmh::data_processing::detail::read_field(it, ite);
    REQUIRE(std::distance(field1.first.first, field1.first.second) == 5);
    REQUIRE(std::distance(field2.first.first, field2.first.second) == 5);
}

TEST_CASE("read_field/spaces around quoted string with leading & trailing spaces", "")
{
    auto record = "    \"  Hello, World \"  ";
    auto it = record;
    auto ite = record+strlen(record);
    auto field = cdmh::data_processing::detail::read_field(it, ite);
    REQUIRE(std::distance(field.first.first, field.first.second) == 15);
}
#else

int main()
{
#if defined(_MSC_VER)  &&  defined(_DEBUG)
    _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif

    cdmh::data_processing::mapped_csv csv("data/training.csv");
    csv.read(100);
    auto keypoints = csv.create_dataset();
    std::cout << keypoints.rows() << " records with " << keypoints.columns() << " columns";
    char const *image = keypoints[0][30];
    image = keypoints[1][30];
    image = keypoints[2][30];
    image = keypoints[3][30];
    auto a = keypoints[3];
    auto b = a[0];
    std::cout << "\n" << a[0] << " " << a[1];

    return 0;
}
#endif
<commit_msg>Improved tests. Default to report time taken on each test<commit_after>#include "stdafx.h"
#include <iostream>
#include "dataproc.h"

#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

std::pair<std::pair<char const *, char const *>, std::uint32_t>
read_field(char const *record)
{
    return cdmh::data_processing::detail::read_field(record, record+strlen(record));
}

TEST_CASE("read_field/string fields", "Ensure reading of correct field types")
{
    CHECK(read_field("Hello").second == string_type);
    CHECK(read_field("\"Hello World\"").second == string_type);
    CHECK(read_field("\"Hello \\\"World\\\"!\"").second == string_type);
}

TEST_CASE("read_field/integer fields", "")
{
    CHECK(read_field("8374").second == integer_type);
    CHECK(read_field("837.4").second == double_type);
}

TEST_CASE("read_field/unary signs", "")
{
    CHECK(read_field("+8374").second == integer_type);
    CHECK(read_field("+837.4").second == double_type);
    CHECK(read_field("-8374").second == integer_type);
    CHECK(read_field("-837.4").second == double_type);
}

TEST_CASE("read_field/string fields starting with numerics", "")
{
    CHECK(read_field("83.7.4").second == string_type);
    CHECK(read_field("+83.7.4").second == string_type);
    CHECK(read_field("83a4").second == string_type);
    CHECK(read_field("8.3a4").second == string_type);
    CHECK(read_field("a8.34").second == string_type);
}

TEST_CASE("read_field/numerics with padding", "")
{
    CHECK(read_field("8374 ").second == integer_type);
    CHECK(read_field("+8374 ").second == integer_type);
    CHECK(read_field("-8374 ").second == integer_type);
    CHECK(read_field(" +8374").second == integer_type);
    CHECK(read_field(" +8374 ").second == integer_type);
}

TEST_CASE("read_field/comma separated fields with space padding", "")
{
    auto record = "      Hello, World   ";
    auto it = record;
    auto ite = record+strlen(record);
    auto field1 = cdmh::data_processing::detail::read_field(it, ite);
    auto field2 = cdmh::data_processing::detail::read_field(it, ite);
    CHECK(std::distance(field1.first.first, field1.first.second) == 5);
    CHECK(std::distance(field2.first.first, field2.first.second) == 5);
}

TEST_CASE("read_field/spaces around quoted string with leading & trailing spaces", "")
{
    auto record = "    \"  Hello, World \"  ";
    auto it = record;
    auto ite = record+strlen(record);
    auto field = cdmh::data_processing::detail::read_field(it, ite);
    CHECK(std::distance(field.first.first, field.first.second) == 15);
}

TEST_CASE("mapped_csv", "")
{
    cdmh::data_processing::mapped_csv csv("data/training.csv");

#ifdef NDEBUG
    size_t const rows_requested = 0;
    size_t const rows_expected  = 7049;
#else
    size_t const rows_requested = 100;
    size_t const rows_expected  = 100;
#endif

    REQUIRE(csv.read(rows_requested));
    REQUIRE(csv.size() == rows_expected);

    SECTION("row and column count")
    {
        auto keypoints = csv.create_dataset();
        std::cout << keypoints.rows() << " records with " << keypoints.columns() << " columns\n";
        CHECK(keypoints.rows() == rows_expected);
        REQUIRE(keypoints.columns() == 31);
    }

    SECTION("row & column data access")
    {
        auto keypoints = csv.create_dataset();
        char const *image = keypoints[0][30];
        image = keypoints[1][30];
        image = keypoints[2][30];
        image = keypoints[3][30];
        auto a = keypoints[3];
        auto b = a[0];
        std::cout << "\n" << a[0] << " " << a[1] << "\n";
    }
}

int main(int argc, char * const argv[])
{
#if defined(_MSC_VER)  &&  defined(_DEBUG)
    _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif

    Catch::Session session;
    Catch::ConfigData &config_data = session.configData();
    config_data.showDurations = Catch::ShowDurations::OrNot::Always;

    int returnCode = session.applyCommandLine(argc, argv);
    if (returnCode != 0)
        return returnCode;

    return session.run();
}
<|endoftext|>


<commit_before><commit_msg>tdf#90969: basic: add horrible hack to avoid crash due to ...<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: interact.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: jl $ $Date: 2002-07-23 14:07:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "interact.hxx"

namespace stoc_javavm
{

InteractionAbort::InteractionAbort( const WeakReference<XInterface>& xJVM,
                                    JavaVirtualMachine_Impl * _pJVM):
    m_xJVM(xJVM),
    m_pJVM(_pJVM)
{
    OSL_ASSERT( _pJVM);
}

void SAL_CALL InteractionAbort::select(  ) throw (RuntimeException)
{
    //If we get a hard reference to JavaVirtualMachine_Impl
    //then we may call the callback
    Reference<XInterface> xIntJVM= m_xJVM;
    if( xIntJVM.is())
        m_pJVM->selectAbort();
}
//================================================================================
InteractionRetry::InteractionRetry( const WeakReference<XInterface>& xJVM,
                                    JavaVirtualMachine_Impl * _pJVM):
    m_xJVM(xJVM),
    m_pJVM(_pJVM)
{
    OSL_ASSERT( _pJVM);
}

void SAL_CALL InteractionRetry::select(  ) throw (RuntimeException)
{
    //If we get a hard reference to JavaVirtualMachine_Impl
    //then we may call the callback
    Reference<XInterface> xIntJVM= m_xJVM;
    if( xIntJVM.is())
        m_pJVM->selectRetry();
}
//================================================================================
InteractionRequest::InteractionRequest( const Reference<XInterface>& xJVM,
                                        JavaVirtualMachine_Impl* _pJVM,
                                        Any& _request):
    m_xJVM(xJVM),
    m_pJVM(_pJVM),
    m_anyRequest(_request),
    m_pseqContinuations(NULL)
{
}

Any SAL_CALL InteractionRequest::getRequest(  ) throw (RuntimeException)
{
    return m_anyRequest;
}

Sequence< Reference< XInteractionContinuation > >
SAL_CALL InteractionRequest::getContinuations(  ) throw (RuntimeException)
{
    if ( ! m_pseqContinuations)
    {
        MutexGuard guard(javavm_getMutex());
        if( ! m_pseqContinuations)
        {
            Reference<XInteractionContinuation> arObjs[2];
            arObjs[0]= Reference< XInteractionContinuation >(
                static_cast<XWeak*> (new InteractionRetry(m_xJVM, m_pJVM)), UNO_QUERY);
            arObjs[1]= Reference< XInteractionContinuation> (
                static_cast<XWeak*> (new InteractionAbort(m_xJVM, m_pJVM)), UNO_QUERY);
            m_seqContinuations= Sequence< Reference< XInteractionContinuation> >( arObjs, 2);
        }
    }
    return m_seqContinuations;
}

} // end namespace
<commit_msg>#1003002# java error handling: on linux reboot necessary after jvmsetup, interaction handler only gets XInteractionAbort<commit_after>/*************************************************************************
 *
 *  $RCSfile: interact.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jl $ $Date: 2002-09-16 12:30:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "interact.hxx"

#ifndef _COM_SUN_STAR_JAVA_JAVADISABLEDEXCEPTION_HPP_
#include <com/sun/star/java/JavaDisabledException.hpp>
#endif

namespace stoc_javavm
{

InteractionAbort::InteractionAbort( const WeakReference<XInterface>& xJVM,
                                    JavaVirtualMachine_Impl * _pJVM):
    m_xJVM(xJVM),
    m_pJVM(_pJVM)
{
    OSL_ASSERT( _pJVM);
}

void SAL_CALL InteractionAbort::select(  ) throw (RuntimeException)
{
    //If we get a hard reference to JavaVirtualMachine_Impl
    //then we may call the callback
    Reference<XInterface> xIntJVM= m_xJVM;
    if( xIntJVM.is())
        m_pJVM->selectAbort();
}
//================================================================================
InteractionRetry::InteractionRetry( const WeakReference<XInterface>& xJVM,
                                    JavaVirtualMachine_Impl * _pJVM):
    m_xJVM(xJVM),
    m_pJVM(_pJVM)
{
    OSL_ASSERT( _pJVM);
}

void SAL_CALL InteractionRetry::select(  ) throw (RuntimeException)
{
    //If we get a hard reference to JavaVirtualMachine_Impl
    //then we may call the callback
    Reference<XInterface> xIntJVM= m_xJVM;
    if( xIntJVM.is())
        m_pJVM->selectRetry();
}
//================================================================================
InteractionRequest::InteractionRequest( const Reference<XInterface>& xJVM,
                                        JavaVirtualMachine_Impl* _pJVM,
                                        Any& _request):
    m_xJVM(xJVM),
    m_pJVM(_pJVM),
    m_anyRequest(_request),
    m_pseqContinuations(NULL)
{
}

Any SAL_CALL InteractionRequest::getRequest(  ) throw (RuntimeException)
{
    return m_anyRequest;
}

Sequence< Reference< XInteractionContinuation > >
SAL_CALL InteractionRequest::getContinuations(  ) throw (RuntimeException)
{
    if ( ! m_pseqContinuations)
    {
        MutexGuard guard(javavm_getMutex());
        if( ! m_pseqContinuations)
        {
#ifdef LINUX
            // Only if java is disabled we allow retry
            if( m_anyRequest.getValueType() == getCppuType( (JavaDisabledException*)0))
            {
                Reference<XInteractionContinuation> arObjs[2];
                arObjs[0]= Reference< XInteractionContinuation >(
                    static_cast<XWeak*> (new InteractionRetry(m_xJVM, m_pJVM)), UNO_QUERY);
                arObjs[1]= Reference< XInteractionContinuation> (
                    static_cast<XWeak*> (new InteractionAbort(m_xJVM, m_pJVM)), UNO_QUERY);
                m_seqContinuations= Sequence< Reference< XInteractionContinuation> >( arObjs, 2);
            }
            else
            {
                Reference<XInteractionContinuation> arObjs[1];
                arObjs[0]= Reference< XInteractionContinuation> (
                    static_cast<XWeak*> (new InteractionAbort(m_xJVM, m_pJVM)), UNO_QUERY);
                m_seqContinuations= Sequence< Reference< XInteractionContinuation> >( arObjs, 1);
            }
#else
            Reference<XInteractionContinuation> arObjs[2];
            arObjs[0]= Reference< XInteractionContinuation >(
                static_cast<XWeak*> (new InteractionRetry(m_xJVM, m_pJVM)), UNO_QUERY);
            arObjs[1]= Reference< XInteractionContinuation> (
                static_cast<XWeak*> (new InteractionAbort(m_xJVM, m_pJVM)), UNO_QUERY);
            m_seqContinuations= Sequence< Reference< XInteractionContinuation> >( arObjs, 2);
#endif
        }
    }
    return m_seqContinuations;
}

} // end namespace
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#pragma once

#include "gms/inet_address.hh"
#include "streaming/stream_session.hh"
#include "streaming/session_info.hh"
#include <map>
#include <algorithm>

namespace streaming {

/**
 * {@link StreamCoordinator} is a helper class that abstracts away maintaining multiple
 * StreamSession and ProgressInfo instances per peer.
 *
 * This class coordinates multiple SessionStreams per peer in both the outgoing StreamPlan context and on the
 * inbound StreamResultFuture context.
 */
class stream_coordinator {
    class host_streaming_data;
private:
    using inet_address = gms::inet_address;
    std::map<inet_address, host_streaming_data> _peer_sessions;
    int _connections_per_host;
    bool _keep_ss_table_level;

public:
    stream_coordinator(int connections_per_host, bool keep_ss_table_level)
        : _connections_per_host(connections_per_host)
        , _keep_ss_table_level(keep_ss_table_level) {
    }
#if 0
    public void setConnectionFactory(StreamConnectionFactory factory)
    {
        this.factory = factory;
    }
#endif
public:
    /**
     * @return true if any stream session is active
     */
    bool has_active_sessions();

    std::vector<stream_session> get_all_stream_sessions() {
        std::vector<stream_session> results;
        for (auto& x : _peer_sessions) {
            auto s = x.second.get_all_stream_sessions();
            std::move(s.begin(), s.end(), std::back_inserter(results));
        }
        return results;
    }

    bool is_receiving() {
        return _connections_per_host == 0;
    }

#if 0
    public void connectAllStreamSessions()
    {
        for (HostStreamingData data : peerSessions.values())
            data.connectAllStreamSessions();
    }

    public synchronized Set<InetAddress> getPeers()
    {
        return new HashSet<>(peerSessions.keySet());
    }
#endif
public:
    stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) {
        return get_or_create_host_data(peer).get_or_create_next_session(peer, connecting);
    }

    stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) {
        return get_or_create_host_data(peer).get_or_create_session_by_id(peer, id, connecting);
    }

    void update_progress(progress_info info) {
        get_host_data(info.peer).update_progress(info);
    }

    void add_session_info(session_info session) {
        auto& data = get_or_create_host_data(session.peer);
        data.add_session_info(std::move(session));
    }

    std::vector<session_info> get_all_session_info() {
        std::vector<session_info> result;
        for (auto& x : _peer_sessions) {
            auto s = x.second.get_all_session_info();
            std::move(s.begin(), s.end(), std::back_inserter(result));
        }
        return result;
    }

public:
    void transfer_files(inet_address to, std::vector<stream_session::ss_table_streaming_sections> sstable_details) {
        host_streaming_data& session_list = get_or_create_host_data(to);
        if (_connections_per_host > 1) {
            abort();
#if 0
            List<List<StreamSession.SSTableStreamingSections>> buckets = sliceSSTableDetails(sstableDetails);

            for (List<StreamSession.SSTableStreamingSections> subList : buckets)
            {
                StreamSession session = sessionList.get_or_create_next_session(to, to);
                session.addTransferFiles(subList);
            }
#endif
        } else {
            auto& session = session_list.get_or_create_next_session(to, to);
            session.add_transfer_files(sstable_details);
        }
    }

private:
#if 0
    private List<List<StreamSession.SSTableStreamingSections>> sliceSSTableDetails(Collection<StreamSession.SSTableStreamingSections> sstableDetails)
    {
        // There's no point in divvying things up into more buckets than we have sstableDetails
        int targetSlices = Math.min(sstableDetails.size(), connectionsPerHost);
        int step = Math.round((float) sstableDetails.size() / (float) targetSlices);
        int index = 0;

        List<List<StreamSession.SSTableStreamingSections>> result = new ArrayList<>();
        List<StreamSession.SSTableStreamingSections> slice = null;
        Iterator<StreamSession.SSTableStreamingSections> iter = sstableDetails.iterator();
        while (iter.hasNext())
        {
            StreamSession.SSTableStreamingSections streamSession = iter.next();

            if (index % step == 0)
            {
                slice = new ArrayList<>();
                result.add(slice);
            }
            slice.add(streamSession);
            ++index;
            iter.remove();
        }

        return result;
    }

#endif
    host_streaming_data& get_host_data(inet_address peer) {
        auto it = _peer_sessions.find(peer);
        if (it == _peer_sessions.end()) {
            throw std::runtime_error(sprint("Unknown peer requested: %s", peer));
        }
        return it->second;
    }

    host_streaming_data& get_or_create_host_data(inet_address peer) {
        _peer_sessions[peer] = host_streaming_data(_connections_per_host, _keep_ss_table_level);
        return _peer_sessions[peer];
    }

#if 0
    private static class StreamSessionConnector implements Runnable
    {
        private final StreamSession session;
        public StreamSessionConnector(StreamSession session)
        {
            this.session = session;
        }

        @Override
        public void run()
        {
            session.start();
            logger.info("[Stream #{}, ID#{}] Beginning stream session with {}", session.planId(), session.sessionIndex(), session.peer);
        }
    }
#endif

private:
    class host_streaming_data {
        using inet_address = gms::inet_address;
    private:
        std::map<int, stream_session> _stream_sessions;
        std::map<int, session_info> _session_infos;
        int _last_returned = -1;
        int _connections_per_host;
        bool _keep_ss_table_level;

    public:
        host_streaming_data() = default;

        host_streaming_data(int connections_per_host, bool keep_ss_table_level)
            : _connections_per_host(connections_per_host)
            , _keep_ss_table_level(keep_ss_table_level) {
        }

        bool has_active_sessions();

        stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) {
            // create
            int size = _stream_sessions.size();
            if (size < _connections_per_host) {
                auto session = stream_session(peer, connecting, size, _keep_ss_table_level);
                _stream_sessions.emplace(++_last_returned, std::move(session));
                return _stream_sessions[_last_returned];
            // get
            } else {
                if (_last_returned >= (size - 1)) {
                    _last_returned = 0;
                }
                return _stream_sessions[_last_returned++];
            }
        }
#if 0
        public void connectAllStreamSessions()
        {
            for (StreamSession session : streamSessions.values())
            {
                streamExecutor.execute(new StreamSessionConnector(session));
            }
        }
#endif

        std::vector<stream_session> get_all_stream_sessions() {
            std::vector<stream_session> sessions;
            for (auto& x : _stream_sessions) {
                sessions.push_back(x.second);
            }
            return sessions;
        }

        stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) {
            auto it = _stream_sessions.find(id);
            if (it == _stream_sessions.end()) {
                it = _stream_sessions.emplace(id, stream_session(peer, connecting, id, _keep_ss_table_level)).first;
            }
            return it->second;
        }

        void update_progress(progress_info info) {
            auto it = _session_infos.find(info.session_index);
            if (it != _session_infos.end()) {
                it->second.update_progress(std::move(info));
            }
        }

        void add_session_info(session_info info) {
            _session_infos[info.session_index] = std::move(info);
        }

        std::vector<session_info> get_all_session_info() {
            std::vector<session_info> sessions;
            for (auto& x : _session_infos) {
                sessions.push_back(x.second);
            }
            return sessions;
        }
    };
};

} // namespace streaming
<commit_msg>streaming: Add stream_coordinator::get_peers<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modified by Cloudius Systems.
 * Copyright 2015 Cloudius Systems.
 */

#pragma once

#include "gms/inet_address.hh"
#include "streaming/stream_session.hh"
#include "streaming/session_info.hh"
#include <map>
#include <algorithm>

namespace streaming {

/**
 * {@link StreamCoordinator} is a helper class that abstracts away maintaining multiple
 * StreamSession and ProgressInfo instances per peer.
 *
 * This class coordinates multiple SessionStreams per peer in both the outgoing StreamPlan context and on the
 * inbound StreamResultFuture context.
 */
class stream_coordinator {
    class host_streaming_data;
private:
    using inet_address = gms::inet_address;
    std::map<inet_address, host_streaming_data> _peer_sessions;
    int _connections_per_host;
    bool _keep_ss_table_level;

public:
    stream_coordinator(int connections_per_host, bool keep_ss_table_level)
        : _connections_per_host(connections_per_host)
        , _keep_ss_table_level(keep_ss_table_level) {
    }
#if 0
    public void setConnectionFactory(StreamConnectionFactory factory)
    {
        this.factory = factory;
    }
#endif
public:
    /**
     * @return true if any stream session is active
     */
    bool has_active_sessions();

    std::vector<stream_session> get_all_stream_sessions() {
        std::vector<stream_session> results;
        for (auto& x : _peer_sessions) {
            auto s = x.second.get_all_stream_sessions();
            std::move(s.begin(), s.end(), std::back_inserter(results));
        }
        return results;
    }

    bool is_receiving() {
        return _connections_per_host == 0;
    }

#if 0
    public void connectAllStreamSessions()
    {
        for (HostStreamingData data : peerSessions.values())
            data.connectAllStreamSessions();
    }
#endif

    std::set<inet_address> get_peers() {
        std::set<inet_address> r;
        for (auto& x : _peer_sessions) {
            r.insert(x.first);
        }
        return r;
    }

public:
    stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) {
        return get_or_create_host_data(peer).get_or_create_next_session(peer, connecting);
    }

    stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) {
        return get_or_create_host_data(peer).get_or_create_session_by_id(peer, id, connecting);
    }

    void update_progress(progress_info info) {
        get_host_data(info.peer).update_progress(info);
    }

    void add_session_info(session_info session) {
        auto& data = get_or_create_host_data(session.peer);
        data.add_session_info(std::move(session));
    }

    std::vector<session_info> get_all_session_info() {
        std::vector<session_info> result;
        for (auto& x : _peer_sessions) {
            auto s = x.second.get_all_session_info();
            std::move(s.begin(), s.end(), std::back_inserter(result));
        }
        return result;
    }

public:
    void transfer_files(inet_address to, std::vector<stream_session::ss_table_streaming_sections> sstable_details) {
        host_streaming_data& session_list = get_or_create_host_data(to);
        if (_connections_per_host > 1) {
            abort();
#if 0
            List<List<StreamSession.SSTableStreamingSections>> buckets = sliceSSTableDetails(sstableDetails);

            for (List<StreamSession.SSTableStreamingSections> subList : buckets)
            {
                StreamSession session = sessionList.get_or_create_next_session(to, to);
                session.addTransferFiles(subList);
            }
#endif
        } else {
            auto& session = session_list.get_or_create_next_session(to, to);
            session.add_transfer_files(sstable_details);
        }
    }

private:
#if 0
    private List<List<StreamSession.SSTableStreamingSections>> sliceSSTableDetails(Collection<StreamSession.SSTableStreamingSections> sstableDetails)
    {
        // There's no point in divvying things up into more buckets than we have sstableDetails
        int targetSlices = Math.min(sstableDetails.size(), connectionsPerHost);
        int step = Math.round((float) sstableDetails.size() / (float) targetSlices);
        int index = 0;

        List<List<StreamSession.SSTableStreamingSections>> result = new ArrayList<>();
        List<StreamSession.SSTableStreamingSections> slice = null;
        Iterator<StreamSession.SSTableStreamingSections> iter = sstableDetails.iterator();
        while (iter.hasNext())
        {
            StreamSession.SSTableStreamingSections streamSession = iter.next();

            if (index % step == 0)
            {
                slice = new ArrayList<>();
                result.add(slice);
            }
            slice.add(streamSession);
            ++index;
            iter.remove();
        }

        return result;
    }

#endif
    host_streaming_data& get_host_data(inet_address peer) {
        auto it = _peer_sessions.find(peer);
        if (it == _peer_sessions.end()) {
            throw std::runtime_error(sprint("Unknown peer requested: %s", peer));
        }
        return it->second;
    }

    host_streaming_data& get_or_create_host_data(inet_address peer) {
        _peer_sessions[peer] = host_streaming_data(_connections_per_host, _keep_ss_table_level);
        return _peer_sessions[peer];
    }

#if 0
    private static class StreamSessionConnector implements Runnable
    {
        private final StreamSession session;
        public StreamSessionConnector(StreamSession session)
        {
            this.session = session;
        }

        @Override
        public void run()
        {
            session.start();
            logger.info("[Stream #{}, ID#{}] Beginning stream session with {}", session.planId(), session.sessionIndex(), session.peer);
        }
    }
#endif

private:
    class host_streaming_data {
        using inet_address = gms::inet_address;
    private:
        std::map<int, stream_session> _stream_sessions;
        std::map<int, session_info> _session_infos;
        int _last_returned = -1;
        int _connections_per_host;
        bool _keep_ss_table_level;

    public:
        host_streaming_data() = default;

        host_streaming_data(int connections_per_host, bool keep_ss_table_level)
            : _connections_per_host(connections_per_host)
            , _keep_ss_table_level(keep_ss_table_level) {
        }

        bool has_active_sessions();

        stream_session& get_or_create_next_session(inet_address peer, inet_address connecting) {
            // create
            int size = _stream_sessions.size();
            if (size < _connections_per_host) {
                auto session = stream_session(peer, connecting, size, _keep_ss_table_level);
                _stream_sessions.emplace(++_last_returned, std::move(session));
                return _stream_sessions[_last_returned];
            // get
            } else {
                if (_last_returned >= (size - 1)) {
                    _last_returned = 0;
                }
                return _stream_sessions[_last_returned++];
            }
        }
#if 0
        public void connectAllStreamSessions()
        {
            for (StreamSession session : streamSessions.values())
            {
                streamExecutor.execute(new StreamSessionConnector(session));
            }
        }
#endif

        std::vector<stream_session> get_all_stream_sessions() {
            std::vector<stream_session> sessions;
            for (auto& x : _stream_sessions) {
                sessions.push_back(x.second);
            }
            return sessions;
        }

        stream_session& get_or_create_session_by_id(inet_address peer, int id, inet_address connecting) {
            auto it = _stream_sessions.find(id);
            if (it == _stream_sessions.end()) {
                it = _stream_sessions.emplace(id, stream_session(peer, connecting, id, _keep_ss_table_level)).first;
            }
            return it->second;
        }

        void update_progress(progress_info info) {
            auto it = _session_infos.find(info.session_index);
            if (it != _session_infos.end()) {
                it->second.update_progress(std::move(info));
            }
        }

        void add_session_info(session_info info) {
            _session_infos[info.session_index] = std::move(info);
        }

        std::vector<session_info> get_all_session_info() {
            std::vector<session_info> sessions;
            for (auto& x : _session_infos) {
                sessions.push_back(x.second);
            }
            return sessions;
        }
    };
};

} // namespace streaming
<|endoftext|>