<commit_before>/*
Copyright (c) 2015-2019, Robert J. Hansen <rjh@sixdemonbag.org>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

#include <algorithm>
#include <boost/tokenizer.hpp>
#include <exception>
#include <iostream>
#include <sstream>
#include <vector>
#include "main.h"

using boost::char_separator;
using boost::tokenizer;
using boost::asio::ip::tcp;
using std::back_inserter;
using std::binary_search;
using std::exception;
using std::getline;
using std::pair;
using std::string;
using std::stringstream;
using std::to_string;
using std::transform;
using std::vector;

// defined in main.cc
extern const vector<pair64>& hashes;

namespace {
enum class Command {
  Version = 0,
  Bye = 1,
  Status = 2,
  Query = 3,
  Upshift = 4,
  Downshift = 5,
  Unknown = 6
};

auto tokenize(const string& line) {
  vector<string> rv;
  char_separator<char> sep(" ");
  tokenizer<char_separator<char>> tokens(line, sep);
  for (const auto& t : tokens) {
    rv.emplace_back(t);
  }
  return rv;
}

bool is_present_in_hashes(const string& hash) {
  return binary_search(hashes.cbegin(), hashes.cend(), to_pair64(hash));
}

auto getCommand(const string& cmdstring) {
  string localcmd = "";
  transform(cmdstring.cbegin(), cmdstring.cend(), back_inserter(localcmd),
            ::toupper);

  auto cmd = Command::Unknown;

  if (localcmd == "VERSION:")
    cmd = Command::Version;
  else if (localcmd == "BYE")
    cmd = Command::Bye;
  else if (localcmd == "STATUS")
    cmd = Command::Status;
  else if (localcmd == "QUERY")
    cmd = Command::Query;
  else if (localcmd == "UPSHIFT")
    cmd = Command::Upshift;
  else if (localcmd == "DOWNSHIFT")
    cmd = Command::Downshift;

  return cmd;
}
}  // namespace

void handle_client(tcp::iostream& stream) {
  const string ipaddr = stream.socket().remote_endpoint().address().to_string();
  unsigned long long queries = 0;
  try {
    while (stream) {
      string line;
      getline(stream, line);
      if (line.size() == 0) return;

      // trim leading/following whitespace
      auto end_ws = line.find_last_not_of("\t\n\v\f\r ");
      if (end_ws != string::npos) {
        line.erase(end_ws + 1);
      }
      auto front_ws = line.find_first_not_of("\t\n\v\f\r ");
      if (front_ws > 0) {
        line.erase(0, front_ws);
      }

      auto commands = tokenize(line);
      switch (getCommand(commands.at(0))) {
        case Command::Version:
          stream << "OK\r\n";
          break;

        case Command::Bye:
          return;

        case Command::Status:
          stream << "NOT SUPPORTED\r\n";
          break;

        case Command::Query: {
          stringstream rv;
          rv << "OK ";
          for (size_t idx = 1; idx < commands.size(); ++idx)
            rv << (is_present_in_hashes(commands.at(idx)) ? "1" : "0");
          rv << "\r\n";
          queries += (commands.size() - 1);
          stream << rv.str();
          break;
        }

        case Command::Upshift:
          stream << "NOT OK\r\n";
          break;

        case Command::Downshift:
          stream << "NOT OK\r\n";
          break;

        case Command::Unknown:
          stream << "NOT OK\r\n";
          return;
      }
    }
  } catch (std::exception& e) {
    log(LogLevel::ALERT, string("Error: ") + e.what());
    // swallow the exception: we'll close the connection
    // automagically on exit
    //
    // fall-through here to function returb
  }

  stringstream status_msg;
  status_msg << ipaddr << " closed session after " << queries << " queries";
  log(LogLevel::ALERT, status_msg.str());
}
<commit_msg>Typo fix<commit_after>/*
Copyright (c) 2015-2019, Robert J. Hansen <rjh@sixdemonbag.org>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

#include <algorithm>
#include <boost/tokenizer.hpp>
#include <exception>
#include <iostream>
#include <sstream>
#include <vector>
#include "main.h"

using boost::char_separator;
using boost::tokenizer;
using boost::asio::ip::tcp;
using std::back_inserter;
using std::binary_search;
using std::exception;
using std::getline;
using std::pair;
using std::string;
using std::stringstream;
using std::to_string;
using std::transform;
using std::vector;

// defined in main.cc
extern const vector<pair64>& hashes;

namespace {
enum class Command {
  Version = 0,
  Bye = 1,
  Status = 2,
  Query = 3,
  Upshift = 4,
  Downshift = 5,
  Unknown = 6
};

auto tokenize(const string& line) {
  vector<string> rv;
  char_separator<char> sep(" ");
  tokenizer<char_separator<char>> tokens(line, sep);
  for (const auto& t : tokens) {
    rv.emplace_back(t);
  }
  return rv;
}

bool is_present_in_hashes(const string& hash) {
  return binary_search(hashes.cbegin(), hashes.cend(), to_pair64(hash));
}

auto getCommand(const string& cmdstring) {
  string localcmd = "";
  transform(cmdstring.cbegin(), cmdstring.cend(), back_inserter(localcmd),
            ::toupper);

  auto cmd = Command::Unknown;

  if (localcmd == "VERSION:")
    cmd = Command::Version;
  else if (localcmd == "BYE")
    cmd = Command::Bye;
  else if (localcmd == "STATUS")
    cmd = Command::Status;
  else if (localcmd == "QUERY")
    cmd = Command::Query;
  else if (localcmd == "UPSHIFT")
    cmd = Command::Upshift;
  else if (localcmd == "DOWNSHIFT")
    cmd = Command::Downshift;

  return cmd;
}
}  // namespace

void handle_client(tcp::iostream& stream) {
  const string ipaddr = stream.socket().remote_endpoint().address().to_string();
  unsigned long long queries = 0;
  try {
    while (stream) {
      string line;
      getline(stream, line);
      if (line.size() == 0) return;

      // trim leading/following whitespace
      auto end_ws = line.find_last_not_of("\t\n\v\f\r ");
      if (end_ws != string::npos) {
        line.erase(end_ws + 1);
      }
      auto front_ws = line.find_first_not_of("\t\n\v\f\r ");
      if (front_ws > 0) {
        line.erase(0, front_ws);
      }

      auto commands = tokenize(line);
      switch (getCommand(commands.at(0))) {
        case Command::Version:
          stream << "OK\r\n";
          break;

        case Command::Bye:
          return;

        case Command::Status:
          stream << "NOT SUPPORTED\r\n";
          break;

        case Command::Query: {
          stringstream rv;
          rv << "OK ";
          for (size_t idx = 1; idx < commands.size(); ++idx)
            rv << (is_present_in_hashes(commands.at(idx)) ? "1" : "0");
          rv << "\r\n";
          queries += (commands.size() - 1);
          stream << rv.str();
          break;
        }

        case Command::Upshift:
          stream << "NOT OK\r\n";
          break;

        case Command::Downshift:
          stream << "NOT OK\r\n";
          break;

        case Command::Unknown:
          stream << "NOT OK\r\n";
          return;
      }
    }
  } catch (std::exception& e) {
    log(LogLevel::ALERT, string("Error: ") + e.what());
    // swallow the exception: we'll close the connection
    // automagically on exit
    //
    // fall-through here to function return
  }

  stringstream status_msg;
  status_msg << ipaddr << " closed session after " << queries << " queries";
  log(LogLevel::ALERT, status_msg.str());
}
<|endoftext|>


<commit_before>// Copyright 2018 Google Inc.
//
// 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.
//
//  header and chunks writing
//
// Author: Skal (pascal.massimino@gmail.com)

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include "sjpegi.h"

using namespace sjpeg;

namespace sjpeg {

////////////////////////////////////////////////////////////////////////////////
// Headers
//
// NOTE(skal): all chunks start with a startcode '0xff??' (0xffd8 e.g),
// followed by the size of the payload *not counting the startcode*!
// That's why you often find these 'Reserve(data_size + 2)' below, the '+2'
// accounting for the 0xff?? startcode size.

void Encoder::WriteAPP0() {  // SOI + APP0
  const uint8_t kHeader0[] = {
    0xff, 0xd8,                     // SOI
    0xff, 0xe0, 0x00, 0x10,         // APP0
    0x4a, 0x46, 0x49, 0x46, 0x00,   // 'JFIF'
    0x01, 0x01,                     // v1.01
    0x00, 0x00, 0x01, 0x00, 0x01,   // aspect ratio = 1:1
    0x00, 0x00                      // thumbnail width/height
  };
  bw_.Reserve(sizeof(kHeader0));
  bw_.PutBytes(kHeader0, sizeof(kHeader0));
}

bool Encoder::WriteAPPMarkers(const std::string& data) {
  if (data.size() == 0) return true;
  const size_t data_size = data.size();
  bw_.Reserve(data_size);
  bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  return true;
}

bool Encoder::WriteEXIF(const std::string& data) {
  if (data.size() == 0) return true;
  const uint8_t kEXIF[] = "Exif\0";
  const size_t kEXIF_len = 6;  // includes the \0's
  const size_t data_size = data.size() + kEXIF_len + 2;
  if (data_size > 0xffff) return false;
  bw_.Reserve(data_size);
  bw_.PutByte(0xff);
  bw_.PutByte(0xe1);
  bw_.PutByte((data_size >> 8) & 0xff);
  bw_.PutByte((data_size >> 0) & 0xff);
  bw_.PutBytes(kEXIF, kEXIF_len);
  bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  return true;
}

bool Encoder::WriteICCP(const std::string& data) {
  if (data.size() == 0) return true;
  size_t data_size = data.size();
  const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data.data());
  const uint8_t kICCP[] = "ICC_PROFILE";
  const size_t kICCP_len = 12;  // includes the \0
  const size_t chunk_size_max = 0xffff - kICCP_len - 4;
  size_t max_chunk = (data_size + chunk_size_max - 1) / chunk_size_max;
  if (max_chunk >= 256) return false;
  size_t seq = 1;
  while (data_size > 0) {
    size_t size = data_size;
    if (size > chunk_size_max) size = chunk_size_max;
    bw_.Reserve(size + kICCP_len + 4 + 2);
    bw_.PutByte(0xff);
    bw_.PutByte(0xe2);
    bw_.PutByte(((size + kICCP_len + 4) >> 8) & 0xff);
    bw_.PutByte(((size + kICCP_len + 4) >> 0) & 0xff);
    bw_.PutBytes(kICCP, kICCP_len);
    bw_.PutByte(seq & 0xff);
    bw_.PutByte(max_chunk & 0xff);
    bw_.PutBytes(ptr, size);
    ptr += size;
    data_size -= size;
    seq += 1;
  }
  return true;
}

bool Encoder::WriteXMP(const std::string& data) {
  if (data.size() == 0) return true;
  const uint8_t kXMP[] = "http://ns.adobe.com/xap/1.0/";
  const size_t kXMP_size = 29;
  const size_t data_size = 2 + data.size() + kXMP_size;
  if (data_size > 0xffff) return false;  // error
  bw_.Reserve(data_size + 2);
  bw_.PutByte(0xff);
  bw_.PutByte(0xe1);
  bw_.PutByte((data_size >> 8) & 0xff);
  bw_.PutByte((data_size >> 0) & 0xff);
  bw_.PutBytes(kXMP, kXMP_size);
  bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  return true;
}

void Encoder::WriteDQT() {
  const int data_size = 2 * 65 + 2;
  const uint8_t kDQTHeader[] = { 0xff, 0xdb, 0x00, (uint8_t)data_size };
  bw_.Reserve(data_size + 2);
  bw_.PutBytes(kDQTHeader, sizeof(kDQTHeader));
  for (int n = 0; n <= 1; ++n) {
    bw_.PutByte(n);
    const uint8_t* quant = quants_[n].quant_;
    for (int i = 0; i < 64; ++i) {
      bw_.PutByte(quant[kZigzag[i]]);
    }
  }
}

////////////////////////////////////////////////////////////////////////////////

#define DATA_16b(X) ((uint8_t)((X) >> 8)), ((uint8_t)((X) & 0xff))

void Encoder::WriteSOF() {   // SOF
  const int data_size = 8 + 3 * nb_comps_;
  assert(data_size <= 255);
  const uint8_t kHeader[] = {
    0xff, 0xc0, DATA_16b(data_size),         // SOF0 marker, size
    0x08,                                    // 8bits/components
    DATA_16b(H_), DATA_16b(W_),              // height, width
    (uint8_t)nb_comps_                       // number of components
  };
  bw_.Reserve(data_size + 2);
  bw_.PutBytes(kHeader, sizeof(kHeader));
  for (int c = 0; c < nb_comps_; ++c) {
    bw_.PutByte(c + 1);
    bw_.PutByte(block_dims_[c]);
    bw_.PutByte(quant_idx_[c]);
  }
}

void Encoder::WriteDHT() {
  InitCodes(false);
  const int nb_tables = (nb_comps_ == 1 ? 1 : 2);
  for (int c = 0; c < nb_tables; ++c) {   // luma, chroma
    for (int type = 0; type <= 1; ++type) {               // dc, ac
      const HuffmanTable* const h = Huffman_tables_[type * 2 + c];
      const int data_size = 3 + 16 + h->nb_syms_;
      assert(data_size <= 255);
      bw_.Reserve(data_size + 2);
      bw_.PutByte(0xff);
      bw_.PutByte(0xc4);
      bw_.PutByte(0x00 /*data_size >> 8*/);
      bw_.PutByte(data_size);
      bw_.PutByte((type << 4) | c);
      bw_.PutBytes(h->bits_, 16);
      bw_.PutBytes(h->syms_, h->nb_syms_);
    }
  }
}

