<commit_before><commit_msg>Apparently missing "nPos <"<commit_after><|endoftext|>


<commit_before>#include "CodeDiscoverWindow.h"

#include <QScrollArea>
#include <QGridLayout>
#include <QCheckBox>
#include <QPushButton>
#include <QFileDialog>
#include <QDebug>

namespace QtcUtilities {
namespace Internal {
namespace CodeDiscover {

CodeDiscoverWindow::CodeDiscoverWindow (ClassFlags flags, QWidget *parent,
                                        Qt::WindowFlags f)
  : QWidget (parent, f),
  imageLabel_ (nullptr)
{
  auto flagsLayout = new QVBoxLayout;
  flagsLayout->addWidget (new QLabel (tr ("Settings")));
#define ADD_CHECKBOX(FLAG, TITLE) flagsLayout->addWidget (flags_.insert (FLAG, new QCheckBox (tr (TITLE))).value ());
  ADD_CHECKBOX (ShowMembers, "Show members");
  ADD_CHECKBOX (ShowMethods, "Show methods");
  ADD_CHECKBOX (ShowPublic, "Show public");
  ADD_CHECKBOX (ShowProtected, "Show protected");
  ADD_CHECKBOX (ShowPrivate, "Show private");
  ADD_CHECKBOX (ShowBase, "Show base classes");
  ADD_CHECKBOX (ShowDerived, "Show derived classes");
  ADD_CHECKBOX (ShowDependencies, "Show dependencies");
  ADD_CHECKBOX (ShowOnlyHierarchyDependencies, "Show only base and derived dependencies");
  ADD_CHECKBOX (ShowDependsDetails, "Show dependencies details");
  ADD_CHECKBOX (ShowHierarchyDetails, "Show base and derived details");
  ADD_CHECKBOX (ShowDetailsFromSameProject, "Show same project symbols details");
  ADD_CHECKBOX (ShowNested, "Show nested classes");
#undef ADD_CHECKBOX
  flagsLayout->addStretch (1);
  auto saveButton = new QPushButton (tr ("Save to file..."));
  connect (saveButton, &QPushButton::clicked, this, &CodeDiscoverWindow::saveToFile);
  flagsLayout->addWidget (saveButton);

  auto layout = new QGridLayout;

  imageLabel_ = new QLabel;
  imageLabel_->setBackgroundRole (QPalette::Base);
  imageLabel_->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
  imageLabel_->setScaledContents (true);

  auto row = 0;
  auto *scrollArea = new QScrollArea;
  scrollArea->setBackgroundRole (QPalette::Dark);
  scrollArea->setWidget (imageLabel_);
  layout->addLayout (flagsLayout, row, 0);
  layout->addWidget (scrollArea, row, 1);

  setLayout (layout);

  for (auto flag: flags_.keys ()) {
    auto *check = flags_[flag];
    if (flags & flag) {
      check->setChecked (true);
    }
    connect (check, &QCheckBox::clicked, this, &CodeDiscoverWindow::updateFlags);
  }
}

void CodeDiscoverWindow::setImage (const QPixmap &image)
{
  imageLabel_->setPixmap (image);
  imageLabel_->adjustSize ();
}

void CodeDiscoverWindow::updateFlags ()
{
  auto flags = ShowNothing;
  for (auto flag: flags_.keys ()) {
    if (flags_[flag]->isChecked ()) {
      flags = ClassFlags (flags | flag);
    }
  }
  emit flagsChanged (flags);
}

void CodeDiscoverWindow::saveToFile ()
{
  QString extension = QStringLiteral (".png");
  auto file = QFileDialog::getSaveFileName (this, {}, {}, QStringLiteral ("*.") + extension);
  if (!file.isEmpty ()) {
    if (!file.endsWith (extension)) {
      file += extension;
    }
    imageLabel_->pixmap ()->save (file, "PNG");
  }
}

} // namespace CodeDiscover
} // namespace Internal
} // namespace QtcUtilities
<commit_msg>Added image saving safety checks.<commit_after>#include "CodeDiscoverWindow.h"

#include <QScrollArea>
#include <QGridLayout>
#include <QCheckBox>
#include <QPushButton>
#include <QFileDialog>
#include <QDebug>

namespace QtcUtilities {
namespace Internal {
namespace CodeDiscover {

CodeDiscoverWindow::CodeDiscoverWindow (ClassFlags flags, QWidget *parent,
                                        Qt::WindowFlags f)
  : QWidget (parent, f),
  imageLabel_ (nullptr)
{
  auto flagsLayout = new QVBoxLayout;
  flagsLayout->addWidget (new QLabel (tr ("Settings")));
#define ADD_CHECKBOX(FLAG, TITLE) flagsLayout->addWidget (flags_.insert (FLAG, new QCheckBox (tr (TITLE))).value ());
  ADD_CHECKBOX (ShowMembers, "Show members");
  ADD_CHECKBOX (ShowMethods, "Show methods");
  ADD_CHECKBOX (ShowPublic, "Show public");
  ADD_CHECKBOX (ShowProtected, "Show protected");
  ADD_CHECKBOX (ShowPrivate, "Show private");
  ADD_CHECKBOX (ShowBase, "Show base classes");
  ADD_CHECKBOX (ShowDerived, "Show derived classes");
  ADD_CHECKBOX (ShowDependencies, "Show dependencies");
  ADD_CHECKBOX (ShowOnlyHierarchyDependencies, "Show only base and derived dependencies");
  ADD_CHECKBOX (ShowDependsDetails, "Show dependencies details");
  ADD_CHECKBOX (ShowHierarchyDetails, "Show base and derived details");
  ADD_CHECKBOX (ShowDetailsFromSameProject, "Show same project symbols details");
  ADD_CHECKBOX (ShowNested, "Show nested classes");
#undef ADD_CHECKBOX
  flagsLayout->addStretch (1);
  auto saveButton = new QPushButton (tr ("Save to file..."));
  connect (saveButton, &QPushButton::clicked, this, &CodeDiscoverWindow::saveToFile);
  flagsLayout->addWidget (saveButton);

  auto layout = new QGridLayout;

  imageLabel_ = new QLabel;
  imageLabel_->setBackgroundRole (QPalette::Base);
  imageLabel_->setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored);
  imageLabel_->setScaledContents (true);

  auto row = 0;
  auto *scrollArea = new QScrollArea;
  scrollArea->setBackgroundRole (QPalette::Dark);
  scrollArea->setWidget (imageLabel_);
  layout->addLayout (flagsLayout, row, 0);
  layout->addWidget (scrollArea, row, 1);

  setLayout (layout);

  for (auto flag: flags_.keys ()) {
    auto *check = flags_[flag];
    if (flags & flag) {
      check->setChecked (true);
    }
    connect (check, &QCheckBox::clicked, this, &CodeDiscoverWindow::updateFlags);
  }
}

void CodeDiscoverWindow::setImage (const QPixmap &image)
{
  imageLabel_->setPixmap (image);
  imageLabel_->adjustSize ();
}

void CodeDiscoverWindow::updateFlags ()
{
  auto flags = ShowNothing;
  for (auto flag: flags_.keys ()) {
    if (flags_[flag]->isChecked ()) {
      flags = ClassFlags (flags | flag);
    }
  }
  emit flagsChanged (flags);
}

void CodeDiscoverWindow::saveToFile ()
{
  const auto *pixmap = imageLabel_->pixmap ();
  if (!pixmap || pixmap->isNull ()) {
    return;
  }
  QString extension = QStringLiteral (".png");
  auto file = QFileDialog::getSaveFileName (this, {}, {}, QStringLiteral ("*") + extension);
  if (!file.isEmpty ()) {
    if (!file.endsWith (extension)) {
      file += extension;
    }
    pixmap->save (file, "PNG");
  }
}

} // namespace CodeDiscover
} // namespace Internal
} // namespace QtcUtilities
<|endoftext|>


<commit_before>#include "frustum.h"
#include "misc.h"

Frustum:: Frustum()
{

}

void Frustum::InitProgram()
{
	mProgram= CreateGPUProgram("res/shader/WhiteColor.vs", "res/shader/WhiteColor.fs");
	mPLocation= glGetAttribLocation(mProgram, "pos");

	mMLocation = glGetUniformLocation(mProgram, "M");
	mVLocation = glGetUniformLocation(mProgram, "V");
	mPLocation = glGetUniformLocation(mProgram, "P");
}

void Frustum::InitPerspective(float fov,float aspect ,float zNear,float zFar)
{
	//near
	float halfFov = 22.5f;
	float randianHalfFov = 3.14f * halfFov/ 180.0f;
	float tanHalFov = sinf(randianHalfFov)/cosf(randianHalfFov);
	float yNear  = tanHalFov *zNear;
	float xNear = yNear*aspect;

	//far
	float yFar = tanHalFov *zFar;
	float xFar = yFar*aspect;

	float vertexs[24] = {
		-xNear,-yNear,-zNear,
		xNear,-yNear,-zNear,
		xNear,yNear,-zNear,
		-xNear,yNear,-zNear,

		-xFar,-yFar,-zFar,
		xFar,-yFar,-zFar,
		xFar,yFar,-zFar,
		-xFar,yFar,-zFar,
	};

	mVBO = CreateBufferObject(GL_ARRAY_BUFFER,sizeof(float)*24,GL_STATIC_DRAW,vertexs);
	unsigned int indexes[] = {
		0,1,1,2,2,3,3,0, //near plane
		4,5,5,6,6,7,7,4, //far plane
		0,4,3,7,2,6,1,5, //connect
	};
	mIBO = CreateBufferObject(GL_ELEMENT_ARRAY_BUFFER,sizeof(unsigned int)*24,GL_STATIC_DRAW,indexes);
}

