<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

# include <dsn/ports.h>
# include <dsn/service_api_c.h>
# include <dsn/cpp/address.h>

# ifdef _WIN32

# else
# include <sys/socket.h>
# include <netdb.h>
# include <arpa/inet.h>

# if defined(__FreeBSD__)
# include <netinet/in.h>
# endif

# endif

# include <mutex>

static void net_init()
{
    static std::once_flag flag;
    static bool flag_inited = false;
    if (!flag_inited)
    {
        std::call_once(flag, [&]()
        {
#ifdef _WIN32
            WSADATA wsaData;
            WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
            flag_inited = true;
        });
    }
}

DSN_API void dsn_address_build(dsn_address_t* ep, const char* host, uint16_t port)
{
    net_init();

    ::dsn::rpc_address addr(HOST_TYPE_IPV4, host, port);
    *ep = addr.c_addr();
}

DSN_API void dsn_address_build_ipv4(
    /*out*/ dsn_address_t* ep,
    uint32_t ipv4,
    uint16_t port
    )
{
    net_init();
    ::dsn::rpc_address addr(ipv4, port);
    *ep = addr.c_addr();
}

// ip etc. to name
DSN_API void dsn_host_to_name(const dsn_address_t* addr, /*out*/ char* name_buffer, int length)
{
    switch (addr->type)
    {
    case HOST_TYPE_IPV4:
    {
        uint32_t nip = htonl(addr->ip);

        // TODO: using global cache
        auto host = gethostbyaddr((char*)&nip, 4, AF_INET);
        if (host == nullptr)
        {
# if defined(_WIN32)
            sprintf_s(
# else
            std::snprintf(
# endif
                name_buffer, (size_t)length,
                "%u.%u.%u.%u",
                nip & 0xff,
                (nip >> 8) & 0xff,
                (nip >> 16) & 0xff,
                (nip >> 24) & 0xff
                );
        }
        else
        {
            strncpy(name_buffer, host->h_name, length);
        }
        name_buffer[length - 1] = '\0';
    }
    break;
    case HOST_TYPE_IPV6:
        dassert(false, "to be implemented");
        break;
    case HOST_TYPE_URI:
        dassert(false, "to be implemented");
        break;
    default:
        break;
    }
}

// name to ip etc.
DSN_API void dsn_host_from_name(dsn_host_type_t type, const char* name, /*out*/ dsn_address_t* daddr)
{
    sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    daddr->type = type;
    switch (type)
    {
    case HOST_TYPE_IPV4:
        addr.sin_family = AF_INET;
        if ((addr.sin_addr.s_addr = inet_addr(name)) == (unsigned int)(-1))
        {
            hostent* hp = gethostbyname(name);
            if (hp != 0)
            {
                memcpy(
                    (void*)&(addr.sin_addr.s_addr),
                    (const void*)hp->h_addr,
                    (size_t)hp->h_length
                    );
            }
            else
            {
                int err = h_errno;
                dassert(false, "Fail to get host by name. error = %s.", ::hstrerror(err));
            }
        }

        // network order
        daddr->ip = (uint32_t)ntohl(addr.sin_addr.s_addr);
        break;

    case HOST_TYPE_IPV6:
        dassert(false, "to be implemented");
        break;

    case HOST_TYPE_URI:
        daddr->uri = name;
        break;

    default:
        break;
    }
}
<commit_msg>Nits.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Microsoft Corporation
 *
 * -=- Robust Distributed System Nucleus (rDSN) -=-
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

# include <dsn/ports.h>
# include <dsn/service_api_c.h>
# include <dsn/cpp/address.h>

# ifdef _WIN32

# else
# include <sys/socket.h>
# include <netdb.h>
# include <arpa/inet.h>

# if defined(__FreeBSD__)
# include <netinet/in.h>
# endif

# endif

# include <mutex>

static void net_init()
{
    static std::once_flag flag;
    static bool flag_inited = false;
    if (!flag_inited)
    {
        std::call_once(flag, [&]()
        {
#ifdef _WIN32
            WSADATA wsaData;
            WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
            flag_inited = true;
        });
    }
}

DSN_API void dsn_address_build(dsn_address_t* ep, const char* host, uint16_t port)
{
    net_init();

    ::dsn::rpc_address addr(HOST_TYPE_IPV4, host, port);
    *ep = addr.c_addr();
}

DSN_API void dsn_address_build_ipv4(
    /*out*/ dsn_address_t* ep,
    uint32_t ipv4,
    uint16_t port
    )
{
    net_init();
    ::dsn::rpc_address addr(ipv4, port);
    *ep = addr.c_addr();
}

// ip etc. to name
DSN_API void dsn_host_to_name(const dsn_address_t* addr, /*out*/ char* name_buffer, int length)
{
    switch (addr->type)
    {
    case HOST_TYPE_IPV4:
    {
        uint32_t nip = htonl(addr->ip);

        // TODO: using global cache
        auto host = gethostbyaddr((char*)&nip, 4, AF_INET);
        if (host == nullptr)
        {
# if defined(_WIN32)
            sprintf_s(
# else
            std::snprintf(
# endif
                name_buffer, (size_t)length,
                "%u.%u.%u.%u",
                nip & 0xff,
                (nip >> 8) & 0xff,
                (nip >> 16) & 0xff,
                (nip >> 24) & 0xff
                );
        }
        else
        {
            strncpy(name_buffer, host->h_name, length);
        }
        name_buffer[length - 1] = '\0';
    }
    break;
    case HOST_TYPE_IPV6:
        dassert(false, "to be implemented");
        break;
    case HOST_TYPE_URI:
        dassert(false, "to be implemented");
        break;
    default:
        break;
    }
}

// name to ip etc.
DSN_API void dsn_host_from_name(dsn_host_type_t type, const char* name, /*out*/ dsn_address_t* daddr)
{
    sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    daddr->type = type;
    switch (type)
    {
    case HOST_TYPE_IPV4:
        addr.sin_family = AF_INET;
        if ((addr.sin_addr.s_addr = inet_addr(name)) == (unsigned int)(-1))
        {
            hostent* hp = gethostbyname(name);
            dassert(hp != nullptr, "gethostbyname failed, err = %s.", ::hstrerror(h_errno));
            if (hp != nullptr)
            {
                memcpy(
                    (void*)&(addr.sin_addr.s_addr),
                    (const void*)hp->h_addr,
                    (size_t)hp->h_length
                    );
            }
        }

        // network order
        daddr->ip = (uint32_t)ntohl(addr.sin_addr.s_addr);
        break;

    case HOST_TYPE_IPV6:
        dassert(false, "to be implemented");
        break;

    case HOST_TYPE_URI:
        daddr->uri = name;
        break;

    default:
        break;
    }
}
<|endoftext|>


<commit_before>#include "connection_manager.hpp"
#include "karabiner_version.h"
#include <iostream>
#include <unistd.h>

int main(int argc, const char* argv[]) {
  if (getuid() != 0) {
    std::cerr << "fatal: karabiner_grabber requires root privilege." << std::endl;
    exit(1);
  }

  signal(SIGUSR1, SIG_IGN);
  signal(SIGUSR2, SIG_IGN);

  logger::get_logger().info("version {0}", karabiner_version);

  device_grabber device_grabber;
  connection_manager connection_manager(device_grabber);

  CFRunLoopRun();

  return 0;
}
<commit_msg>post grabber_is_launched notification<commit_after>#include "connection_manager.hpp"
#include "constants.hpp"
#include "karabiner_version.h"
#include "notification_center.hpp"
#include <iostream>
#include <unistd.h>

int main(int argc, const char* argv[]) {
  if (getuid() != 0) {
    std::cerr << "fatal: karabiner_grabber requires root privilege." << std::endl;
    exit(1);
  }

  signal(SIGUSR1, SIG_IGN);
  signal(SIGUSR2, SIG_IGN);

  logger::get_logger().info("version {0}", karabiner_version);

  device_grabber device_grabber;
  connection_manager connection_manager(device_grabber);

  notification_center::post_distributed_notification_to_all_sessions(constants::get_distributed_notification_grabber_is_launched());

  CFRunLoopRun();

  return 0;
}
<|endoftext|>


<commit_before>#include "crossVideoGrabber.h"

void crossVideoGrabber::setup(string filename){

  videoFlag = videoPlayer.load("movies/"+filename);
  if (videoFlag) {
    videoPlayer.setLoopState(OF_LOOP_NORMAL);
    videoPlayer.play();
  } else {
#ifdef TARGET_RASPBERRY_PI
    cam.setup(1920,1080,false);
    //cam.setup(2592, 1944, false);
    led.switchOnIR();
#else
    cam.initGrabber(640, 480);
#endif
  }
}

void crossVideoGrabber::update(){
  if ( videoFlag ) {
    videoPlayer.update();
  } else {
#ifdef TARGET_RASPBERRY_PI
    newFrame = cam.isFrameNew();
    frame = cam.grab();
#else
    cam.update();
#endif
  }
}
void crossVideoGrabber::draw(int x, int y){
  if ( videoFlag ){
    videoPlayer.draw(x,y);
  } else {
#ifndef TARGET_RASPBERRY_PI
    cam.draw(x,y);
#else
    ofxCv::drawMat(frame,0,0,ofGetWidth(), ofGetHeight());
#endif
  }
}
<commit_msg>strech input video to fulfill the display<commit_after>#include "crossVideoGrabber.h"

void crossVideoGrabber::setup(string filename){

  videoFlag = videoPlayer.load("movies/"+filename);
  if (videoFlag) {
    videoPlayer.setLoopState(OF_LOOP_NORMAL);
    videoPlayer.play();
  } else {
#ifdef TARGET_RASPBERRY_PI
    cam.setup(1920,1080,false);
    //cam.setup(2592, 1944, false);
    led.switchOnIR();
#else
    cam.initGrabber(640, 480);
#endif
  }
}

void crossVideoGrabber::update(){
  if ( videoFlag ) {
    videoPlayer.update();
  } else {
#ifdef TARGET_RASPBERRY_PI
    newFrame = cam.isFrameNew();
    frame = cam.grab();
#else
    cam.update();
#endif
  }
}
void crossVideoGrabber::draw(int x, int y){
  if ( videoFlag ){
    videoPlayer.draw(x,y,ofGetWidth(), ofGetHeight());
  } else {
#ifndef TARGET_RASPBERRY_PI
    cam.draw(x,y);
#else
    ofxCv::drawMat(frame,0,0,ofGetWidth(), ofGetHeight());
#endif
  }
}
<|endoftext|>


<commit_before>#include "vtrace.h"
#include "../logger.h"

ViterbiTraceMatrix::ViterbiTraceMatrix (const EvaluatedMachine& eval, const GaussianModelParams& modelParams, const TraceMoments& trace, const TraceParams& traceParams, size_t blockBytes, double bandWidth) :
  TraceDPMatrix (eval, modelParams, trace, traceParams, blockBytes, bandWidth)
{
  ProgressLog(plog,3);
  plog.initProgress ("Viterbi algorithm (%ld samples, %u states, %u transitions)", outLen, nStates, nTrans);

  cell(0,eval.startState()) = 0;
  for (const auto& it: nullTrans)
    update (0, it.dest, cell(0,it.src) + it.logWeight, it.in);

  for (OutputIndex outPos = 1; outPos <= outLen; ++outPos) {
    plog.logProgress ((outPos - 1) / (double) outLen, "sample %ld/%ld", outPos, outLen);
    fillColumn (outPos);
  }

  logLike = cell (outLen, eval.endState());
  LogThisAt(6,"Viterbi log-likelihood: " << logLike << endl);
  LogThisAt(10,"Viterbi matrix:" << endl << *this);
}

void ViterbiTraceMatrix::fillColumn (OutputIndex outPos) {
  vguard<double>& thisColumn = column(outPos);
  initColumn (thisColumn);
  const auto itBegin = bandTransBegin(outPos);
  const auto itEnd = bandTransEnd(outPos);
  for (auto itIter = itBegin; itIter != itEnd; ++itIter) {
    const auto& it = *itIter;
    const OutputToken outTok = it.out;
    const double llEmit = logEmitProb(outPos,outTok);
    update (outPos, it.dest, cell(outPos-1,it.src) + logTransProb(outPos,it) + llEmit, it.in);
  }

  for (const auto& it: nullTrans)
    update (outPos, it.dest, cell(outPos,it.src) + it.logWeight, it.in);

  lastCheckpoint = checkpoint(outPos);
}

void ViterbiTraceMatrix::readyColumn (OutputIndex outPos) {
  const OutputIndex blockStart = checkpoint(outPos);
  if (blockStart != lastCheckpoint) {
    const OutputIndex blockEnd = min((OutputIndex)nColumns,blockStart+blockSize) - 1;
    LogThisAt(4,"Refilling Viterbi matrix from sample " << (blockStart+1) << " to " << blockEnd << endl);

    for (OutputIndex outPos = blockStart + 1; outPos <= blockEnd; ++outPos)
      fillColumn (outPos);
  }
}

MachinePath ViterbiTraceMatrix::path (const Machine& m) {
  Assert (logLike > -numeric_limits<double>::infinity(), "Can't do Viterbi traceback: no finite-weight paths");
  MachinePath path;
  OutputIndex outPos = outLen;
  StateIndex s = nStates - 1;
  while (outPos > 0 || s != 0) {
    const EvaluatedMachineState& state = eval.state[s];
    double bestLogLike = -numeric_limits<double>::infinity();
    const EvaluatedMachineState::Trans *bestTrans, *bestLoopTrans = NULL;
    StateIndex bestSource;
    readyColumn (outPos - 1);
    for (const auto& inTok_outStateTransMap: state.incoming) {
      const InputToken inTok = inTok_outStateTransMap.first;
      for (const auto& outTok_stateTransMap: inTok_outStateTransMap.second) {
	const OutputToken outTok = outTok_stateTransMap.first;
	if (outTok == 0 || outPos > 0)
	  for (const auto& src_trans: outTok_stateTransMap.second) {
	    const double tll = logIncomingProb (inTok, outTok, outPos, src_trans.first, s, src_trans.second);
	    if (tll > bestLogLike) {
	      bestLogLike = tll;
	      bestLoopTrans = getLoopTrans (inTok, outTok, s);
	      bestSource = src_trans.first;
	      bestTrans = &src_trans.second;
	    }
	  }
      }
    }
    const MachineTransition& bestMachineTrans = m.state[bestSource].getTransition (bestTrans->transIndex);
    if (!bestMachineTrans.outputEmpty()) {
      if (bestLoopTrans) {
	const MachineTransition& bestLoopMachineTrans = m.state[s].getTransition (bestLoopTrans->transIndex);
	const auto& mom = moments.sample[outPos-1];
	for (int n = 1; n < mom.m0; ++n)
	  path.trans.push_front (bestLoopMachineTrans);
      }
      --outPos;
    }
    s = bestSource;
    path.trans.push_front (bestMachineTrans);
  }
  return path;
}
<commit_msg>Logging during Viterbi traceback<commit_after>#include "vtrace.h"
#include "../logger.h"

ViterbiTraceMatrix::ViterbiTraceMatrix (const EvaluatedMachine& eval, const GaussianModelParams& modelParams, const TraceMoments& trace, const TraceParams& traceParams, size_t blockBytes, double bandWidth) :
  TraceDPMatrix (eval, modelParams, trace, traceParams, blockBytes, bandWidth)
{
  ProgressLog(plog,3);
  plog.initProgress ("Viterbi algorithm (%ld samples, %u states, %u transitions)", outLen, nStates, nTrans);

  cell(0,eval.startState()) = 0;
  for (const auto& it: nullTrans)
    update (0, it.dest, cell(0,it.src) + it.logWeight, it.in);

  for (OutputIndex outPos = 1; outPos <= outLen; ++outPos) {
    plog.logProgress ((outPos - 1) / (double) outLen, "sample %ld/%ld", outPos, outLen);
    fillColumn (outPos);
  }

  logLike = cell (outLen, eval.endState());
  LogThisAt(6,"Viterbi log-likelihood: " << logLike << endl);
  LogThisAt(10,"Viterbi matrix:" << endl << *this);
}

void ViterbiTraceMatrix::fillColumn (OutputIndex outPos) {
  vguard<double>& thisColumn = column(outPos);
  initColumn (thisColumn);
  const auto itBegin = bandTransBegin(outPos);
  const auto itEnd = bandTransEnd(outPos);
  for (auto itIter = itBegin; itIter != itEnd; ++itIter) {
    const auto& it = *itIter;
    const OutputToken outTok = it.out;
    const double llEmit = logEmitProb(outPos,outTok);
    update (outPos, it.dest, cell(outPos-1,it.src) + logTransProb(outPos,it) + llEmit, it.in);
  }

  for (const auto& it: nullTrans)
    update (outPos, it.dest, cell(outPos,it.src) + it.logWeight, it.in);

  lastCheckpoint = checkpoint(outPos);
}

void ViterbiTraceMatrix::readyColumn (OutputIndex outPos) {
  const OutputIndex blockStart = checkpoint(outPos);
  if (blockStart != lastCheckpoint) {
    const OutputIndex blockEnd = min((OutputIndex)nColumns,blockStart+blockSize) - 1;
    LogThisAt(4,"Refilling Viterbi matrix from sample " << (blockStart+1) << " to " << blockEnd << endl);

    for (OutputIndex outPos = blockStart + 1; outPos <= blockEnd; ++outPos)
      fillColumn (outPos);
  }
}

MachinePath ViterbiTraceMatrix::path (const Machine& m) {
  Assert (logLike > -numeric_limits<double>::infinity(), "Can't do Viterbi traceback: no finite-weight paths");
  ProgressLog(plog,3);
  plog.initProgress ("Viterbi traceback (%ld samples, %u states, %u transitions)", outLen, nStates, nTrans);
  MachinePath path;
  OutputIndex outPos = outLen;
  StateIndex s = nStates - 1;
  while (outPos > 0 || s != 0) {
    plog.logProgress ((outLen - outPos) / (double) outLen, "sample %ld/%ld", outPos, outLen);
    const EvaluatedMachineState& state = eval.state[s];
    double bestLogLike = -numeric_limits<double>::infinity();
    const EvaluatedMachineState::Trans *bestTrans, *bestLoopTrans = NULL;
    StateIndex bestSource;
    readyColumn (outPos - 1);
    for (const auto& inTok_outStateTransMap: state.incoming) {
      const InputToken inTok = inTok_outStateTransMap.first;
      for (const auto& outTok_stateTransMap: inTok_outStateTransMap.second) {
	const OutputToken outTok = outTok_stateTransMap.first;
	if (outTok == 0 || outPos > 0)
	  for (const auto& src_trans: outTok_stateTransMap.second) {
	    const double tll = logIncomingProb (inTok, outTok, outPos, src_trans.first, s, src_trans.second);
	    if (tll > bestLogLike) {
	      bestLogLike = tll;
	      bestLoopTrans = getLoopTrans (inTok, outTok, s);
	      bestSource = src_trans.first;
	      bestTrans = &src_trans.second;
	    }
	  }
      }
    }
    const MachineTransition& bestMachineTrans = m.state[bestSource].getTransition (bestTrans->transIndex);
    if (!bestMachineTrans.outputEmpty()) {
      if (bestLoopTrans) {
	const MachineTransition& bestLoopMachineTrans = m.state[s].getTransition (bestLoopTrans->transIndex);
	const auto& mom = moments.sample[outPos-1];
	for (int n = 1; n < mom.m0; ++n)
	  path.trans.push_front (bestLoopMachineTrans);
      }
      --outPos;
    }
    s = bestSource;
    path.trans.push_front (bestMachineTrans);
  }
  return path;
}
<|endoftext|>


<commit_before>#include "progress.h"
#include "simulator.h"
#include "config.hpp"
#include "core_manager.h"
#include "hooks_manager.h"
#include "trace_manager.h"
#include "magic_server.h"

Progress::Progress()
   : m_enabled(false)
   , m_t_last(0)
   , m_manual(false)
   , m_manual_value(0.f)
{
   String filename = Sim()->getCfg()->getString("progress_trace/filename");

   if (!filename.empty())
   {
      m_fp = fopen(filename.c_str(), "w");
      m_enabled = true;

      Sim()->getHooksManager()->registerHook(HookType::HOOK_PERIODIC_INS, __record, (UInt64)this);
   }
}

Progress::~Progress(void)
{
   if (m_enabled)
   {
      record(0);
      fclose(m_fp);
   }
}

void Progress::setProgress(float progress)
{
   m_manual = true;
   m_manual_value = progress;
}

void Progress::record(UInt64 simtime)
{
   if (m_t_last + m_interval < time(NULL))
   {
      m_t_last = time(NULL);

      UInt64 expect = 0;

      // Always return global instruction count, so MIPS number as reported by job infrastructure is correct
      UInt64 progress = MagicServer::getGlobalInstructionCount();

      if (m_manual && m_manual_value > 0)
      {
         // Re-compute expected completion based on current progress
         expect = progress / m_manual_value;
      }
      else if (Sim()->getTraceManager())
      {
         UInt64 _expect = Sim()->getTraceManager()->getProgressExpect();
         UInt64 _progress = Sim()->getTraceManager()->getProgressValue();

         // Re-compute expected completion based on file-pointer based % to completion,
         // and the progress value (instruction count) we'll return
         if (_progress > 1)
            expect = progress * _expect / _progress;
         else
            expect = 100000 * progress;
      }

      rewind(m_fp);
      fprintf(m_fp, "%u %" PRId64 " %" PRId64, unsigned(time(NULL)), progress, expect);
      fflush(m_fp);
   }
}
<commit_msg>[progress] Do not callt to update the progress in the destructor as the CoreManager() has already been destroyed (needed by MagicServer::getGlobalInstructionCount())<commit_after>#include "progress.h"
#include "simulator.h"
#include "config.hpp"
#include "core_manager.h"
#include "hooks_manager.h"
#include "trace_manager.h"
#include "magic_server.h"

Progress::Progress()
   : m_enabled(false)
   , m_t_last(0)
   , m_manual(false)
   , m_manual_value(0.f)
{
   String filename = Sim()->getCfg()->getString("progress_trace/filename");

   if (!filename.empty())
   {
      m_fp = fopen(filename.c_str(), "w");
      m_enabled = true;

      Sim()->getHooksManager()->registerHook(HookType::HOOK_PERIODIC_INS, __record, (UInt64)this);
   }
}

Progress::~Progress(void)
{
   if (m_enabled)
   {
      fclose(m_fp);
   }
}

void Progress::setProgress(float progress)
{
   m_manual = true;
   m_manual_value = progress;
}

void Progress::record(UInt64 simtime)
{
   if (m_t_last + m_interval < time(NULL))
   {
      m_t_last = time(NULL);

      UInt64 expect = 0;

      // Always return global instruction count, so MIPS number as reported by job infrastructure is correct
      UInt64 progress = MagicServer::getGlobalInstructionCount();

      if (m_manual && m_manual_value > 0)
      {
         // Re-compute expected completion based on current progress
         expect = progress / m_manual_value;
      }
      else if (Sim()->getTraceManager())
      {
         UInt64 _expect = Sim()->getTraceManager()->getProgressExpect();
         UInt64 _progress = Sim()->getTraceManager()->getProgressValue();

         // Re-compute expected completion based on file-pointer based % to completion,
         // and the progress value (instruction count) we'll return
         if (_progress > 1)
            expect = progress * _expect / _progress;
         else
            expect = 100000 * progress;
      }

      rewind(m_fp);
      fprintf(m_fp, "%u %" PRId64 " %" PRId64, unsigned(time(NULL)), progress, expect);
      fflush(m_fp);
   }
}
<|endoftext|>


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

#include "common/node_bindings.h"

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "v8/include/v8.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h"
#include "vendor/node/src/node_javascript.h"

namespace atom {

NodeBindings::NodeBindings(bool is_browser)
    : is_browser_(is_browser) {
}

NodeBindings::~NodeBindings() {
}

void NodeBindings::Initialize() {
  CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv();

  // Convert string vector to char* array.
  std::vector<char*> argv(str_argv.size(), NULL);
  for (size_t i = 0; i < str_argv.size(); ++i)
    argv[i] = const_cast<char*>(str_argv[i].c_str());

  // Open node's error reporting system for browser process.
  node::g_standalone_mode = is_browser_;

  // Init node.
  node::Init(argv.size(), &argv[0]);
  v8::V8::Initialize();

  // Load node.js.
  v8::HandleScope scope;
  node::g_context = v8::Persistent<v8::Context>::New(
      node::node_isolate, v8::Context::New(node::node_isolate));
  {
    v8::Context::Scope context_scope(node::g_context);
    v8::Handle<v8::Object> process = node::SetupProcessObject(
        argv.size(), &argv[0]);

    // Tell node.js we are in browser or renderer.
    v8::Handle<v8::String> type =
        is_browser_ ? v8::String::New("browser") : v8::String::New("renderer");
    process->Set(v8::String::New("__atom_type"), type);
  }
}

void NodeBindings::Load() {
  v8::HandleScope scope;
  v8::Context::Scope context_scope(node::g_context);
  node::Load(node::process);
}

void NodeBindings::BindTo(WebKit::WebFrame* frame) {
  v8::HandleScope handle_scope;

  v8::Handle<v8::Context> context = frame->mainWorldScriptContext();
  if (context.IsEmpty())
    return;

  v8::Context::Scope scope(context);

  // Erase security token.
  context->SetSecurityToken(node::g_context->GetSecurityToken());

  // Evaluate cefode.js.
  v8::Handle<v8::Script> script = node::CompileCefodeMainSource();
  v8::Local<v8::Value> result = script->Run();

  // Run the script of cefode.js.
  std::string script_path(GURL(frame->document().url()).path());
  v8::Handle<v8::Value> args[2] = {
    v8::Local<v8::Value>::New(node::process),
    v8::String::New(script_path.c_str(), script_path.size())
  };
  v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args);
}

}  // namespace atom
<commit_msg>Implement converting string vector to char pointer array on Windows.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "common/node_bindings.h"

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "v8/include/v8.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "vendor/node/src/node.h"
#include "vendor/node/src/node_internals.h"
#include "vendor/node/src/node_javascript.h"

namespace atom {

NodeBindings::NodeBindings(bool is_browser)
    : is_browser_(is_browser) {
}

NodeBindings::~NodeBindings() {
}

void NodeBindings::Initialize() {
  CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv();

#if defined(OS_WIN)
  std::vector<std::string> utf8_str_argv;
  utf8_str_argv.reserve(str_argv.size());
#endif

  // Convert string vector to char* array.
  std::vector<char*> argv(str_argv.size(), NULL);
  for (size_t i = 0; i < str_argv.size(); ++i) {
#if defined(OS_WIN)
    utf8_str_argv.push_back(UTF16ToUTF8(str_argv[i]));
    argv[i] = const_cast<char*>(utf8_str_argv[i].c_str());
#else
    argv[i] = const_cast<char*>(str_argv[i].c_str());
#endif
  }

  // Open node's error reporting system for browser process.
  node::g_standalone_mode = is_browser_;

  // Init node.
  node::Init(argv.size(), &argv[0]);
  v8::V8::Initialize();

  // Load node.js.
  v8::HandleScope scope;
  node::g_context = v8::Persistent<v8::Context>::New(
      node::node_isolate, v8::Context::New(node::node_isolate));
  {
    v8::Context::Scope context_scope(node::g_context);
    v8::Handle<v8::Object> process = node::SetupProcessObject(
        argv.size(), &argv[0]);

    // Tell node.js we are in browser or renderer.
    v8::Handle<v8::String> type =
        is_browser_ ? v8::String::New("browser") : v8::String::New("renderer");
    process->Set(v8::String::New("__atom_type"), type);
  }
}

void NodeBindings::Load() {
  v8::HandleScope scope;
  v8::Context::Scope context_scope(node::g_context);
  node::Load(node::process);
}

void NodeBindings::BindTo(WebKit::WebFrame* frame) {
  v8::HandleScope handle_scope;

  v8::Handle<v8::Context> context = frame->mainWorldScriptContext();
  if (context.IsEmpty())
    return;

  v8::Context::Scope scope(context);

  // Erase security token.
  context->SetSecurityToken(node::g_context->GetSecurityToken());

  // Evaluate cefode.js.
  v8::Handle<v8::Script> script = node::CompileCefodeMainSource();
  v8::Local<v8::Value> result = script->Run();

  // Run the script of cefode.js.
  std::string script_path(GURL(frame->document().url()).path());
  v8::Handle<v8::Value> args[2] = {
    v8::Local<v8::Value>::New(node::process),
    v8::String::New(script_path.c_str(), script_path.size())
  };
  v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args);
}

}  // namespace atom
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.