////////////////////////////////////////////////////////////////////////////////

void Encoder::WriteSOS() {   // SOS
  const int data_size = 6 + nb_comps_ * 2;
  assert(data_size <= 255);
  const uint8_t kHeader[] = {
      0xff, 0xda, DATA_16b(data_size), (uint8_t)nb_comps_
  };
  bw_.Reserve(data_size + 2);
  bw_.PutBytes(kHeader, sizeof(kHeader));
  for (int c = 0; c < nb_comps_; ++c) {
    bw_.PutByte(c + 1);
    bw_.PutByte(quant_idx_[c] * 0x11);
  }
  bw_.PutByte(0x00);        // Ss
  bw_.PutByte(0x3f);        // Se
  bw_.PutByte(0x00);        // Ah/Al
}

////////////////////////////////////////////////////////////////////////////////

void Encoder::WriteEOI() {   // EOI
  bw_.Flush();
  // append EOI
  bw_.Reserve(2);
  bw_.PutByte(0xff);
  bw_.PutByte(0xd9);
}

}    // namespace sjpeg
<commit_msg>fix bug in data_size calculation for EXIF chunk<commit_after>// Copyright 2018 Google Inc.
//
// 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.
//
//  header and chunks writing
//
// Author: Skal (pascal.massimino@gmail.com)

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include "sjpegi.h"

using namespace sjpeg;

namespace sjpeg {

////////////////////////////////////////////////////////////////////////////////
// Headers
//
// NOTE(skal): all chunks start with a startcode '0xff??' (0xffd8 e.g),
// followed by the size of the payload *not counting the startcode*!
// That's why you often find these 'Reserve(data_size + 2)' below, the '+2'
// accounting for the 0xff?? startcode size.

void Encoder::WriteAPP0() {  // SOI + APP0
  const uint8_t kHeader0[] = {
    0xff, 0xd8,                     // SOI
    0xff, 0xe0, 0x00, 0x10,         // APP0
    0x4a, 0x46, 0x49, 0x46, 0x00,   // 'JFIF'
    0x01, 0x01,                     // v1.01
    0x00, 0x00, 0x01, 0x00, 0x01,   // aspect ratio = 1:1
    0x00, 0x00                      // thumbnail width/height
  };
  bw_.Reserve(sizeof(kHeader0));
  bw_.PutBytes(kHeader0, sizeof(kHeader0));
}

bool Encoder::WriteAPPMarkers(const std::string& data) {
  if (data.size() == 0) return true;
  const size_t data_size = data.size();
  bw_.Reserve(data_size);
  bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  return true;
}

bool Encoder::WriteEXIF(const std::string& data) {
  if (data.size() == 0) return true;
  const uint8_t kEXIF[] = "Exif\0";
  const size_t kEXIF_len = 6;  // includes the \0's
  const size_t data_size = data.size() + kEXIF_len + 2;
  if (data_size > 0xffff) return false;
  bw_.Reserve(data_size + 2);
  bw_.PutByte(0xff);
  bw_.PutByte(0xe1);
  bw_.PutByte((data_size >> 8) & 0xff);
  bw_.PutByte((data_size >> 0) & 0xff);
  bw_.PutBytes(kEXIF, kEXIF_len);
  bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  return true;
}

bool Encoder::WriteICCP(const std::string& data) {
  if (data.size() == 0) return true;
  size_t data_size = data.size();
  const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data.data());
  const uint8_t kICCP[] = "ICC_PROFILE";
  const size_t kICCP_len = 12;  // includes the \0
  const size_t chunk_size_max = 0xffff - kICCP_len - 4;
  size_t max_chunk = (data_size + chunk_size_max - 1) / chunk_size_max;
  if (max_chunk >= 256) return false;
  size_t seq = 1;
  while (data_size > 0) {
    size_t size = data_size;
    if (size > chunk_size_max) size = chunk_size_max;
    bw_.Reserve(size + kICCP_len + 4 + 2);
    bw_.PutByte(0xff);
    bw_.PutByte(0xe2);
    bw_.PutByte(((size + kICCP_len + 4) >> 8) & 0xff);
    bw_.PutByte(((size + kICCP_len + 4) >> 0) & 0xff);
    bw_.PutBytes(kICCP, kICCP_len);
    bw_.PutByte(seq & 0xff);
    bw_.PutByte(max_chunk & 0xff);
    bw_.PutBytes(ptr, size);
    ptr += size;
    data_size -= size;
    seq += 1;
  }
  return true;
}

