<commit_before>/*
*
*   Copyright © 2018 Luxon Jean-Pierre
*   https://gumichan01.github.io/
*
*   This library is under the MIT license
*
*   Luxon Jean-Pierre (Gumichan01)
*   luxon.jean.pierre@gmail.com
*
*/

#ifndef UTF8_ITERATOR_HPP_INCLUDED
#define UTF8_ITERATOR_HPP_INCLUDED

/**
*   @file utf8_iterator.hpp
*   @brief This is a UTF-8 string library header
*/

class UTF8string;

/**
*   @class UTF8iterator
*   @brief Iterator on UTF8 string
*
*   This class defines the iterator of UTF-8 string
*/
class UTF8iterator
{
    size_t _index = 0;
    UTF8string _data;

    char& operator ->();

public:

    UTF8iterator() = delete;

    /**
    *   @fn explicit UTF8iterator(const UTF8string& u) noexcept
    *   Build an iterator object using a UTF8string object
    *   @param u utf-8 string
    */
    explicit UTF8iterator(const UTF8string& u) noexcept;

    /**
    *   @fn UTF8iterator(const UTF8iterator& it) noexcept
    *   @param it The iterator to copy
    */
    UTF8iterator(const UTF8iterator& it) noexcept;

    /**
    *   @fn UTF8iterator& operator ++() noexcept
    *   Prefix incrementation
    *   @return The same iterator, but it has moved forward
    */
    UTF8iterator& operator ++() noexcept;

    /**
    *   @fn UTF8iterator& operator ++(int) noexcept
    *
    *   Postfix incrementation
    *
    *   @return The same iterator before it has moved forward
    */
    UTF8iterator operator ++(int) noexcept;

    /**
    *   @fn UTF8iterator& operator --() noexcept
    *   Prefix derementation
    *   @return The same iterator, but it has moved backward
    */
    UTF8iterator& operator --() noexcept;

    /**
    *   @fn UTF8iterator operator --(int) noexcept
    *
    *   Postfix decrementation
    *
    *   @return The same iterator before it has moved backward
    */
    UTF8iterator operator --(int) noexcept;

    /**
    *   @fn UTF8iterator& operator =(const UTF8iterator& it) noexcept
    *   Asignement
    *   @param it The iterator that wille be assigned
    *   @return The same iterator as the argument
    */
    UTF8iterator& operator =(const UTF8iterator& it) noexcept;

    /**
    *   @fn bool operator ==(const UTF8iterator& it) const noexcept
    *
    *   Check if the current iterator is pointing to the same position as
    *   the iterator given in argument equals.
    *
    *   @param it The iterator to compare with
    *   @return TRUE if they are pointing to the same position, FALSE otherwise
    */
    bool operator ==(const UTF8iterator& it) const noexcept;

    /**
    *   @fn bool operator !=(const UTF8iterator& it) const noexcept
    *
    *   Check if the current iterator is pointing to a different position
    *   from the iterator given in argument equals.
    *
    *   @param it The iterator to compare with
    *   @return TRUE if they are not pointing to the same position,
    *           FALSE otherwise
    */
    bool operator !=(const UTF8iterator& it) const noexcept;

    /**
    *   @fn UTF8iterator operator +(const size_t n) const noexcept
    *
    *   Returns an iterator which has been moved n positions forward
    *
    *   @param n the number of step to move forward
    *   @return The same iterator that moved forward
    */
    UTF8iterator operator +(const size_t n) const noexcept;

    /**
    *   @fn UTF8iterator operator -(const size_t n) const noexcept
    *
    *   Returns an iterator which has been moved n positions backward
    *
    *   @param n the number of steps to move backward
    *   @return The same iterator that moved backward
    */
    UTF8iterator operator -(const size_t n) const noexcept;

    /**
    *   @fn const std::string operator *() const
    *
    *   Dereferences the pointer returning the codepoint
    *   pointed by the iterator at its current potision
    *
    *   @return The codepoint
    *   @note This function will throw an *std::out_of_range* exception
    *         if the iterator does not point to a codepoint
    */
    const std::string operator *() const;

    ~UTF8iterator() = default;
};

#endif // UTF8_ITERATOR_HPP_INCLUDED
<commit_msg>iterator: delete function<commit_after>/*
*
*   Copyright © 2018 Luxon Jean-Pierre
*   https://gumichan01.github.io/
*
*   This library is under the MIT license
*
*   Luxon Jean-Pierre (Gumichan01)
*   luxon.jean.pierre@gmail.com
*
*/

#ifndef UTF8_ITERATOR_HPP_INCLUDED
#define UTF8_ITERATOR_HPP_INCLUDED

/**
*   @file utf8_iterator.hpp
*   @brief This is a UTF-8 string library header
*/

class UTF8string;

/**
*   @class UTF8iterator
*   @brief Iterator on UTF8 string
*
*   This class defines the iterator of UTF-8 string
*/
class UTF8iterator
{
    size_t _index = 0;
    UTF8string _data;

    char& operator ->() = delete;

public:

    UTF8iterator() = delete;

    /**
    *   @fn explicit UTF8iterator(const UTF8string& u) noexcept
    *   Build an iterator object using a UTF8string object
    *   @param u utf-8 string
    */
    explicit UTF8iterator(const UTF8string& u) noexcept;

    /**
    *   @fn UTF8iterator(const UTF8iterator& it) noexcept
    *   @param it The iterator to copy
    */
    UTF8iterator(const UTF8iterator& it) noexcept;

    /**
    *   @fn UTF8iterator& operator ++() noexcept
    *   Prefix incrementation
    *   @return The same iterator, but it has moved forward
    */
    UTF8iterator& operator ++() noexcept;

    /**
    *   @fn UTF8iterator& operator ++(int) noexcept
    *
    *   Postfix incrementation
    *
    *   @return The same iterator before it has moved forward
    */
    UTF8iterator operator ++(int) noexcept;

    /**
    *   @fn UTF8iterator& operator --() noexcept
    *   Prefix derementation
    *   @return The same iterator, but it has moved backward
    */
    UTF8iterator& operator --() noexcept;

    /**
    *   @fn UTF8iterator operator --(int) noexcept
    *
    *   Postfix decrementation
    *
    *   @return The same iterator before it has moved backward
    */
    UTF8iterator operator --(int) noexcept;

    /**
    *   @fn UTF8iterator& operator =(const UTF8iterator& it) noexcept
    *   Asignement
    *   @param it The iterator that wille be assigned
    *   @return The same iterator as the argument
    */
    UTF8iterator& operator =(const UTF8iterator& it) noexcept;

    /**
    *   @fn bool operator ==(const UTF8iterator& it) const noexcept
    *
    *   Check if the current iterator is pointing to the same position as
    *   the iterator given in argument equals.
    *
    *   @param it The iterator to compare with
    *   @return TRUE if they are pointing to the same position, FALSE otherwise
    */
    bool operator ==(const UTF8iterator& it) const noexcept;

    /**
    *   @fn bool operator !=(const UTF8iterator& it) const noexcept
    *
    *   Check if the current iterator is pointing to a different position
    *   from the iterator given in argument equals.
    *
    *   @param it The iterator to compare with
    *   @return TRUE if they are not pointing to the same position,
    *           FALSE otherwise
    */
    bool operator !=(const UTF8iterator& it) const noexcept;

    /**
    *   @fn UTF8iterator operator +(const size_t n) const noexcept
    *
    *   Returns an iterator which has been moved n positions forward
    *
    *   @param n the number of step to move forward
    *   @return The same iterator that moved forward
    */
    UTF8iterator operator +(const size_t n) const noexcept;

    /**
    *   @fn UTF8iterator operator -(const size_t n) const noexcept
    *
    *   Returns an iterator which has been moved n positions backward
    *
    *   @param n the number of steps to move backward
    *   @return The same iterator that moved backward
    */
    UTF8iterator operator -(const size_t n) const noexcept;

    /**
    *   @fn const std::string operator *() const
    *
    *   Dereferences the pointer returning the codepoint
    *   pointed by the iterator at its current potision
    *
    *   @return The codepoint
    *   @note This function will throw an *std::out_of_range* exception
    *         if the iterator does not point to a codepoint
    */
    const std::string operator *() const;

    ~UTF8iterator() = default;
};

#endif // UTF8_ITERATOR_HPP_INCLUDED
<|endoftext|>


<commit_before>#include "sprint.h"
#include <cstdarg> // va_start
#include <cstdlib> // malloc/free/realloc

namespace rpp
{
    ////////////////////////////////////////////////////////////////////////////////

    string_buffer::~string_buffer() noexcept
    {
        if (cap > SIZE) free(ptr);
    }

    void string_buffer::clear()
    {
        ptr[len = 0] = '\0';
    }

    void string_buffer::reserve(int count) noexcept
    {
        int newlen = len + count + 1;
        if (newlen > cap)
        {
            int align = cap; // cap is always aligned
            int newcap = newlen + align;
            if (int rem = newcap % align)
                newcap += align - rem;

            if (cap == SIZE)
                ptr = (char*)memcpy(malloc(newcap), buf, len);
            else
                ptr = (char*)realloc(ptr, newcap);
            cap = newcap;
        }
    }

    void string_buffer::writef(const char* format, ...)
    {
        char buffer[8192];
        va_list ap; va_start(ap, format);
        int n = vsnprintf(buffer, sizeof(buffer), format, ap);
        if (n < 0 || n >= (int)sizeof(buffer))
            n = sizeof(buffer) - 1;
        reserve(n);
        memcpy(&ptr[len], buffer, (size_t)n);
        len += n;
        ptr[len] = '\0';
    }

    void string_buffer::write(const string_buffer& sb) { write(sb.view()); }
    void string_buffer::write_ptr_begin() { write("*{");   }
    void string_buffer::write(nullptr_t)  { write("null"); }
    void string_buffer::write_ptr_end()   { write('}');    }

    void string_buffer::write(const strview& s)
    {
        reserve(s.len);
        char* dst = ptr + len;
        memcpy(dst, s.str, (size_t)s.len);
        len += s.len;
        ptr[len] = '\0';
    }

    void string_buffer::write(const char& value)
    {
        reserve(1);
        ptr[len++] = value;
        ptr[len] = '\0';
    }

    void string_buffer::write(bool value)   { write(value ? "true"_sv : "false"_sv); }
    void string_buffer::write(rpp::byte bv) { reserve(4);  len += _tostring(&ptr[len], bv);    }
    void string_buffer::write(short value)  { reserve(8);  len += _tostring(&ptr[len], value); }
    void string_buffer::write(ushort value) { reserve(8);  len += _tostring(&ptr[len], value); }
    void string_buffer::write(int value)    { reserve(16); len += _tostring(&ptr[len], value); }
    void string_buffer::write(uint value)   { reserve(16); len += _tostring(&ptr[len], value); }
    void string_buffer::write(int64 value)  { reserve(32); len += _tostring(&ptr[len], value); }
    void string_buffer::write(uint64 value) { reserve(32); len += _tostring(&ptr[len], value); }
    void string_buffer::write(float value)  { reserve(32); len += _tostring(&ptr[len], value); }
    void string_buffer::write(double value) { reserve(48); len += _tostring(&ptr[len], value); }