// This file is all the code that used to be in one file.
// TODO: split into modules, delete this file.

#include "ninja.h"

#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>

#include "build_log.h"
#include "graph.h"

int ReadFile(const string& path, string* contents, string* err) {
  FILE* f = fopen(path.c_str(), "r");
  if (!f) {
    err->assign(strerror(errno));
    return -errno;
  }

  char buf[64 << 10];
  size_t len;
  while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
    contents->append(buf, len);
  }
  if (ferror(f)) {
    err->assign(strerror(errno));  // XXX errno?
    contents->clear();
    fclose(f);
    return -errno;
  }
  fclose(f);
  return 0;
}

int RealDiskInterface::Stat(const string& path) {
  struct stat st;
  if (stat(path.c_str(), &st) < 0) {
    if (errno == ENOENT) {
      return 0;
    } else {
      fprintf(stderr, "stat(%s): %s\n", path.c_str(), strerror(errno));
      return -1;
    }
  }

  return st.st_mtime;
  return true;
}

string DirName(const string& path) {
  string::size_type slash_pos = path.rfind('/');
  if (slash_pos == string::npos)
    return "";  // Nothing to do.
  while (slash_pos > 0 && path[slash_pos - 1] == '/')
    --slash_pos;
  return path.substr(0, slash_pos);
}

