<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "SubtitleTrack.h"

#include "Media.h"

namespace medialibrary
{

const std::string SubtitleTrack::Table::Name = "SubtitleTrack";
const std::string SubtitleTrack::Table::PrimaryKeyColumn = "id_track";
int64_t SubtitleTrack::* const SubtitleTrack::Table::PrimaryKey = &SubtitleTrack::m_id;

SubtitleTrack::SubtitleTrack( MediaLibraryPtr, sqlite::Row& row )
    : m_id( row.extract<decltype(m_id)>() )
    , m_codec( row.extract<decltype(m_codec)>() )
    , m_language( row.extract<decltype(m_language)>() )
    , m_description( row.extract<decltype(m_description)>() )
    , m_encoding( row.extract<decltype(m_encoding)>() )
{
    // Ensure there is a media id to load
    assert( row.extract<int64_t>() );
    assert( row.hasRemainingColumns() == false );
}

SubtitleTrack::SubtitleTrack( MediaLibraryPtr, std::string codec,
                              std::string language, std::string description,
                              std::string encoding )
    : m_id( 0 )
    , m_codec( std::move( codec ) )
    , m_language( std::move( language ) )
    , m_description( std::move( description ) )
    , m_encoding( std::move( encoding ) )
{
}

int64_t SubtitleTrack::id() const
{
    return m_id;
}

const std::string&SubtitleTrack::codec() const
{
    return m_codec;
}

const std::string&SubtitleTrack::language() const
{
    return m_language;
}

const std::string&SubtitleTrack::description() const
{
    return m_description;
}

const std::string&SubtitleTrack::encoding() const
{
    return m_encoding;
}

void SubtitleTrack::createTable( sqlite::Connection* dbConnection )
{
    sqlite::Tools::executeRequest( dbConnection,
                                   schema( Table::Name, Settings::DbModelVersion ) );
}

void SubtitleTrack::createIndexes( sqlite::Connection* dbConnection )
{
    sqlite::Tools::executeRequest( dbConnection,
                                   index( Indexes::MediaId, Settings::DbModelVersion ) );
}

std::string SubtitleTrack::schema( const std::string& tableName, uint32_t )
{
    assert( tableName == Table::Name );
    return "CREATE TABLE " + Table::Name +
    "(" +
        Table::PrimaryKeyColumn + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        "codec TEXT,"
        "language TEXT,"
        "description TEXT,"
        "encoding TEXT,"
        "media_id UNSIGNED INT,"
        "FOREIGN KEY(media_id) REFERENCES " + Media::Table::Name +
            "(id_media) ON DELETE CASCADE"
    ")";
}

std::string SubtitleTrack::index( Indexes index, uint32_t dbModel )
{
    assert( index == Indexes::MediaId );
    return "CREATE INDEX " + indexName( index, dbModel ) +
           " ON " + Table::Name + "(media_id)";
}

std::string SubtitleTrack::indexName( Indexes index, uint32_t )
{
    assert( index == Indexes::MediaId );
    return "subtitle_track_media_idx";
}

bool SubtitleTrack::checkDbModel( MediaLibraryPtr ml )
{
    return sqlite::Tools::checkTableSchema( ml->getConn(),
                                       schema( Table::Name, Settings::DbModelVersion ),
                                       Table::Name );
}

std::shared_ptr<SubtitleTrack> SubtitleTrack::create( MediaLibraryPtr ml,
            std::string codec, std::string language, std::string description,
            std::string encoding, int64_t mediaId )
{
    const std::string req = "INSERT INTO " + Table::Name + "(codec, language,"
            "description, encoding, media_id) VALUES(?, ?, ?, ?, ?)";
    auto track = std::make_shared<SubtitleTrack>( ml, std::move( codec ),
                    std::move( language ), std::move( description ),
                    std::move( encoding ) );
    if ( insert( ml, track, req, track->codec(), track->language(),
                 track->description(), track->encoding(), mediaId ) == false )
        return nullptr;
    return track;
}

bool SubtitleTrack::removeFromMedia( MediaLibraryPtr ml, int64_t mediaId )
{
    static const std::string req = "DELETE FROM " + Table::Name + " "
            "WHERE media_id = ?";
    return sqlite::Tools::executeDelete( ml->getConn(), req, mediaId );
}

}
<commit_msg>SubtitleTrack: Check index as part of integrity checks<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "SubtitleTrack.h"

#include "Media.h"

namespace medialibrary
{

const std::string SubtitleTrack::Table::Name = "SubtitleTrack";
const std::string SubtitleTrack::Table::PrimaryKeyColumn = "id_track";
int64_t SubtitleTrack::* const SubtitleTrack::Table::PrimaryKey = &SubtitleTrack::m_id;

SubtitleTrack::SubtitleTrack( MediaLibraryPtr, sqlite::Row& row )
    : m_id( row.extract<decltype(m_id)>() )
    , m_codec( row.extract<decltype(m_codec)>() )
    , m_language( row.extract<decltype(m_language)>() )
    , m_description( row.extract<decltype(m_description)>() )
    , m_encoding( row.extract<decltype(m_encoding)>() )
{
    // Ensure there is a media id to load
    assert( row.extract<int64_t>() );
    assert( row.hasRemainingColumns() == false );
}

SubtitleTrack::SubtitleTrack( MediaLibraryPtr, std::string codec,
                              std::string language, std::string description,
                              std::string encoding )
    : m_id( 0 )
    , m_codec( std::move( codec ) )
    , m_language( std::move( language ) )
    , m_description( std::move( description ) )
    , m_encoding( std::move( encoding ) )
{
}

int64_t SubtitleTrack::id() const
{
    return m_id;
}

const std::string&SubtitleTrack::codec() const
{
    return m_codec;
}

const std::string&SubtitleTrack::language() const
{
    return m_language;
}

const std::string&SubtitleTrack::description() const
{
    return m_description;
}

const std::string&SubtitleTrack::encoding() const
{
    return m_encoding;
}

void SubtitleTrack::createTable( sqlite::Connection* dbConnection )
{
    sqlite::Tools::executeRequest( dbConnection,
                                   schema( Table::Name, Settings::DbModelVersion ) );
}

void SubtitleTrack::createIndexes( sqlite::Connection* dbConnection )
{
    sqlite::Tools::executeRequest( dbConnection,
                                   index( Indexes::MediaId, Settings::DbModelVersion ) );
}

std::string SubtitleTrack::schema( const std::string& tableName, uint32_t )
{
    assert( tableName == Table::Name );
    return "CREATE TABLE " + Table::Name +
    "(" +
        Table::PrimaryKeyColumn + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        "codec TEXT,"
        "language TEXT,"
        "description TEXT,"
        "encoding TEXT,"
        "media_id UNSIGNED INT,"
        "FOREIGN KEY(media_id) REFERENCES " + Media::Table::Name +
            "(id_media) ON DELETE CASCADE"
    ")";
}

std::string SubtitleTrack::index( Indexes index, uint32_t dbModel )
{
    assert( index == Indexes::MediaId );
    return "CREATE INDEX " + indexName( index, dbModel ) +
           " ON " + Table::Name + "(media_id)";
}

std::string SubtitleTrack::indexName( Indexes index, uint32_t )
{
    assert( index == Indexes::MediaId );
    return "subtitle_track_media_idx";
}

bool SubtitleTrack::checkDbModel( MediaLibraryPtr ml )
{
    return sqlite::Tools::checkTableSchema( ml->getConn(),
                                       schema( Table::Name, Settings::DbModelVersion ),
                                       Table::Name ) &&
           sqlite::Tools::checkIndexStatement( ml->getConn(),
                index( Indexes::MediaId, Settings::DbModelVersion ),
                indexName( Indexes::MediaId, Settings::DbModelVersion ) );
}

std::shared_ptr<SubtitleTrack> SubtitleTrack::create( MediaLibraryPtr ml,
            std::string codec, std::string language, std::string description,
            std::string encoding, int64_t mediaId )
{
    const std::string req = "INSERT INTO " + Table::Name + "(codec, language,"
            "description, encoding, media_id) VALUES(?, ?, ?, ?, ?)";
    auto track = std::make_shared<SubtitleTrack>( ml, std::move( codec ),
                    std::move( language ), std::move( description ),
                    std::move( encoding ) );
    if ( insert( ml, track, req, track->codec(), track->language(),
                 track->description(), track->encoding(), mediaId ) == false )
        return nullptr;
    return track;
}

bool SubtitleTrack::removeFromMedia( MediaLibraryPtr ml, int64_t mediaId )
{
    static const std::string req = "DELETE FROM " + Table::Name + " "
            "WHERE media_id = ?";
    return sqlite::Tools::executeDelete( ml->getConn(), req, mediaId );
}

}
<|endoftext|>


<commit_before>// Copyright 2008 the V8 project authors. 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 Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by the SCons build script so their names
// cannot be changed without changing the SCons build script.
#define MAJOR_VERSION     2
#define MINOR_VERSION     0
#define BUILD_NUMBER      7
#define PATCH_LEVEL       0
#define CANDIDATE_VERSION true