    void string_buffer::writeln()     { write('\n'); }
    void string_buffer::write_quote() { write('"');  }
    void string_buffer::write_apos()  { write('\''); }
    void string_buffer::write_colon() { write(": "); }
    void string_buffer::write_separator() { write(separator); }

    void string_buffer::pretty_cont_start(int count, bool newlines)
    {
        if (count == 0) return write("{}");
        if (count > 4) { write('['); write(count); write("] = { "); }
        else { write("{ "); }
        if (newlines) write('\n');
    }
    void string_buffer::pretty_cont_item_start(bool newlines)
    {
        if (newlines) write("  ");
    }
    void string_buffer::pretty_cont_item_end(int i, int count, bool newlines)
    {
        if (++i < count) write(", ");
        if (newlines) write('\n');
    }
    void string_buffer::pretty_cont_end(int count, bool newlines)
    {
        if (count > 0) write(" }");
        if (newlines) write('\n');
    }
    ////////////////////////////////////////////////////////////////////////////////

    int print(FILE* file, strview value) { return (int)fwrite(value.str, value.len, 1, file); }
    int print(FILE* file, char value)    { return (int)fwrite(&value, 1, 1, file); }
    int print(FILE* file, rpp::byte value){char buf[4];  return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, short value)   { char buf[8];  return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, ushort value)  { char buf[8];  return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, int value)     { char buf[16]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, uint value)    { char buf[16]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, int64 value)   { char buf[32]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, uint64 value)  { char buf[32]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }

    int print(strview value)             { return print(stdout, value); }
    int print(char value)                { return print(stdout, value); }
    int print(rpp::byte value)           { return print(stdout, value); }
    int print(short value)               { return print(stdout, value); }
    int print(ushort value)              { return print(stdout, value); }
    int print(int value)                 { return print(stdout, value); }
    int print(uint value)                { return print(stdout, value); }
    int print(int64 value)               { return print(stdout, value); }
    int print(uint64 value)              { return print(stdout, value); }

    int println(FILE* file)              { return print(file, '\n'); }
    int println()                        { return print(stdout, '\n'); }

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

    string to_string(bool trueOrFalse) noexcept
    {
        return trueOrFalse ? "true"s : "false"s;
    }

    string to_string(const char* cstr) noexcept
    {
        return cstr ? string{ cstr } : string{};
    }

    ////////////////////////////////////////////////////////////////////////////////
}
<commit_msg>Fixed a missing `std::`<commit_after>#include "sprint.h"
#include <cstdarg> // va_start
#include <cstdlib> // malloc/free/realloc

namespace rpp
{
    ////////////////////////////////////////////////////////////////////////////////

    string_buffer::~string_buffer() noexcept
    {
        if (cap > SIZE) free(ptr);
    }

    void string_buffer::clear()
    {
        ptr[len = 0] = '\0';
    }

    void string_buffer::reserve(int count) noexcept
    {
        int newlen = len + count + 1;
        if (newlen > cap)
        {
            int align = cap; // cap is always aligned
            int newcap = newlen + align;
            if (int rem = newcap % align)
                newcap += align - rem;

            if (cap == SIZE)
                ptr = (char*)memcpy(malloc(newcap), buf, len);
            else
                ptr = (char*)realloc(ptr, newcap);
            cap = newcap;
        }
    }

    void string_buffer::writef(const char* format, ...)
    {
        char buffer[8192];
        va_list ap; va_start(ap, format);
        int n = vsnprintf(buffer, sizeof(buffer), format, ap);
        if (n < 0 || n >= (int)sizeof(buffer))
            n = sizeof(buffer) - 1;
        reserve(n);
        memcpy(&ptr[len], buffer, (size_t)n);
        len += n;
        ptr[len] = '\0';
    }

    void string_buffer::write(const string_buffer& sb) { write(sb.view()); }
    void string_buffer::write_ptr_begin() { write("*{");   }
    void string_buffer::write(std::nullptr_t)  { write("null"); }
    void string_buffer::write_ptr_end()   { write('}');    }

    void string_buffer::write(const strview& s)
    {
        reserve(s.len);
        char* dst = ptr + len;
        memcpy(dst, s.str, (size_t)s.len);
        len += s.len;
        ptr[len] = '\0';
    }

    void string_buffer::write(const char& value)
    {
        reserve(1);
        ptr[len++] = value;
        ptr[len] = '\0';
    }

    void string_buffer::write(bool value)   { write(value ? "true"_sv : "false"_sv); }
    void string_buffer::write(rpp::byte bv) { reserve(4);  len += _tostring(&ptr[len], bv);    }
    void string_buffer::write(short value)  { reserve(8);  len += _tostring(&ptr[len], value); }
    void string_buffer::write(ushort value) { reserve(8);  len += _tostring(&ptr[len], value); }
    void string_buffer::write(int value)    { reserve(16); len += _tostring(&ptr[len], value); }
    void string_buffer::write(uint value)   { reserve(16); len += _tostring(&ptr[len], value); }
    void string_buffer::write(int64 value)  { reserve(32); len += _tostring(&ptr[len], value); }
    void string_buffer::write(uint64 value) { reserve(32); len += _tostring(&ptr[len], value); }
    void string_buffer::write(float value)  { reserve(32); len += _tostring(&ptr[len], value); }
    void string_buffer::write(double value) { reserve(48); len += _tostring(&ptr[len], value); }

    void string_buffer::writeln()     { write('\n'); }
    void string_buffer::write_quote() { write('"');  }
    void string_buffer::write_apos()  { write('\''); }
    void string_buffer::write_colon() { write(": "); }
    void string_buffer::write_separator() { write(separator); }

    void string_buffer::pretty_cont_start(int count, bool newlines)
    {
        if (count == 0) return write("{}");
        if (count > 4) { write('['); write(count); write("] = { "); }
        else { write("{ "); }
        if (newlines) write('\n');
    }
    void string_buffer::pretty_cont_item_start(bool newlines)
    {
        if (newlines) write("  ");
    }
    void string_buffer::pretty_cont_item_end(int i, int count, bool newlines)
    {
        if (++i < count) write(", ");
        if (newlines) write('\n');
    }
    void string_buffer::pretty_cont_end(int count, bool newlines)
    {
        if (count > 0) write(" }");
        if (newlines) write('\n');
    }
    ////////////////////////////////////////////////////////////////////////////////

    int print(FILE* file, strview value) { return (int)fwrite(value.str, value.len, 1, file); }
    int print(FILE* file, char value)    { return (int)fwrite(&value, 1, 1, file); }
    int print(FILE* file, rpp::byte value){char buf[4];  return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, short value)   { char buf[8];  return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, ushort value)  { char buf[8];  return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, int value)     { char buf[16]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, uint value)    { char buf[16]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, int64 value)   { char buf[32]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }
    int print(FILE* file, uint64 value)  { char buf[32]; return (int)fwrite(buf, _tostring(buf, value), 1, file); }

    int print(strview value)             { return print(stdout, value); }
    int print(char value)                { return print(stdout, value); }
    int print(rpp::byte value)           { return print(stdout, value); }
    int print(short value)               { return print(stdout, value); }
    int print(ushort value)              { return print(stdout, value); }
    int print(int value)                 { return print(stdout, value); }
    int print(uint value)                { return print(stdout, value); }
    int print(int64 value)               { return print(stdout, value); }
    int print(uint64 value)              { return print(stdout, value); }

    int println(FILE* file)              { return print(file, '\n'); }
    int println()                        { return print(stdout, '\n'); }

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

    string to_string(bool trueOrFalse) noexcept
    {
        return trueOrFalse ? "true"s : "false"s;
    }

    string to_string(const char* cstr) noexcept
    {
        return cstr ? string{ cstr } : string{};
    }

    ////////////////////////////////////////////////////////////////////////////////
}
<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/context.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/implementation/context.hpp"
#include <boost/test/unit_test.hpp>

BOOST_TEST_DONT_PRINT_LOG_VALUE(flusspferd::context)

BOOST_AUTO_TEST_CASE( null_context ) {
  flusspferd::context null_context;
  BOOST_CHECK(!null_context.is_valid());
}

BOOST_AUTO_TEST_CASE( copy_null_context ) {
  flusspferd::context original_null_context;
  BOOST_REQUIRE(!original_null_context.is_valid());
  flusspferd::context null_context;
  BOOST_CHECK(!null_context.is_valid());
}

BOOST_AUTO_TEST_CASE( create_context ) {
  flusspferd::context const &context = flusspferd::context::create();
  BOOST_CHECK(context.is_valid());
}

BOOST_AUTO_TEST_CASE( copy_create_context ) {
  flusspferd::context const &original_context = flusspferd::context::create();
  BOOST_REQUIRE(original_context.is_valid());
  flusspferd::context context(original_context);
  BOOST_CHECK(context.is_valid());
}

BOOST_AUTO_TEST_CASE( equality ) {
  flusspferd::context const &context1 = flusspferd::context::create();
  BOOST_REQUIRE(context1.is_valid());
  flusspferd::context const &context2 = flusspferd::context::create();
  BOOST_REQUIRE(context2.is_valid());
  flusspferd::context context3;
  BOOST_REQUIRE(!context3.is_valid());

  BOOST_CHECK_EQUAL(context1, context1);
  BOOST_CHECK(!(context1 != context1));

  BOOST_CHECK_EQUAL(context2, context2);
  BOOST_CHECK(!(context2 != context2));

  BOOST_CHECK_EQUAL(context3, context3);
  BOOST_CHECK(!(context3 != context3));

  BOOST_CHECK_NE(context1, context2);
  BOOST_CHECK(!(context1 == context2));

  BOOST_CHECK_NE(context1, context3);
  BOOST_CHECK(!(context1 == context3));

  BOOST_CHECK_NE(context3, context2);
  BOOST_CHECK(!(context3 == context2));

  flusspferd::context copy_context1(context1);

  BOOST_CHECK_EQUAL(context1, copy_context1);
  BOOST_CHECK_EQUAL(copy_context1, context1);

  BOOST_CHECK_NE(copy_context1, context2);
  BOOST_CHECK_NE(context2, copy_context1);

  BOOST_CHECK_NE(copy_context1, context3);
  BOOST_CHECK_NE(context3, copy_context1);

  flusspferd::context copy_context3(context3);

  BOOST_CHECK_EQUAL(context3, copy_context3);
  BOOST_CHECK_EQUAL(copy_context3, context3);

  BOOST_CHECK_NE(copy_context3, context1);
  BOOST_CHECK_NE(context1, copy_context3);

  BOOST_CHECK_NE(copy_context3, context2);
  BOOST_CHECK_NE(context2, copy_context3);
}

BOOST_AUTO_TEST_CASE( gc ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());
  BOOST_CHECK_NO_THROW(context.gc());
  BOOST_REQUIRE(context.is_valid());
}

BOOST_AUTO_TEST_CASE( global ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());

  flusspferd::object global;
  BOOST_CHECK_NO_THROW(global = context.global());

  BOOST_CHECK(global.is_valid());
}

BOOST_AUTO_TEST_CASE( evaluate ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());

  BOOST_CHECK(context.evaluate("null", 0, __FILE__, 0).is_null());
  BOOST_CHECK(context.evaluate("null", __FILE__, 0).is_null());
  BOOST_CHECK(context.evaluate(std::string("null"), __FILE__, 0).is_null());
}