bool DiskInterface::MakeDirs(const string& path) {
  string dir = DirName(path);
  if (dir.empty())
    return true;  // Reached root; assume it's there.
  int mtime = Stat(dir);
  if (mtime < 0)
    return false;  // Error.
  if (mtime > 0)
    return true;  // Exists already; we're done.

  // Directory doesn't exist.  Try creating its parent first.
  bool success = MakeDirs(dir);
  if (!success)
    return false;
  return MakeDir(dir);
}

string RealDiskInterface::ReadFile(const string& path, string* err) {
  string contents;
  int ret = ::ReadFile(path, &contents, err);
  if (ret == -ENOENT) {
    // Swallow ENOENT.
    err->clear();
  }
  return contents;
}

bool RealDiskInterface::MakeDir(const string& path) {
  if (mkdir(path.c_str(), 0777) < 0) {
    fprintf(stderr, "mkdir(%s): %s\n", path.c_str(), strerror(errno));
    return false;
  }
  return true;
}

FileStat* StatCache::GetFile(const string& path) {
  Paths::iterator i = paths_.find(path);
  if (i != paths_.end())
    return i->second;
  FileStat* file = new FileStat(path);
  paths_[path] = file;
  return file;
}

#include <stdio.h>

void StatCache::Dump() {
  for (Paths::iterator i = paths_.begin(); i != paths_.end(); ++i) {
    FileStat* file = i->second;
    printf("%s %s\n",
           file->path_.c_str(),
           file->status_known()
           ? (file->node_->dirty_ ? "dirty" : "clean")
           : "unknown");
  }
}

