<commit_before>#include "writer/verilog/module.h"

#include "design/design_util.h"
#include "iroha/i_design.h"
#include "iroha/resource_params.h"
#include "iroha/stl_util.h"
#include "writer/connection.h"
#include "writer/module_template.h"
#include "writer/verilog/channel.h"
#include "writer/verilog/dataflow_table.h"
#include "writer/verilog/foreign_reg.h"
#include "writer/verilog/ports.h"
#include "writer/verilog/table.h"
#include "writer/verilog/verilog_writer.h"

namespace iroha {
namespace writer {
namespace verilog {

Module::Module(const IModule *i_mod, const VerilogWriter *writer,
	       const Connection &conn,
	       EmbeddedModules *embed, Names *names)
  : i_mod_(i_mod), writer_(writer), conn_(conn), embed_(embed), names_(names),
    parent_(nullptr) {
  tmpl_.reset(new ModuleTemplate);
  ports_.reset(new Ports);
  reset_polarity_ = ResolveResetPolarity();
  reset_name_ = i_mod->GetParams()->GetResetName();
  if (reset_name_.empty()) {
    if (reset_polarity_) {
      reset_name_ = "rst";
    } else {
      reset_name_ = "rst_n";
    }
  }
  name_ = i_mod_->GetDesign()->GetParams()->GetModuleNamePrefix()
    + i_mod->GetName();
}

Module::~Module() {
  STLDeleteValues(&tables_);
}

void Module::Write(ostream &os) {
  os << "\n// Module " << i_mod_->GetId() << ";\n"
     << "module " << GetName() << "(";
  ports_->Output(Ports::PORT_NAME, os);
  os << ");\n";
  ports_->Output(Ports::PORT_TYPE, os);
  os << "\n";

  os << "  // State decls\n"
     << tmpl_->GetContents(kStateDeclSection)
     << "  // State vars\n"
     << tmpl_->GetContents(kStateVarSection)
     << "  // Registers\n"
     << tmpl_->GetContents(kRegisterSection)
     << "  // Resources\n"
     << tmpl_->GetContents(kResourceSection)
     << "  // Insn wires\n"
     << tmpl_->GetContents(kInsnWireDeclSection)
     << "  // Insn assigns\n"
     << tmpl_->GetContents(kInsnWireValueSection);
  os << "\n";

  for (auto *tab : tables_) {
    tab->Write(os);
  }
  os << tmpl_->GetContents(kEmbeddedInstanceSection);
  for (Module *child : child_modules_) {
    // mod inst_mod(...);
    const IModule *child_imod = child->GetIModule();
    string prefix = i_mod_->GetDesign()->GetParams()->GetModuleNamePrefix();
    os << "  " << prefix << child_imod->GetName() << " "
       << "inst_" << child_imod->GetName() << "(";
    os << ChildModuleInstSectionContents(child, false);
    os << ");\n";
  }
  os << "\nendmodule\n";
}

bool Module::GetResetPolarity() const {
  return reset_polarity_;
}

Module *Module::GetParentModule() const {
  return parent_;
}

void Module::SetParentModule(Module *parent) {
  parent_ = parent;
}

const IModule *Module::GetIModule() const {
  return i_mod_;
}

Ports *Module::GetPorts() const {
  return ports_.get();
}

void Module::PrepareTables() {
  for (auto *i_table : i_mod_->tables_) {
    Table *tab;
    IInsn *insn = DesignUtil::FindDataFlowInInsn(i_table);
    if (insn) {
      tab = new DataFlowTable(i_table, ports_.get(), this, embed_,
			      names_, tmpl_.get());
    } else {
      tab = new Table(i_table, ports_.get(), this, embed_, names_,
		      tmpl_.get());
    }
    tables_.push_back(tab);
  }
  for (Table *tab : tables_) {
    tab->CollectNames();
  }
}

void Module::Build() {
  ports_->AddPort("clk", Port::INPUT_CLK, 0);
  ports_->AddPort(reset_name_, Port::INPUT_RESET, 0);

  for (Table *tab : tables_) {
    tab->Build();
  }

  const ChannelInfo *ci = conn_.GetChannelInfo(i_mod_);
  if (ci != nullptr) {
    Channel::BuildChannelPorts(*ci, ports_.get());
    Channel::BuildRootWire(*ci, this);
  }
  const RegConnectionInfo *ri = conn_.GetRegConnectionInfo(i_mod_);
  if (ri != nullptr) {
    ForeignReg::BuildPorts(*ri, ports_.get(), names_);
    ForeignReg::BuildRegWire(*ri, this);
  }
}

void Module::BuildChildModuleInstSection(vector<Module *> &child_mods) {
  child_modules_ = child_mods;

  // Builds port connections.
  for (auto *child_mod : child_modules_) {
    string current_content = ChildModuleInstSectionContents(child_mod, true);
    ostream &is = ChildModuleInstSectionStream(child_mod);
    is << "." << child_mod->GetPorts()->GetClk()
       << "(" << GetPorts()->GetClk() << ")";
    is << ", ." << child_mod->GetPorts()->GetReset()
       << "(" << GetPorts()->GetReset() << ")";
    is << current_content;
    // Channel
    const IModule *child_imod = child_mod->GetIModule();
    const ChannelInfo *ci = conn_.GetChannelInfo(i_mod_);
    if (ci != nullptr) {
      Channel::BuildChildChannelWire(*ci, child_imod, is);
    }
    // Registers
    const RegConnectionInfo *ri = conn_.GetRegConnectionInfo(child_imod);
    if (ri != nullptr) {
      ForeignReg::BuildChildWire(*ri, child_mod->GetNames(), is);
    }
  }
}

bool Module::ResolveResetPolarity() {
  for (const IModule *mod = i_mod_; mod != nullptr;
       mod = mod->GetParentModule()) {
    if (mod->GetParams()->HasResetPolarity()) {
      return mod->GetParams()->GetResetPolarity();
    }
  }
  // This may return the default value.
  return i_mod_->GetDesign()->GetParams()->GetResetPolarity();
}

ostream &Module::ChildModuleInstSectionStream(Module *child) const {
  return tmpl_->GetStream(kSubModuleSection +
			  Util::Itoa(child->GetIModule()->GetId()));
}

string Module::ChildModuleInstSectionContents(Module *child, bool clear) const {
  string section = kSubModuleSection +
    Util::Itoa(child->GetIModule()->GetId());
  string s = tmpl_->GetContents(section);
  if (clear) {
    tmpl_->Clear(section);
  }
  return s;
}

ModuleTemplate *Module::GetModuleTemplate() const {
  return tmpl_.get();
}

const string &Module::GetName() const {
  return name_;
}

const Connection &Module::GetConnection() const {
  return conn_;
}

Names *Module::GetNames() const {
  return names_;
}

Module *Module::GetByIModule(const IModule *mod) const {
  return writer_->GetByIModule(mod);
}

}  // namespace verilog
}  // namespace writer
}  // namespace iroha
<commit_msg>Add module name after endmodule.<commit_after>#include "writer/verilog/module.h"

#include "design/design_util.h"
#include "iroha/i_design.h"
#include "iroha/resource_params.h"
#include "iroha/stl_util.h"
#include "writer/connection.h"
#include "writer/module_template.h"
#include "writer/verilog/channel.h"
#include "writer/verilog/dataflow_table.h"
#include "writer/verilog/foreign_reg.h"
#include "writer/verilog/ports.h"
#include "writer/verilog/table.h"
#include "writer/verilog/verilog_writer.h"

