<commit_before>#ifndef _SNARKFRONT_BITWISE_OPS_HPP_
#define _SNARKFRONT_BITWISE_OPS_HPP_

#include <climits>
#include "AST.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// operations on built-in integer types
// (templated hash algorithm parameter)
//
// (T, U) is (uint32_t, uint64_t)
//        or (uint64_t, uint32_t)
//

template <typename T, typename U>
class BitwiseINT
{
public:
    // bitwise logical operations
    static T AND(const T x, const T y) { return x & y; }
    static T _AND(const T x, const T y) { return AND(x, y); }
    static T OR(const T x, const T y) { return x | y; }
    static T _OR(const T x, const T y) { return OR(x, y); }
    static T XOR(const T x, const T y) { return x ^ y; }
    static T _XOR(const T x, const T y) { return XOR(x, y); }
    static T CMPLMNT(const T x) { return ~x; }
    static T _CMPLMNT(const T x) { return CMPLMNT(x); }

    // modulo addition
    static T ADDMOD(const T x, const T y) { return x + y; }
    static T _ADDMOD(const T x, const T y) { return ADDMOD(x, y); }

    // bitwise shift
    static T SHL(const T x, const unsigned int n) { return x << n; }
    static T _SHL(const T x, const unsigned int n) { return SHL(x, n); }
    static T SHR(const T x, const unsigned int n) { return x >> n; }
    static T _SHR(const T x, const unsigned int n) { return SHR(x, n); }

    // bitwise rotate
    static T ROTL(const T x, const unsigned int n) {
        return OR(SHL(x, n), SHR(x, sizeof(T) * CHAR_BIT - n));
    }
    static T _ROTL(const T x, const unsigned int n) {
        return ROTL(x, n);
    }
    static T ROTR(const T x, const unsigned int n) {
        return OR(SHR(x, n), SHL(x, sizeof(T) * CHAR_BIT - n));
    }
    static T _ROTR(const T x, const unsigned int n) {
        return ROTR(x, n);
    }

    // literal value
    static T constant(const T x) { return x; }
    static T _constant(const T x) { return constant(x); }

    // converting between 32-bit and 64-bit
    static U xword(const T x) { return x; }
    static U _xword(const T x) { return xword(x); }
};

////////////////////////////////////////////////////////////////////////////////
// operations on AST nodes
// (templated hash algorithm parameter)
//
// (T, U) is (Alg_uint32, Alg_uint64)
//        or (Alg_uint64, Alg_uint32)
//

template <typename T, typename U>
class BitwiseAST
{
    // Note: Every member function is templated to accept both
    // reference and pointer arguments.

public:
    // bitwise complement
    template <typename X>
    static AST_Op<T> CMPLMNT(const X& x) {
        return AST_Op<T>(T::OpType::CMPLMNT, x);
    }
    template <typename X>
    static AST_Op<T>* _CMPLMNT(const X& x) {
        return new AST_Op<T>(T::OpType::CMPLMNT, x);
    }

#define DEFN_OPXY(NAME)                                         \
    template <typename X, typename Y>                           \
    static AST_Op<T> NAME (const X& x, const Y& y) {            \
        return objOp(T::OpType:: NAME , x, y);                  \
    }                                                           \
    template <typename X, typename Y>                           \
    static AST_Op<T>* _ ## NAME (const X& x, const Y& y) {      \
        return ptrOp(T::OpType:: NAME , x, y);                  \
    }

    // AND, OR, XOR, ADDMOD
    DEFN_OPXY(AND)
    DEFN_OPXY(OR)
    DEFN_OPXY(XOR)
    DEFN_OPXY(ADDMOD)

#undef DEFN_OPXY

#define DEFN_OPXN(NAME)                                                 \
    template <typename X>                                               \
    static AST_Op<T> NAME (const X& x, const unsigned int n) {          \
        return objOp(T::OpType:: NAME , x, _constant(n));               \
    }                                                                   \
    template <typename X>                                               \
    static AST_Op<T>* _ ## NAME (const X& x, const unsigned int n) {    \
        return ptrOp(T::OpType:: NAME , x, _constant(n));               \
    }

    // SHL, SHR, ROTL, ROTR
    DEFN_OPXN(SHL)
    DEFN_OPXN(SHR)
    DEFN_OPXN(ROTL)
    DEFN_OPXN(ROTR)

#undef DEFN_OPXN

    // literal value
    template <typename X>
    static AST_Const<T> constant(const X& x) { return AST_Const<T>(x); }

    template <typename X>
    static AST_Const<T>* _constant(const X& x) { return new AST_Const<T>(x); }

    // converting between 32-bit and 64-bit
    template <typename X>
    static AST_X<U> xword(const X& x) { return AST_X<U>(x); }

    template <typename X>
    static AST_X<U> _xword(const X& x) { return new AST_X<U>(x); }

private:
    // AST nodes at statement scope are on stack
    template <typename X, typename Y>
    static AST_Op<T> objOp(const typename T::OpType op, const X& x, const Y& y) {
        return AST_Op<T>(op, x, y);
    }

    // AST nodes nested below statement scope are on the heap
    template <typename X, typename Y>
    static AST_Op<T>* ptrOp(const typename T::OpType op, const X& x, const Y& y) {
        return new AST_Op<T>(op, x, y);
    }
};

} // namespace snarkfront

#endif
<commit_msg>remove whitespace<commit_after>#ifndef _SNARKFRONT_BITWISE_OPS_HPP_
#define _SNARKFRONT_BITWISE_OPS_HPP_

#include <climits>
#include "AST.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// operations on built-in integer types
// (templated hash algorithm parameter)
//
// (T, U) is (uint32_t, uint64_t)
//        or (uint64_t, uint32_t)
//

template <typename T, typename U>
class BitwiseINT
{
public:
    // bitwise logical operations
    static T AND(const T x, const T y) { return x & y; }
    static T _AND(const T x, const T y) { return AND(x, y); }
    static T OR(const T x, const T y) { return x | y; }
    static T _OR(const T x, const T y) { return OR(x, y); }
    static T XOR(const T x, const T y) { return x ^ y; }
    static T _XOR(const T x, const T y) { return XOR(x, y); }
    static T CMPLMNT(const T x) { return ~x; }
    static T _CMPLMNT(const T x) { return CMPLMNT(x); }

    // modulo addition
    static T ADDMOD(const T x, const T y) { return x + y; }
    static T _ADDMOD(const T x, const T y) { return ADDMOD(x, y); }

    // bitwise shift
    static T SHL(const T x, const unsigned int n) { return x << n; }
    static T _SHL(const T x, const unsigned int n) { return SHL(x, n); }
    static T SHR(const T x, const unsigned int n) { return x >> n; }
    static T _SHR(const T x, const unsigned int n) { return SHR(x, n); }

    // bitwise rotate
    static T ROTL(const T x, const unsigned int n) {
        return OR(SHL(x, n), SHR(x, sizeof(T) * CHAR_BIT - n));
    }
    static T _ROTL(const T x, const unsigned int n) {
        return ROTL(x, n);
    }
    static T ROTR(const T x, const unsigned int n) {
        return OR(SHR(x, n), SHL(x, sizeof(T) * CHAR_BIT - n));
    }
    static T _ROTR(const T x, const unsigned int n) {
        return ROTR(x, n);
    }

    // literal value
    static T constant(const T x) { return x; }
    static T _constant(const T x) { return constant(x); }

    // converting between 32-bit and 64-bit
    static U xword(const T x) { return x; }
    static U _xword(const T x) { return xword(x); }
};

////////////////////////////////////////////////////////////////////////////////
// operations on AST nodes
// (templated hash algorithm parameter)
//
// (T, U) is (Alg_uint32, Alg_uint64)
//        or (Alg_uint64, Alg_uint32)
//

template <typename T, typename U>
class BitwiseAST
{
    // Note: Every member function is templated to accept both
    // reference and pointer arguments.

public:
    // bitwise complement
    template <typename X>
    static AST_Op<T> CMPLMNT(const X& x) {
        return AST_Op<T>(T::OpType::CMPLMNT, x);
    }
    template <typename X>
    static AST_Op<T>* _CMPLMNT(const X& x) {
        return new AST_Op<T>(T::OpType::CMPLMNT, x);
    }

#define DEFN_OPXY(NAME)                                         \
    template <typename X, typename Y>                           \
    static AST_Op<T> NAME (const X& x, const Y& y) {            \
        return objOp(T::OpType:: NAME , x, y);                  \
    }                                                           \
    template <typename X, typename Y>                           \
    static AST_Op<T>* _ ## NAME (const X& x, const Y& y) {      \
        return ptrOp(T::OpType:: NAME , x, y);                  \
    }

    // AND, OR, XOR, ADDMOD
    DEFN_OPXY(AND)
    DEFN_OPXY(OR)
    DEFN_OPXY(XOR)
    DEFN_OPXY(ADDMOD)

#undef DEFN_OPXY

#define DEFN_OPXN(NAME)                                                 \
    template <typename X>                                               \
    static AST_Op<T> NAME (const X& x, const unsigned int n) {          \
        return objOp(T::OpType:: NAME , x, _constant(n));               \
    }                                                                   \
    template <typename X>                                               \
    static AST_Op<T>* _ ## NAME (const X& x, const unsigned int n) {    \
        return ptrOp(T::OpType:: NAME , x, _constant(n));               \
    }

    // SHL, SHR, ROTL, ROTR
    DEFN_OPXN(SHL)
    DEFN_OPXN(SHR)
    DEFN_OPXN(ROTL)
    DEFN_OPXN(ROTR)

#undef DEFN_OPXN

    // literal value
    template <typename X>
    static AST_Const<T> constant(const X& x) { return AST_Const<T>(x); }

    template <typename X>
    static AST_Const<T>* _constant(const X& x) { return new AST_Const<T>(x); }

    // converting between 32-bit and 64-bit
    template <typename X>
    static AST_X<U> xword(const X& x) { return AST_X<U>(x); }

    template <typename X>
    static AST_X<U> _xword(const X& x) { return new AST_X<U>(x); }

private:
    // AST nodes at statement scope are on stack
    template <typename X, typename Y>
    static AST_Op<T> objOp(const typename T::OpType op, const X& x, const Y& y) {
        return AST_Op<T>(op, x, y);
    }

    // AST nodes nested below statement scope are on the heap
    template <typename X, typename Y>
    static AST_Op<T>* ptrOp(const typename T::OpType op, const X& x, const Y& y) {
        return new AST_Op<T>(op, x, y);
    }
};

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2017 CodiLime
 *
 * 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 <QSettings>