BOOST_AUTO_TEST_SUITE( spidermonkey )

BOOST_AUTO_TEST_CASE( direct_null_context ) {
  flusspferd::context const &null_context = flusspferd::Impl::wrap_context(0);
  BOOST_CHECK(!null_context.is_valid());
}

BOOST_AUTO_TEST_CASE( create_context ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());

  JSContext *cx;
  BOOST_CHECK_NO_THROW(cx = flusspferd::Impl::get_context(context));

  BOOST_CHECK_NE(cx, (JSContext*) 0);
}

BOOST_AUTO_TEST_SUITE_END()

<commit_msg>fix broken test-case<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "flusspferd/context.hpp"
#include "flusspferd/object.hpp"
#include "flusspferd/implementation/context.hpp"
#include <boost/test/unit_test.hpp>

BOOST_TEST_DONT_PRINT_LOG_VALUE(flusspferd::context)

BOOST_AUTO_TEST_CASE( null_context ) {
  flusspferd::context null_context;
  BOOST_CHECK(!null_context.is_valid());
}

BOOST_AUTO_TEST_CASE( copy_null_context ) {
  flusspferd::context original_null_context;
  BOOST_REQUIRE(!original_null_context.is_valid());
  flusspferd::context null_context;
  BOOST_CHECK(!null_context.is_valid());
}

BOOST_AUTO_TEST_CASE( create_context ) {
  flusspferd::context const &context = flusspferd::context::create();
  BOOST_CHECK(context.is_valid());
}

BOOST_AUTO_TEST_CASE( copy_create_context ) {
  flusspferd::context const &original_context = flusspferd::context::create();
  BOOST_REQUIRE(original_context.is_valid());
  flusspferd::context context(original_context);
  BOOST_CHECK(context.is_valid());
}

BOOST_AUTO_TEST_CASE( equality ) {
  flusspferd::context const &context1 = flusspferd::context::create();
  BOOST_REQUIRE(context1.is_valid());
  flusspferd::context const &context2 = flusspferd::context::create();
  BOOST_REQUIRE(context2.is_valid());
  flusspferd::context context3;
  BOOST_REQUIRE(!context3.is_valid());

  BOOST_CHECK_EQUAL(context1, context1);
  BOOST_CHECK(!(context1 != context1));

  BOOST_CHECK_EQUAL(context2, context2);
  BOOST_CHECK(!(context2 != context2));

  BOOST_CHECK_EQUAL(context3, context3);
  BOOST_CHECK(!(context3 != context3));

  BOOST_CHECK_NE(context1, context2);
  BOOST_CHECK(!(context1 == context2));

  BOOST_CHECK_NE(context1, context3);
  BOOST_CHECK(!(context1 == context3));

  BOOST_CHECK_NE(context3, context2);
  BOOST_CHECK(!(context3 == context2));

  flusspferd::context copy_context1(context1);

  BOOST_CHECK_EQUAL(context1, copy_context1);
  BOOST_CHECK_EQUAL(copy_context1, context1);

  BOOST_CHECK_NE(copy_context1, context2);
  BOOST_CHECK_NE(context2, copy_context1);

  BOOST_CHECK_NE(copy_context1, context3);
  BOOST_CHECK_NE(context3, copy_context1);

  flusspferd::context copy_context3(context3);

  BOOST_CHECK_EQUAL(context3, copy_context3);
  BOOST_CHECK_EQUAL(copy_context3, context3);

  BOOST_CHECK_NE(copy_context3, context1);
  BOOST_CHECK_NE(context1, copy_context3);

  BOOST_CHECK_NE(copy_context3, context2);
  BOOST_CHECK_NE(context2, copy_context3);
}

BOOST_AUTO_TEST_CASE( gc ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());
  BOOST_CHECK_NO_THROW(context.gc());
  BOOST_REQUIRE(context.is_valid());
}

BOOST_AUTO_TEST_CASE( global ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());

  flusspferd::object global;
  BOOST_CHECK_NO_THROW(global = context.global());

  BOOST_CHECK(global.is_valid());
}

BOOST_AUTO_TEST_CASE( evaluate ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());

  BOOST_CHECK(context.evaluate("null", 4, __FILE__, 0).is_null());
  BOOST_CHECK(context.evaluate("null", __FILE__, 0).is_null());
  BOOST_CHECK(context.evaluate(std::string("null"), __FILE__, 0).is_null());
}

BOOST_AUTO_TEST_SUITE( spidermonkey )

BOOST_AUTO_TEST_CASE( direct_null_context ) {
  flusspferd::context const &null_context = flusspferd::Impl::wrap_context(0);
  BOOST_CHECK(!null_context.is_valid());
}

BOOST_AUTO_TEST_CASE( create_context ) {
  flusspferd::context context(flusspferd::context::create());
  BOOST_REQUIRE(context.is_valid());

  JSContext *cx;
  BOOST_CHECK_NO_THROW(cx = flusspferd::Impl::get_context(context));

  BOOST_CHECK_NE(cx, (JSContext*) 0);
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>


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

#include <boost/test/unit_test.hpp>
#include <boost/cstdint.hpp>
#include <pdal/Options.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/drivers/faux/Reader.hpp>
#include <pdal/filters/Programmable.hpp>
#include "Support.hpp"

using namespace pdal;

BOOST_AUTO_TEST_SUITE(LogTest)

BOOST_AUTO_TEST_CASE(test_one)
{
    const Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);

    Option opt1("bounds", bounds);
    Option opt2("log", Support::temppath("mylog.txt"));
    Option opt3("num_points", 1000);
    Option opt4("mode", "constant");

    Options opts;
    opts.add(opt1);
    opts.add(opt2);
    opts.add(opt3);
    opts.add(opt4);

    {
        pdal::drivers::faux::Reader reader(opts);
        reader.initialize();

        BOOST_CHECK_EQUAL(reader.log()->getLevel(), logERROR);
        reader.log()->setLevel(logDEBUG5);
        BOOST_CHECK_EQUAL(reader.log()->getLevel(), logDEBUG5);

        const Schema& schema = reader.getSchema();
        PointBuffer data(schema, 750);

        StageSequentialIterator* iter = reader.createSequentialIterator(data);
        boost::uint32_t numRead = iter->read(data);

        BOOST_CHECK_EQUAL(numRead, 750u);

        delete iter;
    }

    bool ok = Support::compare_text_files(Support::temppath("mylog.txt"), Support::datapath("logtest.txt"));
    BOOST_CHECK(ok);

    FileUtils::deleteFile(Support::temppath("mylog.txt"));

    return;
}

BOOST_AUTO_TEST_CASE(test_two)
{return;
    Options reader_opts;
    {
        const Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);
        Option opt1("bounds", bounds);
        Option opt2("log", Support::temppath("logtest_1.txt"));
        Option opt3("num_points", 1000);
        Option opt4("mode", "constant");

        reader_opts.add(opt1);
        reader_opts.add(opt2);
        reader_opts.add(opt3);
        reader_opts.add(opt4);
    }

    Options xfilter_opts;
    {
        const pdal::Option source("source",
            "import numpy as np\n"
            "def xfunc(ins,outs):\n"
            "  X = ins['X']\n"
            "  #print ins['X']\n"
            "  X = X + 1.0\n"
            "  outs['X'] = X\n"
            "  return True\n"
            );
        const pdal::Option module("module", "xModule");
        const pdal::Option function("function", "xfunc");
        xfilter_opts.add(source);
        xfilter_opts.add(module);
        xfilter_opts.add(function);

        Option optlog("log", Support::temppath("logtest_2.txt"));
        xfilter_opts.add(optlog);
    }

    Options yfilter_opts;
    {
        const pdal::Option source("source",
            "import numpy as np\n"
            "def yfunc(ins,outs):\n"
            "  Y = ins['Y']\n"
            "  #print ins['Y']\n"
            "  Y = Y + 1.0\n"
            "  outs['Y'] = Y\n"
            "  return True\n"
            );
        const pdal::Option module("module", "yModule");
        const pdal::Option function("function", "yfunc");
        yfilter_opts.add(source);
        yfilter_opts.add(module);
        yfilter_opts.add(function);

        Option optlog("log", Support::temppath("logtest_3.txt"));
        yfilter_opts.add(optlog);
 }

    {
        drivers::faux::Reader reader(reader_opts);
        filters::Programmable xfilter(reader, xfilter_opts);
        filters::Programmable yfilter(xfilter, yfilter_opts);

        yfilter.initialize();

        reader.log()->setLevel(logDEBUG5);
        xfilter.log()->setLevel(logDEBUG5);
        yfilter.log()->setLevel(logDEBUG5);

        const Schema& schema = yfilter.getSchema();
        PointBuffer data(schema, 750);

        StageSequentialIterator* iter = yfilter.createSequentialIterator(data);
        boost::uint32_t numRead = iter->read(data);

        BOOST_CHECK_EQUAL(numRead, 750u);

        delete iter;
    }

    //bool ok = Support::compare_text_files(Support::temppath("mylog.txt"), Support::datapath("logtest.txt"));
    //BOOST_CHECK(ok);

    FileUtils::deleteFile(Support::temppath("logtest_1.txt"));
    FileUtils::deleteFile(Support::temppath("logtest_2.txt"));
    FileUtils::deleteFile(Support::temppath("logtest_3.txt"));

    return;
}

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

#include <boost/test/unit_test.hpp>
#include <boost/cstdint.hpp>
#include <pdal/Options.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/drivers/faux/Reader.hpp>
#include <pdal/filters/Programmable.hpp>
#include "Support.hpp"

using namespace pdal;

BOOST_AUTO_TEST_SUITE(LogTest)

BOOST_AUTO_TEST_CASE(test_one)
{
    const Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);

    Option opt1("bounds", bounds);
    Option opt2("log", Support::temppath("mylog.txt"));
    Option opt3("num_points", 1000);
    Option opt4("mode", "constant");

    Options opts;
    opts.add(opt1);
    opts.add(opt2);
    opts.add(opt3);
    opts.add(opt4);

    {
        pdal::drivers::faux::Reader reader(opts);
        reader.initialize();

        BOOST_CHECK_EQUAL(reader.log()->getLevel(), logERROR);
        reader.log()->setLevel(logDEBUG5);
        BOOST_CHECK_EQUAL(reader.log()->getLevel(), logDEBUG5);

        const Schema& schema = reader.getSchema();
        PointBuffer data(schema, 750);

        StageSequentialIterator* iter = reader.createSequentialIterator(data);
        boost::uint32_t numRead = iter->read(data);

        BOOST_CHECK_EQUAL(numRead, 750u);

        delete iter;
    }

    bool ok = Support::compare_text_files(Support::temppath("mylog.txt"), Support::datapath("logtest.txt"));
    BOOST_CHECK(ok);

    FileUtils::deleteFile(Support::temppath("mylog.txt"));

    return;
}