void Frustum::Draw(float *M,float* V,float *P)
{
	glUseProgram(mProgram);
	glUniformMatrix4fv(mMLocation, 1, GL_FALSE, M);
	glUniformMatrix4fv(mVLocation, 1, GL_FALSE, V);
	glUniformMatrix4fv(mPLocation, 1, GL_FALSE, P);

	glBindBuffer(GL_ARRAY_BUFFER, mVBO);
	glEnableVertexAttribArray(mPLocation);
	glVertexAttribPointer(mPLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, (void*)0);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBO);
	glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glUseProgram(0);
}

<commit_msg>fix again<commit_after>#include "frustum.h"
#include "misc.h"

Frustum:: Frustum()
{

}

void Frustum::InitProgram()
{
	mProgram= CreateGPUProgram("res/shader/WhiteColor.vs", "res/shader/WhiteColor.fs");
	mPLocation= glGetAttribLocation(mProgram, "pos");

	mMLocation = glGetUniformLocation(mProgram, "M");
	mVLocation = glGetUniformLocation(mProgram, "V");
	mPLocation = glGetUniformLocation(mProgram, "P");
}

void Frustum::InitPerspective(float fov,float aspect ,float zNear,float zFar)
{
	//near
	float halfFov = 22.5f;
	float randianHalfFov = 3.14f * halfFov/ 180.0f;
	float tanHalFov = sinf(randianHalfFov)/cosf(randianHalfFov);
	float yNear  = tanHalFov *zNear;
	float xNear = yNear*aspect;

	//far
	float yFar = tanHalFov *zFar;
	float xFar = yFar*aspect;

	float vertexs[24] = {
		-xNear,-yNear,-zNear,
		xNear,-yNear,-zNear,
		xNear,yNear,-zNear,
		-xNear,yNear,-zNear,

		-xFar,-yFar,-zFar,
		xFar,-yFar,-zFar,
		xFar,yFar,-zFar,
		-xFar,yFar,-zFar,
	};

	mVBO = CreateBufferObject(GL_ARRAY_BUFFER,sizeof(float)*24,GL_STATIC_DRAW,vertexs);
	unsigned int indexes[] = {
		0,1,1,2,2,3,3,0, //near plane
		4,5,5,6,6,7,7,4, //far plane
		0,4,3,7,2,6,1,5, //connect
	};
	mIBO = CreateBufferObject(GL_ELEMENT_ARRAY_BUFFER,sizeof(unsigned int)*24,GL_STATIC_DRAW,indexes);
}

void Frustum::Draw(float *M,float* V,float *P)
{
	glUseProgram(mProgram);
	glUniformMatrix4fv(mMLocation, 1, GL_FALSE, M);
	glUniformMatrix4fv(mVLocation, 1, GL_FALSE, V);
	glUniformMatrix4fv(mPLocation, 1, GL_FALSE, P);

	glBindBuffer(GL_ARRAY_BUFFER, mVBO);
	glEnableVertexAttribArray(mPosLocation);
	glVertexAttribPointer(mPosLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, (void*)0);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBO);
	glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	glUseProgram(0);
}

<|endoftext|>


<commit_before>#include "Blinking.h"

Blinking::Blinking(int sensorPin) : lightsensorPin(sensorPin) {}

void Blinking::listen(){
	detectStartCode();
  synchronise();
	getHeader();
	getDatas();
}

void Blinking::detectStartCode(){
  bool start = false;
  long t;
  int lightValue = lightLevel; //Will be changed to adapt to differents brightnesses

  while(!start){
    if(micros() - time2 >  1000000.0/480.0){
      time2 = micros();
      sensorValue = analogRead(lightsensorPin);
      //Serial.println(sensorValue);
      if (sensorValue > lightValue){
        begining = micros();
        time = begining;
        lambdaAcc += lambda;
        int count = 1;
        while (count < 3){
          t = micros();
          if( t - begining >  lambdaAcc){
            time = t;
            bitRead.value = detectBit();
            lambdaAcc += lambda;
            //Serial.println(count); //For debugging
            //Serial.println(bitRead); //For debugging
            //If we detect a "1" and there should be a "0", we break out of the loop and restart reading start code from the begenning.
            //Needs more work because we can "miss" the start code
            //Maybe store the "startCodeLenght" last values and compare thoses with the start code, to avoid missing it.
            if (startCode[count] == 0 && bitRead.value == 1){
              begining = 0;
              lambdaAcc = 0;
              break;
            }
            else if (startCode[count] == 1 && bitRead.value == 0){
              begining = 0;
              lambdaAcc = 0;
              break;
            }
            //If what we detect is what we should detect, we continue
            else{
              count++;
            }
          }
        }

        if (count == 3) // Will be changed. We need to compare with the size of the Start Code.
          start = true;
      }
    }
  }
 Serial.println("Start code detected");
 time2 = micros();
}

void Blinking::synchronise(){
  long sum = 0;
  double a = 0;
  double mean;
  long deb = micros();
  long time = millis();
  long t;
  int currentValue;
  int b = 0;
  Bit temp[1];

  readValues(temp, 1, 0);

  while(a < 60){
    currentValue = b;
    while(b == currentValue){
      t = millis();
      if (t - time >  1){
        time = t;
        b = analogRead(lightsensorPin) > lightLevel ? 1 : 0;
      }
    }
    a+=1;
  }

  sum = (micros()-deb);

  /*mean = sum/(a/(sum/1000.0));
  frequency = 1000.0/mean;*/
  frequency = 60.0 / (sum/1000000.0);
  //frequency = 59.559261;
  lambda = 1000000.0/frequency;

  lambdaAcc = lambda;
  begining = micros();

  /*Serial.println("Elapsed time");
  Serial.println(millis()-deb);
  Serial.println("Sum");
  Serial.println(sum);
  Serial.println("Frequency");
  Serial.println(frequency);*/

}

/*
 * Header Composition
 * Data Length = 8 bits; 0000 0000 = 0; 1111 1111 = 255 //Number of groups of data
 * Data Size = 4 bits; 0000 = 0 Byte; 1111 = 15 Bytes // We can change 0000 to be 1 to improve the range
 */
void Blinking::getHeader(){
    Bit buf[8];
    //begining = begining + (begining - time2);

    readValues(buf, 8, 0);
    dataLen = binToDec(buf);

    readValues(buf, 4, 4);
    dataSize = binToDec2(buf, 4);

    Serial.println("Header Read");//For debugging
    Serial.println(dataLen);
    Serial.println(dataSize);
}

/*
 * Get the data transmitted
 */
void Blinking::getDatas(){
  int i = 0;
  int lightValue = lightLevel;

  readValues(datas, dataLen * dataSize * 8, 0);
  Serial.println("Datas Read");

  for (i = 0; i < dataLen*dataSize*8; i++){//For debbugging
    Serial.print(datas[i].value);
  }
}

int Blinking::binToDec(Bit data[8]){
  int number = 0;
  int count = 0;
  for(int i = 7; i >= 0; i--, count++){
    number += data[i].value*power(2, count);
  }
  return number;
}

int Blinking::binToDec2(Bit data[8], int s){
  int number = 0;
  int count = 0;
  for(int i = 7; i >= s; i--, count++){
    number += data[i].value*power(2, count);
  }
  return number;
}

int Blinking::power(int a, int b){
  int result = 1;
  for(int i = 0; i < b; i++){
    result *= a;
  }
  return result;
}

int Blinking::detectBit(){
  boolean read = false;
  int sum = 0;
  long timer = micros();
  long t;
  float div = 5.0;

  for(int i = 0, count = 0, s = 2; i < 3; i++){
	while (!read){
		t = micros();
		if(t - timer > s*lambda/div){
			timer = t;
			sum = analogRead(lightsensorPin) > lightLevel ? sum + 1 : sum;
			read = true;
			s = 1;
		}
	}
	read = false;
  }

  if (sum  > 1)
    return 1;
  else
    return 0;
}

void Blinking::readValues(Bit* buf, int nb, int dec){
  int count = 0;
  long t;
  long time = 0;
  while (count < nb){
      t = micros();
      if (t - begining >  lambdaAcc){
        buf[count+dec].value = detectBit();
        time = t;
        lambdaAcc += lambda;
        count++;
     }
    }
}
<commit_msg>Fixed synchro Stil some problems about the detection of the frenquency of the smartphone probably due to the smartphone himself<commit_after>#include "Blinking.h"

Blinking::Blinking(int sensorPin) : lightsensorPin(sensorPin) {}

void Blinking::listen(){
	detectStartCode();
  synchronise();
	getHeader();
	getDatas();
}