#include <QApplication>

#include "util/settings/connection_client.h"

namespace veles {
namespace util {
namespace settings {
namespace connection {

bool default_run_server = true;
QString localhost("127.0.0.1");
QString default_database("veles.vdb");
int default_server_port = 3135;
bool default_shut_down_server = true;

bool runServerDefault() {
  return default_run_server;
}

bool runServer() {
  QSettings settings;
  return settings.value("conection.run_server", runServerDefault()).toBool();
}

void setRunServer(bool run_server) {
  QSettings settings;
  settings.setValue("conection.run_server", run_server);
}

QString serverHostDefault() {
  return localhost;
}

QString serverHost() {
  QSettings settings;
  return settings.value("conection.server", serverHostDefault()).toString();
}

void setServerHost(QString server_host) {
  QSettings settings;
  settings.setValue("conection.server", server_host);
}

int serverPortDefault() {
  return default_server_port;
}

int serverPort() {
  QSettings settings;
  return settings.value("conection.server_port", serverPortDefault()).toInt();
}

void setServerPort(int server_port) {
  QSettings settings;
  settings.setValue("conection.server_port", server_port);
}

QString clientInterfaceDefault() {
  return localhost;
}

QString clientInterface() {
  QSettings settings;
  return settings.value("conection.client_interface",
      clientInterfaceDefault()).toString();
}

void setClientInterface(QString client_interface) {
  QSettings settings;
  settings.setValue("conection.client_interface", client_interface);
}

QString clientName() {
  QSettings settings;
  return settings.value("conection.client_name", clientNameDefault()).toString();
}

QString clientNameDefault() {
  QString user_name;
#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
    user_name = qgetenv("USER");
#elif defined(Q_OS_WIN)
    user_name = qgetenv("USERNAME");
#else
    user_name = "Veles UI";
#endif

  if(user_name.length() == 0) {
    user_name = "Veles UI";
  }

  return user_name;
}

void setClientName(QString client_name) {
  QSettings settings;
  settings.setValue("conection.client_name", client_name);
}

QString connectionKeyDefault() {
  return QString("");
}

QString connectionKey() {
  QSettings settings;
  return settings.value("conection.key", connectionKeyDefault()).toString();
}

void setConnectionKey(QString connection_key) {
  QSettings settings;
  settings.setValue("conection.key", connection_key);
}

QString databaseNameDefault() {
  return default_database;
}

QString databaseName() {
  QSettings settings;
  return settings.value("conection.database",
      databaseNameDefault()).toString();
}

void setDatabaseName(QString database_name) {
  QSettings settings;
  settings.setValue("conection.database", database_name);
}

QString serverScriptDefault() {
#if defined(Q_OS_WIN)
  return qApp->applicationDirPath() + "/../veles-server/srv.py";
#else
  return QString("../veles/python/srv.py");
#endif
}

QString serverScript() {
  QSettings settings;
  return settings.value("connection.server_script",
      serverScriptDefault()).toString();
}

void setServerScript(QString server_script) {
  QSettings settings;
  settings.setValue("connection.server_script", server_script);
}

bool shutDownServerOnQuitDefault() {
  return default_shut_down_server;
}

bool shutDownServerOnQuit() {
  QSettings settings;
  return settings.value("connection.shut_down_server_on_quit",
      shutDownServerOnQuitDefault()).toBool();
}

void setShutDownServerOnQuit(bool shut_down_server) {
  QSettings settings;
  settings.setValue("connection.shut_down_server_on_quit", shut_down_server);
}

}  // namespace connection
}  // namespace settings
}  // namespace util
}  // namespace veles
<commit_msg>changed default database dir to writable location<commit_after>/*
 * Copyright 2017 CodiLime
 *
 * 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 <QSettings>
#include <QApplication>
#include <QStandardPaths>

#include "util/settings/connection_client.h"

namespace veles {
namespace util {
namespace settings {
namespace connection {

bool default_run_server = true;
QString localhost("127.0.0.1");
QString default_database_file("veles.vdb");
int default_server_port = 3135;
bool default_shut_down_server = true;

bool runServerDefault() {
  return default_run_server;
}

bool runServer() {
  QSettings settings;
  return settings.value("conection.run_server", runServerDefault()).toBool();
}

void setRunServer(bool run_server) {
  QSettings settings;
  settings.setValue("conection.run_server", run_server);
}

QString serverHostDefault() {
  return localhost;
}

QString serverHost() {
  QSettings settings;
  return settings.value("conection.server", serverHostDefault()).toString();
}

void setServerHost(QString server_host) {
  QSettings settings;
  settings.setValue("conection.server", server_host);
}

int serverPortDefault() {
  return default_server_port;
}

int serverPort() {
  QSettings settings;
  return settings.value("conection.server_port", serverPortDefault()).toInt();
}

void setServerPort(int server_port) {
  QSettings settings;
  settings.setValue("conection.server_port", server_port);
}

QString clientInterfaceDefault() {
  return localhost;
}

QString clientInterface() {
  QSettings settings;
  return settings.value("conection.client_interface",
      clientInterfaceDefault()).toString();
}

void setClientInterface(QString client_interface) {
  QSettings settings;
  settings.setValue("conection.client_interface", client_interface);
}

QString clientName() {
  QSettings settings;
  return settings.value("conection.client_name", clientNameDefault()).toString();
}

QString clientNameDefault() {
  QString user_name;
#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
    user_name = qgetenv("USER");
#elif defined(Q_OS_WIN)
    user_name = qgetenv("USERNAME");
#else
    user_name = "Veles UI";
#endif

  if(user_name.length() == 0) {
    user_name = "Veles UI";
  }

  return user_name;
}

void setClientName(QString client_name) {
  QSettings settings;
  settings.setValue("conection.client_name", client_name);
}

QString connectionKeyDefault() {
  return QString("");
}

QString connectionKey() {
  QSettings settings;
  return settings.value("conection.key", connectionKeyDefault()).toString();
}

void setConnectionKey(QString connection_key) {
  QSettings settings;
  settings.setValue("conection.key", connection_key);
}

QString databaseNameDefault() {
  return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation) + "/" + default_database_file;
}

QString databaseName() {
  QSettings settings;
  return settings.value("conection.database",
      databaseNameDefault()).toString();
}

void setDatabaseName(QString database_name) {
  QSettings settings;
  settings.setValue("conection.database", database_name);
}

QString serverScriptDefault() {
#if defined(Q_OS_WIN)
  return qApp->applicationDirPath() + "/../veles-server/srv.py";
#else
  return QString("../veles/python/srv.py");
#endif
}

QString serverScript() {
  QSettings settings;
  return settings.value("connection.server_script",
      serverScriptDefault()).toString();
}

void setServerScript(QString server_script) {
  QSettings settings;
  settings.setValue("connection.server_script", server_script);
}

bool shutDownServerOnQuitDefault() {
  return default_shut_down_server;
}

bool shutDownServerOnQuit() {
  QSettings settings;
  return settings.value("connection.shut_down_server_on_quit",
      shutDownServerOnQuitDefault()).toBool();
}

void setShutDownServerOnQuit(bool shut_down_server) {
  QSettings settings;
  settings.setValue("connection.shut_down_server_on_quit", shut_down_server);
}

}  // namespace connection
}  // namespace settings
}  // namespace util
}  // namespace veles
<|endoftext|>


<commit_before>/*
 Copyright (c) 2010, The Barbarian Group
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/Url.h"
#include "cinder/DataSource.h"
#include "cinder/Utilities.h"
#if defined( CINDER_MSW )
	#include <Shlwapi.h>
	#include "cinder/UrlImplWinInet.h"
	typedef cinder::IStreamUrlImplWinInet	IStreamUrlPlatformImpl;
#elif defined( CINDER_COCOA )
	#include "cinder/cocoa/CinderCocoa.h"
	#include "cinder/UrlImplCocoa.h"
	typedef cinder::IStreamUrlImplCocoa		IStreamUrlPlatformImpl;
#else
	#include "cinder/UrlImplCurl.h"
	typedef cinder::IStreamUrlImplCurl		IStreamUrlPlatformImpl;
#endif

namespace cinder {

//////////////////////////////////////////////////////////////////////////////////////////////////////
// Url
Url::Url( const std::string &urlString, bool isEscaped )
	: mStr( isEscaped ?
		urlString : encode( urlString ) )
{
}

std::string Url::encode( const std::string &unescaped )
{
#if defined( CINDER_COCOA )
	cocoa::SafeCfString unescapedStr = cocoa::createSafeCfString( unescaped );
	CFStringRef escaped = ::CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, unescapedStr.get(), NULL, NULL, kCFStringEncodingUTF8 );
	std::string result = cocoa::convertCfString( escaped );
	::CFRelease( escaped );
	return result;
#elif defined( CINDER_MSW )
	wchar_t buffer[4096];
	DWORD bufferSize = 4096;
	std::wstring wideUnescaped = toUtf16( unescaped );
	UrlEscape( wideUnescaped.c_str(), buffer, &bufferSize, 0 );
	return toUtf8( std::wstring( buffer ) );
#endif
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
// IStreamUrl
IStreamUrlRef IStreamUrl::createRef( const std::string &url, const std::string &user, const std::string &password )
{
	return IStreamUrlRef( new IStreamUrl( url, user, password ) );
}

IStreamUrl::IStreamUrl( const std::string &url, const std::string &user, const std::string &password )
	: IStream()
{
	setFileName( url );
	mImpl = shared_ptr<IStreamUrlImpl>( new IStreamUrlPlatformImpl( url, user, password ) );
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
// loadUrl
IStreamUrlRef loadUrlStream( const Url &url )
{
	try {
		IStreamUrlRef result = IStreamUrl::createRef( url.str(), "", "" );
		return result;
	}
	catch( ... ) {
		return IStreamUrlRef();
	}
}

IStreamUrlRef loadUrlStream( const std::string &url, const std::string &user, const std::string &password )
{
	try {
		IStreamUrlRef result = IStreamUrl::createRef( url, user, password );
		return result;
	}
	catch( ... ) {
		return IStreamUrlRef();
	}
}

} // namespace cinder
<commit_msg>loadUrlStream() passes exceptions rather than returning NULL<commit_after>/*
 Copyright (c) 2010, The Barbarian Group
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/Url.h"
#include "cinder/DataSource.h"
#include "cinder/Utilities.h"
#if defined( CINDER_MSW )
	#include <Shlwapi.h>
	#include "cinder/UrlImplWinInet.h"
	typedef cinder::IStreamUrlImplWinInet	IStreamUrlPlatformImpl;
#elif defined( CINDER_COCOA )
	#include "cinder/cocoa/CinderCocoa.h"
	#include "cinder/UrlImplCocoa.h"
	typedef cinder::IStreamUrlImplCocoa		IStreamUrlPlatformImpl;
#else
	#include "cinder/UrlImplCurl.h"
	typedef cinder::IStreamUrlImplCurl		IStreamUrlPlatformImpl;
#endif

namespace cinder {

//////////////////////////////////////////////////////////////////////////////////////////////////////
// Url
Url::Url( const std::string &urlString, bool isEscaped )
	: mStr( isEscaped ?
		urlString : encode( urlString ) )
{
}

std::string Url::encode( const std::string &unescaped )
{
#if defined( CINDER_COCOA )
	cocoa::SafeCfString unescapedStr = cocoa::createSafeCfString( unescaped );
	CFStringRef escaped = ::CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, unescapedStr.get(), NULL, NULL, kCFStringEncodingUTF8 );
	std::string result = cocoa::convertCfString( escaped );
	::CFRelease( escaped );
	return result;
#elif defined( CINDER_MSW )
	wchar_t buffer[4096];
	DWORD bufferSize = 4096;
	std::wstring wideUnescaped = toUtf16( unescaped );
	UrlEscape( wideUnescaped.c_str(), buffer, &bufferSize, 0 );
	return toUtf8( std::wstring( buffer ) );
#endif
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
// IStreamUrl
IStreamUrlRef IStreamUrl::createRef( const std::string &url, const std::string &user, const std::string &password )
{
	return IStreamUrlRef( new IStreamUrl( url, user, password ) );
}

IStreamUrl::IStreamUrl( const std::string &url, const std::string &user, const std::string &password )
	: IStream()
{
	setFileName( url );
	mImpl = shared_ptr<IStreamUrlImpl>( new IStreamUrlPlatformImpl( url, user, password ) );
}

//////////////////////////////////////////////////////////////////////////////////////////////////////
// loadUrl
IStreamUrlRef loadUrlStream( const Url &url )
{
	return IStreamUrl::createRef( url.str(), "", "" );
}

IStreamUrlRef loadUrlStream( const std::string &url, const std::string &user, const std::string &password )
{
	return IStreamUrl::createRef( url, user, password );
}

} // namespace cinder
<|endoftext|>


<commit_before>#include <sys/socket.h>

#include "utils.h"
#include "client_base.h"

const int WRITE_QUEUE_SIZE = -1;

int BaseClient::total_clients = 0;

BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: io(loop),
	  async(loop),
	  destroyed(false),
	  closed(false),
	  sock(sock_),
	  database_pool(database_pool_),
	  write_queue(WRITE_QUEUE_SIZE)
{
	sig.set<BaseClient, &BaseClient::signal_cb>(this);
	sig.start(SIGINT);

	async.set<BaseClient, &BaseClient::async_cb>(this);
	async.start();

	io.set<BaseClient, &BaseClient::io_cb>(this);
	io.start(sock, ev::READ);
}

BaseClient::~BaseClient()
{
	destroy();
	sig.stop();
	LOG_OBJ(this, "DELETED!\n");
}

void BaseClient::signal_cb(ev::sig &signal, int revents)
{
	LOG_EV(this, "Signaled destroy!!\n");
	destroy();
	delete this;
}

void BaseClient::destroy()
{
	if (destroyed) {
		return;
	}

	destroyed = true;

	close();

	// Stop and free watcher if client socket is closing
	io.stop();
	async.stop();

	::close(sock);
	LOG_OBJ(this, "DESTROYED!\n");
}

void BaseClient::close() {
	if (closed) {
		return;
	}

	closed = true;
	LOG_OBJ(this, "CLOSED!\n");
}

void BaseClient::async_cb(ev::async &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::io_cb(ev::io &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);

	if (revents & EV_ERROR) {
		LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
		destroy();
		return;
	}

	if (revents & EV_READ)
		read_cb(watcher);

	if (revents & EV_WRITE)
		write_cb(watcher);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		} else {
			io.set(ev::READ);
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::write_cb(ev::io &watcher)
{
	if (!write_queue.empty()) {
		Buffer* buffer = write_queue.front();

		size_t buf_size = buffer->nbytes();
		const char * buf = buffer->dpos();

		LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());

		ssize_t written = ::write(watcher.fd, buf, buf_size);

		if (written < 0) {
			if (errno != EAGAIN) {
				LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
				destroy();
			}
		} else if (written == 0) {
			// nothing written?
		} else {
			buffer->pos += written;
			if (buffer->nbytes() == 0) {
				write_queue.pop(buffer);
				delete buffer;
			}
		}
	}
}

void BaseClient::read_cb(ev::io &watcher)
{
	char buf[1024];

	ssize_t received = ::read(watcher.fd, buf, sizeof(buf));

	if (received < 0) {
		if (errno != EAGAIN) {
			LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
			destroy();
		}
	} else if (received == 0) {
		// The peer has closed its half side of the connection.
		LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
		destroy();
	} else {
		LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
		on_read(buf, received);
	}
}

void BaseClient::write(const char *buf, size_t buf_size)
{
	Buffer *buffer = new Buffer('\0', buf, buf_size);
	write_queue.push(buffer);

	async.send();
}
<commit_msg>Assert watcher.fd == sock<commit_after>#include <assert.h>
#include <sys/socket.h>

#include "utils.h"
#include "client_base.h"

const int WRITE_QUEUE_SIZE = -1;

int BaseClient::total_clients = 0;

BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: io(loop),
	  async(loop),
	  destroyed(false),
	  closed(false),
	  sock(sock_),
	  database_pool(database_pool_),
	  write_queue(WRITE_QUEUE_SIZE)
{
	sig.set<BaseClient, &BaseClient::signal_cb>(this);
	sig.start(SIGINT);

	async.set<BaseClient, &BaseClient::async_cb>(this);
	async.start();

	io.set<BaseClient, &BaseClient::io_cb>(this);
	io.start(sock, ev::READ);
}

BaseClient::~BaseClient()
{
	destroy();
	sig.stop();
	LOG_OBJ(this, "DELETED!\n");
}

void BaseClient::signal_cb(ev::sig &signal, int revents)
{
	LOG_EV(this, "Signaled destroy!!\n");
	destroy();
	delete this;
}

void BaseClient::destroy()
{
	if (destroyed) {
		return;
	}

	destroyed = true;

	close();

	// Stop and free watcher if client socket is closing
	io.stop();
	async.stop();

	::close(sock);
	LOG_OBJ(this, "DESTROYED!\n");
}

void BaseClient::close() {
	if (closed) {
		return;
	}

	closed = true;
	LOG_OBJ(this, "CLOSED!\n");
}

void BaseClient::async_cb(ev::async &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::io_cb(ev::io &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	assert(sock == watcher.fd);

	LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);

	if (revents & EV_ERROR) {
		LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
		destroy();
		return;
	}

	if (revents & EV_READ)
		read_cb(watcher);

	if (revents & EV_WRITE)
		write_cb(watcher);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		} else {
			io.set(ev::READ);
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::write_cb(ev::io &watcher)
{
	if (!write_queue.empty()) {
		Buffer* buffer = write_queue.front();

		size_t buf_size = buffer->nbytes();
		const char * buf = buffer->dpos();

		LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());

		ssize_t written = ::write(sock, buf, buf_size);

		if (written < 0) {
			if (errno != EAGAIN) {
				LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
				destroy();
			}
		} else if (written == 0) {
			// nothing written?
		} else {
			buffer->pos += written;
			if (buffer->nbytes() == 0) {
				write_queue.pop(buffer);
				delete buffer;
			}
		}
	}
}

void BaseClient::read_cb(ev::io &watcher)
{
	char buf[1024];

	ssize_t received = ::read(sock, buf, sizeof(buf));

	if (received < 0) {
		if (errno != EAGAIN) {
			LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
			destroy();
		}
	} else if (received == 0) {
		// The peer has closed its half side of the connection.
		LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
		destroy();
	} else {
		LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
		on_read(buf, received);
	}
}

void BaseClient::write(const char *buf, size_t buf_size)
{
	Buffer *buffer = new Buffer('\0', buf, buf_size);
	write_queue.push(buffer);

	async.send();
}
<|endoftext|>


<commit_before>/*ckwg +5
 * Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "process_cluster.h"

#include "pipeline_exception.h"
#include "process_cluster_exception.h"
#include "process_exception.h"
#include "process_registry.h"

#include <boost/foreach.hpp>

#include <algorithm>
#include <map>
#include <utility>
#include <vector>

/**
 * \file process_cluster.cxx
 *
 * \brief Implementation for \link vistk::process_cluster process cluster\endlink.
 */