const Rule State::kPhonyRule("phony");

State::State() : build_log_(NULL) {
  AddRule(&kPhonyRule);
}

const Rule* State::LookupRule(const string& rule_name) {
  map<string, const Rule*>::iterator i = rules_.find(rule_name);
  if (i == rules_.end())
    return NULL;
  return i->second;
}

void State::AddRule(const Rule* rule) {
  assert(LookupRule(rule->name_) == NULL);
  rules_[rule->name_] = rule;
}

Edge* State::AddEdge(const Rule* rule) {
  Edge* edge = new Edge();
  edge->rule_ = rule;
  edge->env_ = &bindings_;
  edges_.push_back(edge);
  return edge;
}

Node* State::LookupNode(const string& path) {
  FileStat* file = stat_cache_.GetFile(path);
  if (!file->node_)
    return NULL;
  return file->node_;
}

Node* State::GetNode(const string& path) {
  FileStat* file = stat_cache_.GetFile(path);
  if (!file->node_)
    file->node_ = new Node(file);
  return file->node_;
}

void State::AddIn(Edge* edge, const string& path) {
  Node* node = GetNode(path);
  edge->inputs_.push_back(node);
  node->out_edges_.push_back(edge);
}

void State::AddOut(Edge* edge, const string& path) {
  Node* node = GetNode(path);
  edge->outputs_.push_back(node);
  if (node->in_edge_) {
    fprintf(stderr, "WARNING: multiple rules generate %s. "
            "build will not be correct; continuing anyway\n", path.c_str());
  }
  node->in_edge_ = edge;
}
<commit_msg>Use Error() to report error.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.

// This file is all the code that used to be in one file.
// TODO: split into modules, delete this file.

#include "ninja.h"

#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>

#include "build_log.h"
#include "graph.h"
#include "util.h"

int ReadFile(const string& path, string* contents, string* err) {
  FILE* f = fopen(path.c_str(), "r");
  if (!f) {
    err->assign(strerror(errno));
    return -errno;
  }

  char buf[64 << 10];
  size_t len;
  while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
    contents->append(buf, len);
  }
  if (ferror(f)) {
    err->assign(strerror(errno));  // XXX errno?
    contents->clear();
    fclose(f);
    return -errno;
  }
  fclose(f);
  return 0;
}

int RealDiskInterface::Stat(const string& path) {
  struct stat st;
  if (stat(path.c_str(), &st) < 0) {
    if (errno == ENOENT) {
      return 0;
    } else {
      Error("stat(%s): %s", path.c_str(), strerror(errno));
      return -1;
    }
  }

  return st.st_mtime;
  return true;
}

string DirName(const string& path) {
  string::size_type slash_pos = path.rfind('/');
  if (slash_pos == string::npos)
    return "";  // Nothing to do.
  while (slash_pos > 0 && path[slash_pos - 1] == '/')
    --slash_pos;
  return path.substr(0, slash_pos);
}

bool DiskInterface::MakeDirs(const string& path) {
  string dir = DirName(path);
  if (dir.empty())
    return true;  // Reached root; assume it's there.
  int mtime = Stat(dir);
  if (mtime < 0)
    return false;  // Error.
  if (mtime > 0)
    return true;  // Exists already; we're done.

  // Directory doesn't exist.  Try creating its parent first.
  bool success = MakeDirs(dir);
  if (!success)
    return false;
  return MakeDir(dir);
}

string RealDiskInterface::ReadFile(const string& path, string* err) {
  string contents;
  int ret = ::ReadFile(path, &contents, err);
  if (ret == -ENOENT) {
    // Swallow ENOENT.
    err->clear();
  }
  return contents;
}

bool RealDiskInterface::MakeDir(const string& path) {
  if (mkdir(path.c_str(), 0777) < 0) {
    Error("mkdir(%s): %s", path.c_str(), strerror(errno));
    return false;
  }
  return true;
}

FileStat* StatCache::GetFile(const string& path) {
  Paths::iterator i = paths_.find(path);
  if (i != paths_.end())
    return i->second;
  FileStat* file = new FileStat(path);
  paths_[path] = file;
  return file;
}

#include <stdio.h>

void StatCache::Dump() {
  for (Paths::iterator i = paths_.begin(); i != paths_.end(); ++i) {
    FileStat* file = i->second;
    printf("%s %s\n",
           file->path_.c_str(),
           file->status_known()
           ? (file->node_->dirty_ ? "dirty" : "clean")
           : "unknown");
  }
}

const Rule State::kPhonyRule("phony");

State::State() : build_log_(NULL) {
  AddRule(&kPhonyRule);
}

const Rule* State::LookupRule(const string& rule_name) {
  map<string, const Rule*>::iterator i = rules_.find(rule_name);
  if (i == rules_.end())
    return NULL;
  return i->second;
}

void State::AddRule(const Rule* rule) {
  assert(LookupRule(rule->name_) == NULL);
  rules_[rule->name_] = rule;
}

Edge* State::AddEdge(const Rule* rule) {
  Edge* edge = new Edge();
  edge->rule_ = rule;
  edge->env_ = &bindings_;
  edges_.push_back(edge);
  return edge;
}

Node* State::LookupNode(const string& path) {
  FileStat* file = stat_cache_.GetFile(path);
  if (!file->node_)
    return NULL;
  return file->node_;
}

Node* State::GetNode(const string& path) {
  FileStat* file = stat_cache_.GetFile(path);
  if (!file->node_)
    file->node_ = new Node(file);
  return file->node_;
}

void State::AddIn(Edge* edge, const string& path) {
  Node* node = GetNode(path);
  edge->inputs_.push_back(node);
  node->out_edges_.push_back(edge);
}

void State::AddOut(Edge* edge, const string& path) {
  Node* node = GetNode(path);
  edge->outputs_.push_back(node);
  if (node->in_edge_) {
    Error("WARNING: multiple rules generate %s. "
          "build will not be correct; continuing anyway", path.c_str());
  }
  node->in_edge_ = edge;
}
<|endoftext|>


<commit_before>//
// Created by Dawid Drozd aka Gelldur on 18/10/16.
//

#include <eventbus/EventCollector.h>

#include <cassert>

namespace
{

void null_deleter(Dexode::EventBus*)
{
}

}

namespace Dexode
{

EventCollector::EventCollector(const std::shared_ptr<EventBus>& bus)
		: _bus(bus)
{
	assert(_bus);
}

//Maybe ugly but hey ;) Less code and simply i can :D
EventCollector::EventCollector(EventBus* bus)
		: _bus(bus, &null_deleter)
{
}

EventCollector::EventCollector(const EventCollector& other)
		: _bus(other._bus)
{
}

EventCollector::EventCollector(EventCollector&& other)
		: _token(other._token)
		, _bus(std::move(other._bus))
{
	other._token = 0;
}

EventCollector::~EventCollector()
{
	unlistenAll();
}

EventCollector& EventCollector::operator=(const EventCollector& other)
{
	std::unique_ptr<int> vector3;
	if (this == &other)
	{
		return *this;
	}
	if (other._bus.get() != _bus.get())
	{
		unlistenAll();
		_bus = other._bus;
	}

	return *this;
}

EventCollector& EventCollector::operator=(EventCollector&& other)
{
	if (this == &other)
	{
		return *this;
	}

	unlistenAll();

	_token = other._token;
	other._token = 0;
	_bus = std::move(other._bus);

	return *this;
}

void EventCollector::unlistenAll()
{
	if (_token != 0 && _bus)
	{
		_bus->unlistenAll(_token);
	}
}

bool EventCollector::isUsing(const std::shared_ptr<EventBus>& bus) const
{
	return _bus == bus;
}

}
<commit_msg>Remove some trash<commit_after>//
// Created by Dawid Drozd aka Gelldur on 18/10/16.
//

#include <eventbus/EventCollector.h>

#include <cassert>

namespace
{

void null_deleter(Dexode::EventBus*)
{
}

}