// Define SONAME to have the SCons build the put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the SCons build script.
#define SONAME            ""

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = CANDIDATE_VERSION;
const char* Version::soname_ = SONAME;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
  if (GetPatch() > 0) {
    OS::SNPrintF(str, "%d.%d.%d.%d%s",
                 GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
  } else {
    OS::SNPrintF(str, "%d.%d.%d%s",
                 GetMajor(), GetMinor(), GetBuild(), candidate);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    OS::SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>Change the candidate version on bleeding_edge from 2.0.7 to  2.1.0. This means that the next version pushed to trunk will be the first version in the 2.1.x series.  Review URL: http://codereview.chromium.org/551139<commit_after>// Copyright 2008 the V8 project authors. 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 Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by the SCons build script so their names
// cannot be changed without changing the SCons build script.
#define MAJOR_VERSION     2
#define MINOR_VERSION     1
#define BUILD_NUMBER      0
#define PATCH_LEVEL       0
#define CANDIDATE_VERSION true

// Define SONAME to have the SCons build the put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the SCons build script.
#define SONAME            ""

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = CANDIDATE_VERSION;
const char* Version::soname_ = SONAME;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
  if (GetPatch() > 0) {
    OS::SNPrintF(str, "%d.%d.%d.%d%s",
                 GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
  } else {
    OS::SNPrintF(str, "%d.%d.%d%s",
                 GetMajor(), GetMinor(), GetBuild(), candidate);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
                   GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    OS::SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>#include "boost/filesystem.hpp"
#include "boost/filesystem/fstream.hpp"

#include "soci/soci/src/core/soci.h"
#include "soci/soci/src/backends/sqlite3/soci-sqlite3.h"

#include <algorithm>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <map>
#include <string>
#include <vector>

#include "PlaylistController.h"
#include "SettingsController.h"

using std::cout;
using std::map;
using std::string;
using std::vector;

using namespace soci;

using boost::filesystem::ofstream;
using boost::filesystem::ifstream;
using namespace boost::filesystem;

extern SettingsController sc;

PlaylistController::PlaylistController() {
}

void PlaylistController::addplaylist(Playlist& pl, const int pos) {
	if(pos < 0) {
		playlists.push_back(pl);
		selection = begin() + offset;
		dispoffset = size() - 1;
		dispselection = begin() + dispoffset;
	}
	else if((size_t)pos < playlists.size()) {
		playlists.insert(begin() + pos, pl);
		selection = begin() + offset;
		dispoffset = pos;
		dispselection = begin() + dispoffset;
	}
}

void PlaylistController::autoaddplaylist(path p) {
	if(!exists(p))
		return;
	if(!is_directory(p))
		return;

#if BOOST_FILESYSTEM_VERSION == 3
	string n = p.filename().string();
#else
	string n = p.filename();
#endif
	if(n.empty())
		return;

	Playlist pl(n);
	map<string,string> shows;

	for(auto i = directory_iterator(p); i != directory_iterator(); ++i) {
#if BOOST_FILESYSTEM_VERSION == 3
		shows[i->path().filename().string()] = i->path().string();
#else
		shows[i->path().filename()] = i->path().string();
#endif
	}

#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
	for(auto i = shows.begin(); i != shows.end(); ++i) {
		Show s((*i).second, (*i).first, EPISODE);
		pl.add(s);
	}
#else
	for(auto &i: shows) {
		Show s(i.second, i.first, EPISODE);
		pl.add(s);
	}
#endif
	addplaylist(pl);
}

auto PlaylistController::begin() -> decltype(playlists.begin()) {
	return playlists.begin();
}

auto PlaylistController::cbegin() -> decltype(playlists.cbegin()) {
	return playlists.cbegin();
}

void deleteselected() {}

auto PlaylistController::end() -> decltype(playlists.end()) {
	return playlists.end();
}

auto PlaylistController::cend() -> decltype(playlists.cend()) {
	return playlists.cend();
}

bool PlaylistController::empty() {
	return playlists.empty();
}

auto PlaylistController::getselection() -> decltype(selection) {
	selection = begin() + offset;
	return selection;
}

auto PlaylistController::getdispselection() -> decltype(selection) {
	dispselection = begin() + dispoffset;
	return dispselection;
}

void PlaylistController::go() {
	offset = dispoffset;
	selection = dispselection;
}

void PlaylistController::go(decltype(selection) pos) {
	//if(pos >= begin() && pos < end())
		selection = pos;
}

void PlaylistController::offsetselection(size_t o) {
	auto s = selection + o;
	if(s >= begin() && s < end()) {
		selection = s;
		offset += o;
	}
	return;
}

void PlaylistController::offsetdispselection(size_t o) {
	auto s = dispselection + o;
	if(s >= begin() && s < end()) {
		dispselection = s;
		dispoffset += o;
	}
	return;
}

/**
	Database loading and saving
*/
bool PlaylistController::loaddb() {
	bool ret = true;

	ifstream db;
	db.open(sc.data);

	size_t played, size;
	unsigned int watched;
	string name, type, file;

	//TODO: Better error checking
	while(db.good()) {
		db >> played >> size;
		db.ignore();
		getline(db, name);
		if(db.fail()) {
			goto cleanup;
		}

		Playlist p(name);
		for(size_t i = 0; i < size; ++i) {
			db >> watched >> type;
			db.ignore(100,'\n');
			getline(db, name);
			getline(db, file);
			// The file was incorrectly formatted
			if(db.fail()) {
				ret = false;
				goto cleanup;
			}

			Show s(file, name, Show::gettype(type), watched);
			p.add(s);
		}

		Playlist pl(p.getname(),p);
		addplaylist(pl);
	}

cleanup:
	selection = dispselection = begin();
	offset = dispoffset = 0;

	std::sort(begin(), end());

	db.close();
	return ret;
}

bool PlaylistController::savedb() {
	ofstream db;
	db.open(sc.data);

	//TODO: Better error checking
#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
	for(auto i = playlists.begin(); i < playlists.end(); ++i) {
		(*i).printdetail(db);
		db << '\n';
		for(auto j = (*i).begin(); j < (*i).end(); ++j) {
			(*j).printdetail(db);
			db << '\n';
		}
	}
#else
	for(Playlist& p : playlists) {
		p.printdetail(db);
		db << '\n';
		for(Show& s : p) {
			s.printdetail(db);
			db << '\n';
		}
	}
#endif

	db.close();

	savedb_new();

	return true;
}

bool PlaylistController::db_create(bool exists, session& db) {

	const double version = .2;
	double v = 0;
	indicator ind;
	bool init = true, caught = false;

	// TODO: remove exists once we drop old database stuff
	if(exists) {
		try {
			db << "SELECT Number FROM Version", into(v, ind);
		}
		catch (const std::exception& e) {
			init = true;
			caught = true;
		}

		if(!caught && db.got_data()) {
			switch(ind) {
				case i_ok:
					init = false;
					break;
				case i_null:
					break;
				case i_truncated:
					break;
			}

			if(v < version) {
				init = true;
			}
		}
	}
	else
		init = true;

	if(init) {
		db << "CREATE TABLE IF NOT EXISTS Playlists ("
			"Name TEXT PRIMARY KEY ASC NOT NULL"
			")";
		db << "CREATE TABLE IF NOT EXISTS Version ("
			"Number REAL NOT NULL"
			")";

		db << "CREATE TABLE IF NOT EXISTS Shows ("
			"File TEXT PRIMARY KEY ASC NOT NULL, "
			"Name TEXT, "
			"ID INT NOT NULL, "
			"Watched INT DEFAULT 0, "
			"Type TEXT NOT NULL DEFAULT EPISODE, "
			"Playlist REFERENCES Playlists (Name) ON DELETE CASCADE ON UPDATE CASCADE"
			")";

		if(exists && !caught && v < version) {
			db << "UPDATE Version SET Number = :version", use(version);
		}
		else
			db << "INSERT INTO Version (Number) VALUES(:version)", use(version);

		// TODO: remove this once we drop old database stuff
		if(!exists) {
#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
			int order = 0;
			for(auto i = playlists.begin(); i < playlists.end(); ++i) {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]);

				for(auto j = playlists[i].begin(); j < playlists[i].end(); ++j) {
					db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)",
						 use(*j), use((*j).getname(), "PLAYLIST");

				}
			}
#else
			int order = 0;
			for(Playlist& p : playlists) {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(p);

				for(Show& s : p) {

					db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)",
						 use(s), use(p.getname(), "PLAYLIST");

				}
			}
#endif
		}

		db << "SELECT Number FROM Version", into(v, ind);

		if(db.got_data()) {
			switch(ind) {
				case i_ok:
					return true;
					break;
				case i_null:
					return false;
					break;
				case i_truncated:
					break;
			}
		}
	}

	return false;
}

bool PlaylistController::savedb_new() {
	bool exists = boost::filesystem::exists(sc.db);
	session db(sqlite3, sc.db.native());

	// TODO: remove exists once we drop old database stuff
	assert(db_create(exists, db));

#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
	size_t size = playlists.size();
	for(size_t i = 0; i < size; ++i) {
		if(playlists[i].haschanged()) {
			std::string name;
			indicator ind;
			db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(playlists[i]), into(name, ind);
			if(ind == i_ok && db.got_data()) {
				db << "UPDATE Playlists SET "
					"Name=:NAME "
					"WHERE Name == :OLDNAME", use(playlists[i]);
			}
			else {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]);
			}
		}

		size_t shows_size = p.size();
		for(size_t j = 0; j < shows_size; ++j) {
			//s.printdetail(db);
			//db << '\n';
		}
	}