bool Encoder::WriteXMP(const std::string& data) {
  if (data.size() == 0) return true;
  const uint8_t kXMP[] = "http://ns.adobe.com/xap/1.0/";
  const size_t kXMP_size = 29;
  const size_t data_size = 2 + data.size() + kXMP_size;
  if (data_size > 0xffff) return false;  // error
  bw_.Reserve(data_size + 2);
  bw_.PutByte(0xff);
  bw_.PutByte(0xe1);
  bw_.PutByte((data_size >> 8) & 0xff);
  bw_.PutByte((data_size >> 0) & 0xff);
  bw_.PutBytes(kXMP, kXMP_size);
  bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());
  return true;
}

void Encoder::WriteDQT() {
  const size_t data_size = 2 * 65 + 2;
  const uint8_t kDQTHeader[] = { 0xff, 0xdb, 0x00, (uint8_t)data_size };
  bw_.Reserve(data_size + 2);
  bw_.PutBytes(kDQTHeader, sizeof(kDQTHeader));
  for (int n = 0; n <= 1; ++n) {
    bw_.PutByte(n);
    const uint8_t* quant = quants_[n].quant_;
    for (int i = 0; i < 64; ++i) {
      bw_.PutByte(quant[kZigzag[i]]);
    }
  }
}

////////////////////////////////////////////////////////////////////////////////

#define DATA_16b(X) ((uint8_t)((X) >> 8)), ((uint8_t)((X) & 0xff))

void Encoder::WriteSOF() {   // SOF
  const size_t data_size = 3 * nb_comps_ + 8;
  assert(data_size <= 255);
  const uint8_t kHeader[] = {
    0xff, 0xc0, DATA_16b(data_size),         // SOF0 marker, size
    0x08,                                    // 8bits/components
    DATA_16b(H_), DATA_16b(W_),              // height, width
    (uint8_t)nb_comps_                       // number of components
  };
  bw_.Reserve(data_size + 2);
  bw_.PutBytes(kHeader, sizeof(kHeader));
  for (int c = 0; c < nb_comps_; ++c) {
    bw_.PutByte(c + 1);
    bw_.PutByte(block_dims_[c]);
    bw_.PutByte(quant_idx_[c]);
  }
}

void Encoder::WriteDHT() {
  InitCodes(false);
  const int nb_tables = (nb_comps_ == 1 ? 1 : 2);
  for (int c = 0; c < nb_tables; ++c) {   // luma, chroma
    for (int type = 0; type <= 1; ++type) {               // dc, ac
      const HuffmanTable* const h = Huffman_tables_[type * 2 + c];
      const size_t data_size = 3 + 16 + h->nb_syms_;
      assert(data_size <= 255);
      bw_.Reserve(data_size + 2);
      bw_.PutByte(0xff);
      bw_.PutByte(0xc4);
      bw_.PutByte(0x00 /*data_size >> 8*/);
      bw_.PutByte(data_size);
      bw_.PutByte((type << 4) | c);
      bw_.PutBytes(h->bits_, 16);
      bw_.PutBytes(h->syms_, h->nb_syms_);
    }
  }
}

////////////////////////////////////////////////////////////////////////////////

void Encoder::WriteSOS() {   // SOS
  const size_t data_size = 3 + nb_comps_ * 2 + 3;
  assert(data_size <= 255);
  const uint8_t kHeader[] = {
      0xff, 0xda, DATA_16b(data_size), (uint8_t)nb_comps_
  };
  bw_.Reserve(data_size + 2);
  bw_.PutBytes(kHeader, sizeof(kHeader));
  for (int c = 0; c < nb_comps_; ++c) {
    bw_.PutByte(c + 1);
    bw_.PutByte(quant_idx_[c] * 0x11);
  }
  bw_.PutByte(0x00);        // Ss
  bw_.PutByte(0x3f);        // Se
  bw_.PutByte(0x00);        // Ah/Al
}

////////////////////////////////////////////////////////////////////////////////

void Encoder::WriteEOI() {   // EOI
  bw_.Flush();
  // append EOI
  bw_.Reserve(2);
  bw_.PutByte(0xff);
  bw_.PutByte(0xd9);
}

}    // namespace sjpeg
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_image_build.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file   p9_io_xbus_image_build.C
/// @brief  Implements HWP that builds the Hcode image in IO Xbus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner        : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner         : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team             : IO
/// *HWP Level            : 3
/// *HWP Consumed by      : FSP:HB
///----------------------------------------------------------------------------

//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_xbus_image_build.H>
#include "p9_xip_image.h"

//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)
{
    FAPI_IMP("Entering getXbusImageFromHwImage.");
    P9XipSection ppeSection;
    ppeSection.iv_offset = 0;
    ppeSection.iv_size = 0;

    FAPI_ASSERT(iImagePtr != NULL ,
                fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
                "Bad pointer to HW Image.");

    // Pulls the IO PPE Section from the HW/XIP Image
    // XIP(Execution In Place) -- Points to Seeprom
    FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));

    // Point to the I/O PPE Section in the HW/XIP Image
    oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);

    // From the I/O Section, lets pull the IOO Nvlink Image.
    FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));

    // Point to the IOO PPE Image of the I/O PPE Section
    oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);

    // Set the Size of the IOO Image
    oSize = ppeSection.iv_size;

fapi_try_exit:
    FAPI_IMP("Exiting getXbusImageFromHwImage.");
    return fapi2::current_err;
}

//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)
{
    fapi2::buffer<uint64_t> data64(iData);
    // Xscom -- Scom from core in Hostboot mode
    return fapi2::putScom(iTgt, iAddr, data64);
}