BOOST_AUTO_TEST_CASE(test_two)
{
    // test commented out for now because it doesn't seem to do what mpg thought it was supposed to do
#if 0
    Options reader_opts;
    {
        const Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);
        Option opt1("bounds", bounds);
        Option opt2("log", Support::temppath("logtest_1.txt"));
        Option opt3("num_points", 1000);
        Option opt4("mode", "constant");

        reader_opts.add(opt1);
        reader_opts.add(opt2);
        reader_opts.add(opt3);
        reader_opts.add(opt4);
    }

    Options xfilter_opts;
    {
        const pdal::Option source("source",
            "import numpy as np\n"
            "def xfunc(ins,outs):\n"
            "  X = ins['X']\n"
            "  #print ins['X']\n"
            "  X = X + 1.0\n"
            "  outs['X'] = X\n"
            "  return True\n"
            );
        const pdal::Option module("module", "xModule");
        const pdal::Option function("function", "xfunc");
        xfilter_opts.add(source);
        xfilter_opts.add(module);
        xfilter_opts.add(function);

        Option optlog("log", Support::temppath("logtest_2.txt"));
        xfilter_opts.add(optlog);
    }

    Options yfilter_opts;
    {
        const pdal::Option source("source",
            "import numpy as np\n"
            "def yfunc(ins,outs):\n"
            "  Y = ins['Y']\n"
            "  #print ins['Y']\n"
            "  Y = Y + 1.0\n"
            "  outs['Y'] = Y\n"
            "  return True\n"
            );
        const pdal::Option module("module", "yModule");
        const pdal::Option function("function", "yfunc");
        yfilter_opts.add(source);
        yfilter_opts.add(module);
        yfilter_opts.add(function);

        Option optlog("log", Support::temppath("logtest_3.txt"));
        yfilter_opts.add(optlog);
    }

    {
        drivers::faux::Reader reader(reader_opts);
        filters::Programmable xfilter(reader, xfilter_opts);
        filters::Programmable yfilter(xfilter, yfilter_opts);

        yfilter.initialize();

        reader.log()->setLevel(logDEBUG5);
        xfilter.log()->setLevel(logDEBUG5);
        yfilter.log()->setLevel(logDEBUG5);

        const Schema& schema = yfilter.getSchema();
        PointBuffer data(schema, 750);

        StageSequentialIterator* iter = yfilter.createSequentialIterator(data);
        boost::uint32_t numRead = iter->read(data);

        BOOST_CHECK_EQUAL(numRead, 750u);

        delete iter;
    }

    //bool ok = Support::compare_text_files(Support::temppath("mylog.txt"), Support::datapath("logtest.txt"));
    //BOOST_CHECK(ok);

    FileUtils::deleteFile(Support::temppath("logtest_1.txt"));
    FileUtils::deleteFile(Support::temppath("logtest_2.txt"));
    FileUtils::deleteFile(Support::temppath("logtest_3.txt"));
#endif
    return;
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 * viewerexample.cpp
 *
 *  Created on: Jul 03, 2013
 *      Author: Bjorn Blissing
 */

#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>

#include "oculusviewer.h"
#include "oculuseventhandler.h"
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgUtil/GLObjectsVisitor>

int main( int argc, char** argv )
{
	// use an ArgumentParser object to manage the program arguments.
	osg::ArgumentParser arguments(&argc, argv);
	// read the scene from the list of file specified command line arguments.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

	// if not loaded assume no arguments passed in, try use default cow model instead.
	if (!loadedModel) loadedModel = osgDB::readNodeFile("cow.osgt");

	// Still no loaded model, then exit
	if (!loadedModel) {
		osg::notify(osg::ALWAYS) << "No model could be loaded and didn't find cow.osgt, terminating.." << std::endl;
		return 0;
	}

	// Create Trackball manipulator
	osg::ref_ptr<osgGA::CameraManipulator> cameraManipulator = new osgGA::TrackballManipulator;
	const osg::BoundingSphere& bs = loadedModel->getBound();

	if (bs.valid()) {
		// Adjust view to object view
		osg::Vec3 modelCenter = bs.center();
		osg::Vec3 eyePos = bs.center() + osg::Vec3(0, bs.radius(), 0);
		cameraManipulator->setHomePosition(eyePos, modelCenter, osg::Vec3(0, 0, 1));
	}

	// Open the HMD
	float nearClip = 0.01f;
	float farClip = 10000.0f;
	float pixelsPerDisplayPixel = 1.0;
	float worldUnitsPerMetre = 1.0f;
	int samples = 4;
	osg::ref_ptr<OculusDevice> oculusDevice = new OculusDevice(nearClip, farClip, pixelsPerDisplayPixel, worldUnitsPerMetre, samples);

	// Get the suggested context traits
	osg::ref_ptr<osg::GraphicsContext::Traits> traits = oculusDevice->graphicsContextTraits();
	traits->windowName = "OsgOculusViewerExample";

	// Create a graphic context based on our desired traits
	osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits);
	if (!gc) {
		osg::notify(osg::NOTICE) << "Error, GraphicsWindow has not been created successfully" << std::endl;
		return 1;
	}

	if (gc.valid()) {
		gc->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
		gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	}

	osgViewer::Viewer viewer(arguments);
	// Force single threaded to make sure that no other thread can use the GL context
	viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
	viewer.getCamera()->setGraphicsContext(gc);
	viewer.getCamera()->setViewport(0, 0, traits->width, traits->height);

	// Disable automatic computation of near and far plane
	viewer.getCamera()->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
	viewer.setCameraManipulator(cameraManipulator);

	// Things to do when viewer is realized
	osg::ref_ptr<OculusRealizeOperation> oculusRealizeOperation = new OculusRealizeOperation(oculusDevice);
	viewer.setRealizeOperation(oculusRealizeOperation.get());

	osg::ref_ptr<OculusViewer> oculusViewer = new OculusViewer(&viewer, oculusDevice, oculusRealizeOperation);
	oculusViewer->addChild(loadedModel);
	viewer.setSceneData(oculusViewer);
	// Add statistics handler
	viewer.addEventHandler(new osgViewer::StatsHandler);

	viewer.addEventHandler(new OculusEventHandler(oculusDevice));

#define standard_viewer_run 0
#if standard_viewer_run
	viewer.run();
#else
	// Realize viewer
	viewer.realize();

	// Start Viewer
	while (!viewer.done()) {
		viewer.frame();
	}
#endif

	return 0;
}
<commit_msg>Removed unnessesary include<commit_after>/*
 * viewerexample.cpp
 *
 *  Created on: Jul 03, 2013
 *      Author: Bjorn Blissing
 */

#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
#include <osgUtil/GLObjectsVisitor>

#include "oculusviewer.h"
#include "oculuseventhandler.h"

int main( int argc, char** argv )
{
	// use an ArgumentParser object to manage the program arguments.
	osg::ArgumentParser arguments(&argc, argv);
	// read the scene from the list of file specified command line arguments.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

	// if not loaded assume no arguments passed in, try use default cow model instead.
	if (!loadedModel) loadedModel = osgDB::readNodeFile("cow.osgt");

	// Still no loaded model, then exit
	if (!loadedModel) {
		osg::notify(osg::ALWAYS) << "No model could be loaded and didn't find cow.osgt, terminating.." << std::endl;
		return 0;
	}

	// Create Trackball manipulator
	osg::ref_ptr<osgGA::CameraManipulator> cameraManipulator = new osgGA::TrackballManipulator;
	const osg::BoundingSphere& bs = loadedModel->getBound();

	if (bs.valid()) {
		// Adjust view to object view
		osg::Vec3 modelCenter = bs.center();
		osg::Vec3 eyePos = bs.center() + osg::Vec3(0, bs.radius(), 0);
		cameraManipulator->setHomePosition(eyePos, modelCenter, osg::Vec3(0, 0, 1));
	}

	// Open the HMD
	float nearClip = 0.01f;
	float farClip = 10000.0f;
	float pixelsPerDisplayPixel = 1.0;
	float worldUnitsPerMetre = 1.0f;
	int samples = 4;
	osg::ref_ptr<OculusDevice> oculusDevice = new OculusDevice(nearClip, farClip, pixelsPerDisplayPixel, worldUnitsPerMetre, samples);

	// Get the suggested context traits
	osg::ref_ptr<osg::GraphicsContext::Traits> traits = oculusDevice->graphicsContextTraits();
	traits->windowName = "OsgOculusViewerExample";

	// Create a graphic context based on our desired traits
	osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits);
	if (!gc) {
		osg::notify(osg::NOTICE) << "Error, GraphicsWindow has not been created successfully" << std::endl;
		return 1;
	}

	if (gc.valid()) {
		gc->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
		gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	}

	osgViewer::Viewer viewer(arguments);
	// Force single threaded to make sure that no other thread can use the GL context
	viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
	viewer.getCamera()->setGraphicsContext(gc);
	viewer.getCamera()->setViewport(0, 0, traits->width, traits->height);

	// Disable automatic computation of near and far plane
	viewer.getCamera()->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
	viewer.setCameraManipulator(cameraManipulator);

	// Things to do when viewer is realized
	osg::ref_ptr<OculusRealizeOperation> oculusRealizeOperation = new OculusRealizeOperation(oculusDevice);
	viewer.setRealizeOperation(oculusRealizeOperation.get());

	osg::ref_ptr<OculusViewer> oculusViewer = new OculusViewer(&viewer, oculusDevice, oculusRealizeOperation);
	oculusViewer->addChild(loadedModel);
	viewer.setSceneData(oculusViewer);
	// Add statistics handler
	viewer.addEventHandler(new osgViewer::StatsHandler);

	viewer.addEventHandler(new OculusEventHandler(oculusDevice));

#define standard_viewer_run 0
#if standard_viewer_run
	viewer.run();
#else
	// Realize viewer
	viewer.realize();

	// Start Viewer
	while (!viewer.done()) {
		viewer.frame();
	}
#endif

	return 0;
}
<|endoftext|>


<commit_before>#include "Test.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkRect.h"

static inline const char* boolStr(bool value) {
    return value ? "true" : "false";
}

// these are in the same order as the SkBitmap::Config enum
static const char* gConfigName[] = {
    "None", "A1", "A8", "Index8", "565", "4444", "8888", "RLE_Index8"
};

/** Returns -1 on success, else the x coord of the first bad pixel, return its
    value in bad
 */
typedef int (*Proc)(const void*, int width, uint32_t expected, uint32_t* bad);

static int proc_32(const void* ptr, int w, uint32_t expected, uint32_t* bad) {
    const SkPMColor* addr = static_cast<const SkPMColor*>(ptr);
    for (int x = 0; x < w; x++) {
        if (addr[x] != expected) {
            *bad = addr[x];
            return x;
        }
    }
    return -1;
}

static int proc_16(const void* ptr, int w, uint32_t expected, uint32_t* bad) {
    const uint16_t* addr = static_cast<const uint16_t*>(ptr);
    for (int x = 0; x < w; x++) {
        if (addr[x] != expected) {
            *bad = addr[x];
            return x;
        }
    }
    return -1;
}

static int proc_8(const void* ptr, int w, uint32_t expected, uint32_t* bad) {
    const SkPMColor* addr = static_cast<const SkPMColor*>(ptr);
    for (int x = 0; x < w; x++) {
        if (SkGetPackedA32(addr[x]) != expected) {
            *bad = SkGetPackedA32(addr[x]);
            return x;
        }
    }
    return -1;
}

static int proc_bad(const void* ptr, int, uint32_t, uint32_t* bad) {
    *bad = 0;
    return 0;
}