#else
	for(Playlist& p : playlists) {
		if(p.haschanged()) {
			std::string name;
			indicator ind;
			db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(p), into(name, ind);
			if(ind == i_ok && db.got_data()) {
				db << "UPDATE Playlists SET "
					"Name=:NAME "
					"WHERE Name == :OLDNAME", use(p);
			}
			else {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(p);
			}
		}

		for(Show& s : p) {
			//s.printdetail(db);
			//db << '\n';
		}
	}
#endif

	return true;
}

size_t PlaylistController::size() { return playlists.size(); }
<commit_msg>since i made the database branch for db work, we don't care about these functions right now<commit_after>#include "boost/filesystem.hpp"
#include "boost/filesystem/fstream.hpp"

#include "soci/soci/src/core/soci.h"
#include "soci/soci/src/backends/sqlite3/soci-sqlite3.h"

#include <algorithm>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <map>
#include <string>
#include <vector>

#include "PlaylistController.h"
#include "SettingsController.h"

using std::cout;
using std::map;
using std::string;
using std::vector;

using namespace soci;

using boost::filesystem::ofstream;
using boost::filesystem::ifstream;
using namespace boost::filesystem;

extern SettingsController sc;

PlaylistController::PlaylistController() {
}

void PlaylistController::addplaylist(Playlist& pl, const int pos) {
	if(pos < 0) {
		playlists.push_back(pl);
		selection = begin() + offset;
		dispoffset = size() - 1;
		dispselection = begin() + dispoffset;
	}
	else if((size_t)pos < playlists.size()) {
		playlists.insert(begin() + pos, pl);
		selection = begin() + offset;
		dispoffset = pos;
		dispselection = begin() + dispoffset;
	}
}

void PlaylistController::autoaddplaylist(path p) {
	if(!exists(p))
		return;
	if(!is_directory(p))
		return;

#if BOOST_FILESYSTEM_VERSION == 3
	string n = p.filename().string();
#else
	string n = p.filename();
#endif
	if(n.empty())
		return;

	Playlist pl(n);
	map<string,string> shows;

	for(auto i = directory_iterator(p); i != directory_iterator(); ++i) {
#if BOOST_FILESYSTEM_VERSION == 3
		shows[i->path().filename().string()] = i->path().string();
#else
		shows[i->path().filename()] = i->path().string();
#endif
	}

#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
	for(auto i = shows.begin(); i != shows.end(); ++i) {
		Show s((*i).second, (*i).first, EPISODE);
		pl.add(s);
	}
#else
	for(auto &i: shows) {
		Show s(i.second, i.first, EPISODE);
		pl.add(s);
	}
#endif
	addplaylist(pl);
}

auto PlaylistController::begin() -> decltype(playlists.begin()) {
	return playlists.begin();
}

auto PlaylistController::cbegin() -> decltype(playlists.cbegin()) {
	return playlists.cbegin();
}

void deleteselected() {}

auto PlaylistController::end() -> decltype(playlists.end()) {
	return playlists.end();
}

auto PlaylistController::cend() -> decltype(playlists.cend()) {
	return playlists.cend();
}

bool PlaylistController::empty() {
	return playlists.empty();
}

auto PlaylistController::getselection() -> decltype(selection) {
	selection = begin() + offset;
	return selection;
}

auto PlaylistController::getdispselection() -> decltype(selection) {
	dispselection = begin() + dispoffset;
	return dispselection;
}

void PlaylistController::go() {
	offset = dispoffset;
	selection = dispselection;
}

void PlaylistController::go(decltype(selection) pos) {
	//if(pos >= begin() && pos < end())
		selection = pos;
}

void PlaylistController::offsetselection(size_t o) {
	auto s = selection + o;
	if(s >= begin() && s < end()) {
		selection = s;
		offset += o;
	}
	return;
}

void PlaylistController::offsetdispselection(size_t o) {
	auto s = dispselection + o;
	if(s >= begin() && s < end()) {
		dispselection = s;
		dispoffset += o;
	}
	return;
}

/**
	Database loading and saving
*/
bool PlaylistController::loaddb() {
	bool ret = true;

	ifstream db;
	db.open(sc.data);

	size_t played, size;
	unsigned int watched;
	string name, type, file;

	//TODO: Better error checking
	while(db.good()) {
		db >> played >> size;
		db.ignore();
		getline(db, name);
		if(db.fail()) {
			goto cleanup;
		}

		Playlist p(name);
		for(size_t i = 0; i < size; ++i) {
			db >> watched >> type;
			db.ignore(100,'\n');
			getline(db, name);
			getline(db, file);
			// The file was incorrectly formatted
			if(db.fail()) {
				ret = false;
				goto cleanup;
			}

			Show s(file, name, Show::gettype(type), watched);
			p.add(s);
		}

		Playlist pl(p.getname(),p);
		addplaylist(pl);
	}

cleanup:
	selection = dispselection = begin();
	offset = dispoffset = 0;

	std::sort(begin(), end());

	db.close();
	return ret;
}

bool PlaylistController::savedb() {
	ofstream db;
	db.open(sc.data);

	//TODO: Better error checking
#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
	for(auto i = playlists.begin(); i < playlists.end(); ++i) {
		(*i).printdetail(db);
		db << '\n';
		for(auto j = (*i).begin(); j < (*i).end(); ++j) {
			(*j).printdetail(db);
			db << '\n';
		}
	}
#else
	for(Playlist& p : playlists) {
		p.printdetail(db);
		db << '\n';
		for(Show& s : p) {
			s.printdetail(db);
			db << '\n';
		}
	}
#endif

	db.close();

	savedb_new();

	return true;
}

bool PlaylistController::db_create(bool exists, session& db) {

	/*
	const double version = .2;
	double v = 0;
	indicator ind;
	bool init = true, caught = false;

	// TODO: remove exists once we drop old database stuff
	if(exists) {
		try {
			db << "SELECT Number FROM Version", into(v, ind);
		}
		catch (const std::exception& e) {
			init = true;
			caught = true;
		}

		if(!caught && db.got_data()) {
			switch(ind) {
				case i_ok:
					init = false;
					break;
				case i_null:
					break;
				case i_truncated:
					break;
			}

			if(v < version) {
				init = true;
			}
		}
	}
	else
		init = true;

	if(init) {
		db << "CREATE TABLE IF NOT EXISTS Playlists ("
			"Name TEXT PRIMARY KEY ASC NOT NULL"
			")";
		db << "CREATE TABLE IF NOT EXISTS Version ("
			"Number REAL NOT NULL"
			")";

		db << "CREATE TABLE IF NOT EXISTS Shows ("
			"File TEXT PRIMARY KEY ASC NOT NULL, "
			"Name TEXT, "
			"ID INT NOT NULL, "
			"Watched INT DEFAULT 0, "
			"Type TEXT NOT NULL DEFAULT EPISODE, "
			"Playlist REFERENCES Playlists (Name) ON DELETE CASCADE ON UPDATE CASCADE"
			")";

		if(exists && !caught && v < version) {
			db << "UPDATE Version SET Number = :version", use(version);
		}
		else
			db << "INSERT INTO Version (Number) VALUES(:version)", use(version);

		// TODO: remove this once we drop old database stuff
		if(!exists) {
#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
			int order = 0;
			for(auto i = playlists.begin(); i < playlists.end(); ++i) {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]);

				for(auto j = playlists[i].begin(); j < playlists[i].end(); ++j) {
					db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)",
						 use(*j), use((*j).getname(), "PLAYLIST");

				}
			}
#else
			int order = 0;
			for(Playlist& p : playlists) {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(p);

				for(Show& s : p) {

					db << "INSERT INTO Shows VALUES(:FILE,:NAME,:WATCHED,:TYPE,:PLAYLIST)",
						 use(s), use(p.getname(), "PLAYLIST");

				}
			}
#endif
		}

		db << "SELECT Number FROM Version", into(v, ind);

		if(db.got_data()) {
			switch(ind) {
				case i_ok:
					return true;
					break;
				case i_null:
					return false;
					break;
				case i_truncated:
					break;
			}
		}
	}

	return false;
	*/
	return true;
}

bool PlaylistController::savedb_new() {
	/*
	bool exists = boost::filesystem::exists(sc.db);
	session db(sqlite3, sc.db.native());

	// TODO: remove exists once we drop old database stuff
	assert(db_create(exists, db));

#if __GNUC__ <= 4 && __GNUC_MINOR__ < 6
	size_t size = playlists.size();
	for(size_t i = 0; i < size; ++i) {
		if(playlists[i].haschanged()) {
			std::string name;
			indicator ind;
			db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(playlists[i]), into(name, ind);
			if(ind == i_ok && db.got_data()) {
				db << "UPDATE Playlists SET "
					"Name=:NAME "
					"WHERE Name == :OLDNAME", use(playlists[i]);
			}
			else {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(playlists[i]);
			}
		}

		size_t shows_size = p.size();
		for(size_t j = 0; j < shows_size; ++j) {
			//s.printdetail(db);
			//db << '\n';
		}
	}
#else
	for(Playlist& p : playlists) {
		if(p.haschanged()) {
			std::string name;
			indicator ind;
			db << "SELECT Name FROM Playlists WHERE Name == :OLDNAME", use(p), into(name, ind);
			if(ind == i_ok && db.got_data()) {
				db << "UPDATE Playlists SET "
					"Name=:NAME "
					"WHERE Name == :OLDNAME", use(p);
			}
			else {
				db << "INSERT INTO Playlists VALUES(:NAME)", use(p);
			}
		}

		for(Show& s : p) {
			//s.printdetail(db);
			//db << '\n';
		}
	}
#endif

*/
	return true;
}