//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)
{
    FAPI_IMP("Entering p9_io_xbus_image_build.");

    const uint64_t SRAM_BASE_ADDR   = 0xFFFF000000000000ull;
    const uint64_t AUTOINC_EN       = 0x8000000000000000ull;
    const uint64_t AUTOINC_DIS      = 0x0000000000000000ull;
    const uint64_t HARD_RESET       = 0x6000000000000000ull; // xcr cmd=110
    const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
    // PPE Address
    const uint64_t BASE_ADDR    = 0x0000000006010840ull;
    const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
    const uint64_t MEM_ARB_SCR  = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
    const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
    const uint64_t XCR_NONE     = 0x0000000000000010ull | BASE_ADDR; // External Control Reg

    uint64_t data      = 0;
    uint8_t* pPpeImg = NULL;
    uint32_t imgSize   = 0;

    // Get vector of xbus units from the processor
    auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();

    // Make sure we have functional xbus units before we load the ppe
    if(!xbusUnits.empty())
    {
        FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), "Extract PPE Image Failed.");

        // PPE Reset
        FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");

        // Set PPE Base Address
        FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");

        // Set PPE into Autoincrement Mode
        FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");

        for(uint32_t i = 0; i < imgSize; i += 8)
        {
            data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |
                   (((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |
                   (((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |
                   (((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |
                   (((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |
                   (((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |
                   (((uint64_t) * (pPpeImg + i + 6) <<  8) & 0x000000000000FF00ull) |
                   (((uint64_t) * (pPpeImg + i + 7) <<  0) & 0x00000000000000FFull);

            // Write Data, as the address will be autoincremented.
            FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
        }

        // Disable Auto Increment
        FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");

        // PPE Reset
        FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");

        // PPE Resume From Halt
        FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
    }
    else
    {
        FAPI_INF("No functional xbus units found. Skipping Xbus PPE Load...");
    }

fapi_try_exit:
    FAPI_IMP("Exit p9_io_xbus_image_build.");
    return fapi2::current_err;
}
<commit_msg>Alink Hot Repair Fix<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_image_build.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file   p9_io_xbus_image_build.C
/// @brief  Implements HWP that builds the Hcode image in IO Xbus PPE Sram.
///----------------------------------------------------------------------------
/// *HWP HWP Owner        : Chris Steffen <cwsteffen@us.ibm.com>
/// *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>
/// *HWP FW Owner         : Jamie Knight <rjknight@us.ibm.com>
/// *HWP Team             : IO
/// *HWP Level            : 3
/// *HWP Consumed by      : FSP:HB
///----------------------------------------------------------------------------

//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <p9_io_xbus_image_build.H>
#include "p9_xip_image.h"

//---------------------------------------------------------------------------
fapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)
{
    FAPI_IMP("Entering getXbusImageFromHwImage.");
    P9XipSection ppeSection;
    ppeSection.iv_offset = 0;
    ppeSection.iv_size = 0;

    FAPI_ASSERT(iImagePtr != NULL ,
                fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),
                "Bad pointer to HW Image.");

    // Pulls the IO PPE Section from the HW/XIP Image
    // XIP(Execution In Place) -- Points to Seeprom
    FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));

    // Point to the I/O PPE Section in the HW/XIP Image
    oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);

    // From the I/O Section, lets pull the IOO Nvlink Image.
    FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));

    // Point to the IOO PPE Image of the I/O PPE Section
    oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);

    // Set the Size of the IOO Image
    oSize = ppeSection.iv_size;

fapi_try_exit:
    FAPI_IMP("Exiting getXbusImageFromHwImage.");
    return fapi2::current_err;
}

//---------------------------------------------------------------------------
fapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)
{
    fapi2::buffer<uint64_t> data64(iData);
    // Xscom -- Scom from core in Hostboot mode
    return fapi2::putScom(iTgt, iAddr, data64);
}

//---------------------------------------------------------------------------
fapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)
{
    FAPI_IMP("Entering p9_io_xbus_image_build.");
    /*
     * Currently a NOP as we do not have a POR to use the xbus image.
     *
    const uint64_t SRAM_BASE_ADDR   = 0xFFFF000000000000ull;
    const uint64_t AUTOINC_EN       = 0x8000000000000000ull;
    const uint64_t AUTOINC_DIS      = 0x0000000000000000ull;
    const uint64_t HARD_RESET       = 0x6000000000000000ull; // xcr cmd=110
    const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; // xcr cmd=010
    // PPE Address
    const uint64_t BASE_ADDR    = 0x0000000006010840ull;
    const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; // Sram Address Reg
    const uint64_t MEM_ARB_SCR  = 0x000000000000000Aull | BASE_ADDR; // Sram Source Control Reg
    const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; // Sram Data Reg
    const uint64_t XCR_NONE     = 0x0000000000000010ull | BASE_ADDR; // External Control Reg

    uint64_t data      = 0;
    uint8_t* pPpeImg = NULL;
    uint32_t imgSize   = 0;

    // Get vector of xbus units from the processor
    auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();

    // Make sure we have functional xbus units before we load the ppe
    if(!xbusUnits.empty())
    {
        FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), "Extract PPE Image Failed.");

        // PPE Reset
        FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");

        // Set PPE Base Address
        FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), "Set Base Address Failed.");

        // Set PPE into Autoincrement Mode
        FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), "Auto-Increment Enable Failed.");

        for(uint32_t i = 0; i < imgSize; i += 8)
        {
            data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |
                   (((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |
                   (((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |
                   (((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |
                   (((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |
                   (((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |
                   (((uint64_t) * (pPpeImg + i + 6) <<  8) & 0x000000000000FF00ull) |
                   (((uint64_t) * (pPpeImg + i + 7) <<  0) & 0x00000000000000FFull);

            // Write Data, as the address will be autoincremented.
            FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), "Data Write Failed.");
        }

        // Disable Auto Increment
        FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), "Auto-Increment Disable Failed.");

        // PPE Reset
        FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), "Hard Reset Failed.");

        // PPE Resume From Halt
        FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), "Resume From Halt Failed.");
    }
    else
    {
        FAPI_INF("No functional xbus units found. Skipping Xbus PPE Load...");
    }

    fapi_try_exit:
    */
    FAPI_IMP("Exit p9_io_xbus_image_build.");
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
///     1) Identify Partical good chiplet and configure Multicasting register
///     2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
///     3) Similar way,  set fence for Nest and MC chiplet
///     4) Similar way,  Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V. Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Brian Silver <bsilver@us.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_

#include <fapi2.H>

namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
    MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
    MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
    MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
    MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
    NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
    HANG_PULSE_0X10 = 0x10,
    HANG_PULSE_0X0F = 0x0F,
    HANG_PULSE_0X06 = 0x06,
    HANG_PULSE_0X17 = 0x17,
    HANG_PULSE_0X18 = 0x18,
    HANG_PULSE_0X22 = 0x22,
    HANG_PULSE_0X13 = 0x13,
    HANG_PULSE_0X03 = 0x03,
    OPCG_ALIGN_SETTING = 0x5000000000003020ull,
    INOP_ALIGN_SETTING_0X5 = 0x5,
    OPCG_WAIT_CYCLE_0X020 = 0x020,
    SCAN_RATIO_0X3 = 0x3,
    SYNC_PULSE_DELAY_0X0 = 0X00,
    SYNC_CONFIG_DEFAULT = 0X0000000000000000,
    HANG_PULSE_0X00 = 0x00,
    HANG_PULSE_0X01 = 0x01,
    HANG_PULSE_0X04 = 0x04,
    HANG_PULSE_0X1A = 0x1A,
    NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
    MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
    MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
    MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
    REGIONS_EXCEPT_VITAL = 0x7FF,
    SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
    SCAN_TYPES_TIME_GPTR_REPR = 0x230,
    SCAN_RATIO_0X0 = 0x0,
    SYNC_CONFIG_4TO1 = 0X0800000000000000,
    HW_NS_DELAY = 200000, // unit is nano seconds
    SIM_CYCLE_DELAY = 10000, // unit is cycles
    HANG_PULSE_0X12 = 0x12,
    HANG_PULSE_0X1C = 0x1C
};
}

typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
        fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

/// @brief Identify all good chiplets excluding EQ/EC
///  -- All chiplets will be reset and PLLs started
///  -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
///  -- Can't use the multicast for all non-nest chiplets
///  -- This is intended to be the eventual product setting
///  -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
///  -- Reset to default state
///  -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
///  -- Start vital clocks and release endpoint reset
///  -- PCB Slave error register Reset
///
///
/// @param[in]     i_target_chip   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    fapi2::ReturnCode p9_sbe_chiplet_reset(const
                                           fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}

#endif
<commit_msg>IPL updates -- IPL_flow_v180<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_chiplet_reset.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_sbe_chiplet_reset.H
///
/// @brief Steps:-
///     1) Identify Partical good chiplet and configure Multicasting register
///     2) Similar way, Configure hang pulse counter for Nest/MC/OBus/XBus/PCIe
///     3) Similar way,  set fence for Nest and MC chiplet
///     4) Similar way,  Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode
///
/// Done
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V. Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Brian Silver <bsilver@us.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

#ifndef _P9_SBE_CHIPLET_RESET_H_
#define _P9_SBE_CHIPLET_RESET_H_

#include <fapi2.H>

namespace p9SbeChipletReset
{
enum P9_SBE_CHIPLET_RESET_Public_Constants
{
    MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,
    MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,
    MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,
    MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,
    NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,
    HANG_PULSE_0X10 = 0x10,
    HANG_PULSE_0X0F = 0x0F,
    HANG_PULSE_0X06 = 0x06,
    HANG_PULSE_0X17 = 0x17,
    HANG_PULSE_0X18 = 0x18,
    HANG_PULSE_0X22 = 0x22,
    HANG_PULSE_0X13 = 0x13,
    HANG_PULSE_0X03 = 0x03,
    OPCG_ALIGN_SETTING = 0x5000000000003020ull,
    INOP_ALIGN_SETTING_0X5 = 0x5,
    OPCG_WAIT_CYCLE_0X020 = 0x020,
    SCAN_RATIO_0X3 = 0x3,
    SYNC_PULSE_DELAY_0X0 = 0X00,
    SYNC_CONFIG_DEFAULT = 0X0000000000000000,
    HANG_PULSE_0X00 = 0x00,
    HANG_PULSE_0X01 = 0x01,
    HANG_PULSE_0X04 = 0x04,
    HANG_PULSE_0X1A = 0x1A,
    NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,
    MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,
    MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,
    MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,
    REGIONS_EXCEPT_VITAL = 0x7FF,
    SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,
    SCAN_TYPES_TIME_GPTR_REPR = 0x230,
    SCAN_RATIO_0X0 = 0x0,
    SYNC_CONFIG_4TO1 = 0X0800000000000000,
    HW_NS_DELAY = 200000, // unit is nano seconds
    SIM_CYCLE_DELAY = 10000, // unit is cycles
    HANG_PULSE_0X12 = 0x12,
    HANG_PULSE_0X1C = 0x1C,
    HANG_PULSE_0X05 = 0x05
};
}

typedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const
        fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

/// @brief Identify all good chiplets excluding EQ/EC
///  -- All chiplets will be reset and PLLs started
///  -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad
/// Setup multicast groups for all chiplets
///  -- Can't use the multicast for all non-nest chiplets
///  -- This is intended to be the eventual product setting
///  -- This includes the core/cache chiplets
/// For all good chiplets excluding EQ/EC
/// -- Setup Chiplet GP3 regs
///  -- Reset to default state
///  -- Set chiplet enable on all all good chiplets excluding EQ/EC
/// For all enabled chiplets excluding EQ/EC/Buses
///  -- Start vital clocks and release endpoint reset
///  -- PCB Slave error register Reset
///
///
/// @param[in]     i_target_chip   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    fapi2::ReturnCode p9_sbe_chiplet_reset(const
                                           fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}

#endif
<|endoftext|>


<commit_before>/*
  http://portaudio.com/docs/v19-doxydocs/api_overview.html
*/

/* BEGIN Setup */
#include "jsaudio.h"
#include "helpers.h"
#include "stream.h"

/* Initialize stream and jsStreamCb as global */
LocalFunction jsStreamCb;