namespace iroha {
namespace writer {
namespace verilog {

Module::Module(const IModule *i_mod, const VerilogWriter *writer,
	       const Connection &conn,
	       EmbeddedModules *embed, Names *names)
  : i_mod_(i_mod), writer_(writer), conn_(conn), embed_(embed), names_(names),
    parent_(nullptr) {
  tmpl_.reset(new ModuleTemplate);
  ports_.reset(new Ports);
  reset_polarity_ = ResolveResetPolarity();
  reset_name_ = i_mod->GetParams()->GetResetName();
  if (reset_name_.empty()) {
    if (reset_polarity_) {
      reset_name_ = "rst";
    } else {
      reset_name_ = "rst_n";
    }
  }
  name_ = i_mod_->GetDesign()->GetParams()->GetModuleNamePrefix()
    + i_mod->GetName();
}

Module::~Module() {
  STLDeleteValues(&tables_);
}

void Module::Write(ostream &os) {
  os << "\n// Module " << i_mod_->GetId() << ";\n"
     << "module " << GetName() << "(";
  ports_->Output(Ports::PORT_NAME, os);
  os << ");\n";
  ports_->Output(Ports::PORT_TYPE, os);
  os << "\n";

  os << "  // State decls\n"
     << tmpl_->GetContents(kStateDeclSection)
     << "  // State vars\n"
     << tmpl_->GetContents(kStateVarSection)
     << "  // Registers\n"
     << tmpl_->GetContents(kRegisterSection)
     << "  // Resources\n"
     << tmpl_->GetContents(kResourceSection)
     << "  // Insn wires\n"
     << tmpl_->GetContents(kInsnWireDeclSection)
     << "  // Insn assigns\n"
     << tmpl_->GetContents(kInsnWireValueSection);
  os << "\n";

  for (auto *tab : tables_) {
    tab->Write(os);
  }
  os << tmpl_->GetContents(kEmbeddedInstanceSection);
  for (Module *child : child_modules_) {
    // mod inst_mod(...);
    const IModule *child_imod = child->GetIModule();
    string prefix = i_mod_->GetDesign()->GetParams()->GetModuleNamePrefix();
    os << "  " << prefix << child_imod->GetName() << " "
       << "inst_" << child_imod->GetName() << "(";
    os << ChildModuleInstSectionContents(child, false);
    os << ");\n";
  }
  os << "\nendmodule // " << GetName() << "\n";
}

bool Module::GetResetPolarity() const {
  return reset_polarity_;
}

Module *Module::GetParentModule() const {
  return parent_;
}

void Module::SetParentModule(Module *parent) {
  parent_ = parent;
}

const IModule *Module::GetIModule() const {
  return i_mod_;
}

Ports *Module::GetPorts() const {
  return ports_.get();
}

void Module::PrepareTables() {
  for (auto *i_table : i_mod_->tables_) {
    Table *tab;
    IInsn *insn = DesignUtil::FindDataFlowInInsn(i_table);
    if (insn) {
      tab = new DataFlowTable(i_table, ports_.get(), this, embed_,
			      names_, tmpl_.get());
    } else {
      tab = new Table(i_table, ports_.get(), this, embed_, names_,
		      tmpl_.get());
    }
    tables_.push_back(tab);
  }
  for (Table *tab : tables_) {
    tab->CollectNames();
  }
}

void Module::Build() {
  ports_->AddPort("clk", Port::INPUT_CLK, 0);
  ports_->AddPort(reset_name_, Port::INPUT_RESET, 0);

  for (Table *tab : tables_) {
    tab->Build();
  }

  const ChannelInfo *ci = conn_.GetChannelInfo(i_mod_);
  if (ci != nullptr) {
    Channel::BuildChannelPorts(*ci, ports_.get());
    Channel::BuildRootWire(*ci, this);
  }
  const RegConnectionInfo *ri = conn_.GetRegConnectionInfo(i_mod_);
  if (ri != nullptr) {
    ForeignReg::BuildPorts(*ri, ports_.get(), names_);
    ForeignReg::BuildRegWire(*ri, this);
  }
}

void Module::BuildChildModuleInstSection(vector<Module *> &child_mods) {
  child_modules_ = child_mods;

  // Builds port connections.
  for (auto *child_mod : child_modules_) {
    string current_content = ChildModuleInstSectionContents(child_mod, true);
    ostream &is = ChildModuleInstSectionStream(child_mod);
    is << "." << child_mod->GetPorts()->GetClk()
       << "(" << GetPorts()->GetClk() << ")";
    is << ", ." << child_mod->GetPorts()->GetReset()
       << "(" << GetPorts()->GetReset() << ")";
    is << current_content;
    // Channel
    const IModule *child_imod = child_mod->GetIModule();
    const ChannelInfo *ci = conn_.GetChannelInfo(i_mod_);
    if (ci != nullptr) {
      Channel::BuildChildChannelWire(*ci, child_imod, is);
    }
    // Registers
    const RegConnectionInfo *ri = conn_.GetRegConnectionInfo(child_imod);
    if (ri != nullptr) {
      ForeignReg::BuildChildWire(*ri, child_mod->GetNames(), is);
    }
  }
}

bool Module::ResolveResetPolarity() {
  for (const IModule *mod = i_mod_; mod != nullptr;
       mod = mod->GetParentModule()) {
    if (mod->GetParams()->HasResetPolarity()) {
      return mod->GetParams()->GetResetPolarity();
    }
  }
  // This may return the default value.
  return i_mod_->GetDesign()->GetParams()->GetResetPolarity();
}

ostream &Module::ChildModuleInstSectionStream(Module *child) const {
  return tmpl_->GetStream(kSubModuleSection +
			  Util::Itoa(child->GetIModule()->GetId()));
}

string Module::ChildModuleInstSectionContents(Module *child, bool clear) const {
  string section = kSubModuleSection +
    Util::Itoa(child->GetIModule()->GetId());
  string s = tmpl_->GetContents(section);
  if (clear) {
    tmpl_->Clear(section);
  }
  return s;
}

ModuleTemplate *Module::GetModuleTemplate() const {
  return tmpl_.get();
}

const string &Module::GetName() const {
  return name_;
}

const Connection &Module::GetConnection() const {
  return conn_;
}

Names *Module::GetNames() const {
  return names_;
}

Module *Module::GetByIModule(const IModule *mod) const {
  return writer_->GetByIModule(mod);
}

}  // namespace verilog
}  // namespace writer
}  // namespace iroha
<|endoftext|>


<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <xenia/kernel/xam_input.h>

#include <xenia/emulator.h>
#include <xenia/hid/hid.h>
#include <xenia/kernel/kernel_state.h>
#include <xenia/kernel/xam_private.h>
#include <xenia/kernel/util/shim_utils.h>

using namespace xe;
using namespace xe::hid;
using namespace xe::kernel;
using namespace xe::kernel::xam;

namespace xe {
namespace kernel {

SHIM_CALL XamResetInactivity_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t unk = SHIM_GET_ARG_32(0);

  XELOGD(
      "XamResetInactivity(%d)",
      unk);

  // Result ignored.
  SHIM_SET_RETURN(0);
}

SHIM_CALL XamEnableInactivityProcessing_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t zero = SHIM_GET_ARG_32(0);
  uint32_t unk = SHIM_GET_ARG_32(2);

  XELOGD(
      "XamEnableInactivityProcessing(%d, %d)",
      zero,
      unk);

  // Expects 0.
  SHIM_SET_RETURN(0);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetcapabilities(v=vs.85).aspx
SHIM_CALL XamInputGetCapabilities_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t flags = SHIM_GET_ARG_32(1);
  uint32_t caps_ptr = SHIM_GET_ARG_32(2);

  XELOGD(
      "XamInputGetCapabilities(%d, %.8X, %.8X)",
      user_index,
      flags,
      caps_ptr);