static Proc find_proc(const SkBitmap& bm, SkPMColor expect32, uint16_t expect16,
                      uint8_t expect8, uint32_t* expect) {
    switch (bm.config()) {
        case SkBitmap::kARGB_8888_Config:
            *expect = expect32;
            return proc_32;
        case SkBitmap::kARGB_4444_Config:
        case SkBitmap::kRGB_565_Config:
            *expect = expect16;
            return proc_16;
        case SkBitmap::kA8_Config:
            *expect = expect8;
            return proc_8;
        default:
            *expect = 0;
            return proc_bad;
    }
}

static bool check_color(const SkBitmap& bm, SkPMColor expect32,
                        uint16_t expect16, uint8_t expect8,
                        skiatest::Reporter* reporter) {
    uint32_t expect;
    Proc proc = find_proc(bm, expect32, expect16, expect8, &expect);
    for (int y = 0; y < bm.height(); y++) {
        uint32_t bad;
        int x = proc(bm.getAddr(0, y), bm.width(), expect, &bad);
        if (x >= 0) {
            SkString str;
            str.printf("BlitRow config=%s [%d %d] expected %x got %x",
                       gConfigName[bm.config()], x, y, expect, bad);
            reporter->reportFailed(str);
            return false;
        }
    }
    return true;
}

static void TestBlitRow(skiatest::Reporter* reporter) {
    static const int W = 256;

    static const SkBitmap::Config gDstConfig[] = {
        SkBitmap::kARGB_8888_Config,
        SkBitmap::kRGB_565_Config,
//        SkBitmap::kARGB_4444_Config,
//        SkBitmap::kA8_Config,
    };

    static const struct {
        SkColor     fSrc;
        SkColor     fDst;
        SkPMColor   fResult32;
        uint16_t    fResult16;
        uint8_t     fResult8;
    } gSrcRec[] = {
        { 0,            0,          0,                                    0,      0 },
        { 0,            0xFFFFFFFF, SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF), 0xFFFF, 0xFF },
        { 0xFFFFFFFF,   0,          SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF), 0xFFFF, 0xFF },
        { 0xFFFFFFFF,   0xFFFFFFFF, SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF), 0xFFFF, 0xFF },
    };

    SkPaint paint;
    paint.setDither(true);

    SkBitmap srcBM;
    srcBM.setConfig(SkBitmap::kARGB_8888_Config, W, 1);
    srcBM.allocPixels();

    for (size_t i = 0; i < SK_ARRAY_COUNT(gDstConfig); i++) {
        SkBitmap dstBM;
        dstBM.setConfig(gDstConfig[i], W, 1);
        dstBM.allocPixels();

        SkCanvas canvas(dstBM);
        for (size_t j = 0; j < SK_ARRAY_COUNT(gSrcRec); j++) {
            srcBM.eraseColor(gSrcRec[j].fSrc);
            dstBM.eraseColor(gSrcRec[j].fDst);

            for (int k = 0; k < 4; k++) {
                bool dither = (k & 1) != 0;
                bool blend = (k & 2) != 0;
                if (gSrcRec[j].fSrc != 0 && blend) {
                    // can't make a numerical promise about blending anything
                    // but 0
                 //   continue;
                }
                paint.setDither(dither);
                paint.setAlpha(blend ? 0x80 : 0xFF);
                canvas.drawBitmap(srcBM, 0, 0, &paint);
                if (!check_color(dstBM, gSrcRec[j].fResult32, gSrcRec[j].fResult16,
                                 gSrcRec[j].fResult8, reporter)) {
                    SkDebugf("--- src index %d dither %d blend %d\n", j, dither, blend);
                }
            }
        }
    }
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("BlitRow", TestBlitRowClass, TestBlitRow)
<commit_msg>update blitrow test to exercise different widths for blitrow<commit_after>#include "Test.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkGradientShader.h"
#include "SkRect.h"

static inline const char* boolStr(bool value) {
    return value ? "true" : "false";
}

// these are in the same order as the SkBitmap::Config enum
static const char* gConfigName[] = {
    "None", "A1", "A8", "Index8", "565", "4444", "8888", "RLE_Index8"
};

/** Returns -1 on success, else the x coord of the first bad pixel, return its
    value in bad
 */
typedef int (*Proc)(const void*, int width, uint32_t expected, uint32_t* bad);

static int proc_32(const void* ptr, int w, uint32_t expected, uint32_t* bad) {
    const SkPMColor* addr = static_cast<const SkPMColor*>(ptr);
    for (int x = 0; x < w; x++) {
        if (addr[x] != expected) {
            *bad = addr[x];
            return x;
        }
    }
    return -1;
}

static int proc_16(const void* ptr, int w, uint32_t expected, uint32_t* bad) {
    const uint16_t* addr = static_cast<const uint16_t*>(ptr);
    for (int x = 0; x < w; x++) {
        if (addr[x] != expected) {
            *bad = addr[x];
            return x;
        }
    }
    return -1;
}

static int proc_8(const void* ptr, int w, uint32_t expected, uint32_t* bad) {
    const SkPMColor* addr = static_cast<const SkPMColor*>(ptr);
    for (int x = 0; x < w; x++) {
        if (SkGetPackedA32(addr[x]) != expected) {
            *bad = SkGetPackedA32(addr[x]);
            return x;
        }
    }
    return -1;
}

static int proc_bad(const void* ptr, int, uint32_t, uint32_t* bad) {
    *bad = 0;
    return 0;
}

static Proc find_proc(const SkBitmap& bm, SkPMColor expect32, uint16_t expect16,
                      uint8_t expect8, uint32_t* expect) {
    switch (bm.config()) {
        case SkBitmap::kARGB_8888_Config:
            *expect = expect32;
            return proc_32;
        case SkBitmap::kARGB_4444_Config:
        case SkBitmap::kRGB_565_Config:
            *expect = expect16;
            return proc_16;
        case SkBitmap::kA8_Config:
            *expect = expect8;
            return proc_8;
        default:
            *expect = 0;
            return proc_bad;
    }
}

static bool check_color(const SkBitmap& bm, SkPMColor expect32,
                        uint16_t expect16, uint8_t expect8,
                        skiatest::Reporter* reporter) {
    uint32_t expect;
    Proc proc = find_proc(bm, expect32, expect16, expect8, &expect);
    for (int y = 0; y < bm.height(); y++) {
        uint32_t bad;
        int x = proc(bm.getAddr(0, y), bm.width(), expect, &bad);
        if (x >= 0) {
            SkString str;
            str.printf("BlitRow config=%s [%d %d] expected %x got %x",
                       gConfigName[bm.config()], x, y, expect, bad);
            reporter->reportFailed(str);
            return false;
        }
    }
    return true;
}

// Make sure our blits always map src==0 to a noop, and src==FF to full opaque
static void test_00_FF(skiatest::Reporter* reporter) {
    static const int W = 256;

    static const SkBitmap::Config gDstConfig[] = {
        SkBitmap::kARGB_8888_Config,
        SkBitmap::kRGB_565_Config,
//        SkBitmap::kARGB_4444_Config,
//        SkBitmap::kA8_Config,
    };

    static const struct {
        SkColor     fSrc;
        SkColor     fDst;
        SkPMColor   fResult32;
        uint16_t    fResult16;
        uint8_t     fResult8;
    } gSrcRec[] = {
        { 0,            0,          0,                                    0,      0 },
        { 0,            0xFFFFFFFF, SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF), 0xFFFF, 0xFF },
        { 0xFFFFFFFF,   0,          SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF), 0xFFFF, 0xFF },
        { 0xFFFFFFFF,   0xFFFFFFFF, SkPackARGB32(0xFF, 0xFF, 0xFF, 0xFF), 0xFFFF, 0xFF },
    };

    SkPaint paint;

    SkBitmap srcBM;
    srcBM.setConfig(SkBitmap::kARGB_8888_Config, W, 1);
    srcBM.allocPixels();

    for (size_t i = 0; i < SK_ARRAY_COUNT(gDstConfig); i++) {
        SkBitmap dstBM;
        dstBM.setConfig(gDstConfig[i], W, 1);
        dstBM.allocPixels();

        SkCanvas canvas(dstBM);
        for (size_t j = 0; j < SK_ARRAY_COUNT(gSrcRec); j++) {
            srcBM.eraseColor(gSrcRec[j].fSrc);
            dstBM.eraseColor(gSrcRec[j].fDst);

            for (int k = 0; k < 4; k++) {
                bool dither = (k & 1) != 0;
                bool blend = (k & 2) != 0;
                if (gSrcRec[j].fSrc != 0 && blend) {
                    // can't make a numerical promise about blending anything
                    // but 0
                 //   continue;
                }
                paint.setDither(dither);
                paint.setAlpha(blend ? 0x80 : 0xFF);
                canvas.drawBitmap(srcBM, 0, 0, &paint);
                if (!check_color(dstBM, gSrcRec[j].fResult32, gSrcRec[j].fResult16,
                                 gSrcRec[j].fResult8, reporter)) {
                    SkDebugf("--- src index %d dither %d blend %d\n", j, dither, blend);
                }
            }
        }
    }
}

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

struct Mesh {
    SkPoint     fPts[4];
    uint16_t    fIndices[6];

    Mesh(const SkBitmap& bm, SkPaint* paint) {
        const SkScalar w = SkIntToScalar(bm.width());
        const SkScalar h = SkIntToScalar(bm.height());
        fPts[0].set(0, 0);
        fPts[1].set(w, 0);
        fPts[2].set(w, h);
        fPts[3].set(0, h);
        SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kClamp_TileMode,
                                                   SkShader::kClamp_TileMode);
        paint->setShader(s)->unref();

    }

    void draw(SkCanvas* canvas, SkPaint* paint) {
        canvas->drawVertices(SkCanvas::kTriangleFan_VertexMode, 4, fPts, fPts,
                             NULL, NULL, NULL, 0, *paint);
    }
};

#include "SkImageEncoder.h"
static void save_bm(const SkBitmap& bm, const char name[]) {
    SkImageEncoder::EncodeFile(name, bm, SkImageEncoder::kPNG_Type, 100);
}

static bool gOnce;

