<commit_before>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "library/util.h"
#include "library/module.h"
#include "library/trace.h"
#include "compiler/compiler_step_visitor.h"

namespace lean {
struct inline_ext : public environment_extension {
    name_set m_set;
};

struct inline_ext_reg {
    unsigned m_ext_id;
    inline_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<inline_ext>()); }
};

static inline_ext_reg * g_ext = nullptr;
static inline_ext const & get_extension(environment const & env) {
    return static_cast<inline_ext const &>(env.get_extension(g_ext->m_ext_id));
}
static environment update(environment const & env, inline_ext const & ext) {
    return env.update(g_ext->m_ext_id, std::make_shared<inline_ext>(ext));
}

static std::string * g_inline_key = nullptr;

environment add_inline(environment const & env, name const & n) {
    inline_ext ext = get_extension(env);
    ext.m_set.insert(n);
    environment new_env = update(env, ext);
    return module::add(new_env, *g_inline_key, [=](environment const &, serializer & s) { s << n; });
}

static void inline_reader(deserializer & d, shared_environment & senv,
                          std::function<void(asynch_update_fn const &)> &,
                          std::function<void(delayed_update_fn const &)> &) {
    name n;
    d >> n;
    senv.update([=](environment const & env) -> environment {
            inline_ext ext = get_extension(env);
            ext.m_set.insert(n);
            return update(env, ext);
        });
}

bool is_inline(environment const & env, name const & n) {
    return get_extension(env).m_set.contains(n);
}

void initialize_inliner() {
    g_ext        = new inline_ext_reg();
    g_inline_key = new std::string("inline");
    register_module_object_reader(*g_inline_key, inline_reader);
}

void finalize_inliner() {
    delete g_inline_key;
    delete g_ext;
}

class inline_simple_definitions_fn : public compiler_step_visitor {
    /* Return true iff v is of the form (g y_1 ... y_n) where
       y_i is a constant or a variable.
       Moreover, y_i's variables are pairwise distinct. */
    bool is_simple_application(expr const & v) {
        buffer<expr> ys;
        buffer<bool> bitmap;
        expr const & g = get_app_args(v, ys);
        if (!is_constant(g) && !is_var(g))
            return false;
        for (expr const & y : ys) {
            if (!is_var(y) && !is_constant(y))
                return false;
            if (is_var(y)) {
                unsigned vidx = var_idx(y);
                if (vidx >= bitmap.size())
                    bitmap.resize(vidx+1, false);
                if (bitmap[vidx]) {
                    /* y_i's are not pairwise distinct */
                    return false;
                }
                bitmap[vidx] = true;
            }
        }
        return true;
    }

    expr default_visit_app(expr const & e) {
        return compiler_step_visitor::visit_app(e);
    }

    virtual expr visit_app(expr const & e) override {
        expr const & fn = get_app_fn(e);
        if (!is_constant(fn))
            return default_visit_app(e);
        unsigned nargs  = get_app_num_args(e);
        name const & n  = const_name(fn);
        declaration d   = env().get(n);
        if (!d.is_definition() || d.is_theorem())
            return default_visit_app(e);
        expr v = d.get_value();
        unsigned arity = 0;
        while (is_lambda(v)) {
            arity++;
            v = binding_body(v);
        }

        if (arity > nargs) {
            // not fully applied
            return default_visit_app(e);
        }

        if (is_inline(env(), n) || is_simple_application(v)) {
            if (auto r = unfold_term(env(), e))
                return visit(*r);
        }

        if (auto r = ctx().reduce_projection(e)) {
            return visit(*r);
        }

        return default_visit_app(e);
    }

public:
    inline_simple_definitions_fn(environment const & env):compiler_step_visitor(env) {}
};

expr inline_simple_definitions(environment const & env, expr const & e) {
    return inline_simple_definitions_fn(env)(e);
}
}
<commit_msg>feat(compiler/inliner): simplify cases_on and nonrecursive recursor applications when possible<commit_after>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "kernel/inductive/inductive.h"
#include "library/util.h"
#include "library/module.h"
#include "library/trace.h"
#include "library/normalize.h"
#include "compiler/util.h"
#include "compiler/compiler_step_visitor.h"

namespace lean {
struct inline_ext : public environment_extension {
    name_set m_set;
};

struct inline_ext_reg {
    unsigned m_ext_id;
    inline_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<inline_ext>()); }
};

static inline_ext_reg * g_ext = nullptr;
static inline_ext const & get_extension(environment const & env) {
    return static_cast<inline_ext const &>(env.get_extension(g_ext->m_ext_id));
}
static environment update(environment const & env, inline_ext const & ext) {
    return env.update(g_ext->m_ext_id, std::make_shared<inline_ext>(ext));
}

static std::string * g_inline_key = nullptr;

environment add_inline(environment const & env, name const & n) {
    inline_ext ext = get_extension(env);
    ext.m_set.insert(n);
    environment new_env = update(env, ext);
    return module::add(new_env, *g_inline_key, [=](environment const &, serializer & s) { s << n; });
}

static void inline_reader(deserializer & d, shared_environment & senv,
                          std::function<void(asynch_update_fn const &)> &,
                          std::function<void(delayed_update_fn const &)> &) {
    name n;
    d >> n;
    senv.update([=](environment const & env) -> environment {
            inline_ext ext = get_extension(env);
            ext.m_set.insert(n);
            return update(env, ext);
        });
}

bool is_inline(environment const & env, name const & n) {
    return get_extension(env).m_set.contains(n);
}

void initialize_inliner() {
    g_ext        = new inline_ext_reg();
    g_inline_key = new std::string("inline");
    register_module_object_reader(*g_inline_key, inline_reader);
}

void finalize_inliner() {
    delete g_inline_key;
    delete g_ext;
}

class inline_simple_definitions_fn : public compiler_step_visitor {
    /* Return true iff v is of the form (g y_1 ... y_n) where
       y_i is a constant or a variable.
       Moreover, y_i's variables are pairwise distinct. */
    bool is_simple_application(expr const & v) {
        buffer<expr> ys;
        buffer<bool> bitmap;
        expr const & g = get_app_args(v, ys);
        if (!is_constant(g) && !is_var(g))
            return false;
        for (expr const & y : ys) {
            if (!is_var(y) && !is_constant(y))
                return false;
            if (is_var(y)) {
                unsigned vidx = var_idx(y);
                if (vidx >= bitmap.size())
                    bitmap.resize(vidx+1, false);
                if (bitmap[vidx]) {
                    /* y_i's are not pairwise distinct */
                    return false;
                }
                bitmap[vidx] = true;
            }
        }
        return true;
    }

    expr default_visit_app(expr const & e) {
        return compiler_step_visitor::visit_app(e);
    }

    bool is_nonrecursive_recursor(name const & n) {
        if (auto I_name = inductive::is_elim_rule(env(), n)) {
            return !is_recursive_datatype(env(), *I_name);
        }
        return false;
    }

    /* Try to reduce cases_on (and nonrecursive recursor) application
       if major became a constructor */
    expr visit_cases_on_app(expr const & e_0) {
        expr e = default_visit_app(e_0);
        buffer<expr> args;
        expr const & fn = get_app_args(e, args);
        lean_assert(is_constant(fn));
        bool is_cases_on            = is_cases_on_recursor(env(), const_name(fn));
        name const & rec_name       = const_name(fn);
        name const & I_name         = rec_name.get_prefix();
        unsigned nparams            = *inductive::get_num_params(env(), I_name);
        unsigned nindices           = *inductive::get_num_indices(env(), I_name);
        unsigned major_idx;
        if (is_cases_on) {
            major_idx       = nparams + 1 + nindices;
        } else {
            major_idx       = *inductive::get_elim_major_idx(env(), rec_name);
        }
        expr major = beta_reduce(args[major_idx]);
        if (is_constructor_app(env(), major)) {
            /* Major premise became a constructor. So, we should reduce. */
            expr new_e = e;
            if (is_cases_on) {
                /* unfold cases_on */
                if (auto r = unfold_term(env(), new_e))
                    new_e = *r;
                else
                    return e;
            }
            /* reduce */
            if (auto r = ctx().norm_ext(new_e))
                return compiler_step_visitor::visit(beta_reduce(*r));
        }
        return e;
    }

    virtual expr visit_app(expr const & e) override {
        expr const & fn = get_app_fn(e);
        if (!is_constant(fn))
            return default_visit_app(e);
        name const & n  = const_name(fn);
        if (is_cases_on_recursor(env(), n) || is_nonrecursive_recursor(n))
            return visit_cases_on_app(e);
        unsigned nargs  = get_app_num_args(e);
        declaration d   = env().get(n);
        if (!d.is_definition() || d.is_theorem())
            return default_visit_app(e);
        expr v = d.get_value();
        unsigned arity = 0;
        while (is_lambda(v)) {
            arity++;
            v = binding_body(v);
        }

        if (arity > nargs) {
            // not fully applied
            return default_visit_app(e);
        }

        if (is_inline(env(), n) || is_simple_application(v)) {
            if (auto r = unfold_term(env(), e))
                return visit(*r);
        }

        if (auto r = ctx().reduce_projection(e)) {
            return visit(*r);
        }

        return default_visit_app(e);
    }

public:
    inline_simple_definitions_fn(environment const & env):compiler_step_visitor(env) {}
};

expr inline_simple_definitions(environment const & env, expr const & e) {
    return inline_simple_definitions_fn(env)(e);
}
}
<|endoftext|>


<commit_before>// Copyright 2013-2015 Stanford University
//
// Licensed 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.

#include "src/cfg/cfg_transforms.h"

using namespace x64asm;

namespace {

/** Returns true for instructions that induce control flow */
bool is_control(const Instruction& instr) {
  return instr.is_label_defn() || instr.is_any_jump() ||
         instr.is_any_call() || instr.is_any_return() ||
         instr.is_any_loop();
}

/** Returns true for instructions that have non-register side effects */
bool has_side_effects(const x64asm::Instruction& instr) {
  // More instructions have side-effects (ie UD2) but aren't relevant here
  return instr.is_memory_dereference() ||
         (instr.get_opcode() >= DIV_M16 && instr.get_opcode() <= DIVSS_XMM_XMM);
}

} // namespace

namespace stoke {

Cfg& CfgTransforms::remove_unreachable(Cfg& cfg) const {
  // Assume that invariants are satisfied on entry
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  // Remove unreachable instructions one at a time
  for (auto removed = true; removed;) {
    removed = false;
    for (size_t i = 0, ie = cfg.get_code().size(); i < ie; ++i) {
      if (!cfg.is_reachable(cfg.get_loc(i).first)) {
        cfg.get_function().remove(i);
        cfg.recompute();
        removed = true;
        break;
      }
    }
  }

  // Make sure that we've left everything back in a valid state before continuing
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  return cfg;
}

Cfg& CfgTransforms::remove_nop(Cfg& cfg) const {
  // Assume that invariants are satisfied on entry
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  // Remove nops one at a time
  for (auto removed = true; removed;) {
    removed = false;
    for (size_t i = 0, ie = cfg.get_code().size(); i < ie; ++i) {
      if (cfg.get_code()[i].is_nop()) {
        cfg.get_function().remove(i);
        cfg.recompute();
        removed = true;
        break;
      }
    }
  }

  // Make sure that we've left everything back in a valid state before continuing
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());
  return cfg;
}