  if (!caps_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_CAPABILITIES caps;
  X_RESULT result = input_system->GetCapabilities(user_index, flags, caps);
  if (XSUCCEEDED(result)) {
    caps.Write(SHIM_MEM_BASE, caps_ptr);
  }
  SHIM_SET_RETURN(result);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetstate(v=vs.85).aspx
SHIM_CALL XamInputGetState_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t state_ptr = SHIM_GET_ARG_32(1);

  XELOGD(
      "XamInputGetState(%d, %.8X)",
      user_index,
      state_ptr);

  // Games call this with a NULL state ptr, probably as a query.

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_STATE input_state;
  X_RESULT result = input_system->GetState(user_index, input_state);
  if (XSUCCEEDED(result)) {
    if (state_ptr) {
      input_state.Write(SHIM_MEM_BASE, state_ptr);
    }
  }
  SHIM_SET_RETURN(result);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputsetstate(v=vs.85).aspx
SHIM_CALL XamInputSetState_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t vibration_ptr = SHIM_GET_ARG_32(1);

  XELOGD(
      "XamInputSetState(%d, %.8X)",
      user_index,
      vibration_ptr);

  if (!vibration_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_VIBRATION vibration(SHIM_MEM_BASE, vibration_ptr);
  X_RESULT result = input_system->SetState(user_index, vibration);
  SHIM_SET_RETURN(result);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetkeystroke(v=vs.85).aspx
SHIM_CALL XamInputGetKeystroke_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t flags = SHIM_GET_ARG_32(1);
  uint32_t keystroke_ptr = SHIM_GET_ARG_32(2);

  // http://ffplay360.googlecode.com/svn/Test/Common/AtgXime.cpp
  // user index = index or XUSER_INDEX_ANY
  // flags = XINPUT_FLAG_GAMEPAD (| _ANYUSER | _ANYDEVICE)

  XELOGD(
      "XamInputGetKeystroke(%d, %.8X, %.8X)",
      user_index,
      flags,
      keystroke_ptr);

  if (!keystroke_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_KEYSTROKE keystroke;
  X_RESULT result = input_system->GetKeystroke(user_index, flags, keystroke);
  if (XSUCCEEDED(result)) {
    keystroke.Write(SHIM_MEM_BASE, keystroke_ptr);
  }
  SHIM_SET_RETURN(result);
}

// Same as non-ex, just takes a pointer to user index.
SHIM_CALL XamInputGetKeystrokeEx_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index_ptr = SHIM_GET_ARG_32(0);
  uint32_t flags = SHIM_GET_ARG_32(1);
  uint32_t keystroke_ptr = SHIM_GET_ARG_32(2);

  uint32_t user_index = SHIM_MEM_32(user_index_ptr);

  XELOGD(
      "XamInputGetKeystroke(%.8X(%.d), %.8X, %.8X)",
      user_index_ptr, user_index,
      flags,
      keystroke_ptr);

  if (!keystroke_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_KEYSTROKE keystroke;
  X_RESULT result = input_system->GetKeystroke(user_index, flags, keystroke);
  if (XSUCCEEDED(result)) {
    SHIM_SET_MEM_32(user_index_ptr, keystroke.user_index);
    keystroke.Write(SHIM_MEM_BASE, keystroke_ptr);
  }
  SHIM_SET_RETURN(result);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xam::RegisterInputExports(
    ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xam.xex", XamResetInactivity, state);
  SHIM_SET_MAPPING("xam.xex", XamEnableInactivityProcessing, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetCapabilities, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetState, state);
  SHIM_SET_MAPPING("xam.xex", XamInputSetState, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetKeystroke, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetKeystrokeEx, state);
}
<commit_msg>Fixing input.<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include <xenia/kernel/xam_input.h>

#include <xenia/emulator.h>
#include <xenia/hid/hid.h>
#include <xenia/kernel/kernel_state.h>
#include <xenia/kernel/xam_private.h>
#include <xenia/kernel/util/shim_utils.h>

using namespace xe;
using namespace xe::hid;
using namespace xe::kernel;
using namespace xe::kernel::xam;

namespace xe {
namespace kernel {

SHIM_CALL XamResetInactivity_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t unk = SHIM_GET_ARG_32(0);

  XELOGD(
      "XamResetInactivity(%d)",
      unk);

  // Result ignored.
  SHIM_SET_RETURN(0);
}

SHIM_CALL XamEnableInactivityProcessing_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t zero = SHIM_GET_ARG_32(0);
  uint32_t unk = SHIM_GET_ARG_32(2);

  XELOGD(
      "XamEnableInactivityProcessing(%d, %d)",
      zero,
      unk);

  // Expects 0.
  SHIM_SET_RETURN(0);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetcapabilities(v=vs.85).aspx
SHIM_CALL XamInputGetCapabilities_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t flags = SHIM_GET_ARG_32(1);
  uint32_t caps_ptr = SHIM_GET_ARG_32(2);

  XELOGD(
      "XamInputGetCapabilities(%d, %.8X, %.8X)",
      user_index,
      flags,
      caps_ptr);

  if (!caps_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_CAPABILITIES caps;
  X_RESULT result = input_system->GetCapabilities(user_index, flags, caps);
  if (XSUCCEEDED(result)) {
    caps.Write(SHIM_MEM_BASE, caps_ptr);
  }
  SHIM_SET_RETURN(result);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetstate(v=vs.85).aspx
SHIM_CALL XamInputGetState_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t one = SHIM_GET_ARG_32(1);
  uint32_t state_ptr = SHIM_GET_ARG_32(2);

  XELOGD(
      "XamInputGetState(%d, %.8X, %.8X)",
      user_index,
      one,
      state_ptr);

  // Games call this with a NULL state ptr, probably as a query.

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_STATE input_state;
  X_RESULT result = input_system->GetState(user_index, input_state);
  if (XSUCCEEDED(result)) {
    if (state_ptr) {
      input_state.Write(SHIM_MEM_BASE, state_ptr);
    }
  }
  SHIM_SET_RETURN(result);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputsetstate(v=vs.85).aspx
SHIM_CALL XamInputSetState_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t vibration_ptr = SHIM_GET_ARG_32(1);

  XELOGD(
      "XamInputSetState(%d, %.8X)",
      user_index,
      vibration_ptr);

  if (!vibration_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_VIBRATION vibration(SHIM_MEM_BASE, vibration_ptr);
  X_RESULT result = input_system->SetState(user_index, vibration);
  SHIM_SET_RETURN(result);
}

// http://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetkeystroke(v=vs.85).aspx
SHIM_CALL XamInputGetKeystroke_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index = SHIM_GET_ARG_32(0);
  uint32_t flags = SHIM_GET_ARG_32(1);
  uint32_t keystroke_ptr = SHIM_GET_ARG_32(2);

  // http://ffplay360.googlecode.com/svn/Test/Common/AtgXime.cpp
  // user index = index or XUSER_INDEX_ANY
  // flags = XINPUT_FLAG_GAMEPAD (| _ANYUSER | _ANYDEVICE)

  XELOGD(
      "XamInputGetKeystroke(%d, %.8X, %.8X)",
      user_index,
      flags,
      keystroke_ptr);

  if (!keystroke_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_KEYSTROKE keystroke;
  X_RESULT result = input_system->GetKeystroke(user_index, flags, keystroke);
  if (XSUCCEEDED(result)) {
    keystroke.Write(SHIM_MEM_BASE, keystroke_ptr);
  }
  SHIM_SET_RETURN(result);
}

// Same as non-ex, just takes a pointer to user index.
SHIM_CALL XamInputGetKeystrokeEx_shim(
    PPCContext* ppc_state, KernelState* state) {
  uint32_t user_index_ptr = SHIM_GET_ARG_32(0);
  uint32_t flags = SHIM_GET_ARG_32(1);
  uint32_t keystroke_ptr = SHIM_GET_ARG_32(2);

  uint32_t user_index = SHIM_MEM_32(user_index_ptr);

  XELOGD(
      "XamInputGetKeystroke(%.8X(%.d), %.8X, %.8X)",
      user_index_ptr, user_index,
      flags,
      keystroke_ptr);

  if (!keystroke_ptr) {
    SHIM_SET_RETURN(X_ERROR_BAD_ARGUMENTS);
    return;
  }

  InputSystem* input_system = state->emulator()->input_system();

  X_INPUT_KEYSTROKE keystroke;
  X_RESULT result = input_system->GetKeystroke(user_index, flags, keystroke);
  if (XSUCCEEDED(result)) {
    SHIM_SET_MEM_32(user_index_ptr, keystroke.user_index);
    keystroke.Write(SHIM_MEM_BASE, keystroke_ptr);
  }
  SHIM_SET_RETURN(result);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xam::RegisterInputExports(
    ExportResolver* export_resolver, KernelState* state) {
  SHIM_SET_MAPPING("xam.xex", XamResetInactivity, state);
  SHIM_SET_MAPPING("xam.xex", XamEnableInactivityProcessing, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetCapabilities, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetState, state);
  SHIM_SET_MAPPING("xam.xex", XamInputSetState, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetKeystroke, state);
  SHIM_SET_MAPPING("xam.xex", XamInputGetKeystrokeEx, state);
}
<|endoftext|>


<commit_before>/* ============================================================================
 * Name        : dvarManager.cpp
 * Author(s)   : Dan "WildN00b" Printzell
 * Copyright   : FreeBSD
 * Description : A manager for dvars
 * ============================================================================ */

#include "dvarManager.h"
#include "../log.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>

std::vector<std::string> &split(const std::string &s, char delim,
		std::vector<std::string> &elems) {
	std::stringstream ss(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		elems.push_back(item);
	}
	return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
	std::vector<std::string> elems;
	return split(s, delim, elems);
}

/*
 * Format for file
 * TYPE NAME VALUE
 * like
 * bool cheats false
 * string name WildN00b
 */

void dvarManager::load(std::string file) {
	std::filebuf fb;
	std::istream * in;
	std::string line;
	char tmp[512];
	std::vector<std::string> s;
	std::string stmp;
	unsigned int i;
	if (!fb.open(file.c_str(), std::ios::in)) {
		log::error("Couldn't load dvar file, reverting to standard dvars.");
		return;
	}
	in = new std::istream(&fb);
	while (in) {
		in->getline(tmp, 512);
		if (!tmp[0])
			break;
		line = tmp;
		s = split(line, ' ');
		log::info("'%s' '%s' '%s'", s.at(0).c_str(), s.at(1).c_str(),
				s.at(2).c_str());
		if (s.at(0) == "int")
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED,
							atol(s.at(2).c_str())), true);
		else if (s.at(0) == "string") {
			for (i = 2; i < s.size(); i++)
				stmp += s.at(i);
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED,
							stmp), true);
		} else if (s.at(0) == "double")
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED,
							atof(s.at(2).c_str())), true);
		else if (s.at(0) == "bool")
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED,
							atoi(s.at(2).c_str()) != 0), true);
		else if (s.at(0).c_str()[0] != '#')
			log::warning("[DvarManager] Unknown type %s", s.at(0).c_str());
	}
	fb.close();
	delete in;
}

void dvarManager::save(std::string file) {
	std::filebuf fb;
	dvar * var;
	if (!fb.open(file.c_str(), std::ios::out)) {
		log::error("Couldn't open dvar file for saving!");
		return;
	}
	std::ostream out(&fb);

	for (std::map<std::string, dvar *>::iterator it = this->dvarList->begin();
			it != this->dvarList->end(); ++it) {
		var = it->second;
		if (!(var->getFlag() & DVAR_FLAG_ARCHIVED))
			continue;
		try {
			log::info("name: %s, type: %s, string:%s", var->getName().c_str(),
					var->getValue().type().name(), typeid(std::string).name());
			if (var->getValue().type() == typeid(int64_t))
				out << "int" << " ";
			else if (var->getValue().type() == typeid(std::string))
				out << "string" << " ";
			else if (var->getValue().type() == typeid(double))
				out << "double" << " ";
			else if (var->getValue().type() == typeid(bool))
				out << "bool" << " ";
			else
				continue;
			out << var->getName() << " " << var->getValue() << " " << "\n";
		} catch (std::exception & e) {
			log::error(e.what());
		}
	}

	fb.close();
}

dvarManager::dvarManager(std::string file) {
	this->dvarList = new std::map<std::string, dvar *>();
	this->file = file;
	try {
		load(file);
	} catch (std::exception & e) {
		log::warning("Failed to load dvars!");
	}
}

dvarManager::~dvarManager() {
	try {
		save(this->file);
	} catch (std::exception & e) {
		log::warning("Failed to save dvars!");
	}

	for (std::map<std::string, dvar *>::iterator it = this->dvarList->begin();
			it != this->dvarList->end(); ++it) {
		delete it->second;
	}
	this->dvarList->clear();
	delete this->dvarList;
}

dvar * dvarManager::registerDvar(dvar * var) {
	return registerDvar(var, false);
}

dvar * dvarManager::registerDvar(dvar * var, bool load) {
	dvar * stored = getDvar(var->getName());
	if (load || !stored) {
		removeDvar(var->getName());
		this->dvarList->insert(
				std::pair<std::string, dvar *>(var->getName(), var));
		return var;
	} else {
		stored->setDesc(var->getDesc());
		stored->setFlag(var->getFlag());
		stored->setDefValue(var->getDefValue());
		delete var;
		return stored;
	}
}

void dvarManager::removeDvar(std::string name) {
	try {
		delete this->dvarList->at(name);
		this->dvarList->erase(name);
	} catch (std::exception & e) {
	}
}

