<commit_before>#include "GameController.h"

#include "AudioProcessor.h"

#include <QThread>

extern "C" {
#include "gba.h"
#include "gba-audio.h"
#include "renderers/video-software.h"
#include "util/vfs.h"
}

using namespace QGBA;

GameController::GameController(QObject* parent)
	: QObject(parent)
	, m_drawContext(new uint32_t[256 * 256])
	, m_threadContext()
	, m_activeKeys(0)
	, m_rom(nullptr)
	, m_audioThread(new QThread(this))
	, m_audioProcessor(new AudioProcessor)
{
	m_renderer = new GBAVideoSoftwareRenderer;
	GBAVideoSoftwareRendererCreate(m_renderer);
	m_renderer->outputBuffer = (color_t*) m_drawContext;
	m_renderer->outputBufferStride = 256;
	m_threadContext.state = THREAD_INITIALIZED;
	m_threadContext.debugger = 0;
	m_threadContext.frameskip = 0;
	m_threadContext.bios = 0;
	m_threadContext.renderer = &m_renderer->d;
	m_threadContext.userData = this;
	m_threadContext.rewindBufferCapacity = 0;
	m_threadContext.logLevel = -1;

	GBAInputMapInit(&m_threadContext.inputMap);

#ifdef BUILD_SDL
	SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
	m_sdlEvents.bindings = &m_threadContext.inputMap;
	GBASDLInitEvents(&m_sdlEvents);
	SDL_JoystickEventState(SDL_QUERY);
#endif

	m_threadContext.startCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->m_audioProcessor->setInput(context);
		controller->gameStarted(context);
	};

	m_threadContext.cleanCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->gameStopped(context);
	};

	m_threadContext.frameCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->m_pauseMutex.lock();
		if (controller->m_pauseAfterFrame) {
			GBAThreadPauseFromThread(context);
			controller->m_pauseAfterFrame = false;
			controller->gamePaused(&controller->m_threadContext);
		}
		controller->m_pauseMutex.unlock();
		controller->frameAvailable(controller->m_drawContext);
	};

	m_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->postLog(level, QString().vsprintf(format, args));
	};

	m_audioThread->start(QThread::TimeCriticalPriority);
	m_audioProcessor->moveToThread(m_audioThread);
	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));

#ifdef BUILD_SDL
	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
#endif
}

GameController::~GameController() {
	m_audioThread->quit();
	m_audioThread->wait();
	if (GBAThreadIsPaused(&m_threadContext)) {
		GBAThreadUnpause(&m_threadContext);
	}
	GBAThreadEnd(&m_threadContext);
	GBAThreadJoin(&m_threadContext);
	delete m_renderer;
}

ARMDebugger* GameController::debugger() {
	return m_threadContext.debugger;
}

void GameController::setDebugger(ARMDebugger* debugger) {
	bool wasPaused = isPaused();
	setPaused(true);
	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
		GBADetachDebugger(m_threadContext.gba);
	}
	m_threadContext.debugger = debugger;
	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
	}
	setPaused(wasPaused);
}

void GameController::loadGame(const QString& path) {
	closeGame();
	m_threadContext.sync.videoFrameWait = 0;
	m_threadContext.sync.audioWait = 1;
	m_rom = new QFile(path);
	if (!m_rom->open(QIODevice::ReadOnly)) {
		delete m_rom;
		m_rom = nullptr;
	}

	m_pauseAfterFrame = false;

	m_threadContext.rom = VFileFromFD(m_rom->handle());
	m_threadContext.fname = strdup(path.toLocal8Bit().constData());

	GBAThreadStart(&m_threadContext);
}

void GameController::closeGame() {
	if (!m_rom) {
		return;
	}
	GBAThreadEnd(&m_threadContext);
	GBAThreadJoin(&m_threadContext);
	if (m_threadContext.fname) {
		free(const_cast<char*>(m_threadContext.fname));
		m_threadContext.fname = nullptr;
	}
	if (m_rom) {
		m_rom->close();
		delete m_rom;
		m_rom = nullptr;
	}
	emit gameStopped(&m_threadContext);
}

bool GameController::isPaused() {
	return GBAThreadIsPaused(&m_threadContext);
}

void GameController::setPaused(bool paused) {
	if (paused == GBAThreadIsPaused(&m_threadContext)) {
		return;
	}
	if (paused) {
		GBAThreadPause(&m_threadContext);
		emit gamePaused(&m_threadContext);
	} else {
		GBAThreadUnpause(&m_threadContext);
		emit gameUnpaused(&m_threadContext);
	}
}

void GameController::reset() {
	GBAThreadReset(&m_threadContext);
}

void GameController::frameAdvance() {
	m_pauseMutex.lock();
	m_pauseAfterFrame = true;
	setPaused(false);
	m_pauseMutex.unlock();
}

void GameController::keyPressed(int key) {
	int mappedKey = 1 << key;
	m_activeKeys |= mappedKey;
	updateKeys();
}

void GameController::keyReleased(int key) {
	int mappedKey = 1 << key;
	m_activeKeys &= ~mappedKey;
	updateKeys();
}

void GameController::setAudioBufferSamples(int samples) {
	GBAThreadInterrupt(&m_threadContext);
	m_threadContext.audioBuffers = samples;
	GBAAudioResizeBuffer(&m_threadContext.gba->audio, samples);
	GBAThreadContinue(&m_threadContext);
	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
}

void GameController::setFPSTarget(float fps) {
	GBAThreadInterrupt(&m_threadContext);
	m_threadContext.fpsTarget = fps;
	GBAThreadContinue(&m_threadContext);
	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
}

void GameController::updateKeys() {
	int activeKeys = m_activeKeys;
#ifdef BUILD_SDL
	activeKeys |= m_activeButtons;
#endif
	m_threadContext.activeKeys = activeKeys;
}

#ifdef BUILD_SDL
void GameController::testSDLEvents() {
	SDL_Joystick* joystick = m_sdlEvents.joystick;
	SDL_JoystickUpdate();
	int numButtons = SDL_JoystickNumButtons(joystick);
	m_activeButtons = 0;
	int i;
	for (i = 0; i < numButtons; ++i) {
		GBAKey key = GBAInputMapKey(&m_threadContext.inputMap, SDL_BINDING_BUTTON, i);
		if (key == GBA_KEY_NONE) {
			continue;
		}
		if (SDL_JoystickGetButton(joystick, i)) {
			m_activeButtons |= 1 << key;
		}
	}
	int numHats = SDL_JoystickNumHats(joystick);
	for (i = 0; i < numHats; ++i) {
		int hat = SDL_JoystickGetHat(joystick, i);
		if (hat & SDL_HAT_UP) {
			m_activeButtons |= 1 << GBA_KEY_UP;
		}
		if (hat & SDL_HAT_LEFT) {
			m_activeButtons |= 1 << GBA_KEY_LEFT;
		}
		if (hat & SDL_HAT_DOWN) {
			m_activeButtons |= 1 << GBA_KEY_DOWN;
		}
		if (hat & SDL_HAT_RIGHT) {
			m_activeButtons |= 1 << GBA_KEY_RIGHT;
		}
	}
	updateKeys();
}
#endif
<commit_msg>Fix double-ending the GBA thread<commit_after>#include "GameController.h"

#include "AudioProcessor.h"

#include <QThread>

extern "C" {
#include "gba.h"
#include "gba-audio.h"
#include "renderers/video-software.h"
#include "util/vfs.h"
}

using namespace QGBA;

GameController::GameController(QObject* parent)
	: QObject(parent)
	, m_drawContext(new uint32_t[256 * 256])
	, m_threadContext()
	, m_activeKeys(0)
	, m_rom(nullptr)
	, m_audioThread(new QThread(this))
	, m_audioProcessor(new AudioProcessor)
{
	m_renderer = new GBAVideoSoftwareRenderer;
	GBAVideoSoftwareRendererCreate(m_renderer);
	m_renderer->outputBuffer = (color_t*) m_drawContext;
	m_renderer->outputBufferStride = 256;
	m_threadContext.state = THREAD_INITIALIZED;
	m_threadContext.debugger = 0;
	m_threadContext.frameskip = 0;
	m_threadContext.bios = 0;
	m_threadContext.renderer = &m_renderer->d;
	m_threadContext.userData = this;
	m_threadContext.rewindBufferCapacity = 0;
	m_threadContext.logLevel = -1;

	GBAInputMapInit(&m_threadContext.inputMap);

#ifdef BUILD_SDL
	SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE);
	m_sdlEvents.bindings = &m_threadContext.inputMap;
	GBASDLInitEvents(&m_sdlEvents);
	SDL_JoystickEventState(SDL_QUERY);
#endif

	m_threadContext.startCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->m_audioProcessor->setInput(context);
		controller->gameStarted(context);
	};

	m_threadContext.cleanCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->gameStopped(context);
	};

	m_threadContext.frameCallback = [] (GBAThread* context) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->m_pauseMutex.lock();
		if (controller->m_pauseAfterFrame) {
			GBAThreadPauseFromThread(context);
			controller->m_pauseAfterFrame = false;
			controller->gamePaused(&controller->m_threadContext);
		}
		controller->m_pauseMutex.unlock();
		controller->frameAvailable(controller->m_drawContext);
	};

	m_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
		GameController* controller = static_cast<GameController*>(context->userData);
		controller->postLog(level, QString().vsprintf(format, args));
	};

	m_audioThread->start(QThread::TimeCriticalPriority);
	m_audioProcessor->moveToThread(m_audioThread);
	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));

#ifdef BUILD_SDL
	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
#endif
}

GameController::~GameController() {
	m_audioThread->quit();
	m_audioThread->wait();
	if (GBAThreadIsPaused(&m_threadContext)) {
		GBAThreadUnpause(&m_threadContext);
	}
	disconnect();
	closeGame();
	delete m_renderer;
}

ARMDebugger* GameController::debugger() {
	return m_threadContext.debugger;
}

void GameController::setDebugger(ARMDebugger* debugger) {
	bool wasPaused = isPaused();
	setPaused(true);
	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
		GBADetachDebugger(m_threadContext.gba);
	}
	m_threadContext.debugger = debugger;
	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
	}
	setPaused(wasPaused);
}