/* BEGIN Initialization, termination, and utility */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abed859482d156622d9332dff9b2d89da
NAN_METHOD(initialize) {
  PaError err = Pa_Initialize();
  if (err != paNoError) {
    ThrowError(Pa_GetErrorText(err));
  }
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0db317604e916e8bd6098e60e6237221
NAN_METHOD(terminate) {
  PaError err = Pa_Terminate();
  if (err != paNoError) {
    ThrowError(Pa_GetErrorText(err));
  }
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a66da08bcf908e0849c62a6b47f50d7b4
NAN_METHOD(getVersion) {
  info.GetReturnValue().Set(Pa_GetVersion());
}

/* BEGIN Host APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a19dbdb7c8702e3f4bfc0cdb99dac3dd9
NAN_METHOD(getHostApiCount) {
  info.GetReturnValue().Set(Pa_GetHostApiCount());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ae55c77f9b7e3f8eb301a6f1c0e2347ac
NAN_METHOD(getDefaultHostApi) {
  info.GetReturnValue().Set(Pa_GetDefaultHostApi());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7c650aede88ea553066bab9bbe97ea90
NAN_METHOD(getHostApiInfo) {
  HandleScope scope;
  int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();
  const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);
  LocalObject obj = New<Object>();
  obj->Set(ToLocString("apiIndex"), New<Number>(api));
  HostApiInfoToLocalObject(obj, hai);
  info.GetReturnValue().Set(obj);
}

/* BEGIN Device APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#acfe4d3c5ec1a343f459981bfa2057f8d
NAN_METHOD(getDeviceCount) {
  info.GetReturnValue().Set(Pa_GetDeviceCount());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abf9f2f82da95553d5adb929af670f74b
NAN_METHOD(getDefaultInputDevice) {
  info.GetReturnValue().Set(Pa_GetDefaultInputDevice());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#adc955dfab007624000695c48d4f876dc
NAN_METHOD(getDefaultOutputDevice) {
  info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ac7d8e091ffc1d1d4a035704660e117eb
NAN_METHOD(getDeviceInfo) {
  HandleScope scope;
  int dvc = info[0].IsEmpty()
    ? Pa_GetDefaultInputDevice()
    : info[0]->Uint32Value();
  const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);
  LocalObject obj = New<Object>();
  obj->Set(ToLocString("deviceIndex"), New<Number>(dvc));
  DeviceInfoToLocalObject(obj, di);
  info.GetReturnValue().Set(obj);
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a443ad16338191af364e3be988014cbbe
NAN_METHOD(openStream) {
  HandleScope scope;
  PaError err;

  // Get params objects
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(ToLocObject(Get(obj, ToLocString("stream"))));

  LocalObject objInput = ToLocObject(Get(obj, ToLocString("input")));
  LocalObject objOutput = ToLocObject(Get(obj, ToLocString("output")));

  PaStreamParameters paramsIn = LocObjToPaStreamParameters(objInput);
  PaStreamParameters paramsOut = LocObjToPaStreamParameters(objOutput);
  // Get stream options
  double sampleRate = LocalizeDouble(Get(obj, ToLocString("sampleRate")));
  unsigned long framesPerBuffer = LocalizeULong(
    Get(obj, ToLocString("framesPerBuffer")));
  PaStreamFlags streamFlags = static_cast<PaStreamFlags>(
    Get(obj, ToLocString("streamFlags")).ToLocalChecked()->IntegerValue());

  // Start stream
  err = Pa_OpenStream(
    stream->streamPtrRef(),
    &paramsIn,
    &paramsOut,
    sampleRate,
    framesPerBuffer,
    streamFlags,
    NULL,
    NULL
  );
  if (err != paNoError) {
    printf("%s\n", "OpenStream: ");
    printf("%s\n", Pa_GetErrorText(err));
    // ThrowError(Pa_GetErrorText(err));
  }
  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(err));
}

/*
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0a12735ac191200f696a43b87667b714
NAN_METHOD(openDefaultStream) {
  // ToDo: implement this
}
*/

//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7432aadd26c40452da12fa99fc1a047b
NAN_METHOD(startStream) {
  HandleScope scope;
  PaError err;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Start stream
  err = Pa_StartStream(stream->streamPtr());
  if (err != paNoError) {
    printf("%s\n", "StartStream: ");
    printf("%s\n", Pa_GetErrorText(err));
    // ThrowError(Pa_GetErrorText(err));
  }
  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(err));
}

NAN_METHOD(getStreamWriteAvailable) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Start stream
  retVal = Pa_GetStreamWriteAvailable(stream->streamPtr());

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}

NAN_METHOD(getStreamReadAvailable) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Start stream
  retVal = Pa_GetStreamReadAvailable(stream->streamPtr());

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}

NAN_METHOD(writeStream) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Get the buffer data
  TypedArrayContents<float> buf(info[1]);
  unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;

  // Start stream
  retVal = Pa_WriteStream(stream->streamPtr(), *buf, bufFrames);

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}

NAN_METHOD(readStream) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Get the buffer data
  TypedArrayContents<float> buf(info[1]);
  unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;

  // Start stream
  retVal = Pa_ReadStream(stream->streamPtr(), *buf, bufFrames);

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}
<commit_msg>Added links to PortAudio docs<commit_after>/*
  http://portaudio.com/docs/v19-doxydocs/api_overview.html
*/

/* BEGIN Setup */
#include "jsaudio.h"
#include "helpers.h"
#include "stream.h"

/* Initialize stream and jsStreamCb as global */
LocalFunction jsStreamCb;

/* BEGIN Initialization, termination, and utility */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abed859482d156622d9332dff9b2d89da
NAN_METHOD(initialize) {
  PaError err = Pa_Initialize();
  if (err != paNoError) {
    ThrowError(Pa_GetErrorText(err));
  }
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0db317604e916e8bd6098e60e6237221
NAN_METHOD(terminate) {
  PaError err = Pa_Terminate();
  if (err != paNoError) {
    ThrowError(Pa_GetErrorText(err));
  }
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a66da08bcf908e0849c62a6b47f50d7b4
NAN_METHOD(getVersion) {
  info.GetReturnValue().Set(Pa_GetVersion());
}

/* BEGIN Host APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a19dbdb7c8702e3f4bfc0cdb99dac3dd9
NAN_METHOD(getHostApiCount) {
  info.GetReturnValue().Set(Pa_GetHostApiCount());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ae55c77f9b7e3f8eb301a6f1c0e2347ac
NAN_METHOD(getDefaultHostApi) {
  info.GetReturnValue().Set(Pa_GetDefaultHostApi());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7c650aede88ea553066bab9bbe97ea90
NAN_METHOD(getHostApiInfo) {
  HandleScope scope;
  int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();
  const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);
  LocalObject obj = New<Object>();
  obj->Set(ToLocString("apiIndex"), New<Number>(api));
  HostApiInfoToLocalObject(obj, hai);
  info.GetReturnValue().Set(obj);
}

/* BEGIN Device APIs */
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#acfe4d3c5ec1a343f459981bfa2057f8d
NAN_METHOD(getDeviceCount) {
  info.GetReturnValue().Set(Pa_GetDeviceCount());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#abf9f2f82da95553d5adb929af670f74b
NAN_METHOD(getDefaultInputDevice) {
  info.GetReturnValue().Set(Pa_GetDefaultInputDevice());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#adc955dfab007624000695c48d4f876dc
NAN_METHOD(getDefaultOutputDevice) {
  info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ac7d8e091ffc1d1d4a035704660e117eb
NAN_METHOD(getDeviceInfo) {
  HandleScope scope;
  int dvc = info[0].IsEmpty()
    ? Pa_GetDefaultInputDevice()
    : info[0]->Uint32Value();
  const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);
  LocalObject obj = New<Object>();
  obj->Set(ToLocString("deviceIndex"), New<Number>(dvc));
  DeviceInfoToLocalObject(obj, di);
  info.GetReturnValue().Set(obj);
}

// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a443ad16338191af364e3be988014cbbe
NAN_METHOD(openStream) {
  HandleScope scope;
  PaError err;

  // Get params objects
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(ToLocObject(Get(obj, ToLocString("stream"))));

  LocalObject objInput = ToLocObject(Get(obj, ToLocString("input")));
  LocalObject objOutput = ToLocObject(Get(obj, ToLocString("output")));

  PaStreamParameters paramsIn = LocObjToPaStreamParameters(objInput);
  PaStreamParameters paramsOut = LocObjToPaStreamParameters(objOutput);
  // Get stream options
  double sampleRate = LocalizeDouble(Get(obj, ToLocString("sampleRate")));
  unsigned long framesPerBuffer = LocalizeULong(
    Get(obj, ToLocString("framesPerBuffer")));
  PaStreamFlags streamFlags = static_cast<PaStreamFlags>(
    Get(obj, ToLocString("streamFlags")).ToLocalChecked()->IntegerValue());

  // Start stream
  err = Pa_OpenStream(
    stream->streamPtrRef(),
    &paramsIn,
    &paramsOut,
    sampleRate,
    framesPerBuffer,
    streamFlags,
    NULL,
    NULL
  );
  if (err != paNoError) {
    printf("%s\n", "OpenStream: ");
    printf("%s\n", Pa_GetErrorText(err));
    // ThrowError(Pa_GetErrorText(err));
  }
  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(err));
}

/*
// http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0a12735ac191200f696a43b87667b714
NAN_METHOD(openDefaultStream) {
  // ToDo: implement this
}
*/

//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a7432aadd26c40452da12fa99fc1a047b
NAN_METHOD(startStream) {
  HandleScope scope;
  PaError err;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Start stream
  err = Pa_StartStream(stream->streamPtr());
  if (err != paNoError) {
    printf("%s\n", "StartStream: ");
    printf("%s\n", Pa_GetErrorText(err));
    // ThrowError(Pa_GetErrorText(err));
  }
  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(err));
}

//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a25595acf48733ec32045aa189c3caa61
NAN_METHOD(getStreamWriteAvailable) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Start stream
  retVal = Pa_GetStreamWriteAvailable(stream->streamPtr());

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}

//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#ad04c33f045fa58d7b705b56b1fd3e816
NAN_METHOD(getStreamReadAvailable) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Start stream
  retVal = Pa_GetStreamReadAvailable(stream->streamPtr());

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}