// Make sure our blits are invariant with the width of the blit (i.e. that
// special case for 8 at a time have the same results as narrower blits)
static void test_diagonal(skiatest::Reporter* reporter) {
    static const int W = 64;
    static const int H = W;

    static const SkBitmap::Config gDstConfig[] = {
        SkBitmap::kARGB_8888_Config,
        SkBitmap::kRGB_565_Config,
        //        SkBitmap::kARGB_4444_Config,
        //        SkBitmap::kA8_Config,
    };

    static const SkColor gDstBG[] = { 0, 0xFFFFFFFF };

    SkPaint paint;

    SkBitmap srcBM;
    srcBM.setConfig(SkBitmap::kARGB_8888_Config, W, H);
    srcBM.allocPixels();
    SkRect srcR = { 0, 0, srcBM.width(), srcBM.height() };

    // cons up a mesh to draw the bitmap with
    Mesh mesh(srcBM, &paint);

    for (size_t i = 0; i < SK_ARRAY_COUNT(gDstConfig); i++) {
        SkBitmap dstBM0, dstBM1;
        dstBM0.setConfig(gDstConfig[i], W, H);
        dstBM1.setConfig(gDstConfig[i], W, H);
        dstBM0.allocPixels();
        dstBM1.allocPixels();

        SkCanvas canvas0(dstBM0);
        SkCanvas canvas1(dstBM1);
        SkColor bgColor;

        for (size_t j = 0; j < SK_ARRAY_COUNT(gDstBG); j++) {
            bgColor = gDstBG[j];

            for (int c = 0; c <= 0xFF; c++) {
                srcBM.eraseARGB(0xFF, c, c, c);

                for (int k = 0; k < 4; k++) {
                    bool dither = (k & 1) != 0;
                    uint8_t alpha = (k & 2) ? 0x80 : 0xFF;
                    paint.setDither(dither);
                    paint.setAlpha(alpha);

                    dstBM0.eraseColor(bgColor);
                    dstBM1.eraseColor(bgColor);

                    canvas0.drawRect(srcR, paint);
                    mesh.draw(&canvas1, &paint);

                    if (!gOnce && false) {
                        save_bm(dstBM0, "drawBitmap.png");
                        save_bm(dstBM1, "drawMesh.png");
                        gOnce = true;
                    }

                    if (memcmp(dstBM0.getPixels(), dstBM1.getPixels(), dstBM0.getSize())) {
                        SkString str;
                        str.printf("Diagonal config=%s bg=0x%x dither=%d alpha=0x%x src=0x%x",
                                   gConfigName[gDstConfig[i]], bgColor, dither, alpha, c);
                        reporter->reportFailed(str);
                    }
                }
            }
        }
    }
}

static void TestBlitRow(skiatest::Reporter* reporter) {
    test_00_FF(reporter);
    test_diagonal(reporter);
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("BlitRow", TestBlitRowClass, TestBlitRow)
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */
#include <libport/unit-test.hh>
#include <libport/sysexits.hh>
using libport::test_suite;

#include <libport/asio.hh>
#include <libport/utime.hh>
#include <libport/unistd.h>

bool abort_ctor = false;

const char* msg = "coincoin\n";

// On OSX:
//   listen            connect        status
// "127.0.0.1"       "127.0.0.1"       PASS  IPv4
// "localhost"       "localhost"       PASS  IPv6
// ""                "localhost"       PASS  IPv6
// ""                "127.0.0.1"       FAIL
// ""                ""                PASS  IPv6
static const char* listen_host = "127.0.0.1";
static const char* connect_host = "127.0.0.1";

template<class T>
void
hold_for(T, libport::utime_t duration)
{
  usleep(duration);
  BOOST_TEST_MESSAGE("Done holding your T");
}

void
delayed_response(boost::shared_ptr<libport::UDPLink> l,
                 libport::utime_t duration)
{
  usleep(duration);
  l->reply("hop hop\n");
}

// Hack until we can kill listenig sockets.
static bool enable_delay = false;
void reply_delay(const void*, int,
                 boost::shared_ptr<libport::UDPLink> l,
                 libport::utime_t duration)
{
  libport::startThread(boost::bind(&delayed_response, l, duration));
}

void echo(const void* d, int s, boost::shared_ptr<libport::UDPLink> l)
{
  if (enable_delay)
    reply_delay(d, s, l, 500000);
  else
    l->reply(d, s);
}

class TestSocket: public libport::Socket
{
  public:
  TestSocket()
    : nRead(0), echo(false), dump(false)
    {
      BOOST_CHECK(!abort_ctor);
      nInstance++;
    }
  TestSocket(bool echo, bool dump)
    : nRead(0), echo(echo), dump(dump)
    {
      BOOST_CHECK(!abort_ctor);
      nInstance++;
    }
  virtual ~TestSocket()
  {
    nInstance--;
    //BOOST_TEST_MESSAGE(this <<" dying, in " << K_get() << " lasterror=" << lastError.message());
    //assert(false);
  }

  int onRead(const void* data, size_t size)
  {
    nRead++;
    //BOOST_TEST_MESSAGE(this << " read " << size);
    if (echo)
      write(data, size);
    if (dump)
      received += std::string((const char*)data, size);
    return size;
  }

  void onError(boost::system::error_code erc)
  {
    lastError = erc;
    destroy();
  }
  // Number of times read callback was called
  int nRead;
  // Echo back what is received.
  bool echo;
  // Store what is received in received.
  bool dump;
  std::string received;
  boost::system::error_code lastError;
  static TestSocket* factory()
    {
      return lastInstance = new TestSocket();
    }
  static TestSocket* factoryEx(bool echo, bool dump)
    {
      return lastInstance = new TestSocket(echo, dump);
    }
  static int nInstance;
  // Last factory-created instance.
  static TestSocket* lastInstance;
};

int TestSocket::nInstance = 0;
TestSocket* TestSocket::lastInstance = 0;

// Delay in microseconds used to sleep when something asynchronous
// is happening.
static const int delay = 200000;

static const int AVAIL_PORT = 7890;
static const std::string S_AVAIL_PORT = "7890";

void test_one(bool proto)
{
  TestSocket* client = new TestSocket(false, true);
  boost::system::error_code err
    = client->connect(connect_host, S_AVAIL_PORT, proto);
  BOOST_REQUIRE_MESSAGE(!err, err.message());
  BOOST_CHECK_NO_THROW(client->send(msg));
  usleep(delay);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, proto ? 1 : 2);
  BOOST_CHECK_EQUAL(client->received, msg);
  if (!proto)
    BOOST_CHECK_EQUAL(TestSocket::lastInstance->received,
                      msg);
  BOOST_CHECK_EQUAL(client->getRemotePort(), AVAIL_PORT);
  if (!proto)
    BOOST_CHECK_EQUAL(TestSocket::lastInstance->getLocalPort(),
                      AVAIL_PORT);
  if (!proto)
    BOOST_CHECK_EQUAL(TestSocket::lastInstance->getRemotePort(),
                      client->getLocalPort());
  // Close client-end. Should send error both ways and destroy all sockets.
  client->close();
  usleep(delay);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);
}

#define RESOLVE()                                                       \
  do {                                                                  \
    libport::resolve<boost::asio::ip::tcp>(connect_host,                \
                                           S_AVAIL_PORT, err);          \
    BOOST_TEST_MESSAGE("Resolve: "                                      \
                       + (err ? err.message() : "No error"));           \
  } while (0)

static
void
test()
{
  // Basic TCP
  BOOST_TEST_MESSAGE("##Safe destruction");
  boost::system::error_code err;
  TestSocket* s = new TestSocket(false, false);
  s->connect(connect_host, S_AVAIL_PORT, false);
  s->destroy();
  usleep(delay);
  RESOLVE();
  libport::Socket* h = new libport::Socket();
  err = h->listen(boost::bind(&TestSocket::factoryEx, true, true),
                  listen_host, S_AVAIL_PORT, false);
  BOOST_CHECK_MESSAGE(!err, err.message());
  BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT);

  BOOST_TEST_MESSAGE("##One client");
  RESOLVE();
  RESOLVE();
  RESOLVE();
  RESOLVE();
  test_one(false);
  BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT);
  RESOLVE();
  test_one(false);
  BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT);
  RESOLVE();
  test_one(false);
  BOOST_TEST_MESSAGE("Socket on stack");
  {
    TestSocket s(false, true);
    err = s.connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    s.send(msg);
    usleep(delay);
  }
  usleep(delay*2);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);

  test_one(false);
  BOOST_TEST_MESSAGE("##many clients");
  std::vector<TestSocket*> clients;
  for (int i=0; i<10; i++)
  {
    TestSocket* client = new TestSocket(false, true);
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    client->send(msg);
    clients.push_back(client);
  }
  usleep(delay*3);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 20);
  foreach(TestSocket* s, clients)
  {
    BOOST_CHECK_EQUAL(s->received, msg);
    s->close();
  }
  usleep(delay*3);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);

  BOOST_TEST_MESSAGE("##Failing connections");
  {
    TestSocket* client = new TestSocket();
    err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", false);
    BOOST_CHECK_MESSAGE(err, err.message());

    err = client->connect(connect_host, "nosuchport", false);
    BOOST_CHECK_MESSAGE(err, err.message());

    // Try to reuse that wasted socket.
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    // Destroy without closing.
    client->destroy();
    usleep(delay);
    BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);
  }

  // Timeout
  BOOST_TEST_MESSAGE("##Timeout connect");
  {
    TestSocket* client = new TestSocket();
    libport::utime_t start = libport::utime();
    err = client->connect("1.1.1.1", "10000", false, 1000000);
    BOOST_CHECK_MESSAGE(err, err.message());
    libport::utime_t timeout = libport::utime() - start;
    // Give it a good margin.
    BOOST_CHECK_LT(timeout, 1400000);
    client->destroy();
  }

  BOOST_TEST_MESSAGE("##Destruction locking");
  {
    TestSocket* client = new TestSocket();
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    usleep(delay);
    libport::startThread(
      boost::bind(&hold_for<libport::Destructible::DestructionLock>,
                  client->getDestructionLock(),
                  1000000));
    client->destroy();
    usleep(500000);
    // There can be 1 or 2 sockets at this point. Client must be still
    // alive because of the lock, but server might have died.
    BOOST_CHECK_MESSAGE(TestSocket::nInstance, TestSocket::nInstance);
    usleep(500000+delay);
    BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);
  }

  BOOST_TEST_MESSAGE("Destroy listener");
  {
    h->close();
    usleep(delay);
    TestSocket* client = new TestSocket();
    abort_ctor = true;
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(err, err.message());
    client->destroy();
    h->destroy();
    usleep(delay);
    abort_ctor = false;
  }

  BOOST_TEST_MESSAGE("##UDP");
  {
    libport::Socket::Handle hu =
      libport::Socket::listenUDP(listen_host, S_AVAIL_PORT, &echo, err);
    (void)hu;
    BOOST_CHECK_MESSAGE(!err, err.message());
    test_one(true);
    usleep(delay);
    test_one(true);

    TestSocket* client = new TestSocket();
    err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", true);
    BOOST_CHECK_MESSAGE(err, err.message());

    err = client->connect(connect_host, "nosuchport", true);
    BOOST_CHECK_MESSAGE(err, err.message());

    // Try to reuse that wasted socket.
    err = client->connect(connect_host, S_AVAIL_PORT, true);
    BOOST_CHECK_MESSAGE(!err, err.message());
    // Destroy without closing.
    client->destroy();
    usleep(delay);
    BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);

    // Check one-write-one-packet semantic
    client = new TestSocket(false, true);
    err = client->connect(connect_host, S_AVAIL_PORT, true);
    BOOST_CHECK_MESSAGE(!err, err.message());
    client->send("coin");
    client->send("pan");
    usleep(delay*2);
    BOOST_CHECK_EQUAL(client->received, "coinpan");
    BOOST_CHECK_EQUAL(client->nRead, 2);

    enable_delay = true;
    client = new TestSocket(false, true);
    err = client->connect(connect_host, S_AVAIL_PORT, true);
    BOOST_CHECK_MESSAGE(!err, err.message());
    client->send("coin");
    usleep(500000+delay);
    BOOST_CHECK_EQUAL(client->received, "hop hop\n");
  }
}