namespace Dexode
{

EventCollector::EventCollector(const std::shared_ptr<EventBus>& bus)
		: _bus(bus)
{
	assert(_bus);
}

//Maybe ugly but hey ;) Less code and simply i can :D
EventCollector::EventCollector(EventBus* bus)
		: _bus(bus, &null_deleter)
{
}

EventCollector::EventCollector(const EventCollector& other)
		: _bus(other._bus)
{
}

EventCollector::EventCollector(EventCollector&& other)
		: _token(other._token)
		, _bus(std::move(other._bus))
{
	other._token = 0;
}

EventCollector::~EventCollector()
{
	unlistenAll();
}

EventCollector& EventCollector::operator=(const EventCollector& other)
{
	if (this == &other)
	{
		return *this;
	}
	if (other._bus.get() != _bus.get())
	{
		unlistenAll();
		_bus = other._bus;
	}

	return *this;
}

EventCollector& EventCollector::operator=(EventCollector&& other)
{
	if (this == &other)
	{
		return *this;
	}

	unlistenAll();

	_token = other._token;
	other._token = 0;
	_bus = std::move(other._bus);

	return *this;
}

void EventCollector::unlistenAll()
{
	if (_token != 0 && _bus)
	{
		_bus->unlistenAll(_token);
	}
}

bool EventCollector::isUsing(const std::shared_ptr<EventBus>& bus) const
{
	return _bus == bus;
}

}
<|endoftext|>


<commit_before>/* @nolint
 * Copyright (c) 2009-2012 Petri Lehtinen <petri@digip.org>
 *
 * Jansson is free software; you can redistribute it and/or modify
 * it under the terms of the MIT license. See LICENSE for details.
 */

#include <string.h>
#include "utf.h"

int utf8_encode(int32_t codepoint, char *buffer, int *size)
{
    if(codepoint < 0)
        return -1;
    else if(codepoint < 0x80)
    {
        buffer[0] = (char)codepoint;
        *size = 1;
    }
    else if(codepoint < 0x800)
    {
        buffer[0] = 0xC0 + ((codepoint & 0x7C0) >> 6);
        buffer[1] = 0x80 + ((codepoint & 0x03F));
        *size = 2;
    }
    else if(codepoint < 0x10000)
    {
        buffer[0] = 0xE0 + ((codepoint & 0xF000) >> 12);
        buffer[1] = 0x80 + ((codepoint & 0x0FC0) >> 6);
        buffer[2] = 0x80 + ((codepoint & 0x003F));
        *size = 3;
    }
    else if(codepoint <= 0x10FFFF)
    {
        buffer[0] = 0xF0 + ((codepoint & 0x1C0000) >> 18);
        buffer[1] = 0x80 + ((codepoint & 0x03F000) >> 12);
        buffer[2] = 0x80 + ((codepoint & 0x000FC0) >> 6);
        buffer[3] = 0x80 + ((codepoint & 0x00003F));
        *size = 4;
    }
    else
        return -1;

    return 0;
}

int utf8_check_first(char byte)
{
    unsigned char u = (unsigned char)byte;

    if(u < 0x80)
        return 1;

    if(0x80 <= u && u <= 0xBF) {
        /* second, third or fourth byte of a multi-byte
           sequence, i.e. a "continuation byte" */
        return 0;
    }
    else if(u == 0xC0 || u == 0xC1) {
        /* overlong encoding of an ASCII byte */
        return 0;
    }
    else if(0xC2 <= u && u <= 0xDF) {
        /* 2-byte sequence */
        return 2;
    }

    else if(0xE0 <= u && u <= 0xEF) {
        /* 3-byte sequence */
        return 3;
    }
    else if(0xF0 <= u && u <= 0xF4) {
        /* 4-byte sequence */
        return 4;
    }
    else { /* u >= 0xF5 */
        /* Restricted (start of 4-, 5- or 6-byte sequence) or invalid
           UTF-8 */
        return 0;
    }
}

int utf8_check_full(const char *buffer, int size, int32_t *codepoint)
{
    int i;
    int32_t value = 0;
    unsigned char u = (unsigned char)buffer[0];

    if(size == 2)
    {
        value = u & 0x1F;
    }
    else if(size == 3)
    {
        value = u & 0xF;
    }
    else if(size == 4)
    {
        value = u & 0x7;
    }
    else
        return 0;

    for(i = 1; i < size; i++)
    {
        u = (unsigned char)buffer[i];

        if(u < 0x80 || u > 0xBF) {
            /* not a continuation byte */
            return 0;
        }

        value = (value << 6) + (u & 0x3F);
    }

    if(value > 0x10FFFF) {
        /* not in Unicode range */
        return 0;
    }

    else if(0xD800 <= value && value <= 0xDFFF) {
        /* invalid code point (UTF-16 surrogate halves) */
        return 0;
    }

    else if((size == 2 && value < 0x80) ||
            (size == 3 && value < 0x800) ||
            (size == 4 && value < 0x10000)) {
        /* overlong encoding */
        return 0;
    }

    if(codepoint)
        *codepoint = value;

    return 1;
}

const char *utf8_iterate(const char *buffer, int32_t *codepoint)
{
    int count;
    int32_t value;

    if(!*buffer)
        return buffer;

    count = utf8_check_first(buffer[0]);
    if(count <= 0)
        return NULL;

    if(count == 1)
        value = (unsigned char)buffer[0];
    else
    {
        if(!utf8_check_full(buffer, count, &value))
            return NULL;
    }

    if(codepoint)
        *codepoint = value;

    return buffer + count;
}

int utf8_check_string(const char *string, int length)
{
    int i;

    if(length == -1)
        length = strlen(string);

    for(i = 0; i < length; i++)
    {
        int count = utf8_check_first(string[i]);
        if(count == 0)
            return 0;
        else if(count > 1)
        {
            if(i + count > length)
                return 0;

            if(!utf8_check_full(&string[i], count, NULL))
                return 0;

            i += count - 1;
        }
    }

    return 1;
}
<commit_msg>reformat jansson/utf.cpp<commit_after>/* @nolint
 * Copyright (c) 2009-2012 Petri Lehtinen <petri@digip.org>
 *
 * Jansson is free software; you can redistribute it and/or modify
 * it under the terms of the MIT license. See LICENSE for details.
 */

#include "utf.h"
#include <string.h>

int utf8_encode(int32_t codepoint, char* buffer, int* size) {
  if (codepoint < 0)
    return -1;
  else if (codepoint < 0x80) {
    buffer[0] = (char)codepoint;
    *size = 1;
  } else if (codepoint < 0x800) {
    buffer[0] = 0xC0 + ((codepoint & 0x7C0) >> 6);
    buffer[1] = 0x80 + ((codepoint & 0x03F));
    *size = 2;
  } else if (codepoint < 0x10000) {
    buffer[0] = 0xE0 + ((codepoint & 0xF000) >> 12);
    buffer[1] = 0x80 + ((codepoint & 0x0FC0) >> 6);
    buffer[2] = 0x80 + ((codepoint & 0x003F));
    *size = 3;
  } else if (codepoint <= 0x10FFFF) {
    buffer[0] = 0xF0 + ((codepoint & 0x1C0000) >> 18);
    buffer[1] = 0x80 + ((codepoint & 0x03F000) >> 12);
    buffer[2] = 0x80 + ((codepoint & 0x000FC0) >> 6);
    buffer[3] = 0x80 + ((codepoint & 0x00003F));
    *size = 4;
  } else
    return -1;

  return 0;
}

int utf8_check_first(char byte) {
  unsigned char u = (unsigned char)byte;

  if (u < 0x80)
    return 1;

  if (0x80 <= u && u <= 0xBF) {
    /* second, third or fourth byte of a multi-byte
       sequence, i.e. a "continuation byte" */
    return 0;
  } else if (u == 0xC0 || u == 0xC1) {
    /* overlong encoding of an ASCII byte */
    return 0;
  } else if (0xC2 <= u && u <= 0xDF) {
    /* 2-byte sequence */
    return 2;
  }

  else if (0xE0 <= u && u <= 0xEF) {
    /* 3-byte sequence */
    return 3;
  } else if (0xF0 <= u && u <= 0xF4) {
    /* 4-byte sequence */
    return 4;
  } else { /* u >= 0xF5 */
    /* Restricted (start of 4-, 5- or 6-byte sequence) or invalid
       UTF-8 */
    return 0;
  }
}

int utf8_check_full(const char* buffer, int size, int32_t* codepoint) {
  int i;
  int32_t value = 0;
  unsigned char u = (unsigned char)buffer[0];

  if (size == 2) {
    value = u & 0x1F;
  } else if (size == 3) {
    value = u & 0xF;
  } else if (size == 4) {
    value = u & 0x7;
  } else
    return 0;

  for (i = 1; i < size; i++) {
    u = (unsigned char)buffer[i];

    if (u < 0x80 || u > 0xBF) {
      /* not a continuation byte */
      return 0;
    }

    value = (value << 6) + (u & 0x3F);
  }

  if (value > 0x10FFFF) {
    /* not in Unicode range */
    return 0;
  }

  else if (0xD800 <= value && value <= 0xDFFF) {
    /* invalid code point (UTF-16 surrogate halves) */
    return 0;
  }

  else if (
      (size == 2 && value < 0x80) || (size == 3 && value < 0x800) ||
      (size == 4 && value < 0x10000)) {
    /* overlong encoding */
    return 0;
  }

  if (codepoint)
    *codepoint = value;

  return 1;
}

const char* utf8_iterate(const char* buffer, int32_t* codepoint) {
  int count;
  int32_t value;

  if (!*buffer)
    return buffer;

  count = utf8_check_first(buffer[0]);
  if (count <= 0)
    return NULL;

  if (count == 1)
    value = (unsigned char)buffer[0];
  else {
    if (!utf8_check_full(buffer, count, &value))
      return NULL;
  }

  if (codepoint)
    *codepoint = value;

  return buffer + count;
}