namespace vistk
{

process::property_t const process_cluster::property_cluster = process::property_t("_cluster");

class process_cluster::priv
{
  public:
    priv();
    ~priv();

    typedef std::pair<config::key_t, config::key_t> config_mapping_t;
    typedef std::vector<config_mapping_t> config_mappings_t;
    typedef std::map<process::name_t, config_mappings_t> config_map_t;
    typedef std::map<process::name_t, process_t> process_map_t;

    bool has_name(name_t const& name) const;
    void ensure_name(name_t const& name) const;

    config_map_t config_map;
    process_map_t processes;
    connections_t input_mappings;
    connections_t output_mappings;
    connections_t internal_connections;
};

processes_t
process_cluster
::processes() const
{
  processes_t procs;

  BOOST_FOREACH (priv::process_map_t::value_type const& process_entry, d->processes)
  {
    process_t const& proc = process_entry.second;

    procs.push_back(proc);
  }

  return procs;
}

process::connections_t
process_cluster
::input_mappings() const
{
  return d->input_mappings;
}

process::connections_t
process_cluster
::output_mappings() const
{
  return d->output_mappings;
}

process::connections_t
process_cluster
::internal_connections() const
{
  return d->internal_connections;
}

process_cluster
::process_cluster(config_t const& config)
  : process(config)
  , d(new priv)
{
}

process_cluster
::~process_cluster()
{
}

static process::name_t convert_name(process::name_t const& cluster_name, process::name_t const& process_name);

void
process_cluster
::map_config(config::key_t const& key, name_t const& name_, config::key_t const& mapped_key)
{
  if (d->has_name(name_))
  {
    throw mapping_after_process_exception(name(), key,
                                          name_, mapped_key);
  }

  priv::config_mapping_t const mapping = priv::config_mapping_t(key, mapped_key);

  d->config_map[name_].push_back(mapping);
}

void
process_cluster
::add_process(name_t const& name_, type_t const& type_, config_t const& conf)
{
  if (d->processes.count(name_))
  {
    throw duplicate_process_name_exception(name_);
  }

  priv::config_mappings_t const mappings = d->config_map[name_];

  BOOST_FOREACH (priv::config_mapping_t const& mapping, mappings)
  {
    config::key_t const& key = mapping.first;
    config::key_t const& mapped_key = mapping.second;

    config::value_t const value = config_value<config::value_t>(key);

    conf->set_value(mapped_key, value);
  }

  process_registry_t const reg = process_registry::self();
  name_t const real_name = convert_name(name(), name_);

  process_t const proc = reg->create_process(type_, real_name, conf);

  d->processes[name_] = proc;
}

void
process_cluster
::map_input(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
  d->ensure_name(name_);

  process_t const& proc = d->processes[name_];

  if (!proc->input_port_info(mapped_port))
  {
    throw no_such_port_exception(name_, mapped_port);

    return;
  }

  name_t const real_name = convert_name(name(), name_);

  BOOST_FOREACH (connection_t const& input_mapping, d->input_mappings)
  {
    port_addr_t const& process_addr = input_mapping.second;
    name_t const& process_name = process_addr.first;
    port_t const& process_port = process_addr.second;

    if ((process_name == real_name) &&
        (process_port == mapped_port))
    {
      throw port_reconnect_exception(process_name, mapped_port);
    }
  }

  port_addr_t const cluster_addr = port_addr_t(name(), port);
  port_addr_t const mapped_addr = port_addr_t(real_name, mapped_port);

  connection_t const connection = connection_t(cluster_addr, mapped_addr);

  d->input_mappings.push_back(connection);
}

void
process_cluster
::map_output(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
  d->ensure_name(name_);

  /// \todo Make sure that only one process is mapped to a port.

  process_t const& proc = d->processes[name_];

  if (!proc->output_port_info(mapped_port))
  {
    throw no_such_port_exception(name_, mapped_port);

    return;
  }

  BOOST_FOREACH (connection_t const& output_mapping, d->output_mappings)
  {
    port_addr_t const& cluster_addr = output_mapping.second;
    port_t const& cluster_port = cluster_addr.second;

    if (cluster_port == port)
    {
      throw port_reconnect_exception(name(), port);
    }
  }

  name_t const real_name = convert_name(name(), name_);

  port_addr_t const cluster_addr = port_addr_t(name(), port);
  port_addr_t const mapped_addr = port_addr_t(real_name, mapped_port);

  connection_t const connection = connection_t(mapped_addr, cluster_addr);

  d->output_mappings.push_back(connection);
}

void
process_cluster
::connect(name_t const& upstream_name, port_t const& upstream_port,
          name_t const& downstream_name, port_t const& downstream_port)
{
  d->ensure_name(upstream_name);
  d->ensure_name(downstream_name);

  process_t const& up_proc = d->processes[upstream_name];

  if (!up_proc->output_port_info(upstream_port))
  {
    throw no_such_port_exception(upstream_name, upstream_port);
  }

  process_t const& down_proc = d->processes[downstream_name];

  if (!down_proc->input_port_info(downstream_port))
  {
    throw no_such_port_exception(downstream_name, downstream_port);
  }

  name_t const up_real_name = convert_name(name(), upstream_name);
  name_t const down_real_name = convert_name(name(), downstream_name);

  port_addr_t const up_addr = port_addr_t(up_real_name, upstream_port);
  port_addr_t const down_addr = port_addr_t(down_real_name, downstream_port);

  connection_t const connection = connection_t(up_addr, down_addr);

  d->internal_connections.push_back(connection);
}

void
process_cluster
::_configure()
{
}

void
process_cluster
::_init()
{
}

void
process_cluster
::_reset()
{
}

void
process_cluster
::_step()
{
  throw process_exception();
}

void
process_cluster
::_reconfigure(config_t const& conf)
{
  config::keys_t const tunable_keys = available_tunable_config();

  BOOST_FOREACH (priv::config_map_t::value_type const& config_mapping, d->config_map)
  {
    name_t const& name_ = config_mapping.first;
    priv::config_mappings_t const& mappings = config_mapping.second;

    config_t const provide_conf = config::empty_config();

    BOOST_FOREACH (priv::config_mapping_t const& mapping, mappings)
    {
      config::key_t const& key = mapping.first;

      if (!std::count(tunable_keys.begin(), tunable_keys.end(), key))
      {
        continue;
      }

      config::key_t const& mapped_key = mapping.second;

      config::value_t const& value = config_value<config::value_t>(key);

      provide_conf->set_value(mapped_key, value);
    }

    process_t const proc = d->processes[name_];

    // Grab the new subblock for the process.
    config_t const proc_conf = conf->subblock(name_);

    // Reconfigure the given process normally.
    proc->reconfigure(proc_conf);
    // Overwrite any provided configuration values which may be read-only.
    proc->reconfigure_with_provides(provide_conf);
  }

  process::_reconfigure(conf);
}

process::properties_t
process_cluster
::_properties() const
{
  properties_t base_properties = process::_properties();

  base_properties.insert(property_cluster);

  return base_properties;
}

process_cluster::priv
::priv()
  : config_map()
  , processes()
  , input_mappings()
  , output_mappings()
  , internal_connections()
{
}

process_cluster::priv
::~priv()
{
}

bool
process_cluster::priv
::has_name(name_t const& name) const
{
  return processes.count(name);
}

void
process_cluster::priv
::ensure_name(name_t const& name) const
{
  if (!has_name(name))
  {
    throw no_such_process_exception(name);
  }
}

process::name_t
convert_name(process::name_t const& cluster_name, process::name_t const& process_name)
{
  static process::name_t const sep = process::name_t("/");

  process::name_t const full_name = cluster_name + sep + process_name;

  return full_name;
}

}
<commit_msg>Add a note to not modify parameters<commit_after>/*ckwg +5
 * Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "process_cluster.h"

#include "pipeline_exception.h"
#include "process_cluster_exception.h"
#include "process_exception.h"
#include "process_registry.h"

#include <boost/foreach.hpp>

#include <algorithm>
#include <map>
#include <utility>
#include <vector>

/**
 * \file process_cluster.cxx
 *
 * \brief Implementation for \link vistk::process_cluster process cluster\endlink.
 */