void GameController::loadGame(const QString& path) {
	closeGame();
	m_threadContext.sync.videoFrameWait = 0;
	m_threadContext.sync.audioWait = 1;
	m_rom = new QFile(path);
	if (!m_rom->open(QIODevice::ReadOnly)) {
		delete m_rom;
		m_rom = nullptr;
	}

	m_pauseAfterFrame = false;

	m_threadContext.rom = VFileFromFD(m_rom->handle());
	m_threadContext.fname = strdup(path.toLocal8Bit().constData());

	GBAThreadStart(&m_threadContext);
}

void GameController::closeGame() {
	if (!m_rom) {
		return;
	}
	GBAThreadEnd(&m_threadContext);
	GBAThreadJoin(&m_threadContext);
	if (m_threadContext.fname) {
		free(const_cast<char*>(m_threadContext.fname));
		m_threadContext.fname = nullptr;
	}
	if (m_rom) {
		m_rom->close();
		delete m_rom;
		m_rom = nullptr;
	}
	emit gameStopped(&m_threadContext);
}

bool GameController::isPaused() {
	return GBAThreadIsPaused(&m_threadContext);
}

void GameController::setPaused(bool paused) {
	if (paused == GBAThreadIsPaused(&m_threadContext)) {
		return;
	}
	if (paused) {
		GBAThreadPause(&m_threadContext);
		emit gamePaused(&m_threadContext);
	} else {
		GBAThreadUnpause(&m_threadContext);
		emit gameUnpaused(&m_threadContext);
	}
}

void GameController::reset() {
	GBAThreadReset(&m_threadContext);
}

void GameController::frameAdvance() {
	m_pauseMutex.lock();
	m_pauseAfterFrame = true;
	setPaused(false);
	m_pauseMutex.unlock();
}

void GameController::keyPressed(int key) {
	int mappedKey = 1 << key;
	m_activeKeys |= mappedKey;
	updateKeys();
}

void GameController::keyReleased(int key) {
	int mappedKey = 1 << key;
	m_activeKeys &= ~mappedKey;
	updateKeys();
}

void GameController::setAudioBufferSamples(int samples) {
	GBAThreadInterrupt(&m_threadContext);
	m_threadContext.audioBuffers = samples;
	GBAAudioResizeBuffer(&m_threadContext.gba->audio, samples);
	GBAThreadContinue(&m_threadContext);
	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
}

void GameController::setFPSTarget(float fps) {
	GBAThreadInterrupt(&m_threadContext);
	m_threadContext.fpsTarget = fps;
	GBAThreadContinue(&m_threadContext);
	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
}

void GameController::updateKeys() {
	int activeKeys = m_activeKeys;
#ifdef BUILD_SDL
	activeKeys |= m_activeButtons;
#endif
	m_threadContext.activeKeys = activeKeys;
}

#ifdef BUILD_SDL
void GameController::testSDLEvents() {
	SDL_Joystick* joystick = m_sdlEvents.joystick;
	SDL_JoystickUpdate();
	int numButtons = SDL_JoystickNumButtons(joystick);
	m_activeButtons = 0;
	int i;
	for (i = 0; i < numButtons; ++i) {
		GBAKey key = GBAInputMapKey(&m_threadContext.inputMap, SDL_BINDING_BUTTON, i);
		if (key == GBA_KEY_NONE) {
			continue;
		}
		if (SDL_JoystickGetButton(joystick, i)) {
			m_activeButtons |= 1 << key;
		}
	}
	int numHats = SDL_JoystickNumHats(joystick);
	for (i = 0; i < numHats; ++i) {
		int hat = SDL_JoystickGetHat(joystick, i);
		if (hat & SDL_HAT_UP) {
			m_activeButtons |= 1 << GBA_KEY_UP;
		}
		if (hat & SDL_HAT_LEFT) {
			m_activeButtons |= 1 << GBA_KEY_LEFT;
		}
		if (hat & SDL_HAT_DOWN) {
			m_activeButtons |= 1 << GBA_KEY_DOWN;
		}
		if (hat & SDL_HAT_RIGHT) {
			m_activeButtons |= 1 << GBA_KEY_RIGHT;
		}
	}
	updateKeys();
}
#endif
<|endoftext|>


<commit_before><commit_msg>add unit test for tdf#88786<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef SC_AUTOFMT_HXX
#define SC_AUTOFMT_HXX

#include <vcl/virdev.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <vcl/morebtn.hxx>
#include <vcl/dialog.hxx>
#include <svtools/scriptedtext.hxx>
#include <svx/framelinkarray.hxx>
#include "scdllapi.h"

//------------------------------------------------------------------------

class ScAutoFormatData;
class SvxBoxItem;
class SvxLineItem;
class ScAutoFmtPreview; // s.u.
class SvNumberFormatter;
class ScDocument;

//------------------------------------------------------------------------

enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };

//========================================================================

class SC_DLLPUBLIC ScAutoFmtPreview : public Window
{
public:
            ScAutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );
            ~ScAutoFmtPreview();

    void NotifyChange( ScAutoFormatData* pNewData );

protected:
    virtual void Paint( const Rectangle& rRect );

private:
    ScAutoFormatData*       pCurData;
    VirtualDevice           aVD;
    SvtScriptedTextHelper   aScriptedText;
    ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;
    bool                    bFitWidth;
    svx::frame::Array       maArray;            /// Implementation to draw the frame borders.
    bool                    mbRTL;
    Size                    aPrvSize;
    long                    mnLabelColWidth;
    long                    mnDataColWidth1;
    long                    mnDataColWidth2;
    long                    mnRowHeight;
    const OUString          aStrJan;
    const OUString          aStrFeb;
    const OUString          aStrMar;
    const OUString          aStrNorth;
    const OUString          aStrMid;
    const OUString          aStrSouth;
    const OUString          aStrSum;
    SvNumberFormatter*      pNumFmt;
    //-------------------------------------------
    SAL_DLLPRIVATE void  Init            ();
    SAL_DLLPRIVATE void  DoPaint         ( const Rectangle& rRect );
    SAL_DLLPRIVATE void  CalcCellArray   ( bool bFitWidth );
    SAL_DLLPRIVATE void  CalcLineMap     ();
    SAL_DLLPRIVATE void  PaintCells      ();

/*  Usage of type size_t instead of SCCOL/SCROW is correct here - used in
    conjunction with class svx::frame::Array (svx/framelinkarray.hxx), which
    expects size_t coordinates. */

    SAL_DLLPRIVATE sal_uInt16              GetFormatIndex( size_t nCol, size_t nRow ) const;
    SAL_DLLPRIVATE const SvxBoxItem&   GetBoxItem( size_t nCol, size_t nRow ) const;
    SAL_DLLPRIVATE const SvxLineItem&  GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;

    SAL_DLLPRIVATE void                DrawString( size_t nCol, size_t nRow );
    SAL_DLLPRIVATE void                DrawStrings();
    SAL_DLLPRIVATE void                DrawBackground();

    SAL_DLLPRIVATE void    MakeFonts       ( sal_uInt16 nIndex,
                              Font& rFont,
                              Font& rCJKFont,
                              Font& rCTLFont );

    SAL_DLLPRIVATE OUString MakeNumberString( OUString cellString, sal_Bool bAddDec );
    SAL_DLLPRIVATE void  DrawFrameLine   ( const ::editeng::SvxBorderLine&   rLineD,
                              Point                 from,
                              Point                 to,
                              sal_Bool                  bHorizontal,
                              const ::editeng::SvxBorderLine&   rLineLT,
                              const ::editeng::SvxBorderLine&   rLineL,
                              const ::editeng::SvxBorderLine&   rLineLB,
                              const ::editeng::SvxBorderLine&   rLineRT,
                              const ::editeng::SvxBorderLine&   rLineR,
                              const ::editeng::SvxBorderLine&   rLineRB );
    SAL_DLLPRIVATE void CheckPriority    ( sal_uInt16            nCurLine,
                              AutoFmtLine       eLine,
                              ::editeng::SvxBorderLine& rLine );
    SAL_DLLPRIVATE void  GetLines        ( sal_uInt16 nIndex, AutoFmtLine eLine,
                              ::editeng::SvxBorderLine& rLineD,
                              ::editeng::SvxBorderLine& rLineLT,
                              ::editeng::SvxBorderLine& rLineL,
                              ::editeng::SvxBorderLine& rLineLB,
                              ::editeng::SvxBorderLine& rLineRT,
                              ::editeng::SvxBorderLine& rLineR,
                              ::editeng::SvxBorderLine& rLineRB );
};

#endif // SC_AUTOFMT_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>remove dead method definitions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef SC_AUTOFMT_HXX
#define SC_AUTOFMT_HXX

#include <vcl/virdev.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <vcl/morebtn.hxx>
#include <vcl/dialog.hxx>
#include <svtools/scriptedtext.hxx>
#include <svx/framelinkarray.hxx>
#include "scdllapi.h"

//------------------------------------------------------------------------

class ScAutoFormatData;
class SvxBoxItem;
class SvxLineItem;
class ScAutoFmtPreview; // s.u.
class SvNumberFormatter;
class ScDocument;

//------------------------------------------------------------------------

enum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };

//========================================================================

class SC_DLLPUBLIC ScAutoFmtPreview : public Window
{
public:
            ScAutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );
            ~ScAutoFmtPreview();

    void NotifyChange( ScAutoFormatData* pNewData );

protected:
    virtual void Paint( const Rectangle& rRect );

private:
    ScAutoFormatData*       pCurData;
    VirtualDevice           aVD;
    SvtScriptedTextHelper   aScriptedText;
    ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;
    bool                    bFitWidth;
    svx::frame::Array       maArray;            /// Implementation to draw the frame borders.
    bool                    mbRTL;
    Size                    aPrvSize;
    long                    mnLabelColWidth;
    long                    mnDataColWidth1;
    long                    mnDataColWidth2;
    long                    mnRowHeight;
    const OUString          aStrJan;
    const OUString          aStrFeb;
    const OUString          aStrMar;
    const OUString          aStrNorth;
    const OUString          aStrMid;
    const OUString          aStrSouth;
    const OUString          aStrSum;
    SvNumberFormatter*      pNumFmt;
    //-------------------------------------------
    SAL_DLLPRIVATE void  Init            ();
    SAL_DLLPRIVATE void  DoPaint         ( const Rectangle& rRect );
    SAL_DLLPRIVATE void  CalcCellArray   ( bool bFitWidth );
    SAL_DLLPRIVATE void  CalcLineMap     ();
    SAL_DLLPRIVATE void  PaintCells      ();