dvar * dvarManager::getDvar(std::string name) {
	try {
		return this->dvarList->at(name);
	} catch (std::exception & e) {
		return NULL;
	}
}
<commit_msg>* Fixed codestyle Signed-off-by: Dan Printzell <xwildn00bx@gmail.com><commit_after>/* ============================================================================
 * Name        : dvarManager.cpp
 * Author(s)   : Dan "WildN00b" Printzell
 * Copyright   : FreeBSD
 * Description : A manager for dvars
 * ============================================================================ */

#include "dvarManager.h"
#include "../log.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>

std::vector<std::string> &split(const std::string &s, char delim,
		std::vector<std::string> &elems) {
	std::stringstream ss(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		elems.push_back(item);
	}
	return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
	std::vector<std::string> elems;
	return split(s, delim, elems);
}

/*
 * Format for file
 * TYPE NAME VALUE
 * like
 * bool cheats false
 * string name WildN00b
 */

void dvarManager::load(std::string file) {
	std::filebuf fb;
	std::istream * in;
	std::string line;
	char tmp[512];
	std::vector<std::string> s;
	std::string stmp;
	unsigned int i;
	if (!fb.open(file.c_str(), std::ios::in)) {
		log::error("Couldn't load dvar file, reverting to standard dvars.");
		return;
	}
	in = new std::istream(&fb);
	while (in) {
		in->getline(tmp, 512);
		if (!tmp[0])
			break;
		line = tmp;
		s = split(line, ' ');
		log::info("'%s' '%s' '%s'", s.at(0).c_str(), s.at(1).c_str(),
				s.at(2).c_str());
		if (s.at(0) == "int")
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED,
							atol(s.at(2).c_str())), true);
		else if (s.at(0) == "string") {
			for (i = 2; i < s.size(); i++)
				stmp += s.at(i);
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED, stmp),
					true);
		} else if (s.at(0) == "double")
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED,
							atof(s.at(2).c_str())), true);
		else if (s.at(0) == "bool")
			registerDvar(
					new dvar(s.at(1).c_str(), "",
							DVAR_FLAG_USERCREATED | DVAR_FLAG_ARCHIVED,
							atoi(s.at(2).c_str()) != 0), true);
		else if (s.at(0).c_str()[0] != '#')
			log::warning("[DvarManager] Unknown type %s", s.at(0).c_str());
	}
	fb.close();
	delete in;
}

void dvarManager::save(std::string file) {
	std::filebuf fb;
	dvar * var;
	if (!fb.open(file.c_str(), std::ios::out)) {
		log::error("Couldn't open dvar file for saving!");
		return;
	}
	std::ostream out(&fb);

	for (std::map<std::string, dvar *>::iterator it = this->dvarList->begin();
			it != this->dvarList->end(); ++it) {
		var = it->second;
		if (!(var->getFlag() & DVAR_FLAG_ARCHIVED))
			continue;
		try {
			log::info("name: %s, type: %s, string:%s", var->getName().c_str(),
					var->getValue().type().name(), typeid(std::string).name());
			if (var->getValue().type() == typeid(int64_t))
				out << "int" << " ";
			else if (var->getValue().type() == typeid(std::string))
				out << "string" << " ";
			else if (var->getValue().type() == typeid(double))
				out << "double" << " ";
			else if (var->getValue().type() == typeid(bool))
				out << "bool" << " ";
			else
				continue;
			out << var->getName() << " " << var->getValue() << " " << "\n";
		} catch (std::exception & e) {
			log::error(e.what());
		}
	}

	fb.close();
}

dvarManager::dvarManager(std::string file) {
	this->dvarList = new std::map<std::string, dvar *>();
	this->file = file;
	try {
		load(file);
	} catch (std::exception & e) {
		log::warning("Failed to load dvars!");
	}
}

dvarManager::~dvarManager() {
	try {
		save(this->file);
	} catch (std::exception & e) {
		log::warning("Failed to save dvars!");
	}

	for (std::map<std::string, dvar *>::iterator it = this->dvarList->begin();
			it != this->dvarList->end(); ++it) {
		delete it->second;
	}
	this->dvarList->clear();
	delete this->dvarList;
}

dvar * dvarManager::registerDvar(dvar * var) {
	return registerDvar(var, false);
}

dvar * dvarManager::registerDvar(dvar * var, bool load) {
	dvar * stored = getDvar(var->getName());
	if (load || !stored) {
		removeDvar(var->getName());
		this->dvarList->insert(
				std::pair<std::string, dvar *>(var->getName(), var));
		return var;
	} else {
		stored->setDesc(var->getDesc());
		stored->setFlag(var->getFlag());
		stored->setDefValue(var->getDefValue());
		delete var;
		return stored;
	}
}

void dvarManager::removeDvar(std::string name) {
	try {
		delete this->dvarList->at(name);
		this->dvarList->erase(name);
	} catch (std::exception & e) {
	}
}

dvar * dvarManager::getDvar(std::string name) {
	try {
		return this->dvarList->at(name);
	} catch (std::exception & e) {
		return NULL;
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MABDriver.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: oj $ $Date: 2001-09-19 09:34:43 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_DRIVER_HXX_
#define _CONNECTIVITY_MAB_DRIVER_HXX_

#ifndef _CONNECTIVITY_FILE_ODRIVER_HXX_
#include "file/FDriver.hxx"
#endif

namespace connectivity
{
    namespace mozaddressbook
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
            OMozabDriver_CreateInstance(const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
                    throw( ::com::sun::star::uno::Exception );

        class OMozabDriver : public file::OFileDriver
        {
        public:
            OMozabDriver(const ::com::sun::star::uno::Reference<
                                ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) :
                file::OFileDriver(_rxFactory), m_xMSFactory(_rxFactory){}

            static ::rtl::OUString getImplementationName_Static(  ) throw(::com::sun::star::uno::RuntimeException);
            ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);

            // XDriver
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL
                    connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence<
                                ::com::sun::star::beans::PropertyValue >& info )
                        throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url )
                        throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
            & getMSFactory(void) const
                    { return m_xMSFactory; }
            static sal_Bool acceptsURL_Stat( const ::rtl::OUString& url );
        private:
            const ::com::sun::star::uno::Reference<
                                                ::com::sun::star::lang::XMultiServiceFactory > m_xMSFactory;
        };
    }
}

#endif //_CONNECTIVITY_MAB_DRIVER_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.342); FILE MERGED 2005/09/05 17:25:39 rt 1.5.342.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MABDriver.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:29:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_MAB_DRIVER_HXX_
#define _CONNECTIVITY_MAB_DRIVER_HXX_

#ifndef _CONNECTIVITY_FILE_ODRIVER_HXX_
#include "file/FDriver.hxx"
#endif

namespace connectivity
{
    namespace mozaddressbook
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
            OMozabDriver_CreateInstance(const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
                    throw( ::com::sun::star::uno::Exception );

        class OMozabDriver : public file::OFileDriver
        {
        public:
            OMozabDriver(const ::com::sun::star::uno::Reference<
                                ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) :
                file::OFileDriver(_rxFactory), m_xMSFactory(_rxFactory){}

            static ::rtl::OUString getImplementationName_Static(  ) throw(::com::sun::star::uno::RuntimeException);
            ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);

            // XDriver
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL
                    connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence<
                                ::com::sun::star::beans::PropertyValue >& info )
                        throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url )
                        throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
            & getMSFactory(void) const
                    { return m_xMSFactory; }
            static sal_Bool acceptsURL_Stat( const ::rtl::OUString& url );
        private:
            const ::com::sun::star::uno::Reference<
                                                ::com::sun::star::lang::XMultiServiceFactory > m_xMSFactory;
        };
    }
}

#endif //_CONNECTIVITY_MAB_DRIVER_HXX_

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/memory/scoped_ptr.h"
#include "base/process_util.h"
#include "base/synchronization/waitable_event.h"
#include "base/system_monitor/system_monitor.h"
#include "content/browser/gamepad/gamepad_provider.h"
#include "content/common/gamepad_messages.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace content {

namespace {

using WebKit::WebGamepads;

class MockDataFetcher : public GamepadDataFetcher {
 public:
  MockDataFetcher(WebGamepads& test_data) : read_data_(false, false) {
    test_data_ = test_data;
  }
  virtual void GetGamepadData(WebGamepads* pads,
                              bool devices_changed_hint) OVERRIDE {
    *pads = test_data_;
    read_data_.Signal();
  }

  void WaitForDataRead() { return read_data_.Wait(); }

  WebGamepads test_data_;
  base::WaitableEvent read_data_;
};

// Main test fixture
class GamepadProviderTest : public testing::Test {
 public:
  GamepadProvider* CreateProvider(WebGamepads& test_data) {
#if defined(OS_MACOSX)
    base::SystemMonitor::AllocateSystemIOPorts();
#endif
    system_monitor_.reset(new base::SystemMonitor);
    mock_data_fetcher_ = new MockDataFetcher(test_data);
    provider_ = new GamepadProvider(mock_data_fetcher_);
    return provider_.get();
  }

 protected:
  GamepadProviderTest() {
  }