namespace vistk
{

process::property_t const process_cluster::property_cluster = process::property_t("_cluster");

class process_cluster::priv
{
  public:
    priv();
    ~priv();

    typedef std::pair<config::key_t, config::key_t> config_mapping_t;
    typedef std::vector<config_mapping_t> config_mappings_t;
    typedef std::map<process::name_t, config_mappings_t> config_map_t;
    typedef std::map<process::name_t, process_t> process_map_t;

    bool has_name(name_t const& name) const;
    void ensure_name(name_t const& name) const;

    config_map_t config_map;
    process_map_t processes;
    connections_t input_mappings;
    connections_t output_mappings;
    connections_t internal_connections;
};

processes_t
process_cluster
::processes() const
{
  processes_t procs;

  BOOST_FOREACH (priv::process_map_t::value_type const& process_entry, d->processes)
  {
    process_t const& proc = process_entry.second;

    procs.push_back(proc);
  }

  return procs;
}

process::connections_t
process_cluster
::input_mappings() const
{
  return d->input_mappings;
}

process::connections_t
process_cluster
::output_mappings() const
{
  return d->output_mappings;
}

process::connections_t
process_cluster
::internal_connections() const
{
  return d->internal_connections;
}

process_cluster
::process_cluster(config_t const& config)
  : process(config)
  , d(new priv)
{
}

process_cluster
::~process_cluster()
{
}

static process::name_t convert_name(process::name_t const& cluster_name, process::name_t const& process_name);

void
process_cluster
::map_config(config::key_t const& key, name_t const& name_, config::key_t const& mapped_key)
{
  if (d->has_name(name_))
  {
    throw mapping_after_process_exception(name(), key,
                                          name_, mapped_key);
  }

  priv::config_mapping_t const mapping = priv::config_mapping_t(key, mapped_key);

  d->config_map[name_].push_back(mapping);
}

void
process_cluster
::add_process(name_t const& name_, type_t const& type_, config_t const& conf)
{
  if (d->processes.count(name_))
  {
    throw duplicate_process_name_exception(name_);
  }

  priv::config_mappings_t const mappings = d->config_map[name_];

  BOOST_FOREACH (priv::config_mapping_t const& mapping, mappings)
  {
    config::key_t const& key = mapping.first;
    config::key_t const& mapped_key = mapping.second;

    config::value_t const value = config_value<config::value_t>(key);

    /// \todo Create a copy of conf before modifying it.
    conf->set_value(mapped_key, value);
  }

  process_registry_t const reg = process_registry::self();
  name_t const real_name = convert_name(name(), name_);

  process_t const proc = reg->create_process(type_, real_name, conf);

  d->processes[name_] = proc;
}

void
process_cluster
::map_input(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
  d->ensure_name(name_);

  process_t const& proc = d->processes[name_];

  if (!proc->input_port_info(mapped_port))
  {
    throw no_such_port_exception(name_, mapped_port);

    return;
  }

  name_t const real_name = convert_name(name(), name_);

  BOOST_FOREACH (connection_t const& input_mapping, d->input_mappings)
  {
    port_addr_t const& process_addr = input_mapping.second;
    name_t const& process_name = process_addr.first;
    port_t const& process_port = process_addr.second;

    if ((process_name == real_name) &&
        (process_port == mapped_port))
    {
      throw port_reconnect_exception(process_name, mapped_port);
    }
  }

  port_addr_t const cluster_addr = port_addr_t(name(), port);
  port_addr_t const mapped_addr = port_addr_t(real_name, mapped_port);

  connection_t const connection = connection_t(cluster_addr, mapped_addr);

  d->input_mappings.push_back(connection);
}

void
process_cluster
::map_output(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
  d->ensure_name(name_);

  /// \todo Make sure that only one process is mapped to a port.

  process_t const& proc = d->processes[name_];

  if (!proc->output_port_info(mapped_port))
  {
    throw no_such_port_exception(name_, mapped_port);

    return;
  }

  BOOST_FOREACH (connection_t const& output_mapping, d->output_mappings)
  {
    port_addr_t const& cluster_addr = output_mapping.second;
    port_t const& cluster_port = cluster_addr.second;

    if (cluster_port == port)
    {
      throw port_reconnect_exception(name(), port);
    }
  }

  name_t const real_name = convert_name(name(), name_);

  port_addr_t const cluster_addr = port_addr_t(name(), port);
  port_addr_t const mapped_addr = port_addr_t(real_name, mapped_port);

  connection_t const connection = connection_t(mapped_addr, cluster_addr);

  d->output_mappings.push_back(connection);
}

void
process_cluster
::connect(name_t const& upstream_name, port_t const& upstream_port,
          name_t const& downstream_name, port_t const& downstream_port)
{
  d->ensure_name(upstream_name);
  d->ensure_name(downstream_name);

  process_t const& up_proc = d->processes[upstream_name];

  if (!up_proc->output_port_info(upstream_port))
  {
    throw no_such_port_exception(upstream_name, upstream_port);
  }

  process_t const& down_proc = d->processes[downstream_name];

  if (!down_proc->input_port_info(downstream_port))
  {
    throw no_such_port_exception(downstream_name, downstream_port);
  }

  name_t const up_real_name = convert_name(name(), upstream_name);
  name_t const down_real_name = convert_name(name(), downstream_name);

  port_addr_t const up_addr = port_addr_t(up_real_name, upstream_port);
  port_addr_t const down_addr = port_addr_t(down_real_name, downstream_port);

  connection_t const connection = connection_t(up_addr, down_addr);

  d->internal_connections.push_back(connection);
}

void
process_cluster
::_configure()
{
}

void
process_cluster
::_init()
{
}

void
process_cluster
::_reset()
{
}

void
process_cluster
::_step()
{
  throw process_exception();
}

void
process_cluster
::_reconfigure(config_t const& conf)
{
  config::keys_t const tunable_keys = available_tunable_config();

  BOOST_FOREACH (priv::config_map_t::value_type const& config_mapping, d->config_map)
  {
    name_t const& name_ = config_mapping.first;
    priv::config_mappings_t const& mappings = config_mapping.second;

    config_t const provide_conf = config::empty_config();

    BOOST_FOREACH (priv::config_mapping_t const& mapping, mappings)
    {
      config::key_t const& key = mapping.first;

      if (!std::count(tunable_keys.begin(), tunable_keys.end(), key))
      {
        continue;
      }

      config::key_t const& mapped_key = mapping.second;

      config::value_t const& value = config_value<config::value_t>(key);

      provide_conf->set_value(mapped_key, value);
    }

    process_t const proc = d->processes[name_];

    // Grab the new subblock for the process.
    config_t const proc_conf = conf->subblock(name_);

    // Reconfigure the given process normally.
    proc->reconfigure(proc_conf);
    // Overwrite any provided configuration values which may be read-only.
    proc->reconfigure_with_provides(provide_conf);
  }

  process::_reconfigure(conf);
}

process::properties_t
process_cluster
::_properties() const
{
  properties_t base_properties = process::_properties();

  base_properties.insert(property_cluster);

  return base_properties;
}

process_cluster::priv
::priv()
  : config_map()
  , processes()
  , input_mappings()
  , output_mappings()
  , internal_connections()
{
}

process_cluster::priv
::~priv()
{
}

bool
process_cluster::priv
::has_name(name_t const& name) const
{
  return processes.count(name);
}

void
process_cluster::priv
::ensure_name(name_t const& name) const
{
  if (!has_name(name))
  {
    throw no_such_process_exception(name);
  }
}

process::name_t
convert_name(process::name_t const& cluster_name, process::name_t const& process_name)
{
  static process::name_t const sep = process::name_t("/");

  process::name_t const full_name = cluster_name + sep + process_name;

  return full_name;
}

}
<|endoftext|>