void Blinking::detectStartCode(){
  bool start = false;
  long t;
  int lightValue = lightLevel; //Will be changed to adapt to differents brightnesses

  while(!start){
    if(micros() - time2 >  1000000.0/1000.0){
      time2 = micros();
      sensorValue = analogRead(lightsensorPin);
      //Serial.println(sensorValue);
      if (sensorValue > lightValue){
        begining = micros();
        time = begining;
        lambdaAcc += lambda;
        int count = 1;
        while (count < 3){
          t = micros();
          if( t - begining >  lambdaAcc){
            time = t;
            bitRead.value = detectBit();
            lambdaAcc += lambda;
            //Serial.println(count); //For debugging
            //Serial.println(bitRead); //For debugging
            //If we detect a "1" and there should be a "0", we break out of the loop and restart reading start code from the begenning.
            //Needs more work because we can "miss" the start code
            //Maybe store the "startCodeLenght" last values and compare thoses with the start code, to avoid missing it.
            if (startCode[count] == 0 && bitRead.value == 1){
              begining = 0;
              lambdaAcc = 0;
              break;
            }
            else if (startCode[count] == 1 && bitRead.value == 0){
              begining = 0;
              lambdaAcc = 0;
              break;
            }
            //If what we detect is what we should detect, we continue
            else{
              count++;
            }
          }
        }

        if (count == 3) // Will be changed. We need to compare with the size of the Start Code.
          start = true;
      }
    }
  }
 Serial.println("Start code detected");
}

void Blinking::synchronise(){
  int sampleSize = 60;
  long sum = 0;
  double a = 1;
  //double mean;
  long deb;
  long time = millis();
  long t;
  int currentValue = 0;
  int b = 1;
  //Bit temp[1];

  while (b != currentValue){
      t = millis();
      if (t - time >  1){
        time = t;
        b = analogRead(lightsensorPin) > lightLevel ? 1 : 0;
      }
  }

  //deb = micros();
  deb = millis();
  //readValues(temp, 1, 0);
  //delay(4);

  while(a <= sampleSize){
    currentValue = b;
    while(b == currentValue){
      t = millis();
      if (t - time >  1){
        time = t;
        b = analogRead(lightsensorPin) > lightLevel ? 1 : 0;
      }
    }
    a+=1;
  }

  //sum = (micros()-deb);
  sum = (millis()-deb);

  /*mean = sum/(a/(sum/1000.0));
  frequency = 1000.0/mean;*/
  //frequency = (double)sampleSize / (sum/1000000.0);
  frequency = (double)sampleSize / (sum/1000.0);
  //frequency = 59.559261;
  lambda = 1000000.0/frequency;

  begining = micros() - lambda;
  lambdaAcc = lambda;

  /*Serial.println("Elapsed time");
  Serial.println(micros()-deb);
  Serial.println("Sum");
  Serial.println(sum);*/
  Serial.println("Frequency");
  Serial.println(frequency);

}

/*
 * Header Composition
 * Data Length = 8 bits; 0000 0000 = 0; 1111 1111 = 255 //Number of groups of data
 * Data Size = 4 bits; 0000 = 0 Byte; 1111 = 15 Bytes // We can change 0000 to be 1 to improve the range
 */
void Blinking::getHeader(){
    Bit buf[8];
    //begining = begining + (begining - time2);

    readValues(buf, 8, 0);
    dataLen = binToDec(buf);

    readValues(buf, 4, 4);
    dataSize = binToDec2(buf, 4);

    Serial.println("Header Read");//For debugging
    Serial.println(dataLen);
    Serial.println(dataSize);
}

/*
 * Get the data transmitted
 */
void Blinking::getDatas(){
  int i = 0;
  int lightValue = lightLevel;

  readValues(datas, dataLen * dataSize * 8, 0);
  Serial.println("Datas Read");

  for (i = 0; i < dataLen*dataSize*8; i++){//For debbugging
    Serial.print(datas[i].value);
  }
}

int Blinking::binToDec(Bit data[8]){
  int number = 0;
  int count = 0;
  for(int i = 7; i >= 0; i--, count++){
    number += data[i].value*power(2, count);
  }
  return number;
}

int Blinking::binToDec2(Bit data[8], int s){
  int number = 0;
  int count = 0;
  for(int i = 7; i >= s; i--, count++){
    number += data[i].value*power(2, count);
  }
  return number;
}

int Blinking::power(int a, int b){
  int result = 1;
  for(int i = 0; i < b; i++){
    result *= a;
  }
  return result;
}

int Blinking::detectBit(){
  boolean read = false;
  int sum = 0;
  long timer = micros();
  long t;
  float div = 5.0;

  for(int i = 0, count = 0, s = 2; i < 3; i++){
	while (!read){
		t = micros();
		if(t - timer > s*lambda/div){
			timer = t;
			sum = analogRead(lightsensorPin) > lightLevel ? sum + 1 : sum;
			read = true;
			s = 1;
		}
	}
	read = false;
  }

  if (sum  > 1)
    return 1;
  else
    return 0;
}

void Blinking::readValues(Bit* buf, int nb, int dec){
  int count = 0;
  long t;
  long time = 0;
  while (count < nb){
      t = micros();
      if (t - begining >  lambdaAcc){
        buf[count+dec].value = detectBit();
        time = t;
        lambdaAcc += lambda;
        count++;
     }
  }
}
<|endoftext|>


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

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "simple.kv"

namespace dsn {
    namespace replication {
        namespace application {

            simple_kv_service_impl::simple_kv_service_impl(replica* replica)
                : simple_kv_service(replica)
            {
                _test_file_learning = false;
            }

            // RPC_SIMPLE_KV_READ
            void simple_kv_service_impl::on_read(const std::string& key, ::dsn::rpc_replier<std::string>& reply)
            {
                zauto_lock l(_lock);

                auto it = _store.find(key);
                if (it == _store.end())
                {
                    reply("");
                }
                else
                {
                    dinfo("read %s, decree = %lld\n", it->second.c_str(), last_committed_decree());
                    reply(it->second);
                }
            }

            // RPC_SIMPLE_KV_WRITE
            void simple_kv_service_impl::on_write(const kv_pair& pr, ::dsn::rpc_replier<int32_t>& reply)
            {
                zauto_lock l(_lock);
                _store[pr.key] = pr.value;
                ++_last_committed_decree;

                dinfo("write %s, decree = %lld\n", pr.value.c_str(), last_committed_decree());
                reply(0);
            }

            // RPC_SIMPLE_KV_APPEND
            void simple_kv_service_impl::on_append(const kv_pair& pr, ::dsn::rpc_replier<int32_t>& reply)
            {
                zauto_lock l(_lock);
                auto it = _store.find(pr.key);
                if (it != _store.end())
                    it->second.append(pr.value);
                else
                    _store[pr.key] = pr.value;
                ++_last_committed_decree;

                dinfo("append %s, decree = %lld\n", pr.value.c_str(), last_committed_decree());
                reply(0);
            }

            int simple_kv_service_impl::open(bool create_new)
            {
                zauto_lock l(_lock);
                if (create_new)
                {
                    boost::filesystem::remove_all(data_dir());
                    boost::filesystem::create_directory(data_dir());
                }
                else
                {
                    recover();
                }
                return 0;
            }

            int simple_kv_service_impl::close(bool clear_state)
            {
                zauto_lock l(_lock);
                if (clear_state)
                {
                    boost::filesystem::remove_all(data_dir());
                }
                return 0;
            }

            // checkpoint related
            void simple_kv_service_impl::recover()
            {
                zauto_lock l(_lock);

                _store.clear();

                decree maxVersion = 0;
                std::string name;
                boost::filesystem::directory_iterator endtr;
                for (boost::filesystem::directory_iterator it(data_dir());
                    it != endtr;
                    ++it)
                {
                    auto s = it->path().filename().string();
                    if (s.substr(0, strlen("checkpoint.")) != std::string("checkpoint."))
                        continue;

                    decree version = static_cast<decree>(atoll(s.substr(strlen("checkpoint.")).c_str()));
                    if (version > maxVersion)
                    {
                        maxVersion = version;
                        name = data_dir() + "/" + s;
                    }
                }

                if (maxVersion > 0)
                {
                    recover(name, maxVersion);
                }
            }

            void simple_kv_service_impl::recover(const std::string& name, decree version)
            {
                zauto_lock l(_lock);

                std::ifstream is(name.c_str(), std::ios::binary);
                if (!is.is_open())
                    return;

                _store.clear();

                uint64_t count;
                int magic;

                is.read((char*)&count, sizeof(count));
                is.read((char*)&magic, sizeof(magic));
                dassert(magic == 0xdeadbeef, "invalid checkpoint");

                for (uint64_t i = 0; i < count; i++)
                {
                    std::string key;
                    std::string value;

                    uint32_t sz;
                    is.read((char*)&sz, (uint32_t)sizeof(sz));
                    key.resize(sz);

                    is.read((char*)&key[0], sz);

                    is.read((char*)&sz, (uint32_t)sizeof(sz));
                    value.resize(sz);

                    is.read((char*)&value[0], sz);

                    _store[key] = value;
                }

                _last_durable_decree = _last_committed_decree = version;
            }