/*  Usage of type size_t instead of SCCOL/SCROW is correct here - used in
    conjunction with class svx::frame::Array (svx/framelinkarray.hxx), which
    expects size_t coordinates. */

    SAL_DLLPRIVATE sal_uInt16              GetFormatIndex( size_t nCol, size_t nRow ) const;
    SAL_DLLPRIVATE const SvxBoxItem&   GetBoxItem( size_t nCol, size_t nRow ) const;
    SAL_DLLPRIVATE const SvxLineItem&  GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;

    SAL_DLLPRIVATE void                DrawString( size_t nCol, size_t nRow );
    SAL_DLLPRIVATE void                DrawStrings();
    SAL_DLLPRIVATE void                DrawBackground();

    SAL_DLLPRIVATE void    MakeFonts       ( sal_uInt16 nIndex,
                              Font& rFont,
                              Font& rCJKFont,
                              Font& rCTLFont );

    SAL_DLLPRIVATE void CheckPriority    ( sal_uInt16            nCurLine,
                              AutoFmtLine       eLine,
                              ::editeng::SvxBorderLine& rLine );
    SAL_DLLPRIVATE void  GetLines        ( sal_uInt16 nIndex, AutoFmtLine eLine,
                              ::editeng::SvxBorderLine& rLineD,
                              ::editeng::SvxBorderLine& rLineLT,
                              ::editeng::SvxBorderLine& rLineL,
                              ::editeng::SvxBorderLine& rLineLB,
                              ::editeng::SvxBorderLine& rLineRT,
                              ::editeng::SvxBorderLine& rLineR,
                              ::editeng::SvxBorderLine& rLineRB );
};

#endif // SC_AUTOFMT_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: drtxtob.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: nn $ $Date: 2001-03-26 19:21:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_DRTXTOB_HXX
#define SC_DRTXTOB_HXX

#ifndef _SFX_HXX
#endif

#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif

#include "shellids.hxx"

USHORT ScGetFontWorkId();       // statt SvxFontWorkChildWindow::GetChildWindowId()

class ScViewData;

class ScDrawTextObjectBar : public SfxShell
{
    ScViewData*         pViewData;

public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SCID_DRAW_TEXT_SHELL);

        ScDrawTextObjectBar(ScViewData* pData);
        ~ScDrawTextObjectBar();

    void StateDisableItems( SfxItemSet &rSet );

    void Execute( SfxRequest &rReq );
    void ExecuteTrans( SfxRequest& rReq );
    void GetState( SfxItemSet& rSet );
    void GetClipState( SfxItemSet& rSet );

    void ExecuteAttr( SfxRequest &rReq );
    void GetAttrState( SfxItemSet& rSet );
    void ExecuteToggle( SfxRequest &rReq );

    BOOL ExecuteCharDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );
    BOOL ExecuteParaDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );

    void ExecuteExtra( SfxRequest &rReq );
    void ExecFormText(SfxRequest& rReq);        // StarFontWork
    void GetFormTextState(SfxItemSet& rSet);

private:
    void ExecuteGlobal( SfxRequest &rReq );         // von Execute gerufen fuer ganze Objekte
    void GetGlobalClipState( SfxItemSet& rSet );
    void ExecutePasteContents( SfxRequest &rReq );
    BOOL HasPasteContents();
    BOOL IsNoteEdit();
};

#endif

<commit_msg>removed unused method HasPasteContents<commit_after>/*************************************************************************
 *
 *  $RCSfile: drtxtob.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: nn $ $Date: 2001-04-23 17:02:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_DRTXTOB_HXX
#define SC_DRTXTOB_HXX

#ifndef _SFX_HXX
#endif

#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif

#include "shellids.hxx"

USHORT ScGetFontWorkId();       // statt SvxFontWorkChildWindow::GetChildWindowId()

class ScViewData;

class ScDrawTextObjectBar : public SfxShell
{
    ScViewData*         pViewData;

public:
    TYPEINFO();
    SFX_DECL_INTERFACE(SCID_DRAW_TEXT_SHELL);

        ScDrawTextObjectBar(ScViewData* pData);
        ~ScDrawTextObjectBar();

    void StateDisableItems( SfxItemSet &rSet );

    void Execute( SfxRequest &rReq );
    void ExecuteTrans( SfxRequest& rReq );
    void GetState( SfxItemSet& rSet );
    void GetClipState( SfxItemSet& rSet );

    void ExecuteAttr( SfxRequest &rReq );
    void GetAttrState( SfxItemSet& rSet );
    void ExecuteToggle( SfxRequest &rReq );

    BOOL ExecuteCharDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );
    BOOL ExecuteParaDlg( const SfxItemSet& rArgs, SfxItemSet& rOutSet );

    void ExecuteExtra( SfxRequest &rReq );
    void ExecFormText(SfxRequest& rReq);        // StarFontWork
    void GetFormTextState(SfxItemSet& rSet);

private:
    void ExecuteGlobal( SfxRequest &rReq );         // von Execute gerufen fuer ganze Objekte
    void GetGlobalClipState( SfxItemSet& rSet );
    void ExecutePasteContents( SfxRequest &rReq );
    BOOL IsNoteEdit();
};

#endif

<|endoftext|>


<commit_before>#include <info/info.hpp>

static const String name("MCPP Information");
static const Word priority=1;
static const String identifier("mcpp");
static const String help("Display information about mcpp.dll.");
static const String mcpp_banner("MINECRAFT++:");
static const String compiled_by_template("Compiled by {0} on {1}");

class MCPPInfo : public Module, public InformationProvider {

	public:

		virtual const String & Name () const noexcept override {

			return name;

		}

		virtual Word Priority () const noexcept override {

			return priority;

		}

		virtual void Install () override {

			Information::Get().Add(this);

		}

		virtual const String & Identifier () const noexcept override {

			return identifier;

		}

		virtual const String & Help () const noexcept override {

			return help;

		}

		virtual void Execute (ChatMessage & message) const override {

			message	<<	ChatStyle::Bold
					<<	mcpp_banner
					<<	ChatFormat::Pop
					<<	Newline
					<<	String::Format(
							compiled_by_template,
							Server::Get().CompiledWith(),
							Server::Get().BuildDate()
						);

		}

};

static Nullable<MCPPInfo> module;

extern "C" {

	Module * Load () {

		if (module.IsNull()) module.Construct();

		return &(*module);

	}

	void Unload () {

		module.Destroy();

	}

}
<commit_msg>MCPP Info Improvements<commit_after>#include <info/info.hpp>
#include <packet.hpp>

using namespace MCPP;

static const String name("MCPP Information");
static const Word priority=1;
static const String identifier("mcpp");
static const String help("Display information about mcpp.dll.");
static const String mcpp_banner("MINECRAFT++:");
static const String compiled_by_template("Compiled by {0} on {1}");
static const String minecraft_compat("Compatible with Minecraft {0} (protocol version {1})");
static const String version_template("{0}.{1}.{2}");

class MCPPInfo : public Module, public InformationProvider {

	public:

		virtual const String & Name () const noexcept override {

			return name;

		}

		virtual Word Priority () const noexcept override {

			return priority;

		}

		virtual void Install () override {

			Information::Get().Add(this);

		}

		virtual const String & Identifier () const noexcept override {

			return identifier;

		}

		virtual const String & Help () const noexcept override {

			return help;

		}

		virtual void Execute (ChatMessage & message) const override {

			message	<<	ChatStyle::Bold
					<<	mcpp_banner
					<<	ChatFormat::Pop
					<<	Newline
					<<	String::Format(
							compiled_by_template,
							Server::Get().CompiledWith(),
							Server::Get().BuildDate()
						)
					<<	Newline
					<<	String::Format(
							minecraft_compat,
							String::Format(
								version_template,
								MinecraftMajorVersion,
								MinecraftMinorVersion,
								MinecraftSubminorVersion
							),
							ProtocolVersion
						);

		}

};

static Nullable<MCPPInfo> module;

extern "C" {

	Module * Load () {

		if (module.IsNull()) module.Construct();

		return &(*module);

	}

	void Unload () {

		module.Destroy();

	}

}
<|endoftext|>


<commit_before>#include "parser.hpp"

#include <iostream>
#include <fstream>

namespace LightGBM {

void GetStatistic(const char* str, int* comma_cnt, int* tab_cnt, int* colon_cnt) {
  *comma_cnt = 0;
  *tab_cnt = 0;
  *colon_cnt = 0;
  for (int i = 0; str[i] != '\0'; ++i) {
    if (str[i] == ',') {
      ++(*comma_cnt);
    } else if (str[i] == '\t') {
      ++(*tab_cnt);
    } else if (str[i] == ':') {
      ++(*colon_cnt);
    }
  }
}

bool CheckHasLabelForLibsvm(std::string& str) {
  str = Common::Trim(str);
  auto pos_space = str.find_first_of(" \f\n\r\t\v");
  auto pos_colon = str.find_first_of(":");
  if (pos_colon == std::string::npos || pos_colon > pos_space) {
    return true;
  } else {
    return false;
  }
}

bool CheckHasLabelForTSV(std::string& str, int num_features) {
  str = Common::Trim(str);
  auto tokens = Common::Split(str.c_str(), '\t');
  if (tokens.size() == num_features) {
    return false;
  } else {
    return true;
  }
}

bool CheckHasLabelForCSV(std::string& str, int num_features) {
  str = Common::Trim(str);
  auto tokens = Common::Split(str.c_str(), ',');
  if (tokens.size() == num_features) {
    return false;
  } else {
    return true;
  }
}

Parser* Parser::CreateParser(const char* filename, int num_features, bool* has_label) {
  std::ifstream tmp_file;
  tmp_file.open(filename);
  if (!tmp_file.is_open()) {
    Log::Stderr("Data file: %s doesn't exist", filename);
  }
  std::string line1, line2;
  if (!tmp_file.eof()) {
    std::getline(tmp_file, line1);
  } else {
    Log::Stderr("Data file: %s at least should have one line", filename);
  }
  if (!tmp_file.eof()) {
    std::getline(tmp_file, line2);
  } else {
    Log::Stdout("Data file: %s only have one line", filename);
  }
  tmp_file.close();
  int comma_cnt = 0, comma_cnt2 = 0;
  int tab_cnt = 0, tab_cnt2 = 0;
  int colon_cnt = 0, colon_cnt2 = 0;
  // Get some statistic from 2 line
  GetStatistic(line1.c_str(), &comma_cnt, &tab_cnt, &colon_cnt);
  GetStatistic(line2.c_str(), &comma_cnt2, &tab_cnt2, &colon_cnt2);
  Parser* ret = nullptr;
  if (line2.size() == 0) {
    // if only have one line on file
    if (colon_cnt > 0) {
      ret =  new LibSVMParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForLibsvm(line1);
      }
    } else if (tab_cnt > 0) {
      ret = new TSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForTSV(line1, num_features);
      }
    } else if (comma_cnt > 0) {
      ret = new CSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForCSV(line1, num_features);
      }
    }
  } else {
    if (colon_cnt > 0 || colon_cnt2 > 0) {
      ret = new LibSVMParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForLibsvm(line1);
      }
    }
    else if (tab_cnt == tab_cnt2 && tab_cnt > 0) {
      ret = new TSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForTSV(line1, num_features);
      }
    } else if (comma_cnt == comma_cnt2 && comma_cnt > 0) {
      ret = new CSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForCSV(line1, num_features);
      }
    }
  }
  return ret;
}

}  // namespace LightGBM
<commit_msg>warning fixed<commit_after>#include "parser.hpp"

#include <iostream>
#include <fstream>

namespace LightGBM {

void GetStatistic(const char* str, int* comma_cnt, int* tab_cnt, int* colon_cnt) {
  *comma_cnt = 0;
  *tab_cnt = 0;
  *colon_cnt = 0;
  for (int i = 0; str[i] != '\0'; ++i) {
    if (str[i] == ',') {
      ++(*comma_cnt);
    } else if (str[i] == '\t') {
      ++(*tab_cnt);
    } else if (str[i] == ':') {
      ++(*colon_cnt);
    }
  }
}

bool CheckHasLabelForLibsvm(std::string& str) {
  str = Common::Trim(str);
  auto pos_space = str.find_first_of(" \f\n\r\t\v");
  auto pos_colon = str.find_first_of(":");
  if (pos_colon == std::string::npos || pos_colon > pos_space) {
    return true;
  } else {
    return false;
  }
}

bool CheckHasLabelForTSV(std::string& str, int num_features) {
  str = Common::Trim(str);
  auto tokens = Common::Split(str.c_str(), '\t');
  if (static_cast<int>(tokens.size()) == num_features) {
    return false;
  } else {
    return true;
  }
}

bool CheckHasLabelForCSV(std::string& str, int num_features) {
  str = Common::Trim(str);
  auto tokens = Common::Split(str.c_str(), ',');
  if (static_cast<int>(tokens.size()) == num_features) {
    return false;
  } else {
    return true;
  }
}

Parser* Parser::CreateParser(const char* filename, int num_features, bool* has_label) {
  std::ifstream tmp_file;
  tmp_file.open(filename);
  if (!tmp_file.is_open()) {
    Log::Stderr("Data file: %s doesn't exist", filename);
  }
  std::string line1, line2;
  if (!tmp_file.eof()) {
    std::getline(tmp_file, line1);
  } else {
    Log::Stderr("Data file: %s at least should have one line", filename);
  }
  if (!tmp_file.eof()) {
    std::getline(tmp_file, line2);
  } else {
    Log::Stdout("Data file: %s only have one line", filename);
  }
  tmp_file.close();
  int comma_cnt = 0, comma_cnt2 = 0;
  int tab_cnt = 0, tab_cnt2 = 0;
  int colon_cnt = 0, colon_cnt2 = 0;
  // Get some statistic from 2 line
  GetStatistic(line1.c_str(), &comma_cnt, &tab_cnt, &colon_cnt);
  GetStatistic(line2.c_str(), &comma_cnt2, &tab_cnt2, &colon_cnt2);
  Parser* ret = nullptr;
  if (line2.size() == 0) {
    // if only have one line on file
    if (colon_cnt > 0) {
      ret =  new LibSVMParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForLibsvm(line1);
      }
    } else if (tab_cnt > 0) {
      ret = new TSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForTSV(line1, num_features);
      }
    } else if (comma_cnt > 0) {
      ret = new CSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForCSV(line1, num_features);
      }
    }
  } else {
    if (colon_cnt > 0 || colon_cnt2 > 0) {
      ret = new LibSVMParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForLibsvm(line1);
      }
    }
    else if (tab_cnt == tab_cnt2 && tab_cnt > 0) {
      ret = new TSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForTSV(line1, num_features);
      }
    } else if (comma_cnt == comma_cnt2 && comma_cnt > 0) {
      ret = new CSVParser();
      if (num_features > 0 && has_label != nullptr) {
        *has_label = CheckHasLabelForCSV(line1, num_features);
      }
    }
  }
  return ret;
}

}  // namespace LightGBM
<|endoftext|>


<commit_before>/**
 *
 * @file    grid.cpp
 * @brief   Implementation of Grid class functions
 * @author  Vontrelle Collins
 * @copyright MIT License
 *
 **/