size_t PlaylistController::size() { return playlists.size(); }
<|endoftext|>


<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      86
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>[Auto-roll] Bump up version to 3.29.89.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      89
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>// $Id$

/*
 Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University
 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 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.
*/

// ----------------------------------------------------------------------
//
//  TreeArbiter
//
// ----------------------------------------------------------------------

#include "tree_arb.hpp"
#include <iostream>
#include <sstream>

using namespace std ;

TreeArbiter::TreeArbiter( Module *parent, const string &name,
			  int size, int groups, const string & arb_type )
  : Arbiter( parent, name, size ) {
  assert(size % groups == 0);
  _group_arbiters.resize(groups);
  _group_reqs.resize(groups, 0);
  _group_size = size / groups;
  for(int i = 0; i < groups; ++i) {
    ostringstream group_arb_name;
    group_arb_name << "group_arb" << i;
    _group_arbiters[i] = Arbiter::NewArbiter(this, group_arb_name.str(), arb_type, _group_size);
  }
  _global_arbiter = Arbiter::NewArbiter(this, "global_arb", arb_type, groups);
}

TreeArbiter::~TreeArbiter() {
  for(int i = 0; i < _group_arbiters.size(); ++i) {
    delete _group_arbiters[i];
  }
  delete _global_arbiter;
}

void TreeArbiter::PrintState() const  {
  for(int i = 0; i < _group_arbiters.size(); ++i) {
    cout << "Group arbiter " << i << ":" << endl;
    _group_arbiters[i]->PrintState();
  }
  cout << "Global arbiter:" << endl;
  _global_arbiter->PrintState();
}

void TreeArbiter::UpdateState() {
  if(_selected > -1) {
    int last_winner = _global_arbiter->LastWinner();
    assert(last_winner >= 0 && last_winner < _group_arbiters.size());
    _group_arbiters[last_winner]->UpdateState();
    _global_arbiter->UpdateState();
  }
}

void TreeArbiter::AddRequest( int input, int id, int pri )
{
  Arbiter::AddRequest(input, id, pri);
  int group_index = input / _group_size;
  _group_arbiters[group_index]->AddRequest( input % _group_size, id, pri );
  ++_group_reqs[group_index];
}

int TreeArbiter::Arbitrate( int* id, int* pri ) {
  if(!_num_reqs) {
    return -1;
  }
  for(int i = 0; i < _group_arbiters.size(); ++i) {
    if(_group_reqs[i]) {
      int group_id, group_pri;
      _group_arbiters[i]->Arbitrate(&group_id, &group_pri);
      _global_arbiter->AddRequest(i, group_id, group_pri);
    }
  }
  int group = _global_arbiter->Arbitrate(NULL, NULL);
  assert(group >= 0 && group < _group_arbiters.size());
  int group_sel = _group_arbiters[group]->LastWinner();
  assert(group_sel >= 0 && group_sel < _group_size);
  _selected = group * _group_size + group_sel;
  assert(_selected >= 0 && _selected < _size);
  return Arbiter::Arbitrate(id, pri);
}

void TreeArbiter::Clear()
{
  if(!_num_reqs) {
    return;
  }
  for(int i = 0; i < _group_arbiters.size(); ++i) {
    _group_arbiters[i]->Clear();
    _group_reqs[i] = 0;
  }
  _global_arbiter->Clear();
  Arbiter::Clear();
}
<commit_msg>signed-ness mismatch fixes<commit_after>// $Id$

/*
 Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University
 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 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.
*/

// ----------------------------------------------------------------------
//
//  TreeArbiter
//
// ----------------------------------------------------------------------

#include "tree_arb.hpp"
#include <iostream>
#include <sstream>

using namespace std ;

TreeArbiter::TreeArbiter( Module *parent, const string &name,
			  int size, int groups, const string & arb_type )
  : Arbiter( parent, name, size ) {
  assert(size % groups == 0);
  _group_arbiters.resize(groups);
  _group_reqs.resize(groups, 0);
  _group_size = size / groups;
  for(int i = 0; i < groups; ++i) {
    ostringstream group_arb_name;
    group_arb_name << "group_arb" << i;
    _group_arbiters[i] = Arbiter::NewArbiter(this, group_arb_name.str(), arb_type, _group_size);
  }
  _global_arbiter = Arbiter::NewArbiter(this, "global_arb", arb_type, groups);
}

TreeArbiter::~TreeArbiter() {
  for(int i = 0; i < (int)_group_arbiters.size(); ++i) {
    delete _group_arbiters[i];
  }
  delete _global_arbiter;
}

void TreeArbiter::PrintState() const  {
  for(int i = 0; i < (int)_group_arbiters.size(); ++i) {
    cout << "Group arbiter " << i << ":" << endl;
    _group_arbiters[i]->PrintState();
  }
  cout << "Global arbiter:" << endl;
  _global_arbiter->PrintState();
}

void TreeArbiter::UpdateState() {
  if(_selected > -1) {
    int last_winner = _global_arbiter->LastWinner();
    assert(last_winner >= 0 && last_winner < (int)_group_arbiters.size());
    _group_arbiters[last_winner]->UpdateState();
    _global_arbiter->UpdateState();
  }
}

void TreeArbiter::AddRequest( int input, int id, int pri )
{
  Arbiter::AddRequest(input, id, pri);
  int group_index = input / _group_size;
  _group_arbiters[group_index]->AddRequest( input % _group_size, id, pri );
  ++_group_reqs[group_index];
}

int TreeArbiter::Arbitrate( int* id, int* pri ) {
  if(!_num_reqs) {
    return -1;
  }
  for(int i = 0; i < (int)_group_arbiters.size(); ++i) {
    if(_group_reqs[i]) {
      int group_id, group_pri;
      _group_arbiters[i]->Arbitrate(&group_id, &group_pri);
      _global_arbiter->AddRequest(i, group_id, group_pri);
    }
  }
  int group = _global_arbiter->Arbitrate(NULL, NULL);
  assert(group >= 0 && group < _group_arbiters.size());
  int group_sel = _group_arbiters[group]->LastWinner();
  assert(group_sel >= 0 && group_sel < _group_size);
  _selected = group * _group_size + group_sel;
  assert(_selected >= 0 && _selected < _size);
  return Arbiter::Arbitrate(id, pri);
}