Cfg& CfgTransforms::remove_redundant(Cfg& cfg) const {
  // Assume that invariants are satisfied on entry
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  // This transformsation subsumes unreachable block removal
  remove_unreachable(cfg);

  // Remove redundant instructions one at a time
  for (auto removed = true; removed;) {
    removed = false;
    for (size_t i = 0, ie = cfg.get_code().size(); i < ie; ++i) {
      const auto& instr = cfg.get_code()[i];

      // Skip instructions that induce control flow or have non-register side effects
      if (is_control(instr) || has_side_effects(instr)) {
        continue;
      }

      // Remove instructions if it doesn't produce a value which is live out afterward
      const auto instr_outputs = cfg.maybe_write_set(instr);
      const auto live_regs_after_instruction = cfg.live_outs(cfg.get_loc(i));
      if ((instr_outputs & live_regs_after_instruction) == RegSet::empty()) {
        cfg.get_function().remove(i);
        cfg.recompute();
        removed = true;
        break;
      }
    }
  }

  // Make sure that we've left everything back in a valid state before continuing
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());
  return cfg;
}

Cfg CfgTransforms::minimal_correct_cfg(const RegSet& def_in, const RegSet& live_out) const {
  Cfg cfg(TUnit(), def_in, live_out);
  const auto diff = cfg.live_outs() - cfg.def_outs();

  // initialize all general purpose registers
  for (auto rit = diff.gp_begin(); rit != diff.gp_end(); ++rit) {
    auto reg = *rit;
    auto type = reg.type();
    if (type == Type::R_64 || type == Type::RAX) {
      cfg.get_function().push_back(Instruction(XOR_R64_R64, {reg, reg}));
    } else if (type == Type::R_32 || type == Type::EAX) {
      cfg.get_function().push_back(Instruction(XOR_R32_R32, {reg, reg}));
    } else if (type == Type::R_16 || type == Type::AX || type == Type::DX) {
      cfg.get_function().push_back(Instruction(XOR_R16_R16, {reg, reg}));
    } else if (type == Type::RL || type == Type::AL || type == Type::CL) {
      cfg.get_function().push_back(Instruction(XOR_RL_RL, {reg, reg}));
    } else if (type == Type::RH) {
      cfg.get_function().push_back(Instruction(XOR_RH_RH, {reg, reg}));
    } else if (type == Type::RB) {
      cfg.get_function().push_back(Instruction(XOR_RB_RB, {reg, reg}));
    }
  }

  // initialize sse registers
  for (auto rit = diff.sse_begin(); rit != diff.sse_end(); ++rit) {
    auto reg = *rit;
    auto type = reg.type();
    if (type == Type::XMM || type == Type::XMM_0) {
      cfg.get_function().push_back(Instruction(PXOR_XMM_XMM, {reg, reg}));
    } else if (type == Type::YMM) {
      cfg.get_function().push_back(Instruction(VPXOR_YMM_YMM_YMM, {reg, reg, reg}));
    }
  }

  // initialize mm registers
  for (auto rit = diff.mm_begin(); rit != diff.mm_end(); ++rit) {
    auto reg = *rit;
    cfg.get_function().push_back(Instruction(PXOR_MM_MM, {reg, reg}));
  }

  // flags
  auto regular = false;
  for (auto rit = diff.flags_begin(); rit != diff.flags_end(); ++rit) {
    auto reg = *rit;
    if ((reg == Constants::eflags_of() ||
         reg == Constants::eflags_zf() ||
         reg == Constants::eflags_sf() ||
         reg == Constants::eflags_af() ||
         reg == Constants::eflags_cf() ||
         reg == Constants::eflags_pf()) && !regular) {
      regular = true;
      cfg.get_function().push_back(Instruction(XOR_R32_R32, {Constants::rax(), Constants::rax()}));
      cfg.get_function().push_back(Instruction(ADD_R32_IMM32, {Constants::rax(), Imm32(0)}));
    }
  }

  cfg.get_function().push_back(RET);
  cfg.recompute();

  // Everything should look good now
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  return cfg;
}

} // namespace stoke
<commit_msg>fix broken minimal_correct_cfg<commit_after>// Copyright 2013-2015 Stanford University
//
// Licensed 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.

#include "src/cfg/cfg_transforms.h"

using namespace x64asm;

namespace {

/** Returns true for instructions that induce control flow */
bool is_control(const Instruction& instr) {
  return instr.is_label_defn() || instr.is_any_jump() ||
         instr.is_any_call() || instr.is_any_return() ||
         instr.is_any_loop();
}

/** Returns true for instructions that have non-register side effects */
bool has_side_effects(const x64asm::Instruction& instr) {
  // More instructions have side-effects (ie UD2) but aren't relevant here
  return instr.is_memory_dereference() ||
         (instr.get_opcode() >= DIV_M16 && instr.get_opcode() <= DIVSS_XMM_XMM);
}

} // namespace

namespace stoke {

Cfg& CfgTransforms::remove_unreachable(Cfg& cfg) const {
  // Assume that invariants are satisfied on entry
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  // Remove unreachable instructions one at a time
  for (auto removed = true; removed;) {
    removed = false;
    for (size_t i = 0, ie = cfg.get_code().size(); i < ie; ++i) {
      if (!cfg.is_reachable(cfg.get_loc(i).first)) {
        cfg.get_function().remove(i);
        cfg.recompute();
        removed = true;
        break;
      }
    }
  }

  // Make sure that we've left everything back in a valid state before continuing
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  return cfg;
}

Cfg& CfgTransforms::remove_nop(Cfg& cfg) const {
  // Assume that invariants are satisfied on entry
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  // Remove nops one at a time
  for (auto removed = true; removed;) {
    removed = false;
    for (size_t i = 0, ie = cfg.get_code().size(); i < ie; ++i) {
      if (cfg.get_code()[i].is_nop()) {
        cfg.get_function().remove(i);
        cfg.recompute();
        removed = true;
        break;
      }
    }
  }

  // Make sure that we've left everything back in a valid state before continuing
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());
  return cfg;
}

Cfg& CfgTransforms::remove_redundant(Cfg& cfg) const {
  // Assume that invariants are satisfied on entry
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  // This transformsation subsumes unreachable block removal
  remove_unreachable(cfg);

  // Remove redundant instructions one at a time
  for (auto removed = true; removed;) {
    removed = false;
    for (size_t i = 0, ie = cfg.get_code().size(); i < ie; ++i) {
      const auto& instr = cfg.get_code()[i];

      // Skip instructions that induce control flow or have non-register side effects
      if (is_control(instr) || has_side_effects(instr)) {
        continue;
      }

      // Remove instructions if it doesn't produce a value which is live out afterward
      const auto instr_outputs = cfg.maybe_write_set(instr);
      const auto live_regs_after_instruction = cfg.live_outs(cfg.get_loc(i));
      if ((instr_outputs & live_regs_after_instruction) == RegSet::empty()) {
        cfg.get_function().remove(i);
        cfg.recompute();
        removed = true;
        break;
      }
    }
  }

  // Make sure that we've left everything back in a valid state before continuing
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());
  return cfg;
}

Cfg CfgTransforms::minimal_correct_cfg(const RegSet& def_in, const RegSet& live_out) const {
  Cfg cfg(TUnit(), def_in, live_out);
  const auto diff = live_out;

  // initialize all general purpose registers
  for (auto rit = diff.gp_begin(); rit != diff.gp_end(); ++rit) {
    auto reg = *rit;
    auto type = reg.type();
    if (type == Type::R_64 || type == Type::RAX) {
      cfg.get_function().push_back(Instruction(XOR_R64_R64, {reg, reg}));
    } else if (type == Type::R_32 || type == Type::EAX) {
      cfg.get_function().push_back(Instruction(XOR_R32_R32, {reg, reg}));
    } else if (type == Type::R_16 || type == Type::AX || type == Type::DX) {
      cfg.get_function().push_back(Instruction(XOR_R16_R16, {reg, reg}));
    } else if (type == Type::RL || type == Type::AL || type == Type::CL) {
      cfg.get_function().push_back(Instruction(XOR_RL_RL, {reg, reg}));
    } else if (type == Type::RH) {
      cfg.get_function().push_back(Instruction(XOR_RH_RH, {reg, reg}));
    } else if (type == Type::RB) {
      cfg.get_function().push_back(Instruction(XOR_RB_RB, {reg, reg}));
    }
  }

  // initialize sse registers
  for (auto rit = diff.sse_begin(); rit != diff.sse_end(); ++rit) {
    auto reg = *rit;
    auto type = reg.type();
    if (type == Type::XMM || type == Type::XMM_0) {
      cfg.get_function().push_back(Instruction(PXOR_XMM_XMM, {reg, reg}));
    } else if (type == Type::YMM) {
      cfg.get_function().push_back(Instruction(VPXOR_YMM_YMM_YMM, {reg, reg, reg}));
    }
  }

  // initialize mm registers
  for (auto rit = diff.mm_begin(); rit != diff.mm_end(); ++rit) {
    auto reg = *rit;
    cfg.get_function().push_back(Instruction(PXOR_MM_MM, {reg, reg}));
  }

  // flags
  auto regular = false;
  for (auto rit = diff.flags_begin(); rit != diff.flags_end(); ++rit) {
    auto reg = *rit;
    if ((reg == Constants::eflags_of() ||
         reg == Constants::eflags_zf() ||
         reg == Constants::eflags_sf() ||
         reg == Constants::eflags_af() ||
         reg == Constants::eflags_cf() ||
         reg == Constants::eflags_pf()) && !regular) {
      regular = true;
      cfg.get_function().push_back(Instruction(XOR_R32_R32, {Constants::rax(), Constants::rax()}));
      cfg.get_function().push_back(Instruction(ADD_R32_IMM32, {Constants::rax(), Imm32(0)}));
    }
  }

  cfg.get_function().push_back(RET);
  cfg.recompute();

  // Everything should look good now
  assert(cfg.check_invariants());
  assert(cfg.get_function().check_invariants());

  return cfg;
}

} // namespace stoke
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "browser/net_log.h"

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/values.h"
#include "content/public/common/content_switches.h"
#include "net/log/net_log_util.h"