            int simple_kv_service_impl::flush(bool force)
            {
                zauto_lock l(_lock);

                if (last_committed_decree() == last_durable_decree())
                {
                    return 0;
                }

                // TODO: should use async write instead
                char name[256];
                sprintf(name, "%s/checkpoint.%lld", data_dir().c_str(),
                        static_cast<long long int>(last_committed_decree()));
                std::ofstream os(name, std::ios::binary);

                uint64_t count = (uint64_t)_store.size();
                int magic = 0xdeadbeef;

                os.write((const char*)&count, (uint32_t)sizeof(count));
                os.write((const char*)&magic, (uint32_t)sizeof(magic));

                for (auto it = _store.begin(); it != _store.end(); it++)
                {
                    const std::string& k = it->first;
                    uint32_t sz = (uint32_t)k.length();

                    os.write((const char*)&sz, (uint32_t)sizeof(sz));
                    os.write((const char*)&k[0], sz);

                    const std::string& v = it->second;
                    sz = (uint32_t)v.length();

                    os.write((const char*)&sz, (uint32_t)sizeof(sz));
                    os.write((const char*)&v[0], sz);
                }

                _last_durable_decree = last_committed_decree();
                return 0;
            }

            // helper routines to accelerate learning
            int simple_kv_service_impl::get_learn_state(decree start, const blob& learn_req, __out_param learn_state& state)
            {
                ::dsn::binary_writer writer;

                zauto_lock l(_lock);

                int magic = 0xdeadbeef;
                writer.write(magic);

                writer.write(_last_committed_decree.load());

                dassert(_last_committed_decree >= 0, "");

                uint64_t count = static_cast<uint64_t>(_store.size());
                writer.write(count);

                for (auto it = _store.begin(); it != _store.end(); it++)
                {
                    writer.write(it->first);
                    writer.write(it->second);
                }

                auto bb = writer.get_buffer();
                auto buf = bb.buffer();

                state.meta.push_back(blob(buf, static_cast<int>(bb.data() - bb.buffer().get()), bb.length()));

                // Test Sample
                if (_test_file_learning)
                {
                    std::stringstream ss;
                    ss << dsn_random32(0, 10000);

                    auto learn_test_file = data_dir() + "/test_learning_" + ss.str() + ".txt";
                    state.files.push_back(learn_test_file);

                    std::ofstream fout(learn_test_file.c_str());
                    fout << "DEADBEEF" << std::endl;
                    fout.close();
                }

                return 0;
            }

            int simple_kv_service_impl::apply_learn_state(learn_state& state)
            {
                blob bb((const char*)state.meta[0].data(), 0, state.meta[0].length());

                binary_reader reader(bb);

                zauto_lock l(_lock);

                _store.clear();

                int magic;
                reader.read(magic);

                dassert(magic == 0xdeadbeef, "");

                decree decree;
                reader.read(decree);

                dassert(decree >= 0, "");

                uint64_t count;
                reader.read(count);

                for (uint64_t i = 0; i < count; i++)
                {
                    std::string key, value;
                    reader.read(key);
                    reader.read(value);
                    _store[key] = value;
                }

                _last_committed_decree = decree;
                _last_durable_decree = 0;

                flush(true);

                bool ret = true;
                if (_test_file_learning)
                {
                    dassert(state.files.size() == 1, "");
                    std::string fn = learn_dir() + "/" + state.files[0];
                    ret = boost::filesystem::exists(fn);
                    if (ret)
                    {
                        std::string s;
                        std::ifstream fin(fn.c_str());

                        getline(fin, s);
                        fin.close();

                        ret = (s == "DEADBEEF");
                    }
                    else
                    {
                        dassert(false, "learning file is missing");
                    }
                }

                if (ret) return 0;
                else return ERR_LEARN_FILE_FALED.get();
            }

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

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "simple.kv"

namespace dsn {
    namespace replication {
        namespace application {

            simple_kv_service_impl::simple_kv_service_impl(replica* replica)
                : simple_kv_service(replica)
            {
                _test_file_learning = false;
            }

            // RPC_SIMPLE_KV_READ
            void simple_kv_service_impl::on_read(const std::string& key, ::dsn::rpc_replier<std::string>& reply)
            {
                zauto_lock l(_lock);

                auto it = _store.find(key);
                if (it == _store.end())
                {
                    reply("");
                }
                else
                {
                    dinfo("read %s, decree = %lld\n", it->second.c_str(), last_committed_decree());
                    reply(it->second);
                }
            }

            // RPC_SIMPLE_KV_WRITE
            void simple_kv_service_impl::on_write(const kv_pair& pr, ::dsn::rpc_replier<int32_t>& reply)
            {
                zauto_lock l(_lock);
                _store[pr.key] = pr.value;
                ++_last_committed_decree;

                dinfo("write %s, decree = %lld\n", pr.key.c_str(), last_committed_decree());
                reply(0);
            }

            // RPC_SIMPLE_KV_APPEND
            void simple_kv_service_impl::on_append(const kv_pair& pr, ::dsn::rpc_replier<int32_t>& reply)
            {
                zauto_lock l(_lock);
                auto it = _store.find(pr.key);
                if (it != _store.end())
                    it->second.append(pr.value);
                else
                    _store[pr.key] = pr.value;
                ++_last_committed_decree;

                dinfo("append %s, decree = %lld\n", pr.key.c_str(), last_committed_decree());
                reply(0);
            }

            int simple_kv_service_impl::open(bool create_new)
            {
                zauto_lock l(_lock);
                if (create_new)
                {
                    boost::filesystem::remove_all(data_dir());
                    boost::filesystem::create_directory(data_dir());
                }
                else
                {
                    recover();
                }
                return 0;
            }

            int simple_kv_service_impl::close(bool clear_state)
            {
                zauto_lock l(_lock);
                if (clear_state)
                {
                    boost::filesystem::remove_all(data_dir());
                }
                return 0;
            }

            // checkpoint related
            void simple_kv_service_impl::recover()
            {
                zauto_lock l(_lock);

                _store.clear();

                decree maxVersion = 0;
                std::string name;
                boost::filesystem::directory_iterator endtr;
                for (boost::filesystem::directory_iterator it(data_dir());
                    it != endtr;
                    ++it)
                {
                    auto s = it->path().filename().string();
                    if (s.substr(0, strlen("checkpoint.")) != std::string("checkpoint."))
                        continue;

                    decree version = static_cast<decree>(atoll(s.substr(strlen("checkpoint.")).c_str()));
                    if (version > maxVersion)
                    {
                        maxVersion = version;
                        name = data_dir() + "/" + s;
                    }
                }

                if (maxVersion > 0)
                {
                    recover(name, maxVersion);
                }
            }

            void simple_kv_service_impl::recover(const std::string& name, decree version)
            {
                zauto_lock l(_lock);

                std::ifstream is(name.c_str(), std::ios::binary);
                if (!is.is_open())
                    return;

                _store.clear();

                uint64_t count;
                int magic;

                is.read((char*)&count, sizeof(count));
                is.read((char*)&magic, sizeof(magic));
                dassert(magic == 0xdeadbeef, "invalid checkpoint");

                for (uint64_t i = 0; i < count; i++)
                {
                    std::string key;
                    std::string value;

                    uint32_t sz;
                    is.read((char*)&sz, (uint32_t)sizeof(sz));
                    key.resize(sz);

                    is.read((char*)&key[0], sz);

                    is.read((char*)&sz, (uint32_t)sizeof(sz));
                    value.resize(sz);

                    is.read((char*)&value[0], sz);

                    _store[key] = value;
                }

                _last_durable_decree = _last_committed_decree = version;
            }

            int simple_kv_service_impl::flush(bool force)
            {
                zauto_lock l(_lock);

                if (last_committed_decree() == last_durable_decree())
                {
                    return 0;
                }

                // TODO: should use async write instead
                char name[256];
                sprintf(name, "%s/checkpoint.%lld", data_dir().c_str(),
                        static_cast<long long int>(last_committed_decree()));
                std::ofstream os(name, std::ios::binary);

                uint64_t count = (uint64_t)_store.size();
                int magic = 0xdeadbeef;

                os.write((const char*)&count, (uint32_t)sizeof(count));
                os.write((const char*)&magic, (uint32_t)sizeof(magic));

                for (auto it = _store.begin(); it != _store.end(); it++)
                {
                    const std::string& k = it->first;
                    uint32_t sz = (uint32_t)k.length();

                    os.write((const char*)&sz, (uint32_t)sizeof(sz));
                    os.write((const char*)&k[0], sz);

                    const std::string& v = it->second;
                    sz = (uint32_t)v.length();

                    os.write((const char*)&sz, (uint32_t)sizeof(sz));
                    os.write((const char*)&v[0], sz);
                }

                _last_durable_decree = last_committed_decree();
                return 0;
            }

            // helper routines to accelerate learning
            int simple_kv_service_impl::get_learn_state(decree start, const blob& learn_req, __out_param learn_state& state)
            {
                ::dsn::binary_writer writer;

                zauto_lock l(_lock);

                int magic = 0xdeadbeef;
                writer.write(magic);

                writer.write(_last_committed_decree.load());

                dassert(_last_committed_decree >= 0, "");

                uint64_t count = static_cast<uint64_t>(_store.size());
                writer.write(count);

                for (auto it = _store.begin(); it != _store.end(); it++)
                {
                    writer.write(it->first);
                    writer.write(it->second);
                }

                auto bb = writer.get_buffer();
                auto buf = bb.buffer();

                state.meta.push_back(blob(buf, static_cast<int>(bb.data() - bb.buffer().get()), bb.length()));

                // Test Sample
                if (_test_file_learning)
                {
                    std::stringstream ss;
                    ss << dsn_random32(0, 10000);

                    auto learn_test_file = data_dir() + "/test_learning_" + ss.str() + ".txt";
                    state.files.push_back(learn_test_file);

                    std::ofstream fout(learn_test_file.c_str());
                    fout << "DEADBEEF" << std::endl;
                    fout.close();
                }

                return 0;
            }