test_suite*
init_test_suite()
{
  // This test cannot run properly with current versions of WineHQ,
  // because they only provide a stub for acceptex.
  const char* running_wine = getenv("RUNNING_WINE");
  const char* running_qemu = getenv("RUNNING_QEMU");
  if ((running_wine && *running_wine) || (running_qemu && *running_qemu))
    std::cerr << "running under Wine, skipping this test"
              << std::endl
              << libport::exit(EX_SKIP);

  test_suite* suite = BOOST_TEST_SUITE("libport::asio test suite");
  suite->add(BOOST_TEST_CASE(test));
  return suite;
}
<commit_msg>Asio: more signedness issues.<commit_after>/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */
#include <libport/unit-test.hh>
#include <libport/sysexits.hh>
using libport::test_suite;

#include <libport/asio.hh>
#include <libport/utime.hh>
#include <libport/unistd.h>

bool abort_ctor = false;

const char* msg = "coincoin\n";

// On OSX:
//   listen            connect        status
// "127.0.0.1"       "127.0.0.1"       PASS  IPv4
// "localhost"       "localhost"       PASS  IPv6
// ""                "localhost"       PASS  IPv6
// ""                "127.0.0.1"       FAIL
// ""                ""                PASS  IPv6
static const char* listen_host = "127.0.0.1";
static const char* connect_host = "127.0.0.1";

template<class T>
void
hold_for(T, libport::utime_t duration)
{
  usleep(duration);
  BOOST_TEST_MESSAGE("Done holding your T");
}

void
delayed_response(boost::shared_ptr<libport::UDPLink> l,
                 libport::utime_t duration)
{
  usleep(duration);
  l->reply("hop hop\n");
}

// Hack until we can kill listenig sockets.
static bool enable_delay = false;
void reply_delay(const void*, int,
                 boost::shared_ptr<libport::UDPLink> l,
                 libport::utime_t duration)
{
  libport::startThread(boost::bind(&delayed_response, l, duration));
}

void echo(const void* d, int s, boost::shared_ptr<libport::UDPLink> l)
{
  if (enable_delay)
    reply_delay(d, s, l, 500000);
  else
    l->reply(d, s);
}

class TestSocket: public libport::Socket
{
  public:
  TestSocket()
    : nRead(0), echo(false), dump(false)
    {
      BOOST_CHECK(!abort_ctor);
      nInstance++;
    }
  TestSocket(bool echo, bool dump)
    : nRead(0), echo(echo), dump(dump)
    {
      BOOST_CHECK(!abort_ctor);
      nInstance++;
    }
  virtual ~TestSocket()
  {
    nInstance--;
    //BOOST_TEST_MESSAGE(this <<" dying, in " << K_get() << " lasterror=" << lastError.message());
    //assert(false);
  }

  size_t onRead(const void* data, size_t size)
  {
    nRead++;
    //BOOST_TEST_MESSAGE(this << " read " << size);
    if (echo)
      write(data, size);
    if (dump)
      received += std::string((const char*)data, size);
    return size;
  }

  void onError(boost::system::error_code erc)
  {
    lastError = erc;
    destroy();
  }
  // Number of times read callback was called
  size_t nRead;
  // Echo back what is received.
  bool echo;
  // Store what is received in received.
  bool dump;
  std::string received;
  boost::system::error_code lastError;
  static TestSocket* factory()
    {
      return lastInstance = new TestSocket();
    }
  static TestSocket* factoryEx(bool echo, bool dump)
    {
      return lastInstance = new TestSocket(echo, dump);
    }
  static size_t nInstance;
  // Last factory-created instance.
  static TestSocket* lastInstance;
};

size_t TestSocket::nInstance = 0;
TestSocket* TestSocket::lastInstance = 0;

// Delay in microseconds used to sleep when something asynchronous
// is happening.
static const useconds_t delay = 200000;

static const int AVAIL_PORT = 7890;
static const std::string S_AVAIL_PORT = string_cast(AVAIL_PORT);

void test_one(bool proto)
{
  TestSocket* client = new TestSocket(false, true);
  boost::system::error_code err
    = client->connect(connect_host, S_AVAIL_PORT, proto);
  BOOST_REQUIRE_MESSAGE(!err, err.message());
  BOOST_CHECK_NO_THROW(client->send(msg));
  usleep(delay);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, proto ? 1 : 2);
  BOOST_CHECK_EQUAL(client->received, msg);
  if (!proto)
    BOOST_CHECK_EQUAL(TestSocket::lastInstance->received,
                      msg);
  BOOST_CHECK_EQUAL(client->getRemotePort(), AVAIL_PORT);
  if (!proto)
    BOOST_CHECK_EQUAL(TestSocket::lastInstance->getLocalPort(),
                      AVAIL_PORT);
  if (!proto)
    BOOST_CHECK_EQUAL(TestSocket::lastInstance->getRemotePort(),
                      client->getLocalPort());
  // Close client-end. Should send error both ways and destroy all sockets.
  client->close();
  usleep(delay);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);
}

#define RESOLVE()                                                       \
  do {                                                                  \
    libport::resolve<boost::asio::ip::tcp>(connect_host,                \
                                           S_AVAIL_PORT, err);          \
    BOOST_TEST_MESSAGE("Resolve: "                                      \
                       + (err ? err.message() : "No error"));           \
  } while (0)

static
void
test()
{
  // Basic TCP
  BOOST_TEST_MESSAGE("##Safe destruction");
  boost::system::error_code err;
  TestSocket* s = new TestSocket(false, false);
  s->connect(connect_host, S_AVAIL_PORT, false);
  s->destroy();
  usleep(delay);
  RESOLVE();
  libport::Socket* h = new libport::Socket();
  err = h->listen(boost::bind(&TestSocket::factoryEx, true, true),
                  listen_host, S_AVAIL_PORT, false);
  BOOST_CHECK_MESSAGE(!err, err.message());
  BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT);

  BOOST_TEST_MESSAGE("##One client");
  RESOLVE();
  RESOLVE();
  RESOLVE();
  RESOLVE();
  test_one(false);
  BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT);
  RESOLVE();
  test_one(false);
  BOOST_CHECK_EQUAL(h->getLocalPort(), AVAIL_PORT);
  RESOLVE();
  test_one(false);
  BOOST_TEST_MESSAGE("Socket on stack");
  {
    TestSocket s(false, true);
    err = s.connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    s.send(msg);
    usleep(delay);
  }
  usleep(delay*2);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);

  test_one(false);
  BOOST_TEST_MESSAGE("##many clients");
  std::vector<TestSocket*> clients;
  for (int i=0; i<10; i++)
  {
    TestSocket* client = new TestSocket(false, true);
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    client->send(msg);
    clients.push_back(client);
  }
  usleep(delay*3);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 20);
  foreach(TestSocket* s, clients)
  {
    BOOST_CHECK_EQUAL(s->received, msg);
    s->close();
  }
  usleep(delay*3);
  BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);

  BOOST_TEST_MESSAGE("##Failing connections");
  {
    TestSocket* client = new TestSocket();
    err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", false);
    BOOST_CHECK_MESSAGE(err, err.message());

    err = client->connect(connect_host, "nosuchport", false);
    BOOST_CHECK_MESSAGE(err, err.message());

    // Try to reuse that wasted socket.
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    // Destroy without closing.
    client->destroy();
    usleep(delay);
    BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);
  }

  // Timeout
  BOOST_TEST_MESSAGE("##Timeout connect");
  {
    TestSocket* client = new TestSocket();
    libport::utime_t start = libport::utime();
    err = client->connect("1.1.1.1", "10000", false, 1000000);
    BOOST_CHECK_MESSAGE(err, err.message());
    libport::utime_t timeout = libport::utime() - start;
    // Give it a good margin.
    BOOST_CHECK_LT(timeout, 1400000);
    client->destroy();
  }

  BOOST_TEST_MESSAGE("##Destruction locking");
  {
    TestSocket* client = new TestSocket();
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(!err, err.message());
    usleep(delay);
    libport::startThread(
      boost::bind(&hold_for<libport::Destructible::DestructionLock>,
                  client->getDestructionLock(),
                  1000000));
    client->destroy();
    usleep(500000);
    // There can be 1 or 2 sockets at this point. Client must be still
    // alive because of the lock, but server might have died.
    BOOST_CHECK_MESSAGE(TestSocket::nInstance, TestSocket::nInstance);
    usleep(500000+delay);
    BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);
  }

  BOOST_TEST_MESSAGE("Destroy listener");
  {
    h->close();
    usleep(delay);
    TestSocket* client = new TestSocket();
    abort_ctor = true;
    err = client->connect(connect_host, S_AVAIL_PORT, false);
    BOOST_CHECK_MESSAGE(err, err.message());
    client->destroy();
    h->destroy();
    usleep(delay);
    abort_ctor = false;
  }

  BOOST_TEST_MESSAGE("##UDP");
  {
    libport::Socket::Handle hu =
      libport::Socket::listenUDP(listen_host, S_AVAIL_PORT, &echo, err);
    (void)hu;
    BOOST_CHECK_MESSAGE(!err, err.message());
    test_one(true);
    usleep(delay);
    test_one(true);

    TestSocket* client = new TestSocket();
    err = client->connect("auunsinsr.nosuch.hostaufisgiu.com.", "20000", true);
    BOOST_CHECK_MESSAGE(err, err.message());

    err = client->connect(connect_host, "nosuchport", true);
    BOOST_CHECK_MESSAGE(err, err.message());

    // Try to reuse that wasted socket.
    err = client->connect(connect_host, S_AVAIL_PORT, true);
    BOOST_CHECK_MESSAGE(!err, err.message());
    // Destroy without closing.
    client->destroy();
    usleep(delay);
    BOOST_CHECK_EQUAL(TestSocket::nInstance, 0);

    // Check one-write-one-packet semantic
    client = new TestSocket(false, true);
    err = client->connect(connect_host, S_AVAIL_PORT, true);
    BOOST_CHECK_MESSAGE(!err, err.message());
    client->send("coin");
    client->send("pan");
    usleep(delay*2);
    BOOST_CHECK_EQUAL(client->received, "coinpan");
    BOOST_CHECK_EQUAL(client->nRead, 2);

    enable_delay = true;
    client = new TestSocket(false, true);
    err = client->connect(connect_host, S_AVAIL_PORT, true);
    BOOST_CHECK_MESSAGE(!err, err.message());
    client->send("coin");
    usleep(500000+delay);
    BOOST_CHECK_EQUAL(client->received, "hop hop\n");
  }
}