namespace brightray {

namespace {

scoped_ptr<base::DictionaryValue> GetConstants() {
  scoped_ptr<base::DictionaryValue> constants = net::GetNetConstants();

  // Adding client information to constants dictionary.
  base::DictionaryValue* client_info = new base::DictionaryValue();
  client_info->SetString(
      "command_line",
      base::CommandLine::ForCurrentProcess()->GetCommandLineString());

  constants->Set("clientInfo", client_info);
  return constants;
}

}  // namespace

NetLog::NetLog() {
  auto command_line = base::CommandLine::ForCurrentProcess();
  if (!command_line->HasSwitch(switches::kLogNetLog))
    return;

  base::FilePath log_path = command_line->GetSwitchValuePath(switches::kLogNetLog);
#if defined(OS_WIN)
  log_file_.reset(_wfopen(log_path.value().c_str(), L"w"));
#elif defined(OS_POSIX)
  log_file_.reset(fopen(log_path.value().c_str(), "w"));
#endif

  if (!log_file_) {
    LOG(ERROR) << "Could not open file: " << log_path.value()
               << "for net logging";
    return;
  }
}

NetLog::~NetLog() {
}

void NetLog::StartLogging(net::URLRequestContext* url_request_context) {
  if (!log_file_)
    return;

  scoped_ptr<base::Value> constants(GetConstants());
  write_to_file_observer_.StartObserving(this, log_file_.Pass(), constants.get(), url_request_context);
}

}  // namespace brightray
<commit_msg>create net log file after context is created<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "browser/net_log.h"

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/values.h"
#include "content/public/common/content_switches.h"
#include "net/log/net_log_util.h"

namespace brightray {

namespace {

scoped_ptr<base::DictionaryValue> GetConstants() {
  scoped_ptr<base::DictionaryValue> constants = net::GetNetConstants();

  // Adding client information to constants dictionary.
  base::DictionaryValue* client_info = new base::DictionaryValue();
  client_info->SetString(
      "command_line",
      base::CommandLine::ForCurrentProcess()->GetCommandLineString());

  constants->Set("clientInfo", client_info);
  return constants;
}

}  // namespace

NetLog::NetLog() {
}

NetLog::~NetLog() {
}

void NetLog::StartLogging(net::URLRequestContext* url_request_context) {
  auto command_line = base::CommandLine::ForCurrentProcess();
  if (!command_line->HasSwitch(switches::kLogNetLog))
    return;

  base::FilePath log_path = command_line->GetSwitchValuePath(switches::kLogNetLog);
#if defined(OS_WIN)
  log_file_.reset(_wfopen(log_path.value().c_str(), L"w"));
#elif defined(OS_POSIX)
  log_file_.reset(fopen(log_path.value().c_str(), "w"));
#endif

  if (!log_file_) {
    LOG(ERROR) << "Could not open file: " << log_path.value()
               << "for net logging";
    return;
  }

  scoped_ptr<base::Value> constants(GetConstants());
  write_to_file_observer_.StartObserving(this,
                                         log_file_.Pass(),
                                         constants.get(),
                                         url_request_context);
}

}  // namespace brightray
<|endoftext|>


<commit_before>#include "filestream_parser.h"

FilestreamParser::FilestreamParser(const std::string& flashstreamFile, const std::string& deviceFile, const uint8_t slaveAddress)
    : m_flashstreamFilename(flashstreamFile)
    , m_i2cInterface(deviceFile, slaveAddress)
{
    // Try to open the file for reading  and load it into a ss buffer
    std::ifstream inputStream(m_flashstreamFilename);
    m_flashstreamBuffer << inputStream.rdbuf();
}

I2CInterface::RET_CODE FilestreamParser::init()
{
    //Setup i2c
    I2CInterface::RET_CODE retCode = m_i2cInterface.init();
    if(retCode != I2CInterface::RET_CODE::SUCCESS)
    {
        std::cout << "Failed i2c init with return code: " << static_cast<int>(retCode) << std::endl;
        return retCode;
    }

    return retCode;
}

I2CInterface::RET_CODE FilestreamParser::flash()
{
    std::cout << "Starting TI FlashStream flasing process." << std::endl;
    std::cout << "Using data file: " << m_flashstreamFilename << std::endl;

    if( validate() )
    {
        std::string token;
        while(std::getline(m_flashstreamBuffer, token, '\n'))
        {
            //Get the key
            char key = token[0];

            switch(key)
            {
                case ';':
                {
                    handleComment(token);
                    break;
                }
                case 'C':
                {
                    I2CInterface::RET_CODE retCode = handleCompare(token);
                    if(retCode != I2CInterface::RET_CODE::SUCCESS)
                    {
                        std::cout << "Failed write because of error code: " << static_cast<int>(retCode) << std::endl;
                        return retCode;
                    }
                    break;
                }
                case 'W':
                {
                    I2CInterface::RET_CODE retCode = handleWrite(token);
                    if(retCode != I2CInterface::RET_CODE::SUCCESS)
                    {
                        std::cout << "Failed write because of error code: " << static_cast<int>(retCode) << std::endl;
                        return retCode;
                    }
                    break;
                }
                case 'X':
                {
                    handleWait(token);
                    break;
                }
                default:
                {
                    std::cout << "Error parsing file. Bad line: " << token << std::endl;
                    break;
                }
            }
        }
    }
    else
    {
        std::cout << "Bad input file." << std::endl;
        return I2CInterface::RET_CODE::FAILED_VALIDATE;
    }

    return I2CInterface::RET_CODE::SUCCESS;

}

bool FilestreamParser::validate()
{
    //Try to parse the file, return false if could not validate
    std::cout << "Validating flash stream file..." << std::endl;

    std::stringstream tmpBuffer;
    tmpBuffer << m_flashstreamBuffer.str();

    std::string token;
    bool isValid = true;
    while(std::getline(tmpBuffer, token, '\n'))
    {
        //Get the key
        char key = token[0];

        switch(key)
        {
            case ';':
            {
                break;
            }
            case 'C':
            {
                break;
            }
            case 'W':
            {
                break;
            }
            case 'X':
            {
                break;
            }
            default:
            {
                std::cout << "Error parsing file. Bad line: " << token << std::endl;
                isValid = false;
                break;
            }
        }
    }
    std::cout << "File is valid" << std::endl;

    return isValid;
}

void FilestreamParser::handleComment(const std::string& commentIn)
{
    //; [comment]
    std::cout << commentIn << std::endl;
}

I2CInterface::RET_CODE FilestreamParser::handleCompare(const std::string& compareLine)
{
    //C: i2cAddr RegAddr Byte0 Byte1 Byte2
    auto split = splitString(compareLine, ' ');

    //get the slave address
    uint8_t slaveAddress = (getHexFromString(split[1]));

    //Bit shift left by one
    slaveAddress = (slaveAddress >> 1);

    uint8_t regAddress = getHexFromString(split[2]);

    auto payload = getPayload(split, 3);

    uint8_t buffer[payload.size()];

    if(slaveAddress != m_i2cInterface.getSlaveAddress())
    {
        I2CInterface::RET_CODE retCode = m_i2cInterface.setSlaveAddress(slaveAddress);
        if(retCode != I2CInterface::RET_CODE::SUCCESS)
        {
            std::cout << "Failed to set address in a handle compare. Returned with error code: " << static_cast<int>(retCode) << std::endl;
            return retCode;
        }
    }

    //Read the bytes
    I2CInterface::RET_CODE retCode = m_i2cInterface.receive(regAddress, buffer, payload.size());
    if(retCode != I2CInterface::RET_CODE::SUCCESS)
    {
        std::cout << "Failed handle write because of error: " << static_cast<int>(retCode) << std::endl;
        return retCode;
    }

    //Compare
    for(size_t i = 1; i < payload.size(); ++i)
    {
        std::cout << static_cast<int>(buffer[i]) << "\t" << static_cast<int>(payload.at(i)) << std::endl;
        if(buffer[i] != payload.at(i))
        {
            throw std::runtime_error("Failed compare");
        }
    }

    return I2CInterface::RET_CODE::SUCCESS;
}

I2CInterface::RET_CODE FilestreamParser::handleWrite(const std::string& writeLine)
{
    //W: I2CAddr RegAddr Byte0 Byte1 Byte2…
    auto split = splitString(writeLine, ' ');

    uint8_t slaveAddress = (getHexFromString(split[1]));

    //Bit shift left by one
    slaveAddress = (slaveAddress >> 1);

    uint8_t regAddress = getHexFromString(split[2]);

    auto payload = getPayload(split, 3);

    std::cout << "Writing to device address: " << (int)slaveAddress << " with reg address: " << (int)regAddress << std::endl;

    if(slaveAddress != m_i2cInterface.getSlaveAddress())
    {
        I2CInterface::RET_CODE retCode = m_i2cInterface.setSlaveAddress(slaveAddress);
        if(retCode != I2CInterface::RET_CODE::SUCCESS)
        {
            std::cout << "Failed to set address in a handle write. Returned with error code: " << static_cast<int>(retCode) << std::endl;
            return retCode;
        }
    }

    //Iterate throught the payload
    for(auto& data : payload)
    {
        std::cout << "Reg: " << (int)regAddress << std::endl;
        std::cout << "Data: " << (int)data << std::endl;
        ++regAddress;
        // I2CInterface::RET_CODE retCode = m_i2cInterface.send(regAddress, &payload.front(), payload.size());
        // if(retCode != I2CInterface::RET_CODE::SUCCESS)
        // {
        //     std::cout << "Failed handle write because of error: " << static_cast<int>(retCode) << std::endl;
        //     return retCode;
        // }
    }

    // I2CInterface::RET_CODE retCode = m_i2cInterface.send(regAddress, &payload.front(), payload.size());
    // if(retCode != I2CInterface::RET_CODE::SUCCESS)
    // {
    //     std::cout << "Failed handle write because of error: " << static_cast<int>(retCode) << std::endl;
    //     return retCode;
    // }
    return I2CInterface::RET_CODE::SUCCESS;
}

void FilestreamParser::handleWait(const std::string& waitLine)
{
    //X: [ms for wait]
    auto split = splitString(waitLine, ' ');
    auto waitTime = split[1];

    std::cout << "Waiting for: " << waitTime << " ms" << std::endl;
    wait(std::stoi(waitTime));
}

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

void FilestreamParser::wait(int milliseconds)
{
    //Sleeps this thread for the specified milliseconds
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}

uint8_t FilestreamParser::getHexFromString(const std::string& stringIn)
{
    uint8_t value = std::stoul(stringIn, nullptr, 16);
    return value;
}

std::vector<unsigned char> FilestreamParser::getPayload(std::vector<std::string>& lineIn, int pruneLength)
{
    lineIn.erase(lineIn.begin(), lineIn.begin() + pruneLength);

    std::vector<unsigned char> payload;
    for(auto& elem : lineIn)
    {
        payload.push_back(getHexFromString(elem));
    }

    return payload;
}<commit_msg>Added multi write<commit_after>#include "filestream_parser.h"

FilestreamParser::FilestreamParser(const std::string& flashstreamFile, const std::string& deviceFile, const uint8_t slaveAddress)
    : m_flashstreamFilename(flashstreamFile)
    , m_i2cInterface(deviceFile, slaveAddress)
{
    // Try to open the file for reading  and load it into a ss buffer
    std::ifstream inputStream(m_flashstreamFilename);
    m_flashstreamBuffer << inputStream.rdbuf();
}