#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include "grid.hpp"

Grid::Grid() : gridSize(20) {

    for(int i=0; i<gridSize; i++) {
        for(int j=0; j<gridSize; j++) {
            GridPoint p(j,i);
            grid.push_back(p);
        }
    }

    auto N {grid.size()-1};

    std::random_device rand;
    std::mt19937 mt(rand());
    std::uniform_int_distribution<int> startIndex(0, (N/2)-1);
    std::uniform_int_distribution<int> destinationIndex(N/2, N);

    iStart = startIndex(mt);
    iDestination = destinationIndex(mt);

    grid[iStart].setStatus(START);
    grid[iDestination].setStatus(DESTINATION);

    unsigned long index {0};
    while(index<=N) {
        grid[index].calH(grid[iDestination]);
        ++index;
    }
}

void Grid::printGrid() {

    int colCount {1};
    for(auto point : grid) {

        switch(point.getStatus()) {

            case START:
                std::cout << "O ";
                break;

            case DESTINATION:
                std::cout << "X ";
                break;

            case PATH:
                std::cout << "# ";
                break;

            default:
                std::cout << "- ";
        }

        if(colCount%gridSize == 0)
            std::cout << std::endl;

        ++colCount;

    }
}

int Grid::findIndex(GridPoint &p) {

    int index {0};
    int i {0};
    for(auto gp : grid) {
        if(gp == p)
            index = i;

        ++i;
    }

    return index;
}

void Grid::findPath() {

    closedList.push_back(std::make_shared<GridPoint>(grid[iStart]));
    bool pathfound {false};

    GridPoint x(1,0);
    GridPoint y(0,1);

    std::shared_ptr<GridPoint> p;
    int index {15};
    int ii {0};

    do {
        int i = findIndex(*closedList[ii]);
         p = std::make_shared<GridPoint>(grid[i]);

        std::vector<GridPoint> children {GridPoint(*p+x), GridPoint(*p-x),GridPoint(*p+y), GridPoint(*p-y)};

        std::shared_ptr<GridPoint> e = std::make_shared<GridPoint>(grid[findIndex(children[0])]);
        e->calF();
        openList.push_back(e);

        std::shared_ptr<GridPoint> w = std::make_shared<GridPoint>(grid[findIndex(children[1])]);
        w->calF();
        openList.push_back(w);

        std::shared_ptr<GridPoint> n = std::make_shared<GridPoint>(grid[findIndex(children[2])]);
        n->calF();
        openList.push_back(n);

        std::shared_ptr<GridPoint> s = std::make_shared<GridPoint>(grid[findIndex(children[3])]);
        s->calF();
        openList.push_back(s);

        std::sort (openList.begin(), openList.end(), myFunc);

        for(auto point : openList) {
            if(point->getStatus() == DESTINATION)
                pathfound = true;
        }

        if(pathfound == false) {
            grid[findIndex(*openList[0])].setStatus(PATH);
            closedList.push_back(openList[0]);
            openList.erase(openList.begin());
        }

        ++ii;
        --index;

    }while(!pathfound);

}

bool myFunc(std::shared_ptr<GridPoint> a, std::shared_ptr<GridPoint> b) {
        return (a->getF() < b->getF());
}

<commit_msg>Task 4 update to Grid class<commit_after>/**
 *
 * @file    grid.cpp
 * @brief   Implementation of Grid class functions
 * @author  Vontrelle Collins
 * @copyright MIT License
 *
 **/

#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include "grid.hpp"

Grid::Grid() : gridSize(20) {

    for(int i=0; i<gridSize; i++) {
        for(int j=0; j<gridSize; j++) {
            GridPoint p(j,i);
            grid.push_back(p);
        }
    }

    auto N {grid.size()-1};

    std::random_device rand;
    std::mt19937 mt(rand());
    std::uniform_int_distribution<int> startIndex(0, (N/2)-1);
    std::uniform_int_distribution<int> destinationIndex(N/2, N);

    iStart = startIndex(mt);
    iDestination = destinationIndex(mt);

    grid[iStart].setStatus(START);
    grid[iDestination].setStatus(DESTINATION);

    unsigned long index {0};
    while(index<=N) {
        grid[index].calH(grid[iDestination]);
        ++index;
    }
}

void Grid::printGrid() {

    int colCount {1};
    for(auto point : grid) {

        switch(point.getStatus()) {

            case START:
                std::cout << "O ";
                break;

            case DESTINATION:
                std::cout << "X ";
                break;

            case PATH:
                std::cout << "# ";
                break;

            default:
                std::cout << "- ";
        }

        if(colCount%gridSize == 0)
            std::cout << std::endl;

        ++colCount;

    }
}

int Grid::findIndex(GridPoint &p) {

    int index {0};
    int i {0};
    for(auto gp : grid) {
        if(gp == p)
            index = i;

        ++i;
    }

    return index;
}