//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a075a6efb503a728213bdae24347ed27d
NAN_METHOD(writeStream) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Get the buffer data
  TypedArrayContents<float> buf(info[1]);
  unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;

  // Start stream
  retVal = Pa_WriteStream(stream->streamPtr(), *buf, bufFrames);

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}

//http://portaudio.com/docs/v19-doxydocs/portaudio_8h.html#a0b62d4b74b5d3d88368e9e4c0b8b2dc7
NAN_METHOD(readStream) {
  HandleScope scope;
  long retVal;

  // Get stream object
  LocalObject obj = info[0]->ToObject();
  JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());

  // Get the buffer data
  TypedArrayContents<float> buf(info[1]);
  unsigned long bufFrames = static_cast<unsigned long>(buf.length()) / 2;

  // Start stream
  retVal = Pa_ReadStream(stream->streamPtr(), *buf, bufFrames);

  // Testing that params are set right
  info.GetReturnValue().Set(New<Number>(retVal));
}
<|endoftext|>


<commit_before>#include <node.h>
#include <v8.h>

#include "zmap-1.2.1/src/zopt.h"

#include "libzmap.h"

namespace libzmap {

using namespace node;
using namespace v8;

Handle<Value> LibZMAP(const Arguments& args) {
  HandleScope scope;

  Local<Function> callback;
  Local<Object> obj;

  if (args.Length() < 1) {
    ThrowException(Exception::TypeError(String::New("Arguments invalid")));
    return scope.Close(Undefined());
  }

  if (args[0]->IsFunction()) {
    callback = Local<Function>::Cast(args[0]);
  } else {
    if (!args[1]->IsFunction()) {
      ThrowException(Exception::TypeError(String::New("Function expected")));
      return scope.Close(Undefined());
    }

    callback = Local<Function>::Cast(args[1]);

    if (!args[0]->IsObject()) {
      ThrowException(Exception::TypeError(String::New("Object expected")));
      return scope.Close(Undefined());
    }
  }

  if (args[0]->IsObject()) {
    obj = args[0]->ToObject();
  }

  obj->Set(String::NewSymbol("x"),
    String::New("wtf"));

  /* Setup options */
  /* Initialize scan */

  return scope.Close(obj);
}

void Init (Handle<Object> exports) {
  exports->Set(String::NewSymbol("zmap"),
    FunctionTemplate::New(LibZMAP)->GetFunction());
}

extern "C" {
  NODE_MODULE(zmap, Init)
}

} // namespace libzmap
<commit_msg>development Tue Sep  2 04:25:20 MDT 2014: Working on argument to option conversions<commit_after>#include <node.h>
#include <v8.h>

#include "zmap-1.2.1/src/zopt.h"

#include "libzmap.h"

namespace libzmap {

using namespace node;
using namespace v8;

Handle<Value> LibZMAP(const Arguments& args) {
  HandleScope scope;

  struct gengetopt_args_info argv;
  struct cmdline_parser_params *params;
  params = cmdline_parser_params_create();
  params->initialize = 1;
  params->override = 0;
  params->check_required = 0;

  int config_loaded = 0;

  if (cmdline_parser_ext(args.Length(), args[0], &argv, params) != 0) {
    ThrowException(Exception::TypeError(String::New("cmdline_parser_ext met")));
    //exit(EXIT_SUCCESS);
  }

  Local<Function> callback;
  Local<Object> obj;

  if (args.Length() < 1) {
    ThrowException(Exception::TypeError(String::New("Arguments invalid")));
    return scope.Close(Undefined());
  }

  if (args[0]->IsFunction()) {
    callback = Local<Function>::Cast(args[0]);
  } else {
    if (!args[1]->IsFunction()) {
      ThrowException(Exception::TypeError(String::New("Function expected")));
      return scope.Close(Undefined());
    }

    callback = Local<Function>::Cast(args[1]);

    if (!args[0]->IsObject()) {
      ThrowException(Exception::TypeError(String::New("Object expected")));
      return scope.Close(Undefined());
    }
  }

  if (args[0]->IsObject()) {
    obj = args[0]->ToObject();
  }

  return scope.Close(obj);
}

void Init (Handle<Object> exports) {
  exports->Set(String::NewSymbol("zmap"),
    FunctionTemplate::New(LibZMAP)->GetFunction());
}

extern "C" {
  NODE_MODULE(zmap, Init)
}

} // namespace libzmap
<|endoftext|>


<commit_before>#include <tinyxml2.h>
#include "mud.h"
#include "living.h"
#include "event.h"
#include "delayedEvent.h"
#include "world.h"

Living::Living()
{
    events.RegisterEvent("HeartBeat", new DelayedEvent(LIVING_PULSE,0));

    _position = POSITION_STANDING;
    _gender = Gender::Neuter;
}

void Living::EnterGame()
{
}
void Living::LeaveGame()
{
}

void Living::Update()
{
    events.CallEvent("HeartBeat", NULL, (void*)this);
}

bool Living::IsLiving() const
{
    return true;
}

Gender Living::GetGender() const
{
    return _gender;
}
void Living::SetGender(Gender gender)
{
    _gender = gender;
}

unsigned int Living::GetPosition() const
{
    return _position;
}
void Living::SetPosition(unsigned int pos)
{
    _position = pos;
}

bool Living::AddAttribute(Attribute* attr)
{
    _attributes.push_back(attr);
    return true;
}
void Living::FindAttribute(int apply, int id, std::vector<Attribute*> &results)
{
    for (Attribute* attr: _attributes)
        {
            if (attr->GetApply() == apply && attr->GetId() == id)
                {
                    results.push_back(attr);
                }
        }
}
void Living::FindAttribute(int type, std::vector<Attribute*>& results)
{
    for (Attribute* attr:_attributes)
        {
            if (attr->GetType() == type)
                {
                    results.push_back(attr);
                }
        }
}

void Living::Serialize(tinyxml2::XMLElement* root)
{
    tinyxml2::XMLDocument* doc = root->GetDocument();
    tinyxml2::XMLElement* node = doc->NewElement("living");

    node->SetAttribute("gender", (int)_gender);
    Entity::Serialize(node);
    root->InsertEndChild(node);
}
void Living::Deserialize(tinyxml2::XMLElement* root)
{
    _gender = (Gender)root->IntAttribute("gender");
    Entity::Deserialize(root->FirstChildElement("entity"));
}
<commit_msg>fixed uninitialized members.<commit_after>#include <tinyxml2.h>
#include "mud.h"
#include "living.h"
#include "event.h"
#include "delayedEvent.h"
#include "world.h"

Living::Living()
{
    events.RegisterEvent("HeartBeat", new DelayedEvent(LIVING_PULSE,0));

    _position = POSITION_STANDING;
    _gender = Gender::Neuter;
    _following = nullptr;
}

void Living::EnterGame()
{
}
void Living::LeaveGame()
{
}

void Living::Update()
{
    events.CallEvent("HeartBeat", NULL, (void*)this);
}

bool Living::IsLiving() const
{
    return true;
}

Gender Living::GetGender() const
{
    return _gender;
}
void Living::SetGender(Gender gender)
{
    _gender = gender;
}

unsigned int Living::GetPosition() const
{
    return _position;
}
void Living::SetPosition(unsigned int pos)
{
    _position = pos;
}

bool Living::AddAttribute(Attribute* attr)
{
    _attributes.push_back(attr);
    return true;
}
void Living::FindAttribute(int apply, int id, std::vector<Attribute*> &results)
{
    for (Attribute* attr: _attributes)
        {
            if (attr->GetApply() == apply && attr->GetId() == id)
                {
                    results.push_back(attr);
                }
        }
}
void Living::FindAttribute(int type, std::vector<Attribute*>& results)
{
    for (Attribute* attr:_attributes)
        {
            if (attr->GetType() == type)
                {
                    results.push_back(attr);
                }
        }
}

void Living::Serialize(tinyxml2::XMLElement* root)
{
    tinyxml2::XMLDocument* doc = root->GetDocument();
    tinyxml2::XMLElement* node = doc->NewElement("living");

    node->SetAttribute("gender", (int)_gender);
    Entity::Serialize(node);
    root->InsertEndChild(node);
}
void Living::Deserialize(tinyxml2::XMLElement* root)
{
    _gender = (Gender)root->IntAttribute("gender");
    Entity::Deserialize(root->FirstChildElement("entity"));
}
<|endoftext|>


<commit_before>#include "parser.h"

int priority[128];
bool rightassoc[128];