  MessageLoop main_message_loop_;
  scoped_ptr<base::SystemMonitor> system_monitor_;
  MockDataFetcher* mock_data_fetcher_;
  scoped_refptr<GamepadProvider> provider_;
};

TEST_F(GamepadProviderTest, PollingAccess) {
  WebGamepads test_data;
  test_data.length = 1;
  test_data.items[0].connected = true;
  test_data.items[0].timestamp = 0;
  test_data.items[0].buttonsLength = 1;
  test_data.items[0].axesLength = 2;
  test_data.items[0].buttons[0] = 1.f;
  test_data.items[0].axes[0] = -1.f;
  test_data.items[0].axes[1] = .5f;

  GamepadProvider* provider = CreateProvider(test_data);

  main_message_loop_.RunAllPending();

  mock_data_fetcher_->WaitForDataRead();

  // Renderer-side, pull data out of poll buffer.
  base::SharedMemoryHandle handle =
      provider->GetRendererSharedMemoryHandle(base::GetCurrentProcessHandle());
  scoped_ptr<base::SharedMemory> shared_memory(
      new base::SharedMemory(handle, true));
  EXPECT_TRUE(shared_memory->Map(sizeof(GamepadHardwareBuffer)));
  void* mem = shared_memory->memory();

  GamepadHardwareBuffer* hwbuf = static_cast<GamepadHardwareBuffer*>(mem);
  // See gamepad_hardware_buffer.h for details on the read discipline.
  WebGamepads output;

  base::subtle::Atomic32 version;
  do {
    version = hwbuf->sequence.ReadBegin();
    memcpy(&output, &hwbuf->buffer, sizeof(output));
  } while (hwbuf->sequence.ReadRetry(version));

  EXPECT_EQ(1u, output.length);
  EXPECT_EQ(1u, output.items[0].buttonsLength);
  EXPECT_EQ(1.f, output.items[0].buttons[0]);
  EXPECT_EQ(2u, output.items[0].axesLength);
  EXPECT_EQ(-1.f, output.items[0].axes[0]);
  EXPECT_EQ(0.5f, output.items[0].axes[1]);
}

}  // namespace

} // namespace content
<commit_msg>Disabling GamepadProviderTest.PollingAccess as it crashes<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/memory/scoped_ptr.h"
#include "base/process_util.h"
#include "base/synchronization/waitable_event.h"
#include "base/system_monitor/system_monitor.h"
#include "content/browser/gamepad/gamepad_provider.h"
#include "content/common/gamepad_messages.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace content {

namespace {

using WebKit::WebGamepads;

class MockDataFetcher : public GamepadDataFetcher {
 public:
  MockDataFetcher(WebGamepads& test_data) : read_data_(false, false) {
    test_data_ = test_data;
  }
  virtual void GetGamepadData(WebGamepads* pads,
                              bool devices_changed_hint) OVERRIDE {
    *pads = test_data_;
    read_data_.Signal();
  }

  void WaitForDataRead() { return read_data_.Wait(); }

  WebGamepads test_data_;
  base::WaitableEvent read_data_;
};

// Main test fixture
class GamepadProviderTest : public testing::Test {
 public:
  GamepadProvider* CreateProvider(WebGamepads& test_data) {
#if defined(OS_MACOSX)
    base::SystemMonitor::AllocateSystemIOPorts();
#endif
    system_monitor_.reset(new base::SystemMonitor);
    mock_data_fetcher_ = new MockDataFetcher(test_data);
    provider_ = new GamepadProvider(mock_data_fetcher_);
    return provider_.get();
  }

 protected:
  GamepadProviderTest() {
  }

  MessageLoop main_message_loop_;
  scoped_ptr<base::SystemMonitor> system_monitor_;
  MockDataFetcher* mock_data_fetcher_;
  scoped_refptr<GamepadProvider> provider_;
};

// Crashes. http://crbug.com/106163
TEST_F(GamepadProviderTest, DISABLED_PollingAccess) {
  WebGamepads test_data;
  test_data.length = 1;
  test_data.items[0].connected = true;
  test_data.items[0].timestamp = 0;
  test_data.items[0].buttonsLength = 1;
  test_data.items[0].axesLength = 2;
  test_data.items[0].buttons[0] = 1.f;
  test_data.items[0].axes[0] = -1.f;
  test_data.items[0].axes[1] = .5f;

  GamepadProvider* provider = CreateProvider(test_data);

  main_message_loop_.RunAllPending();

  mock_data_fetcher_->WaitForDataRead();

  // Renderer-side, pull data out of poll buffer.
  base::SharedMemoryHandle handle =
      provider->GetRendererSharedMemoryHandle(base::GetCurrentProcessHandle());
  scoped_ptr<base::SharedMemory> shared_memory(
      new base::SharedMemory(handle, true));
  EXPECT_TRUE(shared_memory->Map(sizeof(GamepadHardwareBuffer)));
  void* mem = shared_memory->memory();

  GamepadHardwareBuffer* hwbuf = static_cast<GamepadHardwareBuffer*>(mem);
  // See gamepad_hardware_buffer.h for details on the read discipline.
  WebGamepads output;

  base::subtle::Atomic32 version;
  do {
    version = hwbuf->sequence.ReadBegin();
    memcpy(&output, &hwbuf->buffer, sizeof(output));
  } while (hwbuf->sequence.ReadRetry(version));

  EXPECT_EQ(1u, output.length);
  EXPECT_EQ(1u, output.items[0].buttonsLength);
  EXPECT_EQ(1.f, output.items[0].buttons[0]);
  EXPECT_EQ(2u, output.items[0].axesLength);
  EXPECT_EQ(-1.f, output.items[0].axes[0]);
  EXPECT_EQ(0.5f, output.items[0].axes[1]);
}

}  // namespace

} // namespace content
<|endoftext|>


<commit_before>// Demonstration of parsing parts of the SPEF interconnect parasitic format
// to accompany "Analyzing On-Chip Interconnect with Modern C++"
// Author: Jeff Trull <edaskel@att.net>