<commit_before>#include <algorithm>
#include <cpr/cpr.h>
#include <tw/oauth.h>
#include <utils.h>
#include "command.h"
#include "../CommandHandler.h"
#include "../OptionParser.h"

/* full name of the command */
CMDNAME("status");
/* description of the command */
CMDDESCR("set channel status");
/* command usage synopsis */
CMDUSAGE("status [-a] STATUS");

static const std::string TWITCH_API = "https://api.twitch.tv/kraken/channels/";

static std::string curr_status(const std::string &channel, cpr::Header &head,
		std::string &err);
static std::string set_status(const std::string &channel,
		const std::string &status, cpr::Header &head,
		std::string &err);

/* status: set channel status */
std::string CommandHandler::status(struct cmdinfo *c)
{
	if (!P_ALMOD(c->privileges))
		return NO_PERM(c->nick, c->cmd);

	std::string output, status, err;
	bool append;
	cpr::Header head{{ "Accept", "application/vnd.twitchtv.v3+json" },
		{ "Authorization", "OAuth " + m_token }};

	int opt;
	OptionParser op(c->fullCmd, "a");
	static struct OptionParser::option long_opts[] = {
		{ "append", NO_ARG, 'a' },
		{ "help", NO_ARG, 'h' },
		{ 0, 0, 0 }
	};

	append = false;
	while ((opt = op.getopt_long(long_opts)) != EOF) {
		switch (opt) {
		case 'a':
			append = true;
			break;
		case 'h':
			return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR);
		case '?':
			return std::string(op.opterr());
		default:
			return "";
		}
	}

	/* get the current status if no arg provided or if appending */
	if (op.optind() == c->fullCmd.length() || append) {
		if ((status = curr_status(m_channel, head, err)).empty())
			return CMDNAME + ": " + err;
	}

	if (op.optind() == c->fullCmd.length()) {
		if (append)
			return c->cmd + ": no text to append";
		return "[STATUS] Current status for " + m_channel + " is \""
			+ status + "\".";
	}
	if (append)
		status += " ";
	status += c->fullCmd.substr(op.optind());

	if ((output = set_status(m_channel, status, head, err)).empty())
		return CMDNAME + ": " + err;
	return output;
}

/* curr_status: get current status of channel */
static std::string curr_status(const std::string &channel, cpr::Header &head,
		std::string &err)
{
	std::string out;
	cpr::Response resp;
	Json::Reader reader;
	Json::Value response;

	resp = cpr::Get(cpr::Url(TWITCH_API + channel), head);
	if (reader.parse(resp.text, response)) {
		if (response.isMember("error")) {
			err = response["error"].asString();
			std::transform(err.begin(), err.end(),
					err.begin(), tolower);
			return "";
		}
		return response["status"].asString();
	}
	err = "could not parse channel data";
	return "";
}

/* curr_status: set new status of channel */
static std::string set_status(const std::string &channel,
		const std::string &status, cpr::Header &head,
		std::string &err)
{
	std::string out, content;
	cpr::Response resp;
	Json::Reader reader;
	Json::Value response;

	out = tw::pencode(status, " ");
	std::replace(out.begin(), out.end(), ' ', '+');
	content = "channel[status]=" + out;

	resp = cpr::Put(cpr::Url(TWITCH_API + channel), cpr::Body(content),
			head);
	if (reader.parse(resp.text, response)) {
		if (response.isMember("error")) {
			err = response["error"].asString();
			std::transform(err.begin(), err.end(),
					err.begin(), tolower);
			return "";
		}
		return "[STATUS] Channel status changed to \""
			+ response["status"].asString() + "\".";
	}
	err = "could not parse channel data";
	return "";
}
<commit_msg>Fix status synopsis message<commit_after>#include <algorithm>
#include <cpr/cpr.h>
#include <tw/oauth.h>
#include <utils.h>
#include "command.h"
#include "../CommandHandler.h"
#include "../OptionParser.h"

/* full name of the command */
CMDNAME("status");
/* description of the command */
CMDDESCR("set channel status");
/* command usage synopsis */
CMDUSAGE("status [-a] [STATUS]");

static const std::string TWITCH_API = "https://api.twitch.tv/kraken/channels/";

static std::string curr_status(const std::string &channel, cpr::Header &head,
		std::string &err);
static std::string set_status(const std::string &channel,
		const std::string &status, cpr::Header &head,
		std::string &err);

/* status: set channel status */
std::string CommandHandler::status(struct cmdinfo *c)
{
	if (!P_ALMOD(c->privileges))
		return NO_PERM(c->nick, c->cmd);

	std::string output, status, err;
	bool append;
	cpr::Header head{{ "Accept", "application/vnd.twitchtv.v3+json" },
		{ "Authorization", "OAuth " + m_token }};

	int opt;
	OptionParser op(c->fullCmd, "a");
	static struct OptionParser::option long_opts[] = {
		{ "append", NO_ARG, 'a' },
		{ "help", NO_ARG, 'h' },
		{ 0, 0, 0 }
	};

	append = false;
	while ((opt = op.getopt_long(long_opts)) != EOF) {
		switch (opt) {
		case 'a':
			append = true;
			break;
		case 'h':
			return HELPMSG(CMDNAME, CMDUSAGE, CMDDESCR);
		case '?':
			return std::string(op.opterr());
		default:
			return "";
		}
	}

	/* get the current status if no arg provided or if appending */
	if (op.optind() == c->fullCmd.length() || append) {
		if ((status = curr_status(m_channel, head, err)).empty())
			return CMDNAME + ": " + err;
	}

	if (op.optind() == c->fullCmd.length()) {
		if (append)
			return c->cmd + ": no text to append";
		return "[STATUS] Current status for " + m_channel + " is \""
			+ status + "\".";
	}
	if (append)
		status += " ";
	status += c->fullCmd.substr(op.optind());

	if ((output = set_status(m_channel, status, head, err)).empty())
		return CMDNAME + ": " + err;
	return output;
}

/* curr_status: get current status of channel */
static std::string curr_status(const std::string &channel, cpr::Header &head,
		std::string &err)
{
	std::string out;
	cpr::Response resp;
	Json::Reader reader;
	Json::Value response;

	resp = cpr::Get(cpr::Url(TWITCH_API + channel), head);
	if (reader.parse(resp.text, response)) {
		if (response.isMember("error")) {
			err = response["error"].asString();
			std::transform(err.begin(), err.end(),
					err.begin(), tolower);
			return "";
		}
		return response["status"].asString();
	}
	err = "could not parse channel data";
	return "";
}