const std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)
{
    priority[int('+')] = 0;
    priority[int('-')] = 0;
    priority[int('*')] = 1;
    priority[int('/')] = 1;
    priority[int('%')] = 1;
    priority[int('^')] = 2;
    priority[int('\\')] = 3;
    priority[int('=')] = -1;
    rightassoc[int('^')] = true;
    rightassoc[int('\\')] = true;
    std::string func, num, poly;
    std::vector<std::pair<token_type, std::string> > ans;
    token_type last = TOKEN_LEFTPAR;
    bool skip_next_matrix = false;
    for(char i : expr + ' ')
    {
        if(('A' <= i && i <= 'Z') || i == '_')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                ans.push_back({TOKEN_OP, "*"});
            ans.push_back({TOKEN_MATRIX, std::string() + i});
            if(skip_next_matrix)
                last = TOKEN_LEFTPAR;
            else
                last = TOKEN_MATRIX;
            skip_next_matrix = false;
        }
        else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '/' || i == '%')
        {
            if(i == '/' && poly.size())
            {
                poly.push_back('/');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(i == '(')
            {
                if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                    ans.push_back({TOKEN_OP, "*"});
                ans.push_back({TOKEN_LEFTPAR, ""});
            }
            else if(i == ')')
                ans.push_back({TOKEN_RIGHTPAR, ""});
            else
                ans.push_back({TOKEN_OP, std::string() + i});
            last = ans.back().first;
        }
        else if(i == '-')
        {
            if(poly.size())
            {
                poly.push_back('-');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)
            {
                ans.push_back({TOKEN_OP, "\\"});  // unary
            }
            else
            {
                ans.push_back({TOKEN_OP, "-"});
            }
            last = TOKEN_OP;
        }
        else if(('0' <= i && i <= '9') || i == '.')
        {
            if(poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            func = "";
            num.push_back(i);
            last = TOKEN_NUMBER;
        }
        else if('a' <= i && i <= 'z')
        {
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                ans.push_back({TOKEN_OP, "*"});
            func.push_back(i);
            last = TOKEN_FUNC;
        }
        else if(i == ',')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            ans.push_back({TOKEN_COMMA, ""});
            last = TOKEN_COMMA;
        }
        else if(i == '$')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)
                ans.push_back({TOKEN_OP, "*"});
            ans.push_back({TOKEN_DOLLAR, ""});
            last = TOKEN_DOLLAR;
        }
        else if(i == '"' || i == '\'')
        {
            if(poly.size())
            {
                if(poly[0] != i)
                {
                    ans.clear();
                    return ans;
                }
                ans.push_back({TOKEN_POLY, poly});
                poly = "";
                last = TOKEN_POLY;
            }
            else
            {
                poly = i;
                num = func = "";
            }
        }
        else
        {
            if(i == ' ' && poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
            {
                ans.push_back({TOKEN_FUNC, func});
                if(func == "let")
                    skip_next_matrix = true;
            }
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
        }
    }
    return ans;
}
<commit_msg>Более естественная расстановка умнежений<commit_after>#include "parser.h"

int priority[128];
bool rightassoc[128];

const std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)
{
    priority[int('+')] = 0;
    priority[int('-')] = 0;
    priority[int('*')] = 1;
    priority[int('/')] = 1;
    priority[int('%')] = 1;
    priority[int('^')] = 2;
    priority[int('\\')] = 3;
    priority[int('=')] = -1;
    rightassoc[int('^')] = true;
    rightassoc[int('\\')] = true;
    std::string func, num, poly;
    std::vector<std::pair<token_type, std::string> > ans;
    token_type last = TOKEN_LEFTPAR;
    bool skip_next_matrix = false;
    for(char i : expr + ' ')
    {
        if(('A' <= i && i <= 'Z') || i == '_')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
                ans.push_back({TOKEN_OP, "*"});
            ans.push_back({TOKEN_MATRIX, std::string() + i});
            if(skip_next_matrix)
                last = TOKEN_LEFTPAR;
            else
                last = TOKEN_MATRIX;
            skip_next_matrix = false;
        }
        else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '/' || i == '%')
        {
            if(i == '/' && poly.size())
            {
                poly.push_back('/');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(i == '(')
            {
                if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
                    ans.push_back({TOKEN_OP, "*"});
                ans.push_back({TOKEN_LEFTPAR, ""});
            }
            else if(i == ')')
                ans.push_back({TOKEN_RIGHTPAR, ""});
            else
                ans.push_back({TOKEN_OP, std::string() + i});
            last = ans.back().first;
        }
        else if(i == '-')
        {
            if(poly.size())
            {
                poly.push_back('-');
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)
            {
                ans.push_back({TOKEN_OP, "\\"});  // unary
            }
            else
            {
                ans.push_back({TOKEN_OP, "-"});
            }
            last = TOKEN_OP;
        }
        else if(('0' <= i && i <= '9') || i == '.')
        {
            if(poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            func = "";
            num.push_back(i);
            last = TOKEN_NUMBER;
        }
        else if('a' <= i && i <= 'z')
        {
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
                ans.push_back({TOKEN_OP, "*"});
            func.push_back(i);
            last = TOKEN_FUNC;
        }
        else if(i == ',')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            ans.push_back({TOKEN_COMMA, ""});
            last = TOKEN_COMMA;
        }
        else if(i == '$')
        {
            if(func.size())
                ans.push_back({TOKEN_FUNC, func});
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
            if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
                ans.push_back({TOKEN_OP, "*"});
            ans.push_back({TOKEN_DOLLAR, ""});
            last = TOKEN_DOLLAR;
        }
        else if(i == '"' || i == '\'')
        {
            if(poly.size())
            {
                if(poly[0] != i)
                {
                    ans.clear();
                    return ans;
                }
                ans.push_back({TOKEN_POLY, poly});
                poly = "";
                last = TOKEN_POLY;
            }
            else
            {
                if(func.size())
                    ans.push_back({TOKEN_FUNC, func});
                if(num.size())
                    ans.push_back({TOKEN_NUMBER, num});
                if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)
                    ans.push_back({TOKEN_OP, "*"});
                poly = i;
                num = func = "";
            }
        }
        else
        {
            if(i == ' ' && poly.size())
            {
                poly.push_back(i);
                continue;
            }
            if(func.size())
            {
                ans.push_back({TOKEN_FUNC, func});
                if(func == "let")
                    skip_next_matrix = true;
            }
            if(num.size())
                ans.push_back({TOKEN_NUMBER, num});
            num = func = "";
        }
    }
    return ans;
}
<|endoftext|>


<commit_before>#include "parser.hpp"

//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>

#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"

//////////
// Code //

// Creating a parse exception.
ParseException::ParseException(std::string type) {
    this->type = type;
}

// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
    return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}

//// Trying to specifically parse out a JSON object.
//JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
    //throw ParseException("JObject");
//}

//// Trying to specifically parse out a JSON array.
//JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    //if (str[0] == '[' && str[str.size() - 1] == ']') {
        //std::string useStr = str.substr(1, str.size() - 2);
        //if (useStr.compare("") == 0)
            //return JValue();

        //std::vector<JValue> jValues;
        //std::tuple<std::string, std::string> tup;
        //for (tup = untilChar(useStr, ','); std::get<0>(tup).compare("") != 0; tup = untilChar(std::get<1>(tup), ','))
            //jValues.push_back(parseJSON(stripWhitespace(std::get<0>(tup))));

        //return JValue(jValues);
    //}

    //throw ParseException("parseJSONArray");
//}

// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '[') {
        std::vector<JValue> values;
        while (true) {
            consumeWhitespace(ps);
            values.push_back(parseJSON(ps));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == ']')
                break;
            else if (c != ',')
                throw ParseException("parseJSONArray");
        }

        return JValue(values);
    }

    throw ParseException("parseJSONArray");
}

// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    std::string str;
    bool first = true;
    while (!ps.eof() && !isDelimiter(ps.peek())) {
        char c = ps.consume();

        if (first && c == '-') {
            str.push_back(c);
            first = false;
        } else if (('0' <= c && c <= '9') || c == '.')
            str.push_back(c);
        else
            throw ParseException("parseJSONNumber");
    }

    return JValue(stod(str));
}

// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    if (ps.peek() == '"') {
        ps.consume();

        std::string str;
        while (ps.peek() != '"') {
            char c = ps.consume();
            if (c == '\n')
                throw ParseException("parseJSONString");

            if (c == '\\') {
                char c2 = ps.consume();

                switch (c2) {
                case '"':
                    str.push_back('"');
                    break;
                case '\\':
                    str.push_back('\\');
                    break;
                case '/':
                    str.push_back('/');
                case 'b':
                    str.push_back('\b');
                    break;
                case 'f':
                    str.push_back('\f');
                    break;
                case 't':
                    str.push_back('\t');
                    break;
                case 'r':
                    str.push_back('\r');
                    break;
                case 'n':
                    str.push_back('\n');
                    break;
                default:
                    throw ParseException("parseJSONString");
                    break;
                }
            } else
                str.push_back(c);
        }

        ps.consume();
        return JValue(str);
    }

    throw ParseException("parseJSONString");
}

// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("true") == 0)
        return JValue(true);
    else if (str.compare("false") == 0)
        return JValue(false);

    throw ParseException("JSONBool");
}

// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("null") == 0)
        return JValue();
    throw ParseException("parseJSONNull");
}

// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
    int sl = ps.getLoc();
    try { return parseFn(ps); }
    catch (const ParseException& e) {
        ps.back(ps.getLoc() - sl);
        throw e;
    }
}

// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
    std::vector<JValue (*)(ParseStream&)> fns;
    fns.push_back(&parseJSONArray);
    fns.push_back(&parseJSONNumber);
    fns.push_back(&parseJSONString);
    fns.push_back(&parseJSONBool);
    fns.push_back(&parseJSONNull);

    for (auto it = fns.begin(); it != fns.end(); it++) {
        try { return attemptParse(ps, *it); }
        catch (const ParseException& e) { }
    }

    throw ParseException("parseJSON");
}

// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
    ParseStream ps(str);
    return parseJSON(ps);
}

// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
    std::string line, all;

    while (!stream.eof()) {
        std::getline(stream, line);
        all += line;
    }

    return parseJSON(all);
}
<commit_msg>Removed the old parseJSONArray function.<commit_after>#include "parser.hpp"

//////////////
// Includes //
#include <istream>
#include <string>
#include <vector>
#include <tuple>

#include "parsestream.hpp"
#include "streamutils.hpp"
#include "json.hpp"

//////////
// Code //

// Creating a parse exception.
ParseException::ParseException(std::string type) {
    this->type = type;
}

// Returning a string to refer to this exception.
const char* ParseException::what() const throw() {
    return ("Failed to parse a " + this->type + " piece of JSON.").c_str();
}

// Trying to specifically parse out a JSON object.
JValue parseJSONObject(ParseStream& ps) throw(ParseException) {
    throw ParseException("JObject");
}

// Trying to specifically parse out a JSON array.
JValue parseJSONArray(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    if (ps.consume() == '[') {
        std::vector<JValue> values;
        while (true) {
            consumeWhitespace(ps);
            values.push_back(parseJSON(ps));
            consumeWhitespace(ps);

            char c = ps.consume();
            if (c == ']')
                break;
            else if (c != ',')
                throw ParseException("parseJSONArray");
        }

        return JValue(values);
    }

    throw ParseException("parseJSONArray");
}

// Trying to specifically parse out a JSON number.
JValue parseJSONNumber(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);

    std::string str;
    bool first = true;
    while (!ps.eof() && !isDelimiter(ps.peek())) {
        char c = ps.consume();

        if (first && c == '-') {
            str.push_back(c);
            first = false;
        } else if (('0' <= c && c <= '9') || c == '.')
            str.push_back(c);
        else
            throw ParseException("parseJSONNumber");
    }

    return JValue(stod(str));
}

// Trying to specifically parse out a JSON string.
JValue parseJSONString(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    if (ps.peek() == '"') {
        ps.consume();

        std::string str;
        while (ps.peek() != '"') {
            char c = ps.consume();
            if (c == '\n')
                throw ParseException("parseJSONString");

            if (c == '\\') {
                char c2 = ps.consume();

                switch (c2) {
                case '"':
                    str.push_back('"');
                    break;
                case '\\':
                    str.push_back('\\');
                    break;
                case '/':
                    str.push_back('/');
                case 'b':
                    str.push_back('\b');
                    break;
                case 'f':
                    str.push_back('\f');
                    break;
                case 't':
                    str.push_back('\t');
                    break;
                case 'r':
                    str.push_back('\r');
                    break;
                case 'n':
                    str.push_back('\n');
                    break;
                default:
                    throw ParseException("parseJSONString");
                    break;
                }
            } else
                str.push_back(c);
        }

        ps.consume();
        return JValue(str);
    }

    throw ParseException("parseJSONString");
}

// Trying to specifically parse out a JSON boolean.
JValue parseJSONBool(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("true") == 0)
        return JValue(true);
    else if (str.compare("false") == 0)
        return JValue(false);

    throw ParseException("JSONBool");
}

// Trying to specifically parse out the null JSON value.
JValue parseJSONNull(ParseStream& ps) throw(ParseException) {
    consumeWhitespace(ps);
    std::string str;

    while (!ps.eof() && !isDelimiter(ps.peek()))
        str.push_back(ps.consume());

    if (str.compare("null") == 0)
        return JValue();
    throw ParseException("parseJSONNull");
}

// Attempting to perform a parse - and then backing up on an error.
JValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {
    int sl = ps.getLoc();
    try { return parseFn(ps); }
    catch (const ParseException& e) {
        ps.back(ps.getLoc() - sl);
        throw e;
    }
}

// Parsing out a block of JSON from a ParseStream.
JValue parseJSON(ParseStream& ps) throw(ParseException) {
    std::vector<JValue (*)(ParseStream&)> fns;
    fns.push_back(&parseJSONObject);
    fns.push_back(&parseJSONArray);
    fns.push_back(&parseJSONNumber);
    fns.push_back(&parseJSONString);
    fns.push_back(&parseJSONBool);
    fns.push_back(&parseJSONNull);

    for (auto it = fns.begin(); it != fns.end(); it++) {
        try { return attemptParse(ps, *it); }
        catch (const ParseException& e) { }
    }

    throw ParseException("parseJSON");
}

// Parsing out a block of JSON from a string.
JValue parseJSON(const std::string& str) throw(ParseException) {
    ParseStream ps(str);
    return parseJSON(ps);
}

// Parsing out a block of JSON from an istream.
JValue parseJSON(std::istream& stream) throw(ParseException) {
    std::string line, all;

    while (!stream.eof()) {
        std::getline(stream, line);
        all += line;
    }

    return parseJSON(all);
}
<|endoftext|>


<commit_before>/******************************
** Tsunagari Tile Engine     **
** player.cpp                **
** Copyright 2011 OmegaSDG   **
******************************/

#include <Gosu/Audio.hpp>
#include <Gosu/Input.hpp>

#include "area.h"
#include "entity.h"
#include "player.h"
#include "world.h"
#include "window.h"

Player::Player(Resourcer* rc, Area* area)
	: Entity(rc, area)
{
}

void Player::moveByTile(coord_t delta)
{
	bool changed = false;

	// TODO: use double array of directions
	// would make diagonals easier to handle
	if (delta.x > 0) {
		setPhase("right");
		changed = true;
	}
	else if (delta.x < 0) {
		setPhase("left");
		changed = true;
	}
	else if (delta.y > 0) {
		setPhase("down");
		changed = true;
	}
	else if (delta.y < 0) {
		setPhase("up");
		changed = true;
	}

	// Redraw the player if we change graphics.
	if (changed)
		redraw = true;

	// Left CTRL allows changing facing, but disallows movement.
	GameWindow* w = GameWindow::getWindow();
	if (w->input().down(Gosu::kbLeftControl))
		return;

	// Try to actually move.
	coord_t newCoord = getCoordsByTile();
	newCoord.x += delta.x;
	newCoord.y += delta.y;
	newCoord.z += delta.z;
	Area::Tile* dest = area->getTile(newCoord);
	if ((dest->flags       & Area::player_nowalk) != 0 ||
	    (dest->type->flags & Area::player_nowalk) != 0) {
		// The tile we're trying to move onto is set as player_nowalk.
		// Stop here.
		return;
	}

	Entity::moveByTile(delta);
}

void Player::postMove()
{
	SampleRef step_sound = getSound("step");
	if (step_sound)
		step_sound->play(1, 1, 0);

	coord_t coord = getCoordsByTile();
	Area::Tile* dest = area->getTile(coord);
	Area::Door* door = dest->door;
	if (door)
		World::getWorld()->loadArea(door->area, door->coord);
}

<commit_msg>change access to door, realizing its a scoped_ptr<commit_after>/******************************
** Tsunagari Tile Engine     **
** player.cpp                **
** Copyright 2011 OmegaSDG   **
******************************/

#include <Gosu/Audio.hpp>
#include <Gosu/Input.hpp>

#include "area.h"
#include "entity.h"
#include "player.h"
#include "world.h"
#include "window.h"

Player::Player(Resourcer* rc, Area* area)
	: Entity(rc, area)
{
}

void Player::moveByTile(coord_t delta)
{
	bool changed = false;

	// TODO: use double array of directions
	// would make diagonals easier to handle
	if (delta.x > 0) {
		setPhase("right");
		changed = true;
	}
	else if (delta.x < 0) {
		setPhase("left");
		changed = true;
	}
	else if (delta.y > 0) {
		setPhase("down");
		changed = true;
	}
	else if (delta.y < 0) {
		setPhase("up");
		changed = true;
	}

	// Redraw the player if we change graphics.
	if (changed)
		redraw = true;

	// Left CTRL allows changing facing, but disallows movement.
	GameWindow* w = GameWindow::getWindow();
	if (w->input().down(Gosu::kbLeftControl))
		return;

	// Try to actually move.
	coord_t newCoord = getCoordsByTile();
	newCoord.x += delta.x;
	newCoord.y += delta.y;
	newCoord.z += delta.z;
	Area::Tile* dest = area->getTile(newCoord);
	if ((dest->flags       & Area::player_nowalk) != 0 ||
	    (dest->type->flags & Area::player_nowalk) != 0) {
		// The tile we're trying to move onto is set as player_nowalk.
		// Stop here.
		return;
	}

	Entity::moveByTile(delta);
}

void Player::postMove()
{
	SampleRef step_sound = getSound("step");
	if (step_sound)
		step_sound->play(1, 1, 0);

	coord_t coord = getCoordsByTile();
	Area::Tile* dest = area->getTile(coord);
	Area::Door* door = dest->door.get();
	if (door)
		World::getWorld()->loadArea(door->area, door->coord);
}

<|endoftext|>