/*
Copyright (c) 2014 Jeffrey E. Trull

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <iostream>
#include <string>
#include <map>

#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

#include "ckt_graph.h"

// parse "name map" and res/cap entries
std::string name_map_text = R"NMT(
*NAME_MAP
*100 SOME/HIERARCHICAL/PATH/NAME
*101 other_name_at_top_level
)NMT";

// resistance entries
std::string res_section_text = R"RST(
*RES
1 *100:1 *100:2 3.14
2 *101:2 *100:3 2.71
*END
)RST";

struct resistor_t {
    std::string n1;
    std::string n2;
    resistor_value_t value;
};

struct ckt_builder {
    void add_component(std::string const& nname1,
                       std::string const& nname2,
                       resistor_value_t value) {
        using namespace boost;
        // map names back to vertices
        ckt_graph_t::vertex_descriptor n1, n2;
        auto n1_it = node_map_.find(nname1);
        if (n1_it == node_map_.end()) {
            n1 = add_vertex(nname1, g_);
            node_map_.emplace(nname1, n1);
        } else {
            n1 = n1_it->second;
        }
        auto n2_it = node_map_.find(nname2);
        if (n2_it == node_map_.end()) {
            n2 = add_vertex(nname2, g_);
            node_map_.emplace(nname2, n2);
        } else {
            n2 = n2_it->second;
        }
        add_edge(n1, n2, value, g_);
    }

    ckt_builder(ckt_graph_t& g) : g_(g) {}
private:
    ckt_graph_t& g_;
    std::map<std::string, ckt_graph_t::vertex_descriptor> node_map_;
};

int main() {
    using namespace std;
    using namespace boost;

    stringstream nmstream(name_map_text);
    nmstream.unsetf(ios::skipws);                  // we *do* want the whitespace
    spirit::istream_iterator nmbeg(nmstream), end; // end is a "sentinel", takes no data

    using spirit::lit;
    namespace phx = boost::phoenix;
    using namespace boost::spirit::qi;
    symbols<char, std::string> name_map_symtab;

    typedef rule<spirit::istream_iterator, std::string()> name_rule;
    name_rule nm_num  = '*' >> +digit;
    name_rule nm_name = +char_("a-zA-Z0-9/_");
    phrase_parse(nmbeg, end,                                    // input range
                 lit("*NAME_MAP") >>                            // grammar begins
                 *(nm_num >> nm_name)[
                     phx::bind(name_map_symtab.add, _1, _2)],   // action for line
                 space);                                        // "skipper"

    cout << "contents of name map:\n";
    name_map_symtab.for_each([name_map_symtab](std::string const& s, std::string const& d) {
            cout << s << " => " << d << endl;
        });

    ckt_graph_t parsed_circuit;
    ckt_builder builder(parsed_circuit);

    // Now parse some representative resistors using the symbol table
    quantity<si::resistance> r_unit(1.0 * units::si::kilo  * units::si::ohms);
    stringstream rstream(res_section_text);
    rstream.unsetf(ios::skipws);
    spirit::istream_iterator rbeg(rstream), rend;
    phrase_parse(rbeg, rend,
                 lit("*RES") >>
                 *(omit[uint_] >>
                   '*' >> as_string[name_map_symtab >> char_(':') >> lexeme[+alnum]] >>
                   '*' >> as_string[name_map_symtab >> char_(':') >> lexeme[+alnum]] >>
                   double_)[phx::bind(&ckt_builder::add_component, phx::ref(builder),
                                      _1, _2, _3 * phx::cref(r_unit))]
                 >> lit("*END"),
                 space);

    cout << "circuit graph edges:" << endl;
    for (auto e : make_iterator_range(edges(parsed_circuit))) {
        cout << parsed_circuit[source(e, parsed_circuit)] << " -> ";
        cout << parsed_circuit[target(e, parsed_circuit)] << " value ";
        cout << parsed_circuit[e] << endl;
    }
}
<commit_msg>scrub other spirit grammar to remove skipper/lexeme obfuscation<commit_after>// Demonstration of parsing parts of the SPEF interconnect parasitic format
// to accompany "Analyzing On-Chip Interconnect with Modern C++"
// Author: Jeff Trull <edaskel@att.net>

/*
Copyright (c) 2014 Jeffrey E. Trull

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <iostream>
#include <string>
#include <map>

#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

#include "ckt_graph.h"

// parse "name map" and res/cap entries
std::string name_map_text = R"NMT(
*NAME_MAP
*100 SOME/HIERARCHICAL/PATH/NAME
*101 other_name_at_top_level
)NMT";

// resistance entries
std::string res_section_text = R"RST(
*RES
1 *100:1 *100:2 3.14
2 *101:2 *100:3 2.71
*END
)RST";

struct resistor_t {
    std::string n1;
    std::string n2;
    resistor_value_t value;
};

struct ckt_builder {
    void add_component(std::string const& nname1,
                       std::string const& nname2,
                       resistor_value_t value) {
        using namespace boost;
        // map names back to vertices
        ckt_graph_t::vertex_descriptor n1, n2;
        auto n1_it = node_map_.find(nname1);
        if (n1_it == node_map_.end()) {
            n1 = add_vertex(nname1, g_);
            node_map_.emplace(nname1, n1);
        } else {
            n1 = n1_it->second;
        }
        auto n2_it = node_map_.find(nname2);
        if (n2_it == node_map_.end()) {
            n2 = add_vertex(nname2, g_);
            node_map_.emplace(nname2, n2);
        } else {
            n2 = n2_it->second;
        }
        add_edge(n1, n2, value, g_);
    }

    ckt_builder(ckt_graph_t& g) : g_(g) {}
private:
    ckt_graph_t& g_;
    std::map<std::string, ckt_graph_t::vertex_descriptor> node_map_;
};

int main() {
    using namespace std;
    using namespace boost;

    stringstream nmstream(name_map_text);
    nmstream.unsetf(ios::skipws);                  // we *do* want the whitespace
    spirit::istream_iterator nmbeg(nmstream), end; // end is a "sentinel", takes no data

    using spirit::lit;
    namespace phx = boost::phoenix;
    using namespace boost::spirit::qi;
    symbols<char, std::string> name_map_symtab;

    typedef rule<spirit::istream_iterator, std::string()> name_rule;
    name_rule nm_num  = '*' >> +digit;
    name_rule nm_name = +char_("a-zA-Z0-9/_");
    phrase_parse(nmbeg, end,                                    // input range
                 lit("*NAME_MAP") >>                            // grammar begins
                 *(nm_num >> nm_name)[
                     phx::bind(name_map_symtab.add, _1, _2)],   // action for line
                 space);                                        // "skipper"

    cout << "contents of name map:\n";
    name_map_symtab.for_each([name_map_symtab](std::string const& s, std::string const& d) {
            cout << s << " => " << d << endl;
        });

    ckt_graph_t parsed_circuit;
    ckt_builder builder(parsed_circuit);

    // Now parse some representative resistors using the symbol table
    quantity<si::resistance> r_unit(1.0 * units::si::kilo  * units::si::ohms);
    stringstream rstream(res_section_text);
    rstream.unsetf(ios::skipws);
    spirit::istream_iterator rbeg(rstream), rend;
    name_rule node_with_symtab = '*' >> name_map_symtab >> char_(':') >> +alnum;
    phrase_parse(rbeg, rend,
                 lit("*RES") >>
                 *(omit[uint_] >> node_with_symtab >> node_with_symtab >> double_)[
                     phx::bind(&ckt_builder::add_component, phx::ref(builder),
                               _1, _2, _3 * phx::cref(r_unit))]
                 >> lit("*END"),
                 space);

    cout << "circuit graph edges:" << endl;
    for (auto e : make_iterator_range(edges(parsed_circuit))) {
        cout << parsed_circuit[source(e, parsed_circuit)] << " -> ";
        cout << parsed_circuit[target(e, parsed_circuit)] << " value ";
        cout << parsed_circuit[e] << endl;
    }
}
<|endoftext|>


<commit_before>// A very small replacement for boost::tuple
// (c) Alexander Gessler, 2008 [alexander.gessler@gmx.net]

#ifndef BOOST_TUPLE_INCLUDED
#define BOOST_TUPLE_INCLUDED

namespace boost	{
	namespace detail	{

		// Represents an empty tuple slot (up to 5 supported)
		struct nulltype {};

		// For readable error messages
		struct tuple_component_idx_out_of_bounds;

		// To share some code for the const/nonconst versions of the getters
		template <bool b, typename T>
		struct ConstIf {
			typedef T t;
		};

		template <typename T>
		struct ConstIf<true,T> {
			typedef const T t;
		};

		// Predeclare some stuff
		template <typename, unsigned, typename, bool, unsigned> struct value_getter;

		// Helper to obtain the type of a tuple element
		template <typename T, unsigned NIDX, typename TNEXT, unsigned N /*= 0*/>
		struct type_getter	{
			typedef type_getter<typename TNEXT::type,NIDX+1,typename TNEXT::next_type,N> next_elem_getter;
			typedef typename next_elem_getter::type type;
		};

		template <typename T, unsigned NIDX, typename TNEXT >
		struct type_getter <T,NIDX,TNEXT,NIDX>	{
			typedef T type;
		};

		// Base class for all explicit specializations of list_elem
		template <typename T, unsigned NIDX, typename TNEXT >
		struct list_elem_base {

			// Store template parameters
			typedef TNEXT next_type;
			typedef T type;

			static const unsigned nidx = NIDX;
		};

		// Represents an element in the tuple component list
		template <typename T, unsigned NIDX, typename TNEXT >
		struct list_elem : list_elem_base<T,NIDX,TNEXT>{

			// Real members
			T me;
			TNEXT next;

			// Get the value of a specific tuple element
			template <unsigned N>
			typename type_getter<T,NIDX,TNEXT,N>::type& get () {
				value_getter <T,NIDX,TNEXT,false,N> s;
				return s(*this);
			}

			// Get the value of a specific tuple element
			template <unsigned N>
			const typename type_getter<T,NIDX,TNEXT,N>::type& get () const {
				value_getter <T,NIDX,TNEXT,true,N> s;
				return s(*this);
			}

			// Explicit cast
			template <typename T2, typename TNEXT2 >
			operator list_elem<T2,NIDX,TNEXT2> () const	{
				list_elem<T2,NIDX,TNEXT2> ret;
				ret.me   = (T2)me;
				ret.next = next;
				return ret;
			}

			// Recursively compare two elements (last element returns always true)
			bool operator == (const list_elem& s) const	{
				return (me == s.me && next == s.next);
			}
		};

		// Represents a non-used tuple element - the very last element processed
		template <typename TNEXT, unsigned NIDX  >
		struct list_elem<nulltype,NIDX,TNEXT> : list_elem_base<nulltype,NIDX,TNEXT> {
			template <unsigned N, bool IS_CONST = true> struct value_getter		{
				/* just dummy members to produce readable error messages */
				tuple_component_idx_out_of_bounds operator () (typename ConstIf<IS_CONST,list_elem>::t& me);
			};
			template <unsigned N> struct type_getter  {
				/* just dummy members to produce readable error messages */
				typedef tuple_component_idx_out_of_bounds type;
			};

			// dummy
			list_elem& operator = (const list_elem& other)	{
				return *this;
			}

			// dummy
			bool operator == (const list_elem& other)	{
				return true;
			}
		};

		// Represents the absolute end of the list
		typedef list_elem<nulltype,0,int> list_end;

		// Helper obtain to query the value of a tuple element
		// NOTE: This can't be a nested class as the compiler won't accept a full or
		// partial specialization of a nested class of a non-specialized template
		template <typename T, unsigned NIDX, typename TNEXT, bool IS_CONST, unsigned N>
		struct value_getter	 {

			// calling list_elem
			typedef list_elem<T,NIDX,TNEXT> outer_elem;

			// typedef for the getter for next element
			typedef value_getter<typename TNEXT::type,NIDX+1,typename TNEXT::next_type,
				IS_CONST, N> next_value_getter;

			typename ConstIf<IS_CONST,typename type_getter<T,NIDX,TNEXT,N>::type>::t&
				operator () (typename ConstIf<IS_CONST,outer_elem >::t& me) {

				next_value_getter s;
				return s(me.next);
			}
		};

		template <typename T, unsigned NIDX, typename TNEXT, bool IS_CONST>
		struct value_getter <T,NIDX,TNEXT,IS_CONST,NIDX>	{
			typedef list_elem<T,NIDX,TNEXT> outer_elem;

			typename ConstIf<IS_CONST,T>::t& operator () (typename ConstIf<IS_CONST,outer_elem >::t& me) {
				return me.me;
			}
		};
	};

	// A very minimal implementation for up to 5 elements
	template <typename T0  = detail::nulltype,
		      typename T1  = detail::nulltype,
			  typename T2  = detail::nulltype,
			  typename T3  = detail::nulltype,
			  typename T4  = detail::nulltype>
	class tuple	{

		template <typename T0b,
		      typename T1b,
			  typename T2b,
			  typename T3b,
			  typename T4b >
		friend class tuple;

	private:

		typedef detail::list_elem<T0,0,
					detail::list_elem<T1,1,
						detail::list_elem<T2,2,
							detail::list_elem<T3,3,
								detail::list_elem<T4,4,
									detail::list_end > > > > > very_long;

		very_long m;

	public:

		// Get a specific tuple element
		template <unsigned N>
		typename detail::type_getter<T0,0,typename very_long::next_type, N>::type& get ()	{
			return m.template get<N>();
		}

		// ... and the const version
		template <unsigned N>
		const typename detail::type_getter<T0,0,typename very_long::next_type, N>::type& get () const	{
			return m.get<N>();
		}

		// comparison operators
		bool operator== (const tuple& other) const	{
			return m == other.m;
		}

		// ... and the other way round
		bool operator!= (const tuple& other) const	{
			return !(m == other.m);
		}

		// cast to another tuple - all single elements must be convertible
		template <typename T0b, typename T1b,typename T2b,typename T3b, typename T4b>
		operator tuple <T0b,T1b,T2b,T3b,T4b> () const {
			tuple <T0b,T1b,T2b,T3b,T4b> s;
			s.m = (typename tuple <T0b,T1b,T2b,T3b,T4b>::very_long)m;
			return s;
		}
	};

	// Another way to access an element ...
	template <unsigned N,typename T0,typename T1,typename T2,typename T3,typename T4>
	inline typename tuple<T0,T1,T2,T3,T4>::very_long::template type_getter<N>::type& get (
			tuple<T0,T1,T2,T3,T4>& m)	{
			return m.get<N>();
		}

	// ... and the const version
	template <unsigned N,typename T0,typename T1,typename T2,typename T3,typename T4>
	inline const typename tuple<T0,T1,T2,T3,T4>::very_long::template type_getter<N>::type& get (
			const tuple<T0,T1,T2,T3,T4>& m)	{
			return m.get<N>();
		}

	// Constructs a tuple with 5 elements
	template <typename T0,typename T1,typename T2,typename T3,typename T4>
	inline tuple <T0,T1,T2,T3,T4> make_tuple (const T0& t0,
		const T1& t1,const T2& t2,const T3& t3,const T4& t4) {

		tuple <T0,T1,T2,T3,T4> t;
		t.get<0>() = t0;
		t.get<1>() = t1;
		t.get<2>() = t2;
		t.get<3>() = t3;
		t.get<4>() = t4;
		return t;
	}

	// Constructs a tuple with 4 elements
	template <typename T0,typename T1,typename T2,typename T3>
	inline tuple <T0,T1,T2,T3> make_tuple (const T0& t0,
		const T1& t1,const T2& t2,const T3& t3) {
		tuple <T0,T1,T2,T3> t;
		t.get<0>() = t0;
		t.get<1>() = t1;
		t.get<2>() = t2;
		t.get<3>() = t3;
		return t;
	}

	// Constructs a tuple with 3 elements
	template <typename T0,typename T1,typename T2>
	inline tuple <T0,T1,T2> make_tuple (const T0& t0,
		const T1& t1,const T2& t2) {
		tuple <T0,T1,T2> t;
		t.get<0>() = t0;
		t.get<1>() = t1;
		t.get<2>() = t2;
		return t;
	}

	// Constructs a tuple with 2 elements
	template <typename T0,typename T1>
	inline tuple <T0,T1> make_tuple (const T0& t0,
		const T1& t1) {
		tuple <T0,T1> t;
		t.get<0>() = t0;
		t.get<1>() = t1;
		return t;
	}

	// Constructs a tuple with 1 elements (well ...)
	template <typename T0>
	inline tuple <T0> make_tuple (const T0& t0) {
		tuple <T0> t;
		t.get<0>() = t0;
		return t;
	}

	// Constructs a tuple with 0 elements (well ...)
	inline tuple <> make_tuple () {
		tuple <> t;
		return t;
	}
};