I2CInterface::RET_CODE FilestreamParser::init()
{
    //Setup i2c
    I2CInterface::RET_CODE retCode = m_i2cInterface.init();
    if(retCode != I2CInterface::RET_CODE::SUCCESS)
    {
        std::cout << "Failed i2c init with return code: " << static_cast<int>(retCode) << std::endl;
        return retCode;
    }

    return retCode;
}

I2CInterface::RET_CODE FilestreamParser::flash()
{
    std::cout << "Starting TI FlashStream flasing process." << std::endl;
    std::cout << "Using data file: " << m_flashstreamFilename << std::endl;

    if( validate() )
    {
        std::string token;
        while(std::getline(m_flashstreamBuffer, token, '\n'))
        {
            //Get the key
            char key = token[0];

            switch(key)
            {
                case ';':
                {
                    handleComment(token);
                    break;
                }
                case 'C':
                {
                    I2CInterface::RET_CODE retCode = handleCompare(token);
                    if(retCode != I2CInterface::RET_CODE::SUCCESS)
                    {
                        std::cout << "Failed write because of error code: " << static_cast<int>(retCode) << std::endl;
                        return retCode;
                    }
                    break;
                }
                case 'W':
                {
                    I2CInterface::RET_CODE retCode = handleWrite(token);
                    if(retCode != I2CInterface::RET_CODE::SUCCESS)
                    {
                        std::cout << "Failed write because of error code: " << static_cast<int>(retCode) << std::endl;
                        return retCode;
                    }
                    break;
                }
                case 'X':
                {
                    handleWait(token);
                    break;
                }
                default:
                {
                    std::cout << "Error parsing file. Bad line: " << token << std::endl;
                    break;
                }
            }
        }
    }
    else
    {
        std::cout << "Bad input file." << std::endl;
        return I2CInterface::RET_CODE::FAILED_VALIDATE;
    }

    return I2CInterface::RET_CODE::SUCCESS;

}

bool FilestreamParser::validate()
{
    //Try to parse the file, return false if could not validate
    std::cout << "Validating flash stream file..." << std::endl;

    std::stringstream tmpBuffer;
    tmpBuffer << m_flashstreamBuffer.str();

    std::string token;
    bool isValid = true;
    while(std::getline(tmpBuffer, token, '\n'))
    {
        //Get the key
        char key = token[0];

        switch(key)
        {
            case ';':
            {
                break;
            }
            case 'C':
            {
                break;
            }
            case 'W':
            {
                break;
            }
            case 'X':
            {
                break;
            }
            default:
            {
                std::cout << "Error parsing file. Bad line: " << token << std::endl;
                isValid = false;
                break;
            }
        }
    }
    std::cout << "File is valid" << std::endl;

    return isValid;
}

void FilestreamParser::handleComment(const std::string& commentIn)
{
    //; [comment]
    std::cout << commentIn << std::endl;
}

I2CInterface::RET_CODE FilestreamParser::handleCompare(const std::string& compareLine)
{
    //C: i2cAddr RegAddr Byte0 Byte1 Byte2
    auto split = splitString(compareLine, ' ');

    //get the slave address
    uint8_t slaveAddress = (getHexFromString(split[1]));

    //Bit shift left by one
    slaveAddress = (slaveAddress >> 1);

    uint8_t regAddress = getHexFromString(split[2]);

    auto payload = getPayload(split, 3);

    uint8_t buffer[payload.size()];

    if(slaveAddress != m_i2cInterface.getSlaveAddress())
    {
        I2CInterface::RET_CODE retCode = m_i2cInterface.setSlaveAddress(slaveAddress);
        if(retCode != I2CInterface::RET_CODE::SUCCESS)
        {
            std::cout << "Failed to set address in a handle compare. Returned with error code: " << static_cast<int>(retCode) << std::endl;
            return retCode;
        }
    }

    //Read the bytes
    I2CInterface::RET_CODE retCode = m_i2cInterface.receive(regAddress, buffer, payload.size());
    if(retCode != I2CInterface::RET_CODE::SUCCESS)
    {
        std::cout << "Failed handle write because of error: " << static_cast<int>(retCode) << std::endl;
        return retCode;
    }

    //Compare
    for(size_t i = 1; i < payload.size(); ++i)
    {
        std::cout << "Comparing: " << static_cast<int>(buffer[i]) << "\t" << static_cast<int>(payload.at(i)) << std::endl;
        if(buffer[i] != payload.at(i))
        {
            throw std::runtime_error("Failed compare");
        }
    }

    return I2CInterface::RET_CODE::SUCCESS;
}

I2CInterface::RET_CODE FilestreamParser::handleWrite(const std::string& writeLine)
{
    //W: I2CAddr RegAddr Byte0 Byte1 Byte2…
    auto split = splitString(writeLine, ' ');

    uint8_t slaveAddress = (getHexFromString(split[1]));

    //Bit shift left by one
    slaveAddress = (slaveAddress >> 1);

    uint8_t regAddress = getHexFromString(split[2]);

    auto payload = getPayload(split, 3);

    std::cout << "Writing to device address: " << (int)slaveAddress << " with reg address: " << (int)regAddress << std::endl;

    if(slaveAddress != m_i2cInterface.getSlaveAddress())
    {
        I2CInterface::RET_CODE retCode = m_i2cInterface.setSlaveAddress(slaveAddress);
        if(retCode != I2CInterface::RET_CODE::SUCCESS)
        {
            std::cout << "Failed to set address in a handle write. Returned with error code: " << static_cast<int>(retCode) << std::endl;
            return retCode;
        }
    }

    //Iterate throught the payload
    for(auto& data : payload)
    {
        std::cout << "Reg: " << (int)regAddress << std::endl;
        std::cout << "Data: " << (int)data << std::endl;

        I2CInterface::RET_CODE retCode = m_i2cInterface.send(regAddress, &payload.front(), payload.size());
        if(retCode != I2CInterface::RET_CODE::SUCCESS)
        {
            std::cout << "Failed handle write because of error: " << static_cast<int>(retCode) << std::endl;
            return retCode;
        }
        ++regAddress;
    }

    return I2CInterface::RET_CODE::SUCCESS;
}

void FilestreamParser::handleWait(const std::string& waitLine)
{
    //X: [ms for wait]
    auto split = splitString(waitLine, ' ');
    auto waitTime = split[1];

    std::cout << "Waiting for: " << waitTime << " ms" << std::endl;
    wait(std::stoi(waitTime));
}

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

void FilestreamParser::wait(int milliseconds)
{
    //Sleeps this thread for the specified milliseconds
    std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}

uint8_t FilestreamParser::getHexFromString(const std::string& stringIn)
{
    uint8_t value = std::stoul(stringIn, nullptr, 16);
    return value;
}

std::vector<unsigned char> FilestreamParser::getPayload(std::vector<std::string>& lineIn, int pruneLength)
{
    lineIn.erase(lineIn.begin(), lineIn.begin() + pruneLength);

    std::vector<unsigned char> payload;
    for(auto& elem : lineIn)
    {
        payload.push_back(getHexFromString(elem));
    }

    return payload;
}<|endoftext|>


<commit_before>#include "game/skirmish/toggleflatmodehandler.hpp"

#include "eventsystem/inputevents.hpp"
#include "game/deploymentzone.hpp"
#include "game/skirmish/wall.hpp"
#include "game/skirmish/unit.hpp"
#include "game/skirmish/stairs.hpp"

namespace qrw
{

ToggleFlatModeHandler::ToggleFlatModeHandler() : EventHandler(0)
{}

bool ToggleFlatModeHandler::handleEvent(const IEvent& event)
{
	if(event.getName() == KeyPressedEvent::name) {
		if(static_cast<const KeyPressedEvent&>(event).key == KeyboardKey::Space) {
			toggleFlatMode();
		}
	}

	return false;
}

template<class T>
void toggleFlatModeFor(bool isFlatMode)
{
	auto gameObjects = g_scene.findGameObjects<T>();

	for(auto& gameObject : gameObjects) {
		auto* concreteGameObject = dynamic_cast<T*>(gameObject);
		concreteGameObject->setFlatMode(isFlatMode);
	}
}

void ToggleFlatModeHandler::toggleFlatMode()
{
	isFlatMode_ = !isFlatMode_;
	toggleFlatModeFor<Wall>(isFlatMode_);
	toggleFlatModeFor<Stairs>(isFlatMode_);
	toggleFlatModeFor<DeploymentZone>(isFlatMode_);
	toggleFlatModeFor<Unit>(isFlatMode_);
}

} // namespace qrw<commit_msg>Fix flatmode toggling for archer and ladder carrier<commit_after>#include "game/skirmish/toggleflatmodehandler.hpp"

#include "eventsystem/inputevents.hpp"
#include "game/deploymentzone.hpp"
#include "game/skirmish/wall.hpp"
#include "game/skirmish/unit.hpp"
#include "game/skirmish/laddercarrier.hpp"
#include "game/skirmish/archer.hpp"
#include "game/skirmish/stairs.hpp"

namespace qrw
{

ToggleFlatModeHandler::ToggleFlatModeHandler() : EventHandler(0)
{}

bool ToggleFlatModeHandler::handleEvent(const IEvent& event)
{
	if(event.getName() == KeyPressedEvent::name) {
		if(static_cast<const KeyPressedEvent&>(event).key == KeyboardKey::Space) {
			toggleFlatMode();
		}
	}

	return false;
}

template<class T>
void toggleFlatModeFor(bool isFlatMode)
{
	auto gameObjects = g_scene.findGameObjects<T>();

	for(auto& gameObject : gameObjects) {
		auto* concreteGameObject = dynamic_cast<T*>(gameObject);
		concreteGameObject->setFlatMode(isFlatMode);
	}
}

void ToggleFlatModeHandler::toggleFlatMode()
{
	isFlatMode_ = !isFlatMode_;
	toggleFlatModeFor<Wall>(isFlatMode_);
	toggleFlatModeFor<Stairs>(isFlatMode_);
	toggleFlatModeFor<DeploymentZone>(isFlatMode_);
	toggleFlatModeFor<Unit>(isFlatMode_);
	toggleFlatModeFor<LadderCarrier>(isFlatMode_);
	toggleFlatModeFor<Archer>(isFlatMode_);
}

} // namespace qrw<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebSockets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
    \qmltype WebSocket
    \instantiates QQmlWebSocket

    \inqmlmodule Qt.WebSockets
    \ingroup websockets-qml
    \brief QML interface to QWebSocket.

    WebSockets is a web technology providing full-duplex communications channels over a
    single TCP connection.
    The WebSocket protocol was standardized by the IETF as
    \l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
*/

/*!
  \qmlproperty QUrl WebSocket::url
  Server url to connect to. The url must have one of 2 schemes: \e ws:// or \e wss://.
  When not supplied, then \e ws:// is used.
  */