            int simple_kv_service_impl::apply_learn_state(learn_state& state)
            {
                blob bb((const char*)state.meta[0].data(), 0, state.meta[0].length());

                binary_reader reader(bb);

                zauto_lock l(_lock);

                _store.clear();

                int magic;
                reader.read(magic);

                dassert(magic == 0xdeadbeef, "");

                decree decree;
                reader.read(decree);

                dassert(decree >= 0, "");

                uint64_t count;
                reader.read(count);

                for (uint64_t i = 0; i < count; i++)
                {
                    std::string key, value;
                    reader.read(key);
                    reader.read(value);
                    _store[key] = value;
                }

                _last_committed_decree = decree;
                _last_durable_decree = 0;

                flush(true);

                bool ret = true;
                if (_test_file_learning)
                {
                    dassert(state.files.size() == 1, "");
                    std::string fn = learn_dir() + "/" + state.files[0];
                    ret = boost::filesystem::exists(fn);
                    if (ret)
                    {
                        std::string s;
                        std::ifstream fin(fn.c_str());

                        getline(fin, s);
                        fin.close();

                        ret = (s == "DEADBEEF");
                    }
                    else
                    {
                        dassert(false, "learning file is missing");
                    }
                }

                if (ret) return 0;
                else return ERR_LEARN_FILE_FALED.get();
            }

        }
    }
} // namespace
<|endoftext|>


<commit_before><commit_msg>Removed<commit_after><|endoftext|>


<commit_before>// BSD 2-Clause License, see github.com/ma16/rpio

#include "Pwm.h"
#include <cassert>

void RpiExt::Pwm::start()
{
    // [todo] clear fifo; clear errors
    this->pwm.setRange(this->index,32) ;
    auto c = this->pwm.getControl() ;
    auto x = c.get(this->index) ;
    x.mode = 1 ;
    x.pwen = 1 ;
    x.usef = 1 ;
    c.set(index,x) ;
    this->pwm.setControl(c) ;
}

void RpiExt::Pwm::wait()
{
    while (0 == this->pwm.getStatus().cempt())
	;
    auto c = this->pwm.getControl() ;
    auto x = c.get(index) ;
    x.pwen = 0 ;
    c.set(index,x) ;
    this->pwm.setControl(c) ;
}

void RpiExt::Pwm::send(std::vector<uint32_t> const &v)
{
    if (v.size() < 16)
    {
	this->fill_fifo(&v[0],v.size()) ;
	this->start() ;
    }
    else
    {
	this->fill_fifo(&v[0],16) ;
	this->start() ;
	this->send_fifo(&v[16],v.size()-16) ;
    }
    this->wait() ;
}

void RpiExt::Pwm::fill_fifo(uint32_t const*p,unsigned n)
{
    for (decltype(n) i=0 ; i<n ; ++i)
	this->pwm.write(p[i]) ;
    assert(0 == this->pwm.getStatus().cwerr()) ; // [todo] throw
}

void RpiExt::Pwm::send_fifo(uint32_t const *rgb,unsigned n)
{
    for (decltype(n) i=0 ; i<n ; ++i)
    {
	auto t0 = this->timer.cLo() ;
	while (0 != this->pwm.getStatus().cfull())
	    ;
	if (0 != this->pwm.getStatus().cempt())
	{
	    auto t1 = this->timer.cLo() ;
	    auto c = this->pwm.getControl() ;
	    auto x = c.get(index) ;
	    x.pwen = 0 ;
	    c.set(index,x) ;
	    this->pwm.setControl(c) ;
	    throw std::runtime_error("Pwm:unexpected empty FIFO:" + std::to_string(i) + " " + std::to_string(t1-t0)) ;
	}
	this->pwm.write(rgb[i]) ;
	if (0 != this->pwm.getStatus().cwerr())
	    throw std::runtime_error("Pwm:write error even if not full") ;
    }
}
<commit_msg>PWM peripheral defect report (can't determined end of transmission)<commit_after>// BSD 2-Clause License, see github.com/ma16/rpio

#include "Pwm.h"
#include <cassert>

void RpiExt::Pwm::start()
{
    // [todo] clear fifo; clear errors
    this->pwm.setRange(this->index,32) ;
    auto c = this->pwm.getControl() ;
    auto x = c.get(this->index) ;
    x.mode = 1 ;
    x.pwen = 1 ;
    x.usef = 1 ;
    c.set(index,x) ;
    this->pwm.setControl(c) ;
}

void RpiExt::Pwm::wait()
{
    while (0 == this->pwm.getStatus().cempt())
	;
    // [defect]
    // There seems to be no way to figure out when the PWM peripheral
    // actually completes processing of all the FIFO entries. Even if
    // the status flag indicates an empty FIFO, the serializer may
    // still be busy. As it appears, the serializer reads two FIFO
    // entries ahead.
    // So, what the client needs to do, is to put two additional words
    // into the FIFO. These words may be transmitted, or not. The
    // client should keep that in mind and set the levels
    // appropriately. Also, the last word is always transmitted again
    // if the FIFO runs empty (and if the serializer gets to this point
    // at all).
    // [todo] document this defect properly
    auto c = this->pwm.getControl() ;
    auto x = c.get(index) ;
    x.pwen = 0 ;
    c.set(index,x) ;
    this->pwm.setControl(c) ;
}

void RpiExt::Pwm::send(std::vector<uint32_t> const &v)
{
    if (v.size() < 16)
    {
	this->fill_fifo(&v[0],v.size()) ;
	this->start() ;
    }
    else
    {
	this->fill_fifo(&v[0],16) ;
	this->start() ;
	this->send_fifo(&v[16],v.size()-16) ;
    }
    this->wait() ;
}

void RpiExt::Pwm::fill_fifo(uint32_t const*p,unsigned n)
{
    for (decltype(n) i=0 ; i<n ; ++i)
	this->pwm.write(p[i]) ;
    assert(0 == this->pwm.getStatus().cwerr()) ; // [todo] throw
}

void RpiExt::Pwm::send_fifo(uint32_t const *rgb,unsigned n)
{
    for (decltype(n) i=0 ; i<n ; ++i)
    {
	auto t0 = this->timer.cLo() ;
	while (0 != this->pwm.getStatus().cfull())
	    ;
	if (0 != this->pwm.getStatus().cempt())
	{
	    auto t1 = this->timer.cLo() ;
	    auto c = this->pwm.getControl() ;
	    auto x = c.get(index) ;
	    x.pwen = 0 ;
	    c.set(index,x) ;
	    this->pwm.setControl(c) ;
	    throw std::runtime_error("Pwm:unexpected empty FIFO:" + std::to_string(i) + " " + std::to_string(t1-t0)) ;
	}
	this->pwm.write(rgb[i]) ;
	if (0 != this->pwm.getStatus().cwerr())
	    throw std::runtime_error("Pwm:write error even if not full") ;
    }
}
<|endoftext|>


<commit_before>//
// Created by skgchxngsxyz-carbon on 18/11/16.
//

#include <stdint.h>
#include <stddef.h>

#include "jsonrpc.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    using namespace ydsh;
    using namespace rpc;

    RequestParser parser;
    parser.append(reinterpret_cast<const char *>(data), size);
    auto ret = parser();
    if(parser.hasError()) {
        FILE *fp = fopen("/dev/null", "w");
        parser.showError(fp);
        fclose(fp);
    }
    (void) ret;
    return 0;
}

<commit_msg>fix build error<commit_after>//
// Created by skgchxngsxyz-carbon on 18/11/16.
//

#include <stdint.h>
#include <stddef.h>

#include "jsonrpc.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    using namespace ydsh;
    using namespace rpc;