/* curr_status: set new status of channel */
static std::string set_status(const std::string &channel,
		const std::string &status, cpr::Header &head,
		std::string &err)
{
	std::string out, content;
	cpr::Response resp;
	Json::Reader reader;
	Json::Value response;

	out = tw::pencode(status, " ");
	std::replace(out.begin(), out.end(), ' ', '+');
	content = "channel[status]=" + out;

	resp = cpr::Put(cpr::Url(TWITCH_API + channel), cpr::Body(content),
			head);
	if (reader.parse(resp.text, response)) {
		if (response.isMember("error")) {
			err = response["error"].asString();
			std::transform(err.begin(), err.end(),
					err.begin(), tolower);
			return "";
		}
		return "[STATUS] Channel status changed to \""
			+ response["status"].asString() + "\".";
	}
	err = "could not parse channel data";
	return "";
}
<|endoftext|>


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

#ifndef __BASE_TIMEBUF_HH__
#define __BASE_TIMEBUF_HH__

#include <cassert>
#include <cstring>
#include <vector>

template <class T>
class TimeBuffer
{
  protected:
    int past;
    int future;
    unsigned size;
    int _id;

    char *data;
    std::vector<char *> index;
    unsigned base;

    void valid(int idx)
    {
        assert (idx >= -past && idx <= future);
    }

  public:
    friend class wire;
    class wire
    {
        friend class TimeBuffer;
      protected:
        TimeBuffer<T> *buffer;
        int index;

        void set(int idx)
        {
            buffer->valid(idx);
            index = idx;
        }

        wire(TimeBuffer<T> *buf, int i)
            : buffer(buf), index(i)
        { }

      public:
        wire()
        { }

        wire(const wire &i)
            : buffer(i.buffer), index(i.index)
        { }

        const wire &operator=(const wire &i)
        {
            buffer = i.buffer;
            set(i.index);
            return *this;
        }

        const wire &operator=(int idx)
        {
            set(idx);
            return *this;
        }

        const wire &operator+=(int offset)
        {
            set(index + offset);
            return *this;
        }

        const wire &operator-=(int offset)
        {
            set(index - offset);
            return *this;
        }

        wire &operator++()
        {
            set(index + 1);
            return *this;
        }

        wire &operator++(int)
        {
            int i = index;
            set(index + 1);
            return wire(this, i);
        }

        wire &operator--()
        {
            set(index - 1);
            return *this;
        }

        wire &operator--(int)
        {
            int i = index;
            set(index - 1);
            return wire(this, i);
        }
        T &operator*() const { return *buffer->access(index); }
        T *operator->() const { return buffer->access(index); }
    };

  public:
    TimeBuffer(int p, int f)
        : past(p), future(f), size(past + future + 1),
          data(new char[size * sizeof(T)]), index(size), base(0)
    {
        assert(past >= 0 && future >= 0);
        char *ptr = data;
        for (unsigned i = 0; i < size; i++) {
            index[i] = ptr;
            std::memset(ptr, 0, sizeof(T));
            new (ptr) T;
            ptr += sizeof(T);
        }

        _id = -1;
    }

    TimeBuffer()
        : data(NULL)
    {
    }

    ~TimeBuffer()
    {
        for (unsigned i = 0; i < size; ++i)
            (reinterpret_cast<T *>(index[i]))->~T();
        delete [] data;
    }

    void id(int id)
    {
        _id = id;
    }

    int id()
    {
        return _id;
    }

    void
    advance()
    {
        if (++base >= size)
            base = 0;

        int ptr = base + future;
        if (ptr >= (int)size)
            ptr -= size;
        (reinterpret_cast<T *>(index[ptr]))->~T();
        std::memset(index[ptr], 0, sizeof(T));
        new (index[ptr]) T;
    }

    T *access(int idx)
    {
        //Need more complex math here to calculate index.
        valid(idx);

        int vector_index = idx + base;
        if (vector_index >= (int)size) {
            vector_index -= size;
        } else if (vector_index < 0) {
            vector_index += size;
        }

        return reinterpret_cast<T *>(index[vector_index]);
    }

    T &operator[](int idx)
    {
        //Need more complex math here to calculate index.
        valid(idx);

        int vector_index = idx + base;
        if (vector_index >= (int)size) {
            vector_index -= size;
        } else if (vector_index < 0) {
            vector_index += size;
        }

        return reinterpret_cast<T &>(*index[vector_index]);
    }

    wire getWire(int idx)
    {
        valid(idx);

        return wire(this, idx);
    }

    wire zero()
    {
        return wire(this, 0);
    }

    unsigned getSize()
    {
        return size;
    }
};

#endif // __BASE_TIMEBUF_HH__

<commit_msg>cpu: Timebuf const accessors<commit_after>/*
 * Copyright (c) 2004-2005 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Nathan Binkert
 *          Kevin Lim
 */

#ifndef __BASE_TIMEBUF_HH__
#define __BASE_TIMEBUF_HH__

#include <cassert>
#include <cstring>
#include <vector>

template <class T>
class TimeBuffer
{
  protected:
    int past;
    int future;
    unsigned size;
    int _id;

    char *data;
    std::vector<char *> index;
    unsigned base;

    void valid(int idx) const
    {
        assert (idx >= -past && idx <= future);
    }

  public:
    friend class wire;
    class wire
    {
        friend class TimeBuffer;
      protected:
        TimeBuffer<T> *buffer;
        int index;

        void set(int idx)
        {
            buffer->valid(idx);
            index = idx;
        }

        wire(TimeBuffer<T> *buf, int i)
            : buffer(buf), index(i)
        { }

      public:
        wire()
        { }

        wire(const wire &i)
            : buffer(i.buffer), index(i.index)
        { }

        const wire &operator=(const wire &i)
        {
            buffer = i.buffer;
            set(i.index);
            return *this;
        }

        const wire &operator=(int idx)
        {
            set(idx);
            return *this;
        }

        const wire &operator+=(int offset)
        {
            set(index + offset);
            return *this;
        }

        const wire &operator-=(int offset)
        {
            set(index - offset);
            return *this;
        }

        wire &operator++()
        {
            set(index + 1);
            return *this;
        }

        wire &operator++(int)
        {
            int i = index;
            set(index + 1);
            return wire(this, i);
        }

        wire &operator--()
        {
            set(index - 1);
            return *this;
        }

        wire &operator--(int)
        {
            int i = index;
            set(index - 1);
            return wire(this, i);
        }
        T &operator*() const { return *buffer->access(index); }
        T *operator->() const { return buffer->access(index); }
    };

  public:
    TimeBuffer(int p, int f)
        : past(p), future(f), size(past + future + 1),
          data(new char[size * sizeof(T)]), index(size), base(0)
    {
        assert(past >= 0 && future >= 0);
        char *ptr = data;
        for (unsigned i = 0; i < size; i++) {
            index[i] = ptr;
            std::memset(ptr, 0, sizeof(T));
            new (ptr) T;
            ptr += sizeof(T);
        }

        _id = -1;
    }

    TimeBuffer()
        : data(NULL)
    {
    }

    ~TimeBuffer()
    {
        for (unsigned i = 0; i < size; ++i)
            (reinterpret_cast<T *>(index[i]))->~T();
        delete [] data;
    }

    void id(int id)
    {
        _id = id;
    }

    int id()
    {
        return _id;
    }

    void
    advance()
    {
        if (++base >= size)
            base = 0;

        int ptr = base + future;
        if (ptr >= (int)size)
            ptr -= size;
        (reinterpret_cast<T *>(index[ptr]))->~T();
        std::memset(index[ptr], 0, sizeof(T));
        new (index[ptr]) T;
    }

  protected:
    //Calculate the index into this->index for element at position idx
    //relative to now
    inline int calculateVectorIndex(int idx) const
    {
        //Need more complex math here to calculate index.
        valid(idx);

        int vector_index = idx + base;
        if (vector_index >= (int)size) {
            vector_index -= size;
        } else if (vector_index < 0) {
            vector_index += size;
        }

        return vector_index;
    }

  public:
    T *access(int idx)
    {
        int vector_index = calculateVectorIndex(idx);

        return reinterpret_cast<T *>(index[vector_index]);
    }

    T &operator[](int idx)
    {
        int vector_index = calculateVectorIndex(idx);

        return reinterpret_cast<T &>(*index[vector_index]);
    }

    const T &operator[] (int idx) const
    {
        int vector_index = calculateVectorIndex(idx);

        return reinterpret_cast<const T &>(*index[vector_index]);
    }

    wire getWire(int idx)
    {
        valid(idx);

        return wire(this, idx);
    }

    wire zero()
    {
        return wire(this, 0);
    }

    unsigned getSize()
    {
        return size;
    }
};

#endif // __BASE_TIMEBUF_HH__

<|endoftext|>


<commit_before>#include "Generator/Generator.h"

#include "Config.h"
#include "Utils/Utils.h"
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <getopt.h>
#include <cstdio>
#include <iostream>

/*! dalec

    The main compiler executable, responsible for organising the
    arguments for Generator, running Generator, and assembling/linking
    the results together using the system's compiler.
*/

using namespace dale;

static const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR";
static const size_t COPY_SIZE = 8192;

static bool
appearsToBeLib(const char *str)
{
    int len = strlen(str);
    if (len >= 2) {
        const char *end = str + (len - 2);
        if ((!strcmp(end, ".o")) || (!strcmp(end, ".a"))) {
            return true;
        }
    }
    return false;
}

static void
joinWithPrefix(std::vector<const char*> *strings, const char *prefix,
               std::string *buffer)
{
    for (std::vector<const char*>::iterator b = strings->begin(),
                                            e = strings->end();
            b != e;
            ++b) {
        buffer->append(" ");
        buffer->append(prefix);
        buffer->append(" ");
        buffer->append(*b);
    }
}

static void
copyFile(const char *to_path, FILE *from)
{
    FILE *to = fopen(to_path, "w");
    if (!to) {
        error("unable to open %s for writing", to_path, true);
    }
    static char buf[COPY_SIZE];  /* on heap, not stack */
    memset(buf, 0, COPY_SIZE);
    size_t bytes;
    size_t wbytes;

    int res = fseek(from, SEEK_SET, 0);
    if (res != 0) {
        error("unable to seek in temporary file", true);
    }

    while ((bytes = fread(buf, (size_t) 1, (size_t) COPY_SIZE, from))) {
        if (ferror(from)) {
            fclose(from);
            fclose(to);
            error("unable to read temporary file", true);
        }
        wbytes = fwrite(buf, (size_t) 1, bytes, to);
        if (wbytes != bytes) {
            if (ferror(from)) {
                error("unable to copy temporary file content", true);
            }
            if (ferror(to)) {
                error("unable to copy temporary file content", true);
            }
        }
        if (bytes != COPY_SIZE) {
            if (feof(from)) {
                break;
            } else {
                error("unable to copy temporary file content", true);
            }
        }
        memset(buf, 0, COPY_SIZE);
    }

    res = fflush(to);
    if (res != 0) {
        error("unable to flush temporary file (copy)", true);
    }
    res = fclose(from);
    if (res != 0) {
        error("unable to close temporary file (copy from)", true);
    }
    res = fclose(to);
    if (res != 0) {
        error("unable to close temporary file (copy to)", true);
    }

    return;
}