/*!
  \qmlproperty Status WebSocket::status
  Status of the WebSocket.

  The status can have the following values:
  \list
  \li WebSockets.Connecting
  \li WebSockets.Open
  \li WebSockets.Closing
  \li WebSockets.Closed
  \li WebSockets.Error
  \endlist
  */

/*!
  \qmlproperty QString WebSocket::errorString
  Contains a description of the last error that occurred. When no error occurrred,
  this string is empty.
  */

/*!
  \qmlproperty bool WebSocket::active
  When set to true, a connection is made to the server with the given url.
  When set to false, the connection is closed.
  The default value is false.
  */

/*!
  \qmlsignal WebSocket::textMessageReceived(QString message)
  This signal is emitted when a text message is received.
  */

/*!
  \qmlsignal WebSocket::statusChanged(Status status)
  This signal is emitted when the status of the WebSocket changes.
  the \l {WebSocket::status}{status} argument provides the current status.

  \sa WebSocket::status
  */

#include "qqmlwebsocket.h"
#include <QtWebSockets/QWebSocket>

QT_BEGIN_NAMESPACE

QQmlWebSocket::QQmlWebSocket(QObject *parent) :
    QObject(parent),
    m_webSocket(),
    m_status(Closed),
    m_url(),
    m_isActive(false),
    m_componentCompleted(true),
    m_errorString()
{
}

QQmlWebSocket::~QQmlWebSocket()
{
}

qint64 QQmlWebSocket::sendTextMessage(const QString &message)
{
    if (m_status != Open) {
        setErrorString(tr("Messages can only be sent when the socket has Open status."));
        setStatus(Error);
        return 0;
    }
    return m_webSocket->sendTextMessage(message);
}

QUrl QQmlWebSocket::url() const
{
    return m_url;
}

void QQmlWebSocket::setUrl(const QUrl &url)
{
    if (m_url == url) {
        return;
    }
    if (m_webSocket && (m_status == Open)) {
        m_webSocket->close();
    }
    m_url = url;
    Q_EMIT urlChanged();
    if (m_webSocket) {
        m_webSocket->open(m_url);
    }
}

QQmlWebSocket::Status QQmlWebSocket::status() const
{
    return m_status;
}

QString QQmlWebSocket::errorString() const
{
    return m_errorString;
}

void QQmlWebSocket::classBegin()
{
    m_componentCompleted = false;
    m_errorString = tr("QQmlWebSocket is not ready.");
    m_status = Closed;
}

void QQmlWebSocket::componentComplete()
{
    m_webSocket.reset(new (std::nothrow) QWebSocket());
    if (Q_LIKELY(m_webSocket)) {
        connect(m_webSocket.data(), &QWebSocket::textMessageReceived,
                this, &QQmlWebSocket::textMessageReceived);
        typedef void (QWebSocket::* ErrorSignal)(QAbstractSocket::SocketError);
        connect(m_webSocket.data(), static_cast<ErrorSignal>(&QWebSocket::error),
                this, &QQmlWebSocket::onError);
        connect(m_webSocket.data(), &QWebSocket::stateChanged,
                this, &QQmlWebSocket::onStateChanged);

        m_componentCompleted = true;

        open();
    }
}

void QQmlWebSocket::onError(QAbstractSocket::SocketError error)
{
    Q_UNUSED(error)
    setErrorString(m_webSocket->errorString());
    setStatus(Error);
}

void QQmlWebSocket::onStateChanged(QAbstractSocket::SocketState state)
{
    switch (state)
    {
        case QAbstractSocket::ConnectingState:
        case QAbstractSocket::BoundState:
        case QAbstractSocket::HostLookupState:
        {
            setStatus(Connecting);
            break;
        }
        case QAbstractSocket::UnconnectedState:
        {
            setStatus(Closed);
            break;
        }
        case QAbstractSocket::ConnectedState:
        {
            setStatus(Open);
            break;
        }
        case QAbstractSocket::ClosingState:
        {
            setStatus(Closing);
            break;
        }
        default:
        {
            setStatus(Connecting);
            break;
        }
    }
}

void QQmlWebSocket::setStatus(QQmlWebSocket::Status status)
{
    if (m_status == status) {
        return;
    }
    m_status = status;
    if (status != Error) {
        setErrorString();
    }
    Q_EMIT statusChanged(m_status);
}

void QQmlWebSocket::setActive(bool active)
{
    if (m_isActive == active) {
        return;
    }
    m_isActive = active;
    Q_EMIT activeChanged(m_isActive);
    if (!m_componentCompleted) {
        return;
    }
    if (m_isActive) {
        open();
    } else {
        close();
    }
}

bool QQmlWebSocket::isActive() const
{
    return m_isActive;
}

void QQmlWebSocket::open()
{
    if (m_componentCompleted && m_isActive && m_url.isValid() && Q_LIKELY(m_webSocket)) {
        m_webSocket->open(m_url);
    }
}

void QQmlWebSocket::close()
{
    if (m_componentCompleted && Q_LIKELY(m_webSocket)) {
        m_webSocket->close();
    }
}

void QQmlWebSocket::setErrorString(QString errorString)
{
    if (m_errorString == errorString) {
        return;
    }
    m_errorString = errorString;
    Q_EMIT errorStringChanged(m_errorString);
}

QT_END_NAMESPACE
<commit_msg>Small fix to error text<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebSockets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/*!
    \qmltype WebSocket
    \instantiates QQmlWebSocket

    \inqmlmodule Qt.WebSockets
    \ingroup websockets-qml
    \brief QML interface to QWebSocket.

    WebSockets is a web technology providing full-duplex communications channels over a
    single TCP connection.
    The WebSocket protocol was standardized by the IETF as
    \l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
*/

/*!
  \qmlproperty QUrl WebSocket::url
  Server url to connect to. The url must have one of 2 schemes: \e ws:// or \e wss://.
  When not supplied, then \e ws:// is used.
  */

/*!
  \qmlproperty Status WebSocket::status
  Status of the WebSocket.

  The status can have the following values:
  \list
  \li WebSockets.Connecting
  \li WebSockets.Open
  \li WebSockets.Closing
  \li WebSockets.Closed
  \li WebSockets.Error
  \endlist
  */

/*!
  \qmlproperty QString WebSocket::errorString
  Contains a description of the last error that occurred. When no error occurrred,
  this string is empty.
  */

/*!
  \qmlproperty bool WebSocket::active
  When set to true, a connection is made to the server with the given url.
  When set to false, the connection is closed.
  The default value is false.
  */

/*!
  \qmlsignal WebSocket::textMessageReceived(QString message)
  This signal is emitted when a text message is received.
  */

/*!
  \qmlsignal WebSocket::statusChanged(Status status)
  This signal is emitted when the status of the WebSocket changes.
  the \l {WebSocket::status}{status} argument provides the current status.

  \sa WebSocket::status
  */

#include "qqmlwebsocket.h"
#include <QtWebSockets/QWebSocket>

QT_BEGIN_NAMESPACE

QQmlWebSocket::QQmlWebSocket(QObject *parent) :
    QObject(parent),
    m_webSocket(),
    m_status(Closed),
    m_url(),
    m_isActive(false),
    m_componentCompleted(true),
    m_errorString()
{
}

QQmlWebSocket::~QQmlWebSocket()
{
}

qint64 QQmlWebSocket::sendTextMessage(const QString &message)
{
    if (m_status != Open) {
        setErrorString(tr("Messages can only be sent when the socket is open."));
        setStatus(Error);
        return 0;
    }
    return m_webSocket->sendTextMessage(message);
}

QUrl QQmlWebSocket::url() const
{
    return m_url;
}

void QQmlWebSocket::setUrl(const QUrl &url)
{
    if (m_url == url) {
        return;
    }
    if (m_webSocket && (m_status == Open)) {
        m_webSocket->close();
    }
    m_url = url;
    Q_EMIT urlChanged();
    if (m_webSocket) {
        m_webSocket->open(m_url);
    }
}

QQmlWebSocket::Status QQmlWebSocket::status() const
{
    return m_status;
}

QString QQmlWebSocket::errorString() const
{
    return m_errorString;
}

void QQmlWebSocket::classBegin()
{
    m_componentCompleted = false;
    m_errorString = tr("QQmlWebSocket is not ready.");
    m_status = Closed;
}

void QQmlWebSocket::componentComplete()
{
    m_webSocket.reset(new (std::nothrow) QWebSocket());
    if (Q_LIKELY(m_webSocket)) {
        connect(m_webSocket.data(), &QWebSocket::textMessageReceived,
                this, &QQmlWebSocket::textMessageReceived);
        typedef void (QWebSocket::* ErrorSignal)(QAbstractSocket::SocketError);
        connect(m_webSocket.data(), static_cast<ErrorSignal>(&QWebSocket::error),
                this, &QQmlWebSocket::onError);
        connect(m_webSocket.data(), &QWebSocket::stateChanged,
                this, &QQmlWebSocket::onStateChanged);

        m_componentCompleted = true;

        open();
    }
}

void QQmlWebSocket::onError(QAbstractSocket::SocketError error)
{
    Q_UNUSED(error)
    setErrorString(m_webSocket->errorString());
    setStatus(Error);
}

void QQmlWebSocket::onStateChanged(QAbstractSocket::SocketState state)
{
    switch (state)
    {
        case QAbstractSocket::ConnectingState:
        case QAbstractSocket::BoundState:
        case QAbstractSocket::HostLookupState:
        {
            setStatus(Connecting);
            break;
        }
        case QAbstractSocket::UnconnectedState:
        {
            setStatus(Closed);
            break;
        }
        case QAbstractSocket::ConnectedState:
        {
            setStatus(Open);
            break;
        }
        case QAbstractSocket::ClosingState:
        {
            setStatus(Closing);
            break;
        }
        default:
        {
            setStatus(Connecting);
            break;
        }
    }
}

void QQmlWebSocket::setStatus(QQmlWebSocket::Status status)
{
    if (m_status == status) {
        return;
    }
    m_status = status;
    if (status != Error) {
        setErrorString();
    }
    Q_EMIT statusChanged(m_status);
}

void QQmlWebSocket::setActive(bool active)
{
    if (m_isActive == active) {
        return;
    }
    m_isActive = active;
    Q_EMIT activeChanged(m_isActive);
    if (!m_componentCompleted) {
        return;
    }
    if (m_isActive) {
        open();
    } else {
        close();
    }
}

bool QQmlWebSocket::isActive() const
{
    return m_isActive;
}

void QQmlWebSocket::open()
{
    if (m_componentCompleted && m_isActive && m_url.isValid() && Q_LIKELY(m_webSocket)) {
        m_webSocket->open(m_url);
    }
}

void QQmlWebSocket::close()
{
    if (m_componentCompleted && Q_LIKELY(m_webSocket)) {
        m_webSocket->close();
    }
}