#endif // !! BOOST_TUPLE_INCLUDED
<commit_msg>Fixed Assimp's BoostWorkAround for GCC.<commit_after>// A very small replacement for boost::tuple
// (c) Alexander Gessler, 2008 [alexander.gessler@gmx.net]

#ifndef BOOST_TUPLE_INCLUDED
#define BOOST_TUPLE_INCLUDED

namespace boost	{
	namespace detail	{

		// Represents an empty tuple slot (up to 5 supported)
		struct nulltype {};

		// For readable error messages
		struct tuple_component_idx_out_of_bounds;

		// To share some code for the const/nonconst versions of the getters
		template <bool b, typename T>
		struct ConstIf {
			typedef T t;
		};

		template <typename T>
		struct ConstIf<true,T> {
			typedef const T t;
		};

		// Predeclare some stuff
		template <typename, unsigned, typename, bool, unsigned> struct value_getter;

		// Helper to obtain the type of a tuple element
		template <typename T, unsigned NIDX, typename TNEXT, unsigned N /*= 0*/>
		struct type_getter	{
			typedef type_getter<typename TNEXT::type,NIDX+1,typename TNEXT::next_type,N> next_elem_getter;
			typedef typename next_elem_getter::type type;
		};

		template <typename T, unsigned NIDX, typename TNEXT >
		struct type_getter <T,NIDX,TNEXT,NIDX>	{
			typedef T type;
		};

		// Base class for all explicit specializations of list_elem
		template <typename T, unsigned NIDX, typename TNEXT >
		struct list_elem_base {

			// Store template parameters
			typedef TNEXT next_type;
			typedef T type;

			static const unsigned nidx = NIDX;
		};

		// Represents an element in the tuple component list
		template <typename T, unsigned NIDX, typename TNEXT >
		struct list_elem : list_elem_base<T,NIDX,TNEXT>{

			// Real members
			T me;
			TNEXT next;

			// Get the value of a specific tuple element
			template <unsigned N>
			typename type_getter<T,NIDX,TNEXT,N>::type& get () {
				value_getter <T,NIDX,TNEXT,false,N> s;
				return s(*this);
			}

			// Get the value of a specific tuple element
			template <unsigned N>
			const typename type_getter<T,NIDX,TNEXT,N>::type& get () const {
				value_getter <T,NIDX,TNEXT,true,N> s;
				return s(*this);
			}

			// Explicit cast
			template <typename T2, typename TNEXT2 >
			operator list_elem<T2,NIDX,TNEXT2> () const	{
				list_elem<T2,NIDX,TNEXT2> ret;
				ret.me   = (T2)me;
				ret.next = next;
				return ret;
			}

			// Recursively compare two elements (last element returns always true)
			bool operator == (const list_elem& s) const	{
				return (me == s.me && next == s.next);
			}
		};

		// Represents a non-used tuple element - the very last element processed
		template <typename TNEXT, unsigned NIDX  >
		struct list_elem<nulltype,NIDX,TNEXT> : list_elem_base<nulltype,NIDX,TNEXT> {
			template <unsigned N, bool IS_CONST = true> struct value_getter		{
				/* just dummy members to produce readable error messages */
				tuple_component_idx_out_of_bounds operator () (typename ConstIf<IS_CONST,list_elem>::t& me);
			};
			template <unsigned N> struct type_getter  {
				/* just dummy members to produce readable error messages */
				typedef tuple_component_idx_out_of_bounds type;
			};

			// dummy
			list_elem& operator = (const list_elem& other)	{
				return *this;
			}

			// dummy
			bool operator == (const list_elem& other)	{
				return true;
			}
		};

		// Represents the absolute end of the list
		typedef list_elem<nulltype,0,int> list_end;

		// Helper obtain to query the value of a tuple element
		// NOTE: This can't be a nested class as the compiler won't accept a full or
		// partial specialization of a nested class of a non-specialized template
		template <typename T, unsigned NIDX, typename TNEXT, bool IS_CONST, unsigned N>
		struct value_getter	 {

			// calling list_elem
			typedef list_elem<T,NIDX,TNEXT> outer_elem;

			// typedef for the getter for next element
			typedef value_getter<typename TNEXT::type,NIDX+1,typename TNEXT::next_type,
				IS_CONST, N> next_value_getter;

			typename ConstIf<IS_CONST,typename type_getter<T,NIDX,TNEXT,N>::type>::t&
				operator () (typename ConstIf<IS_CONST,outer_elem >::t& me) {

				next_value_getter s;
				return s(me.next);
			}
		};

		template <typename T, unsigned NIDX, typename TNEXT, bool IS_CONST>
		struct value_getter <T,NIDX,TNEXT,IS_CONST,NIDX>	{
			typedef list_elem<T,NIDX,TNEXT> outer_elem;

			typename ConstIf<IS_CONST,T>::t& operator () (typename ConstIf<IS_CONST,outer_elem >::t& me) {
				return me.me;
			}
		};
	};

	// A very minimal implementation for up to 5 elements
	template <typename T0  = detail::nulltype,
		      typename T1  = detail::nulltype,
			  typename T2  = detail::nulltype,
			  typename T3  = detail::nulltype,
			  typename T4  = detail::nulltype>
	class tuple	{

		template <typename T0b,
		      typename T1b,
			  typename T2b,
			  typename T3b,
			  typename T4b >
		friend class tuple;

	private:

		typedef detail::list_elem<T0,0,
					detail::list_elem<T1,1,
						detail::list_elem<T2,2,
							detail::list_elem<T3,3,
								detail::list_elem<T4,4,
									detail::list_end > > > > > very_long;

		very_long m;

	public:

		// Get a specific tuple element
		template <unsigned N>
		typename detail::type_getter<T0,0,typename very_long::next_type, N>::type& get ()	{
			return m.template get<N>();
		}

		// ... and the const version
		template <unsigned N>
		const typename detail::type_getter<T0,0,typename very_long::next_type, N>::type& get () const	{
			return m.template get<N>();
		}

		// comparison operators
		bool operator== (const tuple& other) const	{
			return m == other.m;
		}

		// ... and the other way round
		bool operator!= (const tuple& other) const	{
			return !(m == other.m);
		}

		// cast to another tuple - all single elements must be convertible
		template <typename T0b, typename T1b,typename T2b,typename T3b, typename T4b>
		operator tuple <T0b,T1b,T2b,T3b,T4b> () const {
			tuple <T0b,T1b,T2b,T3b,T4b> s;
			s.m = (typename tuple <T0b,T1b,T2b,T3b,T4b>::very_long)m;
			return s;
		}
	};