void TreeArbiter::Clear()
{
  if(!_num_reqs) {
    return;
  }
  for(int i = 0; i < (int)_group_arbiters.size(); ++i) {
    _group_arbiters[i]->Clear();
    _group_reqs[i] = 0;
  }
  _global_arbiter->Clear();
  Arbiter::Clear();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * For use for simulation and test purposes only
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder 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 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.
 *
 * Authors: Anthony Gutierrez
 */

#ifndef __ARCH_HSAIL_GPU_ISA_HH__
#define __ARCH_HSAIL_GPU_ISA_HH__

#include <cstdint>

#include "arch/hsail/gpu_types.hh"
#include "base/logging.hh"
#include "base/types.hh"
#include "gpu-compute/misc.hh"

namespace HsailISA
{
    typedef uint64_t MiscReg;

    class GPUISA
    {
      public:
        GPUISA()
        {
        }

        void
        writeMiscReg(int opIdx, MiscReg operandVal)
        {
            fatal("HSAIL does not implement misc registers yet\n");
        }

        MiscReg
        readMiscReg(int opIdx) const
        {
            fatal("HSAIL does not implement misc registers yet\n");
        }

        bool hasScalarUnit() const { return false; }

        uint32_t
        advancePC(uint32_t old_pc, GPUDynInstPtr gpuDynInst)
        {
            return old_pc + sizeof(RawMachInst);
        }
    };
}

#endif // __ARCH_HSAIL_GPU_ISA_HH__
<commit_msg>hsail: Remove the MiscReg type.<commit_after>/*
 * Copyright (c) 2016 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * For use for simulation and test purposes only
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder 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 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.
 *
 * Authors: Anthony Gutierrez
 */

#ifndef __ARCH_HSAIL_GPU_ISA_HH__
#define __ARCH_HSAIL_GPU_ISA_HH__

#include <cstdint>

#include "arch/hsail/gpu_types.hh"
#include "base/logging.hh"
#include "base/types.hh"
#include "gpu-compute/misc.hh"

namespace HsailISA
{
    class GPUISA
    {
      public:
        GPUISA()
        {
        }

        void
        writeMiscReg(int opIdx, RegVal operandVal)
        {
            fatal("HSAIL does not implement misc registers yet\n");
        }

        RegVal
        readMiscReg(int opIdx) const
        {
            fatal("HSAIL does not implement misc registers yet\n");
        }

        bool hasScalarUnit() const { return false; }

        uint32_t
        advancePC(uint32_t old_pc, GPUDynInstPtr gpuDynInst)
        {
            return old_pc + sizeof(RawMachInst);
        }
    };
}

#endif // __ARCH_HSAIL_GPU_ISA_HH__
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009-2010 ARM Limited
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * 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: Ali Saidi
 */

#include "arch/arm/faults.hh"
#include "arch/arm/isa_traits.hh"
#include "arch/arm/tlb.hh"
#include "arch/arm/utility.hh"
#include "arch/arm/vtophys.hh"
#include "config/use_checker.hh"
#include "cpu/thread_context.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "sim/full_system.hh"

namespace ArmISA {

void
initCPU(ThreadContext *tc, int cpuId)
{
    // Reset CP15?? What does that mean -- ali

    // FPEXC.EN = 0

    static Fault reset = new Reset;
    reset->invoke(tc);
}

uint64_t
getArgument(ThreadContext *tc, int &number, uint16_t size, bool fp)
{
    if (!FullSystem) {
        panic("getArgument() only implemented for full system mode.\n");
        M5_DUMMY_RETURN
    }

    if (size == (uint16_t)(-1))
        size = ArmISA::MachineBytes;
    if (fp)
        panic("getArgument(): Floating point arguments not implemented\n");

    if (number < NumArgumentRegs) {
        // If the argument is 64 bits, it must be in an even regiser
        // number. Increment the number here if it isn't even.
        if (size == sizeof(uint64_t)) {
            if ((number % 2) != 0)
                number++;
            // Read the two halves of the data. Number is inc here to
            // get the second half of the 64 bit reg.
            uint64_t tmp;
            tmp = tc->readIntReg(number++);
            tmp |= tc->readIntReg(number) << 32;
            return tmp;
        } else {
           return tc->readIntReg(number);
        }
    } else {
        Addr sp = tc->readIntReg(StackPointerReg);
        FSTranslatingPortProxy &vp = tc->getVirtProxy();
        uint64_t arg;
        if (size == sizeof(uint64_t)) {
            // If the argument is even it must be aligned
            if ((number % 2) != 0)
                number++;
            arg = vp.read<uint64_t>(sp +
                    (number-NumArgumentRegs) * sizeof(uint32_t));
            // since two 32 bit args == 1 64 bit arg, increment number
            number++;
        } else {
            arg = vp.read<uint32_t>(sp +
                           (number-NumArgumentRegs) * sizeof(uint32_t));
        }
        return arg;
    }
}

void
skipFunction(ThreadContext *tc)
{
    TheISA::PCState newPC = tc->pcState();
    newPC.set(tc->readIntReg(ReturnAddressReg) & ~ULL(1));
#if USE_CHECKER
    tc->pcStateNoRecord(newPC);
#else
    tc->pcState(newPC);
#endif
}

void
copyRegs(ThreadContext *src, ThreadContext *dest)
{
    int i;

    int saved_mode = ((CPSR)src->readMiscReg(MISCREG_CPSR)).mode;

    // Make sure we're in user mode, so we can easily see all the registers
    // in the copy loop
    src->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);
    dest->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);

    for(i = 0; i < TheISA::NumIntRegs; i++)
        dest->setIntReg(i, src->readIntReg(i));

    // Restore us back to the old mode
    src->setMiscReg(MISCREG_CPSR_MODE, saved_mode);
    dest->setMiscReg(MISCREG_CPSR_MODE, saved_mode);

    for(i = 0; i < TheISA::NumFloatRegs; i++)
        dest->setFloatReg(i, src->readFloatReg(i));
    for(i = 0; i < TheISA::NumMiscRegs; i++)
        dest->setMiscRegNoEffect(i, src->readMiscRegNoEffect(i));

    // setMiscReg "with effect" will set the misc register mapping correctly.
    // e.g. updateRegMap(val)
    dest->setMiscReg(MISCREG_CPSR, src->readMiscRegNoEffect(MISCREG_CPSR));

    // Copy over the PC State
    dest->pcState(src->pcState());

    // Invalidate the tlb misc register cache
    dest->getITBPtr()->invalidateMiscReg();
    dest->getDTBPtr()->invalidateMiscReg();
}

Addr
truncPage(Addr addr)
{
    return addr & ~(PageBytes - 1);
}

Addr
roundPage(Addr addr)
{
    return (addr + PageBytes - 1) & ~(PageBytes - 1);
}

} // namespace ArmISA
<commit_msg>ARM: Don't reset CPUs that are going to be switched in.<commit_after>/*
 * Copyright (c) 2009-2010 ARM Limited
 * All rights reserved.
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * 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: Ali Saidi
 */

#include "arch/arm/faults.hh"
#include "arch/arm/isa_traits.hh"
#include "arch/arm/tlb.hh"
#include "arch/arm/utility.hh"
#include "arch/arm/vtophys.hh"
#include "config/use_checker.hh"
#include "cpu/base.hh"
#include "cpu/thread_context.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "params/BaseCPU.hh"
#include "sim/full_system.hh"

namespace ArmISA {

void
initCPU(ThreadContext *tc, int cpuId)
{
    // Reset CP15?? What does that mean -- ali

    // FPEXC.EN = 0
    if (tc->getCpuPtr()->params()->defer_registration)
       return;

    static Fault reset = new Reset;
    reset->invoke(tc);
}

uint64_t
getArgument(ThreadContext *tc, int &number, uint16_t size, bool fp)
{
    if (!FullSystem) {
        panic("getArgument() only implemented for full system mode.\n");
        M5_DUMMY_RETURN
    }

    if (size == (uint16_t)(-1))
        size = ArmISA::MachineBytes;
    if (fp)
        panic("getArgument(): Floating point arguments not implemented\n");

    if (number < NumArgumentRegs) {
        // If the argument is 64 bits, it must be in an even regiser
        // number. Increment the number here if it isn't even.
        if (size == sizeof(uint64_t)) {
            if ((number % 2) != 0)
                number++;
            // Read the two halves of the data. Number is inc here to
            // get the second half of the 64 bit reg.
            uint64_t tmp;
            tmp = tc->readIntReg(number++);
            tmp |= tc->readIntReg(number) << 32;
            return tmp;
        } else {
           return tc->readIntReg(number);
        }
    } else {
        Addr sp = tc->readIntReg(StackPointerReg);
        FSTranslatingPortProxy &vp = tc->getVirtProxy();
        uint64_t arg;
        if (size == sizeof(uint64_t)) {
            // If the argument is even it must be aligned
            if ((number % 2) != 0)
                number++;
            arg = vp.read<uint64_t>(sp +
                    (number-NumArgumentRegs) * sizeof(uint32_t));
            // since two 32 bit args == 1 64 bit arg, increment number
            number++;
        } else {
            arg = vp.read<uint32_t>(sp +
                           (number-NumArgumentRegs) * sizeof(uint32_t));
        }
        return arg;
    }
}

void
skipFunction(ThreadContext *tc)
{
    TheISA::PCState newPC = tc->pcState();
    newPC.set(tc->readIntReg(ReturnAddressReg) & ~ULL(1));
#if USE_CHECKER
    tc->pcStateNoRecord(newPC);
#else
    tc->pcState(newPC);
#endif
}

void
copyRegs(ThreadContext *src, ThreadContext *dest)
{
    int i;

    int saved_mode = ((CPSR)src->readMiscReg(MISCREG_CPSR)).mode;

    // Make sure we're in user mode, so we can easily see all the registers
    // in the copy loop
    src->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);
    dest->setMiscReg(MISCREG_CPSR_MODE, MODE_USER);

    for(i = 0; i < TheISA::NumIntRegs; i++)
        dest->setIntReg(i, src->readIntReg(i));

    // Restore us back to the old mode
    src->setMiscReg(MISCREG_CPSR_MODE, saved_mode);
    dest->setMiscReg(MISCREG_CPSR_MODE, saved_mode);

    for(i = 0; i < TheISA::NumFloatRegs; i++)
        dest->setFloatReg(i, src->readFloatReg(i));
    for(i = 0; i < TheISA::NumMiscRegs; i++)
        dest->setMiscRegNoEffect(i, src->readMiscRegNoEffect(i));

    // setMiscReg "with effect" will set the misc register mapping correctly.
    // e.g. updateRegMap(val)
    dest->setMiscReg(MISCREG_CPSR, src->readMiscRegNoEffect(MISCREG_CPSR));

    // Copy over the PC State
    dest->pcState(src->pcState());

    // Invalidate the tlb misc register cache
    dest->getITBPtr()->invalidateMiscReg();
    dest->getDTBPtr()->invalidateMiscReg();
}

Addr
truncPage(Addr addr)
{
    return addr & ~(PageBytes - 1);
}

Addr
roundPage(Addr addr)
{
    return (addr + PageBytes - 1) & ~(PageBytes - 1);
}

} // namespace ArmISA
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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 HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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: Gabe Black
 */

#ifndef __ARCH_X86_UTILITY_HH__
#define __ARCH_X86_UTILITY_HH__

#include "arch/x86/types.hh"
#include "base/misc.hh"

class ThreadContext;

namespace X86ISA
{
    static inline bool
    inUserMode(ThreadContext *tc)
    {
        return false;
    }

    inline ExtMachInst
    makeExtMI(MachInst inst, ThreadContext * xc) {
        return inst;
    }