void QQmlWebSocket::setErrorString(QString errorString)
{
    if (m_errorString == errorString) {
        return;
    }
    m_errorString = errorString;
    Q_EMIT errorStringChanged(m_errorString);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>
/* ========================================

   * File Name : 16.cpp

   * Creation Date : 09-08-2020

   * Last Modified : Ne 9. srpna 2020, 19:18:40

   * Created By : Karel Ha <mathemage@gmail.com>

   * URL : https://www.facebook.com/codingcompetitions/hacker-cup/2019/round-1/problems/B

   * Points Gained (in case of online contest) :

   ==========================================*/

#include <bits/stdc++.h>

using namespace std;

#define REP(I,N)   FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A)     (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;

const int CLEAN = -1;

template <typename T>
string NumberToString ( T Number ) {
  ostringstream ss;
  ss << Number;
  return ss.str();
}

#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
  vector<string> v;
  stringstream ss(s);
  string x;
  while (getline(ss, x, c))
    v.emplace_back(x);
  return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
  cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
  err(++it, args...);
}

int main() {
  return 0;
}
<commit_msg>Read input<commit_after>
/* ========================================

   * File Name : 16.cpp

   * Creation Date : 09-08-2020

   * Last Modified : Ne 9. srpna 2020, 19:23:33

   * Created By : Karel Ha <mathemage@gmail.com>

   * URL : https://www.facebook.com/codingcompetitions/hacker-cup/2019/round-1/problems/B

   * Points Gained (in case of online contest) :

   ==========================================*/

#include <bits/stdc++.h>

using namespace std;

#define REP(I,N)   FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A)     (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;

const int CLEAN = -1;

template <typename T>
string NumberToString ( T Number ) {
  ostringstream ss;
  ss << Number;
  return ss.str();
}

#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
  vector<string> v;
  stringstream ss(s);
  string x;
  while (getline(ss, x, c))
    v.emplace_back(x);
  return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
  cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
  err(++it, args...);
}