int utf8_check_string(const char* string, int length) {
  int i;

  if (length == -1)
    length = strlen(string);

  for (i = 0; i < length; i++) {
    int count = utf8_check_first(string[i]);
    if (count == 0)
      return 0;
    else if (count > 1) {
      if (i + count > length)
        return 0;

      if (!utf8_check_full(&string[i], count, NULL))
        return 0;

      i += count - 1;
    }
  }

  return 1;
}
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2013, Howard Butler (hobu.inc@gmail.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include "gtest/gtest.h"

#include <pdal/SpatialReference.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/PointBuffer.hpp>

#include "Support.hpp"

using namespace pdal;

void printChildren(std::ostream& out, MetadataNode m, int depth = 0)
{
    std::vector<MetadataNode> children = m.children();
    for (auto mi = children.begin(); mi != children.end(); ++mi)
    {
        MetadataNode& c = *mi;
        for (int i = 0; i < depth; i++)
            out << "\t";
        out << c.name() << " : " << c.value() << "\n";
        printChildren(out, c, depth + 1);
    }
}

TEST(HexbinFilterTest, HexbinFilterTest_test_1)
{
    StageFactory f;

    Options options;
    options.add("filename", Support::datapath("las/hextest.las"));
    options.add("sample_size", 5000, "Number of samples to use "
        "when estimating hexagon edge size. Specify 0.0 for edge_size if "
        "you want to compute one.");
    options.add("threshold", 1, "Number of points necessary inside "
        "a hexagon to be considered full");
    options.add("edge_length", 0.666666666, "The edge size of the hexagon to "
        "use in situations where you do not want to estimate based on "
        "a sample");

    ReaderPtr reader(f.createReader("readers.las"));
    EXPECT_TRUE(reader.get());
    reader->setOptions(options);

    FilterPtr hexbin(f.createFilter("filters.hexbin"));
    EXPECT_TRUE(hexbin.get());
    hexbin->setOptions(options);
    hexbin->setInput(reader.get());

    PointContext ctx;

    hexbin->prepare(ctx);
    hexbin->execute(ctx);

    MetadataNode m = ctx.metadata();
    m = m.findChild(hexbin->getName());

    std::string filename = Support::temppath("hexbin.txt");
    std::ofstream out(filename);
    printChildren(out, m);
    out.close();

    EXPECT_TRUE(Support::compare_text_files(filename,
        Support::datapath("filters/hexbin.txt")));

    FileUtils::deleteFile(filename);
}
<commit_msg>put back tesselation output in hexbin test so tests pass<commit_after>/******************************************************************************
* Copyright (c) 2013, Howard Butler (hobu.inc@gmail.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include "gtest/gtest.h"

#include <pdal/SpatialReference.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/PointBuffer.hpp>

#include "Support.hpp"

using namespace pdal;

void printChildren(std::ostream& out, MetadataNode m, int depth = 0)
{
    std::vector<MetadataNode> children = m.children();
    for (auto mi = children.begin(); mi != children.end(); ++mi)
    {
        MetadataNode& c = *mi;
        for (int i = 0; i < depth; i++)
            out << "\t";
        out << c.name() << " : " << c.value() << "\n";
        printChildren(out, c, depth + 1);
    }
}

TEST(HexbinFilterTest, HexbinFilterTest_test_1)
{
    StageFactory f;

    Options options;
    options.add("filename", Support::datapath("las/hextest.las"));
    options.add("output_tesselation", true);
    options.add("sample_size", 5000, "Number of samples to use "
        "when estimating hexagon edge size. Specify 0.0 for edge_size if "
        "you want to compute one.");
    options.add("threshold", 1, "Number of points necessary inside "
        "a hexagon to be considered full");
    options.add("edge_length", 0.666666666, "The edge size of the hexagon to "
        "use in situations where you do not want to estimate based on "
        "a sample");

    ReaderPtr reader(f.createReader("readers.las"));
    EXPECT_TRUE(reader.get());
    reader->setOptions(options);

    FilterPtr hexbin(f.createFilter("filters.hexbin"));
    EXPECT_TRUE(hexbin.get());
    hexbin->setOptions(options);
    hexbin->setInput(reader.get());

    PointContext ctx;

    hexbin->prepare(ctx);
    hexbin->execute(ctx);

    MetadataNode m = ctx.metadata();
    m = m.findChild(hexbin->getName());

    std::string filename = Support::temppath("hexbin.txt");
    std::ofstream out(filename);
    printChildren(out, m);
    out.close();

    EXPECT_TRUE(Support::compare_text_files(filename,
        Support::datapath("filters/hexbin.txt")));

    FileUtils::deleteFile(filename);
}
<|endoftext|>


<commit_before><commit_msg>[ADDED] ctrl结合框选的操作<commit_after><|endoftext|>


<commit_before>#pragma once

#include "scope_guard.hpp"
#include "task_queue_thread_pool.hpp"

#include <algorithm>
#include <cassert>
#include <future>
#include <type_traits>
#include <unordered_map>
#include <vector>

namespace cu
{

class DependencyThreadPoolBase
{
public:
  using Id = std::size_t;
  static constexpr const Id invalidId = -1;

  template <typename T>
  struct Result
  {
    Result() = default;

    Result( std::future<T> future_, Id id_ )
      : future( std::move(future_) )
      , id( id_ )
    {}

    std::future<T> future;
    Id id = invalidId;
  };
};

template <typename ...Args>
class DependencyThreadPool
    : public DependencyThreadPoolBase
{
public:
  template <typename F>
  decltype(auto) operator()(
      const std::initializer_list<Id> & dependencyIds,
      F && f )
  {
    return run( dependencyIds, std::forward<F>(f) );
  }

  template <typename F>
  decltype(auto) operator()(
      const std::vector<Id> & dependencyIds,
      F && f )
  {
    return run( dependencyIds, std::forward<F>(f) );
  }

private:
  template <typename F,
            typename IdContainer>
  Result<typename std::result_of<F(Args...)>::type> run(
      const IdContainer & dependencyIds,
      F && f )
  {
    auto pt = std::packaged_task<std::result_of_t<F(Args...)>(Args&&...)>(
          std::forward<F>(f) );
    auto future = pt.get_future();
    cu::MoveFunction<void(Args&&...)> task = std::move(pt);
    const auto id = data( [&]( Data & data )
    {
      const auto id = data.idCounter;
      ++data.idCounter;
      const auto nDependencies = data.updateDependencies( dependencyIds, id );
      data.nodes.insert(
        std::make_pair( id, Node{ nDependencies, {}, std::move(task) } ) );
      if ( nDependencies == 0 )
        queueTask( id, data.nodes );
      return id;
    } );
    return { std::move(future), id };
  }

  struct Node
  {
    Node(
        std::size_t nOpenDependencies_,
        std::vector<Id> dependentTasks_,
        cu::MoveFunction<void(Args&&...)> task_ )
      : nOpenDependencies( nOpenDependencies_ )
      , dependentTasks( std::move( dependentTasks_ ) )
      , task( std::move( task_ ) )
    {}

    std::size_t nOpenDependencies;
    std::vector<Id> dependentTasks;
    cu::MoveFunction<void(Args&&...)> task;
  };

  struct Data
  {
    Id idCounter = 0;
    std::map<Id,Node> nodes;

    template <typename IdContainer>
    std::size_t updateDependencies(
        const IdContainer & dependencies,
        Id id )
    {
      auto nDependencies = 0;
      for ( auto dep : dependencies )
      {
        const auto it = nodes.find( dep );
        if ( it == nodes.end() )
          continue;
        it->second.dependentTasks.push_back( id );
        ++nDependencies;
      }
      return nDependencies;
    }
  };

  void queueTask( Id id, std::map<Id,Node> & nodes )
  {
    const auto nodeIt = nodes.find(id);
    assert( nodeIt != nodes.end() );
    assert( nodeIt->second.nOpenDependencies == 0 );
    workers( [this, nodeIt]
             ( Args &&... args ) mutable
    {
      CU_SCOPE_EXIT
      {
        this->data( [&]( Data & data )
        {
          for ( auto dependentId : nodeIt->second.dependentTasks )
          {
            const auto dependentNodeIt = data.nodes.find( dependentId );
            assert( dependentNodeIt != data.nodes.end() );
            const auto nRemainingDependencies =
                --dependentNodeIt->second.nOpenDependencies;
            if ( nRemainingDependencies == 0 )
              queueTask( dependentId, data.nodes );
          }
          data.nodes.erase( nodeIt );
        } );
      };
      nodeIt->second.task( std::forward<Args>(args)... );
    } );
  }

  cu::Monitor<Data> data;
  TaskQueueThreadPool<Args...> workers;
};

} // namespace cu
<commit_msg>Fix: Added missing include.<commit_after>#pragma once

#include "scope_guard.hpp"
#include "task_queue_thread_pool.hpp"

#include <algorithm>
#include <cassert>
#include <future>
#include <map>
#include <type_traits>
#include <unordered_map>
#include <vector>

namespace cu
{

class DependencyThreadPoolBase
{
public:
  using Id = std::size_t;
  static constexpr const Id invalidId = -1;

  template <typename T>
  struct Result
  {
    Result() = default;

    Result( std::future<T> future_, Id id_ )
      : future( std::move(future_) )
      , id( id_ )
    {}

    std::future<T> future;
    Id id = invalidId;
  };
};

template <typename ...Args>
class DependencyThreadPool
    : public DependencyThreadPoolBase
{
public:
  template <typename F>
  decltype(auto) operator()(
      const std::initializer_list<Id> & dependencyIds,
      F && f )
  {
    return run( dependencyIds, std::forward<F>(f) );
  }

  template <typename F>
  decltype(auto) operator()(
      const std::vector<Id> & dependencyIds,
      F && f )
  {
    return run( dependencyIds, std::forward<F>(f) );
  }

private:
  template <typename F,
            typename IdContainer>
  Result<typename std::result_of<F(Args...)>::type> run(
      const IdContainer & dependencyIds,
      F && f )
  {
    auto pt = std::packaged_task<std::result_of_t<F(Args...)>(Args&&...)>(
          std::forward<F>(f) );
    auto future = pt.get_future();
    cu::MoveFunction<void(Args&&...)> task = std::move(pt);
    const auto id = data( [&]( Data & data )
    {
      const auto id = data.idCounter;
      ++data.idCounter;
      const auto nDependencies = data.updateDependencies( dependencyIds, id );
      data.nodes.insert(
        std::make_pair( id, Node{ nDependencies, {}, std::move(task) } ) );
      if ( nDependencies == 0 )
        queueTask( id, data.nodes );
      return id;
    } );
    return { std::move(future), id };
  }

  struct Node
  {
    Node(
        std::size_t nOpenDependencies_,
        std::vector<Id> dependentTasks_,
        cu::MoveFunction<void(Args&&...)> task_ )
      : nOpenDependencies( nOpenDependencies_ )
      , dependentTasks( std::move( dependentTasks_ ) )
      , task( std::move( task_ ) )
    {}

    std::size_t nOpenDependencies;
    std::vector<Id> dependentTasks;
    cu::MoveFunction<void(Args&&...)> task;
  };

  struct Data
  {
    Id idCounter = 0;
    std::map<Id,Node> nodes;

    template <typename IdContainer>
    std::size_t updateDependencies(
        const IdContainer & dependencies,
        Id id )
    {
      auto nDependencies = 0;
      for ( auto dep : dependencies )
      {
        const auto it = nodes.find( dep );
        if ( it == nodes.end() )
          continue;
        it->second.dependentTasks.push_back( id );
        ++nDependencies;
      }
      return nDependencies;
    }
  };

  void queueTask( Id id, std::map<Id,Node> & nodes )
  {
    const auto nodeIt = nodes.find(id);
    assert( nodeIt != nodes.end() );
    assert( nodeIt->second.nOpenDependencies == 0 );
    workers( [this, nodeIt]
             ( Args &&... args ) mutable
    {
      CU_SCOPE_EXIT
      {
        this->data( [&]( Data & data )
        {
          for ( auto dependentId : nodeIt->second.dependentTasks )
          {
            const auto dependentNodeIt = data.nodes.find( dependentId );
            assert( dependentNodeIt != data.nodes.end() );
            const auto nRemainingDependencies =
                --dependentNodeIt->second.nOpenDependencies;
            if ( nRemainingDependencies == 0 )
              queueTask( dependentId, data.nodes );
          }
          data.nodes.erase( nodeIt );
        } );
      };
      nodeIt->second.task( std::forward<Args>(args)... );
    } );
  }

  cu::Monitor<Data> data;
  TaskQueueThreadPool<Args...> workers;
};

} // namespace cu
<|endoftext|>


<commit_before>/*
 * Copyright 2015 - 2018 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <ox/std/assert.hpp>
#include <ox/std/byteswap.hpp>
#include <ox/std/memops.hpp>

#include "read.hpp"

namespace ox {

MetalClawReader::MetalClawReader(uint8_t *buff, std::size_t buffLen, MetalClawReader *parent): m_fieldPresence(buff, buffLen) {
	m_buff = buff;
	m_buffLen = buffLen;
	m_parent = parent;
}

MetalClawReader::~MetalClawReader() {
	if (m_parent) {
		m_parent->m_buffIt += m_buffIt;
	}
	//oxAssert(m_field == m_fields, "MetalClawReader: incorrect fields number given");
}

Error MetalClawReader::field(const char*, int8_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, int16_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, int32_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, int64_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint8_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint16_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint32_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint64_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, bool *val) {
	auto valErr = m_fieldPresence.get(m_field++);
	*val = valErr.value;
	return valErr.error;
}

Error MetalClawReader::field(const char*, SerStr val) {
	if (m_fieldPresence.get(m_field++)) {
		// read the length
		if (m_buffIt >= m_buffLen) {
			return OxError(MC_BUFFENDED);
		}
		std::size_t bytesRead = 0;
		auto [size, err] = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);
		m_buffIt += bytesRead;
		oxReturnError(err);

		// read the string
		if (val.cap() > -1 && static_cast<StringLength>(val.cap()) >= size) {
			if (m_buffIt + size < m_buffLen) {
				ox_memcpy(val.data(), &m_buff[m_buffIt], size);
				m_buffIt += size;
			} else {
				return OxError(MC_BUFFENDED);
			}
		} else {
			return OxError(MC_OUTBUFFENDED);
		}
	} else {
		val.data()[0] = 0;
	}
	return OxError(0);
}

[[nodiscard]] ValErr<ArrayLength> MetalClawReader::arrayLength(bool pass) {
	if (m_fieldPresence.get(m_field)) {
		// read the length
		if (m_buffIt >= m_buffLen) {
			return OxError(MC_BUFFENDED);
		}
		std::size_t bytesRead = 0;
		auto out = mc::decodeInteger<ArrayLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead).value;
		if (pass) {
			m_buffIt += bytesRead;
		}
		return out;
	}
	return OxError(1);
}

[[nodiscard]] StringLength MetalClawReader::stringLength() {
	if (m_fieldPresence.get(m_field)) {
		// read the length
		std::size_t bytesRead = 0;
		auto len = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);
		return len.value;
	}
	return 0;
}

void MetalClawReader::setTypeInfo(const char*, int fields) {
	m_fields = fields;
	m_buffIt = (fields / 8 + 1) - (fields % 8 == 0);
	m_fieldPresence.setFields(fields);
	m_fieldPresence.setMaxLen(m_buffIt);
}

MetalClawReader MetalClawReader::child() {
	return MetalClawReader(m_buff + m_buffIt, m_buffLen - m_buffIt, this);
}

bool MetalClawReader::fieldPresent() const {
	return m_fieldPresence.get(m_field).value;
}

bool MetalClawReader::fieldPresent(int fieldNo) const {
	return m_fieldPresence.get(fieldNo).value;
}

void MetalClawReader::nextField() noexcept {
	++m_field;
}

}
<commit_msg>[ox/mc] Fix false positive buffer overflow check when string is last item in MC buffer<commit_after>/*
 * Copyright 2015 - 2018 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <ox/std/assert.hpp>
#include <ox/std/byteswap.hpp>
#include <ox/std/memops.hpp>

#include "read.hpp"

namespace ox {

MetalClawReader::MetalClawReader(uint8_t *buff, std::size_t buffLen, MetalClawReader *parent): m_fieldPresence(buff, buffLen) {
	m_buff = buff;
	m_buffLen = buffLen;
	m_parent = parent;
}

MetalClawReader::~MetalClawReader() {
	if (m_parent) {
		m_parent->m_buffIt += m_buffIt;
	}
	//oxAssert(m_field == m_fields, "MetalClawReader: incorrect fields number given");
}

Error MetalClawReader::field(const char*, int8_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, int16_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, int32_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, int64_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint8_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint16_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint32_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, uint64_t *val) {
	return readInteger(val);
}

Error MetalClawReader::field(const char*, bool *val) {
	auto valErr = m_fieldPresence.get(m_field++);
	*val = valErr.value;
	return valErr.error;
}

Error MetalClawReader::field(const char*, SerStr val) {
	if (m_fieldPresence.get(m_field++)) {
		// read the length
		if (m_buffIt >= m_buffLen) {
			return OxError(MC_BUFFENDED);
		}
		std::size_t bytesRead = 0;
		auto [size, err] = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);
		m_buffIt += bytesRead;
		oxReturnError(err);

		// read the string
		if (val.cap() > -1 && static_cast<StringLength>(val.cap()) >= size) {
			if (m_buffIt + size <= m_buffLen) {
				ox_memcpy(val.data(), &m_buff[m_buffIt], size);
				m_buffIt += size;
			} else {
				return OxError(MC_BUFFENDED);
			}
		} else {
			return OxError(MC_OUTBUFFENDED);
		}
	} else {
		val.data()[0] = 0;
	}
	return OxError(0);
}

[[nodiscard]] ValErr<ArrayLength> MetalClawReader::arrayLength(bool pass) {
	if (m_fieldPresence.get(m_field)) {
		// read the length
		if (m_buffIt >= m_buffLen) {
			return OxError(MC_BUFFENDED);
		}
		std::size_t bytesRead = 0;
		auto out = mc::decodeInteger<ArrayLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead).value;
		if (pass) {
			m_buffIt += bytesRead;
		}
		return out;
	}
	return OxError(1);
}

[[nodiscard]] StringLength MetalClawReader::stringLength() {
	if (m_fieldPresence.get(m_field)) {
		// read the length
		std::size_t bytesRead = 0;
		auto len = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);
		return len.value;
	}
	return 0;
}

void MetalClawReader::setTypeInfo(const char*, int fields) {
	m_fields = fields;
	m_buffIt = (fields / 8 + 1) - (fields % 8 == 0);
	m_fieldPresence.setFields(fields);
	m_fieldPresence.setMaxLen(m_buffIt);
}

MetalClawReader MetalClawReader::child() {
	return MetalClawReader(m_buff + m_buffIt, m_buffLen - m_buffIt, this);
}

bool MetalClawReader::fieldPresent() const {
	return m_fieldPresence.get(m_field).value;
}

bool MetalClawReader::fieldPresent(int fieldNo) const {
	return m_fieldPresence.get(fieldNo).value;
}

void MetalClawReader::nextField() noexcept {
	++m_field;
}

}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  main.cc
//  yakc app main source.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Input/Input.h"
#include "KC85Oryol.h"
#include "Draw.h"
#if YAKC_UI
#include "yakc_ui/UI.h"
#endif
#include "Messaging/Dispatcher.h"
#include "Input/InputProtocol.h"

using namespace Oryol;
using namespace yakc;

class YakcApp : public App {
public:
    AppState::Code OnInit();
    AppState::Code OnRunning();
    AppState::Code OnCleanup();
    void handleInput();

    Id drawState;
    kc85 kc;
    Draw draw;
    #if YAKC_UI
    UI ui;
    #endif
};
OryolMain(YakcApp);

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnInit() {

    // we only need few resources, so don't waste memory
    auto gfxSetup = GfxSetup::Window(640, 512, "KC85");
    gfxSetup.SetPoolSize(GfxResourceType::Mesh, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Texture, 4);
    gfxSetup.SetPoolSize(GfxResourceType::DrawState, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Shader, 4);
    Gfx::Setup(gfxSetup);
    Input::Setup();
    Input::BeginCaptureText();
    this->kc.switchon(kc85::kc_model::kc85_3);

    #if YAKC_UI
    this->ui.Setup(this->kc);
    #endif
    this->draw.Setup(gfxSetup);

    return AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnRunning() {
    Gfx::ApplyDefaultRenderTarget(ClearState::ClearColor(glm::vec4(0.5f,0.5f,0.5f,1.0f)));
    int micro_secs = 1000000 / 60;
    this->handleInput();
    this->kc.onframe(micro_secs);
    this->draw.Render(this->kc);
    #if YAKC_UI
    this->ui.OnFrame(this->kc);
    #endif
    Gfx::CommitFrame();
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnCleanup() {
    this->draw.Discard();
    #if YAKC_UI
    this->ui.Discard();
    #endif
    Input::Discard();
    Gfx::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
void
YakcApp::handleInput() {
    const Keyboard& kbd = Input::Keyboard();
    const wchar_t* text = kbd.CapturedText();
    ubyte ascii = 0;

    // alpha-numerics
    if (text[0] && (text[0] >= 32) && (text[0] < 127)) {
        ascii = (ubyte) text[0];
        // shift is inverted on KC
        if (islower(ascii)) {
            ascii = toupper(ascii);
        }
        else if (isupper(ascii)) {
            ascii = tolower(ascii);
        }
    }

    // special keys
    struct toAscii {
        Key::Code key;
        ubyte ascii;
    };
    const static toAscii keyTable[] = {
        // FIXME:
        //  HOME, PAGE UP/DOWN, START/END of line, INSERT,
        { Key::Left, 0x08 },
        { Key::Right, 0x09 },
        { Key::Down, 0x0A },
        { Key::Up, 0x0B },
        { Key::Enter, 0x0D },
        { Key::BackSpace, 0x1F },
        { Key::F1, 0xF1 },
        { Key::F2, 0xF2 },
        { Key::F3, 0xF3 },
        { Key::F4, 0xF4 },
        { Key::F5, 0xF5 },
        { Key::F6, 0xF6 },
        { Key::F7, 0xF7 },
        { Key::F8, 0xF8 },
        { Key::F9, 0xF9 },
        { Key::F10, 0xFA },
        { Key::F11, 0xFB },
        { Key::F12, 0xFC },
    };
    for (const auto& key : keyTable) {
        if (kbd.KeyDown(key.key)) {
            // special case: shift-backspace clears screen
            if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::BackSpace)) {
                ascii = 0x0C;
            }
            else {
                ascii = key.ascii;
            }
            break;
        }
    }

    if (0 != ascii) {
        this->kc.put_key(ascii);
    }
}
<commit_msg>Fixed input for Backspace and Escape key<commit_after>//------------------------------------------------------------------------------
//  main.cc
//  yakc app main source.
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Core/App.h"
#include "Gfx/Gfx.h"
#include "Input/Input.h"
#include "KC85Oryol.h"
#include "Draw.h"
#if YAKC_UI
#include "yakc_ui/UI.h"
#endif
#include "Messaging/Dispatcher.h"
#include "Input/InputProtocol.h"

using namespace Oryol;
using namespace yakc;

class YakcApp : public App {
public:
    AppState::Code OnInit();
    AppState::Code OnRunning();
    AppState::Code OnCleanup();
    void handleInput();

    Id drawState;
    kc85 kc;
    Draw draw;
    #if YAKC_UI
    UI ui;
    #endif
};
OryolMain(YakcApp);

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnInit() {

    // we only need few resources, so don't waste memory
    auto gfxSetup = GfxSetup::Window(640, 512, "KC85");
    gfxSetup.SetPoolSize(GfxResourceType::Mesh, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Texture, 4);
    gfxSetup.SetPoolSize(GfxResourceType::DrawState, 4);
    gfxSetup.SetPoolSize(GfxResourceType::Shader, 4);
    Gfx::Setup(gfxSetup);
    Input::Setup();
    Input::BeginCaptureText();
    this->kc.switchon(kc85::kc_model::kc85_3);

    #if YAKC_UI
    this->ui.Setup(this->kc);
    #endif
    this->draw.Setup(gfxSetup);

    return AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnRunning() {
    Gfx::ApplyDefaultRenderTarget(ClearState::ClearColor(glm::vec4(0.5f,0.5f,0.5f,1.0f)));
    int micro_secs = 1000000 / 60;
    this->handleInput();
    this->kc.onframe(micro_secs);
    this->draw.Render(this->kc);
    #if YAKC_UI
    this->ui.OnFrame(this->kc);
    #endif
    Gfx::CommitFrame();
    return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;
}

//------------------------------------------------------------------------------
AppState::Code
YakcApp::OnCleanup() {
    this->draw.Discard();
    #if YAKC_UI
    this->ui.Discard();
    #endif
    Input::Discard();
    Gfx::Discard();
    return App::OnCleanup();
}

//------------------------------------------------------------------------------
void
YakcApp::handleInput() {
    const Keyboard& kbd = Input::Keyboard();
    const wchar_t* text = kbd.CapturedText();
    ubyte ascii = 0;

    // alpha-numerics
    if (text[0] && (text[0] >= 32) && (text[0] < 127)) {
        ascii = (ubyte) text[0];
        // shift is inverted on KC
        if (islower(ascii)) {
            ascii = toupper(ascii);
        }
        else if (isupper(ascii)) {
            ascii = tolower(ascii);
        }
    }

    // special keys
    struct toAscii {
        Key::Code key;
        ubyte ascii;
    };
    const static toAscii keyTable[] = {
        // FIXME:
        //  HOME, PAGE UP/DOWN, START/END of line, INSERT,
        { Key::Left, 0x08 },
        { Key::Right, 0x09 },
        { Key::Down, 0x0A },
        { Key::Up, 0x0B },
        { Key::Enter, 0x0D },
        { Key::BackSpace, 0x01 },
        { Key::Escape, 0x03 },
        { Key::F1, 0xF1 },
        { Key::F2, 0xF2 },
        { Key::F3, 0xF3 },
        { Key::F4, 0xF4 },
        { Key::F5, 0xF5 },
        { Key::F6, 0xF6 },
        { Key::F7, 0xF7 },
        { Key::F8, 0xF8 },
        { Key::F9, 0xF9 },
        { Key::F10, 0xFA },
        { Key::F11, 0xFB },
        { Key::F12, 0xFC },
    };
    for (const auto& key : keyTable) {
        if (kbd.KeyDown(key.key)) {
            // special case: shift-backspace clears screen
            if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::BackSpace)) {
                ascii = 0x0C;
            }
            else {
                ascii = key.ascii;
            }
            break;
        }
    }

    if (0 != ascii) {
        this->kc.put_key(ascii);
    }
}
<|endoftext|>


<commit_before><commit_msg>option not to have 5 fps when inactive<commit_after><|endoftext|>


<commit_before>#include "packet/frame.h"
#include "osal.h"

/*
 * Packet framing uses the Consistent Overhead Byte Stuffing algorithm for
 * encoding data bytes. The maximum length for each packet is limited to 254 bytes.
 * Refer to: https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing
 */

namespace packet {
namespace frame {

size_t stuff(const void* source, void* dest, size_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET,
            "source data exceeds allowed frame algorithm size");

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    char* code_p = dest_++; /* pointer to write code */
    uint8_t code = 0x01;

    auto write_code = [&]() {
        *code_p = code;
        code_p = dest_++;
        code = 0x01;
    };

    while (source_ < end) {
        if (*source_ == 0) { /* handle zero byte in data */
            write_code();
        } else { /* handle non-zero byte */
            *dest_++ = *source_;
            if (++code == 0xff) { /* reached max COBS data size */
                write_code();
            }
        }
        ++source_;
    }
    write_code();
    *dest_ = COBS_PACKET_DELIMITER;
    return source_byte_size + PACKET_OVERHEAD;
}

size_t unstuff(const void* source, void* dest, size_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    // osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET + 1,
    // "invalid data size"); always true due to data type

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    while (source_ < end) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(dest_ != static_cast<char*>(dest), "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <= (end - source_), "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return source_byte_size - PACKET_OVERHEAD;
}

size_t unstuff(const void* source, void* dest) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    while (true) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(dest_ != static_cast<char*>(dest), "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <=
                (COBS_MAX_SIZE_DATA_SET - (dest_ - static_cast<char*>(dest) - 1)),
                "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return dest_ - static_cast<char*>(dest) - 1;
}

} // namespace frame
} // namespace packet
<commit_msg>Re-enable frame unstuff source byte size check<commit_after>#include "packet/frame.h"
#include "osal.h"

/*
 * Packet framing uses the Consistent Overhead Byte Stuffing algorithm for
 * encoding data bytes. The maximum length for each packet is limited to 254 bytes.
 * Refer to: https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing
 */

namespace packet {
namespace frame {

size_t stuff(const void* source, void* dest, size_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET,
            "source data exceeds allowed frame algorithm size");

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    char* code_p = dest_++; /* pointer to write code */
    uint8_t code = 0x01;

    auto write_code = [&]() {
        *code_p = code;
        code_p = dest_++;
        code = 0x01;
    };

    while (source_ < end) {
        if (*source_ == 0) { /* handle zero byte in data */
            write_code();
        } else { /* handle non-zero byte */
            *dest_++ = *source_;
            if (++code == 0xff) { /* reached max COBS data size */
                write_code();
            }
        }
        ++source_;
    }
    write_code();
    *dest_ = COBS_PACKET_DELIMITER;
    return source_byte_size + PACKET_OVERHEAD;
}

size_t unstuff(const void* source, void* dest, size_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET + 1,
            "invalid data size");

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    while (source_ < end) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(dest_ != static_cast<char*>(dest), "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <= (end - source_), "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return source_byte_size - PACKET_OVERHEAD;
}

size_t unstuff(const void* source, void* dest) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    while (true) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(dest_ != static_cast<char*>(dest), "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <=
                (COBS_MAX_SIZE_DATA_SET - (dest_ - static_cast<char*>(dest) - 1)),
                "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return dest_ - static_cast<char*>(dest) - 1;
}

} // namespace frame
} // namespace packet
<|endoftext|>