    inline bool isCallerSaveIntegerRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    inline bool isCalleeSaveIntegerRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    inline bool isCallerSaveFloatRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    inline bool isCalleeSaveFloatRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    // Instruction address compression hooks
    inline Addr realPCToFetchPC(const Addr &addr)
    {
        return addr;
    }

    inline Addr fetchPCToRealPC(const Addr &addr)
    {
        return addr;
    }

    // the size of "fetched" instructions (not necessarily the size
    // of real instructions for PISA)
    inline size_t fetchInstSize()
    {
        return sizeof(MachInst);
    }

    /**
     * Function to insure ISA semantics about 0 registers.
     * @param tc The thread context.
     */
    template <class TC>
    void zeroRegisters(TC *tc);

    inline void initCPU(ThreadContext *tc, int cpuId)
    {
        panic("initCPU not implemented!\n");
    }
};

#endif // __ARCH_X86_UTILITY_HH__
<commit_msg>Added missing include.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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 HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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: Gabe Black
 */

#ifndef __ARCH_X86_UTILITY_HH__
#define __ARCH_X86_UTILITY_HH__

#include "arch/x86/types.hh"
#include "base/misc.hh"
#include "sim/host.hh"

class ThreadContext;

namespace X86ISA
{
    static inline bool
    inUserMode(ThreadContext *tc)
    {
        return false;
    }

    inline ExtMachInst
    makeExtMI(MachInst inst, ThreadContext * xc) {
        return inst;
    }

    inline bool isCallerSaveIntegerRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    inline bool isCalleeSaveIntegerRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    inline bool isCallerSaveFloatRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    inline bool isCalleeSaveFloatRegister(unsigned int reg) {
        panic("register classification not implemented");
        return false;
    }

    // Instruction address compression hooks
    inline Addr realPCToFetchPC(const Addr &addr)
    {
        return addr;
    }

    inline Addr fetchPCToRealPC(const Addr &addr)
    {
        return addr;
    }

    // the size of "fetched" instructions (not necessarily the size
    // of real instructions for PISA)
    inline size_t fetchInstSize()
    {
        return sizeof(MachInst);
    }

    /**
     * Function to insure ISA semantics about 0 registers.
     * @param tc The thread context.
     */
    template <class TC>
    void zeroRegisters(TC *tc);

    inline void initCPU(ThreadContext *tc, int cpuId)
    {
        panic("initCPU not implemented!\n");
    }
};

#endif // __ARCH_X86_UTILITY_HH__
<|endoftext|>


<commit_before>#include "tests-base.hpp"

#include "utf8rewind.h"

TEST(Utf8Len, Valid)
{
	EXPECT_EQ(3, utf8len("\xE0\xA4\x9C\xE0\xA4\xA1\xE0\xA4\xA4"));
}

TEST(Utf8Len, OneByteSingle)
{
	EXPECT_EQ(1, utf8len("\x30"));
}

TEST(Utf8Len, OneByteSingleInvalidContinuation)
{
	EXPECT_EQ(1, utf8len("\x81"));
}

TEST(Utf8Len, OneByteSingleIllegalFirst)
{
	EXPECT_EQ(1, utf8len("\xFE"));
}

TEST(Utf8Len, OneByteSingleIllegalLast)
{
	EXPECT_EQ(1, utf8len("\xFF"));
}

TEST(Utf8Len, OneByteMultiple)
{
	EXPECT_EQ(5, utf8len("%@#!&"));
}

TEST(Utf8Len, OneByteMultipleInvalidContinuation)
{
	EXPECT_EQ(3, utf8len("\x84\x9A\xB8"));
}

TEST(Utf8Len, OneByteMultipleIllegal)
{
	EXPECT_EQ(4, utf8len("\xFF\xFE\xFF\xFE"));
}

TEST(Utf8Len, TwoBytesSingle)
{
	EXPECT_EQ(1, utf8len("\xC4\xB3"));
}

TEST(Utf8Len, TwoBytesSingleNotEnoughDataOneByte)
{
	EXPECT_EQ(1, utf8len("\xDA"));
}

TEST(Utf8Len, TwoBytesSingleInvalidContinuationFirstLower)
{
	EXPECT_EQ(2, utf8len("\xC8\x7F"));
}

TEST(Utf8Len, TwoBytesSingleInvalidContinuationFirstUpper)
{
	EXPECT_EQ(2, utf8len("\xD0\xF8"));
}

TEST(Utf8Len, TwoByteSingleOverlong)
{
	EXPECT_EQ(1, utf8len("\xC0\xAF"));
}

TEST(Utf8Len, TwoBytesMultiple)
{
	EXPECT_EQ(3, utf8len("\xC2\xA7\xC5\xBC\xC2\xA9"));
}

TEST(Utf8Len, TwoBytesMultipleNotEnoughData)
{
	EXPECT_EQ(4, utf8len("\xC0\xDA\xCB\xDE"));
}

TEST(Utf8Len, TwoBytesMultipleInvalidContinuation)
{
	EXPECT_EQ(6, utf8len("\xDB\xCA\xDC\x12\xDE\xFE"));
}

TEST(Utf8Len, TwoBytesMultipleOverlong)
{
	EXPECT_EQ(3, utf8len("\xC0\x9A\xC0\xA0\xC1\x80"));
}

TEST(Utf8Len, ThreeBytesSingle)
{
	EXPECT_EQ(1, utf8len("\xE0\xAA\xBE"));
}

TEST(Utf8Len, ThreeBytesSingleNotEnoughDataOneByte)
{
	EXPECT_EQ(1, utf8len("\xEE\xA8"));
}