    ByteBuffer buf;
    buf.append(reinterpret_cast<const char *>(data), size);
    MessageParser parser(std::move(buf));
    auto ret = parser();
    if(parser.hasError()) {
        FILE *fp = fopen("/dev/null", "w");
        parser.showError(fp);
        fclose(fp);
    }
    (void) ret;
    return 0;
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "FunctionDocument.hpp"

#include <XalanDOM/XalanNode.hpp>
#include <XalanDOM/XalanDocument.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/PrefixResolver.hpp>

#include <DOMSupport/DOMServices.hpp>

#include <XPath/XObjectFactory.hpp>

FunctionDocument::FunctionDocument()
{
}

FunctionDocument::~FunctionDocument()
{
}

typedef XPathExecutionContext::BorrowReturnMutableNodeRefList	BorrowReturnMutableNodeRefList;

inline void
doWarn(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			const XalanDOMString&				base,
			const XalanNode*					sourceNode,
			const Locator*						locator)
{
	XalanDOMString	theMessage(TranscodeFromLocalCodePage("Cannot load requested document: "));

	theMessage += uri;

	if (length(base) > 0)
	{
		theMessage += TranscodeFromLocalCodePage(" (Base URI: ");
		theMessage += base;
		theMessage += TranscodeFromLocalCodePage(")");
	}

	executionContext.warn(theMessage, sourceNode, locator);
}

inline XalanDocument*
parseDoc(
			XPathExecutionContext&	executionContext,
			const XalanDOMString&	uri,
			const XalanDOMString&	base,
			const XalanNode*		sourceNode,
			const Locator*			locator)
{
	try
	{
		return executionContext.parseXML(uri, base);
	}
	catch(...)
	{
		doWarn(executionContext, uri, base, sourceNode, locator);
	}

	return 0;
}

static void
getDoc(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			const XalanDOMString&				base,
			BorrowReturnMutableNodeRefList&		mnl,
			const XalanNode*					sourceNode,
			const Locator*						locator)
{
    XalanDocument*	newDoc = executionContext.getSourceDocument(uri);

	if(newDoc == 0)
	{
		if(length(uri) != 0)
		{
			newDoc = parseDoc(executionContext, uri, base, sourceNode, locator);
		}
		else
		{
			assert(executionContext.getPrefixResolver() != 0);

			newDoc =
				parseDoc(
					executionContext,
					executionContext.getPrefixResolver()->getURI(),
					base,
					sourceNode,
					locator);
		}
    }

	if(newDoc != 0)
	{
		mnl->addNodeInDocOrder(newDoc, executionContext);
	}
}

inline void
getDoc(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			BorrowReturnMutableNodeRefList&		mnl,
			const XalanNode*					sourceNode,
			const Locator*						locator)
{
	getDoc(executionContext, uri, XalanDOMString(), mnl, sourceNode, locator);
}

inline void
getDoc(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			const XalanNode*					resolver,
			BorrowReturnMutableNodeRefList&		mnl,
			const Locator*						locator)
{
	assert(resolver != 0);

 	const XalanDocument* const	ownerDocument = XalanNode::DOCUMENT_NODE == resolver->getNodeType() ?
#if defined(XALAN_OLD_STYLE_CASTS)
			(const XalanDocument*)resolver :
#else
			static_cast<const XalanDocument*>(resolver) :
#endif
			resolver->getOwnerDocument();

	getDoc(
		executionContext,
		uri,
		executionContext.findURIFromDoc(ownerDocument),
		mnl,
		resolver,
		locator);
}

XObjectPtr
FunctionDocument::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		arg1,
			const Locator*			locator) const
{
	assert(arg1.null() == false);

	if (arg1->getType() == XObject::eTypeNodeSet)
	{
		return doExecute(executionContext, context, arg1, 0, 1, locator);
	}
	else
	{
		XalanDOMString				base;

		assert(executionContext.getPrefixResolver() != 0);

		base = executionContext.getPrefixResolver()->getURI();

		return doExecute(executionContext, context, arg1, &base, 1, locator);
	}
}

XObjectPtr
FunctionDocument::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		arg1,
			const XObjectPtr		arg2,
			const Locator*			locator) const
{
	assert(arg1.null() == false && arg2.null() == false);

	XalanDOMString	base;

	if (context == 0)
	{
		executionContext.error(
			"The document() function requires a non-null context node!",
			context,
			locator);

		return XObjectPtr();
	}
	else
	{
		if(XObject::eTypeNodeSet == arg2->getType())
		{
			const NodeRefListBase&	nodeset = arg2->nodeset();

			if (nodeset.getLength() == 0)
			{
				executionContext.warn("Ignoring the empty node-set provided as the second argument to the function document().",
									  context);

				assert(executionContext.getPrefixResolver() != 0);

				base = executionContext.getPrefixResolver()->getURI();
			}
			else
			{
				XalanNode* const	baseNode =	nodeset.item(0);
				assert(baseNode != 0);

				XalanDocument* const	baseDoc = XalanNode::DOCUMENT_NODE == baseNode->getNodeType() ?
#if defined(XALAN_OLD_STYLE_CASTS)
					(XalanDocument*)baseNode :
#else
					static_cast<XalanDocument*>(baseNode) :
#endif
					baseNode->getOwnerDocument();

				base = executionContext.findURIFromDoc(baseDoc);
			}
		}
		else
		{
			base = arg2->str();
		}
	}

	return doExecute(executionContext, context, arg1, &base, 2, locator);
}

XObjectPtr
FunctionDocument::doExecute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			const XObjectPtr				arg,
			XalanDOMString*					base,
			int								argCount,
			const Locator*					locator) const
{
	typedef XPathExecutionContext::BorrowReturnMutableNodeRefList	BorrowReturnMutableNodeRefList;

	// This list will hold the nodes...
	BorrowReturnMutableNodeRefList	mnl(executionContext);

	const XObject::eObjectType			theType = arg->getType();

	const NodeRefListBase::size_type	nRefs = XObject::eTypeNodeSet == theType ?
												arg->nodeset().getLength()
												: 1;

	for(NodeRefListBase::size_type i = 0; i < nRefs; i++)
	{
		assert(XObject::eTypeNodeSet != theType ||
							arg->nodeset().item(i) != 0);

		const XalanNode*	resolver = 0;

		XalanDOMString		ref;

		if (theType != XObject::eTypeNodeSet)
		{
			ref = arg->str();
		}
		else
		{
			resolver = arg->nodeset().item(i);
			assert(resolver != 0);

			ref = DOMServices::getNodeData(*resolver);
		}

		// This is the case where the function was called with
		// an empty string, which refers to the stylesheet itself.
		if (nRefs == 1 && isEmpty(ref) == true && argCount == 1)
		{
			if (base != 0)
			{
				clear(*base);
			}

			ref = executionContext.getPrefixResolver()->getURI();
		}

		if(!isEmpty(ref))
		{
			// From http://www.ics.uci.edu/pub/ietf/uri/rfc1630.txt
			// A partial form can be distinguished from an absolute form in that the
			// latter must have a colon and that colon must occur before any slash
			// characters. Systems not requiring partial forms should not use any
			// unencoded slashes in their naming schemes.  If they do, absolute URIs
			// will still work, but confusion may result.
			const XalanDOMString::size_type		theLength = length(ref);

			const XalanDOMString::size_type		indexOfColon = indexOf(ref, XalanUnicode::charColon);
			XalanDOMString::size_type			indexOfSlash = indexOf(ref, XalanUnicode::charSolidus);

#if defined(WIN32)
			const XalanDOMString::size_type		indexOfBackSlash = indexOf(ref, XalanUnicode::charReverseSolidus);

			if(indexOfBackSlash > indexOfSlash && indexOfBackSlash < theLength)
			{
				indexOfSlash = indexOfBackSlash;
			}
#endif

			if(indexOfColon < theLength &&
			   indexOfSlash < theLength &&
			   indexOfColon < indexOfSlash)
			{
				// The ref is absolute...
				getDoc(executionContext, ref, mnl, context, locator);
			}
			else
			{
				// The ref is relative.  If there was a base URI
				// provided, use that...
				if (base != 0)
				{
					getDoc(executionContext, ref, *base, mnl, context, locator);
				}
				else
				{
					// If there's no resolver, then try using the
					// relative ref...
					if (resolver == 0)
					{
						getDoc(executionContext, ref, mnl, context, locator);
					}
					else
					{
						getDoc(executionContext, ref, resolver, mnl, locator);
					}
				}
			}
		}
	}

	assert(mnl->checkForDuplicates() == false);

	return executionContext.getXObjectFactory().createNodeSet(mnl);
}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionDocument*
#endif
FunctionDocument::clone() const
{
	return new FunctionDocument(*this);
}

const XalanDOMString
FunctionDocument::getError() const
{
	return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The document() function accepts one or two arguments!"));
}
<commit_msg>Only accept a node-set() as the second argument.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "FunctionDocument.hpp"

#include <XalanDOM/XalanNode.hpp>
#include <XalanDOM/XalanDocument.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/PrefixResolver.hpp>

#include <DOMSupport/DOMServices.hpp>

#include <XPath/XObjectFactory.hpp>

FunctionDocument::FunctionDocument()
{
}

FunctionDocument::~FunctionDocument()
{
}

typedef XPathExecutionContext::BorrowReturnMutableNodeRefList	BorrowReturnMutableNodeRefList;

inline void
doWarn(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			const XalanDOMString&				base,
			const XalanNode*					sourceNode,
			const Locator*						locator)
{
	XalanDOMString	theMessage(TranscodeFromLocalCodePage("Cannot load requested document: "));

	theMessage += uri;

	if (length(base) > 0)
	{
		theMessage += TranscodeFromLocalCodePage(" (Base URI: ");
		theMessage += base;
		theMessage += TranscodeFromLocalCodePage(")");
	}

	executionContext.warn(theMessage, sourceNode, locator);
}

inline XalanDocument*
parseDoc(
			XPathExecutionContext&	executionContext,
			const XalanDOMString&	uri,
			const XalanDOMString&	base,
			const XalanNode*		sourceNode,
			const Locator*			locator)
{
	try
	{
		return executionContext.parseXML(uri, base);
	}
	catch(...)
	{
		doWarn(executionContext, uri, base, sourceNode, locator);
	}

	return 0;
}