int
main(int argc, char **argv)
{
    srand(time(NULL) + getpid());

    progname = argv[0];

    int opt;
    char optc;

    std::vector<const char*> input_files;
    std::vector<const char*> input_link_files;
    std::vector<const char*> compile_libs;
    std::vector<const char*> run_libs;
    std::vector<const char*> include_paths;
    std::vector<const char*> run_paths;
    std::vector<const char*> bitcode_paths;
    std::vector<const char*> static_modules;
    std::vector<const char*> module_paths;

    std::string output_path;
    const char *output_path_arg = NULL;
    const char *module_name     = NULL;

    int produce  = ASM;
    int optlevel = 0;

    int produce_set      = 0;
    int no_linking       = 0;
    int debug            = 0;
    int no_dale_stdlib   = 0;
    int no_stdlib        = 0;
    int remove_macros    = 0;
    int no_common        = 0;
    int static_mods_all  = 0;
    int found_sm         = 0;
    int enable_cto       = 0;
    int version          = 0;
    int print_expansions = 0;

    int option_index         = 0;
    int forced_remove_macros = 0;

    static struct option long_options[] = {
        { "no-dale-stdlib",   no_argument,       &no_dale_stdlib,   1 },
        { "no-common",        no_argument,       &no_common,        1 },
        { "no-stdlib",        no_argument,       &no_stdlib,        1 },
        { "static-modules",   no_argument,       &static_mods_all,  1 },
        { "static-module",    required_argument, &found_sm,         1 },
        { "enable-cto",       no_argument,       &enable_cto,       1 },
        { "version",          no_argument,       &version,          1 },
        { "print-expansions", no_argument,       &print_expansions, 1 },
        { 0, 0, 0, 0 }
    };

    if (argc < 2) {
        error("no input files");
    }

    while ((opt = getopt_long(argc, argv, options,
                              long_options, &option_index)) != -1) {
        optc = (char) opt;

        switch (optc) {
            case 'o': {
                if (output_path_arg) {
                    error("an output path has already been specified");
                }
                output_path_arg = optarg;
                break;
            }
            case 'O': {
                optlevel = (optarg[0] - '0');
                if ((optlevel < 0) || (optlevel > 4)) {
                    error("invalid optimisation level");
                }
                break;
            }
            case 's': {
                const char *type = optarg;
                if (!strcmp(type, "as")) {
                    produce = ASM;
                } else if (!strcmp(type, "ir")) {
                    produce = IR;
                } else if (!strcmp(type, "bc")) {
                    produce = BitCode;
                } else {
                    error("unrecognised output option");
                }
                produce_set = true;
                break;
            }
            case 'd': debug = 1;                                   break;
            case 'c': no_linking = 1;                              break;
            case 'r': remove_macros = 1; forced_remove_macros = 1; break;
            case 'R': remove_macros = 0; forced_remove_macros = 1; break;
            case 'I': include_paths.push_back(optarg);             break;
            case 'a': compile_libs.push_back(optarg);              break;
            case 'L': run_paths.push_back(optarg);                 break;
            case 'l': run_libs.push_back(optarg);                  break;
            case 'b': bitcode_paths.push_back(optarg);             break;
            case 'M': module_paths.push_back(optarg);              break;
            case 'm': module_name = optarg;                        break;
        };

        if (found_sm) {
            found_sm = 0;
            static_modules.push_back(optarg);
        }
    }

    if (version) {
        printf("%d.%d\n", DALE_VERSION_MAJOR, DALE_VERSION_MINOR);
        exit(0);
    }

    /* If the user wants an executable and has not specified either
     * way with respect to removing macros, then remove macros. */
    if (!no_linking && !produce_set && !forced_remove_macros) {
        remove_macros = 1;
    }

    /* Every argument after the options is treated as an input file.
     * Input files that end with .o or .a should go straight to the
     * linker. */
    int input_file_count = argc - optind;
    for (int i = 0; i < input_file_count; ++i) {
        const char *input_file = argv[optind + i];
        if (appearsToBeLib(input_file)) {
            input_link_files.push_back(input_file);
        } else {
            input_files.push_back(input_file);
        }
    }

    if (!input_files.size()) {
        error("no input files");
    }

    /* Set output_path. */
    if (!no_linking) {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            if (produce == ASM) {
                output_path.append("a.out");
            } else if (produce_set) {
                output_path.append(input_files[0]);
                output_path.append(
                      (produce == IR)      ? ".ll"
                    : (produce == ASM)     ? ".s"
                    : (produce == BitCode) ? ".bc"
                                           : ".unknown"
                );
            }
        }
    } else {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            output_path.append(input_files[0]);
            output_path.append(".o");
        }
    }

    std::string compile_lib_str;
    joinWithPrefix(&compile_libs, "-l", &compile_lib_str);

    std::string include_path_str;
    joinWithPrefix(&include_paths, "-I", &include_path_str);

    std::string run_path_str;
    joinWithPrefix(&run_paths, "-L", &run_path_str);

    std::string input_file_str;
    joinWithPrefix(&input_files, " ", &input_file_str);

    std::string input_link_file_str;
    joinWithPrefix(&input_link_files, " ", &input_link_file_str);

    FILE *output_file = tmpfile();
    if (!output_file) {
        error("unable to open temporary file", true);
    }
    std::vector<std::string> so_paths;
    Generator generator;

    bool generated =
        generator.run(&input_files,
                      &bitcode_paths,
                      &compile_libs,
                      &include_paths,
                      &module_paths,
                      &static_modules,
                      module_name,
                      debug,
                      produce,
                      optlevel,
                      remove_macros,
                      no_common,
                      no_dale_stdlib,
                      static_mods_all,
                      enable_cto,
                      print_expansions,
                      &so_paths,
                      output_file);
    if (!generated) {
        exit(1);
    }
    int res = fflush(output_file);
    if (res != 0) {
        error("unable to flush temporary file", true);
    }

    std::string run_lib_str;
    joinWithPrefix(&run_libs, " -l ", &run_lib_str);

    std::string rpath_str;
    if (!strcmp(SYSTEM_NAME, "Darwin")) {
        joinWithPrefix(&module_paths, "-rpath", &rpath_str);
    } else {
        rpath_str = "";
    }

    for (std::vector<std::string>::reverse_iterator b = so_paths.rbegin(),
                                                    e = so_paths.rend();
            b != e;
            ++b) {
        input_link_file_str.append(" ");
        input_link_file_str.append((*b).c_str());
    }

    std::string intermediate_output_path = output_path;
    if (!produce_set) {
        intermediate_output_path.append(".s");
    }
    copyFile(intermediate_output_path.c_str(), output_file);
    if (produce_set) {
        exit(0);
    }

    // compose the compiler/linker command and execute it
    const char *aux = getenv ("DALE_CC_FLAGS");  // auxiliary options
    std::string compile_cmd = DALE_CC;
    if (no_stdlib) compile_cmd += " --nostdlib";
    if (no_linking) compile_cmd += " -c";
    else compile_cmd += strcmp (SYSTEM_NAME, "Darwin")
           ? " -Wl,--gc-sections" : "";
    compile_cmd += run_path_str + rpath_str;
    if (no_linking) compile_cmd += run_lib_str;
    compile_cmd += " " + intermediate_output_path;
    if (! no_linking)
      compile_cmd += input_link_file_str + run_lib_str + " -lm";
    compile_cmd += " -o " + output_path;
    if (aux) compile_cmd += " ", compile_cmd += aux;

    if (aux) std::cerr << "Going to run: " << compile_cmd << std::endl,
               fflush (stderr);  // show it immediately

    int status = system (compile_cmd.c_str ());
    if (status != 0) {
        if (debug) {
          std::cerr << compile_cmd << std::endl;
        }
        error(DALE_CC " failed");
    }

    status = remove(intermediate_output_path.c_str());
    if (status != 0) {
        if (debug) {
          std::cerr << intermediate_output_path << std::endl;
        }
        error("unable to remove temporary file");
    }

    return 0;
}
<commit_msg>dalec: optimizing the path strings generation<commit_after>#include "Generator/Generator.h"

#include "Config.h"
#include "Utils/Utils.h"
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/stat.h>
#include <getopt.h>
#include <cstdio>
#include <iostream>

/*! dalec

    The main compiler executable, responsible for organising the
    arguments for Generator, running Generator, and assembling/linking
    the results together using the system's compiler.
*/

using namespace dale;

static const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR";
static const size_t COPY_SIZE = 8192;

static bool
appearsToBeLib(const char *str)
{
    int len = strlen(str);
    if (len >= 2) {
        const char *end = str + (len - 2);
        if ((!strcmp(end, ".o")) || (!strcmp(end, ".a"))) {
            return true;
        }
    }
    return false;
}

std::string
joinWithPrefix (std::vector<const char*> strings,
                const std::string prefix, std::string buffer)
{
  for (std::vector<const char*>::iterator b = strings.begin (),
                                          e = strings.end ();
       b != e; buffer += " " + prefix + " " + (* b ++));

  return buffer;
}

static void
copyFile(const char *to_path, FILE *from)
{
    FILE *to = fopen(to_path, "w");
    if (!to) {
        error("unable to open %s for writing", to_path, true);
    }
    static char buf[COPY_SIZE];  /* on heap, not stack */
    memset(buf, 0, COPY_SIZE);
    size_t bytes;
    size_t wbytes;

    int res = fseek(from, SEEK_SET, 0);
    if (res != 0) {
        error("unable to seek in temporary file", true);
    }

    while ((bytes = fread(buf, (size_t) 1, (size_t) COPY_SIZE, from))) {
        if (ferror(from)) {
            fclose(from);
            fclose(to);
            error("unable to read temporary file", true);
        }
        wbytes = fwrite(buf, (size_t) 1, bytes, to);
        if (wbytes != bytes) {
            if (ferror(from)) {
                error("unable to copy temporary file content", true);
            }
            if (ferror(to)) {
                error("unable to copy temporary file content", true);
            }
        }
        if (bytes != COPY_SIZE) {
            if (feof(from)) {
                break;
            } else {
                error("unable to copy temporary file content", true);
            }
        }
        memset(buf, 0, COPY_SIZE);
    }

    res = fflush(to);
    if (res != 0) {
        error("unable to flush temporary file (copy)", true);
    }
    res = fclose(from);
    if (res != 0) {
        error("unable to close temporary file (copy from)", true);
    }
    res = fclose(to);
    if (res != 0) {
        error("unable to close temporary file (copy to)", true);
    }

    return;
}