void Grid::findPath() {

    closedList.push_back(std::make_shared<GridPoint>(grid[iStart]));
    bool pathfound {false};

    GridPoint x(1,0);
    GridPoint y(0,1);

    std::shared_ptr<GridPoint> p;
    int index {15};
    int ii {0};

    do {
        int i = findIndex(*closedList[ii]);
         p = std::make_shared<GridPoint>(grid[i]);

        std::vector<GridPoint> children {GridPoint(*p+x), GridPoint(*p-x),GridPoint(*p+y), GridPoint(*p-y)};

        std::shared_ptr<GridPoint> e = std::make_shared<GridPoint>(grid[findIndex(children[0])]);
        e->calF();

        if(!(findIndex(*e) < 0))
            openList.push_back(e);

        std::shared_ptr<GridPoint> w = std::make_shared<GridPoint>(grid[findIndex(children[1])]);
        w->calF();

        if(!(findIndex(*w) < 0))
            openList.push_back(w);

        std::shared_ptr<GridPoint> n = std::make_shared<GridPoint>(grid[findIndex(children[2])]);
        n->calF();

        if(!(findIndex(*n) < 0))
            openList.push_back(n);

        std::shared_ptr<GridPoint> s = std::make_shared<GridPoint>(grid[findIndex(children[3])]);
        s->calF();

        if(!(findIndex(*

            s) < 0))
            openList.push_back(s);

        std::sort (openList.begin(), openList.end(), myFunc);

        for(auto point : openList) {
            if(point->getStatus() == DESTINATION)
                pathfound = true;
        }

        if(pathfound == false) {
            grid[findIndex(*openList[0])].setStatus(PATH);
            closedList.push_back(openList[0]);
            openList.erase(openList.begin());
        }

        ++ii;
        --index;

    }while(!pathfound);

}

bool myFunc(std::shared_ptr<GridPoint> a, std::shared_ptr<GridPoint> b) {
        return (a->getF() < b->getF());
}

<|endoftext|>


<commit_before>#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <stdio.h>
#include <pd_view.h>

#include "core/core.h"
#include "session/session.h"
#include "api/plugin_instance.h"
#include "core/plugin_handler.h"

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

static void* dummyCreateInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
    (void)uiFuncs;
    (void)serviceFunc;
    return 0;
}

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

static void dummyDestroyInstance(void* userData)
{
    (void)userData;
}

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

static int dummyUpdate(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents)
{
    (void)userData;
    (void)uiFuncs;
    (void)inEvents;
    (void)outEvents;

    return 0;
}

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

static PDViewPlugin s_dummyPlugin =
{
    "DummyPlugin",
    dummyCreateInstance,
    dummyDestroyInstance,
    dummyUpdate,
};

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

static PluginData s_pluginData = { &s_dummyPlugin, PD_VIEW_API_VERSION, "", 0 };

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

struct Session* createSession()
{
    struct Session* session = Session_create();

    assert_non_null(session);

    return session;
}

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

static void create_null_session(void** state)
{
    (void)state;

    struct Session* session = createSession();

    Session_destroy(session);
}

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

static void session_add_plugins(void** state)
{
    (void)state;
    int pluginCount = 0;

    struct Session* session = createSession();

    struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);

    Session_addViewPlugin(session, i0);
    Session_addViewPlugin(session, i1);
    Session_addViewPlugin(session, i2);

    struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);

    assert_true(pluginCount == 3);

    assert_true(instances[0] == i0);
    assert_true(instances[1] == i1);
    assert_true(instances[2] == i2);

    Session_destroy(session);
}

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

static void session_delete_plugins(void** state)
{
    (void)state;
    int pluginCount = 0;

    struct Session* session = createSession();

    struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);

    Session_addViewPlugin(session, i0);
    Session_addViewPlugin(session, i1);
    Session_addViewPlugin(session, i2);

    // Delete one of the plugins

    assert_true(Session_removeViewPlugin(session, i1) == true);
    assert_true(Session_removeViewPlugin(session, i1) == false);

    struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);

    assert_true(pluginCount == 2);
    assert_true(instances[0] == i0);
    assert_true(instances[1] == i2);

    Session_destroy(session);
}

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

int main()
{
    const UnitTest tests[] =
    {
        unit_test(create_null_session),
        unit_test(session_add_plugins),
        unit_test(session_delete_plugins),
    };

    return run_tests(tests);
}
<commit_msg>Fixed crashing unit-test<commit_after>#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include <stdio.h>
#include <pd_view.h>

#include "core/core.h"
#include "session/session.h"
#include "api/plugin_instance.h"
#include "core/plugin_handler.h"

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

static void* dummyCreateInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
    (void)uiFuncs;
    (void)serviceFunc;
    return 0;
}

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

static void dummyDestroyInstance(void* userData)
{
    (void)userData;
}

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

static int dummyUpdate(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* outEvents)
{
    (void)userData;
    (void)uiFuncs;
    (void)inEvents;
    (void)outEvents;

    return 0;
}

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

static PDViewPlugin s_dummyPlugin =
{
    "DummyPlugin",
    dummyCreateInstance,
    dummyDestroyInstance,
    dummyUpdate,
};

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

static PluginData s_pluginData = { &s_dummyPlugin, PD_VIEW_API_VERSION, "", 0 };

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

struct Session* createSession()
{
    struct Session* session = Session_create();

    assert_non_null(session);

    return session;
}

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

static void create_null_session(void** state)
{
    (void)state;

    struct Session* session = createSession();

    Session_destroy(session);
}

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

static void session_add_plugins(void** state)
{
    (void)state;
    int pluginCount = 0;

    struct Session* session = createSession();

    struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);

    Session_addViewPlugin(session, i0);
    Session_addViewPlugin(session, i1);
    Session_addViewPlugin(session, i2);

    struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);

    assert_true(pluginCount == 3);

    assert_true(instances[0] == i0);
    assert_true(instances[1] == i1);
    assert_true(instances[2] == i2);

    Session_destroy(session);
}

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

static void session_delete_plugins(void** state)
{
    (void)state;
    int pluginCount = 0;

    struct Session* session = createSession();

    struct ViewPluginInstance* i0 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i1 = PluginInstance_createViewPlugin(&s_pluginData);
    struct ViewPluginInstance* i2 = PluginInstance_createViewPlugin(&s_pluginData);

    Session_addViewPlugin(session, i0);
    Session_addViewPlugin(session, i1);
    Session_addViewPlugin(session, i2);

    // Delete one of the plugins

    assert_true(Session_removeViewPlugin(session, i1) == true);
    assert_true(Session_removeViewPlugin(session, i1) == false);

    struct ViewPluginInstance** instances = Session_getViewPlugins(session, &pluginCount);

    assert_true(pluginCount == 2);
    assert_true(instances[0] == i0);
    assert_true(instances[1] == i2);

    Session_destroy(session);
}

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

int main()
{
	Core_init();

    const UnitTest tests[] =
    {
        unit_test(create_null_session),
        unit_test(session_add_plugins),
        unit_test(session_delete_plugins),
    };

    return run_tests(tests);
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <fstream>
#include <iostream>
#include <Windows.h>
#include <time.h>
using namespace std;

#define	MAX 1000

void PrintLine( int Y, char *cFormat, ... )
{
	COORD Pos = {0, Y};		DWORD cCharsWritten;
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);
	GetConsoleScreenBufferInfo( GetStdHandle(STD_OUTPUT_HANDLE), &csbi );
	FillConsoleOutputCharacter(GetStdHandle(STD_OUTPUT_HANDLE), (TCHAR) ' ', csbi.dwSize.X, Pos, &cCharsWritten );

	static char buffer[1024];
	va_list	vlList;
	va_start( vlList, cFormat );
	_vsnprintf( buffer, 1024, cFormat, vlList );
	printf( buffer );
	va_end( vlList );
}

int Selection(int *selec){
	int num, numID;
	int	iTick = GetTickCount();

	for(int i=MAX; i>0; i--){
		num = selec[0];
		numID = 0;

		for (int j = 0 ; j < i ; j++){
			if(selec[j] > num){
				num = selec[j];
				numID = j;
			}
		}
		selec[numID] = selec[i-1];
		selec[i-1] = num;
	}

	return GetTickCount() - iTick;
}

int main()
{
	int	selec[MAX];
	int iTime;

	ofstream fr;
	fr.open("randomData.txt");

	srand((unsigned int)time(NULL));
	for(int i=0; i<MAX; i++ ){
		selec[i] = rand();
		fr<<selec[i]<<endl;
	}
	fr.close();

	PrintLine( 0, "Selection Sort  [Data::%8d] -----> [Time(ms)::Calc...]\n", MAX );
	iTime = Selection(selec);
	PrintLine( 0, "Selection Sort  [Data::%8d] -----> [Time(ms)::%8d]\n", MAX, iTime );

	ofstream fs;
	fs.open("selectionSort.txt");

	for(int i=0; i<MAX; i++ ){
		fs<<selec[i]<<endl;
	}
	fs.close();

	return 0;
}

<commit_msg>1000 -> 100<commit_after>#include <cstdlib>
#include <fstream>
#include <iostream>
#include <Windows.h>
#include <time.h>
using namespace std;

#define	MAX 100

void PrintLine( int Y, char *cFormat, ... )
{
	COORD Pos = {0, Y};		DWORD cCharsWritten;
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);
	GetConsoleScreenBufferInfo( GetStdHandle(STD_OUTPUT_HANDLE), &csbi );
	FillConsoleOutputCharacter(GetStdHandle(STD_OUTPUT_HANDLE), (TCHAR) ' ', csbi.dwSize.X, Pos, &cCharsWritten );

	static char buffer[1024];
	va_list	vlList;
	va_start( vlList, cFormat );
	_vsnprintf( buffer, 1024, cFormat, vlList );
	printf( buffer );
	va_end( vlList );
}

int Selection(int *selec){
	int num, numID;
	int	iTick = GetTickCount();

	for(int i=MAX; i>0; i--){
		num = selec[0];
		numID = 0;

		for (int j = 0 ; j < i ; j++){
			if(selec[j] > num){
				num = selec[j];
				numID = j;
			}
		}
		selec[numID] = selec[i-1];
		selec[i-1] = num;
	}

	return GetTickCount() - iTick;
}

int main()
{
	int	selec[MAX];
	int iTime;

	ofstream fr;
	fr.open("randomData.txt");

	srand((unsigned int)time(NULL));
	for(int i=0; i<MAX; i++ ){
		selec[i] = rand();
		fr<<selec[i]<<endl;
	}
	fr.close();

	PrintLine( 0, "Selection Sort  [Data::%8d] -----> [Time(ms)::Calc...]\n", MAX );
	iTime = Selection(selec);
	PrintLine( 0, "Selection Sort  [Data::%8d] -----> [Time(ms)::%8d]\n", MAX, iTime );

	ofstream fs;
	fs.open("selectionSort.txt");

	for(int i=0; i<MAX; i++ ){
		fs<<selec[i]<<endl;
	}
	fs.close();

	return 0;
}

<|endoftext|>


<commit_before>#include "libyaml_utils.h"
#include "logger.h"