int main() {
  int T;
  cin >> T;
//   MSG(T)

  REP(t,T) {
    int N, K;
    cin >> N >> K;
//     MSG(N) MSG(K)

    string V;
    V.reserve(N);
    cin >> V;
//     MSG(V) cout << endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "imagesrepository.h"

#include <fnmatch.h>

namespace Uptane {

void ImagesRepository::resetMeta() {
  resetRoot();
  targets.clear();
  snapshot = Snapshot();
  timestamp = TimestampMeta();
}

bool ImagesRepository::verifyTimestamp(const std::string& timestamp_raw) {
  try {
    // Verify the signature:
    timestamp =
        TimestampMeta(RepositoryType::Image(), Utils::parseJSON(timestamp_raw), std::make_shared<MetaWithKeys>(root));
  } catch (const Exception& e) {
    LOG_ERROR << "Signature verification for timestamp metadata failed";
    last_exception = e;
    return false;
  }
  return true;
}

bool ImagesRepository::verifySnapshot(const std::string& snapshot_raw) {
  try {
    const std::string canonical = Utils::jsonToCanonicalStr(Utils::parseJSON(snapshot_raw));
    bool hash_exists = false;
    for (const auto& it : timestamp.snapshot_hashes()) {
      switch (it.type()) {
        case Hash::Type::kSha256:
          if (Hash(Hash::Type::kSha256, boost::algorithm::hex(Crypto::sha256digest(canonical))) != it) {
            LOG_ERROR << "Hash verification for snapshot metadata failed";
            return false;
          }
          hash_exists = true;
          break;
        case Hash::Type::kSha512:
          if (Hash(Hash::Type::kSha512, boost::algorithm::hex(Crypto::sha512digest(canonical))) != it) {
            LOG_ERROR << "Hash verification for snapshot metadata failed";
            return false;
          }
          hash_exists = true;
          break;
        default:
          break;
      }
    }
    if (!hash_exists) {
      LOG_ERROR << "No hash found for shapshot.json";
      return false;
    }
    // Verify the signature:
    snapshot = Snapshot(RepositoryType::Image(), Utils::parseJSON(snapshot_raw), std::make_shared<MetaWithKeys>(root));
    if (snapshot.version() != timestamp.snapshot_version()) {
      return false;
    }
  } catch (const Exception& e) {
    LOG_ERROR << "Signature verification for snapshot metadata failed";
    last_exception = e;
    return false;
  }
  return true;
}

bool ImagesRepository::verifyTargets(const std::string& targets_raw, const Uptane::Role role) {
  try {
    const Json::Value targets_json = Utils::parseJSON(targets_raw);
    const std::string canonical = Utils::jsonToCanonicalStr(targets_json);
    bool hash_exists = false;
    for (const auto& it : snapshot.targets_hashes()) {
      switch (it.type()) {
        case Hash::Type::kSha256:
          if (Hash(Hash::Type::kSha256, boost::algorithm::hex(Crypto::sha256digest(canonical))) != it) {
            LOG_ERROR << "Hash verification for targets metadata failed";
            return false;
          }
          hash_exists = true;
          break;
        case Hash::Type::kSha512:
          if (Hash(Hash::Type::kSha512, boost::algorithm::hex(Crypto::sha512digest(canonical))) != it) {
            LOG_ERROR << "Hash verification for targets metadata failed";
            return false;
          }
          hash_exists = true;
          break;
        default:
          break;
      }
    }
    if (!hash_exists) {
      LOG_ERROR << "No hash found for targets.json";
      return false;
    }

    // Verify the signature:
    std::shared_ptr<MetaWithKeys> signer;
    if (role == Uptane::Role::Targets()) {
      signer = std::make_shared<MetaWithKeys>(root);
    } else {
      // TODO: support nested delegations here. This currently assumes that all
      // delegated targets are signed by the top-level targets.
      signer = std::make_shared<MetaWithKeys>(targets["targets"]);
    }
    targets[role.ToString()] = Targets(RepositoryType::Image(), role, targets_json, signer);

    // Only compare targets version in snapshot metadata for top-level
    // targets.json. Delegated target metadata versions are not tracked outside
    // of their own metadata.
    if (role == Uptane::Role::Targets() && targets[role.ToString()].version() != snapshot.targets_version()) {
      return false;
    }
  } catch (const Exception& e) {
    LOG_ERROR << "Signature verification for images targets metadata failed";
    last_exception = e;
    return false;
  }
  return true;
}

std::unique_ptr<Uptane::Target> ImagesRepository::getTarget(const Uptane::Target& director_target) {
  // Search for the target in the top-level targets metadata.
  Uptane::Targets toplevel = targets["targets"];
  auto it = std::find(toplevel.targets.cbegin(), toplevel.targets.cend(), director_target);
  if (it == toplevel.targets.cend()) {
    // Check if the target matches any of the delegation paths.
    for (const auto& delegate_name : toplevel.delegated_role_names_) {
      Role delegate_role = Role::Delegated(delegate_name);
      std::vector<std::string> patterns = toplevel.paths_for_role_[delegate_role];
      for (const auto& pattern : patterns) {
        if (fnmatch(pattern.c_str(), director_target.filename().c_str(), 0) == 0) {
          // Match! Check delegation.
          Uptane::Targets delegate = targets[delegate_name];
          auto d_it = std::find(delegate.targets.cbegin(), delegate.targets.cend(), director_target);
          if (d_it == delegate.targets.cend()) {
            // TODO: recurse here if the delegation is non-terminating. For now,
            // assume that all delegations are terminating.
            if (!toplevel.terminating_role_[delegate_role]) {
              LOG_ERROR << "Nested delegations are not currently supported.";
            }
            return std::unique_ptr<Uptane::Target>(nullptr);
          } else {
            return std_::make_unique<Uptane::Target>(*d_it);
          }
        }
      }
    }
    return std::unique_ptr<Uptane::Target>(nullptr);
  } else {
    return std_::make_unique<Uptane::Target>(*it);
  }
}

}  // namespace Uptane
<commit_msg>Only check hashes for top-level targets.json.<commit_after>#include "imagesrepository.h"

#include <fnmatch.h>

namespace Uptane {

void ImagesRepository::resetMeta() {
  resetRoot();
  targets.clear();
  snapshot = Snapshot();
  timestamp = TimestampMeta();
}

bool ImagesRepository::verifyTimestamp(const std::string& timestamp_raw) {
  try {
    // Verify the signature:
    timestamp =
        TimestampMeta(RepositoryType::Image(), Utils::parseJSON(timestamp_raw), std::make_shared<MetaWithKeys>(root));
  } catch (const Exception& e) {
    LOG_ERROR << "Signature verification for timestamp metadata failed";
    last_exception = e;
    return false;
  }
  return true;
}

bool ImagesRepository::verifySnapshot(const std::string& snapshot_raw) {
  try {
    const std::string canonical = Utils::jsonToCanonicalStr(Utils::parseJSON(snapshot_raw));
    bool hash_exists = false;
    for (const auto& it : timestamp.snapshot_hashes()) {
      switch (it.type()) {
        case Hash::Type::kSha256:
          if (Hash(Hash::Type::kSha256, boost::algorithm::hex(Crypto::sha256digest(canonical))) != it) {
            LOG_ERROR << "Hash verification for snapshot metadata failed";
            return false;
          }
          hash_exists = true;
          break;
        case Hash::Type::kSha512:
          if (Hash(Hash::Type::kSha512, boost::algorithm::hex(Crypto::sha512digest(canonical))) != it) {
            LOG_ERROR << "Hash verification for snapshot metadata failed";
            return false;
          }
          hash_exists = true;
          break;
        default:
          break;
      }
    }
    if (!hash_exists) {
      LOG_ERROR << "No hash found for shapshot.json";
      return false;
    }
    // Verify the signature:
    snapshot = Snapshot(RepositoryType::Image(), Utils::parseJSON(snapshot_raw), std::make_shared<MetaWithKeys>(root));
    if (snapshot.version() != timestamp.snapshot_version()) {
      return false;
    }
  } catch (const Exception& e) {
    LOG_ERROR << "Signature verification for snapshot metadata failed";
    last_exception = e;
    return false;
  }
  return true;
}

bool ImagesRepository::verifyTargets(const std::string& targets_raw, const Uptane::Role role) {
  try {
    const Json::Value targets_json = Utils::parseJSON(targets_raw);
    const std::string canonical = Utils::jsonToCanonicalStr(targets_json);
    // Delegated targets do not have their hashes stored in their parent.
    if (role == Uptane::Role::Targets()) {
      bool hash_exists = false;
      for (const auto& it : snapshot.targets_hashes()) {
        switch (it.type()) {
          case Hash::Type::kSha256:
            if (Hash(Hash::Type::kSha256, boost::algorithm::hex(Crypto::sha256digest(canonical))) != it) {
              LOG_ERROR << "Hash verification for targets metadata failed";
              return false;
            }
            hash_exists = true;
            break;
          case Hash::Type::kSha512:
            if (Hash(Hash::Type::kSha512, boost::algorithm::hex(Crypto::sha512digest(canonical))) != it) {
              LOG_ERROR << "Hash verification for targets metadata failed";
              return false;
            }
            hash_exists = true;
            break;
          default:
            break;
        }
      }
      if (!hash_exists) {
        LOG_ERROR << "No hash found for targets.json";
        return false;
      }
    }

    // Verify the signature:
    std::shared_ptr<MetaWithKeys> signer;
    if (role == Uptane::Role::Targets()) {
      signer = std::make_shared<MetaWithKeys>(root);
    } else {
      // TODO: support nested delegations here. This currently assumes that all
      // delegated targets are signed by the top-level targets.
      signer = std::make_shared<MetaWithKeys>(targets["targets"]);
    }
    targets[role.ToString()] = Targets(RepositoryType::Image(), role, targets_json, signer);

    // Only compare targets version in snapshot metadata for top-level
    // targets.json. Delegated target metadata versions are not tracked outside
    // of their own metadata.
    if (role == Uptane::Role::Targets() && targets[role.ToString()].version() != snapshot.targets_version()) {
      return false;
    }
  } catch (const Exception& e) {
    LOG_ERROR << "Signature verification for images targets metadata failed";
    last_exception = e;
    return false;
  }
  return true;
}

std::unique_ptr<Uptane::Target> ImagesRepository::getTarget(const Uptane::Target& director_target) {
  // Search for the target in the top-level targets metadata.
  Uptane::Targets toplevel = targets["targets"];
  auto it = std::find(toplevel.targets.cbegin(), toplevel.targets.cend(), director_target);
  if (it == toplevel.targets.cend()) {
    // Check if the target matches any of the delegation paths.
    for (const auto& delegate_name : toplevel.delegated_role_names_) {
      Role delegate_role = Role::Delegated(delegate_name);
      std::vector<std::string> patterns = toplevel.paths_for_role_[delegate_role];
      for (const auto& pattern : patterns) {
        if (fnmatch(pattern.c_str(), director_target.filename().c_str(), 0) == 0) {
          // Match! Check delegation.
          Uptane::Targets delegate = targets[delegate_name];
          auto d_it = std::find(delegate.targets.cbegin(), delegate.targets.cend(), director_target);
          if (d_it == delegate.targets.cend()) {
            // TODO: recurse here if the delegation is non-terminating. For now,
            // assume that all delegations are terminating.
            if (!toplevel.terminating_role_[delegate_role]) {
              LOG_ERROR << "Nested delegations are not currently supported.";
            }
            return std::unique_ptr<Uptane::Target>(nullptr);
          } else {
            return std_::make_unique<Uptane::Target>(*d_it);
          }
        }
      }
    }
    return std::unique_ptr<Uptane::Target>(nullptr);
  } else {
    return std_::make_unique<Uptane::Target>(*it);
  }
}

}  // namespace Uptane
<|endoftext|>


<commit_before>#include <string.h>
#include <iostream>
#include "halide_blas.h"

#define assert_no_error(func)                                       \
  if (func != 0) {                                                  \
    std::cerr << "ERROR! Halide kernel returned non-zero value.\n"; \
  }                                                                 \

namespace {

void init_scalar_buffer(const float *x, buffer_t *buff) {
    memset((void*)buff, 0, sizeof(buffer_t));
    buff->host = (uint8_t*)const_cast<float*>(x);
    buff->extent[0] = 1;
    buff->stride[0] = 1;
    buff->elem_size = sizeof(float);
}

void init_scalar_buffer(const double *x, buffer_t *buff) {
    memset((void*)buff, 0, sizeof(buffer_t));
    buff->host = (uint8_t*)const_cast<double*>(x);
    buff->extent[0] = 1;
    buff->stride[0] = 1;
    buff->elem_size = sizeof(double);
}

void init_vector_buffer(const int N, const float *x, const int incx, buffer_t *buff) {
    memset((void*)buff, 0, sizeof(buffer_t));
    buff->host = (uint8_t*)const_cast<float*>(x);
    buff->extent[0] = N;
    buff->stride[0] = incx;
    buff->elem_size = sizeof(float);
}

void init_vector_buffer(const int N, const double *x, const int incx, buffer_t *buff) {
    memset((void*)buff, 0, sizeof(buffer_t));
    buff->host = (uint8_t*)const_cast<double*>(x);
    buff->extent[0] = N;
    buff->stride[0] = incx;
    buff->elem_size = sizeof(double);
}

void init_matrix_buffer(const int M, const int N, const float *A, const int lda, buffer_t *buff) {
    memset((void*)buff, 0, sizeof(buffer_t));
    buff->host = (uint8_t*)const_cast<float*>(A);
    buff->extent[0] = M;
    buff->extent[1] = N;
    buff->stride[0] = 1;
    buff->stride[1] = lda;
    buff->elem_size = sizeof(float);
}

void init_matrix_buffer(const int M, const int N, const double *A, const int lda, buffer_t *buff) {
    memset((void*)buff, 0, sizeof(buffer_t));
    buff->host = (uint8_t*)const_cast<double*>(A);
    buff->extent[0] = M;
    buff->extent[1] = N;
    buff->stride[0] = 1;
    buff->stride[1] = lda;
    buff->elem_size = sizeof(double);
}

}

#ifdef __cplusplus
extern "C" {
#endif

//////////
// copy //
//////////

void hblas_scopy(const int N, const float *x, const int incx,
                 float *y, const int incy) {
    buffer_t buff_x, buff_y;
    init_vector_buffer(N, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    assert_no_error(halide_scopy(&buff_x, &buff_y));
}

void hblas_dcopy(const int N, const double *x, const int incx,
                 double *y, const int incy) {
    buffer_t buff_x, buff_y;
    init_vector_buffer(N, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    assert_no_error(halide_dcopy(&buff_x, &buff_y));
}

//////////
// scal //
//////////

void hblas_sscal(const int N, const float a, float *x, const int incx) {
    buffer_t buff_x;
    init_vector_buffer(N, x, incx, &buff_x);
    assert_no_error(halide_sscal(a, &buff_x));
}

void hblas_dscal(const int N, const double a, double *x, const int incx) {
    buffer_t buff_x;
    init_vector_buffer(N, x, incx, &buff_x);
    assert_no_error(halide_dscal(a, &buff_x));
}

//////////
// axpy //
//////////

void hblas_saxpy(const int N, const float a, const float *x, const int incx,
                 float *y, const int incy) {
    buffer_t buff_x, buff_y;
    init_vector_buffer(N, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    assert_no_error(halide_saxpy(a, &buff_x, &buff_y));
}

void hblas_daxpy(const int N, const double a, const double *x, const int incx,
                 double *y, const int incy) {
    buffer_t buff_x, buff_y;
    init_vector_buffer(N, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    assert_no_error(halide_daxpy(a, &buff_x, &buff_y));
}

//////////
// dot  //
//////////

float hblas_sdot(const int N, const float *x, const int incx,
                 const float *y, const int incy) {
    float result;
    buffer_t buff_x, buff_y, buff_dot;
    init_vector_buffer(N, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    init_scalar_buffer(&result, &buff_dot);
    assert_no_error(halide_sdot(&buff_x, &buff_y, &buff_dot));
    return result;
}

double hblas_ddot(const int N, const double *x, const int incx,
                  const double *y, const int incy) {
    double result;
    buffer_t buff_x, buff_y, buff_dot;
    init_vector_buffer(N, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    init_scalar_buffer(&result, &buff_dot);
    assert_no_error(halide_ddot(&buff_x, &buff_y, &buff_dot));
    return result;
}

//////////
// nrm2 //
//////////

float hblas_snrm2(const int N, const float *x, const int incx) {
    float result;
    buffer_t buff_x, buff_nrm;
    init_vector_buffer(N, x, incx, &buff_x);
    init_scalar_buffer(&result, &buff_nrm);
    assert_no_error(halide_sdot(&buff_x, &buff_x, &buff_nrm));
    return std::sqrt(result);
}

double hblas_dnrm2(const int N, const double *x, const int incx) {
    double result;
    buffer_t buff_x, buff_nrm;
    init_vector_buffer(N, x, incx, &buff_x);
    init_scalar_buffer(&result, &buff_nrm);
    assert_no_error(halide_ddot(&buff_x, &buff_x, &buff_nrm));
    return std::sqrt(result);
}

//////////
// asum //
//////////

float hblas_sasum(const int N, const float *x, const int incx) {
    float result;
    buffer_t buff_x, buff_sum;
    init_vector_buffer(N, x, incx, &buff_x);
    init_scalar_buffer(&result, &buff_sum);
    assert_no_error(halide_sasum(&buff_x, &buff_sum));
    return result;
}

double hblas_dasum(const int N, const double *x, const int incx) {
    double result;
    buffer_t buff_x, buff_sum;
    init_vector_buffer(N, x, incx, &buff_x);
    init_scalar_buffer(&result, &buff_sum);
    assert_no_error(halide_dasum(&buff_x, &buff_sum));
    return result;
}

//////////
// gemv //
//////////

void hblas_sgemv(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE trans,
                 const int M, const int N, const float a, const float *A, const int lda,
                 const float *x, const int incx, const float b, float *y, const int incy) {
    bool t = false;
    switch (trans) {
    case HblasNoTrans:
        t = false; break;
    case HblasConjTrans:
    case HblasTrans:
        t = true; break;
    };

    buffer_t buff_A, buff_x, buff_y;
    init_matrix_buffer(M, N, A, lda, &buff_A);
    if (t) {
        init_vector_buffer(M, x, incx, &buff_x);
        init_vector_buffer(N, y, incy, &buff_y);
    } else {
        init_vector_buffer(N, x, incx, &buff_x);
        init_vector_buffer(M, y, incy, &buff_y);
    }

    assert_no_error(halide_sgemv(t, a, &buff_A, &buff_x, b, &buff_y));
}

void hblas_dgemv(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE trans,
                 const int M, const int N, const double a, const double *A, const int lda,
                 const double *x, const int incx, const double b, double *y, const int incy) {
    bool t = false;
    switch (trans) {
    case HblasNoTrans:
        t = false; break;
    case HblasConjTrans:
    case HblasTrans:
        t = true; break;
    };

    buffer_t buff_A, buff_x, buff_y;
    init_matrix_buffer(M, N, A, lda, &buff_A);
    if (t) {
        init_vector_buffer(M, x, incx, &buff_x);
        init_vector_buffer(N, y, incy, &buff_y);
    } else {
        init_vector_buffer(N, x, incx, &buff_x);
        init_vector_buffer(M, y, incy, &buff_y);
    }

    assert_no_error(halide_dgemv(t, a, &buff_A, &buff_x, b, &buff_y));
}

//////////
// ger  //
//////////

void hblas_sger(const enum HBLAS_ORDER order, const int M, const int N,
                const float alpha, const float *x, const int incx,
                const float *y, const int incy, float *A, const int lda)
{
    buffer_t buff_x, buff_y, buff_A;
    init_vector_buffer(M, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    init_matrix_buffer(M, N, A, lda, &buff_A);

    assert_no_error(halide_sger(alpha, &buff_x, &buff_y, &buff_A));
}

void hblas_dger(const enum HBLAS_ORDER order, const int M, const int N,
                const double alpha, const double *x, const int incx,
                const double *y, const int incy, double *A, const int lda)
{
    buffer_t buff_x, buff_y, buff_A;
    init_vector_buffer(M, x, incx, &buff_x);
    init_vector_buffer(N, y, incy, &buff_y);
    init_matrix_buffer(M, N, A, lda, &buff_A);

    assert_no_error(halide_dger(alpha, &buff_x, &buff_y, &buff_A));
}

//////////
// gemm //
//////////

void hblas_sgemm(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE TransA,
                 const enum HBLAS_TRANSPOSE TransB, const int M, const int N,
                 const int K, const float alpha, const float *A,
                 const int lda, const float *B, const int ldb,
                 const float beta, float *C, const int ldc) {
    bool tA = false, tB = false;
    switch (TransA) {
    case HblasNoTrans:
        tA = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tA = true; break;
    };

    switch (TransB) {
    case HblasNoTrans:
        tB = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tB = true; break;
    };

    buffer_t buff_A, buff_B, buff_C;
    if (!tA) {
        init_matrix_buffer(M, K, A, lda, &buff_A);
    } else {
        init_matrix_buffer(K, M, A, lda, &buff_A);
    }

    if (!tB) {
        init_matrix_buffer(K, N, B, ldb, &buff_B);
    } else {
        init_matrix_buffer(N, K, B, ldb, &buff_B);
    }

    init_matrix_buffer(M, N, C, ldc, &buff_C);

    assert_no_error(halide_sgemm(tA, tB, alpha, &buff_A, &buff_B, beta, &buff_C));
}

void hblas_dgemm(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE TransA,
                 const enum HBLAS_TRANSPOSE TransB, const int M, const int N,
                 const int K, const double alpha, const double *A,
                 const int lda, const double *B, const int ldb,
                 const double beta, double *C, const int ldc) {
    bool tA = false, tB = false;
    switch (TransA) {
    case HblasNoTrans:
        tA = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tA = true; break;
    };

    switch (TransB) {
    case HblasNoTrans:
        tB = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tB = true; break;
    };

    buffer_t buff_A, buff_B, buff_C;
    if (!tA) {
        init_matrix_buffer(M, K, A, lda, &buff_A);
    } else {
        init_matrix_buffer(K, M, A, lda, &buff_A);
    }

    if (!tB) {
        init_matrix_buffer(K, N, B, ldb, &buff_B);
    } else {
        init_matrix_buffer(N, K, B, ldb, &buff_B);
    }

    init_matrix_buffer(M, N, C, ldc, &buff_C);

    assert_no_error(halide_dgemm(tA, tB, alpha, &buff_A, &buff_B, beta, &buff_C));
}

#ifdef __cplusplus
}
#endif
<commit_msg>Remove some explicit buffer use from linear algebra<commit_after>#include <string.h>
#include <iostream>
#include "halide_blas.h"
#include "HalideBuffer.h"

using Halide::Buffer;

#define assert_no_error(func)                                       \
  if (func != 0) {                                                  \
    std::cerr << "ERROR! Halide kernel returned non-zero value.\n"; \
  }                                                                 \

namespace {

template<typename T>
Buffer<T> init_scalar_buffer(T *x) {
    return Buffer<T>(x, {});
}

template<typename T>
Buffer<T> init_vector_buffer(const int N, T *x, const int incx) {
    halide_dimension_t shape = {0, N, incx};
    return Buffer<T>(x, 1, &shape);
}

template<typename T>
Buffer<T> init_matrix_buffer(const int M, const int N, T *A, const int lda) {
    halide_dimension_t shape[] = {{0, M, 1}, {0, N, lda}};
    return Buffer<T>(A, 2, shape);
}

}

#ifdef __cplusplus
extern "C" {
#endif

//////////
// copy //
//////////

void hblas_scopy(const int N, const float *x, const int incx,
                 float *y, const int incy) {
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    assert_no_error(halide_scopy(buff_x, buff_y));
}

void hblas_dcopy(const int N, const double *x, const int incx,
                 double *y, const int incy) {
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    assert_no_error(halide_dcopy(buff_x, buff_y));
}

//////////
// scal //
//////////

void hblas_sscal(const int N, const float a, float *x, const int incx) {
    auto buff_x = init_vector_buffer(N, x, incx);
    assert_no_error(halide_sscal(a, buff_x));
}

void hblas_dscal(const int N, const double a, double *x, const int incx) {
    auto buff_x = init_vector_buffer(N, x, incx);
    assert_no_error(halide_dscal(a, buff_x));
}

//////////
// axpy //
//////////

void hblas_saxpy(const int N, const float a, const float *x, const int incx,
                 float *y, const int incy) {
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    assert_no_error(halide_saxpy(a, buff_x, buff_y));
}

void hblas_daxpy(const int N, const double a, const double *x, const int incx,
                 double *y, const int incy) {
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    assert_no_error(halide_daxpy(a, buff_x, buff_y));
}

//////////
// dot  //
//////////

float hblas_sdot(const int N, const float *x, const int incx,
                 const float *y, const int incy) {
    float result;
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    auto buff_dot = init_scalar_buffer(&result);
    assert_no_error(halide_sdot(buff_x, buff_y, buff_dot));
    return result;
}

double hblas_ddot(const int N, const double *x, const int incx,
                  const double *y, const int incy) {
    double result;
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    auto buff_dot = init_scalar_buffer(&result);
    assert_no_error(halide_ddot(buff_x, buff_y, buff_dot));
    return result;
}

//////////
// nrm2 //
//////////

float hblas_snrm2(const int N, const float *x, const int incx) {
    float result;
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_nrm = init_scalar_buffer(&result);
    assert_no_error(halide_sdot(buff_x, buff_x, buff_nrm));
    return std::sqrt(result);
}

double hblas_dnrm2(const int N, const double *x, const int incx) {
    double result;
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_nrm = init_scalar_buffer(&result);
    assert_no_error(halide_ddot(buff_x, buff_x, buff_nrm));
    return std::sqrt(result);
}

//////////
// asum //
//////////

float hblas_sasum(const int N, const float *x, const int incx) {
    float result;
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_sum = init_scalar_buffer(&result);
    assert_no_error(halide_sasum(buff_x, buff_sum));
    return result;
}

double hblas_dasum(const int N, const double *x, const int incx) {
    double result;
    auto buff_x = init_vector_buffer(N, x, incx);
    auto buff_sum = init_scalar_buffer(&result);
    assert_no_error(halide_dasum(buff_x, buff_sum));
    return result;
}

//////////
// gemv //
//////////

void hblas_sgemv(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE trans,
                 const int M, const int N, const float a, const float *A, const int lda,
                 const float *x, const int incx, const float b, float *y, const int incy) {
    bool t = false;
    switch (trans) {
    case HblasNoTrans:
        t = false; break;
    case HblasConjTrans:
    case HblasTrans:
        t = true; break;
    };

    auto buff_A = init_matrix_buffer(M, N, A, lda);
    auto buff_x = init_vector_buffer(t ? M : N, x, incx);
    auto buff_y = init_vector_buffer(t ? N : M, y, incy);

    assert_no_error(halide_sgemv(t, a, buff_A, buff_x, b, buff_y));
}

void hblas_dgemv(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE trans,
                 const int M, const int N, const double a, const double *A, const int lda,
                 const double *x, const int incx, const double b, double *y, const int incy) {
    bool t = false;
    switch (trans) {
    case HblasNoTrans:
        t = false; break;
    case HblasConjTrans:
    case HblasTrans:
        t = true; break;
    };

    auto buff_A = init_matrix_buffer(M, N, A, lda);
    auto buff_x = init_vector_buffer(t ? M : N, x, incx);
    auto buff_y = init_vector_buffer(t ? N : M, y, incy);

    assert_no_error(halide_dgemv(t, a, buff_A, buff_x, b, buff_y));
}

//////////
// ger  //
//////////

void hblas_sger(const enum HBLAS_ORDER order, const int M, const int N,
                const float alpha, const float *x, const int incx,
                const float *y, const int incy, float *A, const int lda)
{
    auto buff_x = init_vector_buffer(M, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    auto buff_A = init_matrix_buffer(M, N, A, lda);

    assert_no_error(halide_sger(alpha, buff_x, buff_y, buff_A));
}

void hblas_dger(const enum HBLAS_ORDER order, const int M, const int N,
                const double alpha, const double *x, const int incx,
                const double *y, const int incy, double *A, const int lda)
{
    auto buff_x = init_vector_buffer(M, x, incx);
    auto buff_y = init_vector_buffer(N, y, incy);
    auto buff_A = init_matrix_buffer(M, N, A, lda);

    assert_no_error(halide_dger(alpha, buff_x, buff_y, buff_A));
}

//////////
// gemm //
//////////

void hblas_sgemm(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE TransA,
                 const enum HBLAS_TRANSPOSE TransB, const int M, const int N,
                 const int K, const float alpha, const float *A,
                 const int lda, const float *B, const int ldb,
                 const float beta, float *C, const int ldc) {
    bool tA = false, tB = false;
    switch (TransA) {
    case HblasNoTrans:
        tA = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tA = true; break;
    };

    switch (TransB) {
    case HblasNoTrans:
        tB = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tB = true; break;
    };

    auto buff_A = init_matrix_buffer(tA ? K : M, tA ? M : K, A, lda);
    auto buff_B = init_matrix_buffer(tB ? N : K, tB ? K : N, B, ldb);
    auto buff_C = init_matrix_buffer(M, N, C, ldc);

    assert_no_error(halide_sgemm(tA, tB, alpha, buff_A, buff_B, beta, buff_C));
}

void hblas_dgemm(const enum HBLAS_ORDER Order, const enum HBLAS_TRANSPOSE TransA,
                 const enum HBLAS_TRANSPOSE TransB, const int M, const int N,
                 const int K, const double alpha, const double *A,
                 const int lda, const double *B, const int ldb,
                 const double beta, double *C, const int ldc) {
    bool tA = false, tB = false;
    switch (TransA) {
    case HblasNoTrans:
        tA = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tA = true; break;
    };

    switch (TransB) {
    case HblasNoTrans:
        tB = false; break;
    case HblasConjTrans:
    case HblasTrans:
        tB = true; break;
    };

    auto buff_A = init_matrix_buffer(tA ? K : M, tA ? M : K, A, lda);
    auto buff_B = init_matrix_buffer(tB ? N : K, tB ? K : N, B, ldb);
    auto buff_C = init_matrix_buffer(M, N, C, ldc);

    assert_no_error(halide_dgemm(tA, tB, alpha, buff_A, buff_B, beta, buff_C));
}

#ifdef __cplusplus
}
#endif
<|endoftext|>