TEST(Utf8Len, ThreeBytesSingleNotEnoughDataTwoBytes)
{
	EXPECT_EQ(1, utf8len("\xE2"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationFirstLower)
{
	EXPECT_EQ(3, utf8len("\xE2\x12\xAF"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationFirstUpper)
{
	EXPECT_EQ(2, utf8len("\xEA\xD2\x87"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationSecondLower)
{
	EXPECT_EQ(2, utf8len("\xEF\xA0\x65"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationSecondUpper)
{
	EXPECT_EQ(2, utf8len("\xEC\xB7\xFB"));
}

TEST(Utf8Len, ThreeBytesSingleOverlong)
{
	EXPECT_EQ(1, utf8len("\xE0\x9F\xBF"));
}

TEST(Utf8Len, ThreeBytesMultiple)
{
	EXPECT_EQ(4, utf8len("\xE0\xAA\x81\xE0\xBA\xBA\xE0\xAA\xAE\xE1\xB7\x82"));
}

TEST(Utf8Len, ThreeBytesMultipleNotEnoughData)
{
	EXPECT_EQ(5, utf8len("\xE7\xE8\xAA\xE0\xEF\x81\xE9\xB7"));
}

TEST(Utf8Len, ThreeBytesMultipleInvalidContinuation)
{
	EXPECT_EQ(4, utf8len("\xE7\x12\xEA\x88\xEA"));
}

TEST(Utf8Len, ThreeBytesMultipleOverlong)
{
	EXPECT_EQ(2, utf8len("\xE0\x9F\xBF\xE0\x80\x80"));
}

TEST(Utf8Len, FourBytesSingle)
{
	EXPECT_EQ(1, utf8len("\xF0\x90\x86\x84"));
}

TEST(Utf8Len, FourBytesSingleNotEnoughDataOneByte)
{
	EXPECT_EQ(1, utf8len("\xF4\xB0\xA8"));
}

TEST(Utf8Len, FourBytesSingleNotEnoughDataTwoBytes)
{
	EXPECT_EQ(1, utf8len("\xF6\xAA"));
}

TEST(Utf8Len, FourBytesSingleNotEnoughDataThreeBytes)
{
	EXPECT_EQ(1, utf8len("\xF7"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationFirstLower)
{
	EXPECT_EQ(4, utf8len("\xF1\x5F\xAE\xAE"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationFirstUpper)
{
	EXPECT_EQ(3, utf8len("\xF5\xCC\x88\x9F"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationSecondLower)
{
	EXPECT_EQ(3, utf8len("\xF7\x8A\x2A\x8A"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationSecondUpper)
{
	EXPECT_EQ(2, utf8len("\xF2\x82\xD2\xA6"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationThirdLower)
{
	EXPECT_EQ(2, utf8len("\xF6\x80\x80\x01"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationThirdUpper)
{
	EXPECT_EQ(2, utf8len("\xF4\x88\xA8\xFC"));
}

TEST(Utf8Len, FourBytesSingleOverlong)
{
	EXPECT_EQ(1, utf8len("\xF0\x8F\xBF\xBF"));
}

TEST(Utf8Len, FourBytesMultiple)
{
	EXPECT_EQ(3, utf8len("\xF0\x90\x83\x95\xF0\x90\x80\x9D\xF0\x90\x81\x9C"));
}

TEST(Utf8Len, FourBytesMultipleNotEnoughData)
{
	EXPECT_EQ(5, utf8len("\xF1\x91\xF4\x8A\x8A\xF6\x81\xF7\xF4"));
}

TEST(Utf8Len, FourBytesMultipleOverlong)
{
	EXPECT_EQ(2, utf8len("\xF4\x90\x80\x80\xF7\xBF\x80\x80"));
}

TEST(Utf8Len, FiveByteCodepointLonelyStart)
{
	const char* c = "\xF9";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, FiveByteCodepointLonelyStartAll)
{
	const char* c = "\xF8 \xF9 \xFA \xFB ";

	EXPECT_EQ(8, utf8len(c));
}

TEST(Utf8Len, FiveByteCodepointOverlong)
{
	const char* c = "\xF8\x87\xBF\xBF\xBF";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, FiveByteCodepointOverlongNotEnoughData)
{
	const char* c = "\xF8\x87\xBF\xBF";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, SixByteCodepointLonelyStart)
{
	const char* c = "\xFC";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, SixByteCodepointLonelyStartAll)
{
	const char* c = "\xFC \xFD ";

	EXPECT_EQ(4, utf8len(c));
}

TEST(Utf8Len, SixByteCodepointOverlong)
{
	const char* c = "\xFC\x83\xBF\xBF\xBF\xBF";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, SixByteCodepointOverlongNotEnoughData)
{
	const char* c = "\xFC\x83\xBF\xBF\xBF";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, StringEndsInMiddle)
{
	EXPECT_EQ(6, utf8len("Forest\0dweller"));
}

TEST(Utf8Len, StringEndsAtStart)
{
	EXPECT_EQ(0, utf8len("\0Spaceship"));
}

TEST(Utf8Len, StringZeroLength)
{
	EXPECT_EQ(0, utf8len(""));
}

TEST(Utf8Len, InvalidData)
{
	EXPECT_EQ(0, utf8len(nullptr));
}<commit_msg>suite-utf8-len: Refactored tests for five-byte sequences.<commit_after>#include "tests-base.hpp"

#include "utf8rewind.h"

TEST(Utf8Len, OneByteSingle)
{
	EXPECT_EQ(1, utf8len("\x30"));
}

TEST(Utf8Len, OneByteSingleInvalidContinuationFirst)
{
	EXPECT_EQ(1, utf8len("\x80"));
}

TEST(Utf8Len, OneByteSingleInvalidContinuationLast)
{
	EXPECT_EQ(1, utf8len("\xBF"));
}

TEST(Utf8Len, OneByteSingleIllegalFirst)
{
	EXPECT_EQ(1, utf8len("\xFE"));
}

TEST(Utf8Len, OneByteSingleIllegalLast)
{
	EXPECT_EQ(1, utf8len("\xFF"));
}

TEST(Utf8Len, OneByteMultiple)
{
	EXPECT_EQ(5, utf8len("%@#!&"));
}

TEST(Utf8Len, OneByteMultipleInvalidContinuation)
{
	EXPECT_EQ(3, utf8len("\x84\x9A\xB8"));
}

TEST(Utf8Len, OneByteMultipleIllegal)
{
	EXPECT_EQ(4, utf8len("\xFF\xFE\xFF\xFE"));
}

TEST(Utf8Len, TwoBytesSingle)
{
	EXPECT_EQ(1, utf8len("\xC4\xB3"));
}

TEST(Utf8Len, TwoBytesSingleNotEnoughDataOneByte)
{
	EXPECT_EQ(1, utf8len("\xDA"));
}

TEST(Utf8Len, TwoBytesSingleInvalidContinuationFirstLower)
{
	EXPECT_EQ(2, utf8len("\xC8\x7F"));
}

TEST(Utf8Len, TwoBytesSingleInvalidContinuationFirstUpper)
{
	EXPECT_EQ(2, utf8len("\xD0\xF8"));
}

TEST(Utf8Len, TwoByteSingleOverlong)
{
	EXPECT_EQ(1, utf8len("\xC0\xAF"));
}

TEST(Utf8Len, TwoBytesMultiple)
{
	EXPECT_EQ(3, utf8len("\xC2\xA7\xC5\xBC\xC2\xA9"));
}

TEST(Utf8Len, TwoBytesMultipleNotEnoughData)
{
	EXPECT_EQ(4, utf8len("\xC0\xDA\xCB\xDE"));
}

TEST(Utf8Len, TwoBytesMultipleInvalidContinuation)
{
	EXPECT_EQ(6, utf8len("\xDB\xCA\xDC\x12\xDE\xFE"));
}

TEST(Utf8Len, TwoBytesMultipleOverlong)
{
	EXPECT_EQ(3, utf8len("\xC0\x9A\xC0\xA0\xC1\x80"));
}

TEST(Utf8Len, ThreeBytesSingle)
{
	EXPECT_EQ(1, utf8len("\xE0\xAA\xBE"));
}

TEST(Utf8Len, ThreeBytesSingleNotEnoughDataOneByte)
{
	EXPECT_EQ(1, utf8len("\xE2"));
}

TEST(Utf8Len, ThreeBytesSingleNotEnoughDataTwoBytes)
{
	EXPECT_EQ(1, utf8len("\xEE\xA8"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationFirstLower)
{
	EXPECT_EQ(3, utf8len("\xE2\x12\xAF"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationFirstUpper)
{
	EXPECT_EQ(2, utf8len("\xEA\xD2\x87"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationSecondLower)
{
	EXPECT_EQ(2, utf8len("\xEF\xA0\x65"));
}

TEST(Utf8Len, ThreeBytesSingleInvalidContinuationSecondUpper)
{
	EXPECT_EQ(2, utf8len("\xEC\xB7\xFB"));
}

TEST(Utf8Len, ThreeBytesSingleOverlong)
{
	EXPECT_EQ(1, utf8len("\xE0\x9F\xBF"));
}

TEST(Utf8Len, ThreeBytesMultiple)
{
	EXPECT_EQ(4, utf8len("\xE0\xAA\x81\xE0\xBA\xBA\xE0\xAA\xAE\xE1\xB7\x82"));
}

TEST(Utf8Len, ThreeBytesMultipleNotEnoughData)
{
	EXPECT_EQ(5, utf8len("\xE7\xE8\xAA\xE0\xEF\x81\xE9\xB7"));
}

TEST(Utf8Len, ThreeBytesMultipleInvalidContinuation)
{
	EXPECT_EQ(4, utf8len("\xE7\x12\xEA\x88\xEA"));
}

TEST(Utf8Len, ThreeBytesMultipleOverlong)
{
	EXPECT_EQ(2, utf8len("\xE0\x9F\xBF\xE0\x80\x80"));
}

TEST(Utf8Len, FourBytesSingle)
{
	EXPECT_EQ(1, utf8len("\xF0\x90\x86\x84"));
}

TEST(Utf8Len, FourBytesSingleNotEnoughDataOneByte)
{
	EXPECT_EQ(1, utf8len("\xF7"));
}

TEST(Utf8Len, FourBytesSingleNotEnoughDataTwoBytes)
{
	EXPECT_EQ(1, utf8len("\xF6\xAA"));
}

TEST(Utf8Len, FourBytesSingleNotEnoughDataThreeBytes)
{
	EXPECT_EQ(1, utf8len("\xF4\xB0\xA8"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationFirstLower)
{
	EXPECT_EQ(4, utf8len("\xF1\x5F\xAE\xAE"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationFirstUpper)
{
	EXPECT_EQ(3, utf8len("\xF5\xCC\x88\x9F"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationSecondLower)
{
	EXPECT_EQ(3, utf8len("\xF7\x8A\x2A\x8A"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationSecondUpper)
{
	EXPECT_EQ(2, utf8len("\xF2\x82\xD2\xA6"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationThirdLower)
{
	EXPECT_EQ(2, utf8len("\xF6\x80\x80\x01"));
}

TEST(Utf8Len, FourBytesSingleInvalidContinuationThirdUpper)
{
	EXPECT_EQ(2, utf8len("\xF4\x88\xA8\xFC"));
}

TEST(Utf8Len, FourBytesSingleOverlong)
{
	EXPECT_EQ(1, utf8len("\xF0\x8F\xBF\xBF"));
}

TEST(Utf8Len, FourBytesMultiple)
{
	EXPECT_EQ(3, utf8len("\xF0\x90\x83\x95\xF0\x90\x80\x9D\xF0\x90\x81\x9C"));
}

TEST(Utf8Len, FourBytesMultipleNotEnoughData)
{
	EXPECT_EQ(5, utf8len("\xF1\x91\xF4\x8A\x8A\xF6\x81\xF7\xF4"));
}

TEST(Utf8Len, FourBytesMultipleOverlong)
{
	EXPECT_EQ(2, utf8len("\xF4\x90\x80\x80\xF7\xBF\x80\x80"));
}

TEST(Utf8Len, FiveBytesSingle)
{
	EXPECT_EQ(1, utf8len("\xF8\xA2\xB1\xA0\x88"));
}

TEST(Utf8Len, FiveBytesSingleNotEnoughDataOneByte)
{
	EXPECT_EQ(1, utf8len("\xF9"));
}

TEST(Utf8Len, FiveBytesSingleNotEnoughDataTwoBytes)
{
	EXPECT_EQ(1, utf8len("\xF8\x89"));
}

TEST(Utf8Len, FiveBytesSingleNotEnoughDataThreeBytes)
{
	EXPECT_EQ(1, utf8len("\xFA\x9A\x87"));
}

TEST(Utf8Len, FiveBytesSingleNotEnoughDataFourBytes)
{
	EXPECT_EQ(1, utf8len("\xFB\xAA\xAA\xAB"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteFirstLower)
{
	EXPECT_EQ(5, utf8len("\xFA\x45\x87\xAB\xB1"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteFirstUpper)
{
	EXPECT_EQ(3, utf8len("\xFA\xE7\xA8\xB2\x97"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteSecondLower)
{
	EXPECT_EQ(4, utf8len("\xFB\x8A\x13\x88\x87"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteSecondUpper)
{
	EXPECT_EQ(3, utf8len("\xFB\x88\xDF\x86\xAB"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteThirdLower)
{
	EXPECT_EQ(3, utf8len("\xFA\xAB\xBA\x16\xA8"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteThirdUpper)
{
	EXPECT_EQ(2, utf8len("\xF9\x88\x88\xCC\x88"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteFourthLower)
{
	EXPECT_EQ(2, utf8len("\xFB\x9A\x9B\x90\x24"));
}

TEST(Utf8Len, FiveBytesSingleInvalidContinuationByteFourthUpper)
{
	EXPECT_EQ(2, utf8len("\xF8\x88\x88\x88\xD9"));
}

TEST(Utf8Len, FiveBytesMultiple)
{
	EXPECT_EQ(3, utf8len("\xF8\xAB\x88\xA8\x88\xF8\xBA\xAB\xBA\xAB\xF9\x80\x80\x80\x81"));
}

TEST(Utf8Len, FiveBytesMultipleNotEnoughData)
{
	EXPECT_EQ(5, utf8len("\xFA\xFB\x80\xFA\x8A\x88\xFB\xF8"));
}

TEST(Utf8Len, SixByteCodepointLonelyStart)
{
	const char* c = "\xFC";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, SixByteCodepointLonelyStartAll)
{
	const char* c = "\xFC \xFD ";

	EXPECT_EQ(4, utf8len(c));
}

TEST(Utf8Len, SixByteCodepointOverlong)
{
	const char* c = "\xFC\x83\xBF\xBF\xBF\xBF";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, SixByteCodepointOverlongNotEnoughData)
{
	const char* c = "\xFC\x83\xBF\xBF\xBF";

	EXPECT_EQ(1, utf8len(c));
}

TEST(Utf8Len, StringEndsInMiddle)
{
	EXPECT_EQ(6, utf8len("Forest\0dweller"));
}

TEST(Utf8Len, StringEndsAtStart)
{
	EXPECT_EQ(0, utf8len("\0Spaceship"));
}

TEST(Utf8Len, StringZeroLength)
{
	EXPECT_EQ(0, utf8len(""));
}

TEST(Utf8Len, InvalidData)
{
	EXPECT_EQ(0, utf8len(nullptr));
}<|endoftext|>


<commit_before>/*
Copyright (C) 2016 Jakob Sinclair

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "game.hpp"
#include <GLFW/glfw3.h>
#include "shader.hpp"
#include "screen.hpp"
#include "rect2d.hpp"

Game::Game()
{
	;
}

Game::~Game()
{
        ;
}

bool Game::Init()
{
	bool success = true;
        m_Camera.Initialise(1280, 720);
	return success;
}

void Game::Update()
{
        m_Input.Update();
        m_Camera.Update();
        if (m_Input.GetKey(GLFW_KEY_ESCAPE))
                glfwSetWindowShouldClose(m_Screen.GetWindow(), GL_TRUE);
}

void Game::DrawGame()
{
	Rect2D m_Rect;
	m_Rect.SetRect(0.0f, 0.0f, 100.0f, 100.0f);
	m_Rect.SetColor(0.2f, 0.3f, 0.4f, 1.0f);

        m_2DRender.Clear();

        m_DrawSprite.Begin();
        for(uint8_t i = 0; i < 100; i++)
                m_DrawSprite.Draw(m_Rect);
        m_DrawSprite.End();
        m_DrawSprite.Present(m_Camera);

        m_2DRender.Present(m_Screen.GetWindow());
}
<commit_msg>Removed white lines in game.cpp.<commit_after>/*
Copyright (C) 2016 Jakob Sinclair

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "game.hpp"
#include <GLFW/glfw3.h>
#include "shader.hpp"
#include "screen.hpp"
#include "rect2d.hpp"

Game::Game()
{
	;
}

Game::~Game()
{
        ;
}

bool Game::Init()
{
	bool success = true;
        m_Camera.Initialise(1280, 720);
	return success;
}

void Game::Update()
{
        m_Input.Update();
        m_Camera.Update();
        if (m_Input.GetKey(GLFW_KEY_ESCAPE))
                glfwSetWindowShouldClose(m_Screen.GetWindow(), GL_TRUE);
}

void Game::DrawGame()
{
	Rect2D m_Rect;
	m_Rect.SetRect(0.0f, 0.0f, 100.0f, 100.0f);
	m_Rect.SetColor(0.2f, 0.3f, 0.4f, 1.0f);

        m_2DRender.Clear();

        m_DrawSprite.Begin();
        for(uint8_t i = 0; i < 100; i++)
                m_DrawSprite.Draw(m_Rect);
        m_DrawSprite.End();
        m_DrawSprite.Present(m_Camera);

        m_2DRender.Present(m_Screen.GetWindow());
}
<|endoftext|>


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

#include "XSLTInit.hpp"

#include "Constants.hpp"
#include "ElemNumber.hpp"
#include "NamespacesHandler.hpp"
#include "XSLTEngineImpl.hpp"

unsigned long	XSLTInit::s_initCounter = 0;

XSLTInit::XSLTInit() :
	m_platformSupportInit(),
	m_domSupportInit(),
	m_xmlSupportInit(),
	m_xalanSourceTreeInit(),
	m_xpathInit()
{
	++s_initCounter;

	if (s_initCounter == 1)
	{
		initialize();
	}
}

XSLTInit::~XSLTInit()
{
	--s_initCounter;

	if (s_initCounter == 0)
	{
		terminate();
	}
}

void
XSLTInit::initialize()
{
	Constants::initialize();

	ElemNumber::initialize();

	NamespacesHandler::initialize();

	XSLTEngineImpl::initialize();
}

void
XSLTInit::terminate()
{
	XSLTEngineImpl::terminate();

	NamespacesHandler::terminate();

	ElemNumber::terminate();

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

#include "XSLTInit.hpp"

#include "Constants.hpp"
#include "ElemNumber.hpp"
#include "FunctionFormatNumber.hpp"
#include "NamespacesHandler.hpp"
#include "XSLTEngineImpl.hpp"

unsigned long	XSLTInit::s_initCounter = 0;

XSLTInit::XSLTInit() :
	m_platformSupportInit(),
	m_domSupportInit(),
	m_xmlSupportInit(),
	m_xalanSourceTreeInit(),
	m_xpathInit()
{
	++s_initCounter;

	if (s_initCounter == 1)
	{
		initialize();
	}
}

XSLTInit::~XSLTInit()
{
	--s_initCounter;

	if (s_initCounter == 0)
	{
		terminate();
	}
}

void
XSLTInit::initialize()
{
	Constants::initialize();

	ElemNumber::initialize();

	FunctionFormatNumber::initialize();

	NamespacesHandler::initialize();

	XSLTEngineImpl::initialize();
}

void
XSLTInit::terminate()
{
	XSLTEngineImpl::terminate();

	NamespacesHandler::terminate();

	FunctionFormatNumber::terminate();

	ElemNumber::terminate();

	Constants::terminate();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <algorithm> //for_each
#include <assert.h>
#include <iterator>

using namespace std;

int main(int argc, char* argv[])
{
    vector<double> numbers(istream_iterator<double>(cin), (istream_iterator<double>()));

    if (numbers.size() < 3)
    {
        cout << "You should enter at least three numbers." << endl;
        return 1;
    }
    assert(numbers.size() >= 3);

    vector<double> mins3(3);
    partial_sort_copy(numbers.begin(), numbers.end(), mins3.begin(), mins3.end());
    double sumOfMins = mins3[0] + mins3[1] + mins3[2];

    transform(numbers.begin(), numbers.end(), numbers.begin(), bind2nd(plus<double>(), sumOfMins));

    sort(numbers.begin(), numbers.end());

    copy(numbers.begin(), numbers.end(), ostream_iterator<double>(cout, " "));
    cout << endl;

    return 0;
}
<commit_msg>Поправил комментарий к подключаемому файлу.<commit_after>#include <iostream>
#include <vector>
#include <algorithm> //sort, transform
#include <assert.h>
#include <iterator>

using namespace std;

int main(int argc, char* argv[])
{
    vector<double> numbers(istream_iterator<double>(cin), (istream_iterator<double>()));

    if (numbers.size() < 3)
    {
        cout << "You should enter at least three numbers." << endl;
        return 1;
    }
    assert(numbers.size() >= 3);

    vector<double> mins3(3);
    partial_sort_copy(numbers.begin(), numbers.end(), mins3.begin(), mins3.end());
    double sumOfMins = mins3[0] + mins3[1] + mins3[2];

    transform(numbers.begin(), numbers.end(), numbers.begin(), bind2nd(plus<double>(), sumOfMins));

    sort(numbers.begin(), numbers.end());

    copy(numbers.begin(), numbers.end(), ostream_iterator<double>(cout, " "));
    cout << endl;

    return 0;
}
<|endoftext|>