// ---------------------------------------------------------------------------------
// ------------------------------- libyaml test code -------------------------------
// ---------------------------------------------------------------------------------
namespace
{

bool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode)
{
    if (add_to_me != nullptr)
    {
        if (reference_character ==  mode_type::MAP_TYPE)
        {
            if (map_mode)
            {
                *add_to_me =  mode_type::KEY_TYPE;
            }
            else
            {
                *add_to_me =  mode_type::VALUE_TYPE;
            }
            return !map_mode;
        }
        else if (reference_character ==  mode_type::SEQUENCE_TYPE)
        {
            *add_to_me =  mode_type::SEQUENCE_TYPE;
        }
        else
        {
            *add_to_me =  mode_type::UNKNOWN_TYPE;
        }
    }
    return map_mode;
}

void addTag(YAML::Node* current_node, yaml_char_t* tag)
{
    if (current_node != nullptr)
    {
        if (tag)
        {
            std::string temp_tag_translator = ((char*)tag);

            current_node->SetTag(temp_tag_translator);
        }
        else if(current_node->Tag().empty())
        {
            current_node->SetTag("?");
        }
    }
}

void addToNode
    (YAML::Node* addToMe, YAML::Node* add_me, std::stack<YAML::Node>* key_stack,
    const mode_type* tracking_current_type, yaml_char_t* tag)
{
    addTag(add_me, tag);

    if (tracking_current_type != nullptr && addToMe != nullptr)
    {
        if (*tracking_current_type ==  mode_type::SEQUENCE_TYPE && addToMe->IsSequence())
        {
            TEST_PPRINT("squ type\n")
            addToMe->push_back(*add_me);
        }
        else if (*tracking_current_type ==  mode_type::KEY_TYPE && addToMe->IsMap())
        {
            TEST_PPRINT("key type\n")
            key_stack->push(*add_me);
            (*addToMe)[*add_me];
        }
        else if (*tracking_current_type ==  mode_type::VALUE_TYPE && addToMe->IsMap())
        {
            TEST_PPRINT("map type\n")
            if (!key_stack->empty())
            {
                (*addToMe)[key_stack->top()] = *add_me;
                key_stack->pop();
            }
        }
        else
        {
            TEST_PPRINT("? type\n")
        }
    }
}

bool endEventAddition
    (std::vector<YAML::Node>* libyaml_local_output, std::stack<mode_type>* mode_stack,
    std::stack<bool>* map_mode_stack, bool map_mode, std::stack<YAML::Node>* key_stack)
{
    if (libyaml_local_output->size() > 1 && mode_stack->size() > 1)
    {
        mode_stack->pop();

        if (mode_stack->top() ==  mode_type::MAP_TYPE && !map_mode_stack->empty())
        {
            map_mode = map_mode_stack->top();
            map_mode_stack->pop();
        }
        mode_type temp_position_info;

        if (mode_stack->empty())
        {
            return map_mode;
        }
        positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode);

        YAML::Node temp_node = libyaml_local_output->back();

        libyaml_local_output->pop_back();

        addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr);
    }
    return map_mode;
}

void restartVariables (std::stack<YAML::Node>* key_stack,
    std::stack<mode_type>* mode_stack, std::stack<bool>* map_mode_stack,
    std::vector<YAML::Node>* libyaml_local_output, std::vector<YAML::Node>* libyaml_final_output,
    bool* map_mode, std::map<std::string, YAML::Node>* anchor_map)
{
    while (!key_stack->empty())
    {
        key_stack->pop();
    }

    while (!mode_stack->empty())
    {
        mode_stack->pop();
    }
    mode_stack->push(mode_type::UNKNOWN_TYPE);

    while (!map_mode_stack->empty())
    {
        map_mode_stack->pop();
    }

    if (!libyaml_local_output->empty())
    {
        libyaml_final_output->push_back(libyaml_local_output->back());
    }

    libyaml_local_output->clear();

    *map_mode = true;

    anchor_map->clear();
}

std::string parseLibyaml(const std::string name_of_file, std::string* error_message_container)
{
    return name_of_file;
}
}

std::vector<YAML::Node>* libyaml_parsing::parseLibyaml
    (const uint8_t* input, size_t input_size, std::unique_ptr<std::string>* error_message_container)
{
    yaml_parser_t parser;
    yaml_event_t event;

    std::vector<YAML::Node> libyaml_local_output;

    std::vector<YAML::Node>* libyaml_final_output = new std::vector<YAML::Node>;

    std::stack<YAML::Node> key_stack;

    std::stack<mode_type> mode_stack;

    mode_stack.push(mode_type::UNKNOWN_TYPE);

    std::stack<bool> map_mode_stack;

    bool map_mode = true;

    std::map<std::string, YAML::Node> anchor_map;

    if (!yaml_parser_initialize(&parser))
    {
        TEST_PPRINT("ERROR: Failed to initialize\n");

        *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR"));

        return libyaml_final_output;
    }

    yaml_parser_set_input_string(&parser, input, input_size);

    while (true)
    {

        YAML::Node new_node;

        yaml_event_type_t type;

        mode_type tracking_current_type;

        if (!yaml_parser_parse(&parser, &event))
        {
            yaml_event_delete(&event);

            yaml_parser_delete(&parser);

            TEST_PPRINT("ERROR: Bad parsing\n");

            *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR"));

            return libyaml_final_output;
        }
        type = event.type;

        switch (type)
        {
            case YAML_STREAM_END_EVENT:

                TEST_PPRINT("STR-\n");

                break;
            case YAML_DOCUMENT_END_EVENT:

                TEST_PPRINT("DOC-\n");

                restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,
                    libyaml_final_output, &map_mode, &anchor_map);

                break;
            case YAML_DOCUMENT_START_EVENT:

                TEST_PPRINT("DOC+\n");

                restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,
                    libyaml_final_output, &map_mode, &anchor_map);

                break;

            case YAML_MAPPING_END_EVENT:

                TEST_PPRINT("MAP-\n");

                map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);

                break;
            case YAML_SEQUENCE_END_EVENT:

                TEST_PPRINT("SQU-\n");

                map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);

                break;
            case YAML_MAPPING_START_EVENT:

                TEST_PPRINT("MAP+\n");

                libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map));
                addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);

                if (!mode_stack.empty())
                {
                    positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                    if (mode_stack.top() ==  mode_type::MAP_TYPE)
                    {
                        map_mode_stack.push(!map_mode);
                    }
                }

                mode_stack.push(mode_type::MAP_TYPE);
                map_mode = true;

                if (event.data.mapping_start.anchor)
                {
                    TEST_PPRINT("ANCH-map+\n");
                    anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back();
                }

                break;
            case YAML_SEQUENCE_START_EVENT:

                TEST_PPRINT("SQU+\n");

                libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence));
                addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);

                if (!mode_stack.empty())
                {
                    if (mode_stack.top() ==  mode_type::MAP_TYPE)
                    {
                        map_mode_stack.push(!map_mode);
                    }
                }

                mode_stack.push(mode_type::SEQUENCE_TYPE);

                if (event.data.sequence_start.anchor)
                {
                    TEST_PPRINT("ANCH-squ+\n");

                    anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back();
                }

                break;

            case YAML_SCALAR_EVENT:
            {
                TEST_PPRINT("SCL\n");

                YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length));
                addTag(&add_me, event.data.scalar.tag);

                if (event.data.scalar.anchor)
                {
                    TEST_PPRINT("ANCH-scl\n");
                    std::string temp_translator = ((char*)event.data.scalar.anchor);
                    if (mode_stack.empty())
                    {
                        break;
                    }

                    if (event.data.scalar.value)
                    {

                        TEST_PPRINT("value\n");

                        if(event.data.scalar.length != 0)
                        {
                            anchor_map[temp_translator] = add_me;

                            map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                            if (libyaml_local_output.empty())
                            {
                                libyaml_local_output.push_back(add_me);

                            }
                            else
                            {
                                addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type,
                                    event.data.scalar.tag);
                            }
                        }
                        else
                        {
                            TEST_PPRINT("empty\n");
                            if (mode_stack.top() ==  mode_type::SEQUENCE_TYPE)
                            {
                                TEST_PPRINT("sequence\n");
                                add_me = YAML::Node(YAML::NodeType::Null);

                                if (!libyaml_local_output.empty())
                                {
                                    if (libyaml_local_output.back().IsSequence())
                                    {
                                        libyaml_local_output.back().push_back(add_me);
                                    }
                                }

                                break;
                            }

                            mode_stack.pop();

                            if (!mode_stack.empty())
                            {
                                if (mode_stack.top() ==  mode_type::MAP_TYPE)
                                {
                                    TEST_PPRINT("map\n");
                                    map_mode = map_mode_stack.top();
                                    map_mode_stack.pop();
                                }

                                if (!libyaml_local_output.empty())
                                {
                                    libyaml_local_output.pop_back();
                                }
                            }
                            else
                            {
                                libyaml_local_output.push_back(YAML::Node());
                            }
                        }
                    }
                }
                else
                {
                    TEST_PPRINT("normal\n");
                    if (mode_stack.empty())
                    {
                        break;
                    }
                    map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                    if (event.data.scalar.length <= 0 && !event.data.scalar.tag &&
                            event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE)
                    {
                        TEST_PPRINT("Begin from nothing\n");
                        add_me = YAML::Node();
                    }

                    if (libyaml_local_output.empty())
                    {
                        libyaml_local_output.push_back(add_me);
                    }
                    else
                    {
                        addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type,
                            event.data.scalar.tag);
                    }
                }

                break;
            }
            case YAML_ALIAS_EVENT:
            {

                TEST_PPRINT("ALI\n");

                std::string temp_translator = ((char*) event.data.alias.anchor);

                if(anchor_map.find(temp_translator) != anchor_map.end())
                {

                    if (mode_stack.empty()) // (new)
                    {
                        break;
                    }

                    map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                    addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator],
                        &key_stack, &tracking_current_type, nullptr);
                }
                else
                {
                    yaml_event_delete(&event);

                    yaml_parser_delete(&parser);

                    TEST_PPRINT("ERROR: Missing anchor\n");

                    *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR"));

                    return libyaml_final_output;
                }
                break;
            }
            default:
                break;
        }

        yaml_event_delete(&event);

        if (type == YAML_STREAM_END_EVENT)
        {
            break;
        }

    }

    yaml_parser_delete(&parser);

    fflush(stdout);

    return libyaml_final_output;
}<commit_msg>removes legacy variables, and tighens up code<commit_after>#include "libyaml_utils.h"
#include "logger.h"