	// Another way to access an element ...
	template <unsigned N,typename T0,typename T1,typename T2,typename T3,typename T4>
	inline typename tuple<T0,T1,T2,T3,T4>::very_long::template type_getter<N>::type& get (
			tuple<T0,T1,T2,T3,T4>& m)	{
			return m.template get<N>();
		}

	// ... and the const version
	template <unsigned N,typename T0,typename T1,typename T2,typename T3,typename T4>
	inline const typename tuple<T0,T1,T2,T3,T4>::very_long::template type_getter<N>::type& get (
			const tuple<T0,T1,T2,T3,T4>& m)	{
			return m.template get<N>();
		}

	// Constructs a tuple with 5 elements
	template <typename T0,typename T1,typename T2,typename T3,typename T4>
	inline tuple <T0,T1,T2,T3,T4> make_tuple (const T0& t0,
		const T1& t1,const T2& t2,const T3& t3,const T4& t4) {

		tuple <T0,T1,T2,T3,T4> t;
		t.template get<0>() = t0;
		t.template get<1>() = t1;
		t.template get<2>() = t2;
		t.template get<3>() = t3;
		t.template get<4>() = t4;
		return t;
	}

	// Constructs a tuple with 4 elements
	template <typename T0,typename T1,typename T2,typename T3>
	inline tuple <T0,T1,T2,T3> make_tuple (const T0& t0,
		const T1& t1,const T2& t2,const T3& t3) {
		tuple <T0,T1,T2,T3> t;
		t.template get<0>() = t0;
		t.template get<1>() = t1;
		t.template get<2>() = t2;
		t.template get<3>() = t3;
		return t;
	}

	// Constructs a tuple with 3 elements
	template <typename T0,typename T1,typename T2>
	inline tuple <T0,T1,T2> make_tuple (const T0& t0,
		const T1& t1,const T2& t2) {
		tuple <T0,T1,T2> t;
		t.template get<0>() = t0;
		t.template get<1>() = t1;
		t.template get<2>() = t2;
		return t;
	}

	// Constructs a tuple with 2 elements
	template <typename T0,typename T1>
	inline tuple <T0,T1> make_tuple (const T0& t0,
		const T1& t1) {
		tuple <T0,T1> t;
		t.template get<0>() = t0;
		t.template get<1>() = t1;
		return t;
	}

	// Constructs a tuple with 1 elements (well ...)
	template <typename T0>
	inline tuple <T0> make_tuple (const T0& t0) {
		tuple <T0> t;
		t.template get<0>() = t0;
		return t;
	}

	// Constructs a tuple with 0 elements (well ...)
	inline tuple <> make_tuple () {
		tuple <> t;
		return t;
	}
};

#endif // !! BOOST_TUPLE_INCLUDED
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#define ETL_RELAXED
#include "test.hpp"

TEMPLATE_TEST_CASE_2("batch_hint/A/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == input(b, i) * gamma(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/1", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    input = etl::sequence_generator(1.0);
    output = 42;

    output += batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) + input(b, i) * gamma(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/2", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    input = etl::sequence_generator(1.0);
    output = 42;

    output *= batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) * input(b, i) * gamma(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/3", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 109> gamma;
    etl::fast_matrix<Z, 2, 109> input;
    etl::fast_matrix<Z, 2, 109> output;

    gamma = etl::sequence_generator(2.0);
    input = etl::sequence_generator(1.0);

    output = batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 109; ++i) {
            REQUIRE(output(b, i) == gamma(i) * input(b, i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/B/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint((gamma >> input) + beta);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == input(b, i) * gamma(i) + beta(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/B/1", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output += batch_hint((gamma >> input) + beta);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) + (input(b, i) * gamma(i) + beta(i)));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/B/dyn/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint((gamma >> input) + beta);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == input(b, i) * gamma(i) + beta(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/C/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint(gamma >> (input - beta));

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == gamma(i) * (input(b, i) - beta(i)));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/C/1", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output *= batch_hint(gamma >> (input - beta));

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) * gamma(i) * (input(b, i) - beta(i)));
        }
    }
}
<commit_msg>More batch_hint_2d tests<commit_after>//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#define ETL_RELAXED
#include "test.hpp"

TEMPLATE_TEST_CASE_2("batch_hint/A/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == input(b, i) * gamma(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/1", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    input = etl::sequence_generator(1.0);
    output = 42;

    output += batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) + input(b, i) * gamma(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/2", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    input = etl::sequence_generator(1.0);
    output = 42;

    output *= batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) * input(b, i) * gamma(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/3", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 109> gamma;
    etl::fast_matrix<Z, 2, 109> input;
    etl::fast_matrix<Z, 2, 109> output;

    gamma = etl::sequence_generator(2.0);
    input = etl::sequence_generator(1.0);

    output = batch_hint(gamma >> input);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 109; ++i) {
            REQUIRE(output(b, i) == gamma(i) * input(b, i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/4", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 109> gamma;
    etl::fast_matrix<Z, 3, 109> input;
    etl::fast_matrix<Z, 3, 109> output;

    gamma = etl::sequence_generator(2.0);
    input = etl::sequence_generator(1.0);
    output = 42;

    output += batch_hint(gamma >> input);

    for (size_t b = 0; b < 3; ++b) {
        for (size_t i = 0; i < 109; ++i) {
            REQUIRE(output(b, i) == Z(42) + gamma(i) * input(b, i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/5", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 109> gamma;
    etl::fast_matrix<Z, 3, 109> input;
    etl::fast_matrix<Z, 3, 109> output;

    gamma = etl::sequence_generator(2.0);
    input = etl::sequence_generator(1.0);
    output = 42;

    output -= batch_hint(gamma >> input);

    for (size_t b = 0; b < 3; ++b) {
        for (size_t i = 0; i < 109; ++i) {
            REQUIRE(output(b, i) == Z(42) - gamma(i) * input(b, i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/6", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 109> gamma;
    etl::fast_matrix<Z, 3, 109> input;
    etl::fast_matrix<Z, 3, 109> output;

    gamma = etl::sequence_generator(2.0);
    input = etl::sequence_generator(1.0);
    output = 42;

    output *= batch_hint(gamma >> input);

    for (size_t b = 0; b < 3; ++b) {
        for (size_t i = 0; i < 109; ++i) {
            REQUIRE(output(b, i) == Z(42) * gamma(i) * input(b, i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/A/7", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 109> gamma;
    etl::fast_matrix<Z, 3, 109> input;
    etl::fast_matrix<Z, 3, 109> output;

    gamma = etl::sequence_generator(2.0);
    input = etl::sequence_generator(1.0);
    output = 42;

    output /= batch_hint(gamma >> input);

    for (size_t b = 0; b < 3; ++b) {
        for (size_t i = 0; i < 109; ++i) {
            REQUIRE(output(b, i) == Z(42) / (gamma(i) * input(b, i)));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/B/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint((gamma >> input) + beta);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == input(b, i) * gamma(i) + beta(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/B/1", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output += batch_hint((gamma >> input) + beta);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) + (input(b, i) * gamma(i) + beta(i)));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/B/dyn/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint((gamma >> input) + beta);

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == input(b, i) * gamma(i) + beta(i));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/C/0", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output = batch_hint(gamma >> (input - beta));

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == gamma(i) * (input(b, i) - beta(i)));
        }
    }
}

TEMPLATE_TEST_CASE_2("batch_hint/C/1", "[batch_hint]", Z, float, double) {
    etl::fast_matrix<Z, 3> gamma;
    etl::fast_matrix<Z, 3> beta;
    etl::fast_matrix<Z, 2, 3> input;
    etl::fast_matrix<Z, 2, 3> output;

    gamma[0] = Z(1);
    gamma[1] = Z(2);
    gamma[2] = Z(3);

    beta[0] = Z(10);
    beta[1] = Z(20);
    beta[2] = Z(30);

    input = etl::sequence_generator(1.0);
    output = 42;

    output *= batch_hint(gamma >> (input - beta));

    for (size_t b = 0; b < 2; ++b) {
        for (size_t i = 0; i < 3; ++i) {
            REQUIRE(output(b, i) == Z(42) * gamma(i) * (input(b, i) - beta(i)));
        }
    }
}
<|endoftext|>


<commit_before>#include <Kernel/Process.hh>
#include <Kernel/Thread.hh>
#include <Kernel/ProcessContext.hh>

using namespace Kernel;

Process::Process()
   : contextM(new ProcessContext)
{
//   Thread* thread = Thread::createUserThread(this);
//   threadsM.push_back(thread);
//   thread->init();
}

Process::~Process()
{
   // XXX delete threads
   delete contextM;
}

bool
Process::createThread()
{
   printf("Process::createThread\n");

   auto thread = Thread::createUserThread(this);
   threadsM.push_back(thread);
   return thread->init();
}

ProcessContext*
Process::getContext() const
{
   return contextM;
}
<commit_msg>cleanup<commit_after>#include <Kernel/Process.hh>
#include <Kernel/Thread.hh>
#include <Kernel/ProcessContext.hh>

using namespace Kernel;

Process::Process()
   : contextM(new ProcessContext)
{
}

Process::~Process()
{
   // XXX delete threads
   delete contextM;
}

bool
Process::createThread()
{
   printf("Process::createThread\n");

   auto thread = Thread::createUserThread(this);
   threadsM.push_back(thread);
   return thread->init();
}

ProcessContext*
Process::getContext() const
{
   return contextM;
}
<|endoftext|>