static void
getDoc(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			const XalanDOMString&				base,
			BorrowReturnMutableNodeRefList&		mnl,
			const XalanNode*					sourceNode,
			const Locator*						locator)
{
    XalanDocument*	newDoc = executionContext.getSourceDocument(uri);

	if(newDoc == 0)
	{
		if(length(uri) != 0)
		{
			newDoc = parseDoc(executionContext, uri, base, sourceNode, locator);
		}
		else
		{
			assert(executionContext.getPrefixResolver() != 0);

			newDoc =
				parseDoc(
					executionContext,
					executionContext.getPrefixResolver()->getURI(),
					base,
					sourceNode,
					locator);
		}
    }

	if(newDoc != 0)
	{
		mnl->addNodeInDocOrder(newDoc, executionContext);
	}
}

inline void
getDoc(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			BorrowReturnMutableNodeRefList&		mnl,
			const XalanNode*					sourceNode,
			const Locator*						locator)
{
	getDoc(executionContext, uri, XalanDOMString(), mnl, sourceNode, locator);
}

inline void
getDoc(
			XPathExecutionContext&				executionContext,
			const XalanDOMString&				uri,
			const XalanNode*					resolver,
			BorrowReturnMutableNodeRefList&		mnl,
			const Locator*						locator)
{
	assert(resolver != 0);

 	const XalanDocument* const	ownerDocument = XalanNode::DOCUMENT_NODE == resolver->getNodeType() ?
#if defined(XALAN_OLD_STYLE_CASTS)
			(const XalanDocument*)resolver :
#else
			static_cast<const XalanDocument*>(resolver) :
#endif
			resolver->getOwnerDocument();

	getDoc(
		executionContext,
		uri,
		executionContext.findURIFromDoc(ownerDocument),
		mnl,
		resolver,
		locator);
}

XObjectPtr
FunctionDocument::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		arg1,
			const Locator*			locator) const
{
	assert(arg1.null() == false);

	if (arg1->getType() == XObject::eTypeNodeSet)
	{
		return doExecute(executionContext, context, arg1, 0, 1, locator);
	}
	else
	{
		XalanDOMString				base;

		assert(executionContext.getPrefixResolver() != 0);

		base = executionContext.getPrefixResolver()->getURI();

		return doExecute(executionContext, context, arg1, &base, 1, locator);
	}
}

XObjectPtr
FunctionDocument::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		arg1,
			const XObjectPtr		arg2,
			const Locator*			locator) const
{
	assert(arg1.null() == false && arg2.null() == false);

	XalanDOMString	base;

	if (context == 0)
	{
		executionContext.error(
			"The document() function requires a non-null context node",
			context,
			locator);

		return XObjectPtr();
	}
	else
	{
		if(XObject::eTypeNodeSet != arg2->getType())
		{
			executionContext.error(
				"The second argument to the document() function must be a node-set",
				context,
				locator);
		}
		else
		{
			const NodeRefListBase&	nodeset = arg2->nodeset();

			if (nodeset.getLength() == 0)
			{
				executionContext.warn("Ignoring the empty node-set provided as the second argument to the function document()",
									  context);

				assert(executionContext.getPrefixResolver() != 0);

				base = executionContext.getPrefixResolver()->getURI();
			}
			else
			{
				XalanNode* const	baseNode =	nodeset.item(0);
				assert(baseNode != 0);

				XalanDocument* const	baseDoc = XalanNode::DOCUMENT_NODE == baseNode->getNodeType() ?
#if defined(XALAN_OLD_STYLE_CASTS)
					(XalanDocument*)baseNode :
#else
					static_cast<XalanDocument*>(baseNode) :
#endif
					baseNode->getOwnerDocument();

				base = executionContext.findURIFromDoc(baseDoc);
			}
		}
	}

	return doExecute(executionContext, context, arg1, &base, 2, locator);
}

XObjectPtr
FunctionDocument::doExecute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			const XObjectPtr				arg,
			XalanDOMString*					base,
			int								argCount,
			const Locator*					locator) const
{
	typedef XPathExecutionContext::BorrowReturnMutableNodeRefList	BorrowReturnMutableNodeRefList;

	// This list will hold the nodes...
	BorrowReturnMutableNodeRefList	mnl(executionContext);

	const XObject::eObjectType			theType = arg->getType();

	const NodeRefListBase::size_type	nRefs = XObject::eTypeNodeSet == theType ?
												arg->nodeset().getLength()
												: 1;

	for(NodeRefListBase::size_type i = 0; i < nRefs; i++)
	{
		assert(XObject::eTypeNodeSet != theType ||
							arg->nodeset().item(i) != 0);

		const XalanNode*	resolver = 0;

		XalanDOMString		ref;

		if (theType != XObject::eTypeNodeSet)
		{
			ref = arg->str();
		}
		else
		{
			resolver = arg->nodeset().item(i);
			assert(resolver != 0);

			ref = DOMServices::getNodeData(*resolver);
		}

		// This is the case where the function was called with
		// an empty string, which refers to the stylesheet itself.
		if (nRefs == 1 && isEmpty(ref) == true && argCount == 1)
		{
			if (base != 0)
			{
				clear(*base);
			}

			ref = executionContext.getPrefixResolver()->getURI();
		}

		if(!isEmpty(ref))
		{
			// From http://www.ics.uci.edu/pub/ietf/uri/rfc1630.txt
			// A partial form can be distinguished from an absolute form in that the
			// latter must have a colon and that colon must occur before any slash
			// characters. Systems not requiring partial forms should not use any
			// unencoded slashes in their naming schemes.  If they do, absolute URIs
			// will still work, but confusion may result.
			const XalanDOMString::size_type		theLength = length(ref);

			const XalanDOMString::size_type		indexOfColon = indexOf(ref, XalanUnicode::charColon);
			XalanDOMString::size_type			indexOfSlash = indexOf(ref, XalanUnicode::charSolidus);

#if defined(WIN32)
			const XalanDOMString::size_type		indexOfBackSlash = indexOf(ref, XalanUnicode::charReverseSolidus);

			if(indexOfBackSlash > indexOfSlash && indexOfBackSlash < theLength)
			{
				indexOfSlash = indexOfBackSlash;
			}
#endif

			if(indexOfColon < theLength &&
			   indexOfSlash < theLength &&
			   indexOfColon < indexOfSlash)
			{
				// The ref is absolute...
				getDoc(executionContext, ref, mnl, context, locator);
			}
			else
			{
				// The ref is relative.  If there was a base URI
				// provided, use that...
				if (base != 0)
				{
					getDoc(executionContext, ref, *base, mnl, context, locator);
				}
				else
				{
					// If there's no resolver, then try using the
					// relative ref...
					if (resolver == 0)
					{
						getDoc(executionContext, ref, mnl, context, locator);
					}
					else
					{
						getDoc(executionContext, ref, resolver, mnl, locator);
					}
				}
			}
		}
	}

	assert(mnl->checkForDuplicates() == false);

	return executionContext.getXObjectFactory().createNodeSet(mnl);
}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionDocument*
#endif
FunctionDocument::clone() const
{
	return new FunctionDocument(*this);
}

const XalanDOMString
FunctionDocument::getError() const
{
	return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The document() function accepts one or two arguments!"));
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * $ Id: $
 *
 */

// Base include file.  Must be first.
#include "XSLTResultTarget.hpp"

#include <cassert>

XSLTResultTarget::XSLTResultTarget() :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

XSLTResultTarget::XSLTResultTarget(const XalanDOMString&	fileName) :
	m_fileName(fileName),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

XSLTResultTarget::XSLTResultTarget(const char*	fileName) :
	m_fileName(fileName),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

#if defined(XALAN_NO_NAMESPACES)
XSLTResultTarget::XSLTResultTarget(ostream*		theStream) :
#else
XSLTResultTarget::XSLTResultTarget(std::ostream*	theStream) :
#endif
	m_fileName(),
	m_byteStream(theStream),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
	assert(theStream != 0);
}

#if defined(XALAN_NO_NAMESPACES)
XSLTResultTarget::XSLTResultTarget(ostream&		theStream) :
#else
XSLTResultTarget::XSLTResultTarget(std::ostream&	theStream) :
#endif
	m_fileName(),
	m_byteStream(&theStream),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

XSLTResultTarget::XSLTResultTarget(Writer*	characterStream) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(characterStream),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
	assert(characterStream != 0);
}

XSLTResultTarget::XSLTResultTarget(XalanDocument*	document) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(document),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
	assert(document != 0);
}

XSLTResultTarget::XSLTResultTarget(XalanDocumentFragment*	documentFragment) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(documentFragment),
	m_element(0),
	m_formatterListener(0)
{
	assert(documentFragment != 0);
}

XSLTResultTarget::XSLTResultTarget(XalanElement*	element) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(element),
	m_formatterListener(0)
{
	assert(element != 0);
}

XSLTResultTarget::XSLTResultTarget(FormatterListener&		flistener) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(&flistener)
{
}
<commit_msg>Include stream header files as appropriate.  Fixes bug 6765.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * $ Id: $
 *
 */

// Base include file.  Must be first.
#include "XSLTResultTarget.hpp"

#include <cassert>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <ostream>
#endif

XSLTResultTarget::XSLTResultTarget() :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

XSLTResultTarget::XSLTResultTarget(const XalanDOMString&	fileName) :
	m_fileName(fileName),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

XSLTResultTarget::XSLTResultTarget(const char*	fileName) :
	m_fileName(fileName),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

#if defined(XALAN_NO_NAMESPACES)
XSLTResultTarget::XSLTResultTarget(ostream*		theStream) :
#else
XSLTResultTarget::XSLTResultTarget(std::ostream*	theStream) :
#endif
	m_fileName(),
	m_byteStream(theStream),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
	assert(theStream != 0);
}