// ---------------------------------------------------------------------------------
// ------------------------------- libyaml test code -------------------------------
// ---------------------------------------------------------------------------------
namespace
{

bool positionAnalysis(mode_type* add_to_me, const mode_type reference_character, const bool map_mode)
{
    if (add_to_me != nullptr)
    {
        if (reference_character ==  mode_type::MAP_TYPE)
        {
            if (map_mode)
            {
                *add_to_me =  mode_type::KEY_TYPE;
            }
            else
            {
                *add_to_me =  mode_type::VALUE_TYPE;
            }
            return !map_mode;
        }
        else if (reference_character ==  mode_type::SEQUENCE_TYPE)
        {
            *add_to_me =  mode_type::SEQUENCE_TYPE;
        }
        else
        {
            *add_to_me =  mode_type::UNKNOWN_TYPE;
        }
    }
    return map_mode;
}

void addTag(YAML::Node* current_node, yaml_char_t* tag)
{
    if (current_node != nullptr)
    {
        if (tag)
        {
            std::string temp_tag_translator = ((char*)tag);

            current_node->SetTag(temp_tag_translator);
        }
        else if(current_node->Tag().empty())
        {
            current_node->SetTag("?");
        }
    }
}

void addToNode
    (YAML::Node* addToMe, YAML::Node* add_me, std::stack<YAML::Node>* key_stack,
    const mode_type* tracking_current_type, yaml_char_t* tag)
{
    addTag(add_me, tag);

    if (tracking_current_type != nullptr && addToMe != nullptr)
    {
        if (*tracking_current_type ==  mode_type::SEQUENCE_TYPE && addToMe->IsSequence())
        {
            TEST_PPRINT("squ type\n")
            addToMe->push_back(*add_me);
        }
        else if (*tracking_current_type ==  mode_type::KEY_TYPE && addToMe->IsMap())
        {
            TEST_PPRINT("key type\n")
            key_stack->push(*add_me);
            (*addToMe)[*add_me];
        }
        else if (*tracking_current_type ==  mode_type::VALUE_TYPE && addToMe->IsMap())
        {
            TEST_PPRINT("map type\n")
            if (!key_stack->empty())
            {
                (*addToMe)[key_stack->top()] = *add_me;
                key_stack->pop();
            }
        }
        else
        {
            TEST_PPRINT("? type\n")
        }
    }
}

bool endEventAddition
    (std::vector<YAML::Node>* libyaml_local_output, std::stack<mode_type>* mode_stack,
    std::stack<bool>* map_mode_stack, bool map_mode, std::stack<YAML::Node>* key_stack)
{
    if (libyaml_local_output->size() > 1 && mode_stack->size() > 1)
    {
        mode_stack->pop();

        if (mode_stack->top() == mode_type::MAP_TYPE && !map_mode_stack->empty())
        {
            map_mode = map_mode_stack->top();
            map_mode_stack->pop();
        }
        mode_type temp_position_info;

        if (mode_stack->empty())
        {
            return map_mode;
        }
        positionAnalysis(&temp_position_info, (mode_stack->top()), !map_mode);

        YAML::Node temp_node = libyaml_local_output->back();

        libyaml_local_output->pop_back();

        addToNode(&libyaml_local_output->back(), &temp_node, key_stack, &temp_position_info, nullptr);
    }
    return map_mode;
}

void restartVariables (std::stack<YAML::Node>* key_stack,
    std::stack<mode_type>* mode_stack, std::stack<bool>* map_mode_stack,
    std::vector<YAML::Node>* libyaml_local_output, std::vector<YAML::Node>* libyaml_final_output,
    bool* map_mode, std::map<std::string, YAML::Node>* anchor_map)
{
    while (!key_stack->empty())
    {
        key_stack->pop();
    }

    while (!mode_stack->empty())
    {
        mode_stack->pop();
    }
    mode_stack->push(mode_type::UNKNOWN_TYPE);

    while (!map_mode_stack->empty())
    {
        map_mode_stack->pop();
    }

    if (!libyaml_local_output->empty())
    {
        libyaml_final_output->push_back(libyaml_local_output->back());
    }

    libyaml_local_output->clear();

    *map_mode = true;

    anchor_map->clear();
}

std::string parseLibyaml(const std::string name_of_file, std::string* error_message_container)
{
    return name_of_file;
}
}

std::vector<YAML::Node>* libyaml_parsing::parseLibyaml
    (const uint8_t* input, size_t input_size, std::unique_ptr<std::string>* error_message_container)
{
    yaml_parser_t parser;
    yaml_event_t event;

    std::vector<YAML::Node> libyaml_local_output;

    std::vector<YAML::Node>* libyaml_final_output = new std::vector<YAML::Node>;

    std::stack<YAML::Node> key_stack;

    std::stack<mode_type> mode_stack;

    mode_stack.push(mode_type::UNKNOWN_TYPE);

    std::stack<bool> map_mode_stack;

    bool map_mode = true;

    std::map<std::string, YAML::Node> anchor_map;

    if (!yaml_parser_initialize(&parser))
    {
        TEST_PPRINT("ERROR: Failed to initialize\n");

        *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR"));

        return libyaml_final_output;
    }

    yaml_parser_set_input_string(&parser, input, input_size);

    while (true)
    {
        yaml_event_type_t type;

        mode_type tracking_current_type;

        if (!yaml_parser_parse(&parser, &event))
        {
            yaml_event_delete(&event);

            yaml_parser_delete(&parser);

            TEST_PPRINT("ERROR: Bad parsing\n");

            *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR"));

            return libyaml_final_output;
        }
        type = event.type;

        switch (type)
        {
            case YAML_STREAM_END_EVENT:
                TEST_PPRINT("STR-\n");

                break;
            case YAML_DOCUMENT_END_EVENT:
                TEST_PPRINT("DOC-\n");

                restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,
                    libyaml_final_output, &map_mode, &anchor_map);

                break;
            case YAML_DOCUMENT_START_EVENT:
                TEST_PPRINT("DOC+\n");

                restartVariables(&key_stack, &mode_stack, &map_mode_stack, &libyaml_local_output,
                    libyaml_final_output, &map_mode, &anchor_map);

                break;

            case YAML_MAPPING_END_EVENT:
                TEST_PPRINT("MAP-\n");

                map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);

                break;
            case YAML_SEQUENCE_END_EVENT:
                TEST_PPRINT("SQU-\n");

                map_mode = endEventAddition(&libyaml_local_output, &mode_stack, &map_mode_stack, map_mode, &key_stack);

                break;
            case YAML_MAPPING_START_EVENT:
                TEST_PPRINT("MAP+\n");

                libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Map));
                addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);

                if (!mode_stack.empty())
                {
                    positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                    if (mode_stack.top() ==  mode_type::MAP_TYPE)
                    {
                        map_mode_stack.push(!map_mode);
                    }
                }

                mode_stack.push(mode_type::MAP_TYPE);
                map_mode = true;

                if (event.data.mapping_start.anchor)
                {
                    TEST_PPRINT("ANCH-map+\n");
                    anchor_map[std::string((char*)event.data.mapping_start.anchor)] = libyaml_local_output.back();
                }

                break;
            case YAML_SEQUENCE_START_EVENT:
                TEST_PPRINT("SQU+\n");

                libyaml_local_output.push_back(YAML::Node(YAML::NodeType::Sequence));
                addTag(&libyaml_local_output.back(), event.data.sequence_start.tag);

                if (!mode_stack.empty())
                {
                    if (mode_stack.top() ==  mode_type::MAP_TYPE)
                    {
                        map_mode_stack.push(!map_mode);
                    }
                }

                mode_stack.push(mode_type::SEQUENCE_TYPE);

                if (event.data.sequence_start.anchor)
                {
                    TEST_PPRINT("ANCH-squ+\n");

                    anchor_map[std::string((char*)event.data.sequence_start.anchor)] = libyaml_local_output.back();
                }

                break;

            case YAML_SCALAR_EVENT:
            {
                TEST_PPRINT("SCL\n");

                YAML::Node add_me(std::string((char*)event.data.scalar.value, event.data.scalar.length));
                addTag(&add_me, event.data.scalar.tag);

                if (event.data.scalar.anchor)
                {
                    TEST_PPRINT("ANCH-scl\n");
                    std::string temp_translator = ((char*)event.data.scalar.anchor);
                    if (mode_stack.empty())
                    {
                        break;
                    }

                    if (event.data.scalar.value)
                    {
                        TEST_PPRINT("value\n");

                        if(event.data.scalar.length != 0)
                        {
                            anchor_map[temp_translator] = add_me;

                            map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                            if (libyaml_local_output.empty())
                            {
                                libyaml_local_output.push_back(add_me);

                            }
                            else
                            {
                                addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type,
                                    event.data.scalar.tag);
                            }
                        }
                        else
                        {
                            TEST_PPRINT("empty\n");
                            if (mode_stack.top() ==  mode_type::SEQUENCE_TYPE)
                            {
                                TEST_PPRINT("sequence\n");
                                add_me = YAML::Node(YAML::NodeType::Null);

                                if (!libyaml_local_output.empty())
                                {
                                    if (libyaml_local_output.back().IsSequence())
                                    {
                                        libyaml_local_output.back().push_back(add_me);
                                    }
                                }

                                break;
                            }

                            mode_stack.pop();

                            if (!mode_stack.empty())
                            {
                                if (mode_stack.top() ==  mode_type::MAP_TYPE)
                                {
                                    TEST_PPRINT("map\n");
                                    map_mode = map_mode_stack.top();
                                    map_mode_stack.pop();
                                }

                                if (!libyaml_local_output.empty())
                                {
                                    libyaml_local_output.pop_back();
                                }
                            }
                            else
                            {
                                libyaml_local_output.push_back(YAML::Node());
                            }
                        }
                    }
                }
                else
                {
                    TEST_PPRINT("normal\n");
                    if (mode_stack.empty())
                    {
                        break;
                    }
                    map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                    if (event.data.scalar.length <= 0 && !event.data.scalar.tag &&
                            event.data.scalar.style == YAML_PLAIN_SCALAR_STYLE)
                    {
                        TEST_PPRINT("Begin from nothing\n");
                        add_me = YAML::Node();
                    }

                    if (libyaml_local_output.empty())
                    {
                        libyaml_local_output.push_back(add_me);
                    }
                    else
                    {
                        addToNode(&libyaml_local_output.back(), &add_me, &key_stack, &tracking_current_type,
                            event.data.scalar.tag);
                    }
                }

                break;
            }
            case YAML_ALIAS_EVENT:
            {
                TEST_PPRINT("ALI\n");

                std::string temp_translator = ((char*) event.data.alias.anchor);

                if(anchor_map.find(temp_translator) != anchor_map.end())
                {

                    if (mode_stack.empty()) // (new)
                    {
                        break;
                    }

                    map_mode = positionAnalysis(&tracking_current_type, mode_stack.top(), map_mode);

                    addToNode(&libyaml_local_output.back(), &anchor_map[temp_translator],
                        &key_stack, &tracking_current_type, nullptr);
                }
                else
                {
                    yaml_event_delete(&event);

                    yaml_parser_delete(&parser);

                    TEST_PPRINT("ERROR: Missing anchor\n");

                    *error_message_container = std::unique_ptr<std::string>(new std::string("ERROR"));

                    return libyaml_final_output;
                }
                break;
            }
            default:
                break;
        }

        yaml_event_delete(&event);

        if (type == YAML_STREAM_END_EVENT)
        {
            break;
        }

    }

    yaml_parser_delete(&parser);

    fflush(stdout);

    return libyaml_final_output;
}<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// MurmurHash3 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.