int
main(int argc, char **argv)
{
    srand(time(NULL) + getpid());

    progname = argv[0];

    int opt;
    char optc;

    std::vector<const char*>
      input_files,
      input_link_files,
      compile_libs,
      run_libs,
      include_paths,
      run_paths,
      bitcode_paths,
      static_modules,
      module_paths;

    std::string output_path;
    const char *output_path_arg = NULL;
    const char *module_name     = NULL;

    int produce  = ASM;
    int optlevel = 0;

    int produce_set      = 0;
    int no_linking       = 0;
    int debug            = 0;
    int no_dale_stdlib   = 0;
    int no_stdlib        = 0;
    int remove_macros    = 0;
    int no_common        = 0;
    int static_mods_all  = 0;
    int found_sm         = 0;
    int enable_cto       = 0;
    int version          = 0;
    int print_expansions = 0;

    int option_index         = 0;
    int forced_remove_macros = 0;

    static struct option long_options[] = {
        { "no-dale-stdlib",   no_argument,       &no_dale_stdlib,   1 },
        { "no-common",        no_argument,       &no_common,        1 },
        { "no-stdlib",        no_argument,       &no_stdlib,        1 },
        { "static-modules",   no_argument,       &static_mods_all,  1 },
        { "static-module",    required_argument, &found_sm,         1 },
        { "enable-cto",       no_argument,       &enable_cto,       1 },
        { "version",          no_argument,       &version,          1 },
        { "print-expansions", no_argument,       &print_expansions, 1 },
        { 0, 0, 0, 0 }
    };

    if (argc < 2) {
        error("no input files");
    }

    while ((opt = getopt_long(argc, argv, options,
                              long_options, &option_index)) != -1) {
        optc = (char) opt;

        switch (optc) {
            case 'o': {
                if (output_path_arg) {
                    error("an output path has already been specified");
                }
                output_path_arg = optarg;
                break;
            }
            case 'O': {
                optlevel = (optarg[0] - '0');
                if ((optlevel < 0) || (optlevel > 4)) {
                    error("invalid optimisation level");
                }
                break;
            }
            case 's': {
                const char *type = optarg;
                if (!strcmp(type, "as")) {
                    produce = ASM;
                } else if (!strcmp(type, "ir")) {
                    produce = IR;
                } else if (!strcmp(type, "bc")) {
                    produce = BitCode;
                } else {
                    error("unrecognised output option");
                }
                produce_set = true;
                break;
            }
            case 'd': debug = 1;                                   break;
            case 'c': no_linking = 1;                              break;
            case 'r': remove_macros = 1; forced_remove_macros = 1; break;
            case 'R': remove_macros = 0; forced_remove_macros = 1; break;
            case 'I': include_paths.push_back(optarg);             break;
            case 'a': compile_libs.push_back(optarg);              break;
            case 'L': run_paths.push_back(optarg);                 break;
            case 'l': run_libs.push_back(optarg);                  break;
            case 'b': bitcode_paths.push_back(optarg);             break;
            case 'M': module_paths.push_back(optarg);              break;
            case 'm': module_name = optarg;                        break;
        };

        if (found_sm) {
            found_sm = 0;
            static_modules.push_back(optarg);
        }
    }

    if (version) {
        printf("%d.%d\n", DALE_VERSION_MAJOR, DALE_VERSION_MINOR);
        exit(0);
    }

    /* If the user wants an executable and has not specified either
     * way with respect to removing macros, then remove macros. */
    if (!no_linking && !produce_set && !forced_remove_macros) {
        remove_macros = 1;
    }

    /* Every argument after the options is treated as an input file.
     * Input files that end with .o or .a should go straight to the
     * linker. */
    int input_file_count = argc - optind;
    for (int i = 0; i < input_file_count; ++i) {
        const char *input_file = argv[optind + i];
        if (appearsToBeLib(input_file)) {
            input_link_files.push_back(input_file);
        } else {
            input_files.push_back(input_file);
        }
    }

    if (!input_files.size()) {
        error("no input files");
    }

    /* Set output_path. */
    if (!no_linking) {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            if (produce == ASM) {
                output_path.append("a.out");
            } else if (produce_set) {
                output_path.append(input_files[0]);
                output_path.append(
                      (produce == IR)      ? ".ll"
                    : (produce == ASM)     ? ".s"
                    : (produce == BitCode) ? ".bc"
                                           : ".unknown"
                );
            }
        }
    } else {
        if (output_path_arg) {
            output_path.append(output_path_arg);
        } else {
            output_path.append(input_files[0]);
            output_path.append(".o");
        }
    }

    FILE *output_file = tmpfile();
    if (!output_file) {
        error("unable to open temporary file", true);
    }
    std::vector<std::string> so_paths;
    Generator generator;

    bool generated =
        generator.run(&input_files,
                      &bitcode_paths,
                      &compile_libs,
                      &include_paths,
                      &module_paths,
                      &static_modules,
                      module_name,
                      debug,
                      produce,
                      optlevel,
                      remove_macros,
                      no_common,
                      no_dale_stdlib,
                      static_mods_all,
                      enable_cto,
                      print_expansions,
                      &so_paths,
                      output_file);
    if (!generated) {
        exit(1);
    }
    int res = fflush(output_file);
    if (res != 0) {
        error("unable to flush temporary file", true);
    }

    std::string intermediate_output_path = output_path;
    if (!produce_set) {
        intermediate_output_path.append(".s");
    }
    copyFile(intermediate_output_path.c_str(), output_file);
    if (produce_set) {
        exit(0);
    }

    // prepare the strings to sew the compile command with
    std::string input_file_str =
      joinWithPrefix (input_files, " ", "");
    std::string compile_lib_str =
      joinWithPrefix (compile_libs, "-l", "");
    std::string include_path_str =
      joinWithPrefix (include_paths, "-I", "");
    std::string run_path_str =
      joinWithPrefix (run_paths, "-L", "");
    std::string run_lib_str =
      joinWithPrefix (run_libs, "-l", "");
    std::string rpath_str = strcmp (SYSTEM_NAME, "Darwin") ?
      "" : joinWithPrefix (module_paths, "-rpath", "");

    std::string input_link_file_str =
      joinWithPrefix (input_link_files, " ", "");
    for (std::vector<std::string>::iterator b = so_paths.begin (),
                                            e = so_paths.end ();
         b != e; input_link_file_str += " " + (* b ++));

    // compose the compiler/linker command and execute it
    const char *aux = getenv ("DALE_CC_FLAGS");  // auxiliary options
    std::string compile_cmd = DALE_CC;
    if (no_stdlib) compile_cmd += " --nostdlib";
    if (no_linking) compile_cmd += " -c";
    else compile_cmd += strcmp (SYSTEM_NAME, "Darwin")
           ? " -Wl,--gc-sections" : "";
    compile_cmd += run_path_str + rpath_str;
    if (no_linking) compile_cmd += run_lib_str;
    compile_cmd += " " + intermediate_output_path;
    if (! no_linking)
      compile_cmd += input_link_file_str + run_lib_str + " -lm";
    compile_cmd += " -o " + output_path;
    if (aux) compile_cmd += " ", compile_cmd += aux;

    if (aux) std::cerr << "Going to run: " << compile_cmd << std::endl,
               fflush (stderr);  // show it immediately

    int status = system (compile_cmd.c_str ());
    if (status != 0) {
        if (debug) {
          std::cerr << compile_cmd << std::endl;
        }
        error(DALE_CC " failed");
    }

    status = remove(intermediate_output_path.c_str());
    if (status != 0) {
        if (debug) {
          std::cerr << intermediate_output_path << std::endl;
        }
        error("unable to remove temporary file");
    }

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textwindowpeer.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2007-09-05 17:38:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include <svtools/textwindowpeer.hxx>

#ifndef _TEXTVIEW_HXX
#include <svtools/textview.hxx>
#endif

#ifndef SVTOOLS_ACCESSIBLE_FACTORY_ACCESS_HXX
#include "svtaccessiblefactory.hxx"
#endif

namespace css = ::com::sun::star;

namespace svt
{
    TextWindowPeer::TextWindowPeer(::TextView & rView, bool bCompoundControlChild):
        m_rEngine(*rView.GetTextEngine()), m_rView(rView), m_bCompoundControlChild(bCompoundControlChild)
    {
        SetWindow(rView.GetWindow());
        m_pFactoryAccess.reset( new AccessibleFactoryAccess );
    }

    // virtual
    TextWindowPeer::~TextWindowPeer()
    {
    }

    ::css::uno::Reference< ::css::accessibility::XAccessibleContext > TextWindowPeer::CreateAccessibleContext()
    {
        return m_pFactoryAccess->getFactory().createAccessibleTextWindowContext(
            this, m_rEngine, m_rView, m_bCompoundControlChild
        );
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.170); FILE MERGED 2008/04/01 12:43:32 thb 1.6.170.2: #i85898# Stripping all external header guards 2008/03/31 13:01:52 rt 1.6.170.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: textwindowpeer.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include <svtools/textwindowpeer.hxx>
#include <svtools/textview.hxx>
#include "svtaccessiblefactory.hxx"

namespace css = ::com::sun::star;

namespace svt
{
    TextWindowPeer::TextWindowPeer(::TextView & rView, bool bCompoundControlChild):
        m_rEngine(*rView.GetTextEngine()), m_rView(rView), m_bCompoundControlChild(bCompoundControlChild)
    {
        SetWindow(rView.GetWindow());
        m_pFactoryAccess.reset( new AccessibleFactoryAccess );
    }

    // virtual
    TextWindowPeer::~TextWindowPeer()
    {
    }

    ::css::uno::Reference< ::css::accessibility::XAccessibleContext > TextWindowPeer::CreateAccessibleContext()
    {
        return m_pFactoryAccess->getFactory().createAccessibleTextWindowContext(
            this, m_rEngine, m_rView, m_bCompoundControlChild
        );
    }
}
<|endoftext|>