#if defined(XALAN_NO_NAMESPACES)
XSLTResultTarget::XSLTResultTarget(ostream&		theStream) :
#else
XSLTResultTarget::XSLTResultTarget(std::ostream&	theStream) :
#endif
	m_fileName(),
	m_byteStream(&theStream),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
}

XSLTResultTarget::XSLTResultTarget(Writer*	characterStream) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(characterStream),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
	assert(characterStream != 0);
}

XSLTResultTarget::XSLTResultTarget(XalanDocument*	document) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(document),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(0)
{
	assert(document != 0);
}

XSLTResultTarget::XSLTResultTarget(XalanDocumentFragment*	documentFragment) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(documentFragment),
	m_element(0),
	m_formatterListener(0)
{
	assert(documentFragment != 0);
}

XSLTResultTarget::XSLTResultTarget(XalanElement*	element) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(element),
	m_formatterListener(0)
{
	assert(element != 0);
}

XSLTResultTarget::XSLTResultTarget(FormatterListener&		flistener) :
	m_fileName(),
	m_byteStream(0),
	m_encoding(),
	m_characterStream(0),
	m_document(0),
	m_documentFragment(0),
	m_element(0),
	m_formatterListener(&flistener)
{
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <fs/path.hpp>
#include <common.cxx>

using namespace std::string_literals;

extern lest::tests & specification();

CASE("Path can be constructed with specified path")
{
  fs::Path path {"/Users/Bjarne/Documents"s};
  EXPECT(path.empty() == false);
}

CASE("Path can be assigned to with string")
{
  const std::string str {"/usr/local/bin"};
  fs::Path path = str;
  EXPECT(path.empty() == false);
  EXPECT(path.size() == 3u);
}

CASE("Path can be constructed with initializer list")
{
  fs::Path path {"/", "Users", "Bjarne", "Documents"};
  EXPECT(path.to_string() == "/Users/Bjarne/Documents/");
}

CASE("Paths can be checked for equality")
{
  fs::Path src_path {"/etc"};
  fs::Path dest_path {"/etc"};
  EXPECT(src_path == dest_path);
}

CASE("Paths can be checked for inequality")
{
  fs::Path src_path {"/etc"};
  fs::Path dest_path {"/bin"};
  EXPECT(src_path != dest_path);
}

CASE("Path can return number of components")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  EXPECT(path.size() == 3u);
}

CASE("Path can return specific component")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  EXPECT(path[2] == "Documents");
}

CASE("Path does not segfault when requested component is out of range")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  EXPECT_THROWS(auto path_component = path[242]);
}

CASE("Path can tell if it is empty")
{
  fs::Path path {"/Users/Bjarne"};
  EXPECT(path.empty() == false);
}

CASE("Path can return itself as string")
{
  auto str = "/Users/Bjarne/Documents/"s;
  fs::Path path {"/Users/Bjarne/Documents"s};
  EXPECT(path.to_string() == str);
}

CASE("Path::to_string returns /-ending string")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  auto str = path.to_string();
  EXPECT(str.back() == '/');
}

CASE("Path components can be added")
{
  fs::Path path {"/Users/Bjarne/Documents"s};
  path += "Books"s;
  path += "C++"s;
  EXPECT(path.size() == 5u);
}

CASE("Paths can be added")
{
  fs::Path root {"/etc"};
  auto subdirectory_name = "private/logs"s;
  fs::Path path = root + subdirectory_name;
  EXPECT(path.size() == 3u);
}

CASE("Paths can return their parent")
{
  fs::Path path {"/etc/private/logs"s};
  fs::Path path_parent {path.up()};
  EXPECT(path_parent.size() == 2u);
  EXPECT(path_parent == "/etc/private"s);
  fs::Path root {"/"s};
  fs::Path root_parent {root.up()};
  EXPECT(root_parent == "/");
}

CASE("pop_front returns path with first path component removed")
{
  fs::Path path {"/etc/private/logs"};
  auto front = path.pop_front();
  EXPECT(front == "/private/logs"s);
}

CASE("pop_back returns path with last path component removed")
{
  fs::Path path {"/etc/private/logs"};
  auto back = path.pop_back();
  EXPECT(back == "/etc/private");
}

CASE("pop_back expects that path is not empty")
{
  fs::Path path {"/etc/private/logs"};
  EXPECT_NO_THROW(path.pop_back().pop_back().pop_back());
  EXPECT_THROWS(path.pop_back());
}

CASE("pop_front expects that path is not empty")
{
  fs::Path path {"/usr/local/bin"};
  EXPECT_NO_THROW(path.pop_front().pop_front().pop_front());
  EXPECT_THROWS(path.pop_front());
}

CASE("front expects that path is not empty")
{
  fs::Path path {"/dev"};
  EXPECT_NO_THROW(auto front = path.front());
  path.pop_front();
  EXPECT_THROWS(auto front = path.front());
}

CASE("back expects that path is not empty")
{
  fs::Path path {"/Users"};
  EXPECT_NO_THROW(auto back = path.back());
  path.pop_back();
  EXPECT_THROWS(auto back = path.back());
}
<commit_msg>test: added path unit test case<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <fs/path.hpp>
#include <common.cxx>

using namespace std::string_literals;

extern lest::tests & specification();

CASE("Path can be constructed with specified path")
{
  fs::Path path {"/Users/Bjarne/Documents"s};
  EXPECT(path.empty() == false);
}

CASE("Path can be assigned to with string")
{
  const std::string str {"/usr/local/bin"};
  fs::Path path = str;
  EXPECT(path.empty() == false);
  EXPECT(path.size() == 3u);
}

CASE("Path can be constructed with initializer list")
{
  fs::Path path {"/", "Users", "Bjarne", "Documents"};
  EXPECT(path.to_string() == "/Users/Bjarne/Documents/");
}

CASE("Path by default is constructed as \"/\"")
{
  fs::Path path;
  EXPECT(path.to_string() == "/");
  EXPECT(path.empty() == true);
  EXPECT(path.size() == 0u);
}

CASE("Paths can be checked for equality")
{
  fs::Path src_path {"/etc"};
  fs::Path dest_path {"/etc"};
  EXPECT(src_path == dest_path);
}

CASE("Paths can be checked for inequality")
{
  fs::Path src_path {"/etc"};
  fs::Path dest_path {"/bin"};
  EXPECT(src_path != dest_path);
}

CASE("Path can return number of components")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  EXPECT(path.size() == 3u);
}

CASE("Path can return specific component")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  EXPECT(path[2] == "Documents");
}

CASE("Path does not segfault when requested component is out of range")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  EXPECT_THROWS(auto path_component = path[242]);
}

CASE("Path can tell if it is empty")
{
  fs::Path path {"/Users/Bjarne"};
  EXPECT(path.empty() == false);
}

CASE("Path can return itself as string")
{
  auto str = "/Users/Bjarne/Documents/"s;
  fs::Path path {"/Users/Bjarne/Documents"s};
  EXPECT(path.to_string() == str);
}

CASE("Path::to_string returns /-ending string")
{
  fs::Path path {"/Users/Bjarne/Documents"};
  auto str = path.to_string();
  EXPECT(str.back() == '/');
}

CASE("Path components can be added")
{
  fs::Path path {"/Users/Bjarne/Documents"s};
  path += "Books"s;
  path += "C++"s;
  EXPECT(path.size() == 5u);
}

CASE("Paths can be added")
{
  fs::Path root {"/etc"};
  auto subdirectory_name = "private/logs"s;
  fs::Path path = root + subdirectory_name;
  EXPECT(path.size() == 3u);
}

CASE("Paths can return their parent")
{
  fs::Path path {"/etc/private/logs"s};
  fs::Path path_parent {path.up()};
  EXPECT(path_parent.size() == 2u);
  EXPECT(path_parent == "/etc/private"s);
  fs::Path root {"/"s};
  fs::Path root_parent {root.up()};
  EXPECT(root_parent == "/");
}

CASE("pop_front returns path with first path component removed")
{
  fs::Path path {"/etc/private/logs"};
  auto front = path.pop_front();
  EXPECT(front == "/private/logs"s);
}

CASE("pop_back returns path with last path component removed")
{
  fs::Path path {"/etc/private/logs"};
  auto back = path.pop_back();
  EXPECT(back == "/etc/private");
}

CASE("pop_back expects that path is not empty")
{
  fs::Path path {"/etc/private/logs"};
  EXPECT_NO_THROW(path.pop_back().pop_back().pop_back());
  EXPECT_THROWS(path.pop_back());
}

CASE("pop_front expects that path is not empty")
{
  fs::Path path {"/usr/local/bin"};
  EXPECT_NO_THROW(path.pop_front().pop_front().pop_front());
  EXPECT_THROWS(path.pop_front());
}

CASE("front expects that path is not empty")
{
  fs::Path path {"/dev"};
  EXPECT_NO_THROW(auto front = path.front());
  path.pop_front();
  EXPECT_THROWS(auto front = path.front());
}

CASE("back expects that path is not empty")
{
  fs::Path path {"/Users"};
  EXPECT_NO_THROW(auto back = path.back());
  path.pop_back();
  EXPECT_THROWS(auto back = path.back());
}
<|endoftext|>