// Note - The x86 and x64 versions do _not_ produce the same results, as the
// algorithms are optimized for their respective platforms. You can still
// compile and run any of them on any platform, but your performance with the
// non-native version will be less than optimal.

#include "MurmurHash3.h"

//-----------------------------------------------------------------------------
// Platform-specific functions and macros

// Microsoft Visual Studio

#if defined(_MSC_VER)

#define FORCE_INLINE	__forceinline

#include <stdlib.h>

#define ROTL64(x,y) _rotl64(x,y)

#define BIG_CONSTANT(x) (x)

// Other compilers

#else	// defined(_MSC_VER)

#define	FORCE_INLINE inline __attribute__((always_inline))

inline uint64_t rotl64(uint64_t x, int8_t r)
{
	return (x << r) | (x >> (64 - r));
}

#define ROTL64(x,y)	rotl64(x,y)

#define BIG_CONSTANT(x) (x##LLU)

#endif // !defined(_MSC_VER)

//-----------------------------------------------------------------------------
// Block read - if your platform needs to do endian-swapping or can only
// handle aligned reads, do the conversion here

FORCE_INLINE uint64_t getblock64(const uint64_t * p, int i)
{
	return p[i];
}

//-----------------------------------------------------------------------------
// Finalization mix - force all bits of a hash block to avalanche

FORCE_INLINE uint64_t fmix64(uint64_t k)
{
	k ^= k >> 33;
	k *= BIG_CONSTANT(0xff51afd7ed558ccd);
	k ^= k >> 33;
	k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53);
	k ^= k >> 33;

	return k;
}

//-----------------------------------------------------------------------------

void MurmurHash3_x64_128(const void * key, const int len,
	const uint32_t seed, void * out)
{
	const uint8_t * data = (const uint8_t*)key;
	const int nblocks = len / 16;

	uint64_t h1 = seed;
	uint64_t h2 = seed;

	const uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5);
	const uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f);

	//----------
	// body

	const uint64_t * blocks = (const uint64_t *)(data);

	for (int i = 0; i < nblocks; i++)
	{
		uint64_t k1 = getblock64(blocks, i * 2 + 0);
		uint64_t k2 = getblock64(blocks, i * 2 + 1);

		k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;

		h1 = ROTL64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729;

		k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;

		h2 = ROTL64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5;
	}

	//----------
	// tail

	const uint8_t * tail = (const uint8_t*)(data + nblocks * 16);

	uint64_t k1 = 0;
	uint64_t k2 = 0;

	switch (len & 15)
	{
	case 15: k2 ^= ((uint64_t)tail[14]) << 48;
	case 14: k2 ^= ((uint64_t)tail[13]) << 40;
	case 13: k2 ^= ((uint64_t)tail[12]) << 32;
	case 12: k2 ^= ((uint64_t)tail[11]) << 24;
	case 11: k2 ^= ((uint64_t)tail[10]) << 16;
	case 10: k2 ^= ((uint64_t)tail[9]) << 8;
	case  9: k2 ^= ((uint64_t)tail[8]) << 0;
		k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;

	case  8: k1 ^= ((uint64_t)tail[7]) << 56;
	case  7: k1 ^= ((uint64_t)tail[6]) << 48;
	case  6: k1 ^= ((uint64_t)tail[5]) << 40;
	case  5: k1 ^= ((uint64_t)tail[4]) << 32;
	case  4: k1 ^= ((uint64_t)tail[3]) << 24;
	case  3: k1 ^= ((uint64_t)tail[2]) << 16;
	case  2: k1 ^= ((uint64_t)tail[1]) << 8;
	case  1: k1 ^= ((uint64_t)tail[0]) << 0;
		k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;
	};

	//----------
	// finalization

	h1 ^= len; h2 ^= len;

	h1 += h2;
	h2 += h1;

	h1 = fmix64(h1);
	h2 = fmix64(h2);

	h1 += h2;
	h2 += h1;

	((uint64_t*)out)[0] = h1;
	((uint64_t*)out)[1] = h2;
}

std::array<uint8_t, 16> MurmurHash3_x64_128(const void * key, int len)
{
	std::array<uint8_t, 16> hash;
	MurmurHash3_x64_128(key, len, 104729, hash.data());

	return hash;
}

uint64_t MurmurHash3_x64_64(const void * key, int len)
{
	uint64_t hash[2];
	MurmurHash3_x64_128(key, len, 104729, hash);

	return hash[0] ^ hash[1];
}

//-----------------------------------------------------------------------------

<commit_msg>Linux compilation fixed<commit_after>//-----------------------------------------------------------------------------
// MurmurHash3 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.

// Note - The x86 and x64 versions do _not_ produce the same results, as the
// algorithms are optimized for their respective platforms. You can still
// compile and run any of them on any platform, but your performance with the
// non-native version will be less than optimal.

#include "murmurhash3.h"

//-----------------------------------------------------------------------------
// Platform-specific functions and macros

// Microsoft Visual Studio

#if defined(_MSC_VER)

#define FORCE_INLINE	__forceinline

#include <stdlib.h>

#define ROTL64(x,y) _rotl64(x,y)

#define BIG_CONSTANT(x) (x)

// Other compilers

#else	// defined(_MSC_VER)

#define	FORCE_INLINE inline __attribute__((always_inline))

inline uint64_t rotl64(uint64_t x, int8_t r)
{
	return (x << r) | (x >> (64 - r));
}

#define ROTL64(x,y)	rotl64(x,y)

#define BIG_CONSTANT(x) (x##LLU)

#endif // !defined(_MSC_VER)

//-----------------------------------------------------------------------------
// Block read - if your platform needs to do endian-swapping or can only
// handle aligned reads, do the conversion here

FORCE_INLINE uint64_t getblock64(const uint64_t * p, int i)
{
	return p[i];
}

//-----------------------------------------------------------------------------
// Finalization mix - force all bits of a hash block to avalanche

FORCE_INLINE uint64_t fmix64(uint64_t k)
{
	k ^= k >> 33;
	k *= BIG_CONSTANT(0xff51afd7ed558ccd);
	k ^= k >> 33;
	k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53);
	k ^= k >> 33;

	return k;
}

//-----------------------------------------------------------------------------

void MurmurHash3_x64_128(const void * key, const int len,
	const uint32_t seed, void * out)
{
	const uint8_t * data = (const uint8_t*)key;
	const int nblocks = len / 16;

	uint64_t h1 = seed;
	uint64_t h2 = seed;

	const uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5);
	const uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f);

	//----------
	// body

	const uint64_t * blocks = (const uint64_t *)(data);

	for (int i = 0; i < nblocks; i++)
	{
		uint64_t k1 = getblock64(blocks, i * 2 + 0);
		uint64_t k2 = getblock64(blocks, i * 2 + 1);

		k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;

		h1 = ROTL64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729;

		k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;

		h2 = ROTL64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5;
	}

	//----------
	// tail

	const uint8_t * tail = (const uint8_t*)(data + nblocks * 16);

	uint64_t k1 = 0;
	uint64_t k2 = 0;

	switch (len & 15)
	{
	case 15: k2 ^= ((uint64_t)tail[14]) << 48;
	case 14: k2 ^= ((uint64_t)tail[13]) << 40;
	case 13: k2 ^= ((uint64_t)tail[12]) << 32;
	case 12: k2 ^= ((uint64_t)tail[11]) << 24;
	case 11: k2 ^= ((uint64_t)tail[10]) << 16;
	case 10: k2 ^= ((uint64_t)tail[9]) << 8;
	case  9: k2 ^= ((uint64_t)tail[8]) << 0;
		k2 *= c2; k2 = ROTL64(k2, 33); k2 *= c1; h2 ^= k2;

	case  8: k1 ^= ((uint64_t)tail[7]) << 56;
	case  7: k1 ^= ((uint64_t)tail[6]) << 48;
	case  6: k1 ^= ((uint64_t)tail[5]) << 40;
	case  5: k1 ^= ((uint64_t)tail[4]) << 32;
	case  4: k1 ^= ((uint64_t)tail[3]) << 24;
	case  3: k1 ^= ((uint64_t)tail[2]) << 16;
	case  2: k1 ^= ((uint64_t)tail[1]) << 8;
	case  1: k1 ^= ((uint64_t)tail[0]) << 0;
		k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;
	};

	//----------
	// finalization

	h1 ^= len; h2 ^= len;

	h1 += h2;
	h2 += h1;

	h1 = fmix64(h1);
	h2 = fmix64(h2);

	h1 += h2;
	h2 += h1;

	((uint64_t*)out)[0] = h1;
	((uint64_t*)out)[1] = h2;
}

std::array<uint8_t, 16> MurmurHash3_x64_128(const void * key, int len)
{
	std::array<uint8_t, 16> hash;
	MurmurHash3_x64_128(key, len, 104729, hash.data());

	return hash;
}

uint64_t MurmurHash3_x64_64(const void * key, int len)
{
	uint64_t hash[2];
	MurmurHash3_x64_128(key, len, 104729, hash);

	return hash[0] ^ hash[1];
}

//-----------------------------------------------------------------------------

<|endoftext|>