test_suite*
init_test_suite()
{
  // This test cannot run properly with current versions of WineHQ,
  // because they only provide a stub for acceptex.
  const char* running_wine = getenv("RUNNING_WINE");
  const char* running_qemu = getenv("RUNNING_QEMU");
  if ((running_wine && *running_wine) || (running_qemu && *running_qemu))
    std::cerr << "running under Wine, skipping this test"
              << std::endl
              << libport::exit(EX_SKIP);

  test_suite* suite = BOOST_TEST_SUITE("libport::asio test suite");
  suite->add(BOOST_TEST_CASE(test));
  return suite;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <iostream>
#include <vector>
#include <map>
#include <libserpent/funcs.h>

int main(int argv, char** argc) {
    if (argv == 1) {
        std::cerr << "Must provide a command and arguments! Try parse, rewrite, compile, assemble\n";
        return 0;
    }
    std::string flag = "";
    std::string command = argc[1];
    std::string input;
    std::string secondInput;
    if (std::string(argc[1]) == "-s") {
        flag = command.substr(1);
        command = argc[2];
        input = "";
        std::string line;
        while (std::getline(std::cin, line)) {
            input += line + "\n";
        }
        secondInput = argv == 3 ? "" : argc[3];
    }
    else {
        if (argv == 2) {
            std::cerr << "Not enough arguments for serpent cmdline\n";
            throw(0);
        }
        input = argc[2];
        secondInput = argv == 3 ? "" : argc[3];
    }
    bool haveSec = secondInput.length() > 0;
    if (command == "parse" || command == "parse_serpent") {
        std::cout << printAST(parseSerpent(input), haveSec) << "\n";
    }
    else if (command == "rewrite") {
        std::cout << printAST(rewrite(parseLLL(input, true)), haveSec) << "\n";
    }
    else if (command == "compile_to_lll") {
        std::cout << printAST(compileToLLL(input), haveSec) << "\n";
    }
    else if (command == "build_fragtree") {
        std::cout << printAST(buildFragmentTree(parseLLL(input, true))) << "\n";
    }
    else if (command == "compile_lll") {
        std::cout << binToHex(compileLLL(parseLLL(input, true))) << "\n";
    }
    else if (command == "dereference") {
        std::cout << printAST(dereference(parseLLL(input, true)), haveSec) <<"\n";
    }
    else if (command == "pretty_assemble") {
        std::cout << printTokens(prettyAssemble(parseLLL(input, true))) <<"\n";
    }
    else if (command == "pretty_compile_lll") {
        std::cout << printTokens(prettyCompileLLL(parseLLL(input, true))) << "\n";
    }
    else if (command == "pretty_compile") {
        std::cout << printTokens(prettyCompile(input)) << "\n";
    }
    else if (command == "assemble") {
        std::cout << assemble(parseLLL(input, true)) << "\n";
    }
    else if (command == "serialize") {
        std::cout << binToHex(serialize(tokenize(input))) << "\n";
    }
    else if (command == "flatten") {
        std::cout << printTokens(flatten(parseLLL(input, true))) << "\n";
    }
    else if (command == "deserialize") {
        std::cout << printTokens(deserialize(hexToBin(input))) << "\n";
    }
    else if (command == "compile") {
        std::cout << binToHex(compile(input)) << "\n";
    }
    else if (command == "encode_datalist") {
        std::vector<Node> tokens = tokenize(input);
        std::vector<std::string> o;
        for (int i = 0; i < (int)tokens.size(); i++) {
            o.push_back(tokens[i].val);
        }
        std::cout << binToHex(encodeDatalist(o)) << "\n";
    }
    else if (command == "decode_datalist") {
        std::vector<std::string> o = decodeDatalist(hexToBin(input));
        std::vector<Node> tokens;
        for (int i = 0; i < (int)o.size(); i++)
            tokens.push_back(token(o[i]));
        std::cout << printTokens(tokens) << "\n";
    }
    else if (command == "tokenize") {
        std::cout << printTokens(tokenize(input));
    }
    else if (command == "biject") {
        if (argv == 3)
             std::cerr << "Not enough arguments for biject\n";
        int pos = decimalToInt(secondInput);
        std::vector<Node> n = prettyCompile(input);
        if (pos >= (int)n.size())
             std::cerr << "Code position too high\n";
        Metadata m = n[pos].metadata;
        std::cout << "Opcode: " << n[pos].val << ", file: " << m.file <<
             ", line: " << m.ln << ", char: " << m.ch << "\n";
    }
}
<commit_msg>Minor MSVC build fix.<commit_after>#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include <map>
#include <libserpent/funcs.h>

int main(int argv, char** argc) {
    if (argv == 1) {
        std::cerr << "Must provide a command and arguments! Try parse, rewrite, compile, assemble\n";
        return 0;
    }
    std::string flag = "";
    std::string command = argc[1];
    std::string input;
    std::string secondInput;
    if (std::string(argc[1]) == "-s") {
        flag = command.substr(1);
        command = argc[2];
        input = "";
        std::string line;
        while (std::getline(std::cin, line)) {
            input += line + "\n";
        }
        secondInput = argv == 3 ? "" : argc[3];
    }
    else {
        if (argv == 2) {
            std::cerr << "Not enough arguments for serpent cmdline\n";
            throw(0);
        }
        input = argc[2];
        secondInput = argv == 3 ? "" : argc[3];
    }
    bool haveSec = secondInput.length() > 0;
    if (command == "parse" || command == "parse_serpent") {
        std::cout << printAST(parseSerpent(input), haveSec) << "\n";
    }
    else if (command == "rewrite") {
        std::cout << printAST(rewrite(parseLLL(input, true)), haveSec) << "\n";
    }
    else if (command == "compile_to_lll") {
        std::cout << printAST(compileToLLL(input), haveSec) << "\n";
    }
    else if (command == "build_fragtree") {
        std::cout << printAST(buildFragmentTree(parseLLL(input, true))) << "\n";
    }
    else if (command == "compile_lll") {
        std::cout << binToHex(compileLLL(parseLLL(input, true))) << "\n";
    }
    else if (command == "dereference") {
        std::cout << printAST(dereference(parseLLL(input, true)), haveSec) <<"\n";
    }
    else if (command == "pretty_assemble") {
        std::cout << printTokens(prettyAssemble(parseLLL(input, true))) <<"\n";
    }
    else if (command == "pretty_compile_lll") {
        std::cout << printTokens(prettyCompileLLL(parseLLL(input, true))) << "\n";
    }
    else if (command == "pretty_compile") {
        std::cout << printTokens(prettyCompile(input)) << "\n";
    }
    else if (command == "assemble") {
        std::cout << assemble(parseLLL(input, true)) << "\n";
    }
    else if (command == "serialize") {
        std::cout << binToHex(serialize(tokenize(input))) << "\n";
    }
    else if (command == "flatten") {
        std::cout << printTokens(flatten(parseLLL(input, true))) << "\n";
    }
    else if (command == "deserialize") {
        std::cout << printTokens(deserialize(hexToBin(input))) << "\n";
    }
    else if (command == "compile") {
        std::cout << binToHex(compile(input)) << "\n";
    }
    else if (command == "encode_datalist") {
        std::vector<Node> tokens = tokenize(input);
        std::vector<std::string> o;
        for (int i = 0; i < (int)tokens.size(); i++) {
            o.push_back(tokens[i].val);
        }
        std::cout << binToHex(encodeDatalist(o)) << "\n";
    }
    else if (command == "decode_datalist") {
        std::vector<std::string> o = decodeDatalist(hexToBin(input));
        std::vector<Node> tokens;
        for (int i = 0; i < (int)o.size(); i++)
            tokens.push_back(token(o[i]));
        std::cout << printTokens(tokens) << "\n";
    }
    else if (command == "tokenize") {
        std::cout << printTokens(tokenize(input));
    }
    else if (command == "biject") {
        if (argv == 3)
             std::cerr << "Not enough arguments for biject\n";
        int pos = decimalToInt(secondInput);
        std::vector<Node> n = prettyCompile(input);
        if (pos >= (int)n.size())
             std::cerr << "Code position too high\n";
        Metadata m = n[pos].metadata;
        std::cout << "Opcode: " << n[pos].val << ", file: " << m.file <<
             ", line: " << m.ln << ", char: " << m.ch << "\n";
    }
}
<|endoftext|>


<commit_before>/**
 * scoreboard.cpp
 *
 * The implementation of the scoreboard.h interface
 */
#include"scoreboard.h"

void Scoreboard::clearScoreboard() {
   for(unsigned int i = 0; i < scores.size(); ++i) {
      for(unsigned int j = 0; j < scores[i].size(); ++j) {
         scores[i][j] = 0;
      }
   }

/**
 * Sets the score for a given competition and a given period
 *
 * If the given competitor or period is negative, then no changes take effect
 * If the given competitor or period is greater than the current board size
 * the size of the scoreboard is increased to address this new score
 *
 * @param competitor the competitor to set the score for
 * @param period the period to set the score for
 * @param score the score to set
 */
void Scoreboard::setScore(int competitor, int period, int score) {
    competitor--;
    period--;

    if (competitor < 0 || period < 0) {
        return;
    }

    if (competitor >= scores.size()) {
        for (int i = scores.size(); i < competitor; i++) {
            scores.push_back(vector<int>);
        }
    }

    if (period >= scores[competitor].size()) {
        for (int i = scores[competitor].size(); i < period) {
            scores[competitor].push_back(0);
        }
    }

    scores[competitor][period] = score;
}

/**
 * Gets the score for a given competitor and period
 * @param  competitor the competitor to get the score for
 * @param  period the period to get the score for
 * @return the score
 */
int Scoreboard::getScore(int competitor, int period)
{
   if (competitor <= competitor_size && period <= period_size)
   {
      return scores[competitor][period];
   }

   else
      return -1;
}

/**
 * Gets the total score for the competitor over all periods
 * @param  competitor the competitor to get the total score for
 * @return the total score
 */
int Scoreboard::getTotalScore(int competitor) {
  int totalScore = 0;

  if (competitor < 1 || competitor > scores.size())
    return 0; //out of range

  for (int i = 1; i <= scores[competitor].size(); ++i)
  {
    totalScore += getScore(competitor, i);
  }

  return totalScore;
}
<commit_msg>Added curly brace to clearScoreboard<commit_after>/**
 * scoreboard.cpp
 *
 * The implementation of the scoreboard.h interface
 */
#include"scoreboard.h"

void Scoreboard::clearScoreboard() {
   for(unsigned int i = 0; i < scores.size(); ++i) {
      for(unsigned int j = 0; j < scores[i].size(); ++j) {
         scores[i][j] = 0;
      }
   }
}

/**
 * Sets the score for a given competition and a given period
 *
 * If the given competitor or period is negative, then no changes take effect
 * If the given competitor or period is greater than the current board size
 * the size of the scoreboard is increased to address this new score
 *
 * @param competitor the competitor to set the score for
 * @param period the period to set the score for
 * @param score the score to set
 */
void Scoreboard::setScore(int competitor, int period, int score) {
    competitor--;
    period--;

    if (competitor < 0 || period < 0) {
        return;
    }

    if (competitor >= scores.size()) {
        for (int i = scores.size(); i < competitor; i++) {
            scores.push_back(vector<int>);
        }
    }

    if (period >= scores[competitor].size()) {
        for (int i = scores[competitor].size(); i < period) {
            scores[competitor].push_back(0);
        }
    }

    scores[competitor][period] = score;
}

/**
 * Gets the score for a given competitor and period
 * @param  competitor the competitor to get the score for
 * @param  period the period to get the score for
 * @return the score
 */
int Scoreboard::getScore(int competitor, int period)
{
   if (competitor <= competitor_size && period <= period_size)
   {
      return scores[competitor][period];
   }

   else
      return -1;
}

/**
 * Gets the total score for the competitor over all periods
 * @param  competitor the competitor to get the total score for
 * @return the total score
 */
int Scoreboard::getTotalScore(int competitor) {
  int totalScore = 0;

  if (competitor < 1 || competitor > scores.size())
    return 0; //out of range

  for (int i = 1; i <= scores[competitor].size(); ++i)
  {
    totalScore += getScore(competitor, i);
  }

  return totalScore;
}
<|endoftext|>