commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
748cc79d0f1b0f9ff19f35c2fc056b12414b33b7 | src/utils.hh | src/utils.hh | #ifndef utils_hh_INCLUDED
#define utils_hh_INCLUDED
#include "assert.hh"
#include "exception.hh"
#include <algorithm>
#include <memory>
#include <vector>
#include <unordered_set>
namespace Kakoune
{
// *** Singleton ***
//
// Singleton helper class, every singleton type T should inherit
// from Singleton<T> to provide a consistent interface.
template<typename T>
class Singleton
{
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static T& instance()
{
kak_assert (ms_instance);
return *ms_instance;
}
static void delete_instance()
{
delete ms_instance;
ms_instance = nullptr;
}
static bool has_instance()
{
return ms_instance != nullptr;
}
protected:
Singleton()
{
kak_assert(not ms_instance);
ms_instance = static_cast<T*>(this);
}
~Singleton()
{
kak_assert(ms_instance == this);
ms_instance = nullptr;
}
private:
static T* ms_instance;
};
template<typename T>
T* Singleton<T>::ms_instance = nullptr;
// *** safe_ptr: objects that assert nobody references them when they die ***
template<typename T>
class safe_ptr
{
public:
safe_ptr() : m_ptr(nullptr) {}
explicit safe_ptr(T* ptr) : m_ptr(ptr)
{
#ifdef KAK_DEBUG
if (m_ptr)
m_ptr->inc_safe_count();
#endif
}
safe_ptr(const safe_ptr& other) : safe_ptr(other.m_ptr) {}
safe_ptr(safe_ptr&& other) : m_ptr(other.m_ptr) { other.m_ptr = nullptr; }
~safe_ptr()
{
#ifdef KAK_DEBUG
if (m_ptr)
m_ptr->dec_safe_count();
#endif
}
safe_ptr& operator=(const safe_ptr& other)
{
#ifdef KAK_DEBUG
if (m_ptr != other.m_ptr)
{
if (m_ptr)
m_ptr->dec_safe_count();
if (other.m_ptr)
other.m_ptr->inc_safe_count();
}
#endif
m_ptr = other.m_ptr;
return *this;
}
safe_ptr& operator=(safe_ptr&& other)
{
#ifdef KAK_DEBUG
if (m_ptr)
m_ptr->dec_safe_count();
#endif
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
return *this;
}
void reset(T* ptr)
{
*this = safe_ptr(ptr);
}
bool operator== (const safe_ptr& other) const { return m_ptr == other.m_ptr; }
bool operator!= (const safe_ptr& other) const { return m_ptr != other.m_ptr; }
bool operator== (T* ptr) const { return m_ptr == ptr; }
bool operator!= (T* ptr) const { return m_ptr != ptr; }
T& operator* () const { return *m_ptr; }
T* operator-> () const { return m_ptr; }
T* get() const { return m_ptr; }
explicit operator bool() const { return m_ptr; }
private:
T* m_ptr;
};
class SafeCountable
{
public:
#ifdef KAK_DEBUG
SafeCountable() : m_count(0) {}
~SafeCountable() { kak_assert(m_count == 0); }
void inc_safe_count() const { ++m_count; }
void dec_safe_count() const { --m_count; kak_assert(m_count >= 0); }
private:
mutable int m_count;
#endif
};
// *** Containers helpers ***
template<typename Container>
struct ReversedContainer
{
ReversedContainer(Container& container) : container(container) {}
Container& container;
decltype(container.rbegin()) begin() { return container.rbegin(); }
decltype(container.rend()) end() { return container.rend(); }
};
template<typename Container>
ReversedContainer<Container> reversed(Container&& container)
{
return ReversedContainer<Container>(container);
}
template<typename Container, typename T>
auto find(Container&& container, const T& value) -> decltype(container.begin())
{
return std::find(container.begin(), container.end(), value);
}
template<typename Container, typename T>
auto find_if(Container&& container, T op) -> decltype(container.begin())
{
return std::find_if(container.begin(), container.end(), op);
}
template<typename Container, typename T>
bool contains(Container&& container, const T& value)
{
return find(container, value) != container.end();
}
template<typename T1, typename T2>
bool contains(const std::unordered_set<T1>& container, const T2& value)
{
return container.find(value) != container.end();
}
// *** On scope end ***
//
// on_scope_end provides a way to register some code to be
// executed when current scope closes.
//
// usage:
// auto cleaner = on_scope_end([]() { ... });
//
// This permits to cleanup c-style resources without implementing
// a wrapping class
template<typename T>
class OnScopeEnd
{
public:
OnScopeEnd(T func) : m_func(std::move(func)) {}
~OnScopeEnd() { m_func(); }
private:
T m_func;
};
template<typename T>
OnScopeEnd<T> on_scope_end(T t)
{
return OnScopeEnd<T>(t);
}
// *** Misc helper functions ***
template<typename T>
bool operator== (const std::unique_ptr<T>& lhs, T* rhs)
{
return lhs.get() == rhs;
}
inline String escape(const String& name)
{
static Regex ex{"([ \\t;])"};
return boost::regex_replace(name, ex, R"(\\\1)");
}
template<typename T>
const T& clamp(const T& val, const T& min, const T& max)
{
return (val < min ? min : (val > max ? max : val));
}
template<typename T>
bool is_in_range(const T& val, const T& min, const T& max)
{
return min <= val and val <= max;
}
// *** AutoRegister: RAII handling of value semantics registering classes ***
template<typename EffectiveType, typename RegisterFuncs, typename Registry>
class AutoRegister
{
public:
AutoRegister(Registry& registry)
: m_registry(®istry)
{
RegisterFuncs::insert(*m_registry, effective_this());
}
AutoRegister(const AutoRegister& other)
: m_registry(other.m_registry)
{
RegisterFuncs::insert(*m_registry, effective_this());
}
AutoRegister(AutoRegister&& other)
: m_registry(other.m_registry)
{
RegisterFuncs::insert(*m_registry, effective_this());
}
~AutoRegister()
{
RegisterFuncs::remove(*m_registry, effective_this());
}
AutoRegister& operator=(const AutoRegister& other)
{
if (m_registry != other.m_registry)
{
RegisterFuncs::remove(*m_registry, effective_this());
m_registry = other.m_registry;
RegisterFuncs::insert(*m_registry, effective_this());
}
return *this;
}
AutoRegister& operator=(AutoRegister&& other)
{
if (m_registry != other.m_registry)
{
RegisterFuncs::remove(*m_registry, effective_this());
m_registry = other.m_registry;
RegisterFuncs::insert(*m_registry, effective_this());
}
return *this;
}
Registry& registry() const { return *m_registry; }
private:
EffectiveType& effective_this() { return static_cast<EffectiveType&>(*this); }
Registry* m_registry;
};
}
#endif // utils_hh_INCLUDED
| #ifndef utils_hh_INCLUDED
#define utils_hh_INCLUDED
#include "assert.hh"
#include "exception.hh"
#include <algorithm>
#include <memory>
#include <vector>
#include <unordered_set>
namespace Kakoune
{
// *** Singleton ***
//
// Singleton helper class, every singleton type T should inherit
// from Singleton<T> to provide a consistent interface.
template<typename T>
class Singleton
{
public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static T& instance()
{
kak_assert (ms_instance);
return *ms_instance;
}
static void delete_instance()
{
delete ms_instance;
ms_instance = nullptr;
}
static bool has_instance()
{
return ms_instance != nullptr;
}
protected:
Singleton()
{
kak_assert(not ms_instance);
ms_instance = static_cast<T*>(this);
}
~Singleton()
{
kak_assert(ms_instance == this);
ms_instance = nullptr;
}
private:
static T* ms_instance;
};
template<typename T>
T* Singleton<T>::ms_instance = nullptr;
// *** safe_ptr: objects that assert nobody references them when they die ***
template<typename T>
class safe_ptr
{
public:
safe_ptr() : m_ptr(nullptr) {}
explicit safe_ptr(T* ptr) : m_ptr(ptr)
{
#ifdef KAK_DEBUG
if (m_ptr)
m_ptr->inc_safe_count();
#endif
}
safe_ptr(const safe_ptr& other) : safe_ptr(other.m_ptr) {}
safe_ptr(safe_ptr&& other) : m_ptr(other.m_ptr) { other.m_ptr = nullptr; }
~safe_ptr()
{
#ifdef KAK_DEBUG
if (m_ptr)
m_ptr->dec_safe_count();
#endif
}
safe_ptr& operator=(const safe_ptr& other)
{
#ifdef KAK_DEBUG
if (m_ptr != other.m_ptr)
{
if (m_ptr)
m_ptr->dec_safe_count();
if (other.m_ptr)
other.m_ptr->inc_safe_count();
}
#endif
m_ptr = other.m_ptr;
return *this;
}
safe_ptr& operator=(safe_ptr&& other)
{
#ifdef KAK_DEBUG
if (m_ptr)
m_ptr->dec_safe_count();
#endif
m_ptr = other.m_ptr;
other.m_ptr = nullptr;
return *this;
}
void reset(T* ptr)
{
*this = safe_ptr(ptr);
}
bool operator== (const safe_ptr& other) const { return m_ptr == other.m_ptr; }
bool operator!= (const safe_ptr& other) const { return m_ptr != other.m_ptr; }
bool operator== (T* ptr) const { return m_ptr == ptr; }
bool operator!= (T* ptr) const { return m_ptr != ptr; }
T& operator* () const { return *m_ptr; }
T* operator-> () const { return m_ptr; }
T* get() const { return m_ptr; }
explicit operator bool() const { return m_ptr; }
private:
T* m_ptr;
};
class SafeCountable
{
public:
#ifdef KAK_DEBUG
SafeCountable() : m_count(0) {}
~SafeCountable() { kak_assert(m_count == 0); }
void inc_safe_count() const { ++m_count; }
void dec_safe_count() const { --m_count; kak_assert(m_count >= 0); }
private:
mutable int m_count;
#endif
};
// *** Containers helpers ***
template<typename Container>
struct ReversedContainer
{
ReversedContainer(Container& container) : container(container) {}
Container& container;
decltype(container.rbegin()) begin() { return container.rbegin(); }
decltype(container.rend()) end() { return container.rend(); }
};
template<typename Container>
ReversedContainer<Container> reversed(Container&& container)
{
return ReversedContainer<Container>(container);
}
template<typename Container, typename T>
auto find(Container&& container, const T& value) -> decltype(container.begin())
{
return std::find(container.begin(), container.end(), value);
}
template<typename Container, typename T>
auto find_if(Container&& container, T op) -> decltype(container.begin())
{
return std::find_if(container.begin(), container.end(), op);
}
template<typename Container, typename T>
bool contains(Container&& container, const T& value)
{
return find(container, value) != container.end();
}
template<typename T1, typename T2>
bool contains(const std::unordered_set<T1>& container, const T2& value)
{
return container.find(value) != container.end();
}
// *** On scope end ***
//
// on_scope_end provides a way to register some code to be
// executed when current scope closes.
//
// usage:
// auto cleaner = on_scope_end([]() { ... });
//
// This permits to cleanup c-style resources without implementing
// a wrapping class
template<typename T>
class OnScopeEnd
{
public:
OnScopeEnd(T func) : m_func(std::move(func)) {}
~OnScopeEnd() { m_func(); }
private:
T m_func;
};
template<typename T>
OnScopeEnd<T> on_scope_end(T t)
{
return OnScopeEnd<T>(t);
}
// *** Misc helper functions ***
template<typename T>
bool operator== (const std::unique_ptr<T>& lhs, T* rhs)
{
return lhs.get() == rhs;
}
inline String escape(const String& name)
{
static Regex ex{"([ \\t;])"};
return boost::regex_replace(name, ex, R"(\\\1)");
}
template<typename T>
const T& clamp(const T& val, const T& min, const T& max)
{
return (val < min ? min : (val > max ? max : val));
}
template<typename T>
bool is_in_range(const T& val, const T& min, const T& max)
{
return min <= val and val <= max;
}
// *** AutoRegister: RAII handling of value semantics registering classes ***
template<typename EffectiveType, typename RegisterFuncs, typename Registry>
class AutoRegister
{
public:
AutoRegister(Registry& registry)
: m_registry(®istry)
{
RegisterFuncs::insert(*m_registry, effective_this());
}
AutoRegister(const AutoRegister& other)
: m_registry(other.m_registry)
{
RegisterFuncs::insert(*m_registry, effective_this());
}
AutoRegister(AutoRegister&& other)
: m_registry(other.m_registry)
{
RegisterFuncs::insert(*m_registry, effective_this());
}
~AutoRegister()
{
RegisterFuncs::remove(*m_registry, effective_this());
}
AutoRegister& operator=(const AutoRegister& other)
{
if (m_registry != other.m_registry)
{
RegisterFuncs::remove(*m_registry, effective_this());
m_registry = other.m_registry;
RegisterFuncs::insert(*m_registry, effective_this());
}
return *this;
}
AutoRegister& operator=(AutoRegister&& other)
{
if (m_registry != other.m_registry)
{
RegisterFuncs::remove(*m_registry, effective_this());
m_registry = other.m_registry;
RegisterFuncs::insert(*m_registry, effective_this());
}
return *this;
}
Registry& registry() const { return *m_registry; }
private:
EffectiveType& effective_this() { return static_cast<EffectiveType&>(*this); }
Registry* m_registry;
};
}
// std::pair hashing
namespace std
{
template<typename T1, typename T2>
struct hash<std::pair<T1,T2>>
{
size_t operator()(const std::pair<T1,T2>& val) const
{
size_t seed = std::hash<T2>()(val.second);
return seed ^ (std::hash<T1>()(val.first) + 0x9e3779b9 +
(seed << 6) + (seed >> 2));
}
};
}
#endif // utils_hh_INCLUDED
| Add std::hash specialization for std::pair | Add std::hash specialization for std::pair
| C++ | unlicense | ekie/kakoune,rstacruz/kakoune,lenormf/kakoune,zakgreant/kakoune,elegios/kakoune,casimir/kakoune,mawww/kakoune,alpha123/kakoune,casimir/kakoune,Asenar/kakoune,danr/kakoune,rstacruz/kakoune,occivink/kakoune,casimir/kakoune,ekie/kakoune,alexherbo2/kakoune,alexherbo2/kakoune,jkonecny12/kakoune,lenormf/kakoune,zakgreant/kakoune,danielma/kakoune,ekie/kakoune,elegios/kakoune,mawww/kakoune,occivink/kakoune,jjthrash/kakoune,Asenar/kakoune,flavius/kakoune,danielma/kakoune,flavius/kakoune,Somasis/kakoune,mawww/kakoune,danr/kakoune,jjthrash/kakoune,alexherbo2/kakoune,occivink/kakoune,Somasis/kakoune,jjthrash/kakoune,danielma/kakoune,alpha123/kakoune,danielma/kakoune,flavius/kakoune,rstacruz/kakoune,mawww/kakoune,xificurC/kakoune,ekie/kakoune,flavius/kakoune,xificurC/kakoune,zakgreant/kakoune,Somasis/kakoune,lenormf/kakoune,xificurC/kakoune,lenormf/kakoune,elegios/kakoune,jjthrash/kakoune,occivink/kakoune,elegios/kakoune,alexherbo2/kakoune,jkonecny12/kakoune,Asenar/kakoune,zakgreant/kakoune,xificurC/kakoune,casimir/kakoune,danr/kakoune,Asenar/kakoune,jkonecny12/kakoune,Somasis/kakoune,jkonecny12/kakoune,danr/kakoune,rstacruz/kakoune,alpha123/kakoune,alpha123/kakoune |
7a0efc7f4c4083a7eb3d14dd0a1098fdba78778f | COFF/ICF.cpp | COFF/ICF.cpp | //===- ICF.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements ICF (Identical COMDAT Folding)
//
//===----------------------------------------------------------------------===//
#include "Chunks.h"
#include <tuple>
#include <unordered_set>
#include <vector>
namespace lld {
namespace coff {
namespace {
struct Hasher {
size_t operator()(const SectionChunk *C) const { return C->getHash(); }
};
struct Equals {
bool operator()(const SectionChunk *A, const SectionChunk *B) const {
return A->equals(B);
}
};
} // anonymous namespace
// Merge identical COMDAT sections.
// Two sections are considered as identical when their section headers,
// contents and relocations are all the same.
void doICF(const std::vector<Chunk *> &Chunks) {
std::unordered_set<SectionChunk *, Hasher, Equals> Set;
bool removed = false;
for (Chunk *C : Chunks) {
auto *SC = dyn_cast<SectionChunk>(C);
if (!SC || !SC->isCOMDAT() || !SC->isLive())
continue;
auto P = Set.insert(SC);
bool Inserted = P.second;
if (Inserted)
continue;
SectionChunk *Existing = *P.first;
SC->replaceWith(Existing);
removed = true;
}
// By merging sections, two relocations that originally pointed to
// different locations can now point to the same location.
// So, repeat the process until a convegence is obtained.
if (removed)
doICF(Chunks);
}
} // namespace coff
} // namespace lld
| //===- ICF.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Implements ICF (Identical COMDAT Folding)
//
//===----------------------------------------------------------------------===//
#include "Chunks.h"
#include <tuple>
#include <unordered_set>
#include <vector>
namespace lld {
namespace coff {
namespace {
struct Hasher {
size_t operator()(const SectionChunk *C) const { return C->getHash(); }
};
struct Equals {
bool operator()(const SectionChunk *A, const SectionChunk *B) const {
return A->equals(B);
}
};
} // anonymous namespace
// Merge identical COMDAT sections.
// Two sections are considered as identical when their section headers,
// contents and relocations are all the same.
void doICF(const std::vector<Chunk *> &Chunks) {
std::unordered_set<SectionChunk *, Hasher, Equals> Set;
bool Redo;
do {
Set.clear();
Redo = false;
for (Chunk *C : Chunks) {
auto *SC = dyn_cast<SectionChunk>(C);
if (!SC || !SC->isCOMDAT() || !SC->isLive())
continue;
auto P = Set.insert(SC);
bool Inserted = P.second;
if (Inserted)
continue;
SectionChunk *Existing = *P.first;
SC->replaceWith(Existing);
// By merging sections, two relocations that originally pointed to
// different locations can now point to the same location.
// So, repeat the process until a convegence is obtained.
Redo = true;
}
} while (Redo);
}
} // namespace coff
} // namespace lld
| Make doICF non-recursive. NFC. | COFF: Make doICF non-recursive. NFC.
git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@240898 91177308-0d34-0410-b5e6-96231b3b80d8
| C++ | apache-2.0 | llvm-mirror/lld,llvm-mirror/lld |
fc11f40937fe1ecea6b534f56176f848d4b85eb7 | tests/app/main.cpp | tests/app/main.cpp | /*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <graphene/app/application.hpp>
#include <graphene/app/plugin.hpp>
#include <graphene/chain/key_object.hpp>
#include <graphene/time/time.hpp>
#include <graphene/account_history/account_history_plugin.hpp>
#include <fc/thread/thread.hpp>
#include <boost/filesystem/path.hpp>
#define BOOST_TEST_MODULE Test Application
#include <boost/test/included/unit_test.hpp>
using namespace graphene;
BOOST_AUTO_TEST_CASE( two_node_network )
{
using namespace graphene::chain;
using namespace graphene::app;
try {
fc::temp_directory app_dir;
fc::temp_directory app2_dir;
fc::temp_file genesis_json;
fc::json::save_to_file(genesis_state_type(), genesis_json.path());
fc::time_point_sec now( GRAPHENE_GENESIS_TIMESTAMP );
graphene::app::application app1;
app1.register_plugin<graphene::account_history::account_history_plugin>();
bpo::variables_map cfg;
cfg.emplace("p2p-endpoint", bpo::variable_value(string("127.0.0.1:3939"), false));
cfg.emplace("genesis-json", bpo::variable_value(boost::filesystem::path(genesis_json.path()), false));
app1.initialize(app_dir.path(), cfg);
graphene::app::application app2;
app2.register_plugin<account_history::account_history_plugin>();
auto cfg2 = cfg;
cfg2.erase("p2p-endpoint");
cfg2.emplace("p2p-endpoint", bpo::variable_value(string("127.0.0.1:4040"), false));
cfg2.emplace("seed-node", bpo::variable_value(vector<string>{"127.0.0.1:3939"}, false));
app2.initialize(app2_dir.path(), cfg2);
app1.startup();
app2.startup();
fc::usleep(fc::milliseconds(500));
BOOST_CHECK_EQUAL(app1.p2p_node()->get_connection_count(), 1);
BOOST_CHECK_EQUAL(std::string(app1.p2p_node()->get_connected_peers().front().host.get_address()), "127.0.0.1");
ilog("Connected!");
fc::ecc::private_key nathan_key = fc::ecc::private_key::generate();
fc::ecc::private_key genesis_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("null_key")));
graphene::chain::signed_transaction trx;
trx.set_expiration(now + fc::seconds(30));
std::shared_ptr<chain::database> db2 = app2.chain_database();
trx.operations.push_back(key_create_operation({asset(), account_id_type(1), public_key_type(nathan_key.get_public_key())}));
trx.validate();
trx.sign(key_id_type(0), genesis_key);
processed_transaction ptrx = app1.chain_database()->push_transaction(trx);
app1.p2p_node()->broadcast(graphene::net::trx_message(trx));
key_id_type nathan_key_id = ptrx.operation_results.front().get<object_id_type>();
fc::usleep(fc::milliseconds(250));
BOOST_CHECK(nathan_key_id(*app2.chain_database()).key_data.get<public_key_type>() == nathan_key.get_public_key());
ilog("Pushed transaction");
now += GRAPHENE_DEFAULT_BLOCK_INTERVAL;
app2.p2p_node()->broadcast(graphene::net::block_message(db2->generate_block(
now, db2->get_scheduled_witness( 1 ).first, genesis_key, database::skip_nothing )));
fc::usleep(fc::milliseconds(500));
BOOST_CHECK_EQUAL(app1.p2p_node()->get_connection_count(), 1);
BOOST_CHECK_EQUAL(app1.chain_database()->head_block_num(), 1);
} catch( fc::exception& e ) {
edump((e.to_detail_string()));
throw;
}
}
| /*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <graphene/app/application.hpp>
#include <graphene/app/plugin.hpp>
#include <graphene/chain/key_object.hpp>
#include <graphene/time/time.hpp>
#include <graphene/account_history/account_history_plugin.hpp>
#include <fc/thread/thread.hpp>
#include <boost/filesystem/path.hpp>
#define BOOST_TEST_MODULE Test Application
#include <boost/test/included/unit_test.hpp>
using namespace graphene;
BOOST_AUTO_TEST_CASE( two_node_network )
{
using namespace graphene::chain;
using namespace graphene::app;
try {
fc::temp_directory app_dir;
fc::temp_directory app2_dir;
fc::temp_file genesis_json;
fc::time_point_sec now( GRAPHENE_GENESIS_TIMESTAMP );
graphene::app::application app1;
app1.register_plugin<graphene::account_history::account_history_plugin>();
bpo::variables_map cfg;
cfg.emplace("p2p-endpoint", bpo::variable_value(string("127.0.0.1:3939"), false));
app1.initialize(app_dir.path(), cfg);
graphene::app::application app2;
app2.register_plugin<account_history::account_history_plugin>();
auto cfg2 = cfg;
cfg2.erase("p2p-endpoint");
cfg2.emplace("p2p-endpoint", bpo::variable_value(string("127.0.0.1:4040"), false));
cfg2.emplace("seed-node", bpo::variable_value(vector<string>{"127.0.0.1:3939"}, false));
app2.initialize(app2_dir.path(), cfg2);
app1.startup();
app2.startup();
fc::usleep(fc::milliseconds(500));
BOOST_REQUIRE_EQUAL(app1.p2p_node()->get_connection_count(), 1);
BOOST_CHECK_EQUAL(std::string(app1.p2p_node()->get_connected_peers().front().host.get_address()), "127.0.0.1");
ilog("Connected!");
fc::ecc::private_key nathan_key = fc::ecc::private_key::generate();
fc::ecc::private_key genesis_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan")));
graphene::chain::signed_transaction trx;
trx.set_expiration(now + fc::seconds(30));
std::shared_ptr<chain::database> db2 = app2.chain_database();
trx.operations.push_back(key_create_operation({asset(),
GRAPHENE_TEMP_ACCOUNT,
public_key_type(nathan_key.get_public_key())}));
trx.validate();
processed_transaction ptrx = app1.chain_database()->push_transaction(trx);
app1.p2p_node()->broadcast(graphene::net::trx_message(trx));
key_id_type nathan_key_id = ptrx.operation_results.front().get<object_id_type>();
fc::usleep(fc::milliseconds(250));
BOOST_CHECK(nathan_key_id(*app2.chain_database()).key_data.get<public_key_type>() == nathan_key.get_public_key());
ilog("Pushed transaction");
now += GRAPHENE_DEFAULT_BLOCK_INTERVAL;
app2.p2p_node()->broadcast(graphene::net::block_message(db2->generate_block(now,
db2->get_scheduled_witness(1).first,
genesis_key,
database::skip_nothing)));
fc::usleep(fc::milliseconds(500));
BOOST_CHECK_EQUAL(app1.p2p_node()->get_connection_count(), 1);
BOOST_CHECK_EQUAL(app1.chain_database()->head_block_num(), 1);
} catch( fc::exception& e ) {
edump((e.to_detail_string()));
throw;
}
}
| Fix app_test | Fix app_test
Sometimes it fails to connect, but when it does, it works.
| C++ | mit | bigoc/openchain,bigoc/openchain,peertracksinc/muse,oxarbitrage/bitshares-core,abitmore/bitshares-2,bitshares/bitshares-2,peertracksinc/muse,abitmore/bitshares-2,bitshares/bitshares-2,bigoc/openchain,pmconrad/graphene,cryptonomex/graphene,oxarbitrage/bitshares-core,cryptonomex/graphene,bigoc/openchain,peertracksinc/muse,abitmore/bitshares-2,oxarbitrage/bitshares-core,bitsuperlab/cpp-play2,oxarbitrage/bitshares-core,bitsuperlab/cpp-play2,cryptonomex/graphene,peertracksinc/muse,bitshares/bitshares-2,pmconrad/graphene,abitmore/bitshares-2,bitsuperlab/cpp-play2,pmconrad/graphene,bitshares/bitshares-2,pmconrad/graphene |
3dad655f3e84fe55fb92e6504402138b7bb28a29 | tests/test_115.cpp | tests/test_115.cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
void gen(std::string name, int size, int val0, int val1)
{
tiramisu::init(name);
tiramisu::function *function0 = global::get_implicit_function();
tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);
tiramisu::var i("i", 0, 10), j("j", 0, N);
tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");
tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j);
S0.tile(i, j, 2, 2, i0, j0, i1, j1);
S0.tag_parallel_level(i0);
tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0);
S0.store_in(&buf0, {i ,j});
function0->codegen({&buf0}, "build/generated_fct_test_115.o");
}
int main(int argc, char **argv)
{
gen("func", 10, 3, 4);
return 0;
}
| #include <tiramisu/tiramisu.h>
using namespace tiramisu;
void gen(std::string name, int size, int val0, int val1)
{
tiramisu::init(name);
tiramisu::function *function0 = global::get_implicit_function();
tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);
tiramisu::var i("i", 0, 10), j("j", 0, N);
tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1");
tiramisu::computation S0({i, j}, tiramisu::expr((uint8_t) (val0 + val1)));
S0.tile(i, j, 2, 2, i0, j0, i1, j1);
S0.tag_parallel_level(i0);
tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0);
S0.store_in(&buf0, {i ,j});
function0->codegen({&buf0}, "build/generated_fct_test_115.o");
}
int main(int argc, char **argv)
{
gen("func", 10, 3, 4);
return 0;
}
| Fix test | Fix test
| C++ | mit | rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/ISIR,rbaghdadi/COLi,rbaghdadi/COLi,rbaghdadi/ISIR,rbaghdadi/tiramisu,rbaghdadi/tiramisu |
888aff575337a0b678f7e313d8125f452140826c | math/fraction/fraction.cpp | math/fraction/fraction.cpp | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
void printFraction(const struct Fraction, int);
Fraction getFraction();
Fraction multiply(struct Fraction, struct Fraction);
int validateInt(string);
struct Fraction {
int num;
int den;
};
int main() {
Fraction f1, f2, f3;
f1 = getFraction();
f2 = getFraction();
f3 = multiply(f1, f2);
printFraction(f1, 1);
printFraction(f2, 2);
cout << "\n\nFraction1 * Fraction2 = Fraction3\n";
printFraction(f3, 3);
cout << endl << endl;
return 0;
}
void printFraction(const struct Fraction f, int x) {
cout << "\nFraction" << x << " : " ;
cout << f.num << "/" << f.den;
}
Fraction getFraction() {
Fraction f;
f.num = validateInt("Numerator");
f.den = validateInt("Denominator");
while (f.den == 0) {
cout << "Error Denominator cannot be zero" << endl;
f.den = validateInt("Denominator");
}
return f;
}
Fraction multiply(struct Fraction f1, struct Fraction f2) {
Fraction f3;
f3.den = f1.den * f2.den;
f3.num = f1.num * f2.num;
return f3;
}
int validateInt(string name) {
int num;
while (true) {
cout << "\nEnter the " << name << " : ";
string numStr;
cin >> numStr;
bool valid = true;
for(int i = 0; i < numStr.length(); i++){
if(!isdigit(numStr[i])){
valid = false;
break;
}
}
if (!valid) {
cout << "Error: Enter positive numbers only";
continue;
}
stringstream sstream;
sstream << numStr;
sstream >> num;
if (num < 0 || num > 40000) {
cout << "Error: number entered is out of range";
continue;
}
break;
}
return num;
} | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
struct Fraction {
int num;
int den;
};
int validateInt(string);
Fraction getFraction(string);
Fraction multiply(Fraction, Fraction);
Fraction add(Fraction, Fraction);
Fraction subtract(Fraction, Fraction);
Fraction divide(Fraction, Fraction);
void printFraction(const Fraction);
int main() {
Fraction f1, f2, f3, f4, f5, f6;
f1 = getFraction("first");
f2 = getFraction("second");
f3 = multiply(f1, f2);
f4 = add(f1, f2);
f5 = subtract(f1, f2);
f6 = divide(f1, f2);
cout << "\n\nFraction1 = ";
printFraction(f1);
cout << "\n\nFraction2 = ";
printFraction(f2);
cout << "\n\nFraction1 * Fraction2 = ";
printFraction(f3);
cout << "\n\nFraction1 + Fraction2 = ";
printFraction(f4);
cout << "\n\nFraction1 - Fraction2 = ";
printFraction(f5);
cout << "\n\nFraction1 / Fraction2 = ";
printFraction(f6);
cout << endl << endl;
return 0;
}
int validateInt(string name) {
int num;
while (true) {
cout << "\nEnter the " << name << " : ";
string numStr;
cin >> numStr;
bool valid = true;
for(int i = 0; i < numStr.length(); i++){
if(!isdigit(numStr[i])){
valid = false;
break;
}
}
if (!valid) {
cout << "Error: Enter positive numbers only";
continue;
}
stringstream sstream;
sstream << numStr;
sstream >> num;
if (num < 0 || num > 40000) {
cout << "Error: number entered is out of range";
continue;
}
break;
}
return num;
}
Fraction getFraction(string n) {
Fraction f;
f.num = validateInt(n + " Numerator");
f.den = validateInt(n + " Denominator");
while (f.den == 0) {
cout << "Error Denominator cannot be zero" << endl;
f.den = validateInt("Denominator");
}
return f;
}
Fraction multiply(struct Fraction f1, struct Fraction f2) {
Fraction f3;
f3.den = f1.den * f2.den;
f3.num = f1.num * f2.num;
return f3;
}
Fraction add(Fraction f1, Fraction f2) {
Fraction f3;
f3.den = f1.den * f2.den;
f1.num = f1.num * f2.den;
f2.num = f2.num * f1.den;
f3.num = f1.num + f2.num;
return f3;
}
Fraction subtract(Fraction f1, Fraction f2) {
Fraction f3;
f3.den = f1.den * f2.den;
f1.num = f1.num * f2.den;
f2.num = f2.num * f1.den;
f3.num = f1.num - f2.num;
return f3;
}
Fraction divide(Fraction f1, Fraction f2) {
Fraction f3;
f3.den = f1.den * f2.num;
f3.num = f1.num * f2.den;
return f3;
}
void printFraction(const Fraction f) {
cout << f.num << "/" << f.den;
} | update fraction | update fraction
| C++ | mit | felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms,felipecustodio/algorithms |
9735cc90c2f380c1c4fd9fa66ebe6b17ee1f021a | src/snep/SnepMessage.cpp | src/snep/SnepMessage.cpp | #include "SnepMessage.h"
#include "NdefMessage.h"
#define LOG_TAG "nfcd"
#include <cutils/log.h>
SnepMessage::SnepMessage()
: mNdefMessage(NULL)
{
}
SnepMessage::~SnepMessage()
{
if (mNdefMessage)
delete mNdefMessage;
}
SnepMessage::SnepMessage(std::vector<uint8_t>& buf)
{
int ndefOffset = 0;
int ndefLength = 0;
int idx = 0;
mVersion = buf[idx++];
mField = buf[idx++];
mLength = ((uint32_t)buf[idx] << 24) |
((uint32_t)buf[idx + 1] << 16) |
((uint32_t)buf[idx + 2] << 8) |
(uint32_t)buf[idx + 3];
idx += 4 ;
if (mField == SnepMessage::REQUEST_GET) {
mAcceptableLength = ((uint32_t)buf[idx] << 24) |
((uint32_t)buf[idx + 1] << 16) |
((uint32_t)buf[idx + 2] << 8) |
(uint32_t)buf[idx + 3];
idx += 4;
ndefOffset = SnepMessage::HEADER_LENGTH + 4;
ndefLength = mLength - 4;
} else {
mAcceptableLength = -1;
ndefOffset = SnepMessage::HEADER_LENGTH;
ndefLength = mLength;
}
if (ndefLength > 0) {
mNdefMessage = new NdefMessage();
// TODO : Need to check idx is correct.
mNdefMessage->init(buf, idx);
} else {
mNdefMessage = NULL;
}
}
SnepMessage::SnepMessage(uint8_t version, uint8_t field, int length,
int acceptableLength, NdefMessage* ndefMessage)
{
mVersion = version;
mField = field;
mLength = length;
mAcceptableLength = acceptableLength;
mNdefMessage = ndefMessage;
}
SnepMessage* SnepMessage::getGetRequest(int acceptableLength, NdefMessage& ndef)
{
std::vector<uint8_t> buf;
ndef.toByteArray(buf);
return new SnepMessage(SnepMessage::VERSION, SnepMessage::REQUEST_GET, 4 + buf.size(), acceptableLength, &ndef);
}
SnepMessage* SnepMessage::getPutRequest(NdefMessage& ndef)
{
std::vector<uint8_t> buf;
ndef.toByteArray(buf);
return new SnepMessage(SnepMessage::VERSION, SnepMessage::REQUEST_PUT, buf.size(), 0, &ndef);
}
SnepMessage* SnepMessage::getMessage(uint8_t field)
{
return new SnepMessage(SnepMessage::VERSION, field, 0, 0, NULL);
}
SnepMessage* getSuccessResponse(NdefMessage* ndef)
{
if (!ndef) {
return new SnepMessage(SnepMessage::VERSION, SnepMessage::RESPONSE_SUCCESS, 0, 0, NULL);
} else {
std::vector<uint8_t> buf;
ndef->toByteArray(buf);
return new SnepMessage(SnepMessage::VERSION, SnepMessage::RESPONSE_SUCCESS, buf.size(), 0, ndef);
}
}
SnepMessage* SnepMessage::fromByteArray(std::vector<uint8_t>& buf)
{
return new SnepMessage(buf);
}
SnepMessage* SnepMessage::fromByteArray(uint8_t* pBuf, int size)
{
std::vector<uint8_t> buf;
for (int i = 0; i < size; i++)
buf[i] = pBuf[i];
return new SnepMessage(buf);
}
void SnepMessage::toByteArray(std::vector<uint8_t>& buf)
{
if (!mNdefMessage) {
mNdefMessage->toByteArray(buf);
}
std::vector<uint8_t> snepHeader;
snepHeader.push_back(mVersion);
snepHeader.push_back(mField);
if (mField == SnepMessage::REQUEST_GET) {
uint32_t len = buf.size() + 4;
snepHeader.push_back((len >> 24) & 0xFF);
snepHeader.push_back((len >> 16) & 0xFF);
snepHeader.push_back((len >> 8) & 0xFF);
snepHeader.push_back( len & 0xFF);
snepHeader.push_back((mAcceptableLength >> 24) & 0xFF);
snepHeader.push_back((mAcceptableLength >> 16) & 0xFF);
snepHeader.push_back((mAcceptableLength >> 8) & 0xFF);
snepHeader.push_back( mAcceptableLength & 0xFF);
} else {
uint32_t len = buf.size();
snepHeader.push_back((len >> 24) & 0xFF);
snepHeader.push_back((len >> 16) & 0xFF);
snepHeader.push_back((len >> 8) & 0xFF);
snepHeader.push_back( len & 0xFF);
}
buf.insert(buf.begin(), snepHeader.begin(), snepHeader.end());
}
| #include "SnepMessage.h"
#include "NdefMessage.h"
#define LOG_TAG "nfcd"
#include <cutils/log.h>
SnepMessage::SnepMessage()
: mNdefMessage(NULL)
{
}
SnepMessage::~SnepMessage()
{
if (mNdefMessage)
delete mNdefMessage;
}
SnepMessage::SnepMessage(std::vector<uint8_t>& buf)
{
int ndefOffset = 0;
int ndefLength = 0;
int idx = 0;
mVersion = buf[idx++];
mField = buf[idx++];
mLength = ((uint32_t)buf[idx] << 24) |
((uint32_t)buf[idx + 1] << 16) |
((uint32_t)buf[idx + 2] << 8) |
(uint32_t)buf[idx + 3];
idx += 4 ;
if (mField == SnepMessage::REQUEST_GET) {
mAcceptableLength = ((uint32_t)buf[idx] << 24) |
((uint32_t)buf[idx + 1] << 16) |
((uint32_t)buf[idx + 2] << 8) |
(uint32_t)buf[idx + 3];
idx += 4;
ndefOffset = SnepMessage::HEADER_LENGTH + 4;
ndefLength = mLength - 4;
} else {
mAcceptableLength = -1;
ndefOffset = SnepMessage::HEADER_LENGTH;
ndefLength = mLength;
}
if (ndefLength > 0) {
mNdefMessage = new NdefMessage();
// TODO : Need to check idx is correct.
mNdefMessage->init(buf, idx);
} else {
mNdefMessage = NULL;
}
}
SnepMessage::SnepMessage(uint8_t version, uint8_t field, int length,
int acceptableLength, NdefMessage* ndefMessage)
{
mVersion = version;
mField = field;
mLength = length;
mAcceptableLength = acceptableLength;
mNdefMessage = ndefMessage;
}
SnepMessage* SnepMessage::getGetRequest(int acceptableLength, NdefMessage& ndef)
{
std::vector<uint8_t> buf;
ndef.toByteArray(buf);
return new SnepMessage(SnepMessage::VERSION, SnepMessage::REQUEST_GET, 4 + buf.size(), acceptableLength, &ndef);
}
SnepMessage* SnepMessage::getPutRequest(NdefMessage& ndef)
{
std::vector<uint8_t> buf;
ndef.toByteArray(buf);
return new SnepMessage(SnepMessage::VERSION, SnepMessage::REQUEST_PUT, buf.size(), 0, &ndef);
}
SnepMessage* SnepMessage::getMessage(uint8_t field)
{
return new SnepMessage(SnepMessage::VERSION, field, 0, 0, NULL);
}
SnepMessage* getSuccessResponse(NdefMessage* ndef)
{
if (!ndef) {
return new SnepMessage(SnepMessage::VERSION, SnepMessage::RESPONSE_SUCCESS, 0, 0, NULL);
} else {
std::vector<uint8_t> buf;
ndef->toByteArray(buf);
return new SnepMessage(SnepMessage::VERSION, SnepMessage::RESPONSE_SUCCESS, buf.size(), 0, ndef);
}
}
SnepMessage* SnepMessage::fromByteArray(std::vector<uint8_t>& buf)
{
return new SnepMessage(buf);
}
SnepMessage* SnepMessage::fromByteArray(uint8_t* pBuf, int size)
{
std::vector<uint8_t> buf;
for (int i = 0; i < size; i++)
buf[i] = pBuf[i];
return new SnepMessage(buf);
}
void SnepMessage::toByteArray(std::vector<uint8_t>& buf)
{
if (mNdefMessage) {
mNdefMessage->toByteArray(buf);
}
std::vector<uint8_t> snepHeader;
snepHeader.push_back(mVersion);
snepHeader.push_back(mField);
if (mField == SnepMessage::REQUEST_GET) {
uint32_t len = buf.size() + 4;
snepHeader.push_back((len >> 24) & 0xFF);
snepHeader.push_back((len >> 16) & 0xFF);
snepHeader.push_back((len >> 8) & 0xFF);
snepHeader.push_back( len & 0xFF);
snepHeader.push_back((mAcceptableLength >> 24) & 0xFF);
snepHeader.push_back((mAcceptableLength >> 16) & 0xFF);
snepHeader.push_back((mAcceptableLength >> 8) & 0xFF);
snepHeader.push_back( mAcceptableLength & 0xFF);
} else {
uint32_t len = buf.size();
snepHeader.push_back((len >> 24) & 0xFF);
snepHeader.push_back((len >> 16) & 0xFF);
snepHeader.push_back((len >> 8) & 0xFF);
snepHeader.push_back( len & 0xFF);
}
buf.insert(buf.begin(), snepHeader.begin(), snepHeader.end());
}
| Fix snep bug when receive | Fix snep bug when receive
| C++ | apache-2.0 | mozilla-b2g/platform_system_nfcd,viralwang/platform_system_nfcd,viralwang/platform_system_nfcd,mozilla-b2g/platform_system_nfcd |
3bb645f28e995eb376a83b62a01fdbd7257d6841 | src/args.cc | src/args.cc | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "args.h"
#include "stdlib.h"
#include <string.h>
#include <iostream>
#include <fstream>
Args::Args() {
lr = 0.025;
dim = 100;
ws = 5;
epoch = 5;
minCount = 5;
neg = 5;
wordNgrams = 1;
sampling = sampling_name::sqrt;
loss = loss_name::ns;
model = model_name::sg;
bucket = 2000000;
minn = 3;
maxn = 6;
onlyWord = 0;
thread = 12;
verbose = 1000;
t = 1e-4;
label = L"__label__";
}
void Args::parseArgs(int argc, char** argv) {
if (argc == 1) {
std::wcout << "No arguments were provided! Usage:" << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
std::string command(argv[1]);
if (command == "supervised") {
model = model_name::sup;
loss = loss_name::softmax;
} else if (command == "cbow") {
model == model_name::cbow;
}
int ai = 2;
while (ai < argc) {
if (argv[ai][0] != '-') {
std::wcout << "Provided argument without a dash! Usage:" << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
if (strcmp(argv[ai], "-h") == 0) {
std::wcout << "Here is the help! Usage:" << std::endl;
printHelp();
exit(EXIT_FAILURE);
} else if (strcmp(argv[ai], "-input") == 0) {
input = std::string(argv[ai + 1]);
} else if (strcmp(argv[ai], "-test") == 0) {
test = std::string(argv[ai + 1]);
} else if (strcmp(argv[ai], "-output") == 0) {
output = std::string(argv[ai + 1]);
} else if (strcmp(argv[ai], "-lr") == 0) {
lr = atof(argv[ai + 1]);
} else if (strcmp(argv[ai], "-dim") == 0) {
dim = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-ws") == 0) {
ws = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-epoch") == 0) {
epoch = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-minCount") == 0) {
minCount = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-neg") == 0) {
neg = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-wordNgrams") == 0) {
wordNgrams = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-sampling") == 0) {
if (strcmp(argv[ai + 1], "sqrt") == 0) {
sampling = sampling_name::sqrt;
} else if (strcmp(argv[ai + 1], "log") == 0) {
sampling = sampling_name::log;
} else if (strcmp(argv[ai + 1], "uni") == 0) {
sampling = sampling_name::uni;
} else {
std::wcout << "Unknown sampling: " << argv[ai + 1] << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
} else if (strcmp(argv[ai], "-loss") == 0) {
if (strcmp(argv[ai + 1], "hs") == 0) {
loss = loss_name::hs;
} else if (strcmp(argv[ai + 1], "ns") == 0) {
loss = loss_name::ns;
} else if (strcmp(argv[ai + 1], "softmax") == 0) {
loss = loss_name::softmax;
} else {
std::wcout << "Unknown loss: " << argv[ai + 1] << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
} else if (strcmp(argv[ai], "-bucket") == 0) {
bucket = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-minn") == 0) {
minn = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-maxn") == 0) {
maxn = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-onlyWord") == 0) {
onlyWord = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-thread") == 0) {
thread = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-verbose") == 0) {
verbose = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-t") == 0) {
t = atof(argv[ai + 1]);
} else if (strcmp(argv[ai], "-label") == 0) {
std::string str = std::string(argv[ai + 1]);
label = std::wstring(str.begin(), str.end());
} else {
std::wcout << "Unknown argument: " << argv[ai] << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
ai += 2;
}
if (input.empty() || output.empty()) {
std::wcout << "Empty input or output path." << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
}
void Args::printHelp() {
std::wcout
<< "\n"
<< "The following arguments are mandatory:\n"
<< " -input training file path\n"
<< " -output output file path\n\n"
<< "The following arguments are optional:\n"
<< " -lr learning rate [" << lr << "]\n"
<< " -dim size of word vectors [" << dim << "]\n"
<< " -ws size of the context window [" << ws << "]\n"
<< " -epoch number of epochs [" << epoch << "]\n"
<< " -minCount minimal number of word occurences [" << minCount << "]\n"
<< " -neg number of negatives sampled [" << neg << "]\n"
<< " -wordNgrams max length of word ngram [" << wordNgrams << "]\n"
<< " -sampling sampling distribution {sqrt, log, uni} [log]\n"
<< " -loss loss function {ns, hs, softmax} [ns]\n"
<< " -bucket number of buckets [" << bucket << "]\n"
<< " -minn min length of char ngram [" << minn << "]\n"
<< " -maxn max length of char ngram [" << maxn << "]\n"
<< " -onlyWord number of words with no ngrams [" << onlyWord << "]\n"
<< " -thread number of threads [" << thread << "]\n"
<< " -verbose how often to print to stdout [" << verbose << "]\n"
<< " -t sampling threshold [" << t << "]\n"
<< " -label labels prefix [" << label << "]\n"
<< std::endl;
}
void Args::save(std::ofstream& ofs) {
if (ofs.is_open()) {
ofs.write((char*) &(dim), sizeof(int));
ofs.write((char*) &(ws), sizeof(int));
ofs.write((char*) &(epoch), sizeof(int));
ofs.write((char*) &(minCount), sizeof(int));
ofs.write((char*) &(neg), sizeof(int));
ofs.write((char*) &(wordNgrams), sizeof(int));
ofs.write((char*) &(sampling), sizeof(sampling_name));
ofs.write((char*) &(loss), sizeof(loss_name));
ofs.write((char*) &(model), sizeof(model_name));
ofs.write((char*) &(bucket), sizeof(int));
ofs.write((char*) &(minn), sizeof(int));
ofs.write((char*) &(maxn), sizeof(int));
ofs.write((char*) &(onlyWord), sizeof(int));
ofs.write((char*) &(verbose), sizeof(int));
ofs.write((char*) &(t), sizeof(double));
}
}
void Args::load(std::ifstream& ifs) {
if (ifs.is_open()) {
ifs.read((char*) &(dim), sizeof(int));
ifs.read((char*) &(ws), sizeof(int));
ifs.read((char*) &(epoch), sizeof(int));
ifs.read((char*) &(minCount), sizeof(int));
ifs.read((char*) &(neg), sizeof(int));
ifs.read((char*) &(wordNgrams), sizeof(int));
ifs.read((char*) &(sampling), sizeof(sampling_name));
ifs.read((char*) &(loss), sizeof(loss_name));
ifs.read((char*) &(model), sizeof(model_name));
ifs.read((char*) &(bucket), sizeof(int));
ifs.read((char*) &(minn), sizeof(int));
ifs.read((char*) &(maxn), sizeof(int));
ifs.read((char*) &(onlyWord), sizeof(int));
ifs.read((char*) &(verbose), sizeof(int));
ifs.read((char*) &(t), sizeof(double));
}
}
| /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "args.h"
#include "stdlib.h"
#include <string.h>
#include <iostream>
#include <fstream>
Args::Args() {
lr = 0.025;
dim = 100;
ws = 5;
epoch = 5;
minCount = 5;
neg = 5;
wordNgrams = 1;
sampling = sampling_name::sqrt;
loss = loss_name::ns;
model = model_name::sg;
bucket = 2000000;
minn = 3;
maxn = 6;
onlyWord = 0;
thread = 12;
verbose = 1000;
t = 1e-4;
label = L"__label__";
}
void Args::parseArgs(int argc, char** argv) {
std::string command(argv[1]);
if (command == "supervised") {
model = model_name::sup;
loss = loss_name::softmax;
} else if (command == "cbow") {
model == model_name::cbow;
}
int ai = 2;
while (ai < argc) {
if (argv[ai][0] != '-') {
std::wcout << "Provided argument without a dash! Usage:" << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
if (strcmp(argv[ai], "-h") == 0) {
std::wcout << "Here is the help! Usage:" << std::endl;
printHelp();
exit(EXIT_FAILURE);
} else if (strcmp(argv[ai], "-input") == 0) {
input = std::string(argv[ai + 1]);
} else if (strcmp(argv[ai], "-test") == 0) {
test = std::string(argv[ai + 1]);
} else if (strcmp(argv[ai], "-output") == 0) {
output = std::string(argv[ai + 1]);
} else if (strcmp(argv[ai], "-lr") == 0) {
lr = atof(argv[ai + 1]);
} else if (strcmp(argv[ai], "-dim") == 0) {
dim = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-ws") == 0) {
ws = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-epoch") == 0) {
epoch = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-minCount") == 0) {
minCount = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-neg") == 0) {
neg = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-wordNgrams") == 0) {
wordNgrams = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-sampling") == 0) {
if (strcmp(argv[ai + 1], "sqrt") == 0) {
sampling = sampling_name::sqrt;
} else if (strcmp(argv[ai + 1], "log") == 0) {
sampling = sampling_name::log;
} else if (strcmp(argv[ai + 1], "uni") == 0) {
sampling = sampling_name::uni;
} else {
std::wcout << "Unknown sampling: " << argv[ai + 1] << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
} else if (strcmp(argv[ai], "-loss") == 0) {
if (strcmp(argv[ai + 1], "hs") == 0) {
loss = loss_name::hs;
} else if (strcmp(argv[ai + 1], "ns") == 0) {
loss = loss_name::ns;
} else if (strcmp(argv[ai + 1], "softmax") == 0) {
loss = loss_name::softmax;
} else {
std::wcout << "Unknown loss: " << argv[ai + 1] << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
} else if (strcmp(argv[ai], "-bucket") == 0) {
bucket = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-minn") == 0) {
minn = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-maxn") == 0) {
maxn = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-onlyWord") == 0) {
onlyWord = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-thread") == 0) {
thread = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-verbose") == 0) {
verbose = atoi(argv[ai + 1]);
} else if (strcmp(argv[ai], "-t") == 0) {
t = atof(argv[ai + 1]);
} else if (strcmp(argv[ai], "-label") == 0) {
std::string str = std::string(argv[ai + 1]);
label = std::wstring(str.begin(), str.end());
} else {
std::wcout << "Unknown argument: " << argv[ai] << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
ai += 2;
}
if (input.empty() || output.empty()) {
std::wcout << "Empty input or output path." << std::endl;
printHelp();
exit(EXIT_FAILURE);
}
}
void Args::printHelp() {
std::wcout
<< "\n"
<< "The following arguments are mandatory:\n"
<< " -input training file path\n"
<< " -output output file path\n\n"
<< "The following arguments are optional:\n"
<< " -lr learning rate [" << lr << "]\n"
<< " -dim size of word vectors [" << dim << "]\n"
<< " -ws size of the context window [" << ws << "]\n"
<< " -epoch number of epochs [" << epoch << "]\n"
<< " -minCount minimal number of word occurences [" << minCount << "]\n"
<< " -neg number of negatives sampled [" << neg << "]\n"
<< " -wordNgrams max length of word ngram [" << wordNgrams << "]\n"
<< " -sampling sampling distribution {sqrt, log, uni} [log]\n"
<< " -loss loss function {ns, hs, softmax} [ns]\n"
<< " -bucket number of buckets [" << bucket << "]\n"
<< " -minn min length of char ngram [" << minn << "]\n"
<< " -maxn max length of char ngram [" << maxn << "]\n"
<< " -onlyWord number of words with no ngrams [" << onlyWord << "]\n"
<< " -thread number of threads [" << thread << "]\n"
<< " -verbose how often to print to stdout [" << verbose << "]\n"
<< " -t sampling threshold [" << t << "]\n"
<< " -label labels prefix [" << label << "]\n"
<< std::endl;
}
void Args::save(std::ofstream& ofs) {
if (ofs.is_open()) {
ofs.write((char*) &(dim), sizeof(int));
ofs.write((char*) &(ws), sizeof(int));
ofs.write((char*) &(epoch), sizeof(int));
ofs.write((char*) &(minCount), sizeof(int));
ofs.write((char*) &(neg), sizeof(int));
ofs.write((char*) &(wordNgrams), sizeof(int));
ofs.write((char*) &(sampling), sizeof(sampling_name));
ofs.write((char*) &(loss), sizeof(loss_name));
ofs.write((char*) &(model), sizeof(model_name));
ofs.write((char*) &(bucket), sizeof(int));
ofs.write((char*) &(minn), sizeof(int));
ofs.write((char*) &(maxn), sizeof(int));
ofs.write((char*) &(onlyWord), sizeof(int));
ofs.write((char*) &(verbose), sizeof(int));
ofs.write((char*) &(t), sizeof(double));
}
}
void Args::load(std::ifstream& ifs) {
if (ifs.is_open()) {
ifs.read((char*) &(dim), sizeof(int));
ifs.read((char*) &(ws), sizeof(int));
ifs.read((char*) &(epoch), sizeof(int));
ifs.read((char*) &(minCount), sizeof(int));
ifs.read((char*) &(neg), sizeof(int));
ifs.read((char*) &(wordNgrams), sizeof(int));
ifs.read((char*) &(sampling), sizeof(sampling_name));
ifs.read((char*) &(loss), sizeof(loss_name));
ifs.read((char*) &(model), sizeof(model_name));
ifs.read((char*) &(bucket), sizeof(int));
ifs.read((char*) &(minn), sizeof(int));
ifs.read((char*) &(maxn), sizeof(int));
ifs.read((char*) &(onlyWord), sizeof(int));
ifs.read((char*) &(verbose), sizeof(int));
ifs.read((char*) &(t), sizeof(double));
}
}
| Remove unused test in Args::parseArgs | Remove unused test in Args::parseArgs
| C++ | mit | facebookresearch/fastText,magicBus234/fastTextJob,facebookresearch/fastText,magicBus234/fastTextJob,facebookresearch/fastText,magicBus234/fastTextJob,magicBus234/fastTextJob,facebookresearch/fastText,facebookresearch/fastText,facebookresearch/fastText |
f23cee1925600f6f6dfe3e8090074b9c1b34e752 | src/unittest/chunker.cpp | src/unittest/chunker.cpp | /**
* unittest/chunker.cpp: test cases for the read filtering/transforming logic
*/
#include "catch.hpp"
#include "chunker.hpp"
#include "readfilter.hpp"
namespace vg {
namespace unittest {
using namespace std;
TEST_CASE("basic graph chunking", "[chunk]") {
// Build a toy graph (copied from readfilter test)
const string graph_json = R"(
{
"node": [
{"id": 1, "sequence": "GATTAC"},
{"id": 2, "sequence": "A"},
{"id": 3, "sequence": "AAAAA"},
{"id": 4, "sequence": "CATTAG"},
{"id": 5, "sequence": "TAGTAG"},
{"id": 6, "sequence": "TAG"},
{"id": 7, "sequence": "AGATA"},
{"id": 8, "sequence": "TTT"},
{"id": 9, "sequence": "AAA"}
],
"edge": [
{"from": 1, "to": 2},
{"from": 2, "to": 3},
{"from": 1, "to": 3},
{"from": 3, "to": 4},
{"from": 4, "to": 5},
{"from": 6, "to": 4, "from_start": true, "to_end": true},
{"from": 4, "to": 6, "from_start": true},
{"from": 5, "to": 7},
{"from": 6, "to": 7},
{"from": 7, "to": 8, "to_end": true},
{"from": 7, "to": 9},
{"from": 7, "to": 5, "to_end": true}
],
"path": [
{"name": "x", "mapping": [
{"position": {"node_id": 1}, "rank": 1},
{"position": {"node_id": 2}, "rank": 2},
{"position": {"node_id": 3}, "rank": 3},
{"position": {"node_id": 4}, "rank": 4},
{"position": {"node_id": 5}, "rank": 5},
{"position": {"node_id": 7}, "rank": 6},
{"position": {"node_id": 9}, "rank": 7}]},
{"name": "y", "mapping": [
{"position": {"node_id": 1}, "rank": 1},
{"position": {"node_id": 3}, "rank": 2},
{"position": {"node_id": 4}, "rank": 3},
{"position": {"node_id": 6}, "rank": 4},
{"position": {"node_id": 7}, "rank": 5},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 6},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 7}]},
{"name": "z", "mapping": [
{"position": {"node_id": 1}, "rank": 1},
{"position": {"node_id": 3}, "rank": 2},
{"position": {"node_id": 4}, "rank": 3},
{"position": {"node_id": 6}, "rank": 4},
{"position": {"node_id": 7}, "rank": 5},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 6},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 7},
{"position": {"node_id": 6}, "rank": 8},
{"position": {"node_id": 7}, "rank": 9},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 10},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 11},
{"position": {"node_id": 6}, "rank": 12},
{"position": {"node_id": 7}, "rank": 13},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 14},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 15}]}
]
}
)";
// Load it into Protobuf
Graph chunk;
json2pb(chunk, graph_json.c_str(), graph_json.size());
// Pass it over to XG
xg::XG index(chunk);
PathChunker chunker(&index);
SECTION("Extract whole graph as chunk") {
// Note: regions are 1-based inclusive
Region region = {"x", 1, 32};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 9);
REQUIRE(subgraph.edge_count() == 12);
REQUIRE(out_region.start == 1);
}
SECTION("Extract partial graph as chunk") {
Region region = {"x", 9, 16};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 6);
REQUIRE(subgraph.edge_count() == 7);
REQUIRE(out_region.start == 1);
}
SECTION("Extract partial graph as chunk via id range") {
Region region = {"x", 3, 6};
VG subgraph;
Region out_region;
chunker.extract_id_range(region.start, region.end, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 7);
REQUIRE(subgraph.edge_count() == 10);
REQUIRE(out_region.start == 1);
}
SECTION("Extract partial graph as chunk with exact node boundary") {
Region region = {"x", 8, 16};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 6);
REQUIRE(subgraph.edge_count() == 7);
REQUIRE(out_region.start == 1);
}
SECTION("Extract whole graph via harder path") {
Region region = {"y", 1, 37};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 9);
REQUIRE(subgraph.edge_count() == 12);
REQUIRE(out_region.start == 1);
}
SECTION("Extract partial graph via harder path") {
Region region = {"y", 15, 35};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 7);
REQUIRE(subgraph.edge_count() == 9);
REQUIRE(out_region.start == 7);
}
SECTION("Extract whole graph via cyclic path") {
Region region = {"z", 1, 60};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 9);
REQUIRE(subgraph.edge_count() == 12);
REQUIRE(out_region.start == 1);
}
SECTION("Partial graph via cyclic path") {
Region region = {"z", 36, 59};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 7);
REQUIRE(subgraph.edge_count() == 9);
REQUIRE(out_region.start == 7);
}
}
}
}
| /**
* unittest/chunker.cpp: test cases for the read filtering/transforming logic
*/
#include "catch.hpp"
#include "chunker.hpp"
#include "readfilter.hpp"
namespace vg {
namespace unittest {
using namespace std;
TEST_CASE("basic graph chunking", "[chunk]") {
// Build a toy graph (copied from readfilter test)
const string graph_json = R"(
{
"node": [
{"id": 1, "sequence": "GATTAC"},
{"id": 2, "sequence": "A"},
{"id": 3, "sequence": "AAAAA"},
{"id": 4, "sequence": "CATTAG"},
{"id": 5, "sequence": "TAGTAG"},
{"id": 6, "sequence": "TAG"},
{"id": 7, "sequence": "AGATA"},
{"id": 8, "sequence": "TTT"},
{"id": 9, "sequence": "AAA"}
],
"edge": [
{"from": 1, "to": 2},
{"from": 2, "to": 3},
{"from": 1, "to": 3},
{"from": 3, "to": 4},
{"from": 4, "to": 5},
{"from": 6, "to": 4, "from_start": true, "to_end": true},
{"from": 4, "to": 6, "from_start": true},
{"from": 5, "to": 7},
{"from": 6, "to": 7},
{"from": 7, "to": 8, "to_end": true},
{"from": 7, "to": 9},
{"from": 7, "to": 5, "to_end": true}
],
"path": [
{"name": "x", "mapping": [
{"position": {"node_id": 1}, "rank": 1},
{"position": {"node_id": 2}, "rank": 2},
{"position": {"node_id": 3}, "rank": 3},
{"position": {"node_id": 4}, "rank": 4},
{"position": {"node_id": 5}, "rank": 5},
{"position": {"node_id": 7}, "rank": 6},
{"position": {"node_id": 9}, "rank": 7}]},
{"name": "y", "mapping": [
{"position": {"node_id": 1}, "rank": 1},
{"position": {"node_id": 3}, "rank": 2},
{"position": {"node_id": 4}, "rank": 3},
{"position": {"node_id": 6}, "rank": 4},
{"position": {"node_id": 7}, "rank": 5},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 6},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 7}]},
{"name": "z", "mapping": [
{"position": {"node_id": 1}, "rank": 1},
{"position": {"node_id": 3}, "rank": 2},
{"position": {"node_id": 4}, "rank": 3},
{"position": {"node_id": 6}, "rank": 4},
{"position": {"node_id": 7}, "rank": 5},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 6},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 7},
{"position": {"node_id": 6}, "rank": 8},
{"position": {"node_id": 7}, "rank": 9},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 10},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 11},
{"position": {"node_id": 6}, "rank": 12},
{"position": {"node_id": 7}, "rank": 13},
{"position": {"node_id": 5, "is_reverse": true}, "rank": 14},
{"position": {"node_id": 4, "is_reverse": true}, "rank": 15}]}
]
}
)";
// Load it into Protobuf
Graph chunk;
json2pb(chunk, graph_json.c_str(), graph_json.size());
// Pass it over to XG
xg::XG index(chunk);
PathChunker chunker(&index);
SECTION("Extract whole graph as chunk") {
// Note: regions are 0-based inclusive
Region region = {"x", 1, 32};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 9);
REQUIRE(subgraph.edge_count() == 12);
REQUIRE(out_region.start == 0);
}
SECTION("Extract partial graph as chunk") {
Region region = {"x", 9, 16};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 6);
REQUIRE(subgraph.edge_count() == 7);
REQUIRE(out_region.start == 0);
}
SECTION("Extract partial graph as chunk via id range") {
Region region = {"x", 3, 6};
VG subgraph;
Region out_region;
chunker.extract_id_range(region.start, region.end, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 7);
REQUIRE(subgraph.edge_count() == 10);
REQUIRE(out_region.start == 1);
}
SECTION("Extract partial graph as chunk with exact node boundary") {
Region region = {"x", 8, 16};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 6);
REQUIRE(subgraph.edge_count() == 7);
REQUIRE(out_region.start == 0);
}
SECTION("Extract whole graph via harder path") {
Region region = {"y", 1, 37};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 9);
REQUIRE(subgraph.edge_count() == 12);
REQUIRE(out_region.start == 0);
}
SECTION("Extract partial graph via harder path") {
Region region = {"y", 15, 35};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 7);
REQUIRE(subgraph.edge_count() == 9);
REQUIRE(out_region.start == 6);
}
SECTION("Extract whole graph via cyclic path") {
Region region = {"z", 1, 60};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 9);
REQUIRE(subgraph.edge_count() == 12);
REQUIRE(out_region.start == 0);
}
SECTION("Partial graph via cyclic path") {
Region region = {"z", 36, 59};
VG subgraph;
Region out_region;
chunker.extract_subgraph(region, 1, false, subgraph, out_region);
REQUIRE(subgraph.node_count() == 7);
REQUIRE(subgraph.edge_count() == 9);
REQUIRE(out_region.start == 6);
}
}
}
}
| fix chunk unit tests to expect 0-based outputs | fix chunk unit tests to expect 0-based outputs
| C++ | mit | ekg/vg,ekg/vg,ekg/vg |
2f7194f49e7b35123a4c28bb0f906927a9ff6043 | GAME/OBJLIGHT.C | GAME/OBJLIGHT.C | #include "OBJLIGHT.H"
#include "CAMERA.H"
#include "CONTROL.H"
#include "SPECIFIC.H"
#if PSX_VERSION || PSXPC_VERSION
#include "SPHERES.H"
#include "BUBBLES.H"
#endif
struct FOOTPRINT FootPrint[32];
int FootPrintNum;
//void /*$ra*/ TriggerAlertLight(long x /*$s2*/, long y /*$s3*/, long z /*$s1*/, long r /*$s5*/, long g /*stack 16*/, long b /*stack 20*/, long angle /*stack 24*/, int room_no /*stack 28*/, int falloff /*stack 32*/)
void TriggerAlertLight(long x, long y, long z, long r, long g, long b, long angle, int room_no, int falloff)//5D018, 5D494
{
UNIMPLEMENTED();
}
void ControlStrobeLight(short item_number)//5D118(<), 5D594
{
struct ITEM_INFO* item;
long angle;
long sin;
long cos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
angle = item->pos.y_rot + 2912;
r = (item->trigger_flags) & 0x1F << 3;
b = (item->trigger_flags << 16) >> 17 & 0xF8;
g = (item->trigger_flags << 16) >> 12 & 0xF8;
item->pos.y_rot = angle;
angle += 22528;
angle >>= 4;
angle &= 0xFFF;
TriggerAlertLight(item->box_number, item->pos.y_pos - 512, item->pos.z_pos, r, g, b, angle, 12, item->room_number);
sin = rcossin_tbl[angle];
angle |= 2;
cos = rcossin_tbl[angle | 1];
TriggerDynamic(item->pos.x_pos + ((sin << 16) >> 14), item->pos.y_pos - 768, (item->pos.z_pos + (cos << 16) >> 14), 12, r, g ,b);
}
void ControlPulseLight(short item_number)//5D254, 5D6D0
{
UNIMPLEMENTED();
}
void ControlColouredLight(short item_number)//5D368, 5D7E4
{
UNIMPLEMENTED();
}
void ControlElectricalLight(short item_number)//5D3F8, 5D874
{
UNIMPLEMENTED();
}
void ControlBlinker(short item_number)//5D660(<), 5DADC (F)
{
struct ITEM_INFO* item;
struct PHD_VECTOR pos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
if (--item->item_flags[0] < 3)
{
pos.z = 0;
pos.y = 0;
pos.z = 0;
GetJointAbsPosition(item, &pos, 0);
r = (item->trigger_flags & 0x1F) << 3;
g = (item->trigger_flags >> 4) & 0xF8;
b = (item->trigger_flags >> 1) & 0xF8;
TriggerDynamic(pos.x, pos.y, pos.z, 16, r, g, b);
item->mesh_bits = 2;
if (item->item_flags[0] < 0)
{
item->item_flags[0] = 30;
}//5D73C
}
else
{
//5D734
item->mesh_bits = 1;
}
} | #include "OBJLIGHT.H"
#include "CAMERA.H"
#include "CONTROL.H"
#include "SPECIFIC.H"
#if PSX_VERSION || PSXPC_VERSION
#include "SPHERES.H"
#include "BUBBLES.H"
#endif
struct FOOTPRINT FootPrint[32];
int FootPrintNum;
//void /*$ra*/ TriggerAlertLight(long x /*$s2*/, long y /*$s3*/, long z /*$s1*/, long r /*$s5*/, long g /*stack 16*/, long b /*stack 20*/, long angle /*stack 24*/, int room_no /*stack 28*/, int falloff /*stack 32*/)
void TriggerAlertLight(long x, long y, long z, long r, long g, long b, long angle, int room_no, int falloff)//5D018, 5D494
{
UNIMPLEMENTED();
}
void ControlStrobeLight(short item_number)//5D118(<), 5D594 ///@FIXME im not sure this is correct redo this
{
struct ITEM_INFO* item;
long angle;
long sin;
long cos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
angle = item->pos.y_rot + 2912;
r = (item->trigger_flags) & 0x1F << 3;
b = (item->trigger_flags << 16) >> 17 & 0xF8;
g = (item->trigger_flags << 16) >> 12 & 0xF8;
item->pos.y_rot = angle;
angle += 22528;
angle >>= 4;
angle &= 0xFFF;
TriggerAlertLight(item->box_number, item->pos.y_pos - 512, item->pos.z_pos, r, g, b, angle, 12, item->room_number);
sin = rcossin_tbl[angle];
cos = rcossin_tbl[angle | 1];
TriggerDynamic(item->pos.x_pos + ((sin << 16) >> 14), item->pos.y_pos - 768, (item->pos.z_pos + (cos << 16) >> 14), 12, r, g ,b);
}
void ControlPulseLight(short item_number)//5D254(<), 5D6D0 (F)
{
struct ITEM_INFO* item;
long sin;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
item->item_flags[0] -= 1024;
sin = ABS(SIN((item->pos.y_pos & 0x3FFF) << 2) << 16 >> 14);
if (sin > 255)
{
sin = 255;
}//5D2F0
r = sin * ((item->trigger_flags & 0x1F) << 3) >> 9;
g = sin * ((item->trigger_flags << 10) >> 12) & 0xF8 >> 9;
b = sin * ((item->trigger_flags >> 17) & 0xF8) >> 9;
TriggerDynamic(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 24, r, g, b);
}
void ControlColouredLight(short item_number)//5D368, 5D7E4
{
UNIMPLEMENTED();
}
void ControlElectricalLight(short item_number)//5D3F8, 5D874
{
UNIMPLEMENTED();
}
void ControlBlinker(short item_number)//5D660(<), 5DADC (F)
{
struct ITEM_INFO* item;
struct PHD_VECTOR pos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
if (--item->item_flags[0] < 3)
{
pos.z = 0;
pos.y = 0;
pos.z = 0;
GetJointAbsPosition(item, &pos, 0);
r = (item->trigger_flags & 0x1F) << 3;
g = (item->trigger_flags >> 4) & 0xF8;
b = (item->trigger_flags >> 1) & 0xF8;
TriggerDynamic(pos.x, pos.y, pos.z, 16, r, g, b);
item->mesh_bits = 2;
if (item->item_flags[0] < 0)
{
item->item_flags[0] = 30;
}//5D73C
}
else
{
//5D734
item->mesh_bits = 1;
}
} | Add ControlPulseLight | Add ControlPulseLight
| C++ | mit | TOMB5/TOMB5,TOMB5/TOMB5,TOMB5/TOMB5,TOMB5/TOMB5 |
79963090ca2e2bb929fd9dff774c5d7b72c8c5ac | src/map.cpp | src/map.cpp | #include <SDL.h>
#include <stdio.h>
#include <cstdlib>
#include <cmath>
#include "map.h"
#include "image.h"
#include "world.h"
#include <iostream>
#include <vector>
// returns chance of <eye> over <die> roll
bool roll(int die, int eye);
#define CELL_LENGTH 16
#define COL_TILE_DESIRED 7
#define TRUMP_SPEED 0.7f
Map::Map()
{
}
Map::~Map()
{
delete platformImage;
delete potatoImage;
delete meatImage;
delete babyImage;
delete moneyImage;
}
void Map::loadImages() {
// TODO initialize into spritemaps
platformImage = new Image( World::getRenderer(), "platform.png");
potatoImage = new Image( World::getRenderer(), "small_potatoes.png");
meatImage = new Image( World::getRenderer(), "Meatloaf.png");
babyImage = new Image( World::getRenderer(), "baby.png");
moneyImage = new Image( World::getRenderer(), "Money.png");
}
void Map::init()
{
// Load assets
loadImages();
cCol = std::ceil(World::getWidth() / CELL_LENGTH);
cRow = std::ceil(World::getHeight() / CELL_LENGTH);
// Initialize mapGrid, a representation of Grid
mapGrid = new MapItem*[cCol];
// Initialize into MAP_SKY
for (int i = 0; i < cCol; i++) {
mapGrid[i] = new MapItem[cRow];
for (int j = 0; j < cRow; j++) {
mapGrid[i][j] = MAP_SKY;
}
}
leftCol = 0;
CreateMap();
printMap();
}
void Map::CreateMap() {
for (int i = 1; i < cCol; i++) {
createColumn(i);
}
}
void Map::createColumn(int col) {
// Counting struct
ColCount scanInfo;
// Column to be examined.
int prevColumn = (col - 1) % cCol;
// Column to be written, in case we start a Barrier this time.
int nextColumn = (col + 1) % cCol;
// Current Column to be created.
int currColumn = col % cCol;
// Currently created Tile
int tileCount = 0;
// Clean up first.
cleanColumn(col);
scanColumn(prevColumn, scanInfo);
printCount(scanInfo);
for (int row = 0; row < cRow; row++) {
if (mapGrid[prevColumn][row] != MAP_SKY) {
// If BARRIER_A, continue the block.
if (mapGrid[prevColumn][row] == MAP_BARRIER_A) {
mapGrid[currColumn][row] = MAP_BARRIER_B;
}
// TODO set this Roll to be configurable
else if (roll(7, 3)) {
if (mapGrid[prevColumn][row] == MAP_BARRIER_B) {
mapGrid[currColumn][row] = MAP_BARRIER_A;
}
else {
mapGrid[currColumn][row] = mapGrid[prevColumn][row];
}
tileCount++;
}
}
}
// If this column has not enough tiles, give it another shot.
for( ;tileCount < COL_TILE_DESIRED; tileCount++) {
MapItem *newTile;
int nRow = rand() % cRow;
// TODO set this Roll to be configurable
if (roll(7, 5)) {
newTile = &mapGrid[currColumn][nRow];
if (*newTile == MAP_SKY) {
*newTile = MapItem(rand() % ITEM_KIND);
// Not gonna bother with retroactive barriering.
if (*newTile == MAP_BARRIER_B) {
*newTile = MAP_SKY;
}
}
}
}
}
void Map::scanColumn(int col, ColCount &result) {
for (int i = 0; i < ITEM_KIND; i++) {
result.count[i] = 0;
}
for (int row = 0; row < cRow; row++) {
result.count[mapGrid[col][row]]++;
}
result.non_sky = cCol - result.count[MAP_SKY];
}
void Map::cleanColumn(int col) {
// Column to be written, in case we start a Barrier this time.
int nextCol = (col + 1) % cCol;
for (int row = 0; row < cRow; row++) {
// If BARRIER_A, then clean the next part as well.
if (mapGrid[col][row] == MAP_BARRIER_A) {
mapGrid[nextCol][row] = MAP_SKY;
}
// If BARRIER_B, leave it alone; we don't want to be cleaning up first half.
if (mapGrid[col][row] != MAP_BARRIER_B) {
mapGrid[col][row] = MAP_SKY;
}
}
}
void Map::newGame()
{
printf("Map: New Game Init\n");
}
// Compute where at what screen coordinate the Grid Cell must be drawn.
void Map::gridToScreen(int gridX, int gridY, int &screenX, int &screenY) {
// Nominal - "original" location of the grid; i.e., without any offset.
float nominalX, nominalY;
// Adjusted - location of the draw after the alignment to current location.
float adjustedX, adjustedY;
nominalX = gridX * 16.0f;
nominalY = gridY * 16.0f;
// Shift horizontally
adjustedX = (nominalX - left) * 1.0f;
// Shift vertically(TOP should be coming from Jump mechanism)
adjustedY = nominalY * 1.0f;
if (gridX == 1 && gridY == 1) {
printf("%f, %f\n", adjustedX, adjustedY);
}
World::worldToScreen(adjustedX, adjustedY, screenX, screenY);
}
void Map::screenToGrid(int &gridX, int &gridY, int screenX, int screenY) {
float worldX, worldY;
float targetX, targetY;
// Translate screen coordinates to world coordinate.
World::screenToWorld(screenX, screenY, worldX, worldY);
// printf("%f, %f, %d, %d\n", worldX, worldY, screenX, screenY);
// World::getWidth() / CELL_LENGTH;
targetX = worldX;
targetY = worldY;
// printf("%f, %f, %d, %d\n", targetX, targetY, gridX, gridY);
targetX = targetX / CELL_LENGTH;
targetY = targetY / CELL_LENGTH;
gridX = (int) std::floor(targetX);
gridY = (int) std::floor(targetY);
// printf("%f, %f, %d, %d\n", targetX, targetY, gridX, gridY);
}
void Map::draw(SDL_Renderer *renderer)
{
Image *toDraw;
int screenX, screenY;
for (int x = 0; x < cCol; x++) {
for (int y = 0; y < cRow; y++) {
switch (mapGrid[x][y]) {
// Collectible
case MAP_BARRIER_A:
toDraw = platformImage;
break;
case MAP_POTATO:
toDraw = potatoImage;
break;
case MAP_MONEY:
toDraw = moneyImage;
break;
case MAP_MEATLOAF:
toDraw = meatImage;
break;
// Animation
case MAP_SIGN:
case MAP_WHITESTART:
case MAP_REDSTAR:
case MAP_BLUESTAR:
break;
// SKY
default:
toDraw = NULL;
break;
}
//kgridToScreen(int gridX, int gridY, int &screenX, int &screenY);
gridToScreen(x, y, screenX, screenY);
//printf("%d, %d\n", screenX, screenY);
if (toDraw != NULL) {
toDraw->draw(renderer, screenX, screenY);
}
}
}
}
bool tried = false;
void Map::update(int elapsed) {
if (tried) return;
// printf("COLLIDE: %d, %d: %d\n", 0, 0, collide(0, 0, 0, 0));
for (int i = 0; i < 18; i++) {
for (int j = 0; j < 18; j++) {
// collide(i, j, 0, 0);
// printf("Collide: %d, %d: %d\n", i, j, collide(i, j, 0, 0));
}
}
tried = true;
// 1. Shift horizontally.
// left += TRUMP_SPEED;
// data structure - this is a case where a linked list(vector?) would work
// TODO 1. shift horizontally
// TODO 2. determine if still in display
// TODO 3. dispose
}
int Map::collide(int x,int y,int w,int h)
{
int gridX, gridY;
screenToGrid(gridX, gridY, x, y);
printf("collide; :[%d, %d] %d, %d = %d\n", gridX, gridY, x, y, mapGrid[gridX][gridY]);
return mapGrid[gridX][gridY];
}
int Map::collect(int x,int y,int w,int h)
{
int gridX, gridY;
screenToGrid(gridX, gridY, x, y);
MapItem item = mapGrid[gridX][gridY];
mapGrid[gridX][gridY] = MAP_SKY;
return (int) item;
}
// Console Print
void Map::printMap() {
printf("cCol: %d, cRow: %d\n", cCol, cRow);
for (int i = 0; i < cRow; i++) {
printf("[");
for (int j = 0; j < cCol; j++) {
printf(" %d ", mapGrid[j][i]);
}
printf("]\n");
}
}
// Console Print
void Map::printCount(ColCount &c) {
printf("[");
for (int i = 0; i < ITEM_KIND; i++) {
printf(" %d ", c.count[i]);
}
printf("]\n");
}
// Helper function: returns true for eye / die.
bool roll(int die, int eye) {
return std::rand() % die < eye;
}
| #include <SDL.h>
#include <stdio.h>
#include <cstdlib>
#include <cmath>
#include "map.h"
#include "image.h"
#include "world.h"
#include <iostream>
#include <vector>
// returns chance of <eye> over <die> roll
bool roll(int die, int eye);
#define CELL_LENGTH 16
#define COL_TILE_DESIRED 7
#define TRUMP_SPEED 0.7f
Map::Map()
{
}
Map::~Map()
{
delete platformImage;
delete potatoImage;
delete meatImage;
delete babyImage;
delete moneyImage;
}
void Map::loadImages() {
// TODO initialize into spritemaps
platformImage = new Image( World::getRenderer(), "platform.png");
potatoImage = new Image( World::getRenderer(), "small_potatoes.png");
meatImage = new Image( World::getRenderer(), "Meatloaf.png");
babyImage = new Image( World::getRenderer(), "baby.png");
moneyImage = new Image( World::getRenderer(), "Money.png");
}
void Map::init()
{
// Load assets
loadImages();
cCol = std::ceil(World::getWidth() / CELL_LENGTH);
cRow = std::ceil(World::getHeight() / CELL_LENGTH);
// Initialize mapGrid, a representation of Grid
mapGrid = new MapItem*[cCol];
// Initialize into MAP_SKY
for (int i = 0; i < cCol; i++) {
mapGrid[i] = new MapItem[cRow];
for (int j = 0; j < cRow; j++) {
mapGrid[i][j] = MAP_SKY;
}
}
leftCol = 0;
CreateMap();
printMap();
}
void Map::CreateMap() {
for (int i = 1; i < cCol; i++) {
createColumn(i);
}
}
void Map::createColumn(int col) {
// Counting struct
ColCount scanInfo;
// Column to be examined.
int prevColumn = (col - 1) % cCol;
// Column to be written, in case we start a Barrier this time.
int nextColumn = (col + 1) % cCol;
// Current Column to be created.
int currColumn = col % cCol;
// Currently created Tile
int tileCount = 0;
// Clean up first.
cleanColumn(col);
scanColumn(prevColumn, scanInfo);
printCount(scanInfo);
for (int row = 0; row < cRow; row++) {
if (mapGrid[prevColumn][row] != MAP_SKY) {
// If BARRIER_A, continue the block.
if (mapGrid[prevColumn][row] == MAP_BARRIER_A) {
mapGrid[currColumn][row] = MAP_BARRIER_B;
}
// TODO set this Roll to be configurable
else if (roll(7, 3)) {
if (mapGrid[prevColumn][row] == MAP_BARRIER_B) {
mapGrid[currColumn][row] = MAP_BARRIER_A;
}
else {
mapGrid[currColumn][row] = mapGrid[prevColumn][row];
}
tileCount++;
}
}
}
// If this column has not enough tiles, give it another shot.
for( ;tileCount < COL_TILE_DESIRED; tileCount++) {
MapItem *newTile;
int nRow = rand() % cRow;
// TODO set this Roll to be configurable
if (roll(7, 5)) {
newTile = &mapGrid[currColumn][nRow];
if (*newTile == MAP_SKY) {
*newTile = MapItem(rand() % ITEM_KIND);
// Not gonna bother with retroactive barriering.
if (*newTile == MAP_BARRIER_B) {
*newTile = MAP_SKY;
}
}
}
}
}
void Map::scanColumn(int col, ColCount &result) {
for (int i = 0; i < ITEM_KIND; i++) {
result.count[i] = 0;
}
for (int row = 0; row < cRow; row++) {
result.count[mapGrid[col][row]]++;
}
result.non_sky = cCol - result.count[MAP_SKY];
}
void Map::cleanColumn(int col) {
// Column to be written, in case we start a Barrier this time.
int nextCol = (col + 1) % cCol;
for (int row = 0; row < cRow; row++) {
// If BARRIER_A, then clean the next part as well.
if (mapGrid[col][row] == MAP_BARRIER_A) {
mapGrid[nextCol][row] = MAP_SKY;
}
// If BARRIER_B, leave it alone; we don't want to be cleaning up first half.
if (mapGrid[col][row] != MAP_BARRIER_B) {
mapGrid[col][row] = MAP_SKY;
}
}
}
void Map::newGame()
{
printf("Map: New Game Init\n");
}
// Compute where at what screen coordinate the Grid Cell must be drawn.
void Map::gridToScreen(int gridX, int gridY, int &screenX, int &screenY) {
// Nominal - "original" location of the grid; i.e., without any offset.
float nominalX, nominalY;
// Adjusted - location of the draw after the alignment to current location.
float adjustedX, adjustedY;
nominalX = gridX * 16.0f;
nominalY = gridY * 16.0f;
// Shift horizontally
adjustedX = (nominalX - left) * 1.0f;
// Shift vertically(TOP should be coming from Jump mechanism)
adjustedY = nominalY * 1.0f;
World::worldToScreen(adjustedX, adjustedY, screenX, screenY);
}
void Map::screenToGrid(int &gridX, int &gridY, int screenX, int screenY) {
float worldX, worldY;
float targetX, targetY;
// Translate screen coordinates to world coordinate.
World::screenToWorld(screenX, screenY, worldX, worldY);
targetX = worldX;
targetY = worldY;
// printf("%f, %f, %d, %d\n", targetX, targetY, gridX, gridY);
targetX = targetX / CELL_LENGTH;
targetY = targetY / CELL_LENGTH;
gridX = (int) std::floor(targetX);
gridY = (int) std::floor(targetY);
// printf("%f, %f, %d, %d\n", targetX, targetY, gridX, gridY);
}
void Map::draw(SDL_Renderer *renderer)
{
Image *toDraw;
int screenX, screenY;
for (int x = 0; x < cCol; x++) {
for (int y = 0; y < cRow; y++) {
switch (mapGrid[x][y]) {
// Collectible
case MAP_BARRIER_A:
toDraw = platformImage;
break;
case MAP_POTATO:
toDraw = potatoImage;
break;
case MAP_MONEY:
toDraw = moneyImage;
break;
case MAP_MEATLOAF:
toDraw = meatImage;
break;
// Animation
case MAP_SIGN:
case MAP_WHITESTART:
case MAP_REDSTAR:
case MAP_BLUESTAR:
break;
// SKY
default:
toDraw = NULL;
break;
}
//kgridToScreen(int gridX, int gridY, int &screenX, int &screenY);
gridToScreen(x, y, screenX, screenY);
//printf("%d, %d\n", screenX, screenY);
if (toDraw != NULL) {
toDraw->draw(renderer, screenX, screenY);
}
}
}
}
bool tried = false;
void Map::update(int elapsed) {
if (tried) return;
// printf("COLLIDE: %d, %d: %d\n", 0, 0, collide(0, 0, 0, 0));
for (int i = 0; i < 18; i++) {
for (int j = 0; j < 18; j++) {
// collide(i, j, 0, 0);
// printf("Collide: %d, %d: %d\n", i, j, collide(i, j, 0, 0));
}
}
tried = true;
// 1. Shift horizontally.
// left += TRUMP_SPEED;
// data structure - this is a case where a linked list(vector?) would work
// TODO 2. determine if still in display
// TODO 3. dispose
}
int Map::collide(int x,int y,int w,int h)
{
int gridX, gridY;
screenToGrid(gridX, gridY, x, y);
printf("collide; :[%d, %d] %d, %d = %d\n", gridX, gridY, x, y, mapGrid[gridX][gridY]);
return mapGrid[gridX][gridY];
}
int Map::collect(int x,int y,int w,int h)
{
int gridX, gridY;
screenToGrid(gridX, gridY, x, y);
MapItem item = mapGrid[gridX][gridY];
mapGrid[gridX][gridY] = MAP_SKY;
return (int) item;
}
// Console Print
void Map::printMap() {
printf("cCol: %d, cRow: %d\n", cCol, cRow);
for (int i = 0; i < cRow; i++) {
printf("[");
for (int j = 0; j < cCol; j++) {
printf(" %d ", mapGrid[j][i]);
}
printf("]\n");
}
}
// Console Print
void Map::printCount(ColCount &c) {
printf("[");
for (int i = 0; i < ITEM_KIND; i++) {
printf(" %d ", c.count[i]);
}
printf("]\n");
}
// Helper function: returns true for eye / die.
bool roll(int die, int eye) {
return std::rand() % die < eye;
}
| remove unnecessary printf statements | remove unnecessary printf statements
| C++ | bsd-3-clause | hardhat/trumpjump,hardhat/trumpjump |
7afc92c7808d0ac804d4baff8921001c86efcd21 | delegate/src/test/Convolution3dTest.cpp | delegate/src/test/Convolution3dTest.cpp | //
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "ConvolutionTestHelper.hpp"
#include <armnn_delegate.hpp>
#include <flatbuffers/flatbuffers.h>
#include <tensorflow/lite/interpreter.h>
#include <tensorflow/lite/kernels/register.h>
#include <tensorflow/lite/model.h>
#include <tensorflow/lite/schema/schema_generated.h>
#include <doctest/doctest.h>
namespace armnnDelegate
{
// Conv3d is currently only supports Float32 inputs, filter, bias and outputs in TFLite.
// Conv3d is only correctly supported for external delegates from TF Lite v2.6, as there was a breaking bug in v2.5.
#if defined(ARMNN_POST_TFLITE_2_5)
// Create a vector from 0 to size divided to create smaller floating point values.
template <typename T>
std::vector<T> CreateFloatData(int32_t size, float divisor)
{
std::vector<float> data;
for (int32_t i = 0; i < size; ++i)
{
float value = static_cast<float>(i);
data.push_back(value/divisor);
}
return data;
}
void Conv3DWithBiasesSimpleWithPaddingFp32Test(std::vector<armnn::BackendId>& backends)
{
// Set input data
std::vector<int32_t> inputShape { 1, 2, 2, 2, 1 };
std::vector<int32_t> filterShape { 2, 2, 2, 1, 1 };
std::vector<int32_t> biasShape { 1 };
std::vector<int32_t> outputShape { 1, 2, 2, 2, 1 };
static std::vector<float> inputValues =
{
1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f
};
std::vector<float> filterValues =
{
2.f,1.f, 1.f,0.f, 0.f,1.f, 1.f,1.f
};
std::vector<float> biasValues = { 5.f };
std::vector<float> expectedOutputValues =
{
33.f, 21.f, 23.f, 13.f, 28.f, 25.f, 27.f, 21.f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 1, 1, 1 }, // strideX, strideY, strideZ
{ 1, 1, 1 }, // dilationX, dilationY, dilationZ
tflite::Padding_SAME,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
void Conv3DWithBiasesStridesFp32Test(std::vector<armnn::BackendId>& backends)
{
std::vector<int32_t> inputShape { 1, 3, 10, 10, 1 };
std::vector<int32_t> filterShape { 3, 5, 5, 1, 1 };
std::vector<int32_t> biasShape { 1 };
std::vector<int32_t> outputShape { 1, 1, 3, 3, 1 };
std::vector<float> inputValues = CreateFloatData<float>(300, 1.0f);
std::vector<float> filterValues =
{
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f
};
std::vector<float> biasValues = { 10.f };
std::vector<float> expectedOutputValues =
{
11660.f, 11810.f, 11960.f,
13160.f, 13310.f, 13460.f,
14660.f, 14810.f, 14960.f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 2, 2, 2 }, // strideX, strideY, strideZ
{ 1, 1, 1 }, // dilationX, dilationY, dilationZ
tflite::Padding_VALID,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
void Conv3DWithBiasesDilationFp32Test(std::vector<armnn::BackendId>& backends)
{
std::vector<int32_t> inputShape { 1, 5, 5, 5, 2 };
std::vector<int32_t> filterShape { 2, 2, 2, 2, 2 };
std::vector<int32_t> biasShape { 2 };
std::vector<int32_t> outputShape { 1, 2, 2, 2, 2 };
std::vector<float> inputValues = CreateFloatData<float>(250, 1.0f);
std::vector<float> filterValues =
{
-1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, 1.f, 1.f, 1.f, -1.f, -1.f,
1.f, 1.f, -1.f, 1.f, -1.f, 1.f, -1.f, 1.f, -1.f, -1.f, -1.f, 1.f, -1.f, 1.f, -1.f, 1.f,
};
std::vector<float> biasValues = { 0.f, 2.f };
// Since the dilation rate is 3 this will dilate the kernel to be 4x4,
// therefore the output will be 2x2
std::vector<float> expectedOutputValues =
{
-1124.f, 976.f,
-1148.f, 980.f,
-1244.f, 996.f,
-1268.f, 1000.f,
-1724.f, 1076.f,
-1748.f, 1080.f,
-1844.f, 1096.f,
-1868.f, 1100.f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 1, 1, 1 }, // strideX, strideY, strideZ
{ 3, 3, 3 }, // dilationX, dilationY, dilationZ
tflite::Padding_VALID,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
void Conv3DFp32SmallTest(std::vector<armnn::BackendId>& backends)
{
std::vector<int32_t> inputShape { 1, 3, 10, 10, 1 };
std::vector<int32_t> filterShape { 3, 3, 3, 1, 1 };
std::vector<int32_t> biasShape { 1 };
std::vector<int32_t> outputShape { 1, 1, 4, 4, 1 };
std::vector<float> inputValues = CreateFloatData<float>(300, 100.0f);
std::vector<float> filterValues =
{
0.125977f, 0.150391f, 0.101562f,
0.0585938f, 0.0864258f, 0.043457f,
0.034668f, 0.0322266f, 0.0385742f,
0.125977f, 0.150391f, -0.101562f,
-0.0585938f,-0.0864258f,-0.043457f,
-0.0104630f, 0.0154114f, 0.0013768f,
0.0344238f, 0.035644f, 0.0495605f,
0.0683594f, 0.099121f, -0.0461426f,
-0.0996094f,-0.126953f, -0.043457f,
};
std::vector<float> biasValues = { 0 };
std::vector<float> expectedOutputValues =
{
-0.08156067f, -0.06891209f, -0.05589598f, -0.04310101f,
0.04584253f, 0.05855697f, 0.07129729f, 0.08325434f,
0.17304349f, 0.18521416f, 0.19818866f, 0.21096253f,
0.29965734f, 0.312698f, 0.32547557f, 0.33818722f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 2, 2, 2 }, // strideX, strideY, strideZ
{ 1, 1, 1 }, // dilationX, dilationY, dilationZ
tflite::Padding_VALID,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
TEST_SUITE("Convolution3dTest_CpuRefTests")
{
TEST_CASE ("Conv3DWithBiasesSimpleWithPadding_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DWithBiasesSimpleWithPaddingFp32Test(backends);
}
TEST_CASE ("Conv3DWithBiasesStrides_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DWithBiasesStridesFp32Test(backends);
}
TEST_CASE ("Conv3DWithBiasesDilation_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DWithBiasesDilationFp32Test(backends);
}
TEST_CASE ("Conv3DFp32Small_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DFp32SmallTest(backends);
}
} //End of TEST_SUITE("Convolution3dTest_CpuRefTests")
#endif
} // namespace armnnDelegate | //
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "ConvolutionTestHelper.hpp"
#include <armnn_delegate.hpp>
#include <flatbuffers/flatbuffers.h>
#include <tensorflow/lite/interpreter.h>
#include <tensorflow/lite/kernels/register.h>
#include <tensorflow/lite/model.h>
#include <tensorflow/lite/schema/schema_generated.h>
#include <doctest/doctest.h>
namespace armnnDelegate
{
// Conv3d is currently only supports Float32 inputs, filter, bias and outputs in TFLite.
// Conv3d is only correctly supported for external delegates from TF Lite v2.6, as there was a breaking bug in v2.5.
#if defined(ARMNN_POST_TFLITE_2_5)
// Create a vector from 0 to size divided to create smaller floating point values.
template <typename T>
std::vector<T> CreateFloatData(int32_t size, float divisor)
{
std::vector<float> data;
for (int32_t i = 0; i < size; ++i)
{
float value = static_cast<float>(i);
data.push_back(value/divisor);
}
return data;
}
void Conv3DWithBiasesSimpleWithPaddingFp32Test(std::vector<armnn::BackendId>& backends)
{
// Set input data
std::vector<int32_t> inputShape { 1, 2, 2, 2, 1 };
std::vector<int32_t> filterShape { 2, 2, 2, 1, 1 };
std::vector<int32_t> biasShape { 1 };
std::vector<int32_t> outputShape { 1, 2, 2, 2, 1 };
static std::vector<float> inputValues =
{
1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f
};
std::vector<float> filterValues =
{
2.f,1.f, 1.f,0.f, 0.f,1.f, 1.f,1.f
};
std::vector<float> biasValues = { 5.f };
std::vector<float> expectedOutputValues =
{
33.f, 21.f, 23.f, 13.f, 28.f, 25.f, 27.f, 21.f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 1, 1, 1 }, // strideX, strideY, strideZ
{ 1, 1, 1 }, // dilationX, dilationY, dilationZ
tflite::Padding_SAME,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
void Conv3DWithBiasesStridesFp32Test(std::vector<armnn::BackendId>& backends)
{
std::vector<int32_t> inputShape { 1, 3, 10, 10, 1 };
std::vector<int32_t> filterShape { 3, 5, 5, 1, 1 };
std::vector<int32_t> biasShape { 1 };
std::vector<int32_t> outputShape { 1, 1, 3, 3, 1 };
std::vector<float> inputValues = CreateFloatData<float>(300, 1.0f);
std::vector<float> filterValues =
{
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
1.f, 1.f, 1.f, 1.f, 1.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
0.f, 0.f, 0.f, 0.f, 0.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f,
2.f, 2.f, 2.f, 2.f, 2.f
};
std::vector<float> biasValues = { 10.f };
std::vector<float> expectedOutputValues =
{
11660.f, 11810.f, 11960.f,
13160.f, 13310.f, 13460.f,
14660.f, 14810.f, 14960.f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 2, 2, 2 }, // strideX, strideY, strideZ
{ 1, 1, 1 }, // dilationX, dilationY, dilationZ
tflite::Padding_VALID,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
void Conv3DWithBiasesDilationFp32Test(std::vector<armnn::BackendId>& backends)
{
std::vector<int32_t> inputShape { 1, 5, 5, 5, 2 };
std::vector<int32_t> filterShape { 2, 2, 2, 2, 2 };
std::vector<int32_t> biasShape { 2 };
std::vector<int32_t> outputShape { 1, 2, 2, 2, 2 };
std::vector<float> inputValues = CreateFloatData<float>(250, 1.0f);
std::vector<float> filterValues =
{
-1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, -1.f, 1.f, 1.f, 1.f, -1.f, -1.f,
1.f, 1.f, -1.f, 1.f, -1.f, 1.f, -1.f, 1.f, -1.f, -1.f, -1.f, 1.f, -1.f, 1.f, -1.f, 1.f,
};
std::vector<float> biasValues = { 0.f, 2.f };
// Since the dilation rate is 3 this will dilate the kernel to be 4x4,
// therefore the output will be 2x2
std::vector<float> expectedOutputValues =
{
-1124.f, 976.f,
-1148.f, 980.f,
-1244.f, 996.f,
-1268.f, 1000.f,
-1724.f, 1076.f,
-1748.f, 1080.f,
-1844.f, 1096.f,
-1868.f, 1100.f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 1, 1, 1 }, // strideX, strideY, strideZ
{ 3, 3, 3 }, // dilationX, dilationY, dilationZ
tflite::Padding_VALID,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
void Conv3DFp32SmallTest(std::vector<armnn::BackendId>& backends)
{
std::vector<int32_t> inputShape { 1, 3, 10, 10, 1 };
std::vector<int32_t> filterShape { 3, 3, 3, 1, 1 };
std::vector<int32_t> biasShape { 1 };
std::vector<int32_t> outputShape { 1, 1, 4, 4, 1 };
std::vector<float> inputValues = CreateFloatData<float>(300, 100.0f);
std::vector<float> filterValues =
{
0.125977f, 0.150391f, 0.101562f,
0.0585938f, 0.0864258f, 0.043457f,
0.034668f, 0.0322266f, 0.0385742f,
0.125977f, 0.150391f, -0.101562f,
-0.0585938f,-0.0864258f,-0.043457f,
-0.0104630f, 0.0154114f, 0.0013768f,
0.0344238f, 0.035644f, 0.0495605f,
0.0683594f, 0.099121f, -0.0461426f,
-0.0996094f,-0.126953f, -0.043457f,
};
std::vector<float> biasValues = { 0 };
std::vector<float> expectedOutputValues =
{
-0.08156067f, -0.06891209f, -0.05589598f, -0.04310101f,
0.04584253f, 0.05855697f, 0.07129729f, 0.08325434f,
0.17304349f, 0.18521416f, 0.19818866f, 0.21096253f,
0.29965734f, 0.312698f, 0.32547557f, 0.33818722f
};
Convolution3dTest<float>(tflite::BuiltinOperator_CONV_3D,
::tflite::TensorType_FLOAT32,
{ 2, 2, 2 }, // strideX, strideY, strideZ
{ 1, 1, 1 }, // dilationX, dilationY, dilationZ
tflite::Padding_VALID,
tflite::ActivationFunctionType_NONE,
backends,
inputShape,
filterShape,
outputShape,
inputValues,
filterValues,
expectedOutputValues,
biasShape,
biasValues);
}
TEST_SUITE("Convolution3dTest_CpuRefTests")
{
TEST_CASE ("Conv3DWithBiasesSimpleWithPadding_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DWithBiasesSimpleWithPaddingFp32Test(backends);
}
TEST_CASE ("Conv3DWithBiasesStrides_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DWithBiasesStridesFp32Test(backends);
}
TEST_CASE ("Conv3DWithBiasesDilation_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DWithBiasesDilationFp32Test(backends);
}
TEST_CASE ("Conv3DFp32Small_Fp32_CpuRef_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuRef};
Conv3DFp32SmallTest(backends);
}
} //End of TEST_SUITE("Convolution3dTest_CpuRefTests")
TEST_SUITE("Convolution3dTest_CpuAccTests")
{
TEST_CASE ("Conv3DWithBiasesSimpleWithPadding_Fp32_CpuAcc_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuAcc};
Conv3DWithBiasesSimpleWithPaddingFp32Test(backends);
}
TEST_CASE ("Conv3DWithBiasesStrides_Fp32_CpuAcc_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuAcc};
Conv3DWithBiasesStridesFp32Test(backends);
}
TEST_CASE ("Conv3DFp32Small_Fp32_CpuAcc_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::CpuAcc};
Conv3DFp32SmallTest(backends);
}
} //End of TEST_SUITE("Convolution3dTest_CpuAccTests")
TEST_SUITE("Convolution3dTest_GpuAccTests")
{
TEST_CASE ("Conv3DWithBiasesSimpleWithPadding_Fp32_GpuAcc_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::GpuAcc};
Conv3DWithBiasesSimpleWithPaddingFp32Test(backends);
}
TEST_CASE ("Conv3DWithBiasesStrides_Fp32_GpuAcc_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::GpuAcc};
Conv3DWithBiasesStridesFp32Test(backends);
}
TEST_CASE ("Conv3DFp32Small_Fp32_GpuAcc_Test")
{
std::vector <armnn::BackendId> backends = {armnn::Compute::GpuAcc};
Conv3DFp32SmallTest(backends);
}
} //End of TEST_SUITE("Convolution3dTest_GpuAccTests")
#endif
} // namespace armnnDelegate | Add CpuAcc and GpuAcc TfLite Delegate tests for Conv3d | Add CpuAcc and GpuAcc TfLite Delegate tests for Conv3d
Signed-off-by: Matthew Sloyan <[email protected]>
Change-Id: I3e91796a69f02a8eff3018a1d17a496a66076db5
| C++ | mit | ARM-software/armnn,ARM-software/armnn,ARM-software/armnn |
7c76ed5ab20b8bbffc6c776b98cefd65663bb5f7 | heaptrack_interpret.cpp | heaptrack_interpret.cpp | /*
* Copyright 2014 Milian Wolff <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file heaptrack_interpret.cpp
*
* @brief Interpret raw heaptrack data and add Dwarf based debug information.
*/
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <tuple>
#include <algorithm>
#include <cxxabi.h>
#include <boost/algorithm/string/predicate.hpp>
#include "libbacktrace/backtrace.h"
using namespace std;
namespace {
string demangle(const char* function)
{
if (!function) {
return {};
} else if (function[0] != '_' || function[1] != 'Z') {
return {function};
}
string ret;
int status = 0;
char* demangled = abi::__cxa_demangle(function, 0, 0, &status);
if (demangled) {
ret = demangled;
free(demangled);
}
return ret;
}
struct AddressInformation
{
string function;
string file;
int line = 0;
};
struct Module
{
Module(string _fileName, bool isExe, uintptr_t addressStart, uintptr_t addressEnd)
: fileName(move(_fileName))
, addressStart(addressStart)
, addressEnd(addressEnd)
, isExe(isExe)
, backtraceState(nullptr)
{
if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) {
return;
}
backtraceState = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false,
[] (void *data, const char *msg, int errnum) {
const Module* module = reinterpret_cast<Module*>(data);
cerr << "Failed to create backtrace state for file " << module->fileName
<< ": " << msg << " (error code " << errnum << ")" << endl;
}, this);
if (backtraceState) {
backtrace_fileline_initialize(backtraceState, addressStart, isExe,
[] (void *data, const char *msg, int errnum) {
const Module* module = reinterpret_cast<Module*>(data);
cerr << "Failed to initialize backtrace fileline for "
<< (module->isExe ? "executable" : "library") << module->fileName
<< ": " << msg << " (error code " << errnum << ")" << endl;
}, this);
}
}
AddressInformation resolveAddress(uintptr_t address) const
{
AddressInformation info;
if (!backtraceState) {
return info;
}
backtrace_pcinfo(backtraceState, address,
[] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int {
auto info = reinterpret_cast<AddressInformation*>(data);
info->function = demangle(function);
info->file = file ? file : "";
info->line = line;
return 0;
}, &emptyErrorCallback, &info);
if (info.function.empty()) {
backtrace_syminfo(backtraceState, address,
[] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) {
if (symname) {
reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);
}
}, &errorCallback, &info);
}
return info;
}
static void errorCallback(void */*data*/, const char *msg, int errnum)
{
cerr << "Module backtrace error (code " << errnum << "): " << msg << endl;
}
static void emptyErrorCallback(void */*data*/, const char */*msg*/, int /*errnum*/)
{
}
bool operator<(const Module& module) const
{
return make_tuple(addressStart, addressEnd, fileName)
< make_tuple(module.addressStart, module.addressEnd, module.fileName);
}
bool operator!=(const Module& module) const
{
return make_tuple(addressStart, addressEnd, fileName)
!= make_tuple(module.addressStart, module.addressEnd, module.fileName);
}
backtrace_state* backtraceState = nullptr;
string fileName;
uintptr_t addressStart;
uintptr_t addressEnd;
bool isExe;
};
struct Allocation
{
// backtrace entry point
size_t ipIndex;
// number of allocations
size_t allocations;
// amount of bytes leaked
size_t leaked;
};
/**
* Information for a single call to an allocation function
*/
struct AllocationInfo
{
size_t ipIndex;
size_t size;
};
struct ResolvedIP
{
size_t moduleIndex = 0;
size_t fileIndex = 0;
size_t functionIndex = 0;
int line = 0;
};
struct AccumulatedTraceData
{
AccumulatedTraceData()
{
m_modules.reserve(64);
m_internedData.reserve(4096);
m_encounteredIps.reserve(32768);
}
~AccumulatedTraceData()
{
cout << dec;
cout << "# strings: " << m_internedData.size() << '\n';
cout << "# ips: " << m_encounteredIps.size() << '\n';
}
ResolvedIP resolve(const uintptr_t ip)
{
if (m_modulesDirty) {
// sort by addresses, required for binary search below
sort(m_modules.begin(), m_modules.end());
m_modulesDirty = false;
}
ResolvedIP data;
// find module for this instruction pointer
auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,
[] (const Module& module, const uintptr_t ip) -> bool {
return module.addressEnd < ip;
});
if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {
data.moduleIndex = intern(module->fileName);
const auto info = module->resolveAddress(ip);
data.fileIndex = intern(info.file);
data.functionIndex = intern(info.function);
data.line = info.line;
}
return data;
}
size_t intern(const string& str)
{
if (str.empty()) {
return 0;
}
auto it = m_internedData.find(str);
if (it != m_internedData.end()) {
return it->second;
}
const size_t id = m_internedData.size() + 1;
m_internedData.insert(it, make_pair(str, id));
cout << "s " << str << '\n';
return id;
}
void addModule(Module&& module)
{
m_modules.push_back(move(module));
m_modulesDirty = true;
}
size_t addIp(const uintptr_t instructionPointer)
{
if (!instructionPointer) {
return 0;
}
auto it = m_encounteredIps.find(instructionPointer);
if (it != m_encounteredIps.end()) {
return it->second;
}
const size_t ipId = m_encounteredIps.size() + 1;
m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));
const auto ip = resolve(instructionPointer);
cout << "i " << instructionPointer << ' ' << ip.moduleIndex;
if (ip.functionIndex || ip.fileIndex) {
cout << ' ' << ip.functionIndex;
if (ip.fileIndex) {
cout << ' ' << ip.fileIndex << ' ' << ip.line;
}
}
cout << '\n';
return ipId;
}
private:
vector<Module> m_modules;
bool m_modulesDirty = false;
unordered_map<string, size_t> m_internedData;
unordered_map<uintptr_t, size_t> m_encounteredIps;
};
}
int main(int /*argc*/, char** /*argv*/)
{
// optimize: we only have a single thread
ios_base::sync_with_stdio(false);
AccumulatedTraceData data;
string line;
line.reserve(1024);
stringstream lineIn(ios_base::in);
lineIn << hex;
cout << hex;
while (cin.good()) {
getline(cin, line);
if (line.empty()) {
continue;
}
const char mode = line[0];
lineIn.str(line);
lineIn.clear();
// skip mode and leading whitespace
lineIn.seekg(2);
if (mode == 'm') {
string fileName;
lineIn >> fileName;
bool isExe = false;
lineIn >> isExe;
uintptr_t addressStart = 0;
lineIn >> addressStart;
uintptr_t addressEnd = 0;
lineIn >> addressEnd;
if (lineIn.bad()) {
cerr << "failed to parse line: " << line << endl;
return 1;
}
data.addModule({fileName, isExe, addressStart, addressEnd});
} else if (mode == 't') {
uintptr_t instructionPointer = 0;
size_t parentIndex = 0;
lineIn >> instructionPointer;
lineIn >> parentIndex;
if (lineIn.bad()) {
cerr << "failed to parse line: " << line << endl;
return 1;
}
// ensure ip is encountered
const auto ipId = data.addIp(instructionPointer);
// trace point, map current output index to parent index
cout << "t " << ipId << ' ' << parentIndex << '\n';
} else {
cout << line << '\n';
}
}
return 0;
}
| /*
* Copyright 2014 Milian Wolff <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file heaptrack_interpret.cpp
*
* @brief Interpret raw heaptrack data and add Dwarf based debug information.
*/
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <tuple>
#include <algorithm>
#include <cxxabi.h>
#include <boost/algorithm/string/predicate.hpp>
#include "libbacktrace/backtrace.h"
using namespace std;
namespace {
string demangle(const char* function)
{
if (!function) {
return {};
} else if (function[0] != '_' || function[1] != 'Z') {
return {function};
}
string ret;
int status = 0;
char* demangled = abi::__cxa_demangle(function, 0, 0, &status);
if (demangled) {
ret = demangled;
free(demangled);
}
return ret;
}
struct AddressInformation
{
string function;
string file;
int line = 0;
};
struct Module
{
Module(string _fileName, bool isExe, uintptr_t addressStart, uintptr_t addressEnd)
: fileName(move(_fileName))
, addressStart(addressStart)
, addressEnd(addressEnd)
, isExe(isExe)
, backtraceState(nullptr)
{
if (boost::algorithm::starts_with(fileName, "linux-vdso.so")) {
return;
}
backtraceState = backtrace_create_state(fileName.c_str(), /* we are single threaded, so: not thread safe */ false,
[] (void *data, const char *msg, int errnum) {
const Module* module = reinterpret_cast<Module*>(data);
cerr << "Failed to create backtrace state for file " << module->fileName
<< ": " << msg << " (error code " << errnum << ")" << endl;
}, this);
if (backtraceState) {
backtrace_fileline_initialize(backtraceState, addressStart, isExe,
[] (void *data, const char *msg, int errnum) {
const Module* module = reinterpret_cast<Module*>(data);
cerr << "Failed to initialize backtrace fileline for "
<< (module->isExe ? "executable " : "library ") << module->fileName
<< ": " << msg << " (error code " << errnum << ")" << endl;
}, this);
}
}
AddressInformation resolveAddress(uintptr_t address) const
{
AddressInformation info;
if (!backtraceState) {
return info;
}
backtrace_pcinfo(backtraceState, address,
[] (void *data, uintptr_t /*addr*/, const char *file, int line, const char *function) -> int {
auto info = reinterpret_cast<AddressInformation*>(data);
info->function = demangle(function);
info->file = file ? file : "";
info->line = line;
return 0;
}, &emptyErrorCallback, &info);
if (info.function.empty()) {
backtrace_syminfo(backtraceState, address,
[] (void *data, uintptr_t /*pc*/, const char *symname, uintptr_t /*symval*/, uintptr_t /*symsize*/) {
if (symname) {
reinterpret_cast<AddressInformation*>(data)->function = demangle(symname);
}
}, &errorCallback, &info);
}
return info;
}
static void errorCallback(void */*data*/, const char *msg, int errnum)
{
cerr << "Module backtrace error (code " << errnum << "): " << msg << endl;
}
static void emptyErrorCallback(void */*data*/, const char */*msg*/, int /*errnum*/)
{
}
bool operator<(const Module& module) const
{
return make_tuple(addressStart, addressEnd, fileName)
< make_tuple(module.addressStart, module.addressEnd, module.fileName);
}
bool operator!=(const Module& module) const
{
return make_tuple(addressStart, addressEnd, fileName)
!= make_tuple(module.addressStart, module.addressEnd, module.fileName);
}
backtrace_state* backtraceState = nullptr;
string fileName;
uintptr_t addressStart;
uintptr_t addressEnd;
bool isExe;
};
struct Allocation
{
// backtrace entry point
size_t ipIndex;
// number of allocations
size_t allocations;
// amount of bytes leaked
size_t leaked;
};
/**
* Information for a single call to an allocation function
*/
struct AllocationInfo
{
size_t ipIndex;
size_t size;
};
struct ResolvedIP
{
size_t moduleIndex = 0;
size_t fileIndex = 0;
size_t functionIndex = 0;
int line = 0;
};
struct AccumulatedTraceData
{
AccumulatedTraceData()
{
m_modules.reserve(64);
m_internedData.reserve(4096);
m_encounteredIps.reserve(32768);
}
~AccumulatedTraceData()
{
cout << dec;
cout << "# strings: " << m_internedData.size() << '\n';
cout << "# ips: " << m_encounteredIps.size() << '\n';
}
ResolvedIP resolve(const uintptr_t ip)
{
if (m_modulesDirty) {
// sort by addresses, required for binary search below
sort(m_modules.begin(), m_modules.end());
m_modulesDirty = false;
}
ResolvedIP data;
// find module for this instruction pointer
auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,
[] (const Module& module, const uintptr_t ip) -> bool {
return module.addressEnd < ip;
});
if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {
data.moduleIndex = intern(module->fileName);
const auto info = module->resolveAddress(ip);
data.fileIndex = intern(info.file);
data.functionIndex = intern(info.function);
data.line = info.line;
}
return data;
}
size_t intern(const string& str)
{
if (str.empty()) {
return 0;
}
auto it = m_internedData.find(str);
if (it != m_internedData.end()) {
return it->second;
}
const size_t id = m_internedData.size() + 1;
m_internedData.insert(it, make_pair(str, id));
cout << "s " << str << '\n';
return id;
}
void addModule(Module&& module)
{
m_modules.push_back(move(module));
m_modulesDirty = true;
}
size_t addIp(const uintptr_t instructionPointer)
{
if (!instructionPointer) {
return 0;
}
auto it = m_encounteredIps.find(instructionPointer);
if (it != m_encounteredIps.end()) {
return it->second;
}
const size_t ipId = m_encounteredIps.size() + 1;
m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));
const auto ip = resolve(instructionPointer);
cout << "i " << instructionPointer << ' ' << ip.moduleIndex;
if (ip.functionIndex || ip.fileIndex) {
cout << ' ' << ip.functionIndex;
if (ip.fileIndex) {
cout << ' ' << ip.fileIndex << ' ' << ip.line;
}
}
cout << '\n';
return ipId;
}
private:
vector<Module> m_modules;
bool m_modulesDirty = false;
unordered_map<string, size_t> m_internedData;
unordered_map<uintptr_t, size_t> m_encounteredIps;
};
}
int main(int /*argc*/, char** /*argv*/)
{
// optimize: we only have a single thread
ios_base::sync_with_stdio(false);
AccumulatedTraceData data;
string line;
line.reserve(1024);
stringstream lineIn(ios_base::in);
lineIn << hex;
cout << hex;
while (cin.good()) {
getline(cin, line);
if (line.empty()) {
continue;
}
const char mode = line[0];
lineIn.str(line);
lineIn.clear();
// skip mode and leading whitespace
lineIn.seekg(2);
if (mode == 'm') {
string fileName;
lineIn >> fileName;
bool isExe = false;
lineIn >> isExe;
uintptr_t addressStart = 0;
lineIn >> addressStart;
uintptr_t addressEnd = 0;
lineIn >> addressEnd;
if (lineIn.bad()) {
cerr << "failed to parse line: " << line << endl;
return 1;
}
data.addModule({fileName, isExe, addressStart, addressEnd});
} else if (mode == 't') {
uintptr_t instructionPointer = 0;
size_t parentIndex = 0;
lineIn >> instructionPointer;
lineIn >> parentIndex;
if (lineIn.bad()) {
cerr << "failed to parse line: " << line << endl;
return 1;
}
// ensure ip is encountered
const auto ipId = data.addIp(instructionPointer);
// trace point, map current output index to parent index
cout << "t " << ipId << ' ' << parentIndex << '\n';
} else {
cout << line << '\n';
}
}
return 0;
}
| Add whitespace before lib name. | Add whitespace before lib name.
| C++ | lgpl-2.1 | muojp/heaptrack,muojp/heaptrack,muojp/heaptrack,stormspirit/heaptrack,stormspirit/heaptrack,stormspirit/heaptrack,muojp/heaptrack,muojp/heaptrack |
3a1180c19c84703bcbe240eb4fff1e88ddd6dd64 | chrome/browser/gtk/browser_toolbar_view_gtk.cc | chrome/browser/gtk/browser_toolbar_view_gtk.cc | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/browser_toolbar_view_gtk.h"
#include "base/logging.h"
#include "base/base_paths_linux.h"
#include "base/path_service.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/back_forward_menu_model_gtk.h"
#include "chrome/browser/gtk/standard_menus.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
const int BrowserToolbarGtk::kToolbarHeight = 38;
// For the back/forward dropdown menus, the time in milliseconds between
// when the user clicks and the popup menu appears.
static const int kMenuTimerDelay = 500;
BrowserToolbarGtk::BrowserToolbarGtk(Browser* browser)
: toolbar_(NULL),
entry_(NULL),
model_(browser->toolbar_model()),
browser_(browser),
profile_(NULL),
show_menu_factory_(this) {
browser_->command_updater()->AddCommandObserver(IDC_BACK, this);
browser_->command_updater()->AddCommandObserver(IDC_FORWARD, this);
browser_->command_updater()->AddCommandObserver(IDC_RELOAD, this);
browser_->command_updater()->AddCommandObserver(IDC_HOME, this);
browser_->command_updater()->AddCommandObserver(IDC_STAR, this);
back_menu_model_.reset(new BackForwardMenuModelGtk(
browser, BackForwardMenuModel::BACKWARD_MENU_DELEGATE));
forward_menu_model_.reset(new BackForwardMenuModelGtk(
browser, BackForwardMenuModel::FORWARD_MENU_DELEGATE));
}
BrowserToolbarGtk::~BrowserToolbarGtk() {
}
void BrowserToolbarGtk::Init(Profile* profile) {
show_home_button_.Init(prefs::kShowHomeButton, profile->GetPrefs(), this);
toolbar_ = gtk_hbox_new(FALSE, 0);
gtk_container_set_border_width(GTK_CONTAINER(toolbar_), 4);
// TODO(evanm): this setting of the x-size to 0 makes it so the window
// can be resized arbitrarily small. We should figure out what we want
// with respect to resizing before engineering around it, though.
gtk_widget_set_size_request(toolbar_, 0, kToolbarHeight);
toolbar_tooltips_ = gtk_tooltips_new();
back_.reset(BuildBackForwardButton(IDR_BACK, IDR_BACK_P, IDR_BACK_H,
IDR_BACK_D,
l10n_util::GetString(IDS_TOOLTIP_BACK)));
forward_.reset(BuildBackForwardButton(IDR_FORWARD, IDR_FORWARD_P,
IDR_FORWARD_H, IDR_FORWARD_D,
l10n_util::GetString(IDS_TOOLTIP_FORWARD)));
gtk_box_pack_start(GTK_BOX(toolbar_), gtk_label_new(" "), FALSE, FALSE, 0);
reload_.reset(BuildToolbarButton(IDR_RELOAD, IDR_RELOAD_P, IDR_RELOAD_H, 0,
l10n_util::GetString(IDS_TOOLTIP_RELOAD)));
// TODO(port): we need to dynamically react to changes in show_home_button_
// and hide/show home appropriately. But we don't have a UI for it yet.
if (*show_home_button_)
home_.reset(MakeHomeButton());
gtk_box_pack_start(GTK_BOX(toolbar_), gtk_label_new(" "), FALSE, FALSE, 0);
star_.reset(BuildToolbarButton(IDR_STAR, IDR_STAR_P, IDR_STAR_H, IDR_STAR_D,
l10n_util::GetString(IDS_TOOLTIP_STAR)));
entry_ = gtk_entry_new();
gtk_widget_set_size_request(entry_, 0, 27);
g_signal_connect(G_OBJECT(entry_), "activate",
G_CALLBACK(OnEntryActivate), this);
gtk_box_pack_start(GTK_BOX(toolbar_), entry_, TRUE, TRUE, 0);
go_.reset(BuildToolbarButton(IDR_GO, IDR_GO_P, IDR_GO_H, 0, L""));
gtk_box_pack_start(GTK_BOX(toolbar_), gtk_label_new(" "), FALSE, FALSE, 0);
page_menu_button_.reset(BuildToolbarMenuButton(IDR_MENU_PAGE,
l10n_util::GetString(IDS_PAGEMENU_TOOLTIP)));
app_menu_button_.reset(BuildToolbarMenuButton(IDR_MENU_CHROME,
l10n_util::GetStringF(IDS_APPMENU_TOOLTIP,
l10n_util::GetString(IDS_PRODUCT_NAME))));
SetProfile(profile);
}
void BrowserToolbarGtk::AddToolbarToBox(GtkWidget* box) {
gtk_box_pack_start(GTK_BOX(box), toolbar_, FALSE, FALSE, 0);
}
void BrowserToolbarGtk::EnabledStateChangedForCommand(int id, bool enabled) {
GtkWidget* widget = NULL;
switch (id) {
case IDC_BACK:
widget = back_->widget();
break;
case IDC_FORWARD:
widget = forward_->widget();
break;
case IDC_RELOAD:
widget = reload_->widget();
break;
case IDC_HOME:
if (home_.get())
widget = home_->widget();
break;
case IDC_STAR:
widget = star_->widget();
break;
}
if (widget)
gtk_widget_set_sensitive(widget, enabled);
}
bool BrowserToolbarGtk::IsCommandEnabled(int command_id) const {
return browser_->command_updater()->IsCommandEnabled(command_id);
}
bool BrowserToolbarGtk::IsItemChecked(int id) const {
if (!profile_)
return false;
if (id == IDC_SHOW_BOOKMARK_BAR)
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
// TODO(port): Fix this when we get some items that want checking!
return false;
}
void BrowserToolbarGtk::ExecuteCommand(int id) {
browser_->ExecuteCommand(id);
}
void BrowserToolbarGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED) {
std::wstring* pref_name = Details<std::wstring>(details).ptr();
if (*pref_name == prefs::kShowHomeButton) {
// TODO(port): add/remove home button.
NOTIMPLEMENTED();
}
}
}
void BrowserToolbarGtk::SetProfile(Profile* profile) {
if (profile == profile_)
return;
profile_ = profile;
// TODO(erg): location_bar_ is a normal gtk text box right now. Change this
// when we get omnibox support.
// location_bar_->SetProfile(profile);
}
void BrowserToolbarGtk::UpdateTabContents(TabContents* contents,
bool should_restore_state) {
// Extract the UTF-8 representation of the URL.
gtk_entry_set_text(GTK_ENTRY(entry_),
contents->GetURL().possibly_invalid_spec().c_str());
}
CustomDrawButton* BrowserToolbarGtk::BuildToolbarButton(
int normal_id, int active_id, int highlight_id, int depressed_id,
const std::wstring& localized_tooltip) {
CustomDrawButton* button = new CustomDrawButton(normal_id, active_id,
highlight_id, depressed_id);
gtk_tooltips_set_tip(GTK_TOOLTIPS(toolbar_tooltips_),
GTK_WIDGET(button->widget()),
WideToUTF8(localized_tooltip).c_str(),
WideToUTF8(localized_tooltip).c_str());
g_signal_connect(G_OBJECT(button->widget()), "clicked",
G_CALLBACK(OnButtonClick), this);
gtk_box_pack_start(GTK_BOX(toolbar_), button->widget(), FALSE, FALSE, 0);
return button;
}
CustomContainerButton* BrowserToolbarGtk::BuildToolbarMenuButton(
int icon_id,
const std::wstring& localized_tooltip) {
CustomContainerButton* button = new CustomContainerButton;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
gtk_container_set_border_width(GTK_CONTAINER(button->widget()), 2);
gtk_container_add(GTK_CONTAINER(button->widget()),
gtk_image_new_from_pixbuf(rb.LoadPixbuf(icon_id)));
gtk_tooltips_set_tip(GTK_TOOLTIPS(toolbar_tooltips_),
GTK_WIDGET(button->widget()),
WideToUTF8(localized_tooltip).c_str(),
WideToUTF8(localized_tooltip).c_str());
g_signal_connect(G_OBJECT(button->widget()), "button-press-event",
G_CALLBACK(OnMenuButtonPressEvent), this);
gtk_box_pack_start(GTK_BOX(toolbar_), button->widget(), FALSE, FALSE, 0);
return button;
}
// static
void BrowserToolbarGtk::OnEntryActivate(GtkEntry *entry,
BrowserToolbarGtk* toolbar) {
GURL dest(URLFixerUpper::FixupURL(std::string(gtk_entry_get_text(entry)),
std::string()));
toolbar->browser_->GetSelectedTabContents()->
OpenURL(dest, GURL(), CURRENT_TAB, PageTransition::TYPED);
}
/* static */
void BrowserToolbarGtk::OnButtonClick(GtkWidget* button,
BrowserToolbarGtk* toolbar) {
int tag = -1;
if (button == toolbar->back_->widget())
tag = IDC_BACK;
else if (button == toolbar->forward_->widget())
tag = IDC_FORWARD;
else if (button == toolbar->reload_->widget())
tag = IDC_RELOAD;
else if (toolbar->home_.get() && button == toolbar->home_->widget())
tag = IDC_HOME;
else if (button == toolbar->star_->widget())
tag = IDC_STAR;
if (tag == IDC_BACK || tag == IDC_FORWARD)
toolbar->show_menu_factory_.RevokeAll();
DCHECK(tag != -1) << "Impossible button click callback";
toolbar->browser_->ExecuteCommand(tag);
}
// static
gboolean BrowserToolbarGtk::OnMenuButtonPressEvent(GtkWidget* button,
GdkEvent* event,
BrowserToolbarGtk* toolbar) {
// TODO(port): this never puts the button into the "active" state,
// which means we never display the button-pressed-down graphics. I
// suspect a better way to do it is just to use a real GtkMenuShell
// with our custom drawing.
if (event->type == GDK_BUTTON_PRESS) {
GdkEventButton* event_button = reinterpret_cast<GdkEventButton*>(event);
if (event_button->button == 1) {
// We have a button press we should respond to.
if (button == toolbar->page_menu_button_->widget()) {
toolbar->RunPageMenu(event);
return TRUE;
} else if (button == toolbar->app_menu_button_->widget()) {
toolbar->RunAppMenu(event);
return TRUE;
}
}
}
return FALSE;
}
CustomDrawButton* BrowserToolbarGtk::BuildBackForwardButton(
int normal_id,
int active_id,
int highlight_id,
int depressed_id,
const std::wstring& localized_tooltip) {
CustomDrawButton* button = new CustomDrawButton(normal_id, active_id,
highlight_id, depressed_id);
// TODO(erg): Mismatch between wstring and string.
// gtk_tooltips_set_tip(GTK_TOOLTIPS(toolbar_tooltips_),
// GTK_WIDGET(back_),
// localized_tooltip, localized_tooltip);
g_signal_connect(G_OBJECT(button->widget()), "button-press-event",
G_CALLBACK(OnBackForwardPressEvent), this);
g_signal_connect(G_OBJECT(button->widget()), "clicked",
G_CALLBACK(OnButtonClick), this);
gtk_box_pack_start(GTK_BOX(toolbar_), button->widget(), FALSE, FALSE, 0);
// Popup the menu as left-aligned relative to this widget rather than the
// default of right aligned.
g_object_set_data(G_OBJECT(button->widget()), "left-align-popup",
reinterpret_cast<void*>(true));
return button;
}
// static
gboolean BrowserToolbarGtk::OnBackForwardPressEvent(GtkWidget* widget,
GdkEventButton* event,
BrowserToolbarGtk* toolbar) {
// TODO(port): only allow left clicks to open the menu.
MessageLoop::current()->PostDelayedTask(FROM_HERE,
toolbar->show_menu_factory_.NewRunnableMethod(
&BrowserToolbarGtk::ShowBackForwardMenu,
widget, event->button),
kMenuTimerDelay);
return FALSE;
}
void BrowserToolbarGtk::ShowBackForwardMenu(GtkWidget* widget,
gint button_type) {
if (widget == back_->widget()) {
back_forward_menu_.reset(new MenuGtk(back_menu_model_.get()));
} else {
back_forward_menu_.reset(new MenuGtk(forward_menu_model_.get()));
}
back_forward_menu_->Popup(widget, button_type, gtk_get_current_event_time());
}
void BrowserToolbarGtk::RunPageMenu(GdkEvent* button_press_event) {
if (page_menu_ == NULL) {
page_menu_.reset(new MenuGtk(this, GetStandardPageMenu()));
}
page_menu_->Popup(page_menu_button_->widget(), button_press_event);
}
void BrowserToolbarGtk::RunAppMenu(GdkEvent* button_press_event) {
if (app_menu_ == NULL) {
app_menu_.reset(new MenuGtk(this, GetStandardAppMenu()));
}
app_menu_->Popup(app_menu_button_->widget(), button_press_event);
}
CustomDrawButton* BrowserToolbarGtk::MakeHomeButton() {
return BuildToolbarButton(IDR_HOME, IDR_HOME_P, IDR_HOME_H, 0,
l10n_util::GetString(IDS_TOOLTIP_HOME));
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/browser_toolbar_view_gtk.h"
#include "base/logging.h"
#include "base/base_paths_linux.h"
#include "base/path_service.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/custom_button.h"
#include "chrome/browser/gtk/back_forward_menu_model_gtk.h"
#include "chrome/browser/gtk/standard_menus.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/resource_bundle.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
const int BrowserToolbarGtk::kToolbarHeight = 38;
// For the back/forward dropdown menus, the time in milliseconds between
// when the user clicks and the popup menu appears.
static const int kMenuTimerDelay = 500;
BrowserToolbarGtk::BrowserToolbarGtk(Browser* browser)
: toolbar_(NULL),
entry_(NULL),
model_(browser->toolbar_model()),
browser_(browser),
profile_(NULL),
show_menu_factory_(this) {
browser_->command_updater()->AddCommandObserver(IDC_BACK, this);
browser_->command_updater()->AddCommandObserver(IDC_FORWARD, this);
browser_->command_updater()->AddCommandObserver(IDC_RELOAD, this);
browser_->command_updater()->AddCommandObserver(IDC_HOME, this);
browser_->command_updater()->AddCommandObserver(IDC_STAR, this);
back_menu_model_.reset(new BackForwardMenuModelGtk(
browser, BackForwardMenuModel::BACKWARD_MENU_DELEGATE));
forward_menu_model_.reset(new BackForwardMenuModelGtk(
browser, BackForwardMenuModel::FORWARD_MENU_DELEGATE));
}
BrowserToolbarGtk::~BrowserToolbarGtk() {
}
void BrowserToolbarGtk::Init(Profile* profile) {
show_home_button_.Init(prefs::kShowHomeButton, profile->GetPrefs(), this);
toolbar_ = gtk_hbox_new(FALSE, 0);
gtk_container_set_border_width(GTK_CONTAINER(toolbar_), 4);
// TODO(evanm): this setting of the x-size to 0 makes it so the window
// can be resized arbitrarily small. We should figure out what we want
// with respect to resizing before engineering around it, though.
gtk_widget_set_size_request(toolbar_, 0, kToolbarHeight);
toolbar_tooltips_ = gtk_tooltips_new();
back_.reset(BuildBackForwardButton(IDR_BACK, IDR_BACK_P, IDR_BACK_H,
IDR_BACK_D,
l10n_util::GetString(IDS_TOOLTIP_BACK)));
forward_.reset(BuildBackForwardButton(IDR_FORWARD, IDR_FORWARD_P,
IDR_FORWARD_H, IDR_FORWARD_D,
l10n_util::GetString(IDS_TOOLTIP_FORWARD)));
gtk_box_pack_start(GTK_BOX(toolbar_), gtk_label_new(" "), FALSE, FALSE, 0);
reload_.reset(BuildToolbarButton(IDR_RELOAD, IDR_RELOAD_P, IDR_RELOAD_H, 0,
l10n_util::GetString(IDS_TOOLTIP_RELOAD)));
// TODO(port): we need to dynamically react to changes in show_home_button_
// and hide/show home appropriately. But we don't have a UI for it yet.
if (*show_home_button_)
home_.reset(MakeHomeButton());
gtk_box_pack_start(GTK_BOX(toolbar_), gtk_label_new(" "), FALSE, FALSE, 0);
star_.reset(BuildToolbarButton(IDR_STAR, IDR_STAR_P, IDR_STAR_H, IDR_STAR_D,
l10n_util::GetString(IDS_TOOLTIP_STAR)));
entry_ = gtk_entry_new();
gtk_widget_set_size_request(entry_, 0, 27);
g_signal_connect(G_OBJECT(entry_), "activate",
G_CALLBACK(OnEntryActivate), this);
gtk_box_pack_start(GTK_BOX(toolbar_), entry_, TRUE, TRUE, 0);
go_.reset(BuildToolbarButton(IDR_GO, IDR_GO_P, IDR_GO_H, 0, L""));
gtk_box_pack_start(GTK_BOX(toolbar_), gtk_label_new(" "), FALSE, FALSE, 0);
page_menu_button_.reset(BuildToolbarMenuButton(IDR_MENU_PAGE,
l10n_util::GetString(IDS_PAGEMENU_TOOLTIP)));
app_menu_button_.reset(BuildToolbarMenuButton(IDR_MENU_CHROME,
l10n_util::GetStringF(IDS_APPMENU_TOOLTIP,
l10n_util::GetString(IDS_PRODUCT_NAME))));
SetProfile(profile);
}
void BrowserToolbarGtk::AddToolbarToBox(GtkWidget* box) {
gtk_box_pack_start(GTK_BOX(box), toolbar_, FALSE, FALSE, 0);
}
void BrowserToolbarGtk::EnabledStateChangedForCommand(int id, bool enabled) {
GtkWidget* widget = NULL;
switch (id) {
case IDC_BACK:
widget = back_->widget();
break;
case IDC_FORWARD:
widget = forward_->widget();
break;
case IDC_RELOAD:
widget = reload_->widget();
break;
case IDC_GO:
widget = go_->widget();
break;
case IDC_HOME:
if (home_.get())
widget = home_->widget();
break;
case IDC_STAR:
widget = star_->widget();
break;
}
if (widget)
gtk_widget_set_sensitive(widget, enabled);
}
bool BrowserToolbarGtk::IsCommandEnabled(int command_id) const {
return browser_->command_updater()->IsCommandEnabled(command_id);
}
bool BrowserToolbarGtk::IsItemChecked(int id) const {
if (!profile_)
return false;
if (id == IDC_SHOW_BOOKMARK_BAR)
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
// TODO(port): Fix this when we get some items that want checking!
return false;
}
void BrowserToolbarGtk::ExecuteCommand(int id) {
browser_->ExecuteCommand(id);
}
void BrowserToolbarGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::PREF_CHANGED) {
std::wstring* pref_name = Details<std::wstring>(details).ptr();
if (*pref_name == prefs::kShowHomeButton) {
// TODO(port): add/remove home button.
NOTIMPLEMENTED();
}
}
}
void BrowserToolbarGtk::SetProfile(Profile* profile) {
if (profile == profile_)
return;
profile_ = profile;
// TODO(erg): location_bar_ is a normal gtk text box right now. Change this
// when we get omnibox support.
// location_bar_->SetProfile(profile);
}
void BrowserToolbarGtk::UpdateTabContents(TabContents* contents,
bool should_restore_state) {
// Extract the UTF-8 representation of the URL.
gtk_entry_set_text(GTK_ENTRY(entry_),
contents->GetURL().possibly_invalid_spec().c_str());
}
CustomDrawButton* BrowserToolbarGtk::BuildToolbarButton(
int normal_id, int active_id, int highlight_id, int depressed_id,
const std::wstring& localized_tooltip) {
CustomDrawButton* button = new CustomDrawButton(normal_id, active_id,
highlight_id, depressed_id);
gtk_tooltips_set_tip(GTK_TOOLTIPS(toolbar_tooltips_),
GTK_WIDGET(button->widget()),
WideToUTF8(localized_tooltip).c_str(),
WideToUTF8(localized_tooltip).c_str());
g_signal_connect(G_OBJECT(button->widget()), "clicked",
G_CALLBACK(OnButtonClick), this);
gtk_box_pack_start(GTK_BOX(toolbar_), button->widget(), FALSE, FALSE, 0);
return button;
}
CustomContainerButton* BrowserToolbarGtk::BuildToolbarMenuButton(
int icon_id,
const std::wstring& localized_tooltip) {
CustomContainerButton* button = new CustomContainerButton;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
gtk_container_set_border_width(GTK_CONTAINER(button->widget()), 2);
gtk_container_add(GTK_CONTAINER(button->widget()),
gtk_image_new_from_pixbuf(rb.LoadPixbuf(icon_id)));
gtk_tooltips_set_tip(GTK_TOOLTIPS(toolbar_tooltips_),
GTK_WIDGET(button->widget()),
WideToUTF8(localized_tooltip).c_str(),
WideToUTF8(localized_tooltip).c_str());
g_signal_connect(G_OBJECT(button->widget()), "button-press-event",
G_CALLBACK(OnMenuButtonPressEvent), this);
gtk_box_pack_start(GTK_BOX(toolbar_), button->widget(), FALSE, FALSE, 0);
return button;
}
// static
void BrowserToolbarGtk::OnEntryActivate(GtkEntry *entry,
BrowserToolbarGtk* toolbar) {
GURL dest(URLFixerUpper::FixupURL(std::string(gtk_entry_get_text(entry)),
std::string()));
toolbar->browser_->GetSelectedTabContents()->
OpenURL(dest, GURL(), CURRENT_TAB, PageTransition::TYPED);
}
/* static */
void BrowserToolbarGtk::OnButtonClick(GtkWidget* button,
BrowserToolbarGtk* toolbar) {
int tag = -1;
if (button == toolbar->back_->widget())
tag = IDC_BACK;
else if (button == toolbar->forward_->widget())
tag = IDC_FORWARD;
else if (button == toolbar->reload_->widget())
tag = IDC_RELOAD;
else if (button == toolbar->go_->widget())
tag = IDC_GO;
else if (toolbar->home_.get() && button == toolbar->home_->widget())
tag = IDC_HOME;
else if (button == toolbar->star_->widget())
tag = IDC_STAR;
if (tag == IDC_BACK || tag == IDC_FORWARD)
toolbar->show_menu_factory_.RevokeAll();
DCHECK(tag != -1) << "Impossible button click callback";
toolbar->browser_->ExecuteCommand(tag);
}
// static
gboolean BrowserToolbarGtk::OnMenuButtonPressEvent(GtkWidget* button,
GdkEvent* event,
BrowserToolbarGtk* toolbar) {
// TODO(port): this never puts the button into the "active" state,
// which means we never display the button-pressed-down graphics. I
// suspect a better way to do it is just to use a real GtkMenuShell
// with our custom drawing.
if (event->type == GDK_BUTTON_PRESS) {
GdkEventButton* event_button = reinterpret_cast<GdkEventButton*>(event);
if (event_button->button == 1) {
// We have a button press we should respond to.
if (button == toolbar->page_menu_button_->widget()) {
toolbar->RunPageMenu(event);
return TRUE;
} else if (button == toolbar->app_menu_button_->widget()) {
toolbar->RunAppMenu(event);
return TRUE;
}
}
}
return FALSE;
}
CustomDrawButton* BrowserToolbarGtk::BuildBackForwardButton(
int normal_id,
int active_id,
int highlight_id,
int depressed_id,
const std::wstring& localized_tooltip) {
CustomDrawButton* button = new CustomDrawButton(normal_id, active_id,
highlight_id, depressed_id);
// TODO(erg): Mismatch between wstring and string.
// gtk_tooltips_set_tip(GTK_TOOLTIPS(toolbar_tooltips_),
// GTK_WIDGET(back_),
// localized_tooltip, localized_tooltip);
g_signal_connect(G_OBJECT(button->widget()), "button-press-event",
G_CALLBACK(OnBackForwardPressEvent), this);
g_signal_connect(G_OBJECT(button->widget()), "clicked",
G_CALLBACK(OnButtonClick), this);
gtk_box_pack_start(GTK_BOX(toolbar_), button->widget(), FALSE, FALSE, 0);
// Popup the menu as left-aligned relative to this widget rather than the
// default of right aligned.
g_object_set_data(G_OBJECT(button->widget()), "left-align-popup",
reinterpret_cast<void*>(true));
return button;
}
// static
gboolean BrowserToolbarGtk::OnBackForwardPressEvent(GtkWidget* widget,
GdkEventButton* event,
BrowserToolbarGtk* toolbar) {
// TODO(port): only allow left clicks to open the menu.
MessageLoop::current()->PostDelayedTask(FROM_HERE,
toolbar->show_menu_factory_.NewRunnableMethod(
&BrowserToolbarGtk::ShowBackForwardMenu,
widget, event->button),
kMenuTimerDelay);
return FALSE;
}
void BrowserToolbarGtk::ShowBackForwardMenu(GtkWidget* widget,
gint button_type) {
if (widget == back_->widget()) {
back_forward_menu_.reset(new MenuGtk(back_menu_model_.get()));
} else {
back_forward_menu_.reset(new MenuGtk(forward_menu_model_.get()));
}
back_forward_menu_->Popup(widget, button_type, gtk_get_current_event_time());
}
void BrowserToolbarGtk::RunPageMenu(GdkEvent* button_press_event) {
if (page_menu_ == NULL) {
page_menu_.reset(new MenuGtk(this, GetStandardPageMenu()));
}
page_menu_->Popup(page_menu_button_->widget(), button_press_event);
}
void BrowserToolbarGtk::RunAppMenu(GdkEvent* button_press_event) {
if (app_menu_ == NULL) {
app_menu_.reset(new MenuGtk(this, GetStandardAppMenu()));
}
app_menu_->Popup(app_menu_button_->widget(), button_press_event);
}
CustomDrawButton* BrowserToolbarGtk::MakeHomeButton() {
return BuildToolbarButton(IDR_HOME, IDR_HOME_P, IDR_HOME_H, 0,
l10n_util::GetString(IDS_TOOLTIP_HOME));
}
| Add the IDC_GO mapping for the go button widget. | Add the IDC_GO mapping for the go button widget.
We previously crashed with a NOTREACHED() when you clicked the go button.
Review URL: http://codereview.chromium.org/27205
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@10473 0039d316-1c4b-4281-b951-d872f2087c98
| C++ | bsd-3-clause | junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,robclark/chromium,anirudhSK/chromium,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,zcbenz/cefode-chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,robclark/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,littlstar/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,dushu1203/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,keishi/chromium,nacl-webkit/chrome_deps,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,patrickm/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,Chilledheart/chromium,robclark/chromium,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,robclark/chromium,ltilve/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,keishi/chromium,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,ChromiumWebApps/chromium,keishi/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,ltilve/chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,hgl888/chromium-crosswalk,keishi/chromium,markYoungH/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,Chilledheart/chromium,dednal/chromium.src,Just-D/chromium-1,Just-D/chromium-1,Jonekee/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,axinging/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,robclark/chromium,rogerwang/chromium,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,Chilledheart/chromium,dednal/chromium.src,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,hujiajie/pa-chromium,jaruba/chromium.src,M4sse/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,Chilledheart/chromium,anirudhSK/chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,dushu1203/chromium.src,dednal/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,keishi/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,robclark/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,keishi/chromium,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,M4sse/chromium.src,ltilve/chromium,patrickm/chromium.src,keishi/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,jaruba/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Chilledheart/chromium,robclark/chromium,Chilledheart/chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,markYoungH/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,littlstar/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,littlstar/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,hujiajie/pa-chromium,rogerwang/chromium,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,Just-D/chromium-1,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,littlstar/chromium.src,mogoweb/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,rogerwang/chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,Just-D/chromium-1,mogoweb/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,dushu1203/chromium.src,rogerwang/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,robclark/chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,patrickm/chromium.src,keishi/chromium,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail |
46e5f26c122e14a321a0663a15f44d9741b5e04d | chrome/common/extensions/extension_unpacker.cc | chrome/common/extensions/extension_unpacker.cc | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/extension_unpacker.h"
#include "base/file_util.h"
#include "base/scoped_handle.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/values.h"
#include "net/base/file_stream.h"
#include "chrome/common/common_param_traits.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_file_util.h"
#include "chrome/common/extensions/extension_l10n_util.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/zip.h"
#include "ipc/ipc_message_utils.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/glue/image_decoder.h"
namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;
namespace {
// The name of a temporary directory to install an extension into for
// validation before finalizing install.
const char kTempExtensionName[] = "TEMP_INSTALL";
// The file to write our decoded images to, relative to the extension_path.
const char kDecodedImagesFilename[] = "DECODED_IMAGES";
// The file to write our decoded message catalogs to, relative to the
// extension_path.
const char kDecodedMessageCatalogsFilename[] = "DECODED_MESSAGE_CATALOGS";
// Errors
const char* kCouldNotCreateDirectoryError =
"Could not create directory for unzipping.";
const char* kCouldNotDecodeImageError = "Could not decode theme image.";
const char* kCouldNotUnzipExtension = "Could not unzip extension.";
const char* kPathNamesMustBeAbsoluteOrLocalError =
"Path names must not be absolute or contain '..'.";
// A limit to stop us passing dangerously large canvases to the browser.
const int kMaxImageCanvas = 4096 * 4096;
} // namespace
static SkBitmap DecodeImage(const FilePath& path) {
// Read the file from disk.
std::string file_contents;
if (!file_util::PathExists(path) ||
!file_util::ReadFileToString(path, &file_contents)) {
return SkBitmap();
}
// Decode the image using WebKit's image decoder.
const unsigned char* data =
reinterpret_cast<const unsigned char*>(file_contents.data());
webkit_glue::ImageDecoder decoder;
SkBitmap bitmap = decoder.Decode(data, file_contents.length());
Sk64 bitmap_size = bitmap.getSize64();
if (!bitmap_size.is32() || bitmap_size.get32() > kMaxImageCanvas)
return SkBitmap();
return bitmap;
}
static bool PathContainsParentDirectory(const FilePath& path) {
const FilePath::StringType kSeparators(FilePath::kSeparators);
const FilePath::StringType kParentDirectory(FilePath::kParentDirectory);
const size_t npos = FilePath::StringType::npos;
const FilePath::StringType& value = path.value();
for (size_t i = 0; i < value.length(); ) {
i = value.find(kParentDirectory, i);
if (i != npos) {
if ((i == 0 || kSeparators.find(value[i-1]) == npos) &&
(i+1 < value.length() || kSeparators.find(value[i+1]) == npos)) {
return true;
}
++i;
}
}
return false;
}
DictionaryValue* ExtensionUnpacker::ReadManifest() {
FilePath manifest_path =
temp_install_dir_.Append(Extension::kManifestFilename);
if (!file_util::PathExists(manifest_path)) {
SetError(errors::kInvalidManifest);
return NULL;
}
JSONFileValueSerializer serializer(manifest_path);
std::string error;
scoped_ptr<Value> root(serializer.Deserialize(&error));
if (!root.get()) {
SetError(error);
return NULL;
}
if (!root->IsType(Value::TYPE_DICTIONARY)) {
SetError(errors::kInvalidManifest);
return NULL;
}
return static_cast<DictionaryValue*>(root.release());
}
bool ExtensionUnpacker::ReadAllMessageCatalogs(
const std::string& default_locale) {
FilePath locales_path =
temp_install_dir_.Append(Extension::kLocaleFolder);
// Not all folders under _locales have to be valid locales.
file_util::FileEnumerator locales(locales_path,
false,
file_util::FileEnumerator::DIRECTORIES);
std::set<std::string> all_locales;
extension_l10n_util::GetAllLocales(&all_locales);
FilePath locale_path;
while (!(locale_path = locales.Next()).empty()) {
if (extension_l10n_util::ShouldSkipValidation(locales_path, locale_path,
all_locales))
continue;
FilePath messages_path =
locale_path.Append(Extension::kMessagesFilename);
if (!ReadMessageCatalog(messages_path))
return false;
}
return true;
}
bool ExtensionUnpacker::Run() {
LOG(INFO) << "Installing extension " << extension_path_.value();
// <profile>/Extensions/INSTALL_TEMP/<version>
temp_install_dir_ =
extension_path_.DirName().AppendASCII(kTempExtensionName);
if (!file_util::CreateDirectory(temp_install_dir_)) {
SetError(kCouldNotCreateDirectoryError);
return false;
}
if (!Unzip(extension_path_, temp_install_dir_)) {
SetError(kCouldNotUnzipExtension);
return false;
}
// Parse the manifest.
parsed_manifest_.reset(ReadManifest());
if (!parsed_manifest_.get())
return false; // Error was already reported.
// NOTE: Since the Unpacker doesn't have the extension's public_id, the
// InitFromValue is allowed to generate a temporary id for the extension.
// ANY CODE THAT FOLLOWS SHOULD NOT DEPEND ON THE CORRECT ID OF THIS
// EXTENSION.
Extension extension(temp_install_dir_);
std::string error;
if (!extension.InitFromValue(*parsed_manifest_,
false,
&error)) {
SetError(error);
return false;
}
if (!extension_file_util::ValidateExtension(&extension, &error)) {
SetError(error);
return false;
}
// Decode any images that the browser needs to display.
std::set<FilePath> image_paths = extension.GetBrowserImages();
for (std::set<FilePath>::iterator it = image_paths.begin();
it != image_paths.end(); ++it) {
if (!AddDecodedImage(*it))
return false; // Error was already reported.
}
// Parse all message catalogs (if any).
parsed_catalogs_.reset(new DictionaryValue);
if (!extension.default_locale().empty()) {
if (!ReadAllMessageCatalogs(extension.default_locale()))
return false; // Error was already reported.
}
return true;
}
bool ExtensionUnpacker::DumpImagesToFile() {
IPC::Message pickle; // We use a Message so we can use WriteParam.
IPC::WriteParam(&pickle, decoded_images_);
FilePath path = extension_path_.DirName().AppendASCII(kDecodedImagesFilename);
if (!file_util::WriteFile(path, static_cast<const char*>(pickle.data()),
pickle.size())) {
SetError("Could not write image data to disk.");
return false;
}
return true;
}
bool ExtensionUnpacker::DumpMessageCatalogsToFile() {
IPC::Message pickle;
IPC::WriteParam(&pickle, *parsed_catalogs_.get());
FilePath path = extension_path_.DirName().AppendASCII(
kDecodedMessageCatalogsFilename);
if (!file_util::WriteFile(path, static_cast<const char*>(pickle.data()),
pickle.size())) {
SetError("Could not write message catalogs to disk.");
return false;
}
return true;
}
// static
bool ExtensionUnpacker::ReadImagesFromFile(const FilePath& extension_path,
DecodedImages* images) {
FilePath path = extension_path.AppendASCII(kDecodedImagesFilename);
std::string file_str;
if (!file_util::ReadFileToString(path, &file_str))
return false;
IPC::Message pickle(file_str.data(), file_str.size());
void* iter = NULL;
return IPC::ReadParam(&pickle, &iter, images);
}
// static
bool ExtensionUnpacker::ReadMessageCatalogsFromFile(
const FilePath& extension_path, DictionaryValue* catalogs) {
FilePath path = extension_path.AppendASCII(kDecodedMessageCatalogsFilename);
std::string file_str;
if (!file_util::ReadFileToString(path, &file_str))
return false;
IPC::Message pickle(file_str.data(), file_str.size());
void* iter = NULL;
return IPC::ReadParam(&pickle, &iter, catalogs);
}
bool ExtensionUnpacker::AddDecodedImage(const FilePath& path) {
// Make sure it's not referencing a file outside the extension's subdir.
if (path.IsAbsolute() || PathContainsParentDirectory(path)) {
SetError(kPathNamesMustBeAbsoluteOrLocalError);
return false;
}
SkBitmap image_bitmap = DecodeImage(temp_install_dir_.Append(path));
if (image_bitmap.isNull()) {
SetError(kCouldNotDecodeImageError);
return false;
}
decoded_images_.push_back(MakeTuple(image_bitmap, path));
return true;
}
bool ExtensionUnpacker::ReadMessageCatalog(const FilePath& message_path) {
std::string error;
JSONFileValueSerializer serializer(message_path);
scoped_ptr<DictionaryValue> root(
static_cast<DictionaryValue*>(serializer.Deserialize(&error)));
if (!root.get()) {
std::string messages_file = WideToASCII(message_path.ToWStringHack());
if (error.empty()) {
// If file is missing, Deserialize will fail with empty error.
SetError(StringPrintf("%s %s", errors::kLocalesMessagesFileMissing,
messages_file.c_str()));
} else {
SetError(StringPrintf("%s: %s", messages_file.c_str(), error.c_str()));
}
return false;
}
FilePath relative_path;
// message_path was created from temp_install_dir. This should never fail.
if (!temp_install_dir_.AppendRelativePath(message_path, &relative_path))
NOTREACHED();
parsed_catalogs_->Set(relative_path.DirName().ToWStringHack(),
root.release());
return true;
}
void ExtensionUnpacker::SetError(const std::string &error) {
error_message_ = error;
}
| // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/extensions/extension_unpacker.h"
#include "base/file_util.h"
#include "base/scoped_handle.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/values.h"
#include "net/base/file_stream.h"
#include "chrome/common/common_param_traits.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/extensions/extension_file_util.h"
#include "chrome/common/extensions/extension_l10n_util.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/zip.h"
#include "ipc/ipc_message_utils.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "webkit/glue/image_decoder.h"
namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;
namespace {
// The name of a temporary directory to install an extension into for
// validation before finalizing install.
const char kTempExtensionName[] = "TEMP_INSTALL";
// The file to write our decoded images to, relative to the extension_path.
const char kDecodedImagesFilename[] = "DECODED_IMAGES";
// The file to write our decoded message catalogs to, relative to the
// extension_path.
const char kDecodedMessageCatalogsFilename[] = "DECODED_MESSAGE_CATALOGS";
// Errors
const char* kCouldNotCreateDirectoryError =
"Could not create directory for unzipping: ";
const char* kCouldNotDecodeImageError = "Could not decode theme image.";
const char* kCouldNotUnzipExtension = "Could not unzip extension.";
const char* kPathNamesMustBeAbsoluteOrLocalError =
"Path names must not be absolute or contain '..'.";
// A limit to stop us passing dangerously large canvases to the browser.
const int kMaxImageCanvas = 4096 * 4096;
} // namespace
static SkBitmap DecodeImage(const FilePath& path) {
// Read the file from disk.
std::string file_contents;
if (!file_util::PathExists(path) ||
!file_util::ReadFileToString(path, &file_contents)) {
return SkBitmap();
}
// Decode the image using WebKit's image decoder.
const unsigned char* data =
reinterpret_cast<const unsigned char*>(file_contents.data());
webkit_glue::ImageDecoder decoder;
SkBitmap bitmap = decoder.Decode(data, file_contents.length());
Sk64 bitmap_size = bitmap.getSize64();
if (!bitmap_size.is32() || bitmap_size.get32() > kMaxImageCanvas)
return SkBitmap();
return bitmap;
}
static bool PathContainsParentDirectory(const FilePath& path) {
const FilePath::StringType kSeparators(FilePath::kSeparators);
const FilePath::StringType kParentDirectory(FilePath::kParentDirectory);
const size_t npos = FilePath::StringType::npos;
const FilePath::StringType& value = path.value();
for (size_t i = 0; i < value.length(); ) {
i = value.find(kParentDirectory, i);
if (i != npos) {
if ((i == 0 || kSeparators.find(value[i-1]) == npos) &&
(i+1 < value.length() || kSeparators.find(value[i+1]) == npos)) {
return true;
}
++i;
}
}
return false;
}
DictionaryValue* ExtensionUnpacker::ReadManifest() {
FilePath manifest_path =
temp_install_dir_.Append(Extension::kManifestFilename);
if (!file_util::PathExists(manifest_path)) {
SetError(errors::kInvalidManifest);
return NULL;
}
JSONFileValueSerializer serializer(manifest_path);
std::string error;
scoped_ptr<Value> root(serializer.Deserialize(&error));
if (!root.get()) {
SetError(error);
return NULL;
}
if (!root->IsType(Value::TYPE_DICTIONARY)) {
SetError(errors::kInvalidManifest);
return NULL;
}
return static_cast<DictionaryValue*>(root.release());
}
bool ExtensionUnpacker::ReadAllMessageCatalogs(
const std::string& default_locale) {
FilePath locales_path =
temp_install_dir_.Append(Extension::kLocaleFolder);
// Not all folders under _locales have to be valid locales.
file_util::FileEnumerator locales(locales_path,
false,
file_util::FileEnumerator::DIRECTORIES);
std::set<std::string> all_locales;
extension_l10n_util::GetAllLocales(&all_locales);
FilePath locale_path;
while (!(locale_path = locales.Next()).empty()) {
if (extension_l10n_util::ShouldSkipValidation(locales_path, locale_path,
all_locales))
continue;
FilePath messages_path =
locale_path.Append(Extension::kMessagesFilename);
if (!ReadMessageCatalog(messages_path))
return false;
}
return true;
}
bool ExtensionUnpacker::Run() {
LOG(INFO) << "Installing extension " << extension_path_.value();
// <profile>/Extensions/INSTALL_TEMP/<version>
temp_install_dir_ =
extension_path_.DirName().AppendASCII(kTempExtensionName);
if (!file_util::CreateDirectory(temp_install_dir_)) {
#if defined(OS_WIN)
std::string dir_string = WideToUTF8(temp_install_dir_.value());
#else
std::string dir_string = temp_install_dir_.value();
#endif
SetError(kCouldNotCreateDirectoryError + dir_string);
return false;
}
if (!Unzip(extension_path_, temp_install_dir_)) {
SetError(kCouldNotUnzipExtension);
return false;
}
// Parse the manifest.
parsed_manifest_.reset(ReadManifest());
if (!parsed_manifest_.get())
return false; // Error was already reported.
// NOTE: Since the Unpacker doesn't have the extension's public_id, the
// InitFromValue is allowed to generate a temporary id for the extension.
// ANY CODE THAT FOLLOWS SHOULD NOT DEPEND ON THE CORRECT ID OF THIS
// EXTENSION.
Extension extension(temp_install_dir_);
std::string error;
if (!extension.InitFromValue(*parsed_manifest_,
false,
&error)) {
SetError(error);
return false;
}
if (!extension_file_util::ValidateExtension(&extension, &error)) {
SetError(error);
return false;
}
// Decode any images that the browser needs to display.
std::set<FilePath> image_paths = extension.GetBrowserImages();
for (std::set<FilePath>::iterator it = image_paths.begin();
it != image_paths.end(); ++it) {
if (!AddDecodedImage(*it))
return false; // Error was already reported.
}
// Parse all message catalogs (if any).
parsed_catalogs_.reset(new DictionaryValue);
if (!extension.default_locale().empty()) {
if (!ReadAllMessageCatalogs(extension.default_locale()))
return false; // Error was already reported.
}
return true;
}
bool ExtensionUnpacker::DumpImagesToFile() {
IPC::Message pickle; // We use a Message so we can use WriteParam.
IPC::WriteParam(&pickle, decoded_images_);
FilePath path = extension_path_.DirName().AppendASCII(kDecodedImagesFilename);
if (!file_util::WriteFile(path, static_cast<const char*>(pickle.data()),
pickle.size())) {
SetError("Could not write image data to disk.");
return false;
}
return true;
}
bool ExtensionUnpacker::DumpMessageCatalogsToFile() {
IPC::Message pickle;
IPC::WriteParam(&pickle, *parsed_catalogs_.get());
FilePath path = extension_path_.DirName().AppendASCII(
kDecodedMessageCatalogsFilename);
if (!file_util::WriteFile(path, static_cast<const char*>(pickle.data()),
pickle.size())) {
SetError("Could not write message catalogs to disk.");
return false;
}
return true;
}
// static
bool ExtensionUnpacker::ReadImagesFromFile(const FilePath& extension_path,
DecodedImages* images) {
FilePath path = extension_path.AppendASCII(kDecodedImagesFilename);
std::string file_str;
if (!file_util::ReadFileToString(path, &file_str))
return false;
IPC::Message pickle(file_str.data(), file_str.size());
void* iter = NULL;
return IPC::ReadParam(&pickle, &iter, images);
}
// static
bool ExtensionUnpacker::ReadMessageCatalogsFromFile(
const FilePath& extension_path, DictionaryValue* catalogs) {
FilePath path = extension_path.AppendASCII(kDecodedMessageCatalogsFilename);
std::string file_str;
if (!file_util::ReadFileToString(path, &file_str))
return false;
IPC::Message pickle(file_str.data(), file_str.size());
void* iter = NULL;
return IPC::ReadParam(&pickle, &iter, catalogs);
}
bool ExtensionUnpacker::AddDecodedImage(const FilePath& path) {
// Make sure it's not referencing a file outside the extension's subdir.
if (path.IsAbsolute() || PathContainsParentDirectory(path)) {
SetError(kPathNamesMustBeAbsoluteOrLocalError);
return false;
}
SkBitmap image_bitmap = DecodeImage(temp_install_dir_.Append(path));
if (image_bitmap.isNull()) {
SetError(kCouldNotDecodeImageError);
return false;
}
decoded_images_.push_back(MakeTuple(image_bitmap, path));
return true;
}
bool ExtensionUnpacker::ReadMessageCatalog(const FilePath& message_path) {
std::string error;
JSONFileValueSerializer serializer(message_path);
scoped_ptr<DictionaryValue> root(
static_cast<DictionaryValue*>(serializer.Deserialize(&error)));
if (!root.get()) {
std::string messages_file = WideToASCII(message_path.ToWStringHack());
if (error.empty()) {
// If file is missing, Deserialize will fail with empty error.
SetError(StringPrintf("%s %s", errors::kLocalesMessagesFileMissing,
messages_file.c_str()));
} else {
SetError(StringPrintf("%s: %s", messages_file.c_str(), error.c_str()));
}
return false;
}
FilePath relative_path;
// message_path was created from temp_install_dir. This should never fail.
if (!temp_install_dir_.AppendRelativePath(message_path, &relative_path))
NOTREACHED();
parsed_catalogs_->Set(relative_path.DirName().ToWStringHack(),
root.release());
return true;
}
void ExtensionUnpacker::SetError(const std::string &error) {
error_message_ = error;
}
| Make an error message verbose to investigate a un-reproducible bug. | Make an error message verbose to investigate a un-reproducible bug.
BUG=35198
TEST=none
Review URL: http://codereview.chromium.org/1528018
git-svn-id: http://src.chromium.org/svn/trunk/src@43686 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 5451b1648790573a58fafe34aac57cc94583996e | C++ | bsd-3-clause | meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser |
1026e375b58ff99712e977669a7a3b866898db0d | chrome/browser/command_updater_unittest.cc | chrome/browser/command_updater_unittest.cc | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "chrome/browser/command_updater.h"
#include "testing/gtest/include/gtest/gtest.h"
class TestingCommandHandlerMock
: public CommandUpdater::CommandUpdaterDelegate {
public:
virtual void ExecuteCommand(int id) {
EXPECT_EQ(1, id);
}
};
class CommandUpdaterTest : public testing::Test {
};
class TestingCommandObserverMock : public CommandUpdater::CommandObserver {
public:
virtual void EnabledStateChangedForCommand(int id, bool enabled) {
enabled_ = enabled;
}
bool enabled() const { return enabled_; }
private:
bool enabled_;
};
TEST_F(CommandUpdaterTest, TestBasicAPI) {
TestingCommandHandlerMock handler;
CommandUpdater command_updater(&handler);
// Unsupported command
EXPECT_FALSE(command_updater.SupportsCommand(0));
EXPECT_FALSE(command_updater.IsCommandEnabled(0));
// TestingCommandHandlerMock::ExecuteCommand should not be called, since
// the command is not supported.
command_updater.ExecuteCommand(0);
// Supported, enabled command
command_updater.UpdateCommandEnabled(1, true);
EXPECT_TRUE(command_updater.SupportsCommand(1));
EXPECT_TRUE(command_updater.IsCommandEnabled(1));
command_updater.ExecuteCommand(1);
// Supported, disabled command
command_updater.UpdateCommandEnabled(2, false);
EXPECT_TRUE(command_updater.SupportsCommand(2));
EXPECT_FALSE(command_updater.IsCommandEnabled(2));
// TestingCommandHandlerMock::ExecuteCommmand should not be called, since
// the command_updater is disabled
command_updater.ExecuteCommand(2);
}
TEST_F(CommandUpdaterTest, TestObservers) {
TestingCommandHandlerMock handler;
CommandUpdater command_updater(&handler);
// Create an observer for the command 2 and add it to the controller, then
// update the command.
TestingCommandObserverMock observer;
command_updater.AddCommandObserver(2, &observer);
command_updater.UpdateCommandEnabled(2, true);
EXPECT_TRUE(observer.enabled());
command_updater.UpdateCommandEnabled(2, false);
EXPECT_FALSE(observer.enabled());
// Remove the observer and update the command.
command_updater.RemoveCommandObserver(2, &observer);
command_updater.UpdateCommandEnabled(2, true);
EXPECT_FALSE(observer.enabled());
}
TEST_F(CommandUpdaterTest, TestRemoveObserverForUnsupportedCommand) {
TestingCommandHandlerMock handler;
CommandUpdater command_updater(&handler);
// Test removing observers for commands that are unsupported
TestingCommandObserverMock observer;
command_updater.RemoveCommandObserver(3, &observer);
}
TEST_F(CommandUpdaterTest, TestAddingNullObserver) {
TestingCommandHandlerMock handler;
CommandUpdater command_updater(&handler);
// Test adding/removing NULL observers
command_updater.AddCommandObserver(4, NULL);
}
TEST_F(CommandUpdaterTest, TestRemovingNullObserver) {
TestingCommandHandlerMock handler;
CommandUpdater command_updater(&handler);
command_updater.RemoveCommandObserver(4, NULL);
}
| // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "chrome/browser/command_updater.h"
#include "testing/gtest/include/gtest/gtest.h"
class TestingCommandHandlerMock
: public CommandUpdater::CommandUpdaterDelegate {
public:
virtual void ExecuteCommand(int id) {
EXPECT_EQ(1, id);
}
};
class CommandUpdaterTest : public testing::Test {
};
class TestingCommandObserverMock : public CommandUpdater::CommandObserver {
public:
virtual void EnabledStateChangedForCommand(int id, bool enabled) {
enabled_ = enabled;
}
bool enabled() const { return enabled_; }
private:
bool enabled_;
};
TEST_F(CommandUpdaterTest, TestBasicAPI) {
TestingCommandHandlerMock handler;
CommandUpdater command_updater(&handler);
// Unsupported command
EXPECT_FALSE(command_updater.SupportsCommand(0));
EXPECT_FALSE(command_updater.IsCommandEnabled(0));
// TestingCommandHandlerMock::ExecuteCommand should not be called, since
// the command is not supported.
command_updater.ExecuteCommand(0);
// Supported, enabled command
command_updater.UpdateCommandEnabled(1, true);
EXPECT_TRUE(command_updater.SupportsCommand(1));
EXPECT_TRUE(command_updater.IsCommandEnabled(1));
command_updater.ExecuteCommand(1);
// Supported, disabled command
command_updater.UpdateCommandEnabled(2, false);
EXPECT_TRUE(command_updater.SupportsCommand(2));
EXPECT_FALSE(command_updater.IsCommandEnabled(2));
// TestingCommandHandlerMock::ExecuteCommmand should not be called, since
// the command_updater is disabled
command_updater.ExecuteCommand(2);
}
TEST_F(CommandUpdaterTest, TestObservers) {
TestingCommandHandlerMock handler;
CommandUpdater command_updater(&handler);
// Create an observer for the command 2 and add it to the controller, then
// update the command.
TestingCommandObserverMock observer;
command_updater.AddCommandObserver(2, &observer);
command_updater.UpdateCommandEnabled(2, true);
EXPECT_TRUE(observer.enabled());
command_updater.UpdateCommandEnabled(2, false);
EXPECT_FALSE(observer.enabled());
// Remove the observer and update the command.
command_updater.RemoveCommandObserver(2, &observer);
command_updater.UpdateCommandEnabled(2, true);
EXPECT_FALSE(observer.enabled());
}
| Remove unnecessary unit tests (now we're just using ObserverList). | Remove unnecessary unit tests (now we're just using ObserverList).
TBR=pinkerton
Review URL: http://codereview.chromium.org/18386
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@8336 0039d316-1c4b-4281-b951-d872f2087c98
| C++ | bsd-3-clause | adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium |
ac7a1c49499503c1d93cfc49ea9d5f731c3272ed | chrome/browser/sync/notification_method.cc | chrome/browser/sync/notification_method.cc | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notification_method.h"
#include "base/logging.h"
namespace browser_sync {
// TODO(akalin): Eventually change this to NOTIFICATION_NEW.
const NotificationMethod kDefaultNotificationMethod =
NOTIFICATION_TRANSITIONAL;
std::string NotificationMethodToString(
NotificationMethod notification_method) {
switch (notification_method) {
case NOTIFICATION_LEGACY:
return "NOTIFICATION_LEGACY";
break;
case NOTIFICATION_TRANSITIONAL:
return "NOTIFICATION_TRANSITIONAL";
break;
case NOTIFICATION_NEW:
return "NOTIFICATION_NEW";
break;
case NOTIFICATION_SERVER:
return "NOTIFICATION_SERVER";
break;
default:
LOG(WARNING) << "Unknown value for notification method: "
<< notification_method;
break;
}
return "<unknown notification method>";
}
NotificationMethod StringToNotificationMethod(const std::string& str) {
if (str == "legacy") {
return NOTIFICATION_LEGACY;
} else if (str == "transitional") {
return NOTIFICATION_TRANSITIONAL;
} else if (str == "new") {
return NOTIFICATION_NEW;
} else if (str == "server") {
return NOTIFICATION_SERVER;
}
LOG(WARNING) << "Unknown notification method \"" << str
<< "\"; using method "
<< NotificationMethodToString(kDefaultNotificationMethod);
return kDefaultNotificationMethod;
}
} // namespace browser_sync
| // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notification_method.h"
#include "base/logging.h"
namespace browser_sync {
const NotificationMethod kDefaultNotificationMethod =
NOTIFICATION_SERVER;
std::string NotificationMethodToString(
NotificationMethod notification_method) {
switch (notification_method) {
case NOTIFICATION_LEGACY:
return "NOTIFICATION_LEGACY";
break;
case NOTIFICATION_TRANSITIONAL:
return "NOTIFICATION_TRANSITIONAL";
break;
case NOTIFICATION_NEW:
return "NOTIFICATION_NEW";
break;
case NOTIFICATION_SERVER:
return "NOTIFICATION_SERVER";
break;
default:
LOG(WARNING) << "Unknown value for notification method: "
<< notification_method;
break;
}
return "<unknown notification method>";
}
NotificationMethod StringToNotificationMethod(const std::string& str) {
if (str == "legacy") {
return NOTIFICATION_LEGACY;
} else if (str == "transitional") {
return NOTIFICATION_TRANSITIONAL;
} else if (str == "new") {
return NOTIFICATION_NEW;
} else if (str == "server") {
return NOTIFICATION_SERVER;
}
LOG(WARNING) << "Unknown notification method \"" << str
<< "\"; using method "
<< NotificationMethodToString(kDefaultNotificationMethod);
return kDefaultNotificationMethod;
}
} // namespace browser_sync
| Set default sync notification method to "server". | Set default sync notification method to "server".
BUG=34647
TEST=manual
Review URL: http://codereview.chromium.org/2822044
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@51494 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
| C++ | bsd-3-clause | wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser |
cb2caf36632d6bfc4b341828e91eacdf6aa70447 | chrome/browser/views/frame/browser_frame_win.cc | chrome/browser/views/frame/browser_frame_win.cc | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/frame/browser_frame_win.h"
#include <dwmapi.h>
#include <shellapi.h>
#include <set>
#include "app/resource_bundle.h"
#include "app/theme_provider.h"
#include "app/win_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dock_info.h"
#include "chrome/browser/views/frame/browser_non_client_frame_view.h"
#include "chrome/browser/views/frame/browser_root_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/frame/glass_browser_frame_view.h"
#include "chrome/browser/views/frame/opaque_browser_frame_view.h"
#include "chrome/browser/views/tabs/browser_tab_strip.h"
#include "grit/theme_resources.h"
#include "views/screen.h"
#include "views/window/window_delegate.h"
// static
static const int kClientEdgeThickness = 3;
static const int kTabDragWindowAlpha = 200;
// static (Factory method.)
BrowserFrame* BrowserFrame::Create(BrowserView* browser_view,
Profile* profile) {
BrowserFrameWin* frame = new BrowserFrameWin(browser_view, profile);
frame->Init();
return frame;
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, public:
BrowserFrameWin::BrowserFrameWin(BrowserView* browser_view, Profile* profile)
: WindowWin(browser_view),
browser_view_(browser_view),
saved_window_style_(0),
saved_window_ex_style_(0),
detached_drag_mode_(false),
drop_tabstrip_(NULL),
root_view_(NULL),
frame_initialized_(false),
profile_(profile) {
browser_view_->set_frame(this);
GetNonClientView()->SetFrameView(CreateFrameViewForWindow());
// Don't focus anything on creation, selecting a tab will set the focus.
set_focus_on_creation(false);
}
void BrowserFrameWin::Init() {
WindowWin::Init(NULL, gfx::Rect());
}
BrowserFrameWin::~BrowserFrameWin() {
}
views::Window* BrowserFrameWin::GetWindow() {
return this;
}
void BrowserFrameWin::TabStripCreated(TabStripWrapper* tabstrip) {
}
int BrowserFrameWin::GetMinimizeButtonOffset() const {
TITLEBARINFOEX titlebar_info;
titlebar_info.cbSize = sizeof(TITLEBARINFOEX);
SendMessage(GetNativeView(), WM_GETTITLEBARINFOEX, 0, (WPARAM)&titlebar_info);
CPoint minimize_button_corner(titlebar_info.rgrect[2].left,
titlebar_info.rgrect[2].top);
MapWindowPoints(HWND_DESKTOP, GetNativeView(), &minimize_button_corner, 1);
return minimize_button_corner.x;
}
gfx::Rect BrowserFrameWin::GetBoundsForTabStrip(
TabStripWrapper* tabstrip) const {
return browser_frame_view_->GetBoundsForTabStrip(tabstrip);
}
void BrowserFrameWin::UpdateThrobber(bool running) {
browser_frame_view_->UpdateThrobber(running);
}
void BrowserFrameWin::ContinueDraggingDetachedTab() {
detached_drag_mode_ = true;
// Set the frame to partially transparent.
UpdateWindowAlphaForTabDragging(detached_drag_mode_);
// Send the message directly, so that the window is positioned appropriately.
SendMessage(GetNativeWindow(), WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(0, 0));
}
ThemeProvider* BrowserFrameWin::GetThemeProviderForFrame() const {
// This is implemented for a different interface than GetThemeProvider is,
// but they mean the same things.
return GetThemeProvider();
}
bool BrowserFrameWin::AlwaysUseNativeFrame() const {
// We use the native frame when we're told we should by the theme provider
// (e.g. no custom theme is active), or when we're a popup or app window. We
// don't theme popup or app windows, so regardless of whether or not a theme
// is active for normal browser windows, we don't want to use the custom frame
// for popups/apps.
return GetThemeProvider()->ShouldUseNativeFrame() ||
(!browser_view_->IsBrowserTypeNormal() &&
win_util::ShouldUseVistaFrame());
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, views::WindowWin overrides:
gfx::Insets BrowserFrameWin::GetClientAreaInsets() const {
if (!GetNonClientView()->UseNativeFrame())
return WindowWin::GetClientAreaInsets();
int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
// We draw our own client edge over part of the default frame.
if (!IsMaximized())
border_thickness -= kClientEdgeThickness;
return gfx::Insets(0, border_thickness, border_thickness, border_thickness);
}
bool BrowserFrameWin::GetAccelerator(int cmd_id,
views::Accelerator* accelerator) {
return browser_view_->GetAccelerator(cmd_id, accelerator);
}
void BrowserFrameWin::OnEndSession(BOOL ending, UINT logoff) {
BrowserList::WindowsSessionEnding();
}
void BrowserFrameWin::OnEnterSizeMove() {
drop_tabstrip_ = NULL;
browser_view_->WindowMoveOrResizeStarted();
}
void BrowserFrameWin::OnExitSizeMove() {
if (TabStrip2::Enabled()) {
if (detached_drag_mode_) {
detached_drag_mode_ = false;
if (drop_tabstrip_) {
gfx::Point screen_point = views::Screen::GetCursorScreenPoint();
BrowserTabStrip* tabstrip =
browser_view_->tabstrip()->AsBrowserTabStrip();
gfx::Rect tsb = tabstrip->GetDraggedTabScreenBounds(screen_point);
drop_tabstrip_->AttachTab(tabstrip->DetachTab(0), screen_point, tsb);
} else {
UpdateWindowAlphaForTabDragging(detached_drag_mode_);
browser_view_->tabstrip()->AsBrowserTabStrip()->SendDraggedTabHome();
}
}
}
WidgetWin::OnExitSizeMove();
}
void BrowserFrameWin::OnInitMenuPopup(HMENU menu, UINT position,
BOOL is_system_menu) {
browser_view_->PrepareToRunSystemMenu(menu);
}
LRESULT BrowserFrameWin::OnMouseActivate(HWND window, UINT hittest_code,
UINT message) {
return browser_view_->ActivateAppModalDialog() ? MA_NOACTIVATEANDEAT
: MA_ACTIVATE;
}
void BrowserFrameWin::OnMove(const CPoint& point) {
browser_view_->WindowMoved();
}
void BrowserFrameWin::OnMoving(UINT param, LPRECT new_bounds) {
browser_view_->WindowMoved();
}
LRESULT BrowserFrameWin::OnNCActivate(BOOL active) {
if (browser_view_->ActivateAppModalDialog())
return TRUE;
browser_view_->ActivationChanged(!!active);
return WindowWin::OnNCActivate(active);
}
LRESULT BrowserFrameWin::OnNCHitTest(const CPoint& pt) {
// Only do DWM hit-testing when we are using the native frame.
if (GetNonClientView()->UseNativeFrame()) {
LRESULT result;
if (DwmDefWindowProc(GetNativeView(), WM_NCHITTEST, 0,
MAKELPARAM(pt.x, pt.y), &result)) {
return result;
}
}
return WindowWin::OnNCHitTest(pt);
}
void BrowserFrameWin::OnWindowPosChanged(WINDOWPOS* window_pos) {
if (TabStrip2::Enabled()) {
if (detached_drag_mode_) {
// TODO(beng): move all to BrowserTabStrip...
// We check to see if the mouse cursor is in the magnetism zone of another
// visible TabStrip. If so, we should dock to it.
std::set<HWND> ignore_windows;
ignore_windows.insert(GetNativeWindow());
gfx::Point screen_point = views::Screen::GetCursorScreenPoint();
HWND local_window =
DockInfo::GetLocalProcessWindowAtPoint(screen_point, ignore_windows);
if (local_window) {
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(local_window);
drop_tabstrip_ = browser_view->tabstrip()->AsBrowserTabStrip();
if (TabStrip2::IsDragRearrange(drop_tabstrip_, screen_point)) {
ReleaseCapture();
return;
}
}
drop_tabstrip_ = NULL;
}
}
// Windows lies to us about the position of the minimize button before a
// window is visible. We use the position of the minimize button to place the
// distributor logo in official builds. When the window is shown, we need to
// re-layout and schedule a paint for the non-client frame view so that the
// distributor logo has the correct position when the window becomes visible.
// This fixes bugs where the distributor logo appears to overlay the minimize
// button. http://crbug.com/15520
// Note that we will call Layout every time SetWindowPos is called with
// SWP_SHOWWINDOW, however callers typically are careful about not specifying
// this flag unless necessary to avoid flicker.
if (window_pos->flags & SWP_SHOWWINDOW) {
GetNonClientView()->Layout();
GetNonClientView()->SchedulePaint();
}
UpdateDWMFrame();
// Let the default window procedure handle - IMPORTANT!
WindowWin::OnWindowPosChanged(window_pos);
}
ThemeProvider* BrowserFrameWin::GetThemeProvider() const {
return profile_->GetThemeProvider();
}
ThemeProvider* BrowserFrameWin::GetDefaultThemeProvider() const {
return profile_->GetThemeProvider();
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, views::CustomFrameWindow overrides:
int BrowserFrameWin::GetShowState() const {
return browser_view_->GetShowState();
}
views::NonClientFrameView* BrowserFrameWin::CreateFrameViewForWindow() {
if (AlwaysUseNativeFrame())
browser_frame_view_ = new GlassBrowserFrameView(this, browser_view_);
else
browser_frame_view_ = new OpaqueBrowserFrameView(this, browser_view_);
return browser_frame_view_;
}
void BrowserFrameWin::UpdateFrameAfterFrameChange() {
// We need to update the glass region on or off before the base class adjusts
// the window region.
UpdateDWMFrame();
WindowWin::UpdateFrameAfterFrameChange();
}
views::RootView* BrowserFrameWin::CreateRootView() {
root_view_ = new BrowserRootView(browser_view_, this);
return root_view_;
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, private:
void BrowserFrameWin::UpdateDWMFrame() {
// Nothing to do yet, or we're not showing a DWM frame.
if (!GetClientView() || !AlwaysUseNativeFrame())
return;
MARGINS margins = { 0 };
if (browser_view_->IsBrowserTypeNormal()) {
// In fullscreen mode, we don't extend glass into the client area at all,
// because the GDI-drawn text in the web content composited over it will
// become semi-transparent over any glass area.
if (!IsMaximized() && !IsFullscreen()) {
margins.cxLeftWidth = kClientEdgeThickness + 1;
margins.cxRightWidth = kClientEdgeThickness + 1;
margins.cyBottomHeight = kClientEdgeThickness + 1;
}
// In maximized mode, we only have a titlebar strip of glass, no side/bottom
// borders.
if (!browser_view_->IsFullscreen()) {
margins.cyTopHeight =
GetBoundsForTabStrip(browser_view_->tabstrip()).bottom();
}
} else {
// For popup and app windows we want to use the default margins.
}
DwmExtendFrameIntoClientArea(GetNativeView(), &margins);
}
void BrowserFrameWin::UpdateWindowAlphaForTabDragging(bool dragging) {
HWND frame_hwnd = GetNativeWindow();
if (dragging) {
// Make the frame slightly transparent during the drag operation.
saved_window_style_ = ::GetWindowLong(frame_hwnd, GWL_STYLE);
saved_window_ex_style_ = ::GetWindowLong(frame_hwnd, GWL_EXSTYLE);
::SetWindowLong(frame_hwnd, GWL_EXSTYLE,
saved_window_ex_style_ | WS_EX_LAYERED);
// Remove the captions tyle so the window doesn't have window controls for a
// more "transparent" look.
::SetWindowLong(frame_hwnd, GWL_STYLE,
saved_window_style_ & ~WS_CAPTION);
SetLayeredWindowAttributes(frame_hwnd, RGB(0xFF, 0xFF, 0xFF),
kTabDragWindowAlpha, LWA_ALPHA);
} else {
::SetWindowLong(frame_hwnd, GWL_STYLE, saved_window_style_);
::SetWindowLong(frame_hwnd, GWL_EXSTYLE, saved_window_ex_style_);
}
}
| // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/frame/browser_frame_win.h"
#include <dwmapi.h>
#include <shellapi.h>
#include <set>
#include "app/resource_bundle.h"
#include "app/theme_provider.h"
#include "app/win_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/dock_info.h"
#include "chrome/browser/views/frame/browser_non_client_frame_view.h"
#include "chrome/browser/views/frame/browser_root_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/frame/glass_browser_frame_view.h"
#include "chrome/browser/views/frame/opaque_browser_frame_view.h"
#include "chrome/browser/views/tabs/browser_tab_strip.h"
#include "grit/theme_resources.h"
#include "views/screen.h"
#include "views/window/window_delegate.h"
// static
static const int kClientEdgeThickness = 3;
static const int kTabDragWindowAlpha = 200;
// static (Factory method.)
BrowserFrame* BrowserFrame::Create(BrowserView* browser_view,
Profile* profile) {
BrowserFrameWin* frame = new BrowserFrameWin(browser_view, profile);
frame->Init();
return frame;
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, public:
BrowserFrameWin::BrowserFrameWin(BrowserView* browser_view, Profile* profile)
: WindowWin(browser_view),
browser_view_(browser_view),
saved_window_style_(0),
saved_window_ex_style_(0),
detached_drag_mode_(false),
drop_tabstrip_(NULL),
root_view_(NULL),
frame_initialized_(false),
profile_(profile) {
browser_view_->set_frame(this);
GetNonClientView()->SetFrameView(CreateFrameViewForWindow());
// Don't focus anything on creation, selecting a tab will set the focus.
set_focus_on_creation(false);
}
void BrowserFrameWin::Init() {
WindowWin::Init(NULL, gfx::Rect());
}
BrowserFrameWin::~BrowserFrameWin() {
}
views::Window* BrowserFrameWin::GetWindow() {
return this;
}
void BrowserFrameWin::TabStripCreated(TabStripWrapper* tabstrip) {
}
int BrowserFrameWin::GetMinimizeButtonOffset() const {
TITLEBARINFOEX titlebar_info;
titlebar_info.cbSize = sizeof(TITLEBARINFOEX);
SendMessage(GetNativeView(), WM_GETTITLEBARINFOEX, 0, (WPARAM)&titlebar_info);
CPoint minimize_button_corner(titlebar_info.rgrect[2].left,
titlebar_info.rgrect[2].top);
MapWindowPoints(HWND_DESKTOP, GetNativeView(), &minimize_button_corner, 1);
return minimize_button_corner.x;
}
gfx::Rect BrowserFrameWin::GetBoundsForTabStrip(
TabStripWrapper* tabstrip) const {
return browser_frame_view_->GetBoundsForTabStrip(tabstrip);
}
void BrowserFrameWin::UpdateThrobber(bool running) {
browser_frame_view_->UpdateThrobber(running);
}
void BrowserFrameWin::ContinueDraggingDetachedTab() {
detached_drag_mode_ = true;
// Set the frame to partially transparent.
UpdateWindowAlphaForTabDragging(detached_drag_mode_);
// Send the message directly, so that the window is positioned appropriately.
SendMessage(GetNativeWindow(), WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(0, 0));
}
ThemeProvider* BrowserFrameWin::GetThemeProviderForFrame() const {
// This is implemented for a different interface than GetThemeProvider is,
// but they mean the same things.
return GetThemeProvider();
}
bool BrowserFrameWin::AlwaysUseNativeFrame() const {
// We use the native frame when we're told we should by the theme provider
// (e.g. no custom theme is active), or when we're a popup or app window. We
// don't theme popup or app windows, so regardless of whether or not a theme
// is active for normal browser windows, we don't want to use the custom frame
// for popups/apps.
return GetThemeProvider()->ShouldUseNativeFrame() ||
(!browser_view_->IsBrowserTypeNormal() &&
win_util::ShouldUseVistaFrame());
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, views::WindowWin overrides:
gfx::Insets BrowserFrameWin::GetClientAreaInsets() const {
// Use the default client insets for an opaque frame or a glass popup/app
// frame.
if (!GetNonClientView()->UseNativeFrame() ||
!browser_view_->IsBrowserTypeNormal()) {
return WindowWin::GetClientAreaInsets();
}
int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
// We draw our own client edge over part of the default frame.
if (!IsMaximized())
border_thickness -= kClientEdgeThickness;
return gfx::Insets(0, border_thickness, border_thickness, border_thickness);
}
bool BrowserFrameWin::GetAccelerator(int cmd_id,
views::Accelerator* accelerator) {
return browser_view_->GetAccelerator(cmd_id, accelerator);
}
void BrowserFrameWin::OnEndSession(BOOL ending, UINT logoff) {
BrowserList::WindowsSessionEnding();
}
void BrowserFrameWin::OnEnterSizeMove() {
drop_tabstrip_ = NULL;
browser_view_->WindowMoveOrResizeStarted();
}
void BrowserFrameWin::OnExitSizeMove() {
if (TabStrip2::Enabled()) {
if (detached_drag_mode_) {
detached_drag_mode_ = false;
if (drop_tabstrip_) {
gfx::Point screen_point = views::Screen::GetCursorScreenPoint();
BrowserTabStrip* tabstrip =
browser_view_->tabstrip()->AsBrowserTabStrip();
gfx::Rect tsb = tabstrip->GetDraggedTabScreenBounds(screen_point);
drop_tabstrip_->AttachTab(tabstrip->DetachTab(0), screen_point, tsb);
} else {
UpdateWindowAlphaForTabDragging(detached_drag_mode_);
browser_view_->tabstrip()->AsBrowserTabStrip()->SendDraggedTabHome();
}
}
}
WidgetWin::OnExitSizeMove();
}
void BrowserFrameWin::OnInitMenuPopup(HMENU menu, UINT position,
BOOL is_system_menu) {
browser_view_->PrepareToRunSystemMenu(menu);
}
LRESULT BrowserFrameWin::OnMouseActivate(HWND window, UINT hittest_code,
UINT message) {
return browser_view_->ActivateAppModalDialog() ? MA_NOACTIVATEANDEAT
: MA_ACTIVATE;
}
void BrowserFrameWin::OnMove(const CPoint& point) {
browser_view_->WindowMoved();
}
void BrowserFrameWin::OnMoving(UINT param, LPRECT new_bounds) {
browser_view_->WindowMoved();
}
LRESULT BrowserFrameWin::OnNCActivate(BOOL active) {
if (browser_view_->ActivateAppModalDialog())
return TRUE;
browser_view_->ActivationChanged(!!active);
return WindowWin::OnNCActivate(active);
}
LRESULT BrowserFrameWin::OnNCHitTest(const CPoint& pt) {
// Only do DWM hit-testing when we are using the native frame.
if (GetNonClientView()->UseNativeFrame()) {
LRESULT result;
if (DwmDefWindowProc(GetNativeView(), WM_NCHITTEST, 0,
MAKELPARAM(pt.x, pt.y), &result)) {
return result;
}
}
return WindowWin::OnNCHitTest(pt);
}
void BrowserFrameWin::OnWindowPosChanged(WINDOWPOS* window_pos) {
if (TabStrip2::Enabled()) {
if (detached_drag_mode_) {
// TODO(beng): move all to BrowserTabStrip...
// We check to see if the mouse cursor is in the magnetism zone of another
// visible TabStrip. If so, we should dock to it.
std::set<HWND> ignore_windows;
ignore_windows.insert(GetNativeWindow());
gfx::Point screen_point = views::Screen::GetCursorScreenPoint();
HWND local_window =
DockInfo::GetLocalProcessWindowAtPoint(screen_point, ignore_windows);
if (local_window) {
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(local_window);
drop_tabstrip_ = browser_view->tabstrip()->AsBrowserTabStrip();
if (TabStrip2::IsDragRearrange(drop_tabstrip_, screen_point)) {
ReleaseCapture();
return;
}
}
drop_tabstrip_ = NULL;
}
}
// Windows lies to us about the position of the minimize button before a
// window is visible. We use the position of the minimize button to place the
// distributor logo in official builds. When the window is shown, we need to
// re-layout and schedule a paint for the non-client frame view so that the
// distributor logo has the correct position when the window becomes visible.
// This fixes bugs where the distributor logo appears to overlay the minimize
// button. http://crbug.com/15520
// Note that we will call Layout every time SetWindowPos is called with
// SWP_SHOWWINDOW, however callers typically are careful about not specifying
// this flag unless necessary to avoid flicker.
if (window_pos->flags & SWP_SHOWWINDOW) {
GetNonClientView()->Layout();
GetNonClientView()->SchedulePaint();
}
UpdateDWMFrame();
// Let the default window procedure handle - IMPORTANT!
WindowWin::OnWindowPosChanged(window_pos);
}
ThemeProvider* BrowserFrameWin::GetThemeProvider() const {
return profile_->GetThemeProvider();
}
ThemeProvider* BrowserFrameWin::GetDefaultThemeProvider() const {
return profile_->GetThemeProvider();
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, views::CustomFrameWindow overrides:
int BrowserFrameWin::GetShowState() const {
return browser_view_->GetShowState();
}
views::NonClientFrameView* BrowserFrameWin::CreateFrameViewForWindow() {
if (AlwaysUseNativeFrame())
browser_frame_view_ = new GlassBrowserFrameView(this, browser_view_);
else
browser_frame_view_ = new OpaqueBrowserFrameView(this, browser_view_);
return browser_frame_view_;
}
void BrowserFrameWin::UpdateFrameAfterFrameChange() {
// We need to update the glass region on or off before the base class adjusts
// the window region.
UpdateDWMFrame();
WindowWin::UpdateFrameAfterFrameChange();
}
views::RootView* BrowserFrameWin::CreateRootView() {
root_view_ = new BrowserRootView(browser_view_, this);
return root_view_;
}
///////////////////////////////////////////////////////////////////////////////
// BrowserFrame, private:
void BrowserFrameWin::UpdateDWMFrame() {
// Nothing to do yet, or we're not showing a DWM frame.
if (!GetClientView() || !AlwaysUseNativeFrame())
return;
MARGINS margins = { 0 };
if (browser_view_->IsBrowserTypeNormal()) {
// In fullscreen mode, we don't extend glass into the client area at all,
// because the GDI-drawn text in the web content composited over it will
// become semi-transparent over any glass area.
if (!IsMaximized() && !IsFullscreen()) {
margins.cxLeftWidth = kClientEdgeThickness + 1;
margins.cxRightWidth = kClientEdgeThickness + 1;
margins.cyBottomHeight = kClientEdgeThickness + 1;
}
// In maximized mode, we only have a titlebar strip of glass, no side/bottom
// borders.
if (!browser_view_->IsFullscreen()) {
margins.cyTopHeight =
GetBoundsForTabStrip(browser_view_->tabstrip()).bottom();
}
} else {
// For popup and app windows we want to use the default margins.
}
DwmExtendFrameIntoClientArea(GetNativeView(), &margins);
}
void BrowserFrameWin::UpdateWindowAlphaForTabDragging(bool dragging) {
HWND frame_hwnd = GetNativeWindow();
if (dragging) {
// Make the frame slightly transparent during the drag operation.
saved_window_style_ = ::GetWindowLong(frame_hwnd, GWL_STYLE);
saved_window_ex_style_ = ::GetWindowLong(frame_hwnd, GWL_EXSTYLE);
::SetWindowLong(frame_hwnd, GWL_EXSTYLE,
saved_window_ex_style_ | WS_EX_LAYERED);
// Remove the captions tyle so the window doesn't have window controls for a
// more "transparent" look.
::SetWindowLong(frame_hwnd, GWL_STYLE,
saved_window_style_ & ~WS_CAPTION);
SetLayeredWindowAttributes(frame_hwnd, RGB(0xFF, 0xFF, 0xFF),
kTabDragWindowAlpha, LWA_ALPHA);
} else {
::SetWindowLong(frame_hwnd, GWL_STYLE, saved_window_style_);
::SetWindowLong(frame_hwnd, GWL_EXSTYLE, saved_window_ex_style_);
}
}
| Fix regression where popups and app frames lost their titlebars. | Fix regression where popups and app frames lost their titlebars.
TBR=pkasting
http://crbug.com/25784
TEST=open any popup window or app frame, should have title bar to drag window.
Review URL: http://codereview.chromium.org/328026
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@30029 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
| C++ | bsd-3-clause | wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser |
081d2786cd3c16d1c2c534be84c9ca8129b0ed7b | chrome/browser/tabs/default_tab_handler.cc | chrome/browser/tabs/default_tab_handler.cc | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/metrics/nacl_histogram.h"
#include "chrome/browser/tabs/default_tab_handler.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/tabs/tab_strip_model.h"
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, public:
DefaultTabHandler::DefaultTabHandler(TabHandlerDelegate* delegate)
: delegate_(delegate),
ALLOW_THIS_IN_INITIALIZER_LIST(
model_(new TabStripModel(this, delegate->GetProfile()))) {
UmaNaclHistogramEnumeration(FIRST_TAB_NACL_BASELINE);
model_->AddObserver(this);
}
DefaultTabHandler::~DefaultTabHandler() {
// The tab strip should not have any tabs at this point.
DCHECK(model_->empty());
model_->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, TabHandler implementation:
TabStripModel* DefaultTabHandler::GetTabStripModel() const {
return model_.get();
}
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, TabStripModelDelegate implementation:
TabContents* DefaultTabHandler::AddBlankTab(bool foreground) {
UmaNaclHistogramEnumeration(NEW_TAB_NACL_BASELINE);
return delegate_->AsBrowser()->AddBlankTab(foreground);
}
TabContents* DefaultTabHandler::AddBlankTabAt(int index, bool foreground) {
return delegate_->AsBrowser()->AddBlankTabAt(index, foreground);
}
Browser* DefaultTabHandler::CreateNewStripWithContents(
TabContents* detached_contents,
const gfx::Rect& window_bounds,
const DockInfo& dock_info,
bool maximize) {
return delegate_->AsBrowser()->CreateNewStripWithContents(detached_contents,
window_bounds,
dock_info,
maximize);
}
void DefaultTabHandler::ContinueDraggingDetachedTab(
TabContents* contents,
const gfx::Rect& window_bounds,
const gfx::Rect& tab_bounds) {
delegate_->AsBrowser()->ContinueDraggingDetachedTab(contents,
window_bounds,
tab_bounds);
}
int DefaultTabHandler::GetDragActions() const {
return delegate_->AsBrowser()->GetDragActions();
}
TabContents* DefaultTabHandler::CreateTabContentsForURL(
const GURL& url,
const GURL& referrer,
Profile* profile,
PageTransition::Type transition,
bool defer_load,
SiteInstance* instance) const {
return delegate_->AsBrowser()->CreateTabContentsForURL(url,
referrer,
profile,
transition,
defer_load,
instance);
}
bool DefaultTabHandler::CanDuplicateContentsAt(int index) {
return delegate_->AsBrowser()->CanDuplicateContentsAt(index);
}
void DefaultTabHandler::DuplicateContentsAt(int index) {
delegate_->AsBrowser()->DuplicateContentsAt(index);
}
void DefaultTabHandler::CloseFrameAfterDragSession() {
delegate_->AsBrowser()->CloseFrameAfterDragSession();
}
void DefaultTabHandler::CreateHistoricalTab(TabContents* contents) {
delegate_->AsBrowser()->CreateHistoricalTab(contents);
}
bool DefaultTabHandler::RunUnloadListenerBeforeClosing(TabContents* contents) {
return delegate_->AsBrowser()->RunUnloadListenerBeforeClosing(contents);
}
bool DefaultTabHandler::CanCloseContentsAt(int index) {
return delegate_->AsBrowser()->CanCloseContentsAt(index);
}
bool DefaultTabHandler::CanBookmarkAllTabs() const {
return delegate_->AsBrowser()->CanBookmarkAllTabs();
}
void DefaultTabHandler::BookmarkAllTabs() {
delegate_->AsBrowser()->BookmarkAllTabs();
}
bool DefaultTabHandler::CanCloseTab() const {
return delegate_->AsBrowser()->CanCloseTab();
}
void DefaultTabHandler::ToggleUseVerticalTabs() {
delegate_->AsBrowser()->ToggleUseVerticalTabs();
}
bool DefaultTabHandler::CanRestoreTab() {
return delegate_->AsBrowser()->CanRestoreTab();
}
void DefaultTabHandler::RestoreTab() {
delegate_->AsBrowser()->RestoreTab();
}
bool DefaultTabHandler::LargeIconsPermitted() const {
return delegate_->AsBrowser()->LargeIconsPermitted();
}
bool DefaultTabHandler::UseVerticalTabs() const {
return delegate_->AsBrowser()->UseVerticalTabs();
}
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, TabStripModelObserver implementation:
void DefaultTabHandler::TabInsertedAt(TabContents* contents,
int index,
bool foreground) {
delegate_->AsBrowser()->TabInsertedAt(contents, index, foreground);
}
void DefaultTabHandler::TabClosingAt(TabStripModel* tab_strip_model,
TabContents* contents,
int index) {
delegate_->AsBrowser()->TabClosingAt(tab_strip_model, contents, index);
}
void DefaultTabHandler::TabDetachedAt(TabContents* contents, int index) {
delegate_->AsBrowser()->TabDetachedAt(contents, index);
}
void DefaultTabHandler::TabDeselectedAt(TabContents* contents, int index) {
delegate_->AsBrowser()->TabDeselectedAt(contents, index);
}
void DefaultTabHandler::TabSelectedAt(TabContents* old_contents,
TabContents* new_contents,
int index,
bool user_gesture) {
delegate_->AsBrowser()->TabSelectedAt(old_contents,
new_contents,
index,
user_gesture);
}
void DefaultTabHandler::TabMoved(TabContents* contents,
int from_index,
int to_index) {
delegate_->AsBrowser()->TabMoved(contents, from_index, to_index);
}
void DefaultTabHandler::TabReplacedAt(TabContents* old_contents,
TabContents* new_contents,
int index) {
delegate_->AsBrowser()->TabReplacedAt(old_contents, new_contents, index);
}
void DefaultTabHandler::TabPinnedStateChanged(TabContents* contents,
int index) {
delegate_->AsBrowser()->TabPinnedStateChanged(contents, index);
}
void DefaultTabHandler::TabStripEmpty() {
delegate_->AsBrowser()->TabStripEmpty();
}
////////////////////////////////////////////////////////////////////////////////
// TabHandler, public:
// static
TabHandler* TabHandler::CreateTabHandler(TabHandlerDelegate* delegate) {
return new DefaultTabHandler(delegate);
}
| // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/metrics/nacl_histogram.h"
#include "chrome/browser/tabs/default_tab_handler.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/tabs/tab_strip_model.h"
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, public:
DefaultTabHandler::DefaultTabHandler(TabHandlerDelegate* delegate)
: delegate_(delegate),
ALLOW_THIS_IN_INITIALIZER_LIST(
model_(new TabStripModel(this, delegate->GetProfile()))) {
UmaNaclHistogramEnumeration(FIRST_TAB_NACL_BASELINE);
model_->AddObserver(this);
}
DefaultTabHandler::~DefaultTabHandler() {
// The tab strip should not have any tabs at this point.
DCHECK(model_->empty());
model_->RemoveObserver(this);
}
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, TabHandler implementation:
TabStripModel* DefaultTabHandler::GetTabStripModel() const {
return model_.get();
}
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, TabStripModelDelegate implementation:
TabContents* DefaultTabHandler::AddBlankTab(bool foreground) {
UmaNaclHistogramEnumeration(NEW_TAB_NACL_BASELINE);
return delegate_->AsBrowser()->AddBlankTab(foreground);
}
TabContents* DefaultTabHandler::AddBlankTabAt(int index, bool foreground) {
return delegate_->AsBrowser()->AddBlankTabAt(index, foreground);
}
Browser* DefaultTabHandler::CreateNewStripWithContents(
TabContents* detached_contents,
const gfx::Rect& window_bounds,
const DockInfo& dock_info,
bool maximize) {
return delegate_->AsBrowser()->CreateNewStripWithContents(detached_contents,
window_bounds,
dock_info,
maximize);
}
void DefaultTabHandler::ContinueDraggingDetachedTab(
TabContents* contents,
const gfx::Rect& window_bounds,
const gfx::Rect& tab_bounds) {
delegate_->AsBrowser()->ContinueDraggingDetachedTab(contents,
window_bounds,
tab_bounds);
}
int DefaultTabHandler::GetDragActions() const {
return delegate_->AsBrowser()->GetDragActions();
}
TabContents* DefaultTabHandler::CreateTabContentsForURL(
const GURL& url,
const GURL& referrer,
Profile* profile,
PageTransition::Type transition,
bool defer_load,
SiteInstance* instance) const {
return delegate_->AsBrowser()->CreateTabContentsForURL(url,
referrer,
profile,
transition,
defer_load,
instance);
}
bool DefaultTabHandler::CanDuplicateContentsAt(int index) {
return delegate_->AsBrowser()->CanDuplicateContentsAt(index);
}
void DefaultTabHandler::DuplicateContentsAt(int index) {
delegate_->AsBrowser()->DuplicateContentsAt(index);
}
void DefaultTabHandler::CloseFrameAfterDragSession() {
delegate_->AsBrowser()->CloseFrameAfterDragSession();
}
void DefaultTabHandler::CreateHistoricalTab(TabContents* contents) {
delegate_->AsBrowser()->CreateHistoricalTab(contents);
}
bool DefaultTabHandler::RunUnloadListenerBeforeClosing(TabContents* contents) {
return delegate_->AsBrowser()->RunUnloadListenerBeforeClosing(contents);
}
bool DefaultTabHandler::CanCloseContentsAt(int index) {
return delegate_->AsBrowser()->CanCloseContentsAt(index);
}
bool DefaultTabHandler::CanBookmarkAllTabs() const {
return delegate_->AsBrowser()->CanBookmarkAllTabs();
}
void DefaultTabHandler::BookmarkAllTabs() {
delegate_->AsBrowser()->BookmarkAllTabs();
}
bool DefaultTabHandler::CanCloseTab() const {
return delegate_->AsBrowser()->CanCloseTab();
}
void DefaultTabHandler::ToggleUseVerticalTabs() {
delegate_->AsBrowser()->ToggleUseVerticalTabs();
}
bool DefaultTabHandler::CanRestoreTab() {
return delegate_->AsBrowser()->CanRestoreTab();
}
void DefaultTabHandler::RestoreTab() {
delegate_->AsBrowser()->RestoreTab();
}
bool DefaultTabHandler::LargeIconsPermitted() const {
return delegate_->AsBrowser()->LargeIconsPermitted();
}
bool DefaultTabHandler::UseVerticalTabs() const {
return delegate_->AsBrowser()->UseVerticalTabs();
}
////////////////////////////////////////////////////////////////////////////////
// DefaultTabHandler, TabStripModelObserver implementation:
void DefaultTabHandler::TabInsertedAt(TabContents* contents,
int index,
bool foreground) {
delegate_->AsBrowser()->TabInsertedAt(contents, index, foreground);
}
void DefaultTabHandler::TabClosingAt(TabStripModel* tab_strip_model,
TabContents* contents,
int index) {
delegate_->AsBrowser()->TabClosingAt(tab_strip_model, contents, index);
}
void DefaultTabHandler::TabDetachedAt(TabContents* contents, int index) {
delegate_->AsBrowser()->TabDetachedAt(contents, index);
}
void DefaultTabHandler::TabDeselectedAt(TabContents* contents, int index) {
delegate_->AsBrowser()->TabDeselectedAt(contents, index);
}
void DefaultTabHandler::TabSelectedAt(TabContents* old_contents,
TabContents* new_contents,
int index,
bool user_gesture) {
delegate_->AsBrowser()->TabSelectedAt(old_contents,
new_contents,
index,
user_gesture);
}
void DefaultTabHandler::TabMoved(TabContents* contents,
int from_index,
int to_index) {
delegate_->AsBrowser()->TabMoved(contents, from_index, to_index);
}
void DefaultTabHandler::TabReplacedAt(TabContents* old_contents,
TabContents* new_contents,
int index) {
delegate_->AsBrowser()->TabReplacedAt(old_contents, new_contents, index);
}
void DefaultTabHandler::TabPinnedStateChanged(TabContents* contents,
int index) {
delegate_->AsBrowser()->TabPinnedStateChanged(contents, index);
}
void DefaultTabHandler::TabStripEmpty() {
delegate_->AsBrowser()->TabStripEmpty();
}
////////////////////////////////////////////////////////////////////////////////
// TabHandler, public:
// static
TabHandler* TabHandler::CreateTabHandler(TabHandlerDelegate* delegate) {
return new DefaultTabHandler(delegate);
}
| Fix indentation of a continuation. BUG=none TEST=none | Fix indentation of a continuation.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/4148010
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@64643 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
| C++ | bsd-3-clause | wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser |
a7863117d9535bb7ead8e44dd1230881dbd2e13b | Source/platform/audio/mac/FFTFrameMac.cpp | Source/platform/audio/mac/FFTFrameMac.cpp | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Mac OS X - specific FFTFrame implementation
#include "config.h"
#if ENABLE(WEB_AUDIO)
#if OS(MACOSX)
#include "platform/audio/FFTFrame.h"
#include "platform/audio/VectorMath.h"
namespace blink {
const int kMaxFFTPow2Size = 24;
FFTSetup* FFTFrame::fftSetups = 0;
// Normal constructor: allocates for a given fftSize
FFTFrame::FFTFrame(unsigned fftSize)
: m_realData(fftSize)
, m_imagData(fftSize)
{
m_FFTSize = fftSize;
m_log2FFTSize = static_cast<unsigned>(log2(fftSize));
// We only allow power of two
ASSERT(1UL << m_log2FFTSize == m_FFTSize);
// Lazily create and share fftSetup with other frames
m_FFTSetup = fftSetupForSize(fftSize);
// Setup frame data
m_frame.realp = m_realData.data();
m_frame.imagp = m_imagData.data();
}
// Creates a blank/empty frame (interpolate() must later be called)
FFTFrame::FFTFrame()
: m_realData(0)
, m_imagData(0)
{
// Later will be set to correct values when interpolate() is called
m_frame.realp = 0;
m_frame.imagp = 0;
m_FFTSize = 0;
m_log2FFTSize = 0;
}
// Copy constructor
FFTFrame::FFTFrame(const FFTFrame& frame)
: m_FFTSize(frame.m_FFTSize)
, m_log2FFTSize(frame.m_log2FFTSize)
, m_realData(frame.m_FFTSize)
, m_imagData(frame.m_FFTSize)
, m_FFTSetup(frame.m_FFTSetup)
{
// Setup frame data
m_frame.realp = m_realData.data();
m_frame.imagp = m_imagData.data();
// Copy/setup frame data
unsigned nbytes = sizeof(float) * m_FFTSize;
memcpy(realData(), frame.m_frame.realp, nbytes);
memcpy(imagData(), frame.m_frame.imagp, nbytes);
}
FFTFrame::~FFTFrame()
{
}
void FFTFrame::doFFT(const float* data)
{
AudioFloatArray scaledData(m_FFTSize);
// veclib fft returns a result that is twice as large as would be expected. Compensate for that
// by scaling the input by half so the FFT has the correct scaling.
float scale = 0.5f;
VectorMath::vsmul(data, 1, &scale, scaledData.data(), 1, m_FFTSize);
vDSP_ctoz((DSPComplex*)scaledData.data(), 2, &m_frame, 1, m_FFTSize / 2);
vDSP_fft_zrip(m_FFTSetup, &m_frame, 1, m_log2FFTSize, FFT_FORWARD);
}
void FFTFrame::doInverseFFT(float* data)
{
vDSP_fft_zrip(m_FFTSetup, &m_frame, 1, m_log2FFTSize, FFT_INVERSE);
vDSP_ztoc(&m_frame, 1, (DSPComplex*)data, 2, m_FFTSize / 2);
// Do final scaling so that x == IFFT(FFT(x))
float scale = 1.0f / m_FFTSize;
vDSP_vsmul(data, 1, &scale, data, 1, m_FFTSize);
}
FFTSetup FFTFrame::fftSetupForSize(unsigned fftSize)
{
if (!fftSetups) {
fftSetups = (FFTSetup*)malloc(sizeof(FFTSetup) * kMaxFFTPow2Size);
memset(fftSetups, 0, sizeof(FFTSetup) * kMaxFFTPow2Size);
}
int pow2size = static_cast<int>(log2(fftSize));
ASSERT(pow2size < kMaxFFTPow2Size);
if (!fftSetups[pow2size])
fftSetups[pow2size] = vDSP_create_fftsetup(pow2size, FFT_RADIX2);
return fftSetups[pow2size];
}
void FFTFrame::initialize()
{
}
void FFTFrame::cleanup()
{
if (!fftSetups)
return;
for (int i = 0; i < kMaxFFTPow2Size; ++i) {
if (fftSetups[i])
vDSP_destroy_fftsetup(fftSetups[i]);
}
free(fftSetups);
fftSetups = 0;
}
} // namespace blink
#endif // #if OS(MACOSX)
#endif // ENABLE(WEB_AUDIO)
| /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Mac OS X - specific FFTFrame implementation
#include "config.h"
#if ENABLE(WEB_AUDIO)
#if OS(MACOSX)
#include "platform/audio/FFTFrame.h"
#include "platform/audio/VectorMath.h"
namespace blink {
const int kMaxFFTPow2Size = 24;
FFTSetup* FFTFrame::fftSetups = 0;
// Normal constructor: allocates for a given fftSize
FFTFrame::FFTFrame(unsigned fftSize)
: m_realData(fftSize)
, m_imagData(fftSize)
{
m_FFTSize = fftSize;
m_log2FFTSize = static_cast<unsigned>(log2(fftSize));
// We only allow power of two
ASSERT(1UL << m_log2FFTSize == m_FFTSize);
// Lazily create and share fftSetup with other frames
m_FFTSetup = fftSetupForSize(fftSize);
// Setup frame data
m_frame.realp = m_realData.data();
m_frame.imagp = m_imagData.data();
}
// Creates a blank/empty frame (interpolate() must later be called)
FFTFrame::FFTFrame()
: m_realData(0)
, m_imagData(0)
{
// Later will be set to correct values when interpolate() is called
m_frame.realp = 0;
m_frame.imagp = 0;
m_FFTSize = 0;
m_log2FFTSize = 0;
}
// Copy constructor
FFTFrame::FFTFrame(const FFTFrame& frame)
: m_FFTSize(frame.m_FFTSize)
, m_log2FFTSize(frame.m_log2FFTSize)
, m_realData(frame.m_FFTSize)
, m_imagData(frame.m_FFTSize)
, m_FFTSetup(frame.m_FFTSetup)
{
// Setup frame data
m_frame.realp = m_realData.data();
m_frame.imagp = m_imagData.data();
// Copy/setup frame data
unsigned nbytes = sizeof(float) * m_FFTSize;
memcpy(realData(), frame.m_frame.realp, nbytes);
memcpy(imagData(), frame.m_frame.imagp, nbytes);
}
FFTFrame::~FFTFrame()
{
}
void FFTFrame::doFFT(const float* data)
{
AudioFloatArray scaledData(m_FFTSize);
// veclib fft returns a result that is twice as large as would be expected. Compensate for that
// by scaling the input by half so the FFT has the correct scaling.
float scale = 0.5f;
VectorMath::vsmul(data, 1, &scale, scaledData.data(), 1, m_FFTSize);
vDSP_ctoz((DSPComplex*)scaledData.data(), 2, &m_frame, 1, m_FFTSize / 2);
vDSP_fft_zrip(m_FFTSetup, &m_frame, 1, m_log2FFTSize, FFT_FORWARD);
}
void FFTFrame::doInverseFFT(float* data)
{
vDSP_fft_zrip(m_FFTSetup, &m_frame, 1, m_log2FFTSize, FFT_INVERSE);
vDSP_ztoc(&m_frame, 1, (DSPComplex*)data, 2, m_FFTSize / 2);
// Do final scaling so that x == IFFT(FFT(x))
float scale = 1.0f / m_FFTSize;
VectorMath::vsmul(data, 1, &scale, data, 1, m_FFTSize);
}
FFTSetup FFTFrame::fftSetupForSize(unsigned fftSize)
{
if (!fftSetups) {
fftSetups = (FFTSetup*)malloc(sizeof(FFTSetup) * kMaxFFTPow2Size);
memset(fftSetups, 0, sizeof(FFTSetup) * kMaxFFTPow2Size);
}
int pow2size = static_cast<int>(log2(fftSize));
ASSERT(pow2size < kMaxFFTPow2Size);
if (!fftSetups[pow2size])
fftSetups[pow2size] = vDSP_create_fftsetup(pow2size, FFT_RADIX2);
return fftSetups[pow2size];
}
void FFTFrame::initialize()
{
}
void FFTFrame::cleanup()
{
if (!fftSetups)
return;
for (int i = 0; i < kMaxFFTPow2Size; ++i) {
if (fftSetups[i])
vDSP_destroy_fftsetup(fftSetups[i]);
}
free(fftSetups);
fftSetups = 0;
}
} // namespace blink
#endif // #if OS(MACOSX)
#endif // ENABLE(WEB_AUDIO)
| Change vsmul method from vDSP_ to VectorMatch. | Change vsmul method from vDSP_ to VectorMatch.
Inside of VectorMatch::vsmul is calling vDSP_vsmul when MACOS macro is enabled.
FFTFrameMac is used both method VectorMatch::vsmul and vDSP_vsmul.
It needs to change to VectorMatch for code maintenance.
BUG=411128
Review URL: https://codereview.chromium.org/545773002
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@181444 bbb929c8-8fbe-4397-9dbb-9b2b20218538
| C++ | bsd-3-clause | primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs |
f717cb30e03e435918ae19409cf427843b139849 | test/correctness/interleave.cpp | test/correctness/interleave.cpp | #include "Halide.h"
#include <stdio.h>
#include <math.h>
using std::vector;
using namespace Halide;
using namespace Halide::Internal;
class CountInterleaves : public IRVisitor {
public:
int result;
CountInterleaves() : result(0) {}
using IRVisitor::visit;
void visit(const Call *op) {
if (op->name == Call::interleave_vectors &&
op->call_type == Call::Intrinsic) {
result++;
}
IRVisitor::visit(op);
}
};
int count_interleaves(Func f) {
Target t = get_jit_target_from_environment();
t.set_feature(Target::NoBoundsQuery);
t.set_feature(Target::NoAsserts);
f.compute_root();
Stmt s = Internal::lower({f.function()}, t);
CountInterleaves i;
s.accept(&i);
return i.result;
}
void check_interleave_count(Func f, int correct) {
int c = count_interleaves(f);
if (c < correct) {
printf("Func %s should have interleaved >= %d times but interleaved %d times instead.\n",
f.name().c_str(), correct, c);
exit(-1);
}
}
// Make sure the interleave pattern generates good vector code
int main(int argc, char **argv) {
Var x, y, c;
{
Func f, g, h;
f(x) = sin(x);
g(x) = cos(x);
h(x) = select(x % 2 == 0, 1.0f/f(x/2), g(x/2)*17.0f);
f.compute_root();
g.compute_root();
h.vectorize(x, 8);
check_interleave_count(h, 1);
Image<float> result = h.realize(16);
for (int x = 0; x < 16; x++) {
float correct = ((x % 2) == 0) ? (1.0f/(sinf(x/2))) : (cosf(x/2)*17.0f);
float delta = result(x) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result(x), correct);
return -1;
}
}
}
{
// Test interleave 3 vectors:
Func planar, interleaved;
planar(x, y) = Halide::cast<float>( 3 * x + y );
interleaved(x, y) = planar(x, y);
Var xy("xy");
planar
.compute_at(interleaved, xy)
.vectorize(x, 4);
interleaved
.reorder(y, x)
.bound(y, 0, 3)
.bound(x, 0, 16)
.fuse(y, x, xy)
.vectorize(xy, 12);
interleaved
.output_buffer()
.set_min(1, 0)
.set_stride(0, 3)
.set_stride(1, 1)
.set_extent(1, 3);
Buffer buff3;
buff3 = Buffer(Float(32), 16, 3, 0, 0, (uint8_t *)0);
buff3.raw_buffer()->stride[0] = 3;
buff3.raw_buffer()->stride[1] = 1;
Realization r3({buff3});
interleaved.realize(r3);
check_interleave_count(interleaved, 2);
Image<float> result3 = r3[0];
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 3; y++) {
float correct = 3*x + y;
float delta = result3(x,y) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result3(x,y), correct);
return -1;
}
}
}
}
{
// Test interleave 4 vectors:
Func f1, f2, f3, f4, f5;
f1(x) = sin(x);
f2(x) = sin(2*x);
f3(x) = sin(3*x);
f4(x) = sin(4*x);
f5(x) = sin(5*x);
Func output4;
output4(x, y) = select(y == 0, f1(x),
y == 1, f2(x),
y == 2, f3(x),
f4(x));
output4
.reorder(y, x)
.bound(y, 0, 4)
.unroll(y)
.vectorize(x, 4);
output4.output_buffer()
.set_min(1, 0)
.set_stride(0, 4)
.set_stride(1, 1)
.set_extent(1, 4);
check_interleave_count(output4, 1);
Buffer buff4;
buff4 = Buffer(Float(32), 16, 4, 0, 0, (uint8_t *)0);
buff4.raw_buffer()->stride[0] = 4;
buff4.raw_buffer()->stride[1] = 1;
Realization r4({buff4});
output4.realize(r4);
Image<float> result4 = r4[0];
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 4; y++) {
float correct = sin((y+1)*x);
float delta = result4(x,y) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result4(x,y), correct);
return -1;
}
}
}
// Test interleave 5 vectors:
Func output5;
output5(x, y) = select(y == 0, f1(x),
y == 1, f2(x),
y == 2, f3(x),
y == 3, f4(x),
f5(x));
output5
.reorder(y, x)
.bound(y, 0, 5)
.unroll(y)
.vectorize(x, 4);
output5.output_buffer()
.set_min(1, 0)
.set_stride(0, 5)
.set_stride(1, 1)
.set_extent(1, 5);
check_interleave_count(output5, 1);
Buffer buff5;
buff5 = Buffer(Float(32), 16, 5, 0, 0, (uint8_t *)0);
buff5.raw_buffer()->stride[0] = 5;
buff5.raw_buffer()->stride[1] = 1;
Realization r5({buff5});
output5.realize(r5);
Image<float> result5 = r5[0];
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 5; y++) {
float correct = sin((y+1)*x);
float delta = result5(x,y) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result5(x,y), correct);
return -1;
}
}
}
}
{
// Test interleaving inside of nested blocks
Func f1, f2, f3, f4, f5;
f1(x) = sin(x);
f1.compute_root();
f2(x) = sin(2*x);
f2.compute_root();
Func unrolled;
unrolled(x, y) = select(x % 2 == 0, f1(x), f2(x)) + y;
Var xi, yi;
unrolled.tile(x, y, xi, yi, 2, 2).vectorize(x, 4).unroll(xi).unroll(yi).unroll(x, 2);
check_interleave_count(unrolled, 4);
}
{
// Make sure we don't interleave when the reordering would change the meaning.
Image<uint8_t> ref;
for (int i = 0; i < 2; i++) {
Func output6;
output6(x, y) = cast<uint8_t>(x);
RDom r(0, 16);
// A not-safe-to-merge pair of updates
output6(2*r, 0) = cast<uint8_t>(3);
output6(2*r+1, 0) = output6(2*r, 0)+2;
// A safe-to-merge pair of updates
output6(2*r, 1) = cast<uint8_t>(3);
output6(2*r+1, 1) = cast<uint8_t>(4);
// A safe-to-merge-but-not-complete triple of updates:
output6(3*r, 3) = cast<uint8_t>(3);
output6(3*r+1, 3) = cast<uint8_t>(4);
// A safe-to-merge-but-we-don't pair of updates, because they
// load recursively, so we conservatively bail out.
output6(2*r, 2) += 1;
output6(2*r+1, 2) += 2;
// A safe-to-merge triple of updates:
output6(3*r, 3) = cast<uint8_t>(7);
output6(3*r+2, 3) = cast<uint8_t>(9);
output6(3*r+1, 3) = cast<uint8_t>(8);
if (i == 0) {
// Making the reference output.
ref = output6.realize(50, 4);
} else {
// Vectorize and compare to the reference.
for (int j = 0; j < 11; j++) {
output6.update(j).vectorize(r);
}
check_interleave_count(output6, 2);
Image<uint8_t> out = output6.realize(50, 4);
for (int y = 0; y < ref.height(); y++) {
for (int x = 0; x < ref.width(); x++) {
if (out(x, y) != ref(x, y)) {
printf("result(%d, %d) = %d instead of %d\n",
x, y, out(x, y), ref(x, y));
return -1;
}
}
}
}
}
}
{
// Test that transposition works when vectorizing either dimension:
Func square("square");
square(x, y) = cast(UInt(16), 5*x + y);
Func trans1("trans1");
trans1(x, y) = square(y, x);
Func trans2("trans2");
trans2(x, y) = square(y, x);
square.compute_root()
.bound(x, 0, 8)
.bound(y, 0, 8);
trans1.compute_root()
.bound(x, 0, 8)
.bound(y, 0, 8)
.vectorize(x)
.unroll(y);
trans2.compute_root()
.bound(x, 0, 8)
.bound(y, 0, 8)
.unroll(x)
.vectorize(y);
trans1.output_buffer()
.set_min(0,0).set_min(1,0)
.set_stride(0,1).set_stride(1,8)
.set_extent(0,8).set_extent(1,8);
trans2.output_buffer()
.set_min(0,0).set_min(1,0)
.set_stride(0,1).set_stride(1,8)
.set_extent(0,8).set_extent(1,8);
Image<uint16_t> result6(8,8);
Image<uint16_t> result7(8,8);
trans1.realize(result6);
trans2.realize(result7);
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
int correct = 5*y + x;
if (result6(x,y) != correct) {
printf("result(%d) = %d instead of %d\n", x, result6(x,y), correct);
return -1;
}
if (result7(x,y) != correct) {
printf("result(%d) = %d instead of %d\n", x, result7(x,y), correct);
return -1;
}
}
}
check_interleave_count(trans1, 1);
check_interleave_count(trans2, 1);
}
printf("Success!\n");
return 0;
}
| #include "Halide.h"
#include <stdio.h>
#include <math.h>
using std::vector;
using namespace Halide;
using namespace Halide::Internal;
class CountInterleaves : public IRVisitor {
public:
int result;
CountInterleaves() : result(0) {}
using IRVisitor::visit;
void visit(const Call *op) {
if (op->name == Call::interleave_vectors &&
op->call_type == Call::Intrinsic) {
result++;
}
IRVisitor::visit(op);
}
};
int count_interleaves(Func f) {
Target t = get_jit_target_from_environment();
t.set_feature(Target::NoBoundsQuery);
t.set_feature(Target::NoAsserts);
f.compute_root();
Stmt s = Internal::lower({f.function()}, f.name(), t);
CountInterleaves i;
s.accept(&i);
return i.result;
}
void check_interleave_count(Func f, int correct) {
int c = count_interleaves(f);
if (c < correct) {
printf("Func %s should have interleaved >= %d times but interleaved %d times instead.\n",
f.name().c_str(), correct, c);
exit(-1);
}
}
// Make sure the interleave pattern generates good vector code
int main(int argc, char **argv) {
Var x, y, c;
{
Func f, g, h;
f(x) = sin(x);
g(x) = cos(x);
h(x) = select(x % 2 == 0, 1.0f/f(x/2), g(x/2)*17.0f);
f.compute_root();
g.compute_root();
h.vectorize(x, 8);
check_interleave_count(h, 1);
Image<float> result = h.realize(16);
for (int x = 0; x < 16; x++) {
float correct = ((x % 2) == 0) ? (1.0f/(sinf(x/2))) : (cosf(x/2)*17.0f);
float delta = result(x) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result(x), correct);
return -1;
}
}
}
{
// Test interleave 3 vectors:
Func planar, interleaved;
planar(x, y) = Halide::cast<float>( 3 * x + y );
interleaved(x, y) = planar(x, y);
Var xy("xy");
planar
.compute_at(interleaved, xy)
.vectorize(x, 4);
interleaved
.reorder(y, x)
.bound(y, 0, 3)
.bound(x, 0, 16)
.fuse(y, x, xy)
.vectorize(xy, 12);
interleaved
.output_buffer()
.set_min(1, 0)
.set_stride(0, 3)
.set_stride(1, 1)
.set_extent(1, 3);
Buffer buff3;
buff3 = Buffer(Float(32), 16, 3, 0, 0, (uint8_t *)0);
buff3.raw_buffer()->stride[0] = 3;
buff3.raw_buffer()->stride[1] = 1;
Realization r3({buff3});
interleaved.realize(r3);
check_interleave_count(interleaved, 2);
Image<float> result3 = r3[0];
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 3; y++) {
float correct = 3*x + y;
float delta = result3(x,y) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result3(x,y), correct);
return -1;
}
}
}
}
{
// Test interleave 4 vectors:
Func f1, f2, f3, f4, f5;
f1(x) = sin(x);
f2(x) = sin(2*x);
f3(x) = sin(3*x);
f4(x) = sin(4*x);
f5(x) = sin(5*x);
Func output4;
output4(x, y) = select(y == 0, f1(x),
y == 1, f2(x),
y == 2, f3(x),
f4(x));
output4
.reorder(y, x)
.bound(y, 0, 4)
.unroll(y)
.vectorize(x, 4);
output4.output_buffer()
.set_min(1, 0)
.set_stride(0, 4)
.set_stride(1, 1)
.set_extent(1, 4);
check_interleave_count(output4, 1);
Buffer buff4;
buff4 = Buffer(Float(32), 16, 4, 0, 0, (uint8_t *)0);
buff4.raw_buffer()->stride[0] = 4;
buff4.raw_buffer()->stride[1] = 1;
Realization r4({buff4});
output4.realize(r4);
Image<float> result4 = r4[0];
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 4; y++) {
float correct = sin((y+1)*x);
float delta = result4(x,y) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result4(x,y), correct);
return -1;
}
}
}
// Test interleave 5 vectors:
Func output5;
output5(x, y) = select(y == 0, f1(x),
y == 1, f2(x),
y == 2, f3(x),
y == 3, f4(x),
f5(x));
output5
.reorder(y, x)
.bound(y, 0, 5)
.unroll(y)
.vectorize(x, 4);
output5.output_buffer()
.set_min(1, 0)
.set_stride(0, 5)
.set_stride(1, 1)
.set_extent(1, 5);
check_interleave_count(output5, 1);
Buffer buff5;
buff5 = Buffer(Float(32), 16, 5, 0, 0, (uint8_t *)0);
buff5.raw_buffer()->stride[0] = 5;
buff5.raw_buffer()->stride[1] = 1;
Realization r5({buff5});
output5.realize(r5);
Image<float> result5 = r5[0];
for (int x = 0; x < 16; x++) {
for (int y = 0; y < 5; y++) {
float correct = sin((y+1)*x);
float delta = result5(x,y) - correct;
if (delta > 0.01 || delta < -0.01) {
printf("result(%d) = %f instead of %f\n", x, result5(x,y), correct);
return -1;
}
}
}
}
{
// Test interleaving inside of nested blocks
Func f1, f2, f3, f4, f5;
f1(x) = sin(x);
f1.compute_root();
f2(x) = sin(2*x);
f2.compute_root();
Func unrolled;
unrolled(x, y) = select(x % 2 == 0, f1(x), f2(x)) + y;
Var xi, yi;
unrolled.tile(x, y, xi, yi, 2, 2).vectorize(x, 4).unroll(xi).unroll(yi).unroll(x, 2);
check_interleave_count(unrolled, 4);
}
{
// Make sure we don't interleave when the reordering would change the meaning.
Image<uint8_t> ref;
for (int i = 0; i < 2; i++) {
Func output6;
output6(x, y) = cast<uint8_t>(x);
RDom r(0, 16);
// A not-safe-to-merge pair of updates
output6(2*r, 0) = cast<uint8_t>(3);
output6(2*r+1, 0) = output6(2*r, 0)+2;
// A safe-to-merge pair of updates
output6(2*r, 1) = cast<uint8_t>(3);
output6(2*r+1, 1) = cast<uint8_t>(4);
// A safe-to-merge-but-not-complete triple of updates:
output6(3*r, 3) = cast<uint8_t>(3);
output6(3*r+1, 3) = cast<uint8_t>(4);
// A safe-to-merge-but-we-don't pair of updates, because they
// load recursively, so we conservatively bail out.
output6(2*r, 2) += 1;
output6(2*r+1, 2) += 2;
// A safe-to-merge triple of updates:
output6(3*r, 3) = cast<uint8_t>(7);
output6(3*r+2, 3) = cast<uint8_t>(9);
output6(3*r+1, 3) = cast<uint8_t>(8);
if (i == 0) {
// Making the reference output.
ref = output6.realize(50, 4);
} else {
// Vectorize and compare to the reference.
for (int j = 0; j < 11; j++) {
output6.update(j).vectorize(r);
}
check_interleave_count(output6, 2);
Image<uint8_t> out = output6.realize(50, 4);
for (int y = 0; y < ref.height(); y++) {
for (int x = 0; x < ref.width(); x++) {
if (out(x, y) != ref(x, y)) {
printf("result(%d, %d) = %d instead of %d\n",
x, y, out(x, y), ref(x, y));
return -1;
}
}
}
}
}
}
{
// Test that transposition works when vectorizing either dimension:
Func square("square");
square(x, y) = cast(UInt(16), 5*x + y);
Func trans1("trans1");
trans1(x, y) = square(y, x);
Func trans2("trans2");
trans2(x, y) = square(y, x);
square.compute_root()
.bound(x, 0, 8)
.bound(y, 0, 8);
trans1.compute_root()
.bound(x, 0, 8)
.bound(y, 0, 8)
.vectorize(x)
.unroll(y);
trans2.compute_root()
.bound(x, 0, 8)
.bound(y, 0, 8)
.unroll(x)
.vectorize(y);
trans1.output_buffer()
.set_min(0,0).set_min(1,0)
.set_stride(0,1).set_stride(1,8)
.set_extent(0,8).set_extent(1,8);
trans2.output_buffer()
.set_min(0,0).set_min(1,0)
.set_stride(0,1).set_stride(1,8)
.set_extent(0,8).set_extent(1,8);
Image<uint16_t> result6(8,8);
Image<uint16_t> result7(8,8);
trans1.realize(result6);
trans2.realize(result7);
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
int correct = 5*y + x;
if (result6(x,y) != correct) {
printf("result(%d) = %d instead of %d\n", x, result6(x,y), correct);
return -1;
}
if (result7(x,y) != correct) {
printf("result(%d) = %d instead of %d\n", x, result7(x,y), correct);
return -1;
}
}
}
check_interleave_count(trans1, 1);
check_interleave_count(trans2, 1);
}
printf("Success!\n");
return 0;
}
| Add missing arg to test | Add missing arg to test
| C++ | mit | kgnk/Halide,lglucin/Halide,dougkwan/Halide,adasworks/Halide,myrtleTree33/Halide,fengzhyuan/Halide,myrtleTree33/Halide,ayanazmat/Halide,tdenniston/Halide,tdenniston/Halide,myrtleTree33/Halide,fengzhyuan/Halide,rodrigob/Halide,ronen/Halide,mcanthony/Halide,kgnk/Halide,psuriana/Halide,delcypher/Halide,psuriana/Halide,fengzhyuan/Halide,lglucin/Halide,kenkuang1213/Halide,myrtleTree33/Halide,dan-tull/Halide,mcanthony/Halide,ayanazmat/Halide,damienfir/Halide,damienfir/Halide,dan-tull/Halide,kenkuang1213/Halide,kenkuang1213/Halide,delcypher/Halide,smxlong/Halide,aam/Halide,lglucin/Halide,tdenniston/Halide,damienfir/Halide,mcanthony/Halide,fengzhyuan/Halide,damienfir/Halide,kgnk/Halide,delcypher/Halide,dougkwan/Halide,tdenniston/Halide,smxlong/Halide,adasworks/Halide,mcanthony/Halide,delcypher/Halide,myrtleTree33/Halide,psuriana/Halide,mcanthony/Halide,dougkwan/Halide,rodrigob/Halide,aam/Halide,aam/Halide,lglucin/Halide,delcypher/Halide,ayanazmat/Halide,rodrigob/Halide,smxlong/Halide,aam/Halide,smxlong/Halide,kgnk/Halide,ayanazmat/Halide,ronen/Halide,lglucin/Halide,psuriana/Halide,kenkuang1213/Halide,kgnk/Halide,delcypher/Halide,ayanazmat/Halide,rodrigob/Halide,damienfir/Halide,fengzhyuan/Halide,delcypher/Halide,tdenniston/Halide,dougkwan/Halide,dougkwan/Halide,aam/Halide,ronen/Halide,myrtleTree33/Halide,kgnk/Halide,psuriana/Halide,ronen/Halide,psuriana/Halide,jiawen/Halide,lglucin/Halide,psuriana/Halide,adasworks/Halide,aam/Halide,myrtleTree33/Halide,jiawen/Halide,dan-tull/Halide,jiawen/Halide,adasworks/Halide,jiawen/Halide,adasworks/Halide,kenkuang1213/Halide,adasworks/Halide,aam/Halide,adasworks/Halide,mcanthony/Halide,adasworks/Halide,mcanthony/Halide,damienfir/Halide,jiawen/Halide,dan-tull/Halide,kgnk/Halide,kenkuang1213/Halide,rodrigob/Halide,dougkwan/Halide,smxlong/Halide,rodrigob/Halide,ronen/Halide,damienfir/Halide,myrtleTree33/Halide,dan-tull/Halide,dougkwan/Halide,kgnk/Halide,kenkuang1213/Halide,tdenniston/Halide,jiawen/Halide,tdenniston/Halide,smxlong/Halide,delcypher/Halide,ayanazmat/Halide,rodrigob/Halide,fengzhyuan/Halide,ayanazmat/Halide,mcanthony/Halide,dan-tull/Halide,dougkwan/Halide,tdenniston/Halide,dan-tull/Halide,smxlong/Halide,ronen/Halide,damienfir/Halide,dan-tull/Halide,smxlong/Halide,ayanazmat/Halide,fengzhyuan/Halide,ronen/Halide,rodrigob/Halide,fengzhyuan/Halide,jiawen/Halide,kenkuang1213/Halide,lglucin/Halide,ronen/Halide |
4a27cec8d3468fffb36e640b9782adefcccae414 | src/test/confutils.cc | src/test/confutils.cc | // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/ConfUtils.h"
#include "common/errno.h"
#include "gtest/gtest.h"
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
using std::cerr;
using std::ostringstream;
#define MAX_FILES_TO_DELETE 1000UL
static size_t config_idx = 0;
static size_t unlink_idx = 0;
static char *to_unlink[MAX_FILES_TO_DELETE];
static std::string get_temp_dir()
{
static std::string temp_dir;
if (temp_dir.empty()) {
const char *tmpdir = getenv("TMPDIR");
if (!tmpdir)
tmpdir = "/tmp";
srand(time(NULL));
ostringstream oss;
oss << tmpdir << "/confutils_test_dir." << rand() << "." << getpid();
umask(022);
int res = mkdir(oss.str().c_str(), 01777);
if (res) {
cerr << "failed to create temp directory '" << temp_dir << "'" << std::endl;
return "";
}
temp_dir = oss.str();
}
return temp_dir;
}
static void unlink_all(void)
{
for (size_t i = 0; i < unlink_idx; ++i) {
unlink(to_unlink[i]);
}
for (size_t i = 0; i < unlink_idx; ++i) {
free(to_unlink[i]);
}
rmdir(get_temp_dir().c_str());
}
static int create_tempfile(const std::string &fname, const char *text)
{
FILE *fp = fopen(fname.c_str(), "w");
if (!fp) {
int err = errno;
cerr << "Failed to write file '" << fname << "' to temp directory '"
<< get_temp_dir() << "'. " << cpp_strerror(err) << std::endl;
return err;
}
if (unlink_idx >= MAX_FILES_TO_DELETE)
return -ENOBUFS;
if (unlink_idx == 0) {
memset(to_unlink, 0, sizeof(to_unlink));
atexit(unlink_all);
}
to_unlink[unlink_idx++] = strdup(fname.c_str());
size_t strlen_text = strlen(text);
size_t res = fwrite(text, 1, strlen_text, fp);
if (res != strlen_text) {
int err = errno;
cerr << "fwrite error while writing to " << fname
<< ": " << cpp_strerror(err) << std::endl;
fclose(fp);
return err;
}
fclose(fp);
return 0;
}
static std::string next_tempfile(const char *text)
{
ostringstream oss;
std::string temp_dir(get_temp_dir());
if (temp_dir.empty())
return "";
oss << temp_dir << "/test_config." << config_idx++ << ".config";
int ret = create_tempfile(oss.str(), text);
if (ret)
return "";
return oss.str();
}
const char * const simple_conf_1 = "\
; here's a comment\n\
[global]\n\
keyring = .my_ceph_keyring\n\
\n\
[mds]\n\
log dir = out\n\
log per instance = true\n\
log sym history = 100\n\
profiling logger = true\n\
profiling logger dir = wowsers\n\
chdir = ""\n\
pid file = out/$name.pid\n\
\n\
mds debug frag = true\n\
[osd]\n\
pid file = out/$name.pid\n\
osd scrub load threshold = 5.0\n\
\n\
lockdep = 1\n\
[osd0]\n\
osd data = dev/osd0\n\
osd journal size = 100\n\
[mds.a]\n\
[mds.b]\n\
[mds.c]\n\
";
// we can add whitespace at odd locations and it will get stripped out.
const char * const simple_conf_2 = "\
[mds.a]\n\
log dir = special_mds_a\n\
[mds]\n\
log sym history = 100\n\
log dir = out # after a comment, anything # can ### happen ;;; right?\n\
log per instance = true\n\
profiling logger = true\n\
profiling logger dir = log\n\
chdir = ""\n\
pid file\t=\tfoo2\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
\n\
[global]\n\
# I like pound signs as comment markers.\n\
; Do you like pound signs as comment markers?\n\
keyring = shenanigans ; The keyring of a leprechaun\n\
\n\
# Let's just have a line with a lot of whitespace and nothing else.\n\
\n\
lockdep = 1\n\
";
// test line-combining
const char * const conf3 = "\
[global]\n\
log file = /quite/a/long/path\\\n\
/for/a/log/file\n\
pid file = \\\n\
spork\\\n\
\n\
[mon] #nothing here \n\
";
// illegal because it contains an invalid utf8 sequence.
const char illegal_conf1[] = "\
[global]\n\
log file = foo\n\
pid file = invalid-utf-\xe2\x28\xa1\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
";
// illegal because it contains a malformed section header.
const char illegal_conf2[] = "\
[global\n\
log file = foo\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
";
// illegal because it contains a line that doesn't parse
const char illegal_conf3[] = "\
[global]\n\
who_what_where\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
";
TEST(ParseFiles1, ConfUtils) {
std::string simple_conf_1_f(next_tempfile(simple_conf_1));
ConfFile cf1(simple_conf_1_f.c_str());
ASSERT_EQ(cf1.parse(), 0);
std::string simple_conf_2_f(next_tempfile(simple_conf_1));
ConfFile cf2(simple_conf_2_f.c_str());
ASSERT_EQ(cf2.parse(), 0);
bufferlist bl3;
bl3.append(simple_conf_1, strlen(simple_conf_1));
ConfFile cf3(&bl3);
ASSERT_EQ(cf3.parse(), 0);
bufferlist bl4;
bl4.append(simple_conf_2, strlen(simple_conf_2));
ConfFile cf4(&bl4);
ASSERT_EQ(cf4.parse(), 0);
}
TEST(ReadFiles1, ConfUtils) {
std::string simple_conf_1_f(next_tempfile(simple_conf_1));
ConfFile cf1(simple_conf_1_f.c_str());
ASSERT_EQ(cf1.parse(), 0);
std::string val;
ASSERT_EQ(cf1.read("global", "keyring", val), 0);
ASSERT_EQ(val, ".my_ceph_keyring");
ASSERT_EQ(cf1.read("mds", "profiling logger dir", val), 0);
ASSERT_EQ(val, "wowsers");
ASSERT_EQ(cf1.read("mds", "something that does not exist", val), -ENOENT);
// exists in mds section, but not in global
ASSERT_EQ(cf1.read("global", "profiling logger dir", val), -ENOENT);
bufferlist bl2;
bl2.append(simple_conf_2, strlen(simple_conf_2));
ConfFile cf2(&bl2);
ASSERT_EQ(cf2.parse(), 0);
ASSERT_EQ(cf2.read("osd0", "keyring", val), 0);
ASSERT_EQ(val, "osd_keyring");
ASSERT_EQ(cf2.read("mds", "pid file", val), 0);
ASSERT_EQ(val, "foo2");
ASSERT_EQ(cf2.read("nonesuch", "keyring", val), -ENOENT);
}
TEST(ReadFiles2, ConfUtils) {
std::string conf3_f(next_tempfile(conf3));
ConfFile cf1(conf3_f.c_str());
std::string val;
ASSERT_EQ(cf1.parse(), 0);
ASSERT_EQ(cf1.read("global", "log file", val), 0);
ASSERT_EQ(val, "/quite/a/long/path/for/a/log/file");
ASSERT_EQ(cf1.read("global", "pid file", val), 0);
ASSERT_EQ(val, "spork");
}
// FIXME: illegal configuration files don't return a parse error currently.
TEST(IllegalFiles, ConfUtils) {
std::string illegal_conf1_f(next_tempfile(illegal_conf1));
ConfFile cf1(illegal_conf1_f.c_str());
std::string val;
ASSERT_EQ(cf1.parse(), 0);
bufferlist bl2;
bl2.append(illegal_conf2, strlen(illegal_conf2));
ConfFile cf2(&bl2);
ASSERT_EQ(cf2.parse(), 0);
std::string illegal_conf3_f(next_tempfile(illegal_conf3));
ConfFile cf3(illegal_conf3_f.c_str());
ASSERT_EQ(cf3.parse(), 0);
}
| // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2011 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "common/ConfUtils.h"
#include "common/errno.h"
#include "gtest/gtest.h"
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
using std::cerr;
using std::ostringstream;
#define MAX_FILES_TO_DELETE 1000UL
static size_t config_idx = 0;
static size_t unlink_idx = 0;
static char *to_unlink[MAX_FILES_TO_DELETE];
static std::string get_temp_dir()
{
static std::string temp_dir;
if (temp_dir.empty()) {
const char *tmpdir = getenv("TMPDIR");
if (!tmpdir)
tmpdir = "/tmp";
srand(time(NULL));
ostringstream oss;
oss << tmpdir << "/confutils_test_dir." << rand() << "." << getpid();
umask(022);
int res = mkdir(oss.str().c_str(), 01777);
if (res) {
cerr << "failed to create temp directory '" << temp_dir << "'" << std::endl;
return "";
}
temp_dir = oss.str();
}
return temp_dir;
}
static void unlink_all(void)
{
for (size_t i = 0; i < unlink_idx; ++i) {
unlink(to_unlink[i]);
}
for (size_t i = 0; i < unlink_idx; ++i) {
free(to_unlink[i]);
}
rmdir(get_temp_dir().c_str());
}
static int create_tempfile(const std::string &fname, const char *text)
{
FILE *fp = fopen(fname.c_str(), "w");
if (!fp) {
int err = errno;
cerr << "Failed to write file '" << fname << "' to temp directory '"
<< get_temp_dir() << "'. " << cpp_strerror(err) << std::endl;
return err;
}
if (unlink_idx >= MAX_FILES_TO_DELETE)
return -ENOBUFS;
if (unlink_idx == 0) {
memset(to_unlink, 0, sizeof(to_unlink));
atexit(unlink_all);
}
to_unlink[unlink_idx++] = strdup(fname.c_str());
size_t strlen_text = strlen(text);
size_t res = fwrite(text, 1, strlen_text, fp);
if (res != strlen_text) {
int err = errno;
cerr << "fwrite error while writing to " << fname
<< ": " << cpp_strerror(err) << std::endl;
fclose(fp);
return err;
}
fclose(fp);
return 0;
}
static std::string next_tempfile(const char *text)
{
ostringstream oss;
std::string temp_dir(get_temp_dir());
if (temp_dir.empty())
return "";
oss << temp_dir << "/test_config." << config_idx++ << ".config";
int ret = create_tempfile(oss.str(), text);
if (ret)
return "";
return oss.str();
}
const char * const simple_conf_1 = "\
; here's a comment\n\
[global]\n\
keyring = .my_ceph_keyring\n\
\n\
[mds]\n\
log dir = out\n\
log per instance = true\n\
log sym history = 100\n\
profiling logger = true\n\
profiling logger dir = wowsers\n\
chdir = ""\n\
pid file = out/$name.pid\n\
\n\
mds debug frag = true\n\
[osd]\n\
pid file = out/$name.pid\n\
osd scrub load threshold = 5.0\n\
\n\
lockdep = 1\n\
[osd0]\n\
osd data = dev/osd0\n\
osd journal size = 100\n\
[mds.a]\n\
[mds.b]\n\
[mds.c]\n\
";
// we can add whitespace at odd locations and it will get stripped out.
const char * const simple_conf_2 = "\
[mds.a]\n\
log dir = special_mds_a\n\
[mds]\n\
log sym history = 100\n\
log dir = out # after a comment, anything # can ### happen ;;; right?\n\
log per instance = true\n\
profiling logger = true\n\
profiling logger dir = log\n\
chdir = ""\n\
pid file\t=\tfoo2\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
\n\
[global]\n\
# I like pound signs as comment markers.\n\
; Do you like pound signs as comment markers?\n\
keyring = shenanigans ; The keyring of a leprechaun\n\
\n\
# Let's just have a line with a lot of whitespace and nothing else.\n\
\n\
lockdep = 1\n\
";
// test line-combining
const char * const conf3 = "\
[global]\n\
log file = /quite/a/long/path\\\n\
/for/a/log/file\n\
pid file = \\\n\
spork\\\n\
\n\
[mon] #nothing here \n\
";
// illegal because it contains an invalid utf8 sequence.
const char illegal_conf1[] = "\
[global]\n\
log file = foo\n\
pid file = invalid-utf-\xe2\x28\xa1\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
";
// illegal because it contains a malformed section header.
const char illegal_conf2[] = "\
[global\n\
log file = foo\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
";
// illegal because it contains a line that doesn't parse
const char illegal_conf3[] = "\
[global]\n\
who_what_where\n\
[osd0]\n\
keyring = osd_keyring ; osd's keyring\n\
";
// unicode config file
const char unicode_config_1[] = "\
[global]\n\
log file = \x66\xd1\x86\xd1\x9d\xd3\xad\xd3\xae \n\
pid file = foo-bar\n\
[osd0]\n\
";
TEST(ParseFiles1, ConfUtils) {
std::string simple_conf_1_f(next_tempfile(simple_conf_1));
ConfFile cf1(simple_conf_1_f.c_str());
ASSERT_EQ(cf1.parse(), 0);
std::string simple_conf_2_f(next_tempfile(simple_conf_1));
ConfFile cf2(simple_conf_2_f.c_str());
ASSERT_EQ(cf2.parse(), 0);
bufferlist bl3;
bl3.append(simple_conf_1, strlen(simple_conf_1));
ConfFile cf3(&bl3);
ASSERT_EQ(cf3.parse(), 0);
bufferlist bl4;
bl4.append(simple_conf_2, strlen(simple_conf_2));
ConfFile cf4(&bl4);
ASSERT_EQ(cf4.parse(), 0);
}
TEST(ReadFiles1, ConfUtils) {
std::string simple_conf_1_f(next_tempfile(simple_conf_1));
ConfFile cf1(simple_conf_1_f.c_str());
ASSERT_EQ(cf1.parse(), 0);
std::string val;
ASSERT_EQ(cf1.read("global", "keyring", val), 0);
ASSERT_EQ(val, ".my_ceph_keyring");
ASSERT_EQ(cf1.read("mds", "profiling logger dir", val), 0);
ASSERT_EQ(val, "wowsers");
ASSERT_EQ(cf1.read("mds", "something that does not exist", val), -ENOENT);
// exists in mds section, but not in global
ASSERT_EQ(cf1.read("global", "profiling logger dir", val), -ENOENT);
bufferlist bl2;
bl2.append(simple_conf_2, strlen(simple_conf_2));
ConfFile cf2(&bl2);
ASSERT_EQ(cf2.parse(), 0);
ASSERT_EQ(cf2.read("osd0", "keyring", val), 0);
ASSERT_EQ(val, "osd_keyring");
ASSERT_EQ(cf2.read("mds", "pid file", val), 0);
ASSERT_EQ(val, "foo2");
ASSERT_EQ(cf2.read("nonesuch", "keyring", val), -ENOENT);
}
TEST(ReadFiles2, ConfUtils) {
std::string conf3_f(next_tempfile(conf3));
ConfFile cf1(conf3_f.c_str());
std::string val;
ASSERT_EQ(cf1.parse(), 0);
ASSERT_EQ(cf1.read("global", "log file", val), 0);
ASSERT_EQ(val, "/quite/a/long/path/for/a/log/file");
ASSERT_EQ(cf1.read("global", "pid file", val), 0);
ASSERT_EQ(val, "spork");
std::string unicode_config_1f(next_tempfile(unicode_config_1));
ConfFile cf2(unicode_config_1f.c_str());
ASSERT_EQ(cf2.parse(), 0);
ASSERT_EQ(cf2.read("global", "log file", val), 0);
ASSERT_EQ(val, "\x66\xd1\x86\xd1\x9d\xd3\xad\xd3\xae");
}
// FIXME: illegal configuration files don't return a parse error currently.
TEST(IllegalFiles, ConfUtils) {
std::string illegal_conf1_f(next_tempfile(illegal_conf1));
ConfFile cf1(illegal_conf1_f.c_str());
std::string val;
ASSERT_EQ(cf1.parse(), 0);
bufferlist bl2;
bl2.append(illegal_conf2, strlen(illegal_conf2));
ConfFile cf2(&bl2);
ASSERT_EQ(cf2.parse(), 0);
std::string illegal_conf3_f(next_tempfile(illegal_conf3));
ConfFile cf3(illegal_conf3_f.c_str());
ASSERT_EQ(cf3.parse(), 0);
}
| test unicode parsing | confutils: test unicode parsing
Signed-off-by: Colin McCabe <[email protected]>
| C++ | lgpl-2.1 | ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph |
fef70e3136cbe10831d8a47d3fae2ff1f984330a | src/views/ds3_browser.cc | src/views/ds3_browser.cc | /*
* *****************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*/
#include <QMenu>
#include "lib/client.h"
#include "lib/logger.h"
#include "models/ds3_browser_model.h"
#include "models/session.h"
#include "views/buckets/new_bucket_dialog.h"
#include "views/ds3_browser.h"
#include "views/jobs_view.h"
DS3Browser::DS3Browser(Client* client, JobsView* jobsView,
QWidget* parent, Qt::WindowFlags flags)
: Browser(client, parent, flags),
m_jobsView(jobsView)
{
AddCustomToolBarActions();
m_model = new DS3BrowserModel(m_client, this);
m_model->SetView(m_treeView);
m_treeView->setModel(m_model);
connect(m_treeView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(OnModelItemClick(const QModelIndex&)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
this, SLOT(HandleJobUpdate(const Job)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
m_jobsView, SLOT(UpdateJob(const Job)));
}
void
DS3Browser::HandleJobUpdate(const Job job)
{
Job::State state = job.GetState();
if (state == Job::FINISHED) {
Refresh();
}
}
void
DS3Browser::AddCustomToolBarActions()
{
m_rootAction = new QAction(QIcon(":/resources/icons/root_directory.png"),
"Root directory", this);
connect(m_rootAction, SIGNAL(triggered()), this, SLOT(GoToRoot()));
m_toolBar->addAction(m_rootAction);
m_refreshAction = new QAction(style()->standardIcon(QStyle::SP_BrowserReload),
"Refresh", this);
connect(m_refreshAction, SIGNAL(triggered()), this, SLOT(Refresh()));
m_toolBar->addAction(m_refreshAction);
}
QString
DS3Browser::IndexToPath(const QModelIndex& index) const
{
return m_model->GetPath(index);
}
void
DS3Browser::OnContextMenuRequested(const QPoint& /*pos*/)
{
QMenu menu;
QAction newBucketAction("New Bucket", &menu);
QModelIndex index = m_treeView->rootIndex();
if (!index.isValid()) {
// "New Bucket" is only displayed when at the root (the
// page that lists all buckets).
menu.addAction(&newBucketAction);
}
QAction* selectedAction = menu.exec(QCursor::pos());
if (!selectedAction)
{
return;
}
if (selectedAction == &newBucketAction)
{
CreateBucket();
}
}
void
DS3Browser::CreateBucket()
{
NewBucketDialog newBucketDialog(m_client);
if (newBucketDialog.exec() == QDialog::Rejected) {
return;
}
Refresh();
}
void
DS3Browser::OnModelItemDoubleClick(const QModelIndex& index)
{
if (m_model->IsBucketOrFolder(index)) {
QString path = IndexToPath(index);
m_treeView->setRootIndex(index);
UpdatePathLabel(path);
}
}
void
DS3Browser::Refresh()
{
QModelIndex index = m_treeView->rootIndex();
if (m_model->IsFetching(index)) {
return;
}
m_model->Refresh(index);
QString path = IndexToPath(index);
UpdatePathLabel(path);
m_treeView->setRootIndex(index);
}
void
DS3Browser::OnModelItemClick(const QModelIndex& index)
{
if (m_model->IsPageBreak(index)) {
m_model->fetchMore(index.parent());
}
}
| /*
* *****************************************************************************
* Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License
* is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*/
#include <QMenu>
#include "lib/client.h"
#include "lib/logger.h"
#include "models/ds3_browser_model.h"
#include "models/session.h"
#include "views/buckets/new_bucket_dialog.h"
#include "views/ds3_browser.h"
#include "views/jobs_view.h"
DS3Browser::DS3Browser(Client* client, JobsView* jobsView,
QWidget* parent, Qt::WindowFlags flags)
: Browser(client, parent, flags),
m_jobsView(jobsView)
{
AddCustomToolBarActions();
m_model = new DS3BrowserModel(m_client, this);
m_model->SetView(m_treeView);
m_treeView->setModel(m_model);
connect(m_treeView, SIGNAL(clicked(const QModelIndex&)),
this, SLOT(OnModelItemClick(const QModelIndex&)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
this, SLOT(HandleJobUpdate(const Job)));
connect(m_client, SIGNAL(JobProgressUpdate(const Job)),
m_jobsView, SLOT(UpdateJob(const Job)));
}
void
DS3Browser::HandleJobUpdate(const Job job)
{
Job::State state = job.GetState();
if (state == Job::FINISHED) {
Refresh();
}
}
void
DS3Browser::AddCustomToolBarActions()
{
m_rootAction = new QAction(QIcon(":/resources/icons/root_directory.png"),
"Root directory", this);
connect(m_rootAction, SIGNAL(triggered()), this, SLOT(GoToRoot()));
m_toolBar->addAction(m_rootAction);
m_refreshAction = new QAction(style()->standardIcon(QStyle::SP_BrowserReload),
"Refresh", this);
connect(m_refreshAction, SIGNAL(triggered()), this, SLOT(Refresh()));
m_toolBar->addAction(m_refreshAction);
}
QString
DS3Browser::IndexToPath(const QModelIndex& index) const
{
return m_model->GetPath(index);
}
void
DS3Browser::OnContextMenuRequested(const QPoint& /*pos*/)
{
QMenu menu;
QAction newBucketAction("New Bucket", &menu);
QModelIndex index = m_treeView->rootIndex();
bool atBucketListingLevel = !index.isValid();
if (atBucketListingLevel) {
menu.addAction(&newBucketAction);
}
QAction* selectedAction = menu.exec(QCursor::pos());
if (!selectedAction)
{
return;
}
if (selectedAction == &newBucketAction)
{
CreateBucket();
}
}
void
DS3Browser::CreateBucket()
{
NewBucketDialog newBucketDialog(m_client);
if (newBucketDialog.exec() == QDialog::Rejected) {
return;
}
Refresh();
}
void
DS3Browser::OnModelItemDoubleClick(const QModelIndex& index)
{
if (m_model->IsBucketOrFolder(index)) {
QString path = IndexToPath(index);
m_treeView->setRootIndex(index);
UpdatePathLabel(path);
}
}
void
DS3Browser::Refresh()
{
QModelIndex index = m_treeView->rootIndex();
if (m_model->IsFetching(index)) {
return;
}
m_model->Refresh(index);
QString path = IndexToPath(index);
UpdatePathLabel(path);
m_treeView->setRootIndex(index);
}
void
DS3Browser::OnModelItemClick(const QModelIndex& index)
{
if (m_model->IsPageBreak(index)) {
m_model->fetchMore(index.parent());
}
}
| Make DS3Browser::OnContextMenuRequested slightly more self-documenting. Remove a comment that is now no longer necessary as a result. | Make DS3Browser::OnContextMenuRequested slightly more self-documenting.
Remove a comment that is now no longer necessary as a result.
| C++ | apache-2.0 | SpectraLogic/ds3_browser,Klopsch/ds3_browser,Klopsch/ds3_browser,Klopsch/ds3_browser,SpectraLogic/ds3_browser,SpectraLogic/ds3_browser |
622df1eae9d4954c1b50bcf85fb6a62fb0651667 | tests/connection/connection.cpp | tests/connection/connection.cpp | /*
Copyright 2015 University of Auckland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.Some license of other
*/
#include "gtest/gtest.h"
#include <libcellml>
TEST(Variable, addAndGetEquivalentVariable) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
EXPECT_EQ(v2,v1->getEquivalentVariable(0));
}
TEST(Variable, addAndGetEquivalentVariableReciprocal) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
EXPECT_EQ(v1,v2->getEquivalentVariable(0));
}
TEST(Variable, addTwoEquivalentVariablesAndCount) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v3);
size_t e = 2;
size_t a = v1->equivalentVariableCount();
EXPECT_EQ(e, a);
}
TEST(Variable, addDuplicateEquivalentVariablesAndCount) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v2,v1);
libcellml::Variable::addEquivalence(v2,v1);
size_t e = 1;
size_t a = v1->equivalentVariableCount();
EXPECT_EQ(e, a);
}
TEST(Variable, hasEquivalentVariable) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
EXPECT_EQ(true,v1->hasEquivalentVariable(v2));
}
TEST(Connection, componentlessVariableInvalidConnection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection>"
"<map_components component1_1=\"component1\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr comp1 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
comp1->setName("component1");
v1->setName("variable1");
v2->setName("variable2");
comp1->addVariable(v1);
m.addComponent(comp1);
libcellml::Variable::addEquivalence(v1,v2);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, validConnection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<component name=\"component2\">"
"<variable name=\"variable2\"/>"
"</component>"
"<connection>"
"<map_components component_1=\"component1\" component_2=\"component2\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr comp1 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr comp2 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
comp1->setName("component1");
comp2->setName("component2");
v1->setName("variable1");
v2->setName("variable2");
comp1->addVariable(v1);
comp2->addVariable(v2);
m.addComponent(comp1);
m.addComponent(comp2);
libcellml::Variable::addEquivalence(v1,v2);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, twoMapVariablesConnection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"component1\">"
"<variable name=\"variable11\"/>"
"<variable name=\"variable12\"/>"
"</component>"
"<component name=\"component2\">"
"<variable name=\"variable21\"/>"
"<variable name=\"variable22\"/>"
"</component>"
"<connection>"
"<map_components component_1=\"component1\" component_2=\"component2\"/>"
"<map_variables variable_1=\"variable11\" variable_2=\"variable21\"/>"
"<map_variables variable_1=\"variable12\" variable_2=\"variable22\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr comp1 = std::make_shared<libcellml::Component>();
comp1->setName("component1");
libcellml::ComponentPtr comp2 = std::make_shared<libcellml::Component>();
comp2->setName("component2");
libcellml::VariablePtr v11 = std::make_shared<libcellml::Variable>();
v11->setName("variable11");
libcellml::VariablePtr v12 = std::make_shared<libcellml::Variable>();
v12->setName("variable12");
libcellml::VariablePtr v21 = std::make_shared<libcellml::Variable>();
v21->setName("variable21");
libcellml::VariablePtr v22 = std::make_shared<libcellml::Variable>();
v22->setName("variable22");
comp1->addVariable(v11);
comp1->addVariable(v12);
comp2->addVariable(v21);
comp2->addVariable(v22);
m.addComponent(comp1);
m.addComponent(comp2);
libcellml::Variable::addEquivalence(v11,v21);
libcellml::Variable::addEquivalence(v12,v22);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, twoEncapsulatedChildComponentsWithConnectionsAndMixedInterfaces) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"parent_component\">"
"<variable name=\"variable1\" interface=\"private\"/>"
"</component>"
"<component name=\"child1\">"
"<variable name=\"variable2\" interface=\"public\"/>"
"</component>"
"<component name=\"child2\">"
"<variable name=\"variable3\" interface=\"public\"/>"
"</component>"
"<encapsulation>"
"<component_ref component=\"parent_component\">"
"<component_ref component=\"child1\"/>"
"<component_ref component=\"child2\"/>"
"</component_ref>"
"</encapsulation>"
"<connection>"
"<map_components component_2=\"parent_component\" component_1=\"child1\"/>"
"<map_variables variable_2=\"variable1\" variable_1=\"variable2\"/>"
"</connection>"
"<connection>"
"<map_components component_2=\"parent_component\" component_1=\"child2\"/>"
"<map_variables variable_2=\"variable1\" variable_1=\"variable3\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr parent = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child1 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child2 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
parent->setName("parent_component");
child1->setName("child1");
child2->setName("child2");
v1->setName("variable1");
v2->setName("variable2");
v3->setName("variable3");
m.addComponent(parent);
parent->addComponent(child1);
parent->addComponent(child2);
parent->addVariable(v1);
child1->addVariable(v2);
child2->addVariable(v3);
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v3);
v1->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PRIVATE);
v2->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
v3->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, twoEncapsulatedChildComponentsWithConnectionsAndPublicInterfaces) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"parent_component\">"
"<variable name=\"variable1\" interface=\"public\"/>"
"</component>"
"<component name=\"child1\">"
"<variable name=\"variable2\" interface=\"public\"/>"
"</component>"
"<component name=\"child2\">"
"<variable name=\"variable3\" interface=\"public\"/>"
"</component>"
"<encapsulation>"
"<component_ref component=\"parent_component\">"
"<component_ref component=\"child1\"/>"
"<component_ref component=\"child2\"/>"
"</component_ref>"
"</encapsulation>"
"<connection>"
"<map_components component_2=\"parent_component\" component_1=\"child1\"/>"
"<map_variables variable_2=\"variable1\" variable_1=\"variable2\"/>"
"</connection>"
"<connection>"
"<map_components component_2=\"parent_component\" component_1=\"child2\"/>"
"<map_variables variable_2=\"variable1\" variable_1=\"variable3\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr parent = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child1 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child2 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
parent->setName("parent_component");
child1->setName("child1");
child2->setName("child2");
v1->setName("variable1");
v2->setName("variable2");
v3->setName("variable3");
m.addComponent(parent);
parent->addComponent(child1);
parent->addComponent(child2);
parent->addVariable(v1);
child1->addVariable(v2);
child2->addVariable(v3);
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v3);
v1->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
v2->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
v3->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
| /*
Copyright 2015 University of Auckland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.Some license of other
*/
#include "gtest/gtest.h"
#include <libcellml>
TEST(Variable, addAndGetEquivalentVariable) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
EXPECT_EQ(v2,v1->getEquivalentVariable(0));
}
TEST(Variable, addAndGetEquivalentVariableReciprocal) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
EXPECT_EQ(v1,v2->getEquivalentVariable(0));
}
TEST(Variable, addTwoEquivalentVariablesAndCount) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v3);
size_t e = 2;
size_t a = v1->equivalentVariableCount();
EXPECT_EQ(e, a);
}
TEST(Variable, addDuplicateEquivalentVariablesAndCount) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v2,v1);
libcellml::Variable::addEquivalence(v2,v1);
size_t e = 1;
size_t a = v1->equivalentVariableCount();
EXPECT_EQ(e, a);
}
TEST(Variable, hasEquivalentVariable) {
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::Variable::addEquivalence(v1,v2);
EXPECT_EQ(true,v1->hasEquivalentVariable(v2));
}
TEST(Connection, componentlessVariableInvalidConnection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<connection>"
"<map_components component_1=\"component1\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr comp1 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
comp1->setName("component1");
v1->setName("variable1");
v2->setName("variable2");
comp1->addVariable(v1);
m.addComponent(comp1);
libcellml::Variable::addEquivalence(v1,v2);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, validConnection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<component name=\"component2\">"
"<variable name=\"variable2\"/>"
"</component>"
"<connection>"
"<map_components component_1=\"component1\" component_2=\"component2\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr comp1 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr comp2 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
comp1->setName("component1");
comp2->setName("component2");
v1->setName("variable1");
v2->setName("variable2");
comp1->addVariable(v1);
comp2->addVariable(v2);
m.addComponent(comp1);
m.addComponent(comp2);
libcellml::Variable::addEquivalence(v1,v2);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, twoMapVariablesConnection) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"component1\">"
"<variable name=\"variable11\"/>"
"<variable name=\"variable12\"/>"
"</component>"
"<component name=\"component2\">"
"<variable name=\"variable21\"/>"
"<variable name=\"variable22\"/>"
"</component>"
"<connection>"
"<map_components component_1=\"component1\" component_2=\"component2\"/>"
"<map_variables variable_1=\"variable11\" variable_2=\"variable21\"/>"
"<map_variables variable_1=\"variable12\" variable_2=\"variable22\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr comp1 = std::make_shared<libcellml::Component>();
comp1->setName("component1");
libcellml::ComponentPtr comp2 = std::make_shared<libcellml::Component>();
comp2->setName("component2");
libcellml::VariablePtr v11 = std::make_shared<libcellml::Variable>();
v11->setName("variable11");
libcellml::VariablePtr v12 = std::make_shared<libcellml::Variable>();
v12->setName("variable12");
libcellml::VariablePtr v21 = std::make_shared<libcellml::Variable>();
v21->setName("variable21");
libcellml::VariablePtr v22 = std::make_shared<libcellml::Variable>();
v22->setName("variable22");
comp1->addVariable(v11);
comp1->addVariable(v12);
comp2->addVariable(v21);
comp2->addVariable(v22);
m.addComponent(comp1);
m.addComponent(comp2);
libcellml::Variable::addEquivalence(v11,v21);
libcellml::Variable::addEquivalence(v12,v22);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, twoValidConnections) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"component1\">"
"<variable name=\"variable1\"/>"
"</component>"
"<component name=\"component2\">"
"<variable name=\"variable2\"/>"
"</component>"
"<component name=\"component3\">"
"<variable name=\"variable3\"/>"
"</component>"
"<connection>"
"<map_components component_1=\"component1\" component_2=\"component2\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"<connection>"
"<map_components component_1=\"component1\" component_2=\"component3\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable3\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr comp1 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr comp2 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr comp3 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
comp1->setName("component1");
comp2->setName("component2");
comp3->setName("component3");
v1->setName("variable1");
v2->setName("variable2");
v3->setName("variable3");
comp1->addVariable(v1);
comp2->addVariable(v2);
comp3->addVariable(v3);
m.addComponent(comp1);
m.addComponent(comp2);
m.addComponent(comp3);
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v3);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, twoEncapsulatedChildComponentsWithConnectionsAndMixedInterfaces) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"parent_component\">"
"<variable name=\"variable1\" interface=\"private\"/>"
"</component>"
"<component name=\"child1\">"
"<variable name=\"variable2\" interface=\"public\"/>"
"</component>"
"<component name=\"child2\">"
"<variable name=\"variable3\" interface=\"public\"/>"
"</component>"
"<encapsulation>"
"<component_ref component=\"parent_component\">"
"<component_ref component=\"child1\"/>"
"<component_ref component=\"child2\"/>"
"</component_ref>"
"</encapsulation>"
"<connection>"
"<map_components component_1=\"parent_component\" component_2=\"child1\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"<connection>"
"<map_components component_1=\"parent_component\" component_2=\"child2\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable3\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr parent = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child1 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child2 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
parent->setName("parent_component");
child1->setName("child1");
child2->setName("child2");
v1->setName("variable1");
v2->setName("variable2");
v3->setName("variable3");
m.addComponent(parent);
parent->addComponent(child1);
parent->addComponent(child2);
parent->addVariable(v1);
child1->addVariable(v2);
child2->addVariable(v3);
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v3);
v1->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PRIVATE);
v2->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
v3->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
TEST(Connection, twoEncapsulatedChildComponentsWithConnectionsAndPublicInterfaces) {
const std::string e =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<model xmlns=\"http://www.cellml.org/cellml/1.2#\">"
"<component name=\"parent_component\">"
"<variable name=\"variable1\" interface=\"public\"/>"
"</component>"
"<component name=\"child1\">"
"<variable name=\"variable2\" interface=\"public\"/>"
"</component>"
"<component name=\"child2\">"
"<variable name=\"variable3\" interface=\"public\"/>"
"</component>"
"<encapsulation>"
"<component_ref component=\"parent_component\">"
"<component_ref component=\"child1\"/>"
"<component_ref component=\"child2\"/>"
"</component_ref>"
"</encapsulation>"
"<connection>"
"<map_components component_1=\"parent_component\" component_2=\"child1\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable2\"/>"
"</connection>"
"<connection>"
"<map_components component_1=\"parent_component\" component_2=\"child2\"/>"
"<map_variables variable_1=\"variable1\" variable_2=\"variable3\"/>"
"</connection>"
"</model>";
libcellml::Model m;
libcellml::ComponentPtr parent = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child1 = std::make_shared<libcellml::Component>();
libcellml::ComponentPtr child2 = std::make_shared<libcellml::Component>();
libcellml::VariablePtr v1 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v2 = std::make_shared<libcellml::Variable>();
libcellml::VariablePtr v3 = std::make_shared<libcellml::Variable>();
parent->setName("parent_component");
child1->setName("child1");
child2->setName("child2");
v1->setName("variable1");
v2->setName("variable2");
v3->setName("variable3");
m.addComponent(parent);
parent->addComponent(child1);
parent->addComponent(child2);
parent->addVariable(v1);
child1->addVariable(v2);
child2->addVariable(v3);
libcellml::Variable::addEquivalence(v1,v2);
libcellml::Variable::addEquivalence(v1,v3);
v1->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
v2->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
v3->setInterfaceType(libcellml::Variable::INTERFACE_TYPE_PUBLIC);
std::string a = m.serialise(libcellml::FORMAT_XML);
EXPECT_EQ(e, a);
}
| add two connection test; test bugfixes | add two connection test; test bugfixes
| C++ | apache-2.0 | cellml/libcellml,nickerso/libcellml,cellml/libcellml,MichaelClerx/libcellml,hsorby/libcellml,hsorby/libcellml,hsorby/libcellml,libcellml/buildbot-testing,libcellml/buildbot-testing,cellml/libcellml,hsorby/libcellml,nickerso/libcellml,nickerso/libcellml,MichaelClerx/libcellml,cellml/libcellml,MichaelClerx/libcellml,nickerso/libcellml |
a8404ed7079e2aeeb415129f352d5c8ffe80bef5 | Rx/v2/src/rxcpp/operators/rx-filter.hpp | Rx/v2/src/rxcpp/operators/rx-filter.hpp | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_OPERATORS_RX_FILTER_HPP)
#define RXCPP_OPERATORS_RX_FILTER_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace operators {
namespace detail {
template<class T, class Observable, class Predicate>
struct filter : public operator_base<T>
{
typedef typename std::decay<Observable>::type source_type;
typedef typename std::decay<Predicate>::type test_type;
source_type source;
test_type test;
template<class CT, class CP>
static auto check(int) -> decltype((*(CP*)nullptr)(*(CT*)nullptr));
template<class CT, class CP>
static void check(...);
filter(source_type o, test_type p)
: source(std::move(o))
, test(std::move(p))
{
static_assert(std::is_convertible<decltype(check<T, test_type>(0)), bool>::value, "filter Predicate must be a function with the signature bool(T)");
}
template<class Subscriber>
void on_subscribe(const Subscriber& o) {
source.subscribe(
o,
// on_next
[this, o](T t) {
bool filtered = false;
try {
filtered = !this->test(t);
} catch(...) {
o.on_error(std::current_exception());
return;
}
if (!filtered) {
o.on_next(std::move(t));
}
},
// on_error
[o](std::exception_ptr e) {
o.on_error(e);
},
// on_completed
[o]() {
o.on_completed();
}
);
}
};
template<class Predicate>
class filter_factory
{
typedef typename std::decay<Predicate>::type test_type;
test_type predicate;
public:
filter_factory(test_type p) : predicate(std::move(p)) {}
template<class Observable>
auto operator()(Observable&& source)
-> observable<typename std::decay<Observable>::type::value_type, filter<typename std::decay<Observable>::type::value_type, Observable, Predicate>> {
return observable<typename std::decay<Observable>::type::value_type, filter<typename std::decay<Observable>::type::value_type, Observable, Predicate>>(
filter<typename std::decay<Observable>::type::value_type, Observable, Predicate>(std::forward<Observable>(source), std::move(predicate)));
}
};
}
template<class Predicate>
auto filter(Predicate&& p)
-> detail::filter_factory<Predicate> {
return detail::filter_factory<Predicate>(std::forward<Predicate>(p));
}
}
}
#endif
| // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
#pragma once
#if !defined(RXCPP_OPERATORS_RX_FILTER_HPP)
#define RXCPP_OPERATORS_RX_FILTER_HPP
#include "../rx-includes.hpp"
namespace rxcpp {
namespace operators {
namespace detail {
template<class T, class Observable, class Predicate>
struct filter : public operator_base<T>
{
typedef typename std::decay<Observable>::type source_type;
typedef typename std::decay<Predicate>::type test_type;
source_type source;
test_type test;
template<class CT, class CP>
static auto check(int) -> decltype((*(CP*)nullptr)(*(CT*)nullptr));
template<class CT, class CP>
static void check(...);
filter(source_type o, test_type p)
: source(std::move(o))
, test(std::move(p))
{
static_assert(std::is_convertible<decltype(check<T, test_type>(0)), bool>::value, "filter Predicate must be a function with the signature bool(T)");
}
template<class Subscriber>
void on_subscribe(const Subscriber& o) {
source.subscribe(
o,
// on_next
[this, o](T t) {
bool filtered = false;
try {
filtered = !this->test(t);
} catch(...) {
o.on_error(std::current_exception());
return;
}
if (!filtered) {
o.on_next(t);
}
},
// on_error
[o](std::exception_ptr e) {
o.on_error(e);
},
// on_completed
[o]() {
o.on_completed();
}
);
}
};
template<class Predicate>
class filter_factory
{
typedef typename std::decay<Predicate>::type test_type;
test_type predicate;
public:
filter_factory(test_type p) : predicate(std::move(p)) {}
template<class Observable>
auto operator()(Observable&& source)
-> observable<typename std::decay<Observable>::type::value_type, filter<typename std::decay<Observable>::type::value_type, Observable, Predicate>> {
return observable<typename std::decay<Observable>::type::value_type, filter<typename std::decay<Observable>::type::value_type, Observable, Predicate>>(
filter<typename std::decay<Observable>::type::value_type, Observable, Predicate>(std::forward<Observable>(source), std::move(predicate)));
}
};
}
template<class Predicate>
auto filter(Predicate&& p)
-> detail::filter_factory<Predicate> {
return detail::filter_factory<Predicate>(std::forward<Predicate>(p));
}
}
}
#endif
| remove move call | remove move call
| C++ | apache-2.0 | ReactiveX/RxCpp,Reactive-Extensions/RxCpp,Reactive-Extensions/RxCpp,Reactive-Extensions/RxCpp,alexeymarkov/RxCpp,alexeymarkov/RxCpp,ReactiveX/RxCpp,ReactiveX/RxCpp,alexeymarkov/RxCpp |
e3390eb75b9debf3ee6a1ba24090c5cb44c69a9c | src/arch/x86/m3/system.hh | src/arch/x86/m3/system.hh | /*
* Copyright (c) 2015, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#ifndef __ARCH_M3_X86_SYSTEM_HH__
#define __ARCH_M3_X86_SYSTEM_HH__
#include <string>
#include <vector>
#include "arch/x86/system.hh"
#include "params/M3X86System.hh"
#include "mem/qport.hh"
#include "mem/dtu/noc_addr.hh"
class M3X86System : public X86System
{
protected:
static const size_t MAX_MODS = 8;
static const size_t MAX_PES = 64;
static const size_t RT_SIZE = 0x2000;
static const uintptr_t RT_START = 0x3000;
static const size_t STACK_SIZE = 0x1000;
static const uintptr_t STACK_AREA = RT_START + RT_SIZE;
static const size_t HEAP_SIZE = 64 * 1024;
static const unsigned RES_PAGES;
class NoCMasterPort : public QueuedMasterPort
{
protected:
ReqPacketQueue reqQueue;
SnoopRespPacketQueue snoopRespQueue;
public:
NoCMasterPort(M3X86System &_sys);
bool recvTimingResp(PacketPtr) override
{
// unused
return true;
}
};
struct BootModule
{
char name[128];
uint64_t addr;
uint64_t size;
} M5_ATTR_PACKED;
struct KernelEnv
{
enum
{
TYPE_IMEM = 0,
TYPE_EMEM = 1,
TYPE_MEM = 2,
};
uintptr_t mods[MAX_MODS];
uint32_t pes[MAX_PES];
} M5_ATTR_PACKED;
struct StartEnv
{
uint64_t coreid;
uint32_t argc;
char **argv;
uintptr_t sp;
uintptr_t entry;
uintptr_t lambda;
uint32_t pager_sess;
uint32_t pager_gate;
uint32_t mounts_len;
uintptr_t mounts;
uint32_t fds_len;
uintptr_t fds;
uintptr_t eps;
uintptr_t caps;
uintptr_t exit;
uintptr_t backend;
uintptr_t kenv;
uint32_t pe;
} M5_ATTR_PACKED;
NoCMasterPort nocPort;
std::vector<Addr> pes;
std::string commandLine;
public:
const unsigned coreId;
const unsigned memPe;
const Addr memOffset;
const Addr memSize;
const Addr modOffset;
const Addr modSize;
unsigned nextFrame;
public:
typedef M3X86SystemParams Params;
M3X86System(Params *p);
~M3X86System();
BaseMasterPort& getMasterPort(const std::string &if_name,
PortID idx = InvalidPortID) override;
NocAddr getRootPt() const
{
return NocAddr(memPe, 0, memOffset);
}
void initState();
private:
bool isKernelArg(const std::string &arg);
void mapPage(Addr virt, Addr phys, uint access);
void mapSegment(Addr start, Addr size, unsigned perm);
void mapMemory();
size_t getArgc() const;
void writeRemote(Addr dest, const uint8_t *data, size_t size);
void writeArg(Addr &args, size_t &i, Addr argv, const char *cmd, const char *begin);
Addr loadModule(const std::string &path, const std::string &name, Addr addr);
};
#endif
| /*
* Copyright (c) 2015, Nils Asmussen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the FreeBSD Project.
*/
#ifndef __ARCH_M3_X86_SYSTEM_HH__
#define __ARCH_M3_X86_SYSTEM_HH__
#include <string>
#include <vector>
#include "arch/x86/system.hh"
#include "params/M3X86System.hh"
#include "mem/qport.hh"
#include "mem/dtu/noc_addr.hh"
class M3X86System : public X86System
{
protected:
static const size_t MAX_MODS = 8;
static const size_t MAX_PES = 64;
static const size_t RT_SIZE = 0x2000;
static const uintptr_t RT_START = 0x3000;
static const size_t STACK_SIZE = 0x1000;
static const uintptr_t STACK_AREA = RT_START + RT_SIZE;
static const size_t HEAP_SIZE = 64 * 1024;
static const unsigned RES_PAGES;
class NoCMasterPort : public QueuedMasterPort
{
protected:
ReqPacketQueue reqQueue;
SnoopRespPacketQueue snoopRespQueue;
public:
NoCMasterPort(M3X86System &_sys);
bool recvTimingResp(PacketPtr) override
{
// unused
return true;
}
};
struct BootModule
{
char name[128];
uint64_t addr;
uint64_t size;
} M5_ATTR_PACKED;
struct KernelEnv
{
enum
{
TYPE_IMEM = 0,
TYPE_EMEM = 1,
TYPE_MEM = 2,
};
uint64_t mods[MAX_MODS];
uint32_t pes[MAX_PES];
} M5_ATTR_PACKED;
struct StartEnv
{
uint64_t coreid;
uint32_t argc;
char **argv;
uint64_t sp;
uint64_t entry;
uint64_t lambda;
uint32_t pager_sess;
uint32_t pager_gate;
uint32_t mounts_len;
uint64_t mounts;
uint32_t fds_len;
uint64_t fds;
uint64_t eps;
uint64_t caps;
uint64_t exit;
uint64_t backend;
uint64_t kenv;
uint32_t pe;
} M5_ATTR_PACKED;
NoCMasterPort nocPort;
std::vector<Addr> pes;
std::string commandLine;
public:
const unsigned coreId;
const unsigned memPe;
const Addr memOffset;
const Addr memSize;
const Addr modOffset;
const Addr modSize;
unsigned nextFrame;
public:
typedef M3X86SystemParams Params;
M3X86System(Params *p);
~M3X86System();
BaseMasterPort& getMasterPort(const std::string &if_name,
PortID idx = InvalidPortID) override;
NocAddr getRootPt() const
{
return NocAddr(memPe, 0, memOffset);
}
void initState();
private:
bool isKernelArg(const std::string &arg);
void mapPage(Addr virt, Addr phys, uint access);
void mapSegment(Addr start, Addr size, unsigned perm);
void mapMemory();
size_t getArgc() const;
void writeRemote(Addr dest, const uint8_t *data, size_t size);
void writeArg(Addr &args, size_t &i, Addr argv, const char *cmd, const char *begin);
Addr loadModule(const std::string &path, const std::string &name, Addr addr);
};
#endif
| use fixed-width integers in StartEnv and KernelEnv. | DTU: use fixed-width integers in StartEnv and KernelEnv.
| C++ | bsd-3-clause | TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu |
0c0eb2a6a1ba111f0896dd16a579342fa16f7629 | tests/cpp_tests/test_stream.cpp | tests/cpp_tests/test_stream.cpp | /*!
* Copyright (c) 2022 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#include <gtest/gtest.h>
#include <testutils.h>
#include <LightGBM/utils/log.h>
#include <LightGBM/c_api.h>
#include <LightGBM/dataset.h>
#include <iostream>
using LightGBM::Dataset;
using LightGBM::Log;
using LightGBM::TestUtils;
void test_stream_dense(
int8_t creation_type,
DatasetHandle ref_datset_handle,
int32_t nrows,
int32_t ncols,
int32_t nclasses,
int batch_count,
const std::vector<double>* features,
const std::vector<float>* labels,
const std::vector<float>* weights,
const std::vector<double>* init_scores,
const std::vector<int32_t>* groups) {
Log::Info("Streaming %d rows dense data with a batch size of %d", nrows, batch_count);
DatasetHandle dataset_handle = nullptr;
Dataset* dataset = nullptr;
int has_weights = weights != nullptr;
int has_init_scores = init_scores != nullptr;
int has_queries = groups != nullptr;
try {
int result = 0;
switch (creation_type) {
case 0: {
Log::Info("Creating Dataset using LGBM_DatasetCreateFromSampledColumn, %d rows dense data with a batch size of %d", nrows, batch_count);
// construct sample data first (use all data for convenience and since size is small)
std::vector<std::vector<double>> sample_values(ncols);
std::vector<std::vector<int>> sample_idx(ncols);
const double* current_val = features->data();
for (int32_t idx = 0; idx < nrows; ++idx) {
for (int32_t k = 0; k < ncols; ++k) {
if (std::fabs(*current_val) > 1e-35f || std::isnan(*current_val)) {
sample_values[k].emplace_back(*current_val);
sample_idx[k].emplace_back(static_cast<int>(idx));
}
current_val++;
}
}
std::vector<int> sample_sizes;
std::vector<double*> sample_values_ptrs;
std::vector<int*> sample_idx_ptrs;
for (int32_t i = 0; i < ncols; ++i) {
sample_values_ptrs.push_back(sample_values[i].data());
sample_idx_ptrs.push_back(sample_idx[i].data());
sample_sizes.push_back(static_cast<int>(sample_values[i].size()));
}
result = LGBM_DatasetCreateFromSampledColumn(
sample_values_ptrs.data(),
sample_idx_ptrs.data(),
ncols,
sample_sizes.data(),
nrows,
nrows,
nrows,
"max_bin=15",
&dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateFromSampledColumn result code: " << result;
result = LGBM_DatasetInitStreaming(dataset_handle, has_weights, has_init_scores, has_queries, nclasses, 1);
EXPECT_EQ(0, result) << "LGBM_DatasetInitStreaming result code: " << result;
break;
}
case 1:
Log::Info("Creating Dataset using LGBM_DatasetCreateByReference, %d rows dense data with a batch size of %d", nrows, batch_count);
result = LGBM_DatasetCreateByReference(ref_datset_handle, nrows, &dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateByReference result code: " << result;
break;
}
dataset = static_cast<Dataset*>(dataset_handle);
Log::Info("Streaming dense dataset, %d rows dense data with a batch size of %d", nrows, batch_count);
TestUtils::StreamDenseDataset(
dataset_handle,
nrows,
ncols,
nclasses,
batch_count,
features,
labels,
weights,
init_scores,
groups);
dataset->FinishLoad();
TestUtils::AssertMetadata(&dataset->metadata(),
labels,
weights,
init_scores,
groups);
}
catch (...) {
}
if (dataset_handle) {
int result = LGBM_DatasetFree(dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
}
void test_stream_sparse(
int8_t creation_type,
DatasetHandle ref_datset_handle,
int32_t nrows,
int32_t ncols,
int32_t nclasses,
int batch_count,
const std::vector<int32_t>* indptr,
const std::vector<int32_t>* indices,
const std::vector<double>* vals,
const std::vector<float>* labels,
const std::vector<float>* weights,
const std::vector<double>* init_scores,
const std::vector<int32_t>* groups) {
Log::Info("Streaming %d rows sparse data with a batch size of %d", nrows, batch_count);
DatasetHandle dataset_handle = nullptr;
Dataset* dataset = nullptr;
int has_weights = weights != nullptr;
int has_init_scores = init_scores != nullptr;
int has_queries = groups != nullptr;
try {
int result = 0;
switch (creation_type) {
case 0: {
Log::Info("Creating Dataset using LGBM_DatasetCreateFromSampledColumn, %d rows sparse data with a batch size of %d", nrows, batch_count);
std::vector<std::vector<double>> sample_values(ncols);
std::vector<std::vector<int>> sample_idx(ncols);
for (size_t i = 0; i < indptr->size() - 1; ++i) {
int start_index = indptr->at(i);
int stop_index = indptr->at(i + 1);
for (int32_t j = start_index; j < stop_index; ++j) {
auto val = vals->at(j);
auto idx = indices->at(j);
if (std::fabs(val) > 1e-35f || std::isnan(val)) {
sample_values[idx].emplace_back(val);
sample_idx[idx].emplace_back(static_cast<int>(i));
}
}
}
std::vector<int> sample_sizes;
std::vector<double*> sample_values_ptrs;
std::vector<int*> sample_idx_ptrs;
for (int32_t i = 0; i < ncols; ++i) {
sample_values_ptrs.push_back(sample_values[i].data());
sample_idx_ptrs.push_back(sample_idx[i].data());
sample_sizes.push_back(static_cast<int>(sample_values[i].size()));
}
result = LGBM_DatasetCreateFromSampledColumn(
sample_values_ptrs.data(),
sample_idx_ptrs.data(),
ncols,
sample_sizes.data(),
nrows,
nrows,
nrows,
"max_bin=15",
&dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateFromSampledColumn result code: " << result;
dataset = static_cast<Dataset*>(dataset_handle);
dataset->InitStreaming(nrows, has_weights, has_init_scores, has_queries, nclasses, 2);
break;
}
case 1:
Log::Info("Creating Dataset using LGBM_DatasetCreateByReference, %d rows sparse data with a batch size of %d", nrows, batch_count);
result = LGBM_DatasetCreateByReference(ref_datset_handle, nrows, &dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateByReference result code: " << result;
break;
}
dataset = static_cast<Dataset*>(dataset_handle);
Log::Info("Streaming sparse dataset, %d rows sparse data with a batch size of %d", nrows, batch_count);
TestUtils::StreamSparseDataset(
dataset_handle,
nrows,
nclasses,
batch_count,
indptr,
indices,
vals,
labels,
weights,
init_scores,
groups);
dataset->FinishLoad();
TestUtils::AssertMetadata(&dataset->metadata(),
labels,
weights,
init_scores,
groups);
}
catch (...) {
}
if (dataset_handle) {
int result = LGBM_DatasetFree(dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
}
TEST(Stream, PushDenseRowsWithMetadata) {
// Load some test data
DatasetHandle ref_datset_handle;
const char* params = "max_bin=15";
// Use the smaller ".test" data because we don't care about the actual data and it's smaller
int result = TestUtils::LoadDatasetFromExamples("binary_classification/binary.test", params, &ref_datset_handle);
EXPECT_EQ(0, result) << "LoadDatasetFromExamples result code: " << result;
Dataset* ref_dataset = static_cast<Dataset*>(ref_datset_handle);
auto noriginalrows = ref_dataset->num_data();
Log::Info("Row count: %d", noriginalrows);
Log::Info("Feature group count: %d", ref_dataset->num_features());
// Add some fake initial_scores and groups so we can test streaming them
int nclasses = 2; // choose > 1 just to test multi-class handling
std::vector<double> unused_init_scores;
unused_init_scores.resize(noriginalrows * nclasses);
std::vector<int32_t> unused_groups;
unused_groups.assign(noriginalrows, 1);
result = LGBM_DatasetSetField(ref_datset_handle, "init_score", unused_init_scores.data(), noriginalrows * nclasses, 1);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField init_score result code: " << result;
result = LGBM_DatasetSetField(ref_datset_handle, "group", unused_groups.data(), noriginalrows, 2);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField group result code: " << result;
// Now use the reference dataset schema to make some testable Datasets with N rows each
int32_t nrows = 1000;
int32_t ncols = ref_dataset->num_features();
std::vector<double> features;
std::vector<float> labels;
std::vector<float> weights;
std::vector<double> init_scores;
std::vector<int32_t> groups;
Log::Info("Creating random data");
TestUtils::CreateRandomDenseData(nrows, ncols, nclasses, &features, &labels, &weights, &init_scores, &groups);
const std::vector<int32_t> batch_counts = { 1, nrows / 100, nrows / 10, nrows };
const std::vector<int8_t> creation_types = { 0, 1 };
for (size_t i = 0; i < creation_types.size(); ++i) { // from sampled data or reference
for (size_t j = 0; j < batch_counts.size(); ++j) {
auto type = creation_types[i];
auto batch_count = batch_counts[j];
test_stream_dense(type, ref_datset_handle, nrows, ncols, nclasses, batch_count, &features, &labels, &weights, &init_scores, &groups);
}
}
result = LGBM_DatasetFree(ref_datset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
TEST(Stream, PushSparseRowsWithMetadata) {
// Load some test data
DatasetHandle ref_datset_handle;
const char* params = "max_bin=15";
// Use the smaller ".test" data because we don't care about the actual data and it's smaller
int result = TestUtils::LoadDatasetFromExamples("binary_classification/binary.test", params, &ref_datset_handle);
EXPECT_EQ(0, result) << "LoadDatasetFromExamples result code: " << result;
Dataset* ref_dataset = static_cast<Dataset*>(ref_datset_handle);
auto noriginalrows = ref_dataset->num_data();
Log::Info("Row count: %d", noriginalrows);
Log::Info("Feature group count: %d", ref_dataset->num_features());
// Add some fake initial_scores and groups so we can test streaming them
int32_t nclasses = 2;
std::vector<double> unused_init_scores;
unused_init_scores.resize(noriginalrows * nclasses);
std::vector<int32_t> unused_groups;
unused_groups.assign(noriginalrows, 1);
result = LGBM_DatasetSetField(ref_datset_handle, "init_score", unused_init_scores.data(), noriginalrows * nclasses, 1);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField init_score result code: " << result;
result = LGBM_DatasetSetField(ref_datset_handle, "group", unused_groups.data(), noriginalrows, 2);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField group result code: " << result;
// Now use the reference dataset schema to make some testable Datasets with N rows each
int32_t nrows = 1000;
int32_t ncols = ref_dataset->num_features();
std::vector<int32_t> indptr;
std::vector<int32_t> indices;
std::vector<double> vals;
std::vector<float> labels;
std::vector<float> weights;
std::vector<double> init_scores;
std::vector<int32_t> groups;
Log::Info("Creating random data");
float sparse_percent = .1f;
TestUtils::CreateRandomSparseData(nrows, ncols, nclasses, sparse_percent, &indptr, &indices, &vals, &labels, &weights, &init_scores, &groups);
const std::vector<int32_t> batch_counts = { 1, nrows / 100, nrows / 10, nrows };
const std::vector<int8_t> creation_types = { 0, 1 };
for (size_t i = 0; i < creation_types.size(); ++i) { // from sampled data or reference
for (size_t j = 0; j < batch_counts.size(); ++j) {
auto type = creation_types[i];
auto batch_count = batch_counts[j];
test_stream_sparse(type, ref_datset_handle, nrows, ncols, nclasses, batch_count, &indptr, &indices, &vals, &labels, &weights, &init_scores, &groups);
}
}
result = LGBM_DatasetFree(ref_datset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
| /*!
* Copyright (c) 2022 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#include <gtest/gtest.h>
#include <testutils.h>
#include <LightGBM/utils/log.h>
#include <LightGBM/c_api.h>
#include <LightGBM/dataset.h>
#include <iostream>
using LightGBM::Dataset;
using LightGBM::Log;
using LightGBM::TestUtils;
void test_stream_dense(
int8_t creation_type,
DatasetHandle ref_datset_handle,
int32_t nrows,
int32_t ncols,
int32_t nclasses,
int batch_count,
const std::vector<double>* features,
const std::vector<float>* labels,
const std::vector<float>* weights,
const std::vector<double>* init_scores,
const std::vector<int32_t>* groups) {
Log::Info("Streaming %d rows dense data with a batch size of %d", nrows, batch_count);
DatasetHandle dataset_handle = nullptr;
Dataset* dataset = nullptr;
int has_weights = weights != nullptr;
int has_init_scores = init_scores != nullptr;
int has_queries = groups != nullptr;
bool succeeded = true;
std::string exceptionText("");
try {
int result = 0;
switch (creation_type) {
case 0: {
Log::Info("Creating Dataset using LGBM_DatasetCreateFromSampledColumn, %d rows dense data with a batch size of %d", nrows, batch_count);
// construct sample data first (use all data for convenience and since size is small)
std::vector<std::vector<double>> sample_values(ncols);
std::vector<std::vector<int>> sample_idx(ncols);
const double* current_val = features->data();
for (int32_t idx = 0; idx < nrows; ++idx) {
for (int32_t k = 0; k < ncols; ++k) {
if (std::fabs(*current_val) > 1e-35f || std::isnan(*current_val)) {
sample_values[k].emplace_back(*current_val);
sample_idx[k].emplace_back(static_cast<int>(idx));
}
current_val++;
}
}
std::vector<int> sample_sizes;
std::vector<double*> sample_values_ptrs;
std::vector<int*> sample_idx_ptrs;
for (int32_t i = 0; i < ncols; ++i) {
sample_values_ptrs.push_back(sample_values[i].data());
sample_idx_ptrs.push_back(sample_idx[i].data());
sample_sizes.push_back(static_cast<int>(sample_values[i].size()));
}
result = LGBM_DatasetCreateFromSampledColumn(
sample_values_ptrs.data(),
sample_idx_ptrs.data(),
ncols,
sample_sizes.data(),
nrows,
nrows,
nrows,
"max_bin=15",
&dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateFromSampledColumn result code: " << result;
result = LGBM_DatasetInitStreaming(dataset_handle, has_weights, has_init_scores, has_queries, nclasses, 1);
EXPECT_EQ(0, result) << "LGBM_DatasetInitStreaming result code: " << result;
break;
}
case 1:
Log::Info("Creating Dataset using LGBM_DatasetCreateByReference, %d rows dense data with a batch size of %d", nrows, batch_count);
result = LGBM_DatasetCreateByReference(ref_datset_handle, nrows, &dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateByReference result code: " << result;
break;
}
dataset = static_cast<Dataset*>(dataset_handle);
Log::Info("Streaming dense dataset, %d rows dense data with a batch size of %d", nrows, batch_count);
TestUtils::StreamDenseDataset(
dataset_handle,
nrows,
ncols,
nclasses,
batch_count,
features,
labels,
weights,
init_scores,
groups);
dataset->FinishLoad();
TestUtils::AssertMetadata(&dataset->metadata(),
labels,
weights,
init_scores,
groups);
}
catch (std::exception& ex) {
succeeded = false;
exceptionText = std::string(ex.what());
}
if (dataset_handle) {
int result = LGBM_DatasetFree(dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
if (!succeeded) {
FAIL() << "Test Dense Stream failed with exception: " << exceptionText;
}
}
void test_stream_sparse(
int8_t creation_type,
DatasetHandle ref_datset_handle,
int32_t nrows,
int32_t ncols,
int32_t nclasses,
int batch_count,
const std::vector<int32_t>* indptr,
const std::vector<int32_t>* indices,
const std::vector<double>* vals,
const std::vector<float>* labels,
const std::vector<float>* weights,
const std::vector<double>* init_scores,
const std::vector<int32_t>* groups) {
Log::Info("Streaming %d rows sparse data with a batch size of %d", nrows, batch_count);
DatasetHandle dataset_handle = nullptr;
Dataset* dataset = nullptr;
int has_weights = weights != nullptr;
int has_init_scores = init_scores != nullptr;
int has_queries = groups != nullptr;
bool succeeded = true;
std::string exceptionText("");
try {
int result = 0;
switch (creation_type) {
case 0: {
Log::Info("Creating Dataset using LGBM_DatasetCreateFromSampledColumn, %d rows sparse data with a batch size of %d", nrows, batch_count);
std::vector<std::vector<double>> sample_values(ncols);
std::vector<std::vector<int>> sample_idx(ncols);
for (size_t i = 0; i < indptr->size() - 1; ++i) {
int start_index = indptr->at(i);
int stop_index = indptr->at(i + 1);
for (int32_t j = start_index; j < stop_index; ++j) {
auto val = vals->at(j);
auto idx = indices->at(j);
if (std::fabs(val) > 1e-35f || std::isnan(val)) {
sample_values[idx].emplace_back(val);
sample_idx[idx].emplace_back(static_cast<int>(i));
}
}
}
std::vector<int> sample_sizes;
std::vector<double*> sample_values_ptrs;
std::vector<int*> sample_idx_ptrs;
for (int32_t i = 0; i < ncols; ++i) {
sample_values_ptrs.push_back(sample_values[i].data());
sample_idx_ptrs.push_back(sample_idx[i].data());
sample_sizes.push_back(static_cast<int>(sample_values[i].size()));
}
result = LGBM_DatasetCreateFromSampledColumn(
sample_values_ptrs.data(),
sample_idx_ptrs.data(),
ncols,
sample_sizes.data(),
nrows,
nrows,
nrows,
"max_bin=15",
&dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateFromSampledColumn result code: " << result;
dataset = static_cast<Dataset*>(dataset_handle);
dataset->InitStreaming(nrows, has_weights, has_init_scores, has_queries, nclasses, 2);
break;
}
case 1:
Log::Info("Creating Dataset using LGBM_DatasetCreateByReference, %d rows sparse data with a batch size of %d", nrows, batch_count);
result = LGBM_DatasetCreateByReference(ref_datset_handle, nrows, &dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetCreateByReference result code: " << result;
break;
}
dataset = static_cast<Dataset*>(dataset_handle);
Log::Info("Streaming sparse dataset, %d rows sparse data with a batch size of %d", nrows, batch_count);
TestUtils::StreamSparseDataset(
dataset_handle,
nrows,
nclasses,
batch_count,
indptr,
indices,
vals,
labels,
weights,
init_scores,
groups);
dataset->FinishLoad();
TestUtils::AssertMetadata(&dataset->metadata(),
labels,
weights,
init_scores,
groups);
}
catch (std::exception& ex) {
succeeded = false;
exceptionText = std::string(ex.what());
}
if (dataset_handle) {
int result = LGBM_DatasetFree(dataset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
if (!succeeded) {
FAIL() << "Test Sparse Stream failed with exception: " << exceptionText;
}
}
TEST(Stream, PushDenseRowsWithMetadata) {
// Load some test data
DatasetHandle ref_datset_handle;
const char* params = "max_bin=15";
// Use the smaller ".test" data because we don't care about the actual data and it's smaller
int result = TestUtils::LoadDatasetFromExamples("binary_classification/binary.test", params, &ref_datset_handle);
EXPECT_EQ(0, result) << "LoadDatasetFromExamples result code: " << result;
Dataset* ref_dataset = static_cast<Dataset*>(ref_datset_handle);
auto noriginalrows = ref_dataset->num_data();
Log::Info("Row count: %d", noriginalrows);
Log::Info("Feature group count: %d", ref_dataset->num_features());
// Add some fake initial_scores and groups so we can test streaming them
int nclasses = 2; // choose > 1 just to test multi-class handling
std::vector<double> unused_init_scores;
unused_init_scores.resize(noriginalrows * nclasses);
std::vector<int32_t> unused_groups;
unused_groups.assign(noriginalrows, 1);
result = LGBM_DatasetSetField(ref_datset_handle, "init_score", unused_init_scores.data(), noriginalrows * nclasses, 1);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField init_score result code: " << result;
result = LGBM_DatasetSetField(ref_datset_handle, "group", unused_groups.data(), noriginalrows, 2);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField group result code: " << result;
// Now use the reference dataset schema to make some testable Datasets with N rows each
int32_t nrows = 1000;
int32_t ncols = ref_dataset->num_features();
std::vector<double> features;
std::vector<float> labels;
std::vector<float> weights;
std::vector<double> init_scores;
std::vector<int32_t> groups;
Log::Info("Creating random data");
TestUtils::CreateRandomDenseData(nrows, ncols, nclasses, &features, &labels, &weights, &init_scores, &groups);
const std::vector<int32_t> batch_counts = { 1, nrows / 100, nrows / 10, nrows };
const std::vector<int8_t> creation_types = { 0, 1 };
for (size_t i = 0; i < creation_types.size(); ++i) { // from sampled data or reference
for (size_t j = 0; j < batch_counts.size(); ++j) {
auto type = creation_types[i];
auto batch_count = batch_counts[j];
test_stream_dense(type, ref_datset_handle, nrows, ncols, nclasses, batch_count, &features, &labels, &weights, &init_scores, &groups);
}
}
result = LGBM_DatasetFree(ref_datset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
TEST(Stream, PushSparseRowsWithMetadata) {
// Load some test data
DatasetHandle ref_datset_handle;
const char* params = "max_bin=15";
// Use the smaller ".test" data because we don't care about the actual data and it's smaller
int result = TestUtils::LoadDatasetFromExamples("binary_classification/binary.test", params, &ref_datset_handle);
EXPECT_EQ(0, result) << "LoadDatasetFromExamples result code: " << result;
Dataset* ref_dataset = static_cast<Dataset*>(ref_datset_handle);
auto noriginalrows = ref_dataset->num_data();
Log::Info("Row count: %d", noriginalrows);
Log::Info("Feature group count: %d", ref_dataset->num_features());
// Add some fake initial_scores and groups so we can test streaming them
int32_t nclasses = 2;
std::vector<double> unused_init_scores;
unused_init_scores.resize(noriginalrows * nclasses);
std::vector<int32_t> unused_groups;
unused_groups.assign(noriginalrows, 1);
result = LGBM_DatasetSetField(ref_datset_handle, "init_score", unused_init_scores.data(), noriginalrows * nclasses, 1);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField init_score result code: " << result;
result = LGBM_DatasetSetField(ref_datset_handle, "group", unused_groups.data(), noriginalrows, 2);
EXPECT_EQ(0, result) << "LGBM_DatasetSetField group result code: " << result;
// Now use the reference dataset schema to make some testable Datasets with N rows each
int32_t nrows = 1000;
int32_t ncols = ref_dataset->num_features();
std::vector<int32_t> indptr;
std::vector<int32_t> indices;
std::vector<double> vals;
std::vector<float> labels;
std::vector<float> weights;
std::vector<double> init_scores;
std::vector<int32_t> groups;
Log::Info("Creating random data");
float sparse_percent = .1f;
TestUtils::CreateRandomSparseData(nrows, ncols, nclasses, sparse_percent, &indptr, &indices, &vals, &labels, &weights, &init_scores, &groups);
const std::vector<int32_t> batch_counts = { 1, nrows / 100, nrows / 10, nrows };
const std::vector<int8_t> creation_types = { 0, 1 };
for (size_t i = 0; i < creation_types.size(); ++i) { // from sampled data or reference
for (size_t j = 0; j < batch_counts.size(); ++j) {
auto type = creation_types[i];
auto batch_count = batch_counts[j];
test_stream_sparse(type, ref_datset_handle, nrows, ncols, nclasses, batch_count, &indptr, &indices, &vals, &labels, &weights, &init_scores, &groups);
}
}
result = LGBM_DatasetFree(ref_datset_handle);
EXPECT_EQ(0, result) << "LGBM_DatasetFree result code: " << result;
}
| Fix cpp streaming data tests (#5481) | [tests] Fix cpp streaming data tests (#5481)
| C++ | mit | microsoft/LightGBM,microsoft/LightGBM,microsoft/LightGBM,microsoft/LightGBM,microsoft/LightGBM |
0f976557d5101248e6f8d31fefa7ab5dc7a411f7 | C++/singleton.cpp | C++/singleton.cpp | // Time: O(1)
// Space: O(1)
// Thread-Safe, Lazy Initilization
class Solution {
public:
/**
* @return: The same instance of this class every time
*/
static Solution* getInstance() {
static Solution *instance = new Solution(); // C++ 11 thread-safe local-static-initialization
return instance;
}
private:
Solution() {}
};
| // Time: O(1)
// Space: O(1)
// Thread-Safe, Lazy Initilization
class Solution {
public:
/**
* @return: The same instance of this class every time
*/
static Solution* getInstance() {
// C++ 11 thread-safe local-static-initialization.
static Solution *instance = new Solution();
return instance;
}
private:
Solution() {}
};
| Update singleton.cpp | Update singleton.cpp | C++ | mit | kamyu104/LintCode,kamyu104/LintCode,jaredkoontz/lintcode,jaredkoontz/lintcode,jaredkoontz/lintcode,kamyu104/LintCode |
5df8423f778cff4f8c957e7abf72e85cb1ba218f | src/widget_untrusted.cxx | src/widget_untrusted.cxx | /*
* Widget declarations.
*
* author: Max Kellermann <[email protected]>
*/
#include "widget_class.hxx"
#include <string.h>
static bool
widget_check_untrusted_host(const char *untrusted_host, const char *host)
{
assert(untrusted_host != nullptr);
if (host == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
/* untrusted widget only allowed on matching untrusted host
name */
return strcmp(host, untrusted_host) == 0;
}
static bool
widget_check_untrusted_prefix(const char *untrusted_prefix, const char *host)
{
assert(untrusted_prefix != nullptr);
if (host == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
/* untrusted widget only allowed on matching untrusted host
name */
size_t length = strlen(untrusted_prefix);
return memcmp(host, untrusted_prefix, length) == 0 &&
host[length] == '.';
}
static bool
widget_check_untrusted_site_suffix(const char *untrusted_site_suffix,
const char *host, const char *site_name)
{
assert(untrusted_site_suffix != nullptr);
if (host == nullptr || site_name == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
size_t site_name_length = strlen(site_name);
return memcmp(host, site_name, site_name_length) == 0 &&
host[site_name_length] == '.' &&
strcmp(host + site_name_length + 1,
untrusted_site_suffix) == 0;
}
static bool
widget_check_untrusted_raw_site_suffix(const char *untrusted_raw_site_suffix,
const char *host, const char *site_name)
{
assert(untrusted_raw_site_suffix != nullptr);
if (host == nullptr || site_name == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
size_t site_name_length = strlen(site_name);
return memcmp(host, site_name, site_name_length) == 0 &&
strcmp(host + site_name_length,
untrusted_raw_site_suffix) == 0;
}
bool
WidgetClass::CheckHost(const char *host, const char *site_name) const
{
if (untrusted_host != nullptr)
return widget_check_untrusted_host(untrusted_host, host);
else if (untrusted_prefix != nullptr)
return widget_check_untrusted_prefix(untrusted_prefix, host);
else if (untrusted_site_suffix != nullptr)
return widget_check_untrusted_site_suffix(untrusted_site_suffix,
host, site_name);
else if (untrusted_raw_site_suffix != nullptr)
return widget_check_untrusted_raw_site_suffix(untrusted_raw_site_suffix,
host, site_name);
else
/* trusted widget is only allowed on a trusted host name
(host==nullptr) */
return host == nullptr;
}
| /*
* Widget declarations.
*
* author: Max Kellermann <[email protected]>
*/
#include "widget_class.hxx"
#include <string.h>
static bool
widget_check_untrusted_host(const char *untrusted_host, const char *host)
{
assert(untrusted_host != nullptr);
if (host == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
/* untrusted widget only allowed on matching untrusted host
name */
return strcmp(host, untrusted_host) == 0;
}
static bool
widget_check_untrusted_prefix(const char *untrusted_prefix, const char *host)
{
assert(untrusted_prefix != nullptr);
if (host == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
/* untrusted widget only allowed on matching untrusted host
name */
size_t length = strlen(untrusted_prefix);
return strncmp(host, untrusted_prefix, length) == 0 &&
host[length] == '.';
}
static bool
widget_check_untrusted_site_suffix(const char *untrusted_site_suffix,
const char *host, const char *site_name)
{
assert(untrusted_site_suffix != nullptr);
if (host == nullptr || site_name == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
size_t site_name_length = strlen(site_name);
return strncmp(host, site_name, site_name_length) == 0 &&
host[site_name_length] == '.' &&
strcmp(host + site_name_length + 1,
untrusted_site_suffix) == 0;
}
static bool
widget_check_untrusted_raw_site_suffix(const char *untrusted_raw_site_suffix,
const char *host, const char *site_name)
{
assert(untrusted_raw_site_suffix != nullptr);
if (host == nullptr || site_name == nullptr)
/* untrusted widget not allowed on trusted host name */
return false;
size_t site_name_length = strlen(site_name);
return strncmp(host, site_name, site_name_length) == 0 &&
strcmp(host + site_name_length,
untrusted_raw_site_suffix) == 0;
}
bool
WidgetClass::CheckHost(const char *host, const char *site_name) const
{
if (untrusted_host != nullptr)
return widget_check_untrusted_host(untrusted_host, host);
else if (untrusted_prefix != nullptr)
return widget_check_untrusted_prefix(untrusted_prefix, host);
else if (untrusted_site_suffix != nullptr)
return widget_check_untrusted_site_suffix(untrusted_site_suffix,
host, site_name);
else if (untrusted_raw_site_suffix != nullptr)
return widget_check_untrusted_raw_site_suffix(untrusted_raw_site_suffix,
host, site_name);
else
/* trusted widget is only allowed on a trusted host name
(host==nullptr) */
return host == nullptr;
}
| use strncmp() instead of memcmp() to avoid buffer overflows | widget_untrusted: use strncmp() instead of memcmp() to avoid buffer overflows | C++ | bsd-2-clause | CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy |
d4dec1ee02f6ec171ae8f4e4ffc9b5cdb2ce697b | plugins/single_plugins/wm-actions.cpp | plugins/single_plugins/wm-actions.cpp | #include <wayfire/view.hpp>
#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/workspace-manager.hpp>
class wayfire_wm_actions_t : public wf::plugin_interface_t
{
nonstd::observer_ptr<wf::sublayer_t> always_above;
wf::activator_callback on_toggle_above =
[=](wf::activator_source_t, uint32_t) -> bool
{
if (!output->can_activate_plugin(this->grab_interface))
return false;
auto view = output->get_active_view();
if (view->role != wf::VIEW_ROLE_TOPLEVEL)
return false;
auto always_on_top_views =
output->workspace->get_views_in_sublayer(always_above);
auto it = std::find(
always_on_top_views.begin(), always_on_top_views.end(), view);
if (it != always_on_top_views.end()) {
output->workspace->add_view(view,
(wf::layer_t)output->workspace->get_view_layer(view));
} else {
output->workspace->add_view_to_sublayer(view, always_above);
}
return true;
};
wf::option_wrapper_t<wf::activatorbinding_t> toggle_above{"wm-actions/toggle_always_on_top"};
public:
void init() override
{
always_above = output->workspace->create_sublayer(
wf::LAYER_WORKSPACE, wf::SUBLAYER_DOCKED_ABOVE);
output->add_activator(toggle_above, &on_toggle_above);
}
void fini() override
{
output->workspace->destroy_sublayer(always_above);
output->rem_binding(&on_toggle_above);
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_wm_actions_t);
| #include <wayfire/view.hpp>
#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/workspace-manager.hpp>
class wayfire_wm_actions_t : public wf::plugin_interface_t
{
nonstd::observer_ptr<wf::sublayer_t> always_above;
wayfire_view choose_view(wf::activator_source_t source)
{
if (source == wf::ACTIVATOR_SOURCE_BUTTONBINDING)
return wf::get_core().get_cursor_focus_view();
return output->get_active_view();
}
wf::activator_callback on_toggle_above =
[=](wf::activator_source_t source, uint32_t) -> bool
{
if (!output->can_activate_plugin(this->grab_interface))
return false;
auto view = choose_view(source);
if (!view || view->role != wf::VIEW_ROLE_TOPLEVEL)
return false;
auto always_on_top_views =
output->workspace->get_views_in_sublayer(always_above);
auto it = std::find(
always_on_top_views.begin(), always_on_top_views.end(), view);
if (it != always_on_top_views.end()) {
output->workspace->add_view(view,
(wf::layer_t)output->workspace->get_view_layer(view));
} else {
output->workspace->add_view_to_sublayer(view, always_above);
}
return true;
};
wf::option_wrapper_t<wf::activatorbinding_t> toggle_above{"wm-actions/toggle_always_on_top"};
public:
void init() override
{
always_above = output->workspace->create_sublayer(
wf::LAYER_WORKSPACE, wf::SUBLAYER_DOCKED_ABOVE);
output->add_activator(toggle_above, &on_toggle_above);
}
void fini() override
{
output->workspace->destroy_sublayer(always_above);
output->rem_binding(&on_toggle_above);
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_wm_actions_t);
| support clicking on a view with modifier to set always on top | wm-actions: support clicking on a view with modifier to set always on top
| C++ | mit | ammen99/wayfire,ammen99/wayfire |
4fbb769502af87db81c5af37f5e2c9c786999f76 | src/osvr/ClientKit/ServerAutoStartC.cpp | src/osvr/ClientKit/ServerAutoStartC.cpp | /** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/ClientKit/ServerAutoStartC.h>
#include <osvr/Util/ProcessUtils.h>
#include <osvr/Util/PlatformConfig.h>
#include <osvr/Client/LocateServer.h>
#include <osvr/Util/GetEnvironmentVariable.h>
#if defined(OSVR_ANDROID)
#include <osvr/Server/ConfigFilePaths.h>
#include <osvr/Server/ConfigureServerFromFile.h>
#endif
// Library/third-party includes
// - none
// Standard includes
#include <string>
#include <vector>
// @todo use a thread-safe lazy-initialized singleton pattern
#if defined(OSVR_ANDROID)
static osvr::server::ServerPtr gServer;
#endif
void osvrClientAttemptServerAutoStart()
{
// @todo start the server.
#if defined(OSVR_ANDROID)
if(!gServer) {
OSVR_DEV_VERBOSE("Creating android auto-start server. Looking at config file paths:");
std::vector<std::string> configPaths = osvr::server::getDefaultConfigFilePaths();
for(size_t i = 0; i < configPaths.size(); i++) {
OSVR_DEV_VERBOSE(configPaths[i]);
}
gServer = osvr::server::configureServerFromFirstFileInList(configPaths);
OSVR_DEV_VERBOSE("Android-auto-start server created. Starting server thread...");
gServer->start();
OSVR_DEV_VERBOSE("Android server thread started...");
}
#else
auto server = osvr::client::getServerBinaryDirectoryPath();
if (server) {
OSVR_DEV_VERBOSE("Attempting to auto-start OSVR server from path " << *server);
auto exePath = osvr::client::getServerLauncherBinaryPath();
if (!exePath) {
OSVR_DEV_VERBOSE("No server launcher binary available.");
return;
}
if (osvrStartProcess(exePath->c_str(), server->c_str()) == OSVR_RETURN_FAILURE) {
OSVR_DEV_VERBOSE("Could not auto-start server process.");
return;
}
} else {
OSVR_DEV_VERBOSE("The current server location is currently unknown. Assuming server is already running.");
}
#endif
return;
}
void osvrClientReleaseAutoStartedServer()
{
#if defined(OSVR_ANDROID)
if(gServer) {
gServer->stop();
gServer = nullptr;
}
#else
// no-op. Leave the server running.
#endif
return;
}
| /** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Internal Includes
#include <osvr/ClientKit/ServerAutoStartC.h>
#include <osvr/Util/ProcessUtils.h>
#include <osvr/Util/PlatformConfig.h>
#include <osvr/Client/LocateServer.h>
#include <osvr/Util/GetEnvironmentVariable.h>
#if defined(OSVR_ANDROID)
#include <osvr/Server/ConfigFilePaths.h>
#include <osvr/Server/ConfigureServerFromFile.h>
#endif
// Library/third-party includes
// - none
// Standard includes
#include <string>
#include <vector>
// @todo use a thread-safe lazy-initialized singleton pattern
#if defined(OSVR_ANDROID)
static osvr::server::ServerPtr gServer;
#endif
void osvrClientAttemptServerAutoStart()
{
// @todo start the server.
#if defined(OSVR_ANDROID)
if(!gServer) {
try {
OSVR_DEV_VERBOSE("Creating android auto-start server. Looking at config file paths:");
std::vector<std::string> configPaths = osvr::server::getDefaultConfigFilePaths();
for(size_t i = 0; i < configPaths.size(); i++) {
OSVR_DEV_VERBOSE(configPaths[i]);
}
gServer = osvr::server::configureServerFromFirstFileInList(configPaths);
if(!gServer) {
OSVR_DEV_VERBOSE("Failed to create Android-auto-start server. Most likely the server is already running.");
return;
}
OSVR_DEV_VERBOSE("Android-auto-start server created. Starting server thread...");
gServer->start();
OSVR_DEV_VERBOSE("Android server thread started...");
} catch(...) {
OSVR_DEV_VERBOSE("Android server auto-start failed to start. Most likely the server is already running.");
gServer = nullptr;
}
}
#else
auto server = osvr::client::getServerBinaryDirectoryPath();
if (server) {
OSVR_DEV_VERBOSE("Attempting to auto-start OSVR server from path " << *server);
auto exePath = osvr::client::getServerLauncherBinaryPath();
if (!exePath) {
OSVR_DEV_VERBOSE("No server launcher binary available.");
return;
}
if (osvrStartProcess(exePath->c_str(), server->c_str()) == OSVR_RETURN_FAILURE) {
OSVR_DEV_VERBOSE("Could not auto-start server process.");
return;
}
} else {
OSVR_DEV_VERBOSE("The current server location is currently unknown. Assuming server is already running.");
}
#endif
return;
}
void osvrClientReleaseAutoStartedServer()
{
#if defined(OSVR_ANDROID)
if(gServer) {
gServer->stop();
gServer = nullptr;
}
#else
// no-op. Leave the server running.
#endif
return;
}
| Fix for android auto-start API implementation - no longer crashes when a server is already running. | Fix for android auto-start API implementation - no longer crashes when a server is already running.
| C++ | apache-2.0 | godbyk/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,godbyk/OSVR-Core |
2550a7074eb18071c7ae577517e1e2e007a6504b | src/x509_helper_fetch.cc | src/x509_helper_fetch.cc | /**
* This file is part of the CernVM File System.
*/
#include "x509_helper_fetch.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <cassert>
#include <climits>
#include <cstdio>
#include <cstring>
#include "x509_helper_log.h"
using namespace std; // NOLINT
/**
* For a given pid, extracts the X509_USER_PROXY path from the foreign
* process' environment. Stores the resulting path in the user provided buffer
* path.
*/
static bool GetProxyFileFromEnv(
const pid_t pid,
const size_t path_len,
char *path)
{
assert(path_len > 0);
static const char * const X509_USER_PROXY = "\0X509_USER_PROXY=";
size_t X509_USER_PROXY_LEN = strlen(X509_USER_PROXY + 1) + 1;
if (snprintf(path, path_len, "/proc/%d/environ", pid) >=
static_cast<int>(path_len))
{
if (errno == 0) {errno = ERANGE;}
return false;
}
int olduid = geteuid();
// NOTE: we ignore return values of these syscalls; this code path
// will work if cvmfs is FUSE-mounted as an unprivileged user.
seteuid(0);
FILE *fp = fopen(path, "r");
if (!fp) {
LogAuthz(kLogAuthzSyslogErr | kLogAuthzDebug,
"failed to open environment file for pid %d.", pid);
seteuid(olduid);
return false;
}
// Look for X509_USER_PROXY in the environment and store the value in path
int c = '\0';
size_t idx = 0, key_idx = 0;
bool set_env = false;
while (1) {
if (c == EOF) {break;}
if (key_idx == X509_USER_PROXY_LEN) {
if (idx >= path_len - 1) {break;}
if (c == '\0') {set_env = true; break;}
path[idx++] = c;
} else if (X509_USER_PROXY[key_idx++] != c) {
key_idx = 0;
}
c = fgetc(fp);
}
fclose(fp);
seteuid(olduid);
if (set_env) {path[idx] = '\0';}
return set_env;
}
/**
* Opens a read-only file pointer to the proxy certificate as a given user.
* The path is either taken from X509_USER_PROXY environment from the given pid
* or it is the default location /tmp/x509up_u<UID>
*/
static FILE *GetProxyFileInternal(pid_t pid, uid_t uid, gid_t gid)
{
char path[PATH_MAX];
if (!GetProxyFileFromEnv(pid, PATH_MAX, path)) {
LogAuthz(kLogAuthzDebug,
"could not find proxy in environment; using default location "
"in /tmp/x509up_u%d.", uid);
if (snprintf(path, PATH_MAX, "/tmp/x509up_u%d", uid) >= PATH_MAX) {
if (errno == 0) {errno = ERANGE;}
return NULL;
}
}
LogAuthz(kLogAuthzDebug, "looking for proxy in file %s", path);
/**
* If the target process is running inside a container, then we must
* adjust our fopen below for a chroot.
*/
char container_path[PATH_MAX];
if (snprintf(container_path, PATH_MAX, "/proc/%d/root", pid) >=
PATH_MAX) {
if (errno == 0) {errno = ERANGE;}
return NULL;
}
char container_cwd[PATH_MAX];
if (snprintf(container_cwd, PATH_MAX, "/proc/%d/cwd", pid) >=
PATH_MAX) {
if (errno == 0) {errno = ERANGE;}
return NULL;
}
int olduid = geteuid();
int oldgid = getegid();
// NOTE the sequencing: we must be eUID 0
// to change the UID and GID.
seteuid(0);
int fd = open("/", O_RDONLY); // Open FD to old root directory.
int fd2 = open(".", O_RDONLY); // Open FD to old $CWD
if ((fd == -1) || (fd2 == -1)) {
seteuid(olduid);
return NULL;
}
// If we can't chroot, we might be running this binary unprivileged -
// don't try subsequent changes.
bool can_chroot = true;
if (-1 == chroot(container_path)) {
can_chroot = false;
}
else if (-1 == chdir(container_cwd)) { // Change directory to same one as process.
if ((-1 == fchdir(fd)) || (-1 == chroot(".")) || (-1 == fchdir(fd2))) {
// Unable to restore original state! Abort...
abort();
}
seteuid(olduid);
return NULL;
}
setegid(gid);
seteuid(uid);
FILE *fp = fopen(path, "r");
seteuid(0); // Restore root privileges.
if (can_chroot &&
((-1 == fchdir(fd)) || // Change to old root directory so we can reset chroot.
(-1 == chroot(".")) ||
(-1 == fchdir(fd2)) // Change to original $CWD
)
) {
abort();
}
setegid(oldgid); // Restore remaining privileges.
seteuid(olduid);
return fp;
}
FILE *GetX509Proxy(
const AuthzRequest &authz_req, string *proxy) {
assert(proxy != NULL);
FILE *fproxy =
GetProxyFileInternal(authz_req.pid, authz_req.uid, authz_req.gid);
if (fproxy == NULL) {
LogAuthz(kLogAuthzDebug, "no proxy found for %s",
authz_req.Ident().c_str());
return NULL;
}
proxy->clear();
const unsigned kBufSize = 1024;
char buf[kBufSize];
unsigned nbytes;
do {
nbytes = fread(buf, 1, kBufSize, fproxy);
if (nbytes > 0)
proxy->append(string(buf, nbytes));
} while (nbytes == kBufSize);
rewind(fproxy);
return fproxy;
}
| /**
* This file is part of the CernVM File System.
*/
#include "x509_helper_fetch.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <cassert>
#include <climits>
#include <cstdio>
#include <cstring>
#include "x509_helper_log.h"
using namespace std; // NOLINT
/**
* For a given pid, extracts the X509_USER_PROXY path from the foreign
* process' environment. Stores the resulting path in the user provided buffer
* path.
*/
static bool GetProxyFileFromEnv(
const pid_t pid,
const size_t path_len,
char *path)
{
assert(path_len > 0);
static const char * const X509_USER_PROXY = "\0X509_USER_PROXY=";
size_t X509_USER_PROXY_LEN = strlen(X509_USER_PROXY + 1) + 1;
if (snprintf(path, path_len, "/proc/%d/environ", pid) >=
static_cast<int>(path_len))
{
if (errno == 0) {errno = ERANGE;}
return false;
}
int olduid = geteuid();
// NOTE: we ignore return values of these syscalls; this code path
// will work if cvmfs is FUSE-mounted as an unprivileged user.
seteuid(0);
FILE *fp = fopen(path, "r");
if (!fp) {
LogAuthz(kLogAuthzSyslogErr | kLogAuthzDebug,
"failed to open environment file for pid %d.", pid);
seteuid(olduid);
return false;
}
// Look for X509_USER_PROXY in the environment and store the value in path
int c = '\0';
size_t idx = 0, key_idx = 0;
bool set_env = false;
while (1) {
if (c == EOF) {break;}
if (key_idx == X509_USER_PROXY_LEN) {
if (idx >= path_len - 1) {break;}
if (c == '\0') {set_env = true; break;}
path[idx++] = c;
} else if (X509_USER_PROXY[key_idx++] != c) {
key_idx = 0;
}
c = fgetc(fp);
}
fclose(fp);
seteuid(olduid);
if (set_env) {path[idx] = '\0';}
return set_env;
}
/**
* Opens a read-only file pointer to the proxy certificate as a given user.
* The path is either taken from X509_USER_PROXY environment from the given pid
* or it is the default location /tmp/x509up_u<UID>
*/
static FILE *GetProxyFileInternal(pid_t pid, uid_t uid, gid_t gid)
{
char path[PATH_MAX];
if (!GetProxyFileFromEnv(pid, PATH_MAX, path)) {
LogAuthz(kLogAuthzDebug,
"could not find proxy in environment; using default location "
"in /tmp/x509up_u%d.", uid);
if (snprintf(path, PATH_MAX, "/tmp/x509up_u%d", uid) >= PATH_MAX) {
if (errno == 0) {errno = ERANGE;}
return NULL;
}
}
LogAuthz(kLogAuthzDebug, "looking for proxy in file %s", path);
/**
* If the target process is running inside a container, then we must
* adjust our fopen below for a chroot.
*/
char container_path[PATH_MAX];
if (snprintf(container_path, PATH_MAX, "/proc/%d/root", pid) >=
PATH_MAX) {
if (errno == 0) {errno = ERANGE;}
return NULL;
}
char container_cwd[PATH_MAX];
if (snprintf(container_cwd, PATH_MAX, "/proc/%d/cwd", pid) >=
PATH_MAX) {
if (errno == 0) {errno = ERANGE;}
return NULL;
}
int olduid = geteuid();
int oldgid = getegid();
// NOTE the sequencing: we must be eUID 0
// to change the UID and GID.
seteuid(0);
int fd = open("/", O_RDONLY); // Open FD to old root directory.
int fd2 = open(".", O_RDONLY); // Open FD to old $CWD
if ((fd == -1) || (fd2 == -1)) {
seteuid(olduid);
return NULL;
}
// If we can't chroot, we might be running this binary unprivileged -
// don't try subsequent changes.
bool can_chroot = true;
if (-1 == chdir(container_cwd)) { // Change directory to same one as process.
can_chroot = false;
}
if (can_chroot && (-1 == chroot(container_path))) {
if (-1 == fchdir(fd)) {
// Unable to restore original state! Abort...
abort();
}
can_chroot = false;
seteuid(olduid);
return NULL;
}
setegid(gid);
seteuid(uid);
FILE *fp = fopen(path, "r");
seteuid(0); // Restore root privileges.
if (can_chroot &&
((-1 == fchdir(fd)) || // Change to old root directory so we can reset chroot.
(-1 == chroot(".")) ||
(-1 == fchdir(fd2)) // Change to original $CWD
)
) {
abort();
}
setegid(oldgid); // Restore remaining privileges.
seteuid(olduid);
return fp;
}
FILE *GetX509Proxy(
const AuthzRequest &authz_req, string *proxy) {
assert(proxy != NULL);
FILE *fproxy =
GetProxyFileInternal(authz_req.pid, authz_req.uid, authz_req.gid);
if (fproxy == NULL) {
LogAuthz(kLogAuthzDebug, "no proxy found for %s",
authz_req.Ident().c_str());
return NULL;
}
proxy->clear();
const unsigned kBufSize = 1024;
char buf[kBufSize];
unsigned nbytes;
do {
nbytes = fread(buf, 1, kBufSize, fproxy);
if (nbytes > 0)
proxy->append(string(buf, nbytes));
} while (nbytes == kBufSize);
rewind(fproxy);
return fproxy;
}
| Change directory to same as target process first. | Change directory to same as target process first.
| C++ | bsd-3-clause | cvmfs/cvmfs-x509-helper,cvmfs/cvmfs-x509-helper,cvmfs/cvmfs-x509-helper |
bf4f6cf34c11ccccf4936641933e5850e45e270e | tests/mesh/mesh_triangulation.C | tests/mesh/mesh_triangulation.C | #include <libmesh/parallel_implementation.h> // max()
#include <libmesh/elem.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_triangle_holes.h>
#include <libmesh/mesh_triangle_interface.h>
#include <libmesh/point.h>
#include <libmesh/poly2tri_triangulator.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
#include <cmath>
using namespace libMesh;
class MeshTriangulationTest : public CppUnit::TestCase
{
/**
* The goal of this test is to verify proper operation of the
* interfaces to triangulation libraries
*/
public:
CPPUNIT_TEST_SUITE( MeshTriangulationTest );
CPPUNIT_TEST( testTriangleHoleArea );
#ifdef LIBMESH_HAVE_POLY2TRI
CPPUNIT_TEST( testPoly2Tri );
CPPUNIT_TEST( testPoly2TriHoles );
CPPUNIT_TEST( testPoly2TriSegments );
CPPUNIT_TEST( testPoly2TriRefined );
CPPUNIT_TEST( testPoly2TriExtraRefined );
CPPUNIT_TEST( testPoly2TriHolesRefined );
#endif
#ifdef LIBMESH_HAVE_TRIANGLE
CPPUNIT_TEST( testTriangle );
CPPUNIT_TEST( testTriangleHoles );
CPPUNIT_TEST( testTriangleSegments );
#endif
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {}
void tearDown() {}
void testTriangleHoleArea()
{
// Using center=(1,0), radius=2 for the heck of it
Point center{1};
Real radius = 2;
std::vector<TriangulatorInterface::PolygonHole> polyholes;
// Line
polyholes.emplace_back(center, radius, 2);
// Triangle
polyholes.emplace_back(center, radius, 3);
// Square
polyholes.emplace_back(center, radius, 4);
// Pentagon
polyholes.emplace_back(center, radius, 5);
// Hexagon
polyholes.emplace_back(center, radius, 6);
for (int i=0; i != 5; ++i)
{
const int n_sides = i+2;
const TriangulatorInterface::Hole & hole = polyholes[i];
// Really? This isn't until C++20?
constexpr double my_pi = 3.141592653589793238462643383279;
const Real computed_area = hole.area();
const Real theta = my_pi/n_sides;
const Real half_side_length = radius*std::cos(theta);
const Real apothem = radius*std::sin(theta);
const Real area = n_sides * apothem * half_side_length;
LIBMESH_ASSERT_FP_EQUAL(computed_area, area, TOLERANCE*TOLERANCE);
}
TriangulatorInterface::ArbitraryHole arbhole {center, {{0,-1},{2,-1},{2,1},{0,2}}};
LIBMESH_ASSERT_FP_EQUAL(arbhole.area(), Real(5), TOLERANCE*TOLERANCE);
#ifdef LIBMESH_HAVE_TRIANGLE
// Make sure we're compatible with the old naming structure too
TriangleInterface::PolygonHole square(center, radius, 4);
LIBMESH_ASSERT_FP_EQUAL(square.area(), 2*radius*radius, TOLERANCE*TOLERANCE);
#endif
}
void testTriangulatorBase(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// Use the point order to define the boundary, because our
// Poly2Tri implementation doesn't do convex hulls yet, even when
// that would give the same answer.
triangulator.triangulation_type() = TriangulatorInterface::PSLG;
// Don't try to insert points yet
triangulator.desired_area() = 1000;
triangulator.minimum_angle() = 0;
triangulator.smooth_after_generating() = false;
triangulator.triangulate();
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(2));
for (const auto & elem : mesh.element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);
// Make sure we're not getting any inverted elements
auto cross_prod =
(elem->point(1) - elem->point(0)).cross
(elem->point(2) - elem->point(0));
CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));
bool found_triangle = false;
for (const auto & node : elem->node_ref_range())
{
const Point & point = node;
if (point == Point(0,0))
{
found_triangle = true;
CPPUNIT_ASSERT((elem->point(0) == Point(0,0) &&
elem->point(1) == Point(1,0) &&
elem->point(2) == Point(0,1)) ||
(elem->point(1) == Point(0,0) &&
elem->point(2) == Point(1,0) &&
elem->point(0) == Point(0,1)) ||
(elem->point(2) == Point(0,0) &&
elem->point(0) == Point(1,0) &&
elem->point(1) == Point(0,1)));
}
if (point == Point(1,2))
{
found_triangle = true;
CPPUNIT_ASSERT((elem->point(0) == Point(0,1) &&
elem->point(1) == Point(1,0) &&
elem->point(2) == Point(1,2)) ||
(elem->point(1) == Point(0,1) &&
elem->point(2) == Point(1,0) &&
elem->point(0) == Point(1,2)) ||
(elem->point(2) == Point(0,1) &&
elem->point(0) == Point(1,0) &&
elem->point(1) == Point(1,2)));
}
}
CPPUNIT_ASSERT(found_triangle);
}
}
void testTriangulator(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// A non-square quad, so we don't have ambiguity about which
// diagonal a Delaunay algorithm will pick.
// Manually-numbered points, so we can use the point numbering as
// a segment ordering even on DistributedMesh.
mesh.add_point(Point(0,0), 0);
mesh.add_point(Point(1,0), 1);
mesh.add_point(Point(1,2), 2);
mesh.add_point(Point(0,1), 3);
this->testTriangulatorBase(mesh, triangulator);
}
void testTriangulatorHoles(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// A square quad; we'll put a diamond hole in the middle to make
// the Delaunay selection unambiguous.
mesh.add_point(Point(-1,-1), 0);
mesh.add_point(Point(1,-1), 1);
mesh.add_point(Point(1,1), 2);
mesh.add_point(Point(-1,1), 3);
// Use the point order to define the boundary, because our
// Poly2Tri implementation doesn't do convex hulls yet, even when
// that would give the same answer.
triangulator.triangulation_type() = TriangulatorInterface::PSLG;
// Add a diamond hole in the center
TriangulatorInterface::PolygonHole diamond(Point(0), std::sqrt(2)/2, 4);
const std::vector<TriangulatorInterface::Hole*> holes { &diamond };
triangulator.attach_hole_list(&holes);
// Don't try to insert points yet
triangulator.desired_area() = 1000;
triangulator.minimum_angle() = 0;
triangulator.smooth_after_generating() = false;
triangulator.triangulate();
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(8));
// Center coordinates for all the elements we expect
Real r2p2o6 = (std::sqrt(Real(2))+2)/6;
Real r2p4o6 = (std::sqrt(Real(2))+4)/6;
std::vector <Point> expected_centers
{ {r2p2o6,r2p2o6}, {r2p2o6,-r2p2o6},
{-r2p2o6,r2p2o6}, {-r2p2o6,-r2p2o6},
{0,r2p4o6}, {r2p4o6, 0},
{0,-r2p4o6}, {-r2p4o6, 0}
};
std::vector<bool> found_centers(expected_centers.size(), false);
for (const auto & elem : mesh.element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);
// Make sure we're not getting any inverted elements
auto cross_prod =
(elem->point(1) - elem->point(0)).cross
(elem->point(2) - elem->point(0));
CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));
// Make sure we're finding all the elements we expect
Point center = elem->vertex_average();
bool found_mine = false;
for (auto i : index_range(expected_centers))
{
Point possible = expected_centers[i];
if (possible.absolute_fuzzy_equals(center, TOLERANCE*TOLERANCE))
{
found_mine = true;
found_centers[i] = true;
}
}
CPPUNIT_ASSERT(found_mine);
}
mesh.comm().max(found_centers);
for (auto found_it : found_centers)
CPPUNIT_ASSERT(found_it);
}
void testTriangulatorSegments(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// The same quad as testTriangulator, but out of order
mesh.add_point(Point(0,0), 0);
mesh.add_point(Point(1,2), 1);
mesh.add_point(Point(1,0), 2);
mesh.add_point(Point(0,1), 3);
// Segments to put them in order
triangulator.segments = {{0,2},{2,1},{1,3},{3,0}};
this->testTriangulatorBase(mesh, triangulator);
}
#ifdef LIBMESH_HAVE_TRIANGLE
void testTriangle()
{
Mesh mesh(*TestCommWorld);
TriangleInterface triangle(mesh);
testTriangulator(mesh, triangle);
}
void testTriangleHoles()
{
Mesh mesh(*TestCommWorld);
TriangleInterface triangle(mesh);
testTriangulatorHoles(mesh, triangle);
}
void testTriangleSegments()
{
Mesh mesh(*TestCommWorld);
TriangleInterface triangle(mesh);
testTriangulatorSegments(mesh, triangle);
}
#endif // LIBMESH_HAVE_TRIANGLE
#ifdef LIBMESH_HAVE_POLY2TRI
void testPoly2Tri()
{
Mesh mesh(*TestCommWorld);
Poly2TriTriangulator p2t_tri(mesh);
testTriangulator(mesh, p2t_tri);
}
void testPoly2TriHoles()
{
Mesh mesh(*TestCommWorld);
Poly2TriTriangulator p2t_tri(mesh);
testTriangulatorHoles(mesh, p2t_tri);
}
void testPoly2TriSegments()
{
Mesh mesh(*TestCommWorld);
Poly2TriTriangulator p2t_tri(mesh);
testTriangulatorSegments(mesh, p2t_tri);
}
void testPoly2TriRefinementBase
(const std::vector<TriangulatorInterface::Hole*> * holes,
Real expected_total_area,
dof_id_type n_original_elem,
Real desired_area = 0.1)
{
Mesh mesh(*TestCommWorld);
mesh.add_point(Point(0,0), 0);
mesh.add_point(Point(1,0), 1);
mesh.add_point(Point(1,2), 2);
mesh.add_point(Point(0,1), 3);
Poly2TriTriangulator triangulator(mesh);
// Use the point order to define the boundary, because our
// Poly2Tri implementation doesn't do convex hulls yet, even when
// that would give the same answer.
triangulator.triangulation_type() = TriangulatorInterface::PSLG;
if (holes)
triangulator.attach_hole_list(holes);
// Try to insert points!
triangulator.desired_area() = desired_area;
triangulator.minimum_angle() = 0;
triangulator.smooth_after_generating() = false;
triangulator.triangulate();
CPPUNIT_ASSERT(mesh.n_elem() > n_original_elem);
Real area = 0;
for (const auto & elem : mesh.active_local_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->level(), 0u);
CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);
const Real my_area = elem->volume();
// my_area <= desired_area, wow this macro ordering hurts
CPPUNIT_ASSERT_LESSEQUAL(desired_area, my_area);
area += my_area;
}
mesh.comm().sum(area);
LIBMESH_ASSERT_FP_EQUAL(area, expected_total_area, TOLERANCE*TOLERANCE);
}
void testPoly2TriRefined()
{
testPoly2TriRefinementBase(nullptr, 1.5, 15);
}
void testPoly2TriExtraRefined()
{
testPoly2TriRefinementBase(nullptr, 1.5, 150, 0.01);
}
void testPoly2TriHolesRefined()
{
// Add a diamond hole
TriangulatorInterface::PolygonHole diamond(Point(0.5,0.5), std::sqrt(2)/4, 4);
const std::vector<TriangulatorInterface::Hole*> holes { &diamond };
testPoly2TriRefinementBase(&holes, 1.25, 13);
}
#endif // LIBMESH_HAVE_POLY2TRI
};
CPPUNIT_TEST_SUITE_REGISTRATION( MeshTriangulationTest );
| #include <libmesh/parallel_implementation.h> // max()
#include <libmesh/elem.h>
#include <libmesh/mesh.h>
#include <libmesh/mesh_triangle_holes.h>
#include <libmesh/mesh_triangle_interface.h>
#include <libmesh/point.h>
#include <libmesh/poly2tri_triangulator.h>
#include "test_comm.h"
#include "libmesh_cppunit.h"
#include <cmath>
using namespace libMesh;
class MeshTriangulationTest : public CppUnit::TestCase
{
/**
* The goal of this test is to verify proper operation of the
* interfaces to triangulation libraries
*/
public:
CPPUNIT_TEST_SUITE( MeshTriangulationTest );
CPPUNIT_TEST( testTriangleHoleArea );
#ifdef LIBMESH_HAVE_POLY2TRI
CPPUNIT_TEST( testPoly2Tri );
CPPUNIT_TEST( testPoly2TriHoles );
CPPUNIT_TEST( testPoly2TriSegments );
CPPUNIT_TEST( testPoly2TriRefined );
CPPUNIT_TEST( testPoly2TriExtraRefined );
CPPUNIT_TEST( testPoly2TriHolesRefined );
// This covers an old poly2tri collinearity-tolerance bug
CPPUNIT_TEST( testPoly2TriHolesExtraRefined );
#endif
#ifdef LIBMESH_HAVE_TRIANGLE
CPPUNIT_TEST( testTriangle );
CPPUNIT_TEST( testTriangleHoles );
CPPUNIT_TEST( testTriangleSegments );
#endif
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {}
void tearDown() {}
void testTriangleHoleArea()
{
// Using center=(1,0), radius=2 for the heck of it
Point center{1};
Real radius = 2;
std::vector<TriangulatorInterface::PolygonHole> polyholes;
// Line
polyholes.emplace_back(center, radius, 2);
// Triangle
polyholes.emplace_back(center, radius, 3);
// Square
polyholes.emplace_back(center, radius, 4);
// Pentagon
polyholes.emplace_back(center, radius, 5);
// Hexagon
polyholes.emplace_back(center, radius, 6);
for (int i=0; i != 5; ++i)
{
const int n_sides = i+2;
const TriangulatorInterface::Hole & hole = polyholes[i];
// Really? This isn't until C++20?
constexpr double my_pi = 3.141592653589793238462643383279;
const Real computed_area = hole.area();
const Real theta = my_pi/n_sides;
const Real half_side_length = radius*std::cos(theta);
const Real apothem = radius*std::sin(theta);
const Real area = n_sides * apothem * half_side_length;
LIBMESH_ASSERT_FP_EQUAL(computed_area, area, TOLERANCE*TOLERANCE);
}
TriangulatorInterface::ArbitraryHole arbhole {center, {{0,-1},{2,-1},{2,1},{0,2}}};
LIBMESH_ASSERT_FP_EQUAL(arbhole.area(), Real(5), TOLERANCE*TOLERANCE);
#ifdef LIBMESH_HAVE_TRIANGLE
// Make sure we're compatible with the old naming structure too
TriangleInterface::PolygonHole square(center, radius, 4);
LIBMESH_ASSERT_FP_EQUAL(square.area(), 2*radius*radius, TOLERANCE*TOLERANCE);
#endif
}
void testTriangulatorBase(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// Use the point order to define the boundary, because our
// Poly2Tri implementation doesn't do convex hulls yet, even when
// that would give the same answer.
triangulator.triangulation_type() = TriangulatorInterface::PSLG;
// Don't try to insert points yet
triangulator.desired_area() = 1000;
triangulator.minimum_angle() = 0;
triangulator.smooth_after_generating() = false;
triangulator.triangulate();
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(2));
for (const auto & elem : mesh.element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);
// Make sure we're not getting any inverted elements
auto cross_prod =
(elem->point(1) - elem->point(0)).cross
(elem->point(2) - elem->point(0));
CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));
bool found_triangle = false;
for (const auto & node : elem->node_ref_range())
{
const Point & point = node;
if (point == Point(0,0))
{
found_triangle = true;
CPPUNIT_ASSERT((elem->point(0) == Point(0,0) &&
elem->point(1) == Point(1,0) &&
elem->point(2) == Point(0,1)) ||
(elem->point(1) == Point(0,0) &&
elem->point(2) == Point(1,0) &&
elem->point(0) == Point(0,1)) ||
(elem->point(2) == Point(0,0) &&
elem->point(0) == Point(1,0) &&
elem->point(1) == Point(0,1)));
}
if (point == Point(1,2))
{
found_triangle = true;
CPPUNIT_ASSERT((elem->point(0) == Point(0,1) &&
elem->point(1) == Point(1,0) &&
elem->point(2) == Point(1,2)) ||
(elem->point(1) == Point(0,1) &&
elem->point(2) == Point(1,0) &&
elem->point(0) == Point(1,2)) ||
(elem->point(2) == Point(0,1) &&
elem->point(0) == Point(1,0) &&
elem->point(1) == Point(1,2)));
}
}
CPPUNIT_ASSERT(found_triangle);
}
}
void testTriangulator(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// A non-square quad, so we don't have ambiguity about which
// diagonal a Delaunay algorithm will pick.
// Manually-numbered points, so we can use the point numbering as
// a segment ordering even on DistributedMesh.
mesh.add_point(Point(0,0), 0);
mesh.add_point(Point(1,0), 1);
mesh.add_point(Point(1,2), 2);
mesh.add_point(Point(0,1), 3);
this->testTriangulatorBase(mesh, triangulator);
}
void testTriangulatorHoles(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// A square quad; we'll put a diamond hole in the middle to make
// the Delaunay selection unambiguous.
mesh.add_point(Point(-1,-1), 0);
mesh.add_point(Point(1,-1), 1);
mesh.add_point(Point(1,1), 2);
mesh.add_point(Point(-1,1), 3);
// Use the point order to define the boundary, because our
// Poly2Tri implementation doesn't do convex hulls yet, even when
// that would give the same answer.
triangulator.triangulation_type() = TriangulatorInterface::PSLG;
// Add a diamond hole in the center
TriangulatorInterface::PolygonHole diamond(Point(0), std::sqrt(2)/2, 4);
const std::vector<TriangulatorInterface::Hole*> holes { &diamond };
triangulator.attach_hole_list(&holes);
// Don't try to insert points yet
triangulator.desired_area() = 1000;
triangulator.minimum_angle() = 0;
triangulator.smooth_after_generating() = false;
triangulator.triangulate();
CPPUNIT_ASSERT_EQUAL(mesh.n_elem(), dof_id_type(8));
// Center coordinates for all the elements we expect
Real r2p2o6 = (std::sqrt(Real(2))+2)/6;
Real r2p4o6 = (std::sqrt(Real(2))+4)/6;
std::vector <Point> expected_centers
{ {r2p2o6,r2p2o6}, {r2p2o6,-r2p2o6},
{-r2p2o6,r2p2o6}, {-r2p2o6,-r2p2o6},
{0,r2p4o6}, {r2p4o6, 0},
{0,-r2p4o6}, {-r2p4o6, 0}
};
std::vector<bool> found_centers(expected_centers.size(), false);
for (const auto & elem : mesh.element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);
// Make sure we're not getting any inverted elements
auto cross_prod =
(elem->point(1) - elem->point(0)).cross
(elem->point(2) - elem->point(0));
CPPUNIT_ASSERT_GREATER(Real(0), cross_prod(2));
// Make sure we're finding all the elements we expect
Point center = elem->vertex_average();
bool found_mine = false;
for (auto i : index_range(expected_centers))
{
Point possible = expected_centers[i];
if (possible.absolute_fuzzy_equals(center, TOLERANCE*TOLERANCE))
{
found_mine = true;
found_centers[i] = true;
}
}
CPPUNIT_ASSERT(found_mine);
}
mesh.comm().max(found_centers);
for (auto found_it : found_centers)
CPPUNIT_ASSERT(found_it);
}
void testTriangulatorSegments(MeshBase & mesh,
TriangulatorInterface & triangulator)
{
// The same quad as testTriangulator, but out of order
mesh.add_point(Point(0,0), 0);
mesh.add_point(Point(1,2), 1);
mesh.add_point(Point(1,0), 2);
mesh.add_point(Point(0,1), 3);
// Segments to put them in order
triangulator.segments = {{0,2},{2,1},{1,3},{3,0}};
this->testTriangulatorBase(mesh, triangulator);
}
#ifdef LIBMESH_HAVE_TRIANGLE
void testTriangle()
{
Mesh mesh(*TestCommWorld);
TriangleInterface triangle(mesh);
testTriangulator(mesh, triangle);
}
void testTriangleHoles()
{
Mesh mesh(*TestCommWorld);
TriangleInterface triangle(mesh);
testTriangulatorHoles(mesh, triangle);
}
void testTriangleSegments()
{
Mesh mesh(*TestCommWorld);
TriangleInterface triangle(mesh);
testTriangulatorSegments(mesh, triangle);
}
#endif // LIBMESH_HAVE_TRIANGLE
#ifdef LIBMESH_HAVE_POLY2TRI
void testPoly2Tri()
{
Mesh mesh(*TestCommWorld);
Poly2TriTriangulator p2t_tri(mesh);
testTriangulator(mesh, p2t_tri);
}
void testPoly2TriHoles()
{
Mesh mesh(*TestCommWorld);
Poly2TriTriangulator p2t_tri(mesh);
testTriangulatorHoles(mesh, p2t_tri);
}
void testPoly2TriSegments()
{
Mesh mesh(*TestCommWorld);
Poly2TriTriangulator p2t_tri(mesh);
testTriangulatorSegments(mesh, p2t_tri);
}
void testPoly2TriRefinementBase
(const std::vector<TriangulatorInterface::Hole*> * holes,
Real expected_total_area,
dof_id_type n_original_elem,
Real desired_area = 0.1)
{
Mesh mesh(*TestCommWorld);
mesh.add_point(Point(0,0), 0);
mesh.add_point(Point(1,0), 1);
mesh.add_point(Point(1,2), 2);
mesh.add_point(Point(0,1), 3);
Poly2TriTriangulator triangulator(mesh);
// Use the point order to define the boundary, because our
// Poly2Tri implementation doesn't do convex hulls yet, even when
// that would give the same answer.
triangulator.triangulation_type() = TriangulatorInterface::PSLG;
if (holes)
triangulator.attach_hole_list(holes);
// Try to insert points!
triangulator.desired_area() = desired_area;
triangulator.minimum_angle() = 0;
triangulator.smooth_after_generating() = false;
triangulator.triangulate();
CPPUNIT_ASSERT(mesh.n_elem() > n_original_elem);
Real area = 0;
for (const auto & elem : mesh.active_local_element_ptr_range())
{
CPPUNIT_ASSERT_EQUAL(elem->level(), 0u);
CPPUNIT_ASSERT_EQUAL(elem->type(), TRI3);
const Real my_area = elem->volume();
// my_area <= desired_area, wow this macro ordering hurts
CPPUNIT_ASSERT_LESSEQUAL(desired_area, my_area);
area += my_area;
}
mesh.comm().sum(area);
LIBMESH_ASSERT_FP_EQUAL(area, expected_total_area, TOLERANCE*TOLERANCE);
}
void testPoly2TriRefined()
{
testPoly2TriRefinementBase(nullptr, 1.5, 15);
}
void testPoly2TriExtraRefined()
{
testPoly2TriRefinementBase(nullptr, 1.5, 150, 0.01);
}
void testPoly2TriHolesRefined()
{
// Add a diamond hole
TriangulatorInterface::PolygonHole diamond(Point(0.5,0.5), std::sqrt(2)/4, 4);
const std::vector<TriangulatorInterface::Hole*> holes { &diamond };
testPoly2TriRefinementBase(&holes, 1.25, 13);
}
void testPoly2TriHolesExtraRefined()
{
// Add a diamond hole
TriangulatorInterface::PolygonHole diamond(Point(0.5,0.5), std::sqrt(2)/4, 4);
const std::vector<TriangulatorInterface::Hole*> holes { &diamond };
testPoly2TriRefinementBase(&holes, 1.25, 125, 0.01);
}
#endif // LIBMESH_HAVE_POLY2TRI
};
CPPUNIT_TEST_SUITE_REGISTRATION( MeshTriangulationTest );
| Test more Poly2TriTriangulator refinement w/holes | Test more Poly2TriTriangulator refinement w/holes
With poly2tri issue 39 fixed, this passes for me
| C++ | lgpl-2.1 | jwpeterson/libmesh,jwpeterson/libmesh,libMesh/libmesh,dschwen/libmesh,jwpeterson/libmesh,dschwen/libmesh,jwpeterson/libmesh,libMesh/libmesh,libMesh/libmesh,libMesh/libmesh,libMesh/libmesh,dschwen/libmesh,jwpeterson/libmesh,dschwen/libmesh,libMesh/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,libMesh/libmesh,jwpeterson/libmesh,dschwen/libmesh,dschwen/libmesh,dschwen/libmesh,dschwen/libmesh,libMesh/libmesh |
c35d7e67d0dbf23448a56032ae8f2c15d6ec8ccb | include/etl/op/unary/plus.hpp | include/etl/op/unary/plus.hpp | //=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
namespace etl {
/*!
* \brief Unary operation computing the plus operation
* \tparam T The type of value
*/
template <typename T>
struct plus_unary_op {
/*!
* The vectorization type for V
*/
template <typename V = default_vec>
using vec_type = typename V::template vec_type<T>;
static constexpr bool linear = true; ///< Indicates if the operator is linear
static constexpr bool thread_safe = true; ///< Indicates if the operator is thread safe or not
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
static constexpr bool vectorizable = true;
/*!
* \brief Indicates if the operator can be computed on GPU
*/
template <typename E>
static constexpr bool gpu_computable = cuda_enabled;
/*!
* \brief Apply the unary operator on x
* \param x The value on which to apply the operator
* \return The result of applying the unary operator on x
*/
static constexpr T apply(const T& x) noexcept {
return +x;
}
/*!
* \brief Compute several applications of the operator at a time
* \param x The vector on which to operate
* \tparam V The vectorization mode
* \return a vector containing several results of the operator
*/
template <typename V = default_vec>
static vec_type<V> load(const vec_type<V>& x) noexcept {
return x;
}
/*!
* \brief Compute the result of the operation using the GPU
*
* \param x The expression of the unary operation
*
* \return The result of applying the unary operator on x. The result must be a GPU computed expression.
*/
template <typename X>
static auto gpu_compute(const X& x) noexcept {
decltype(auto) t1 = smart_gpu_compute(x);
return force_temporary_gpu_dim_only(t1);
}
/*!
* \brief Compute the result of the operation using the GPU
*
* \param x The expression of the unary operation
* \param y The expression into which to store the reuslt
*/
template <typename X, typename Y>
static Y& gpu_compute(const X& x, Y& y) noexcept {
return smart_gpu_compute(x, y);
}
/*!
* \brief Returns a textual representation of the operator
* \return a string representing the operator
*/
static std::string desc() noexcept {
return "+";
}
};
} //end of namespace etl
| //=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
namespace etl {
/*!
* \brief Unary operation computing the plus operation
* \tparam T The type of value
*/
template <typename T>
struct plus_unary_op {
/*!
* The vectorization type for V
*/
template <typename V = default_vec>
using vec_type = typename V::template vec_type<T>;
static constexpr bool linear = true; ///< Indicates if the operator is linear
static constexpr bool thread_safe = true; ///< Indicates if the operator is thread safe or not
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
static constexpr bool vectorizable = true;
/*!
* \brief Indicates if the operator can be computed on GPU
*/
template <typename E>
static constexpr bool gpu_computable = cuda_enabled && !is_scalar<E>;
/*!
* \brief Apply the unary operator on x
* \param x The value on which to apply the operator
* \return The result of applying the unary operator on x
*/
static constexpr T apply(const T& x) noexcept {
return +x;
}
/*!
* \brief Compute several applications of the operator at a time
* \param x The vector on which to operate
* \tparam V The vectorization mode
* \return a vector containing several results of the operator
*/
template <typename V = default_vec>
static vec_type<V> load(const vec_type<V>& x) noexcept {
return x;
}
/*!
* \brief Compute the result of the operation using the GPU
*
* \param x The expression of the unary operation
*
* \return The result of applying the unary operator on x. The result must be a GPU computed expression.
*/
template <typename X>
static auto gpu_compute(const X& x) noexcept {
decltype(auto) t1 = smart_gpu_compute(x);
return force_temporary_gpu_dim_only(t1);
}
/*!
* \brief Compute the result of the operation using the GPU
*
* \param x The expression of the unary operation
* \param y The expression into which to store the reuslt
*/
template <typename X, typename Y>
static Y& gpu_compute(const X& x, Y& y) noexcept {
return smart_gpu_compute(x, y);
}
/*!
* \brief Returns a textual representation of the operator
* \return a string representing the operator
*/
static std::string desc() noexcept {
return "+";
}
};
} //end of namespace etl
| Fix plus in GPU mode for scalars | Fix plus in GPU mode for scalars
| C++ | mit | wichtounet/etl,wichtounet/etl |
481b6b7958937cd5134dab47d1a58748335d87fb | include/mapnik/image_view.hpp | include/mapnik/image_view.hpp | /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_IMAGE_VIEW_HPP
#define MAPNIK_IMAGE_VIEW_HPP
namespace mapnik {
template <typename T>
class image_view
{
public:
using pixel_type = typename T::pixel_type;
static constexpr std::size_t pixel_size = sizeof(pixel_type);
image_view(unsigned x, unsigned y, unsigned width, unsigned height, T const& data)
: x_(x),
y_(y),
width_(width),
height_(height),
data_(data)
{
if (x_ >= data_.width()) x_=data_.width()-1;
if (y_ >= data_.height()) y_=data_.height()-1;
if (x_ + width_ > data_.width()) width_= data_.width() - x_;
if (y_ + height_ > data_.height()) height_= data_.height() - y_;
}
~image_view() {}
image_view(image_view<T> const& rhs)
: x_(rhs.x_),
y_(rhs.y_),
width_(rhs.width_),
height_(rhs.height_),
data_(rhs.data_) {}
image_view<T> & operator=(image_view<T> const& rhs)
{
if (&rhs==this) return *this;
x_ = rhs.x_;
y_ = rhs.y_;
width_ = rhs.width_;
height_ = rhs.height_;
data_ = rhs.data_;
return *this;
}
inline unsigned x() const
{
return x_;
}
inline unsigned y() const
{
return y_;
}
inline unsigned width() const
{
return width_;
}
inline unsigned height() const
{
return height_;
}
inline unsigned getSize() const
{
return height_ * width_ * pixel_size;
}
inline unsigned getRowSize() const
{
return width_ * pixel_size;
}
inline const pixel_type* getRow(unsigned row) const
{
return data_.getRow(row + y_) + x_;
}
inline const pixel_type* getRow(unsigned row, std::size_t x0) const
{
return data_.getRow(row + y_, x0) + x_;
}
inline const unsigned char* getBytes() const
{
return data_.getBytes();
}
inline T& data()
{
return data_;
}
inline T const& data() const
{
return data_;
}
inline pixel_type* getData()
{
return data_.getData();
}
inline const pixel_type* getData() const
{
return data_.getData();
}
private:
unsigned x_;
unsigned y_;
unsigned width_;
unsigned height_;
T const& data_;
};
}
#endif // MAPNIK_IMAGE_VIEW_HPP
| /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_IMAGE_VIEW_HPP
#define MAPNIK_IMAGE_VIEW_HPP
namespace mapnik {
template <typename T>
class image_view
{
public:
using pixel_type = typename T::pixel_type;
static constexpr std::size_t pixel_size = sizeof(pixel_type);
image_view(unsigned x, unsigned y, unsigned width, unsigned height, T const& data)
: x_(x),
y_(y),
width_(width),
height_(height),
data_(data)
{
if (x_ >= data_.width()) x_=data_.width()-1;
if (y_ >= data_.height()) y_=data_.height()-1;
if (x_ + width_ > data_.width()) width_= data_.width() - x_;
if (y_ + height_ > data_.height()) height_= data_.height() - y_;
}
~image_view() {}
image_view(image_view<T> const& rhs)
: x_(rhs.x_),
y_(rhs.y_),
width_(rhs.width_),
height_(rhs.height_),
data_(rhs.data_) {}
image_view<T> & operator=(image_view<T> const& rhs)
{
if (&rhs==this) return *this;
x_ = rhs.x_;
y_ = rhs.y_;
width_ = rhs.width_;
height_ = rhs.height_;
data_ = rhs.data_;
return *this;
}
inline unsigned x() const
{
return x_;
}
inline unsigned y() const
{
return y_;
}
inline unsigned width() const
{
return width_;
}
inline unsigned height() const
{
return height_;
}
inline unsigned getSize() const
{
return height_ * width_ * pixel_size;
}
inline unsigned getRowSize() const
{
return width_ * pixel_size;
}
inline const pixel_type* getRow(unsigned row) const
{
return data_.getRow(row + y_) + x_;
}
inline const pixel_type* getRow(unsigned row, std::size_t x0) const
{
return data_.getRow(row + y_, x0) + x_;
}
inline const unsigned char* getBytes() const
{
return data_.getBytes();
}
inline T const& data() const
{
return data_;
}
inline const pixel_type* getData() const
{
return data_.getData();
}
private:
unsigned x_;
unsigned y_;
unsigned width_;
unsigned height_;
T const& data_;
};
}
#endif // MAPNIK_IMAGE_VIEW_HPP
| remove uneeded/unused nonconst access to image_view - amends 0d2eb9cb5f2d71 | remove uneeded/unused nonconst access to image_view - amends 0d2eb9cb5f2d71
| C++ | lgpl-2.1 | manz/python-mapnik,lightmare/mapnik,rouault/mapnik,tomhughes/mapnik,pramsey/mapnik,rouault/mapnik,mapnik/mapnik,yohanboniface/python-mapnik,mapnik/python-mapnik,rouault/mapnik,Airphrame/mapnik,manz/python-mapnik,Airphrame/mapnik,mbrukman/mapnik,sebastic/python-mapnik,mbrukman/mapnik,tomhughes/python-mapnik,pnorman/mapnik,naturalatlas/mapnik,jwomeara/mapnik,Airphrame/mapnik,Uli1/mapnik,stefanklug/mapnik,cjmayo/mapnik,pnorman/mapnik,mapycz/python-mapnik,jwomeara/mapnik,Uli1/mapnik,lightmare/mapnik,zerebubuth/mapnik,stefanklug/mapnik,zerebubuth/mapnik,mapnik/mapnik,davenquinn/python-mapnik,yohanboniface/python-mapnik,whuaegeanse/mapnik,pnorman/mapnik,stefanklug/mapnik,mapycz/mapnik,tomhughes/mapnik,pramsey/mapnik,stefanklug/mapnik,rouault/mapnik,cjmayo/mapnik,CartoDB/mapnik,tomhughes/mapnik,tomhughes/python-mapnik,whuaegeanse/mapnik,jwomeara/mapnik,pramsey/mapnik,tomhughes/python-mapnik,mapycz/python-mapnik,naturalatlas/mapnik,Airphrame/mapnik,mapnik/python-mapnik,davenquinn/python-mapnik,sebastic/python-mapnik,mapnik/mapnik,CartoDB/mapnik,mapycz/mapnik,cjmayo/mapnik,manz/python-mapnik,mbrukman/mapnik,mapnik/python-mapnik,yohanboniface/python-mapnik,sebastic/python-mapnik,whuaegeanse/mapnik,lightmare/mapnik,jwomeara/mapnik,tomhughes/mapnik,mapycz/mapnik,Uli1/mapnik,mbrukman/mapnik,pnorman/mapnik,Uli1/mapnik,garnertb/python-mapnik,garnertb/python-mapnik,CartoDB/mapnik,davenquinn/python-mapnik,zerebubuth/mapnik,mapnik/mapnik,garnertb/python-mapnik,lightmare/mapnik,pramsey/mapnik,naturalatlas/mapnik,cjmayo/mapnik,whuaegeanse/mapnik,naturalatlas/mapnik |
9cf1b62055a194dc6fc199f47b6f8efc96e75f9f | src/runtime/opencl/opencl_device_api.cc | src/runtime/opencl/opencl_device_api.cc | /*!
* Copyright (c) 2017 by Contributors
* \file opencl_device_api.cc
*/
#include <tvm/runtime/registry.h>
#include <dmlc/thread_local.h>
#include "opencl_common.h"
namespace tvm {
namespace runtime {
namespace cl {
OpenCLThreadEntry* OpenCLWorkspace::GetThreadEntry() {
return OpenCLThreadEntry::ThreadLocal();
}
const std::shared_ptr<OpenCLWorkspace>& OpenCLWorkspace::Global() {
static std::shared_ptr<OpenCLWorkspace> inst = std::make_shared<OpenCLWorkspace>();
return inst;
}
void OpenCLWorkspace::SetDevice(TVMContext ctx) {
GetThreadEntry()->context.device_id = ctx.device_id;
}
void OpenCLWorkspace::GetAttr(
TVMContext ctx, DeviceAttrKind kind, TVMRetValue* rv) {
this->Init();
size_t index = static_cast<size_t>(ctx.device_id);
if (kind == kExist) {
*rv = static_cast<int>(index< devices.size());
return;
}
CHECK_LT(index, devices.size())
<< "Invalid device id " << index;
switch (kind) {
case kExist: break;
case kMaxThreadsPerBlock: {
size_t value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_WORK_GROUP_SIZE,
sizeof(size_t), &value, nullptr));
*rv = static_cast<int64_t>(value);
break;
}
case kWarpSize: {
/* TODO: the warp size of OpenCL device is not always 1
e.g. Intel Graphics has a sub group concept which contains 8 - 32 work items,
corresponding to the number of SIMD entries the heardware configures.
We need to figure out a way to query this information from the hardware.
*/
*rv = 1;
break;
}
case kMaxSharedMemoryPerBlock: {
cl_ulong value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_LOCAL_MEM_SIZE,
sizeof(cl_ulong), &value, nullptr));
*rv = static_cast<int64_t>(value);
break;
}
case kComputeVersion: return;
case kDeviceName: {
char value[128] = {0};
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_NAME,
sizeof(value) - 1, value, nullptr));
*rv = std::string(value);
break;
}
case kMaxClockRate: {
cl_uint value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_CLOCK_FREQUENCY,
sizeof(cl_uint), &value, nullptr));
*rv = static_cast<int32_t>(value);
break;
}
case kMultiProcessorCount: {
cl_uint value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_COMPUTE_UNITS,
sizeof(cl_uint), &value, nullptr));
*rv = static_cast<int32_t>(value);
break;
}
case kMaxThreadDimensions: {
size_t dims[3];
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(dims), dims, nullptr));
std::stringstream ss; // use json string to return multiple int values;
ss << "[" << dims[0] <<", " << dims[1] << ", " << dims[2] << "]";
*rv = ss.str();
break;
}
}
}
void* OpenCLWorkspace::AllocDataSpace(
TVMContext ctx, size_t size, size_t alignment, TVMType type_hint) {
this->Init();
CHECK(context != nullptr) << "No OpenCL device";
cl_int err_code;
cl_mem mptr = clCreateBuffer(
this->context, CL_MEM_READ_WRITE, size, nullptr, &err_code);
OPENCL_CHECK_ERROR(err_code);
return mptr;
}
void OpenCLWorkspace::FreeDataSpace(TVMContext ctx, void* ptr) {
// We have to make sure that the memory object is not in the command queue
// for some OpenCL platforms.
OPENCL_CALL(clFinish(this->GetQueue(ctx)));
cl_mem mptr = static_cast<cl_mem>(ptr);
OPENCL_CALL(clReleaseMemObject(mptr));
}
void OpenCLWorkspace::CopyDataFromTo(const void* from,
size_t from_offset,
void* to,
size_t to_offset,
size_t size,
TVMContext ctx_from,
TVMContext ctx_to,
TVMType type_hint,
TVMStreamHandle stream) {
this->Init();
CHECK(stream == nullptr);
if (IsOpenCLDevice(ctx_from) && IsOpenCLDevice(ctx_to)) {
OPENCL_CALL(clEnqueueCopyBuffer(
this->GetQueue(ctx_to),
static_cast<cl_mem>((void*)from), // NOLINT(*)
static_cast<cl_mem>(to),
from_offset, to_offset, size, 0, nullptr, nullptr));
} else if (IsOpenCLDevice(ctx_from) && ctx_to.device_type == kDLCPU) {
OPENCL_CALL(clEnqueueReadBuffer(
this->GetQueue(ctx_from),
static_cast<cl_mem>((void*)from), // NOLINT(*)
CL_FALSE, from_offset, size,
static_cast<char*>(to) + to_offset,
0, nullptr, nullptr));
OPENCL_CALL(clFinish(this->GetQueue(ctx_from)));
} else if (ctx_from.device_type == kDLCPU && IsOpenCLDevice(ctx_to)) {
OPENCL_CALL(clEnqueueWriteBuffer(
this->GetQueue(ctx_to),
static_cast<cl_mem>(to),
CL_FALSE, to_offset, size,
static_cast<const char*>(from) + from_offset,
0, nullptr, nullptr));
OPENCL_CALL(clFinish(this->GetQueue(ctx_to)));
} else {
LOG(FATAL) << "Expect copy from/to OpenCL or between OpenCL";
}
}
void OpenCLWorkspace::StreamSync(TVMContext ctx, TVMStreamHandle stream) {
CHECK(stream == nullptr);
OPENCL_CALL(clFinish(this->GetQueue(ctx)));
}
void* OpenCLWorkspace::AllocWorkspace(TVMContext ctx,
size_t size,
TVMType type_hint) {
return GetThreadEntry()->pool.AllocWorkspace(ctx, size);
}
void OpenCLWorkspace::FreeWorkspace(TVMContext ctx, void* data) {
GetThreadEntry()->pool.FreeWorkspace(ctx, data);
}
typedef dmlc::ThreadLocalStore<OpenCLThreadEntry> OpenCLThreadStore;
OpenCLThreadEntry* OpenCLThreadEntry::ThreadLocal() {
return OpenCLThreadStore::Get();
}
std::string GetPlatformInfo(
cl_platform_id pid, cl_platform_info param_name) {
size_t ret_size;
OPENCL_CALL(clGetPlatformInfo(pid, param_name, 0, nullptr, &ret_size));
std::string ret;
ret.resize(ret_size);
OPENCL_CALL(clGetPlatformInfo(pid, param_name, ret_size, &ret[0], nullptr));
return ret;
}
std::string GetDeviceInfo(
cl_device_id pid, cl_device_info param_name) {
size_t ret_size;
OPENCL_CALL(clGetDeviceInfo(pid, param_name, 0, nullptr, &ret_size));
std::string ret;
ret.resize(ret_size);
OPENCL_CALL(clGetDeviceInfo(pid, param_name, ret_size, &ret[0], nullptr));
return ret;
}
std::vector<cl_platform_id> GetPlatformIDs() {
cl_uint ret_size;
cl_int code = clGetPlatformIDs(0, nullptr, &ret_size);
std::vector<cl_platform_id> ret;
if (code != CL_SUCCESS) return ret;
ret.resize(ret_size);
OPENCL_CALL(clGetPlatformIDs(ret_size, &ret[0], nullptr));
return ret;
}
std::vector<cl_device_id> GetDeviceIDs(
cl_platform_id pid, std::string device_type) {
cl_device_type dtype = CL_DEVICE_TYPE_ALL;
if (device_type == "cpu") dtype = CL_DEVICE_TYPE_CPU;
if (device_type == "gpu") dtype = CL_DEVICE_TYPE_GPU;
if (device_type == "accelerator") dtype = CL_DEVICE_TYPE_ACCELERATOR;
cl_uint ret_size;
cl_int code = clGetDeviceIDs(pid, dtype, 0, nullptr, &ret_size);
std::vector<cl_device_id> ret;
if (code != CL_SUCCESS) return ret;
ret.resize(ret_size);
OPENCL_CALL(clGetDeviceIDs(pid, dtype, ret_size, &ret[0], nullptr));
return ret;
}
bool MatchPlatformInfo(
cl_platform_id pid,
cl_platform_info param_name,
std::string value) {
if (value.length() == 0) return true;
std::string param_value = GetPlatformInfo(pid, param_name);
return param_value.find(value) != std::string::npos;
}
void OpenCLWorkspace::Init(const std::string& type_key, const std::string& device_type,
const std::string& platform_name) {
if (initialized_) return;
std::lock_guard<std::mutex> lock(this->mu);
if (initialized_) return;
if (context != nullptr) return;
// matched platforms
std::vector<cl_platform_id> platform_ids = cl::GetPlatformIDs();
if (platform_ids.size() == 0) {
LOG(WARNING) << "No OpenCL platform matched given existing options ...";
return;
}
this->platform_id = nullptr;
for (auto platform_id : platform_ids) {
if (!MatchPlatformInfo(platform_id, CL_PLATFORM_NAME, platform_name)) {
continue;
}
std::vector<cl_device_id> devices_matched = cl::GetDeviceIDs(platform_id, device_type);
if ((devices_matched.size() == 0) && (device_type == "gpu")) {
LOG(WARNING) << "Using CPU OpenCL device";
devices_matched = cl::GetDeviceIDs(platform_id, "cpu");
}
if (devices_matched.size() > 0) {
this->type_key = type_key;
this->platform_id = platform_id;
this->platform_name = cl::GetPlatformInfo(platform_id, CL_PLATFORM_NAME);
this->device_type = device_type;
this->devices = devices_matched;
break;
}
}
if (this->platform_id == nullptr) {
LOG(WARNING) << "No OpenCL device";
return;
}
cl_int err_code;
this->context = clCreateContext(
nullptr, this->devices.size(), &(this->devices[0]),
nullptr, nullptr, &err_code);
OPENCL_CHECK_ERROR(err_code);
CHECK_EQ(this->queues.size(), 0U);
for (size_t i = 0; i < this->devices.size(); ++i) {
cl_device_id did = this->devices[i];
this->queues.push_back(
clCreateCommandQueue(this->context, did, 0, &err_code));
OPENCL_CHECK_ERROR(err_code);
}
initialized_ = true;
}
TVM_REGISTER_GLOBAL("device_api.opencl")
.set_body([](TVMArgs args, TVMRetValue* rv) {
DeviceAPI* ptr = OpenCLWorkspace::Global().get();
*rv = static_cast<void*>(ptr);
});
} // namespace cl
} // namespace runtime
} // namespace tvm
| /*!
* Copyright (c) 2017 by Contributors
* \file opencl_device_api.cc
*/
#include <tvm/runtime/registry.h>
#include <dmlc/thread_local.h>
#include "opencl_common.h"
namespace tvm {
namespace runtime {
namespace cl {
OpenCLThreadEntry* OpenCLWorkspace::GetThreadEntry() {
return OpenCLThreadEntry::ThreadLocal();
}
const std::shared_ptr<OpenCLWorkspace>& OpenCLWorkspace::Global() {
static std::shared_ptr<OpenCLWorkspace> inst = std::make_shared<OpenCLWorkspace>();
return inst;
}
void OpenCLWorkspace::SetDevice(TVMContext ctx) {
GetThreadEntry()->context.device_id = ctx.device_id;
}
void OpenCLWorkspace::GetAttr(
TVMContext ctx, DeviceAttrKind kind, TVMRetValue* rv) {
this->Init();
size_t index = static_cast<size_t>(ctx.device_id);
if (kind == kExist) {
*rv = static_cast<int>(index< devices.size());
return;
}
CHECK_LT(index, devices.size())
<< "Invalid device id " << index;
switch (kind) {
case kExist: break;
case kMaxThreadsPerBlock: {
size_t value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_WORK_GROUP_SIZE,
sizeof(size_t), &value, nullptr));
*rv = static_cast<int64_t>(value);
break;
}
case kWarpSize: {
/* TODO: the warp size of OpenCL device is not always 1
e.g. Intel Graphics has a sub group concept which contains 8 - 32 work items,
corresponding to the number of SIMD entries the heardware configures.
We need to figure out a way to query this information from the hardware.
*/
*rv = 1;
break;
}
case kMaxSharedMemoryPerBlock: {
cl_ulong value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_LOCAL_MEM_SIZE,
sizeof(cl_ulong), &value, nullptr));
*rv = static_cast<int64_t>(value);
break;
}
case kComputeVersion: return;
case kDeviceName: {
char value[128] = {0};
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_NAME,
sizeof(value) - 1, value, nullptr));
*rv = std::string(value);
break;
}
case kMaxClockRate: {
cl_uint value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_CLOCK_FREQUENCY,
sizeof(cl_uint), &value, nullptr));
*rv = static_cast<int32_t>(value);
break;
}
case kMultiProcessorCount: {
cl_uint value;
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_COMPUTE_UNITS,
sizeof(cl_uint), &value, nullptr));
*rv = static_cast<int32_t>(value);
break;
}
case kMaxThreadDimensions: {
size_t dims[3];
OPENCL_CALL(clGetDeviceInfo(
devices[index], CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(dims), dims, nullptr));
std::stringstream ss; // use json string to return multiple int values;
ss << "[" << dims[0] <<", " << dims[1] << ", " << dims[2] << "]";
*rv = ss.str();
break;
}
}
}
void* OpenCLWorkspace::AllocDataSpace(
TVMContext ctx, size_t size, size_t alignment, TVMType type_hint) {
this->Init();
CHECK(context != nullptr) << "No OpenCL device";
cl_int err_code;
cl_mem mptr = clCreateBuffer(
this->context, CL_MEM_READ_WRITE, size, nullptr, &err_code);
OPENCL_CHECK_ERROR(err_code);
return mptr;
}
void OpenCLWorkspace::FreeDataSpace(TVMContext ctx, void* ptr) {
// We have to make sure that the memory object is not in the command queue
// for some OpenCL platforms.
OPENCL_CALL(clFinish(this->GetQueue(ctx)));
cl_mem mptr = static_cast<cl_mem>(ptr);
OPENCL_CALL(clReleaseMemObject(mptr));
}
void OpenCLWorkspace::CopyDataFromTo(const void* from,
size_t from_offset,
void* to,
size_t to_offset,
size_t size,
TVMContext ctx_from,
TVMContext ctx_to,
TVMType type_hint,
TVMStreamHandle stream) {
this->Init();
CHECK(stream == nullptr);
if (IsOpenCLDevice(ctx_from) && IsOpenCLDevice(ctx_to)) {
OPENCL_CALL(clEnqueueCopyBuffer(
this->GetQueue(ctx_to),
static_cast<cl_mem>((void*)from), // NOLINT(*)
static_cast<cl_mem>(to),
from_offset, to_offset, size, 0, nullptr, nullptr));
} else if (IsOpenCLDevice(ctx_from) && ctx_to.device_type == kDLCPU) {
OPENCL_CALL(clEnqueueReadBuffer(
this->GetQueue(ctx_from),
static_cast<cl_mem>((void*)from), // NOLINT(*)
CL_FALSE, from_offset, size,
static_cast<char*>(to) + to_offset,
0, nullptr, nullptr));
OPENCL_CALL(clFinish(this->GetQueue(ctx_from)));
} else if (ctx_from.device_type == kDLCPU && IsOpenCLDevice(ctx_to)) {
OPENCL_CALL(clEnqueueWriteBuffer(
this->GetQueue(ctx_to),
static_cast<cl_mem>(to),
CL_FALSE, to_offset, size,
static_cast<const char*>(from) + from_offset,
0, nullptr, nullptr));
OPENCL_CALL(clFinish(this->GetQueue(ctx_to)));
} else {
LOG(FATAL) << "Expect copy from/to OpenCL or between OpenCL";
}
}
void OpenCLWorkspace::StreamSync(TVMContext ctx, TVMStreamHandle stream) {
CHECK(stream == nullptr);
OPENCL_CALL(clFinish(this->GetQueue(ctx)));
}
void* OpenCLWorkspace::AllocWorkspace(TVMContext ctx,
size_t size,
TVMType type_hint) {
return GetThreadEntry()->pool.AllocWorkspace(ctx, size);
}
void OpenCLWorkspace::FreeWorkspace(TVMContext ctx, void* data) {
GetThreadEntry()->pool.FreeWorkspace(ctx, data);
}
typedef dmlc::ThreadLocalStore<OpenCLThreadEntry> OpenCLThreadStore;
OpenCLThreadEntry* OpenCLThreadEntry::ThreadLocal() {
return OpenCLThreadStore::Get();
}
std::string GetPlatformInfo(
cl_platform_id pid, cl_platform_info param_name) {
size_t ret_size;
OPENCL_CALL(clGetPlatformInfo(pid, param_name, 0, nullptr, &ret_size));
std::string ret;
ret.resize(ret_size);
OPENCL_CALL(clGetPlatformInfo(pid, param_name, ret_size, &ret[0], nullptr));
return ret;
}
std::string GetDeviceInfo(
cl_device_id pid, cl_device_info param_name) {
size_t ret_size;
OPENCL_CALL(clGetDeviceInfo(pid, param_name, 0, nullptr, &ret_size));
std::string ret;
ret.resize(ret_size);
OPENCL_CALL(clGetDeviceInfo(pid, param_name, ret_size, &ret[0], nullptr));
return ret;
}
std::vector<cl_platform_id> GetPlatformIDs() {
cl_uint ret_size;
cl_int code = clGetPlatformIDs(0, nullptr, &ret_size);
std::vector<cl_platform_id> ret;
if (code != CL_SUCCESS) return ret;
ret.resize(ret_size);
OPENCL_CALL(clGetPlatformIDs(ret_size, &ret[0], nullptr));
return ret;
}
std::vector<cl_device_id> GetDeviceIDs(
cl_platform_id pid, std::string device_type) {
cl_device_type dtype = CL_DEVICE_TYPE_ALL;
if (device_type == "cpu") dtype = CL_DEVICE_TYPE_CPU;
if (device_type == "gpu") dtype = CL_DEVICE_TYPE_GPU;
if (device_type == "accelerator") dtype = CL_DEVICE_TYPE_ACCELERATOR;
cl_uint ret_size;
cl_int code = clGetDeviceIDs(pid, dtype, 0, nullptr, &ret_size);
std::vector<cl_device_id> ret;
if (code != CL_SUCCESS) return ret;
ret.resize(ret_size);
OPENCL_CALL(clGetDeviceIDs(pid, dtype, ret_size, &ret[0], nullptr));
return ret;
}
bool MatchPlatformInfo(
cl_platform_id pid,
cl_platform_info param_name,
std::string value) {
if (value.length() == 0) return true;
std::string param_value = GetPlatformInfo(pid, param_name);
return param_value.find(value) != std::string::npos;
}
void OpenCLWorkspace::Init(const std::string& type_key, const std::string& device_type,
const std::string& platform_name) {
if (initialized_) return;
std::lock_guard<std::mutex> lock(this->mu);
if (initialized_) return;
if (context != nullptr) return;
this->type_key = type_key;
// matched platforms
std::vector<cl_platform_id> platform_ids = cl::GetPlatformIDs();
if (platform_ids.size() == 0) {
LOG(WARNING) << "No OpenCL platform matched given existing options ...";
return;
}
this->platform_id = nullptr;
for (auto platform_id : platform_ids) {
if (!MatchPlatformInfo(platform_id, CL_PLATFORM_NAME, platform_name)) {
continue;
}
std::vector<cl_device_id> devices_matched = cl::GetDeviceIDs(platform_id, device_type);
if ((devices_matched.size() == 0) && (device_type == "gpu")) {
LOG(WARNING) << "Using CPU OpenCL device";
devices_matched = cl::GetDeviceIDs(platform_id, "cpu");
}
if (devices_matched.size() > 0) {
this->platform_id = platform_id;
this->platform_name = cl::GetPlatformInfo(platform_id, CL_PLATFORM_NAME);
this->device_type = device_type;
this->devices = devices_matched;
break;
}
}
if (this->platform_id == nullptr) {
LOG(WARNING) << "No OpenCL device";
return;
}
cl_int err_code;
this->context = clCreateContext(
nullptr, this->devices.size(), &(this->devices[0]),
nullptr, nullptr, &err_code);
OPENCL_CHECK_ERROR(err_code);
CHECK_EQ(this->queues.size(), 0U);
for (size_t i = 0; i < this->devices.size(); ++i) {
cl_device_id did = this->devices[i];
this->queues.push_back(
clCreateCommandQueue(this->context, did, 0, &err_code));
OPENCL_CHECK_ERROR(err_code);
}
initialized_ = true;
}
TVM_REGISTER_GLOBAL("device_api.opencl")
.set_body([](TVMArgs args, TVMRetValue* rv) {
DeviceAPI* ptr = OpenCLWorkspace::Global().get();
*rv = static_cast<void*>(ptr);
});
} // namespace cl
} // namespace runtime
} // namespace tvm
| set type_key even when platform is not available (#2741) | [RUNTIME][OPENCL] set type_key even when platform is not available (#2741)
| C++ | apache-2.0 | Laurawly/tvm-1,Laurawly/tvm-1,Laurawly/tvm-1,Laurawly/tvm-1,Huyuwei/tvm,Huyuwei/tvm,sxjscience/tvm,Huyuwei/tvm,dmlc/tvm,dmlc/tvm,tqchen/tvm,dmlc/tvm,Laurawly/tvm-1,sxjscience/tvm,Huyuwei/tvm,Laurawly/tvm-1,sxjscience/tvm,Huyuwei/tvm,dmlc/tvm,dmlc/tvm,tqchen/tvm,Laurawly/tvm-1,Huyuwei/tvm,tqchen/tvm,sxjscience/tvm,tqchen/tvm,tqchen/tvm,sxjscience/tvm,dmlc/tvm,sxjscience/tvm,tqchen/tvm,Laurawly/tvm-1,tqchen/tvm,Laurawly/tvm-1,Huyuwei/tvm,dmlc/tvm,Huyuwei/tvm,tqchen/tvm,dmlc/tvm,dmlc/tvm,tqchen/tvm,Huyuwei/tvm,sxjscience/tvm,sxjscience/tvm,sxjscience/tvm,Laurawly/tvm-1,tqchen/tvm |
c278f7391a24ad680ea4017755887c7058a6f91f | include/zmsg/zmsg_fs_spec.hpp | include/zmsg/zmsg_fs_spec.hpp | #pragma once
#include "zmsg_types.hpp"
namespace zmsg {
template<>
struct zmsg<mid_t::set_fs_spec> {
public:
uint16_t window_x_row; // unit: pixel
uint16_t window_x_col; // unit: pixel
uint16_t window_y_row; // unit: pixel
uint16_t window_y_col; // unit: pixel
uint32_t nm_per_pixel; // unit: nm/pixel
uint32_t nm_per_step; // unit: nm/step
uint16_t img_cap_delay; // unit: ms
uint16_t img_delay_for_env_change; // unit: ms
uint32_t clr_discharge_gap; // unit: nm
uint16_t check_fiber_exist_time; // unit: ms
uint16_t motor_min_speed[motorId_t::NUM];
uint16_t motor_max_speed[motorId_t::NUM];
uint16_t motor_lzrz_fs_speed;
uint32_t motor_xy_precise_calibrate_speed;
uint16_t motor_xy_steps_per_pixel; // unit: step/pixel
double fiber_outline_blacklevel; // 0.0 ~ 1.0
double calibrating_xy_dist_threshold; // unit: pixel
double precise_calibrating_xy_dist_threshold; // unit: pixel
double z_dist_threshold; // unit: pixel
discharge_data_t discharge_base;
discharge_data_t discharge_revise;
double dust_check_threshold0;
double dust_check_threshold1;
double led_brightness[ledId_t::LED_NUM];
public:
ZMSG_PU(
window_x_row,
window_x_col,
window_y_row,
window_y_col,
nm_per_pixel,
nm_per_step,
img_cap_delay,
img_delay_for_env_change,
clr_discharge_gap,
check_fiber_exist_time,
motor_min_speed,
motor_max_speed,
motor_lzrz_fs_speed,
motor_xy_precise_calibrate_speed,
motor_xy_steps_per_pixel,
fiber_outline_blacklevel,
calibrating_xy_dist_threshold,
precise_calibrating_xy_dist_threshold,
z_dist_threshold,
discharge_base,
discharge_revise,
dust_check_threshold0,
dust_check_threshold1,
led_brightness)
};
template<>
struct zmsg<mid_t::update_led_brightness> {
public:
ledId_t id;
double brightness;
public:
ZMSG_PU(id,
brightness)
};
}
| #pragma once
#include "zmsg_types.hpp"
namespace zmsg {
template<>
struct zmsg<mid_t::set_fs_spec> {
public:
uint16_t window_x_row; // unit: pixel
uint16_t window_x_col; // unit: pixel
uint16_t window_y_row; // unit: pixel
uint16_t window_y_col; // unit: pixel
uint32_t nm_per_pixel; // unit: nm/pixel
uint32_t nm_per_step; // unit: nm/step
uint16_t img_cap_delay; // unit: ms
uint32_t clr_discharge_gap; // unit: nm
uint16_t check_fiber_exist_time; // unit: ms
uint16_t motor_min_speed[motorId_t::NUM];
uint16_t motor_max_speed[motorId_t::NUM];
uint16_t motor_lzrz_fs_speed;
uint32_t motor_xy_precise_calibrate_speed;
uint16_t motor_xy_steps_per_pixel; // unit: step/pixel
double fiber_outline_blacklevel; // 0.0 ~ 1.0
double calibrating_xy_dist_threshold; // unit: pixel
double precise_calibrating_xy_dist_threshold; // unit: pixel
double z_dist_threshold; // unit: pixel
discharge_data_t discharge_base;
discharge_data_t discharge_revise;
double dust_check_threshold0;
double dust_check_threshold1;
double led_brightness[ledId_t::LED_NUM];
public:
ZMSG_PU(
window_x_row,
window_x_col,
window_y_row,
window_y_col,
nm_per_pixel,
nm_per_step,
img_cap_delay,
clr_discharge_gap,
check_fiber_exist_time,
motor_min_speed,
motor_max_speed,
motor_lzrz_fs_speed,
motor_xy_precise_calibrate_speed,
motor_xy_steps_per_pixel,
fiber_outline_blacklevel,
calibrating_xy_dist_threshold,
precise_calibrating_xy_dist_threshold,
z_dist_threshold,
discharge_base,
discharge_revise,
dust_check_threshold0,
dust_check_threshold1,
led_brightness)
};
template<>
struct zmsg<mid_t::update_led_brightness> {
public:
ledId_t id;
double brightness;
public:
ZMSG_PU(id,
brightness)
};
}
| revert last change | revert last change
Signed-off-by: Yi Qingliang <[email protected]>
| C++ | apache-2.0 | walkthetalk/libem,walkthetalk/libem,walkthetalk/libem |
26bcad7df70c2c26098aa6a8dd191b7179e40b37 | src/grid/VoxelGridMap.hpp | src/grid/VoxelGridMap.hpp | #pragma once
#include "GridMap.hpp"
#include "DiscreteTree.hpp"
namespace maps { namespace grid
{
template<class CellT>
class VoxelGridMap : public GridMap< DiscreteTree<CellT> >
{
typedef GridMap< DiscreteTree<CellT> > _Base;
public:
VoxelGridMap(const Vector2ui &num_cells,
const Eigen::Vector3d &resolution) :
GridMap< DiscreteTree<CellT> >(num_cells,
resolution.block(0,0,2,1), DiscreteTree<CellT>(resolution.z())) {}
bool hasVoxelCell(const Eigen::Vector3d &position) const
{
Index idx;
if(_Base::toGrid(position, idx))
{
return _Base::at(idx).hasCell(position.z());
}
return false;
}
bool hasVoxelCell(const Eigen::Vector3i &index) const
{
Index idx = index.block(0,0,2,1);
return _Base::at(idx).hasCell(index.z());
}
CellT& getVoxelCell(const Eigen::Vector3i &index)
{
Index idx = index.block(0,0,2,1);
return _Base::at(idx).getCellAt(index.z());
}
CellT& getVoxelCell(const Eigen::Vector3d &position)
{
return _Base::at(position)[position.z()];
}
bool fromVoxelGrid(const Eigen::Vector3i& idx, Eigen::Vector3d& position) const
{
Index idx_2d = idx.block(0,0,2,1);
if(_Base::fromGrid(idx_2d, position))
{
position << position.block(0,0,2,1), _Base::at(idx_2d).getCellCenter(idx.z());
return true;
}
return false;
}
bool toVoxelGrid(const Eigen::Vector3d& position, Eigen::Vector3i& idx) const
{
Index idx_2d;
if(_Base::toGrid(position, idx_2d))
{
idx << idx_2d, _Base::at(idx_2d).getCellIndex(position.z());
return true;
}
return false;
}
bool toVoxelGrid(const Eigen::Vector3d& position, Eigen::Vector3i& idx, Eigen::Vector3d &pos_diff) const
{
Index idx_2d;
if(_Base::toGrid(position, idx_2d, pos_diff))
{
idx << idx_2d, _Base::at(idx_2d).getCellIndex(position.z(), pos_diff.z());
return true;
}
return false;
}
Eigen::Vector3d getVoxelResolution() const
{
Eigen::Vector3d res;
res << _Base::getResolution(), _Base::getDefaultValue().getResolution();
return res;
}
protected:
/** Grants access to boost serialization */
friend class boost::serialization::access;
/** Serializes the members of this class*/
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(GridMap< DiscreteTree<CellT> >);
}
};
}} | #pragma once
#include "GridMap.hpp"
#include "DiscreteTree.hpp"
namespace maps { namespace grid
{
template<class CellT>
class VoxelGridMap : public GridMap< DiscreteTree<CellT> >
{
typedef GridMap< DiscreteTree<CellT> > _Base;
public:
VoxelGridMap(const Vector2ui &num_cells,
const Eigen::Vector3d &resolution) :
GridMap< DiscreteTree<CellT> >(num_cells,
resolution.block(0,0,2,1), DiscreteTree<CellT>(resolution.z())) {}
bool hasVoxelCell(const Eigen::Vector3d &position) const
{
Index idx;
if(_Base::toGrid(position, idx))
{
return _Base::at(idx).hasCell(position.z());
}
return false;
}
bool hasVoxelCell(const Eigen::Vector3i &index) const
{
Index idx = index.block(0,0,2,1);
return _Base::at(idx).hasCell(index.z());
}
CellT& getVoxelCell(const Eigen::Vector3i &index)
{
Index idx = index.block(0,0,2,1);
return _Base::at(idx).getCellAt(index.z());
}
CellT& getVoxelCell(const Eigen::Vector3d &position)
{
return _Base::at(position)[position.z()];
}
bool fromVoxelGrid(const Eigen::Vector3i& idx, Eigen::Vector3d& position, bool checkIndex = true) const
{
Index idx_2d = idx.block(0,0,2,1);
if(_Base::fromGrid(idx_2d, position, checkIndex))
{
position << position.block(0,0,2,1), _Base::getDefaultValue().getCellCenter(idx.z());
return true;
}
return false;
}
bool toVoxelGrid(const Eigen::Vector3d& position, Eigen::Vector3i& idx, bool checkIndex = true) const
{
Index idx_2d;
if(_Base::toGrid(position, idx_2d, checkIndex))
{
idx << idx_2d, _Base::getDefaultValue().getCellIndex(position.z(), checkIndex);
return true;
}
return false;
}
bool toVoxelGrid(const Eigen::Vector3d& position, Eigen::Vector3i& idx, Eigen::Vector3d &pos_diff) const
{
Index idx_2d;
if(_Base::toGrid(position, idx_2d, pos_diff))
{
idx << idx_2d, _Base::at(idx_2d).getCellIndex(position.z(), pos_diff.z());
return true;
}
return false;
}
Eigen::Vector3d getVoxelResolution() const
{
Eigen::Vector3d res;
res << _Base::getResolution(), _Base::getDefaultValue().getResolution();
return res;
}
protected:
/** Grants access to boost serialization */
friend class boost::serialization::access;
/** Serializes the members of this class*/
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(GridMap< DiscreteTree<CellT> >);
}
};
}} | use default tree to lookup the index and cell center | use default tree to lookup the index and cell center
This allows to get valid values even if the cells are outside of the defined grid.
Even if every discrete tree has its own resolution, VoxelGridMap requires them to have the same
| C++ | bsd-2-clause | envire/slam-maps,envire/slam-maps |
e773b0486a4784994a900c03a2620baf2775ac9d | src/gui/kernel/qt_mac.cpp | src/gui/kernel/qt_mac.cpp | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include <private/qt_mac_p.h>
#include <private/qpixmap_mac_p.h>
#include <private/qnativeimage_p.h>
#include <qdebug.h>
QT_BEGIN_NAMESPACE
#ifdef QT_MAC_USE_COCOA
static CTFontRef CopyCTThemeFont(ThemeFontID themeID)
{
CTFontUIFontType ctID = HIThemeGetUIFontType(themeID);
return CTFontCreateUIFontForLanguage(ctID, 0, 0);
}
#endif
QFont qfontForThemeFont(ThemeFontID themeID)
{
#ifndef QT_MAC_USE_COCOA
static const ScriptCode Script = smRoman;
Str255 f_name;
SInt16 f_size;
Style f_style;
GetThemeFont(themeID, Script, f_name, &f_size, &f_style);
extern QString qt_mac_from_pascal_string(const Str255); //qglobal.cpp
return QFont(qt_mac_from_pascal_string(f_name), f_size,
(f_style & ::bold) ? QFont::Bold : QFont::Normal,
(bool)(f_style & ::italic));
#else
QCFType<CTFontRef> ctfont = CopyCTThemeFont(themeID);
QString familyName = QCFString(CTFontCopyFamilyName(ctfont));
QCFType<CFDictionaryRef> dict = CTFontCopyTraits(ctfont);
CFNumberRef num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontWeightTrait));
float fW;
CFNumberGetValue(num, kCFNumberFloat32Type, &fW);
QFont::Weight wght = fW > 0. ? QFont::Bold : QFont::Normal;
num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontSlantTrait));
CFNumberGetValue(num, kCFNumberFloatType, &fW);
bool italic = (fW != 0.0);
return QFont(familyName, CTFontGetSize(ctfont), wght, italic);
#endif
}
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
static QColor qcolorFromCGColor(CGColorRef cgcolor)
{
QColor pc;
CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(cgcolor));
const CGFloat *components = CGColorGetComponents(cgcolor);
if (model == kCGColorSpaceModelRGB) {
pc.setRgbF(components[0], components[1], components[2], components[3]);
} else if (model == kCGColorSpaceModelCMYK) {
pc.setCmykF(components[0], components[1], components[2], components[3]);
} else {
// Colorspace we can't deal with.
qWarning("Qt: qcolorFromCGColor: cannot convert from colorspace model: %d", model);
Q_ASSERT(false);
}
return pc;
}
static inline QColor leopardBrush(ThemeBrush brush)
{
QCFType<CGColorRef> cgClr = 0;
HIThemeBrushCreateCGColor(brush, &cgClr);
return qcolorFromCGColor(cgClr);
}
#endif
QColor qcolorForTheme(ThemeBrush brush)
{
#ifndef QT_MAC_USE_COCOA
# if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
return leopardBrush(brush);
} else
# endif
{
RGBColor rgbcolor;
GetThemeBrushAsColor(brush, 32, true, &rgbcolor);
return QColor(rgbcolor.red / 256, rgbcolor.green / 256, rgbcolor.blue / 256);
}
#else
return leopardBrush(brush);
#endif
}
QColor qcolorForThemeTextColor(ThemeTextColor themeColor)
{
#ifndef QT_MAC_USE_COCOA
RGBColor c;
GetThemeTextColor(themeColor, 32, true, &c);
return QColor(c.red / 265, c.green / 256, c.blue / 256);
#else
QNativeImage nativeImage(16,16, QNativeImage::systemFormat());
CGRect cgrect = CGRectMake(0, 0, 16, 16);
HIThemeSetTextFill(themeColor, 0, nativeImage.cg, kHIThemeOrientationNormal);
CGContextFillRect(nativeImage.cg, cgrect);
return QColor(nativeImage.image.pixel(0 , 0));
#endif
}
QT_END_NAMESPACE
| /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include <private/qt_mac_p.h>
#include <private/qpixmap_mac_p.h>
#include <private/qnativeimage_p.h>
#include <qdebug.h>
QT_BEGIN_NAMESPACE
#ifdef QT_MAC_USE_COCOA
static CTFontRef CopyCTThemeFont(ThemeFontID themeID)
{
CTFontUIFontType ctID = HIThemeGetUIFontType(themeID);
return CTFontCreateUIFontForLanguage(ctID, 0, 0);
}
#endif
QFont qfontForThemeFont(ThemeFontID themeID)
{
#ifndef QT_MAC_USE_COCOA
static const ScriptCode Script = smRoman;
Str255 f_name;
SInt16 f_size;
Style f_style;
GetThemeFont(themeID, Script, f_name, &f_size, &f_style);
extern QString qt_mac_from_pascal_string(const Str255); //qglobal.cpp
return QFont(qt_mac_from_pascal_string(f_name), f_size,
(f_style & ::bold) ? QFont::Bold : QFont::Normal,
(bool)(f_style & ::italic));
#else
QCFType<CTFontRef> ctfont = CopyCTThemeFont(themeID);
QString familyName = QCFString(CTFontCopyFamilyName(ctfont));
QCFType<CFDictionaryRef> dict = CTFontCopyTraits(ctfont);
CFNumberRef num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontWeightTrait));
float fW;
CFNumberGetValue(num, kCFNumberFloat32Type, &fW);
QFont::Weight wght = fW > 0. ? QFont::Bold : QFont::Normal;
num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontSlantTrait));
CFNumberGetValue(num, kCFNumberFloatType, &fW);
bool italic = (fW != 0.0);
return QFont(familyName, CTFontGetSize(ctfont), wght, italic);
#endif
}
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
static QColor qcolorFromCGColor(CGColorRef cgcolor)
{
QColor pc;
CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(cgcolor));
const CGFloat *components = CGColorGetComponents(cgcolor);
if (model == kCGColorSpaceModelRGB) {
pc.setRgbF(components[0], components[1], components[2], components[3]);
} else if (model == kCGColorSpaceModelCMYK) {
pc.setCmykF(components[0], components[1], components[2], components[3]);
} else if (model == kCGColorSpaceModelMonochrome) {
pc.setRgbF(components[0], components[0], components[0], components[1]);
} else {
// Colorspace we can't deal with.
qWarning("Qt: qcolorFromCGColor: cannot convert from colorspace model: %d", model);
Q_ASSERT(false);
}
return pc;
}
static inline QColor leopardBrush(ThemeBrush brush)
{
QCFType<CGColorRef> cgClr = 0;
HIThemeBrushCreateCGColor(brush, &cgClr);
return qcolorFromCGColor(cgClr);
}
#endif
QColor qcolorForTheme(ThemeBrush brush)
{
#ifndef QT_MAC_USE_COCOA
# if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
return leopardBrush(brush);
} else
# endif
{
RGBColor rgbcolor;
GetThemeBrushAsColor(brush, 32, true, &rgbcolor);
return QColor(rgbcolor.red / 256, rgbcolor.green / 256, rgbcolor.blue / 256);
}
#else
return leopardBrush(brush);
#endif
}
QColor qcolorForThemeTextColor(ThemeTextColor themeColor)
{
#ifndef QT_MAC_USE_COCOA
RGBColor c;
GetThemeTextColor(themeColor, 32, true, &c);
return QColor(c.red / 265, c.green / 256, c.blue / 256);
#else
QNativeImage nativeImage(16,16, QNativeImage::systemFormat());
CGRect cgrect = CGRectMake(0, 0, 16, 16);
HIThemeSetTextFill(themeColor, 0, nativeImage.cg, kHIThemeOrientationNormal);
CGContextFillRect(nativeImage.cg, cgrect);
return QColor(nativeImage.image.pixel(0 , 0));
#endif
}
QT_END_NAMESPACE
| Handle monochrome CGColors as well. | Handle monochrome CGColors as well.
It seems that snow leopard is storing some colors as grayscale. This
means that we need to handle them or otherwise things go very black.
It's an easy case to do as well, so just do it.
Reviewed-by: Bradley T. Hughes
| C++ | lgpl-2.1 | igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,KDE/qt,radekp/qt,RLovelett/qt,igor-sfdc/qt-wk,radekp/qt,RLovelett/qt,radekp/qt,radekp/qt,pruiz/wkhtmltopdf-qt,KDE/qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,KDE/qt,radekp/qt,radekp/qt,igor-sfdc/qt-wk,RLovelett/qt,radekp/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,RLovelett/qt,RLovelett/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,RLovelett/qt,pruiz/wkhtmltopdf-qt,KDE/qt,KDE/qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,RLovelett/qt,radekp/qt,RLovelett/qt,radekp/qt,RLovelett/qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,KDE/qt,KDE/qt,RLovelett/qt,RLovelett/qt,pruiz/wkhtmltopdf-qt,radekp/qt,KDE/qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt |
1200ef4fab3b4cde88b3c32dd44256d1a90c7e4a | stdlib/runtime/Stubs.cpp | stdlib/runtime/Stubs.cpp | //===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Misc stubs for functions which should be in swift.swift, but are difficult
// or impossible to write in swift at the moment.
//
//===----------------------------------------------------------------------===//
#include <mach/mach_time.h>
#include <sys/resource.h>
#include <sys/errno.h>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <sys/stat.h> // stat
#include <fcntl.h> // open
#include <unistd.h> // read, close
#include <dirent.h>
#include <limits.h>
#include "llvm/ADT/StringExtras.h"
// static func String(v : Int128, radix : Int) -> String
extern "C"
unsigned long long
print_int(char* TmpBuffer, __int64_t buf_len, __int128_t X, uint64_t Radix,
bool uppercase) {
assert(Radix != 0 && Radix <= 36 && "Invalid radix for string conversion");
char *P = TmpBuffer;
bool WasNeg = X < 0;
__uint128_t Y = WasNeg ? -X : X;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !uppercase);
Y /= Radix32;
}
}
if (WasNeg) *P++ = '-';
std::reverse(TmpBuffer, P);
return size_t(P - TmpBuffer);
}
// static func String(v : UInt128, radix : Int) -> String
extern "C"
unsigned long long
print_uint(char* TmpBuffer, __int64_t buf_len, __uint128_t Y, uint64_t Radix,
bool uppercase) {
assert(Radix != 0 && Radix <= 36 && "Invalid radix for string conversion");
char *P = TmpBuffer;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !uppercase);
Y /= Radix32;
}
}
std::reverse(TmpBuffer, P);
return size_t(P - TmpBuffer);
}
// static func String(v : Double) -> String
extern "C"
unsigned long long
print_double(char* Buffer, double X) {
long long i = sprintf(Buffer, "%g", X);
// Add ".0" to a float that (a) is not in scientific notation, (b) does not
// already have a fractional part, (c) is not infinite, and (d) is not a NaN
// value.
if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr &&
strchr(Buffer, 'n') == nullptr) {
Buffer[i++] = '.';
Buffer[i++] = '0';
}
if (i < 0) {
__builtin_trap();
}
return i;
}
// FIXME: We shouldn't be writing implemenetations for functions in the swift
// module in C, and this isn't really an ideal place to put those
// implementations.
extern "C" void _TSs5printFT3valSi_T_(int64_t l) {
printf("%lld", l);
}
extern "C" void _TSs5printFT3valSu_T_(uint64_t l) {
printf("%llu", l);
}
extern "C" void _TSs5printFT3valSd_T_(double l) {
char Buffer[256];
unsigned long long i = print_double(Buffer, l);
Buffer[i] = '\0';
printf("%s", Buffer);
}
extern "C" bool _TSb13getLogicValuefRSbFT_Bi1_(bool* b) {
return *b;
}
static bool
_swift_replOutputIsUTF8(void) {
const char *lang = getenv("LANG");
return lang && strstr(lang, "UTF-8");
}
extern "C"
uint32_t
swift_replOutputIsUTF8(void) {
static auto rval = _swift_replOutputIsUTF8();
return rval;
}
#if defined(__i386__) || defined(__x86_64__)
static inline uint64_t
rdtsc() {
uint32_t lo, hi;
asm("rdtsc" : "=a" (lo), "=d" (hi));
return uint64_t(hi) << 32 | lo;
}
#else
#error "not supported"
#endif
static double interruptOverhead;
static double loopOverhead;
static uint64_t
_swift_startBenchmark(void) {
return rdtsc();
}
extern "C"
void
swift_printBenchmark(uint64_t start, uint64_t laps, char *buffer, int64_t len) {
double val = rdtsc() - start;
val /= laps;
val /= interruptOverhead;
val -= loopOverhead;
printf("%12.2f %*s\n", val, (int)len, buffer);
}
extern "C"
__attribute__((noinline,used))
__typeof__(&_swift_startBenchmark)
_swift_initBenchmark() asm("_swift_startBenchmark");
__typeof__(&_swift_startBenchmark)
_swift_initBenchmark() {
asm(".symbol_resolver _swift_startBenchmark");
union {
unsigned reg[4*3];
char brand[48];
} u;
char brand[48];
char *s2 = u.brand;
char *s1 = brand;
unsigned eax, ebx, ecx, edx;
memset(&u, 0, sizeof(u));
int r;
// Let's not have the OS compete with our CPU time if we can avoid it
r = setvbuf(stdout, 0, _IOFBF, 0);
assert(r == 0);
// XXX -- There doesn't seem to be an API to figure out the max value
sched_param schedParam;
schedParam.sched_priority = 79;
r = pthread_setschedparam(pthread_self(), SCHED_FIFO, &schedParam);
assert(r == 0);
eax = 0x80000002;
asm("cpuid" : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx));
u.reg[0] = eax;
u.reg[1] = ebx;
u.reg[2] = ecx;
u.reg[3] = edx;
eax = 0x80000003;
asm("cpuid" : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx));
u.reg[4] = eax;
u.reg[5] = ebx;
u.reg[6] = ecx;
u.reg[7] = edx;
eax = 0x80000004;
asm("cpuid" : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx));
u.reg[8] = eax;
u.reg[9] = ebx;
u.reg[10] = ecx;
u.reg[11] = edx;
while (*s2 == ' ') {
s2++;
}
do {
while (s2[0] == ' ' && s2[1] == ' ') {
s2++;
}
} while ((*s1++ = *s2++));
printf("Processor: %s\n\n", brand);
uint64_t start = rdtsc();
for (unsigned long i = 0; i < 1000000000ull; i++) {
asm("");
}
double delta = (rdtsc() - start) / 1000000000.0;
assert((delta >= 1.0 && delta < 1.05) || (delta >= 2.0 && delta < 2.05));
if (delta >= 2.0) {
loopOverhead = 2.0;
interruptOverhead = delta / 2.0;
} else {
loopOverhead = 1.0;
interruptOverhead = delta / 1.0;
}
assert((interruptOverhead - 1.0) < 0.01);
eax = 6;
asm("cpuid" : "+a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx));
if (eax & 2) {
fprintf(stderr, "WARNING: TurboBoost. Results will be less reliable.\n");
fprintf(stderr, " Consider: sudo /usr/local/bin/pstates -D\n\n");
}
if (geteuid()) {
fprintf(stderr, "WARNING: Non-elevated priority. Results will be less reliable.\n");
fprintf(stderr, " Consider: sudo ./myBench\n\n");
}
return _swift_startBenchmark;
}
extern "C"
int
swift_file_open(const char* filename)
{
return open(filename, O_RDONLY);
}
extern "C"
int
swift_file_close(int fd)
{
return close(fd);
}
extern "C"
size_t
swift_file_read(int fd, char* buf, size_t nb)
{
return read(fd, buf, nb);
}
extern "C"
size_t
swift_fd_size(int fd)
{
struct stat buf;
int err = fstat(fd, &buf);
assert(err == 0);
(void) err;
return buf.st_size;
}
struct readdir_tuple_s {
char *str;
int64_t len;
};
extern "C"
struct readdir_tuple_s
posix_readdir_hack(DIR *d)
{
struct readdir_tuple_s rval = { NULL, 0 };
struct dirent *dp;
if ((dp = readdir(d))) {
rval.str = dp->d_name;
rval.len = dp->d_namlen;
}
return rval;
}
extern "C"
int64_t
posix_isDirectory_hack(const char *path)
{
struct stat sb;
int r = stat(path, &sb);
(void)r;
assert(r != -1);
return S_ISDIR(sb.st_mode);
}
extern "C"
int
posix_get_errno(void)
{
return errno; // errno is not a global, but a macro
}
extern "C"
void
posix_set_errno(int value)
{
errno = value; // errno is not a global, but a macro
}
| //===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Misc stubs for functions which should be in swift.swift, but are difficult
// or impossible to write in swift at the moment.
//
//===----------------------------------------------------------------------===//
#include <mach/mach_time.h>
#include <sys/resource.h>
#include <sys/errno.h>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <sys/stat.h> // stat
#include <fcntl.h> // open
#include <unistd.h> // read, close
#include <dirent.h>
#include <limits.h>
#include "llvm/ADT/StringExtras.h"
// static func String(v : Int128, radix : Int) -> String
extern "C"
unsigned long long
print_int(char* TmpBuffer, __int64_t buf_len, __int128_t X, uint64_t Radix,
bool uppercase) {
assert(Radix != 0 && Radix <= 36 && "Invalid radix for string conversion");
char *P = TmpBuffer;
bool WasNeg = X < 0;
__uint128_t Y = WasNeg ? -X : X;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !uppercase);
Y /= Radix32;
}
}
if (WasNeg) *P++ = '-';
std::reverse(TmpBuffer, P);
return size_t(P - TmpBuffer);
}
// static func String(v : UInt128, radix : Int) -> String
extern "C"
unsigned long long
print_uint(char* TmpBuffer, __int64_t buf_len, __uint128_t Y, uint64_t Radix,
bool uppercase) {
assert(Radix != 0 && Radix <= 36 && "Invalid radix for string conversion");
char *P = TmpBuffer;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !uppercase);
Y /= Radix32;
}
}
std::reverse(TmpBuffer, P);
return size_t(P - TmpBuffer);
}
// static func String(v : Double) -> String
extern "C"
unsigned long long
print_double(char* Buffer, double X) {
long long i = sprintf(Buffer, "%g", X);
// Add ".0" to a float that (a) is not in scientific notation, (b) does not
// already have a fractional part, (c) is not infinite, and (d) is not a NaN
// value.
if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr &&
strchr(Buffer, 'n') == nullptr) {
Buffer[i++] = '.';
Buffer[i++] = '0';
}
if (i < 0) {
__builtin_trap();
}
return i;
}
// FIXME: We shouldn't be writing implemenetations for functions in the swift
// module in C, and this isn't really an ideal place to put those
// implementations.
extern "C" void _TSs5printFT3valSi_T_(int64_t l) {
printf("%lld", l);
}
extern "C" void _TSs5printFT3valSu_T_(uint64_t l) {
printf("%llu", l);
}
extern "C" void _TSs5printFT3valSd_T_(double l) {
char Buffer[256];
unsigned long long i = print_double(Buffer, l);
Buffer[i] = '\0';
printf("%s", Buffer);
}
extern "C" bool _TSb13getLogicValuefRSbFT_Bi1_(bool* b) {
return *b;
}
static bool
_swift_replOutputIsUTF8(void) {
const char *lang = getenv("LANG");
return lang && strstr(lang, "UTF-8");
}
extern "C"
uint32_t
swift_replOutputIsUTF8(void) {
static auto rval = _swift_replOutputIsUTF8();
return rval;
}
extern "C"
int
swift_file_open(const char* filename)
{
return open(filename, O_RDONLY);
}
extern "C"
int
swift_file_close(int fd)
{
return close(fd);
}
extern "C"
size_t
swift_file_read(int fd, char* buf, size_t nb)
{
return read(fd, buf, nb);
}
extern "C"
size_t
swift_fd_size(int fd)
{
struct stat buf;
int err = fstat(fd, &buf);
assert(err == 0);
(void) err;
return buf.st_size;
}
struct readdir_tuple_s {
char *str;
int64_t len;
};
extern "C"
struct readdir_tuple_s
posix_readdir_hack(DIR *d)
{
struct readdir_tuple_s rval = { NULL, 0 };
struct dirent *dp;
if ((dp = readdir(d))) {
rval.str = dp->d_name;
rval.len = dp->d_namlen;
}
return rval;
}
extern "C"
int64_t
posix_isDirectory_hack(const char *path)
{
struct stat sb;
int r = stat(path, &sb);
(void)r;
assert(r != -1);
return S_ISDIR(sb.st_mode);
}
extern "C"
int
posix_get_errno(void)
{
return errno; // errno is not a global, but a macro
}
extern "C"
void
posix_set_errno(int value)
{
errno = value; // errno is not a global, but a macro
}
| Move benchmark machinery out of stdlib. | Move benchmark machinery out of stdlib.
Swift SVN r7961
| C++ | apache-2.0 | gottesmm/swift,Jnosh/swift,jtbandes/swift,gribozavr/swift,KrishMunot/swift,hughbe/swift,natecook1000/swift,cbrentharris/swift,khizkhiz/swift,Ivacker/swift,karwa/swift,swiftix/swift,tjw/swift,calebd/swift,modocache/swift,Jnosh/swift,kentya6/swift,mightydeveloper/swift,karwa/swift,karwa/swift,zisko/swift,calebd/swift,jopamer/swift,dduan/swift,tardieu/swift,modocache/swift,nathawes/swift,gottesmm/swift,CodaFi/swift,xwu/swift,tkremenek/swift,CodaFi/swift,kstaring/swift,ken0nek/swift,tardieu/swift,MukeshKumarS/Swift,rudkx/swift,kperryua/swift,JGiola/swift,kusl/swift,practicalswift/swift,return/swift,swiftix/swift,gottesmm/swift,shajrawi/swift,hooman/swift,xedin/swift,deyton/swift,arvedviehweger/swift,dduan/swift,kusl/swift,allevato/swift,roambotics/swift,roambotics/swift,ken0nek/swift,OscarSwanros/swift,jopamer/swift,uasys/swift,atrick/swift,djwbrown/swift,gmilos/swift,dreamsxin/swift,emilstahl/swift,hughbe/swift,allevato/swift,codestergit/swift,kentya6/swift,tinysun212/swift-windows,shajrawi/swift,adrfer/swift,Jnosh/swift,austinzheng/swift,ben-ng/swift,brentdax/swift,ben-ng/swift,sschiau/swift,stephentyrone/swift,alblue/swift,slavapestov/swift,shajrawi/swift,OscarSwanros/swift,frootloops/swift,LeoShimonaka/swift,cbrentharris/swift,nathawes/swift,sdulal/swift,sdulal/swift,lorentey/swift,danielmartin/swift,swiftix/swift.old,kusl/swift,ben-ng/swift,gmilos/swift,benlangmuir/swift,OscarSwanros/swift,emilstahl/swift,arvedviehweger/swift,gribozavr/swift,glessard/swift,tardieu/swift,huonw/swift,OscarSwanros/swift,sschiau/swift,djwbrown/swift,zisko/swift,Jnosh/swift,kusl/swift,austinzheng/swift,slavapestov/swift,jopamer/swift,brentdax/swift,OscarSwanros/swift,brentdax/swift,johnno1962d/swift,natecook1000/swift,alblue/swift,russbishop/swift,MukeshKumarS/Swift,sdulal/swift,LeoShimonaka/swift,therealbnut/swift,stephentyrone/swift,deyton/swift,kstaring/swift,arvedviehweger/swift,Ivacker/swift,xwu/swift,tkremenek/swift,austinzheng/swift,devincoughlin/swift,LeoShimonaka/swift,cbrentharris/swift,hooman/swift,swiftix/swift.old,sdulal/swift,emilstahl/swift,arvedviehweger/swift,tjw/swift,LeoShimonaka/swift,Jnosh/swift,KrishMunot/swift,slavapestov/swift,stephentyrone/swift,arvedviehweger/swift,codestergit/swift,russbishop/swift,therealbnut/swift,frootloops/swift,danielmartin/swift,tinysun212/swift-windows,hooman/swift,MukeshKumarS/Swift,xedin/swift,JaSpa/swift,atrick/swift,benlangmuir/swift,dreamsxin/swift,apple/swift,frootloops/swift,gregomni/swift,felix91gr/swift,alblue/swift,gribozavr/swift,aschwaighofer/swift,kperryua/swift,tjw/swift,jmgc/swift,CodaFi/swift,jtbandes/swift,benlangmuir/swift,adrfer/swift,deyton/swift,devincoughlin/swift,djwbrown/swift,slavapestov/swift,CodaFi/swift,amraboelela/swift,mightydeveloper/swift,austinzheng/swift,tinysun212/swift-windows,ahoppen/swift,IngmarStein/swift,apple/swift,shajrawi/swift,gribozavr/swift,sschiau/swift,tkremenek/swift,codestergit/swift,sdulal/swift,djwbrown/swift,uasys/swift,xedin/swift,parkera/swift,gmilos/swift,frootloops/swift,IngmarStein/swift,codestergit/swift,SwiftAndroid/swift,zisko/swift,airspeedswift/swift,kusl/swift,cbrentharris/swift,manavgabhawala/swift,stephentyrone/swift,cbrentharris/swift,MukeshKumarS/Swift,apple/swift,airspeedswift/swift,johnno1962d/swift,jtbandes/swift,devincoughlin/swift,manavgabhawala/swift,gmilos/swift,gregomni/swift,aschwaighofer/swift,adrfer/swift,jtbandes/swift,MukeshKumarS/Swift,swiftix/swift,hooman/swift,uasys/swift,calebd/swift,Ivacker/swift,calebd/swift,Jnosh/swift,CodaFi/swift,parkera/swift,russbishop/swift,SwiftAndroid/swift,ken0nek/swift,practicalswift/swift,alblue/swift,aschwaighofer/swift,harlanhaskins/swift,deyton/swift,mightydeveloper/swift,jmgc/swift,tkremenek/swift,xwu/swift,jtbandes/swift,LeoShimonaka/swift,mightydeveloper/swift,gregomni/swift,therealbnut/swift,kperryua/swift,huonw/swift,benlangmuir/swift,gribozavr/swift,IngmarStein/swift,natecook1000/swift,austinzheng/swift,gregomni/swift,SwiftAndroid/swift,zisko/swift,sdulal/swift,uasys/swift,jckarter/swift,KrishMunot/swift,slavapestov/swift,tkremenek/swift,frootloops/swift,russbishop/swift,swiftix/swift.old,KrishMunot/swift,harlanhaskins/swift,kentya6/swift,brentdax/swift,devincoughlin/swift,deyton/swift,johnno1962d/swift,practicalswift/swift,hughbe/swift,cbrentharris/swift,JGiola/swift,atrick/swift,harlanhaskins/swift,return/swift,apple/swift,kentya6/swift,Ivacker/swift,allevato/swift,parkera/swift,therealbnut/swift,mightydeveloper/swift,SwiftAndroid/swift,calebd/swift,emilstahl/swift,kentya6/swift,Ivacker/swift,slavapestov/swift,aschwaighofer/swift,felix91gr/swift,austinzheng/swift,practicalswift/swift,zisko/swift,mightydeveloper/swift,hughbe/swift,amraboelela/swift,stephentyrone/swift,djwbrown/swift,karwa/swift,khizkhiz/swift,modocache/swift,harlanhaskins/swift,allevato/swift,JGiola/swift,tardieu/swift,IngmarStein/swift,parkera/swift,danielmartin/swift,stephentyrone/swift,lorentey/swift,gottesmm/swift,modocache/swift,ahoppen/swift,jckarter/swift,russbishop/swift,xwu/swift,shahmishal/swift,apple/swift,atrick/swift,parkera/swift,gregomni/swift,shahmishal/swift,JGiola/swift,arvedviehweger/swift,manavgabhawala/swift,sdulal/swift,jckarter/swift,kusl/swift,khizkhiz/swift,IngmarStein/swift,therealbnut/swift,shahmishal/swift,jckarter/swift,mightydeveloper/swift,xedin/swift,ahoppen/swift,hughbe/swift,OscarSwanros/swift,nathawes/swift,rudkx/swift,atrick/swift,swiftix/swift.old,tjw/swift,shajrawi/swift,LeoShimonaka/swift,bitjammer/swift,glessard/swift,danielmartin/swift,jopamer/swift,bitjammer/swift,uasys/swift,bitjammer/swift,rudkx/swift,karwa/swift,kstaring/swift,sschiau/swift,LeoShimonaka/swift,bitjammer/swift,kstaring/swift,therealbnut/swift,KrishMunot/swift,amraboelela/swift,allevato/swift,swiftix/swift,swiftix/swift.old,amraboelela/swift,stephentyrone/swift,huonw/swift,felix91gr/swift,practicalswift/swift,kstaring/swift,ahoppen/swift,manavgabhawala/swift,xedin/swift,kusl/swift,milseman/swift,SwiftAndroid/swift,gribozavr/swift,tinysun212/swift-windows,sschiau/swift,therealbnut/swift,milseman/swift,shahmishal/swift,gmilos/swift,swiftix/swift.old,Ivacker/swift,austinzheng/swift,sschiau/swift,CodaFi/swift,milseman/swift,SwiftAndroid/swift,jopamer/swift,ahoppen/swift,milseman/swift,shajrawi/swift,kperryua/swift,hughbe/swift,codestergit/swift,emilstahl/swift,jmgc/swift,jmgc/swift,kperryua/swift,modocache/swift,xedin/swift,tardieu/swift,swiftix/swift,khizkhiz/swift,jckarter/swift,milseman/swift,JaSpa/swift,aschwaighofer/swift,parkera/swift,tkremenek/swift,codestergit/swift,dduan/swift,benlangmuir/swift,shajrawi/swift,LeoShimonaka/swift,natecook1000/swift,johnno1962d/swift,return/swift,tardieu/swift,natecook1000/swift,airspeedswift/swift,arvedviehweger/swift,frootloops/swift,zisko/swift,bitjammer/swift,swiftix/swift.old,codestergit/swift,nathawes/swift,tinysun212/swift-windows,jtbandes/swift,gottesmm/swift,calebd/swift,jopamer/swift,airspeedswift/swift,JaSpa/swift,gmilos/swift,ken0nek/swift,harlanhaskins/swift,swiftix/swift,roambotics/swift,devincoughlin/swift,kperryua/swift,kentya6/swift,aschwaighofer/swift,djwbrown/swift,practicalswift/swift,russbishop/swift,roambotics/swift,MukeshKumarS/Swift,airspeedswift/swift,dduan/swift,kusl/swift,JaSpa/swift,cbrentharris/swift,johnno1962d/swift,JaSpa/swift,felix91gr/swift,calebd/swift,johnno1962d/swift,alblue/swift,felix91gr/swift,gmilos/swift,manavgabhawala/swift,shajrawi/swift,brentdax/swift,practicalswift/swift,JGiola/swift,IngmarStein/swift,swiftix/swift.old,milseman/swift,amraboelela/swift,JaSpa/swift,ben-ng/swift,khizkhiz/swift,MukeshKumarS/Swift,alblue/swift,benlangmuir/swift,xwu/swift,adrfer/swift,glessard/swift,danielmartin/swift,Jnosh/swift,rudkx/swift,russbishop/swift,parkera/swift,lorentey/swift,jckarter/swift,natecook1000/swift,felix91gr/swift,brentdax/swift,Ivacker/swift,natecook1000/swift,tinysun212/swift-windows,parkera/swift,gregomni/swift,glessard/swift,harlanhaskins/swift,bitjammer/swift,huonw/swift,sschiau/swift,jmgc/swift,huonw/swift,jmgc/swift,return/swift,roambotics/swift,jtbandes/swift,shahmishal/swift,Ivacker/swift,ben-ng/swift,frootloops/swift,hooman/swift,SwiftAndroid/swift,gottesmm/swift,nathawes/swift,return/swift,return/swift,lorentey/swift,kentya6/swift,kstaring/swift,djwbrown/swift,nathawes/swift,return/swift,cbrentharris/swift,ken0nek/swift,rudkx/swift,airspeedswift/swift,lorentey/swift,adrfer/swift,karwa/swift,emilstahl/swift,karwa/swift,swiftix/swift,airspeedswift/swift,brentdax/swift,roambotics/swift,allevato/swift,kentya6/swift,alblue/swift,lorentey/swift,xedin/swift,danielmartin/swift,johnno1962d/swift,dduan/swift,manavgabhawala/swift,manavgabhawala/swift,practicalswift/swift,CodaFi/swift,OscarSwanros/swift,khizkhiz/swift,lorentey/swift,dduan/swift,nathawes/swift,ken0nek/swift,modocache/swift,deyton/swift,lorentey/swift,adrfer/swift,aschwaighofer/swift,shahmishal/swift,mightydeveloper/swift,kperryua/swift,devincoughlin/swift,huonw/swift,gribozavr/swift,modocache/swift,atrick/swift,tjw/swift,KrishMunot/swift,tardieu/swift,uasys/swift,glessard/swift,allevato/swift,deyton/swift,zisko/swift,harlanhaskins/swift,shahmishal/swift,tinysun212/swift-windows,tkremenek/swift,kstaring/swift,hooman/swift,ken0nek/swift,devincoughlin/swift,JGiola/swift,dduan/swift,xedin/swift,felix91gr/swift,hughbe/swift,ben-ng/swift,jopamer/swift,rudkx/swift,hooman/swift,tjw/swift,karwa/swift,devincoughlin/swift,xwu/swift,jckarter/swift,uasys/swift,gottesmm/swift,ahoppen/swift,KrishMunot/swift,bitjammer/swift,glessard/swift,danielmartin/swift,amraboelela/swift,emilstahl/swift,JaSpa/swift,amraboelela/swift,jmgc/swift,khizkhiz/swift,apple/swift,tjw/swift,shahmishal/swift,huonw/swift,sschiau/swift,emilstahl/swift,milseman/swift,sdulal/swift,ben-ng/swift,xwu/swift,gribozavr/swift,IngmarStein/swift,adrfer/swift,slavapestov/swift |
4fffee7d86d05940211beb5edb67ca3bec403b5b | stk500/stk500session.cpp | stk500/stk500session.cpp | #include "stk500session.h"
#include <QDebug>
#include <QApplication>
#include <QSerialPortInfo>
#include "progressdialog.h"
stk500Session::stk500Session(QWidget *owner)
: QObject(owner) {
process = NULL;
}
bool stk500Session::isOpen() {
return (process != NULL && !process->closeRequested);
}
bool stk500Session::isSerialOpen() {
return isOpen() && process->serialBaud;
}
void stk500Session::open(QString & portName) {
// If already opened; ignore
if (isOpen() && (process->portName == portName)) {
return;
}
// Close the current process if opened
close();
// Start a new process for the new port
process = new stk500_ProcessThread(this, portName);
process->start();
}
void stk500Session::close() {
if (isOpen()) {
// Tell the process to quit if running
if (process->isRunning) {
process->closeRequested = true;
process->cancelTasks();
// Add process to the processes being killed
killedProcesses.append(process);
process = NULL;
} else {
delete process;
process = NULL;
}
}
}
bool stk500Session::abort() {
close();
// Wait for a maximum of 1 second until all processes are killed
for (int i = 0; i < 20 && !cleanKilledProcesses(); i++) {
QThread::msleep(50);
}
return cleanKilledProcesses();
}
bool stk500Session::cleanKilledProcesses() {
if (killedProcesses.isEmpty()) {
return true;
}
int i = 0;
bool isAllKilled = true;
while (i < killedProcesses.length()) {
stk500_ProcessThread *process = killedProcesses.at(i);
if (process->isRunning) {
isAllKilled = false;
i++;
} else {
delete process;
killedProcesses.removeAt(i);
}
}
return isAllKilled;
}
void stk500Session::notifyStatus(stk500_ProcessThread*, QString status) {
emit statusChanged(status);
}
void stk500Session::notifyClosed(stk500_ProcessThread *) {
emit closed();
}
void stk500Session::notifySerialOpened(stk500_ProcessThread *) {
emit serialOpened();
}
void stk500Session::execute(stk500Task *task) {
QList<stk500Task*> tasks;
tasks.append(task);
executeAll(tasks);
}
void stk500Session::executeAll(QList<stk500Task*> tasks) {
/* No tasks - don't do anything */
if (tasks.isEmpty()) return;
/* If not open, fail all tasks right away */
if (!isOpen()) {
for (stk500Task *task : tasks) {
task->setError(ProtocolException("Port is not opened"));
}
return;
}
/* Show just a wait cursor for processing < 1000ms */
QApplication::setOverrideCursor(Qt::WaitCursor);
for (int i = 0; i < 20 && process->isProcessing; i++) {
QThread::msleep(50);
}
QApplication::restoreOverrideCursor();
ProgressDialog *dialog = NULL;
qint64 currentTime;
qint64 startTime = QDateTime::currentMSecsSinceEpoch();
bool isWaitCursor = true;
int totalTaskCount = tasks.count();
int processedCount = 0;
qint64 waitTimeout = 1000;
if (!process->isSignedOn) {
waitTimeout += 300; // Give 300 MS to open port
}
QApplication::setOverrideCursor(Qt::WaitCursor);
while (!tasks.isEmpty()) {
// Obtain next task, check if it's not cancelled
stk500Task *task = tasks.takeFirst();
if (task->isCancelled() || task->hasError()) {
continue;
}
// Put into the process thread for processing
process->sync.lock();
process->currentTask = task;
process->sync.unlock();
process->wake();
process->isProcessing = true;
if (dialog != NULL) {
dialog->setWindowTitle(task->title());
}
// Wait until it's done processing
while (process->isProcessing) {
currentTime = QDateTime::currentMSecsSinceEpoch();
if ((currentTime - startTime) < waitTimeout) {
/* Allows for active UI updates, but is slightly dangerous */
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
continue;
}
// No longer waiting, hide wait cursor and show dialog
if (isWaitCursor) {
isWaitCursor = false;
QApplication::restoreOverrideCursor();
dialog = new ProgressDialog((QWidget*) this->parent());
dialog->setWindowTitle(task->title());
dialog->show();
}
// Calculate progress value
double progress = task->progress();
if (progress < 0.0 && processedCount) {
progress = 0.0;
}
progress /= totalTaskCount;
progress += ((double) processedCount / (double) totalTaskCount);
// Update progress
dialog->updateProgress(progress, task->status());
// Do events; handle cancelling
QCoreApplication::processEvents();
if (dialog->isCancelClicked() && !task->isCancelled()) {
task->cancel();
for (stk500Task *task : tasks) {
task->cancel();
}
}
if (!process->isRunning) {
task->setError(ProtocolException("Port is not opened"));
}
}
// If task has an error, stop other tasks too (errors are dangerous)
if (task->hasError()) {
for (stk500Task *task : tasks) {
task->setError(ProtocolException("Cancelled due to previous error"));
}
}
if (task->hasError()) {
task->showError();
}
processedCount++;
}
if (isWaitCursor) {
QApplication::restoreOverrideCursor();
}
if (dialog != NULL) {
dialog->close();
delete dialog;
}
}
void stk500Session::cancelTasks() {
process->cancelTasks();
}
void stk500Session::closeSerial() {
openSerial(0);
}
void stk500Session::openSerial(int baudrate) {
// Don't do anything if not open
if (!isOpen()) {
return;
}
// If already closed; ignore
if (!baudrate && !this->process->serialBaud) {
return;
}
// Update baud rate and notify the change
this->process->serialBaud = baudrate;
this->process->isBaudChanged = true;
}
int stk500Session::read(char* buff, int len) {
stk500_ProcessThread *thread = this->process;
if (thread == NULL) {
return 0;
}
// Lock the reading buffer and read from it
thread->inputBuffLock.lock();
int count = thread->inputBuff.length();
int remaining = 0;
if (count > len) {
remaining = (count - len);
count = len;
}
if (count) {
char* input_buff = thread->inputBuff.data();
// Read the contents
memcpy(buff, input_buff, count);
// Shift data around
memcpy(input_buff, input_buff + count, remaining);
thread->inputBuff.truncate(remaining);
}
thread->inputBuffLock.unlock();
// All done!
return count;
}
/* Task processing thread */
stk500_ProcessThread::stk500_ProcessThread(stk500Session *owner, QString portName) {
this->owner = owner;
this->closeRequested = false;
this->isRunning = true;
this->isProcessing = false;
this->isSignedOn = false;
this->isBaudChanged = false;
this->serialBaud = 0;
this->currentTask = NULL;
this->portName = portName;
this->status = "";
}
void stk500_ProcessThread::run() {
/* First check whether the port can be opened at all */
QSerialPortInfo info(portName);
if (info.isBusy()) {
this->closeRequested = true;
this->owner->notifyStatus(this, "Serial port busy");
}
if (!info.isValid()) {
this->closeRequested = true;
this->owner->notifyStatus(this, "Serial port invalid");
}
if (!this->closeRequested) {
/* First attempt to open the Serial port */
QSerialPort port;
stk500 protocol(&port);
this->owner->notifyStatus(this, "Opening...");
/* Initialize the port */
port.setPortName(portName);
port.setReadBufferSize(1024);
port.setSettingsRestoredOnClose(false);
port.open(QIODevice::ReadWrite);
port.clearError();
port.setBaudRate(115200);
/* Run process loop while not being closed */
bool needSignOn = true;
bool hasData = false;
qint64 start_time;
long currSerialBaud = 0;
char serialBuffer[1024];
while (!this->closeRequested) {
if (this->isBaudChanged) {
this->isBaudChanged = false;
currSerialBaud = this->serialBaud;
/* Clear input/output buffers */
this->inputBuffLock.lock();
this->inputBuff.clear();
this->inputBuffLock.unlock();
if (currSerialBaud) {
// Changing to a different baud rate
start_time = QDateTime::currentMSecsSinceEpoch();
// If currently signed on the reset can be skipped
this->owner->notifySerialOpened(this);
if (isSignedOn) {
isSignedOn = false;
protocol.signOut();
} else {
protocol.reset();
}
port.setBaudRate(currSerialBaud);
updateStatus("[Serial] Active");
} else {
// Leaving Serial mode - sign on needed
needSignOn = true;
port.setBaudRate(115200);
}
}
if (currSerialBaud) {
/* Serial mode: process serial I/O */
/* If no data available, wait for reading to be done shortly */
if (!port.bytesAvailable()) {
port.waitForReadyRead(20);
}
/* Read in data */
int cnt = port.read((char*) serialBuffer, sizeof(serialBuffer));
/* Copy to the read buffer */
if (cnt) {
if (!hasData) {
hasData = true;
qDebug() << "Program started after " << (QDateTime::currentMSecsSinceEpoch() - start_time) << "ms";
}
this->inputBuffLock.lock();
this->inputBuff.append(serialBuffer, cnt);
this->inputBuffLock.unlock();
}
} else {
/* Command mode: process bootloader I/O */
stk500Task *task = this->currentTask;
/* If not signed on and a task is to be handled, sign on first */
if (task != NULL && !isSignedOn) {
needSignOn = true;
}
/* Sign on with the bootloader */
if (needSignOn) {
needSignOn = false;
updateStatus("[STK500] Signing on");
isSignedOn = trySignOn(&protocol);
if (!isSignedOn) {
updateStatus("[STK500] Sign-on error");
}
}
if (task == NULL) {
/* No task - wait for tasks to be sent our way */
this->isProcessing = false;
// Waited for the full interval time, ping with a signOn command
// Still alive?
if (isSignedOn) {
updateStatus("[STK500] Idle");
isSignedOn = trySignOn(&protocol);
if (!isSignedOn) {
updateStatus("[STK500] Session lost");
}
}
/* Wait for a short time to keep the bootloader in the right mode */
sync.lock();
cond.wait(&sync, STK500_CMD_MIN_INTERVAL);
sync.unlock();
} else {
/* Update status */
updateStatus("[STK500] Busy");
/* Process the current task */
try {
if (!isSignedOn) {
throw ProtocolException("Could not communicate with device");
}
// Before processing, force the Micro-SD to re-read information
protocol.sd().reset();
protocol.sd().discardCache();
// Process the task after setting the protocol
task->setProtocol(protocol);
task->run();
// Flush the data on the Micro-SD now all is well
protocol.sd().flushCache();
} catch (ProtocolException &ex) {
task->setError(ex);
/* Flush here as well, but eat up any errors... */
try {
protocol.sd().flushCache();
} catch (ProtocolException&) {
}
}
// Clear the currently executed task
currentTask = NULL;
}
}
/* If port is closed, exit the thread */
if (!port.isOpen()) {
this->closeRequested = true;
}
}
/* Notify owner that this port is (being) closed */
this->owner->notifyStatus(this, "Closing...");
/* Close the serial port; this can hang in some cases */
port.close();
/* Notify owner that port has been closed */
this->owner->notifyStatus(this, "Port closed");
}
this->isRunning = false;
this->isProcessing = false;
this->owner->notifyClosed(this);
}
bool stk500_ProcessThread::trySignOn(stk500 *protocol) {
for (int i = 0; i < 2; i++) {
try {
protocolName = protocol->signOn();
return true;
} catch (ProtocolException& ex) {
qDebug() << "Failed to sign on: " << ex.what();
protocol->resetDelayed();
}
}
return false;
}
void stk500_ProcessThread::updateStatus(QString status) {
if (this->status != status) {
this->status = status;
this->owner->notifyStatus(this, this->status);
}
}
void stk500_ProcessThread::cancelTasks() {
stk500Task *curr = currentTask;
if (curr != NULL) {
curr->cancel();
}
wake();
}
void stk500_ProcessThread::wake() {
cond.wakeAll();
}
| #include "stk500session.h"
#include <QDebug>
#include <QApplication>
#include <QSerialPortInfo>
#include "progressdialog.h"
stk500Session::stk500Session(QWidget *owner)
: QObject(owner) {
process = NULL;
}
bool stk500Session::isOpen() {
return (process != NULL && !process->closeRequested);
}
bool stk500Session::isSerialOpen() {
return isOpen() && process->serialBaud;
}
void stk500Session::open(QString & portName) {
// If already opened; ignore
if (isOpen() && (process->portName == portName)) {
return;
}
// Close the current process if opened
close();
// Start a new process for the new port
process = new stk500_ProcessThread(this, portName);
process->start();
}
void stk500Session::close() {
if (isOpen()) {
// Tell the process to quit if running
if (process->isRunning) {
process->closeRequested = true;
process->cancelTasks();
// Add process to the processes being killed
killedProcesses.append(process);
process = NULL;
} else {
delete process;
process = NULL;
}
}
}
bool stk500Session::abort() {
close();
// Wait for a maximum of 1 second until all processes are killed
for (int i = 0; i < 20 && !cleanKilledProcesses(); i++) {
QThread::msleep(50);
}
return cleanKilledProcesses();
}
bool stk500Session::cleanKilledProcesses() {
if (killedProcesses.isEmpty()) {
return true;
}
int i = 0;
bool isAllKilled = true;
while (i < killedProcesses.length()) {
stk500_ProcessThread *process = killedProcesses.at(i);
if (process->isRunning) {
isAllKilled = false;
i++;
} else {
delete process;
killedProcesses.removeAt(i);
}
}
return isAllKilled;
}
void stk500Session::notifyStatus(stk500_ProcessThread*, QString status) {
emit statusChanged(status);
}
void stk500Session::notifyClosed(stk500_ProcessThread *) {
emit closed();
}
void stk500Session::notifySerialOpened(stk500_ProcessThread *) {
emit serialOpened();
}
void stk500Session::execute(stk500Task *task) {
QList<stk500Task*> tasks;
tasks.append(task);
executeAll(tasks);
}
void stk500Session::executeAll(QList<stk500Task*> tasks) {
/* No tasks - don't do anything */
if (tasks.isEmpty()) return;
/* If not open, fail all tasks right away */
if (!isOpen()) {
for (stk500Task *task : tasks) {
task->setError(ProtocolException("Port is not opened"));
}
return;
}
/* Show just a wait cursor for processing < 1000ms */
QApplication::setOverrideCursor(Qt::WaitCursor);
for (int i = 0; i < 20 && process->isProcessing; i++) {
QThread::msleep(50);
}
QApplication::restoreOverrideCursor();
ProgressDialog *dialog = NULL;
qint64 currentTime;
qint64 startTime = QDateTime::currentMSecsSinceEpoch();
bool isWaitCursor = true;
int totalTaskCount = tasks.count();
int processedCount = 0;
qint64 waitTimeout = 1000;
if (!process->isSignedOn) {
waitTimeout += 300; // Give 300 MS to open port
}
QApplication::setOverrideCursor(Qt::WaitCursor);
while (!tasks.isEmpty()) {
// Obtain next task, check if it's not cancelled
stk500Task *task = tasks.takeFirst();
if (task->isCancelled() || task->hasError()) {
continue;
}
// Put into the process thread for processing
process->sync.lock();
process->currentTask = task;
process->sync.unlock();
process->wake();
process->isProcessing = true;
if (dialog != NULL) {
dialog->setWindowTitle(task->title());
}
// Wait until it's done processing
while (process->isProcessing) {
currentTime = QDateTime::currentMSecsSinceEpoch();
if ((currentTime - startTime) < waitTimeout) {
/* Allows for active UI updates, but is slightly dangerous */
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
continue;
}
// No longer waiting, hide wait cursor and show dialog
if (isWaitCursor) {
isWaitCursor = false;
QApplication::restoreOverrideCursor();
dialog = new ProgressDialog((QWidget*) this->parent());
dialog->setWindowTitle(task->title());
dialog->show();
}
// Calculate progress value
double progress = task->progress();
if (progress < 0.0 && processedCount) {
progress = 0.0;
}
progress /= totalTaskCount;
progress += ((double) processedCount / (double) totalTaskCount);
// Update progress
dialog->updateProgress(progress, task->status());
// Do events; handle cancelling
QCoreApplication::processEvents();
if (dialog->isCancelClicked() && !task->isCancelled()) {
task->cancel();
for (stk500Task *task : tasks) {
task->cancel();
}
}
if (!process->isRunning) {
task->setError(ProtocolException("Port is not opened"));
}
}
// If task has an error, stop other tasks too (errors are dangerous)
if (task->hasError()) {
for (stk500Task *task : tasks) {
task->setError(ProtocolException("Cancelled due to previous error"));
}
}
if (task->hasError()) {
task->showError();
}
processedCount++;
}
if (isWaitCursor) {
QApplication::restoreOverrideCursor();
}
if (dialog != NULL) {
dialog->close();
delete dialog;
}
}
void stk500Session::cancelTasks() {
process->cancelTasks();
}
void stk500Session::closeSerial() {
openSerial(0);
}
void stk500Session::openSerial(int baudrate) {
// Don't do anything if not open
if (!isOpen()) {
return;
}
// If already closed; ignore
if (!baudrate && !this->process->serialBaud) {
return;
}
// Update baud rate and notify the change
this->process->serialBaud = baudrate;
this->process->isBaudChanged = true;
}
int stk500Session::read(char* buff, int len) {
stk500_ProcessThread *thread = this->process;
if (thread == NULL) {
return 0;
}
// Lock the reading buffer and read from it
thread->inputBuffLock.lock();
int count = thread->inputBuff.length();
int remaining = 0;
if (count > len) {
remaining = (count - len);
count = len;
}
if (count) {
char* input_buff = thread->inputBuff.data();
// Read the contents
memcpy(buff, input_buff, count);
// Shift data around
memcpy(input_buff, input_buff + count, remaining);
thread->inputBuff.truncate(remaining);
}
thread->inputBuffLock.unlock();
// All done!
return count;
}
/* Task processing thread */
stk500_ProcessThread::stk500_ProcessThread(stk500Session *owner, QString portName) {
this->owner = owner;
this->closeRequested = false;
this->isRunning = true;
this->isProcessing = false;
this->isSignedOn = false;
this->isBaudChanged = false;
this->serialBaud = 0;
this->currentTask = NULL;
this->portName = portName;
this->status = "";
}
void stk500_ProcessThread::run() {
/* First check whether the port can be opened at all */
QSerialPortInfo info(portName);
if (info.isBusy()) {
this->closeRequested = true;
updateStatus("Serial port busy");
}
if (!info.isValid()) {
this->closeRequested = true;
updateStatus("Serial port invalid");
}
if (!this->closeRequested) {
/* First attempt to open the Serial port */
QSerialPort port;
stk500 protocol(&port);
updateStatus("Opening...");
/* Initialize the port */
port.setPortName(portName);
port.setReadBufferSize(1024);
port.setSettingsRestoredOnClose(false);
port.open(QIODevice::ReadWrite);
port.clearError();
port.setBaudRate(115200);
/* Run process loop while not being closed */
bool needSignOn = true;
bool hasData = false;
qint64 start_time;
long currSerialBaud = 0;
char serialBuffer[1024];
while (!this->closeRequested) {
if (this->isBaudChanged) {
this->isBaudChanged = false;
currSerialBaud = this->serialBaud;
/* Clear input/output buffers */
this->inputBuffLock.lock();
this->inputBuff.clear();
this->inputBuffLock.unlock();
if (currSerialBaud) {
// Changing to a different baud rate
start_time = QDateTime::currentMSecsSinceEpoch();
// If currently signed on the reset can be skipped
this->owner->notifySerialOpened(this);
if (isSignedOn) {
isSignedOn = false;
protocol.signOut();
} else {
protocol.reset();
}
port.setBaudRate(currSerialBaud);
updateStatus("[Serial] Active");
} else {
// Leaving Serial mode - sign on needed
needSignOn = true;
port.setBaudRate(115200);
}
}
if (currSerialBaud) {
/* Serial mode: process serial I/O */
/* If no data available, wait for reading to be done shortly */
if (!port.bytesAvailable()) {
port.waitForReadyRead(20);
}
/* Read in data */
int cnt = port.read((char*) serialBuffer, sizeof(serialBuffer));
/* Copy to the read buffer */
if (cnt) {
if (!hasData) {
hasData = true;
qDebug() << "Program started after " << (QDateTime::currentMSecsSinceEpoch() - start_time) << "ms";
}
this->inputBuffLock.lock();
this->inputBuff.append(serialBuffer, cnt);
this->inputBuffLock.unlock();
}
} else {
/* Command mode: process bootloader I/O */
stk500Task *task = this->currentTask;
/* If not signed on and a task is to be handled, sign on first */
if (task != NULL && !isSignedOn) {
needSignOn = true;
}
/* Sign on with the bootloader */
if (needSignOn) {
needSignOn = false;
updateStatus("[STK500] Signing on");
isSignedOn = trySignOn(&protocol);
if (!isSignedOn) {
updateStatus("[STK500] Sign-on error");
}
}
if (task == NULL) {
/* No task - wait for tasks to be sent our way */
this->isProcessing = false;
// Waited for the full interval time, ping with a signOn command
// Still alive?
if (isSignedOn) {
updateStatus("[STK500] Idle");
isSignedOn = trySignOn(&protocol);
if (!isSignedOn) {
updateStatus("[STK500] Session lost");
}
}
/* Wait for a short time to keep the bootloader in the right mode */
sync.lock();
cond.wait(&sync, STK500_CMD_MIN_INTERVAL);
sync.unlock();
} else {
/* Update status */
updateStatus("[STK500] Busy");
/* Process the current task */
try {
if (!isSignedOn) {
throw ProtocolException("Could not communicate with device");
}
// Before processing, force the Micro-SD to re-read information
protocol.sd().reset();
protocol.sd().discardCache();
// Process the task after setting the protocol
task->setProtocol(protocol);
task->run();
// Flush the data on the Micro-SD now all is well
protocol.sd().flushCache();
} catch (ProtocolException &ex) {
task->setError(ex);
/* Flush here as well, but eat up any errors... */
try {
protocol.sd().flushCache();
} catch (ProtocolException&) {
}
}
// Clear the currently executed task
currentTask = NULL;
}
}
/* If port is closed, exit the thread */
if (!port.isOpen()) {
this->closeRequested = true;
}
}
/* Notify owner that this port is (being) closed */
updateStatus("Closing...");
/* Close the serial port; this can hang in some cases */
port.close();
/* Notify owner that port has been closed */
updateStatus("Port closed");
}
this->isRunning = false;
this->isProcessing = false;
this->owner->notifyClosed(this);
}
bool stk500_ProcessThread::trySignOn(stk500 *protocol) {
for (int i = 0; i < 2; i++) {
try {
protocolName = protocol->signOn();
return true;
} catch (ProtocolException& ex) {
qDebug() << "Failed to sign on: " << ex.what();
protocol->resetDelayed();
}
}
return false;
}
void stk500_ProcessThread::updateStatus(QString status) {
if (this->status != status) {
this->status = status;
this->owner->notifyStatus(this, this->status);
}
}
void stk500_ProcessThread::cancelTasks() {
stk500Task *curr = currentTask;
if (curr != NULL) {
curr->cancel();
}
wake();
}
void stk500_ProcessThread::wake() {
cond.wakeAll();
}
| Replace status update routines for consistency | Replace status update routines for consistency
| C++ | mit | Phoenard/Phoenard-Toolkit,Phoenard/Phoenard-Toolkit |
1ca6e4384312f5420f718401517368c86962cb1e | COFF/ICF.cpp | COFF/ICF.cpp | //===- ICF.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// ICF is short for Identical Code Folding. That is a size optimization to
// identify and merge two or more read-only sections (typically functions)
// that happened to have the same contents. It usually reduces output size
// by a few percent.
//
// On Windows, ICF is enabled by default.
//
// See ELF/ICF.cpp for the details about the algortihm.
//
//===----------------------------------------------------------------------===//
#include "ICF.h"
#include "Chunks.h"
#include "Symbols.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Timer.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/xxhash.h"
#include <algorithm>
#include <atomic>
#include <vector>
using namespace llvm;
namespace lld {
namespace coff {
static Timer ICFTimer("ICF", Timer::root());
class ICF {
public:
void run(ArrayRef<Chunk *> V);
private:
void segregate(size_t Begin, size_t End, bool Constant);
bool assocEquals(const SectionChunk *A, const SectionChunk *B);
bool equalsConstant(const SectionChunk *A, const SectionChunk *B);
bool equalsVariable(const SectionChunk *A, const SectionChunk *B);
uint32_t getHash(SectionChunk *C);
bool isEligible(SectionChunk *C);
size_t findBoundary(size_t Begin, size_t End);
void forEachClassRange(size_t Begin, size_t End,
std::function<void(size_t, size_t)> Fn);
void forEachClass(std::function<void(size_t, size_t)> Fn);
std::vector<SectionChunk *> Chunks;
int Cnt = 0;
std::atomic<bool> Repeat = {false};
};
// Returns true if section S is subject of ICF.
//
// Microsoft's documentation
// (https://msdn.microsoft.com/en-us/library/bxwfs976.aspx; visited April
// 2017) says that /opt:icf folds both functions and read-only data.
// Despite that, the MSVC linker folds only functions. We found
// a few instances of programs that are not safe for data merging.
// Therefore, we merge only functions just like the MSVC tool. However, we also
// merge read-only sections in a couple of cases where the address of the
// section is insignificant to the user program and the behaviour matches that
// of the Visual C++ linker.
bool ICF::isEligible(SectionChunk *C) {
// Non-comdat chunks, dead chunks, and writable chunks are not elegible.
bool Writable = C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
if (!C->isCOMDAT() || !C->Live || Writable)
return false;
// Code sections are eligible.
if (C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
return true;
// .pdata and .xdata unwind info sections are eligible.
StringRef OutSecName = C->getSectionName().split('$').first;
if (OutSecName == ".pdata" || OutSecName == ".xdata")
return true;
// So are vtables.
if (C->Sym && C->Sym->getName().startswith("??_7"))
return true;
// Anything else not in an address-significance table is eligible.
return !C->KeepUnique;
}
// Split an equivalence class into smaller classes.
void ICF::segregate(size_t Begin, size_t End, bool Constant) {
while (Begin < End) {
// Divide [Begin, End) into two. Let Mid be the start index of the
// second group.
auto Bound = std::stable_partition(
Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
if (Constant)
return equalsConstant(Chunks[Begin], S);
return equalsVariable(Chunks[Begin], S);
});
size_t Mid = Bound - Chunks.begin();
// Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
// equivalence class ID because every group ends with a unique index.
for (size_t I = Begin; I < Mid; ++I)
Chunks[I]->Class[(Cnt + 1) % 2] = Mid;
// If we created a group, we need to iterate the main loop again.
if (Mid != End)
Repeat = true;
Begin = Mid;
}
}
// Returns true if two sections' associative children are equal.
bool ICF::assocEquals(const SectionChunk *A, const SectionChunk *B) {
auto ChildClasses = [&](const SectionChunk *SC) {
std::vector<uint32_t> Classes;
for (const SectionChunk *C : SC->children())
if (!C->SectionName.startswith(".debug") &&
C->SectionName != ".gfids$y" && C->SectionName != ".gljmp$y")
Classes.push_back(C->Class[Cnt % 2]);
return Classes;
};
return ChildClasses(A) == ChildClasses(B);
}
// Compare "non-moving" part of two sections, namely everything
// except relocation targets.
bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) {
if (A->Relocs.size() != B->Relocs.size())
return false;
// Compare relocations.
auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
if (R1.Type != R2.Type ||
R1.VirtualAddress != R2.VirtualAddress) {
return false;
}
Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
if (B1 == B2)
return true;
if (auto *D1 = dyn_cast<DefinedRegular>(B1))
if (auto *D2 = dyn_cast<DefinedRegular>(B2))
return D1->getValue() == D2->getValue() &&
D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
return false;
};
if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
return false;
// Compare section attributes and contents.
return A->getOutputCharacteristics() == B->getOutputCharacteristics() &&
A->SectionName == B->SectionName &&
A->Header->SizeOfRawData == B->Header->SizeOfRawData &&
A->Checksum == B->Checksum && A->getContents() == B->getContents() &&
assocEquals(A, B);
}
// Compare "moving" part of two sections, namely relocation targets.
bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) {
// Compare relocations.
auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
if (B1 == B2)
return true;
if (auto *D1 = dyn_cast<DefinedRegular>(B1))
if (auto *D2 = dyn_cast<DefinedRegular>(B2))
return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
return false;
};
return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(),
Eq) &&
assocEquals(A, B);
}
// Find the first Chunk after Begin that has a different class from Begin.
size_t ICF::findBoundary(size_t Begin, size_t End) {
for (size_t I = Begin + 1; I < End; ++I)
if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2])
return I;
return End;
}
void ICF::forEachClassRange(size_t Begin, size_t End,
std::function<void(size_t, size_t)> Fn) {
while (Begin < End) {
size_t Mid = findBoundary(Begin, End);
Fn(Begin, Mid);
Begin = Mid;
}
}
// Call Fn on each class group.
void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) {
// If the number of sections are too small to use threading,
// call Fn sequentially.
if (Chunks.size() < 1024) {
forEachClassRange(0, Chunks.size(), Fn);
++Cnt;
return;
}
// Shard into non-overlapping intervals, and call Fn in parallel.
// The sharding must be completed before any calls to Fn are made
// so that Fn can modify the Chunks in its shard without causing data
// races.
const size_t NumShards = 256;
size_t Step = Chunks.size() / NumShards;
size_t Boundaries[NumShards + 1];
Boundaries[0] = 0;
Boundaries[NumShards] = Chunks.size();
for_each_n(parallel::par, size_t(1), NumShards, [&](size_t I) {
Boundaries[I] = findBoundary((I - 1) * Step, Chunks.size());
});
for_each_n(parallel::par, size_t(1), NumShards + 1, [&](size_t I) {
if (Boundaries[I - 1] < Boundaries[I]) {
forEachClassRange(Boundaries[I - 1], Boundaries[I], Fn);
}
});
++Cnt;
}
// Merge identical COMDAT sections.
// Two sections are considered the same if their section headers,
// contents and relocations are all the same.
void ICF::run(ArrayRef<Chunk *> Vec) {
ScopedTimer T(ICFTimer);
// Collect only mergeable sections and group by hash value.
uint32_t NextId = 1;
for (Chunk *C : Vec) {
if (auto *SC = dyn_cast<SectionChunk>(C)) {
if (isEligible(SC))
Chunks.push_back(SC);
else
SC->Class[0] = NextId++;
}
}
// Make sure that ICF doesn't merge sections that are being handled by string
// tail merging.
for (auto &P : MergeChunk::Instances)
for (SectionChunk *SC : P.second->Sections)
SC->Class[0] = NextId++;
// Initially, we use hash values to partition sections.
for_each(parallel::par, Chunks.begin(), Chunks.end(), [&](SectionChunk *SC) {
SC->Class[1] = xxHash64(SC->getContents());
});
// Combine the hashes of the sections referenced by each section into its
// hash.
for_each(parallel::par, Chunks.begin(), Chunks.end(), [&](SectionChunk *SC) {
uint32_t Hash = SC->Class[1];
for (Symbol *B : SC->symbols())
if (auto *Sym = dyn_cast_or_null<DefinedRegular>(B))
Hash ^= Sym->getChunk()->Class[1];
// Set MSB to 1 to avoid collisions with non-hash classs.
SC->Class[0] = Hash | (1U << 31);
});
// From now on, sections in Chunks are ordered so that sections in
// the same group are consecutive in the vector.
std::stable_sort(Chunks.begin(), Chunks.end(),
[](SectionChunk *A, SectionChunk *B) {
return A->Class[0] < B->Class[0];
});
// Compare static contents and assign unique IDs for each static content.
forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
// Split groups by comparing relocations until convergence is obtained.
do {
Repeat = false;
forEachClass(
[&](size_t Begin, size_t End) { segregate(Begin, End, false); });
} while (Repeat);
log("ICF needed " + Twine(Cnt) + " iterations");
// Merge sections in the same classs.
forEachClass([&](size_t Begin, size_t End) {
if (End - Begin == 1)
return;
log("Selected " + Chunks[Begin]->getDebugName());
for (size_t I = Begin + 1; I < End; ++I) {
log(" Removed " + Chunks[I]->getDebugName());
Chunks[Begin]->replace(Chunks[I]);
}
});
}
// Entry point to ICF.
void doICF(ArrayRef<Chunk *> Chunks) { ICF().run(Chunks); }
} // namespace coff
} // namespace lld
| //===- ICF.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// ICF is short for Identical Code Folding. That is a size optimization to
// identify and merge two or more read-only sections (typically functions)
// that happened to have the same contents. It usually reduces output size
// by a few percent.
//
// On Windows, ICF is enabled by default.
//
// See ELF/ICF.cpp for the details about the algortihm.
//
//===----------------------------------------------------------------------===//
#include "ICF.h"
#include "Chunks.h"
#include "Symbols.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Threads.h"
#include "lld/Common/Timer.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/xxhash.h"
#include <algorithm>
#include <atomic>
#include <vector>
using namespace llvm;
namespace lld {
namespace coff {
static Timer ICFTimer("ICF", Timer::root());
class ICF {
public:
void run(ArrayRef<Chunk *> V);
private:
void segregate(size_t Begin, size_t End, bool Constant);
bool assocEquals(const SectionChunk *A, const SectionChunk *B);
bool equalsConstant(const SectionChunk *A, const SectionChunk *B);
bool equalsVariable(const SectionChunk *A, const SectionChunk *B);
uint32_t getHash(SectionChunk *C);
bool isEligible(SectionChunk *C);
size_t findBoundary(size_t Begin, size_t End);
void forEachClassRange(size_t Begin, size_t End,
std::function<void(size_t, size_t)> Fn);
void forEachClass(std::function<void(size_t, size_t)> Fn);
std::vector<SectionChunk *> Chunks;
int Cnt = 0;
std::atomic<bool> Repeat = {false};
};
// Returns true if section S is subject of ICF.
//
// Microsoft's documentation
// (https://msdn.microsoft.com/en-us/library/bxwfs976.aspx; visited April
// 2017) says that /opt:icf folds both functions and read-only data.
// Despite that, the MSVC linker folds only functions. We found
// a few instances of programs that are not safe for data merging.
// Therefore, we merge only functions just like the MSVC tool. However, we also
// merge read-only sections in a couple of cases where the address of the
// section is insignificant to the user program and the behaviour matches that
// of the Visual C++ linker.
bool ICF::isEligible(SectionChunk *C) {
// Non-comdat chunks, dead chunks, and writable chunks are not elegible.
bool Writable = C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_WRITE;
if (!C->isCOMDAT() || !C->Live || Writable)
return false;
// Code sections are eligible.
if (C->getOutputCharacteristics() & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
return true;
// .pdata and .xdata unwind info sections are eligible.
StringRef OutSecName = C->getSectionName().split('$').first;
if (OutSecName == ".pdata" || OutSecName == ".xdata")
return true;
// So are vtables.
if (C->Sym && C->Sym->getName().startswith("??_7"))
return true;
// Anything else not in an address-significance table is eligible.
return !C->KeepUnique;
}
// Split an equivalence class into smaller classes.
void ICF::segregate(size_t Begin, size_t End, bool Constant) {
while (Begin < End) {
// Divide [Begin, End) into two. Let Mid be the start index of the
// second group.
auto Bound = std::stable_partition(
Chunks.begin() + Begin + 1, Chunks.begin() + End, [&](SectionChunk *S) {
if (Constant)
return equalsConstant(Chunks[Begin], S);
return equalsVariable(Chunks[Begin], S);
});
size_t Mid = Bound - Chunks.begin();
// Split [Begin, End) into [Begin, Mid) and [Mid, End). We use Mid as an
// equivalence class ID because every group ends with a unique index.
for (size_t I = Begin; I < Mid; ++I)
Chunks[I]->Class[(Cnt + 1) % 2] = Mid;
// If we created a group, we need to iterate the main loop again.
if (Mid != End)
Repeat = true;
Begin = Mid;
}
}
// Returns true if two sections' associative children are equal.
bool ICF::assocEquals(const SectionChunk *A, const SectionChunk *B) {
auto ChildClasses = [&](const SectionChunk *SC) {
std::vector<uint32_t> Classes;
for (const SectionChunk *C : SC->children())
if (!C->SectionName.startswith(".debug") &&
C->SectionName != ".gfids$y" && C->SectionName != ".gljmp$y")
Classes.push_back(C->Class[Cnt % 2]);
return Classes;
};
return ChildClasses(A) == ChildClasses(B);
}
// Compare "non-moving" part of two sections, namely everything
// except relocation targets.
bool ICF::equalsConstant(const SectionChunk *A, const SectionChunk *B) {
if (A->Relocs.size() != B->Relocs.size())
return false;
// Compare relocations.
auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
if (R1.Type != R2.Type ||
R1.VirtualAddress != R2.VirtualAddress) {
return false;
}
Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
if (B1 == B2)
return true;
if (auto *D1 = dyn_cast<DefinedRegular>(B1))
if (auto *D2 = dyn_cast<DefinedRegular>(B2))
return D1->getValue() == D2->getValue() &&
D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
return false;
};
if (!std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(), Eq))
return false;
// Compare section attributes and contents.
return A->getOutputCharacteristics() == B->getOutputCharacteristics() &&
A->SectionName == B->SectionName &&
A->Header->SizeOfRawData == B->Header->SizeOfRawData &&
A->Checksum == B->Checksum && A->getContents() == B->getContents() &&
assocEquals(A, B);
}
// Compare "moving" part of two sections, namely relocation targets.
bool ICF::equalsVariable(const SectionChunk *A, const SectionChunk *B) {
// Compare relocations.
auto Eq = [&](const coff_relocation &R1, const coff_relocation &R2) {
Symbol *B1 = A->File->getSymbol(R1.SymbolTableIndex);
Symbol *B2 = B->File->getSymbol(R2.SymbolTableIndex);
if (B1 == B2)
return true;
if (auto *D1 = dyn_cast<DefinedRegular>(B1))
if (auto *D2 = dyn_cast<DefinedRegular>(B2))
return D1->getChunk()->Class[Cnt % 2] == D2->getChunk()->Class[Cnt % 2];
return false;
};
return std::equal(A->Relocs.begin(), A->Relocs.end(), B->Relocs.begin(),
Eq) &&
assocEquals(A, B);
}
// Find the first Chunk after Begin that has a different class from Begin.
size_t ICF::findBoundary(size_t Begin, size_t End) {
for (size_t I = Begin + 1; I < End; ++I)
if (Chunks[Begin]->Class[Cnt % 2] != Chunks[I]->Class[Cnt % 2])
return I;
return End;
}
void ICF::forEachClassRange(size_t Begin, size_t End,
std::function<void(size_t, size_t)> Fn) {
while (Begin < End) {
size_t Mid = findBoundary(Begin, End);
Fn(Begin, Mid);
Begin = Mid;
}
}
// Call Fn on each class group.
void ICF::forEachClass(std::function<void(size_t, size_t)> Fn) {
// If the number of sections are too small to use threading,
// call Fn sequentially.
if (Chunks.size() < 1024) {
forEachClassRange(0, Chunks.size(), Fn);
++Cnt;
return;
}
// Shard into non-overlapping intervals, and call Fn in parallel.
// The sharding must be completed before any calls to Fn are made
// so that Fn can modify the Chunks in its shard without causing data
// races.
const size_t NumShards = 256;
size_t Step = Chunks.size() / NumShards;
size_t Boundaries[NumShards + 1];
Boundaries[0] = 0;
Boundaries[NumShards] = Chunks.size();
parallelForEachN(1, NumShards, [&](size_t I) {
Boundaries[I] = findBoundary((I - 1) * Step, Chunks.size());
});
parallelForEachN(1, NumShards + 1, [&](size_t I) {
if (Boundaries[I - 1] < Boundaries[I]) {
forEachClassRange(Boundaries[I - 1], Boundaries[I], Fn);
}
});
++Cnt;
}
// Merge identical COMDAT sections.
// Two sections are considered the same if their section headers,
// contents and relocations are all the same.
void ICF::run(ArrayRef<Chunk *> Vec) {
ScopedTimer T(ICFTimer);
// Collect only mergeable sections and group by hash value.
uint32_t NextId = 1;
for (Chunk *C : Vec) {
if (auto *SC = dyn_cast<SectionChunk>(C)) {
if (isEligible(SC))
Chunks.push_back(SC);
else
SC->Class[0] = NextId++;
}
}
// Make sure that ICF doesn't merge sections that are being handled by string
// tail merging.
for (auto &P : MergeChunk::Instances)
for (SectionChunk *SC : P.second->Sections)
SC->Class[0] = NextId++;
// Initially, we use hash values to partition sections.
parallelForEach(Chunks, [&](SectionChunk *SC) {
SC->Class[1] = xxHash64(SC->getContents());
});
// Combine the hashes of the sections referenced by each section into its
// hash.
parallelForEach(Chunks, [&](SectionChunk *SC) {
uint32_t Hash = SC->Class[1];
for (Symbol *B : SC->symbols())
if (auto *Sym = dyn_cast_or_null<DefinedRegular>(B))
Hash ^= Sym->getChunk()->Class[1];
// Set MSB to 1 to avoid collisions with non-hash classs.
SC->Class[0] = Hash | (1U << 31);
});
// From now on, sections in Chunks are ordered so that sections in
// the same group are consecutive in the vector.
std::stable_sort(Chunks.begin(), Chunks.end(),
[](SectionChunk *A, SectionChunk *B) {
return A->Class[0] < B->Class[0];
});
// Compare static contents and assign unique IDs for each static content.
forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); });
// Split groups by comparing relocations until convergence is obtained.
do {
Repeat = false;
forEachClass(
[&](size_t Begin, size_t End) { segregate(Begin, End, false); });
} while (Repeat);
log("ICF needed " + Twine(Cnt) + " iterations");
// Merge sections in the same classs.
forEachClass([&](size_t Begin, size_t End) {
if (End - Begin == 1)
return;
log("Selected " + Chunks[Begin]->getDebugName());
for (size_t I = Begin + 1; I < End; ++I) {
log(" Removed " + Chunks[I]->getDebugName());
Chunks[Begin]->replace(Chunks[I]);
}
});
}
// Entry point to ICF.
void doICF(ArrayRef<Chunk *> Chunks) { ICF().run(Chunks); }
} // namespace coff
} // namespace lld
| use parallelForEach{,N} | [COFF] ICF: use parallelForEach{,N}
Summary: They have an additional `ThreadsEnabled` check, which does not matter much.
Reviewers: pcc, ruiu, rnk
Reviewed By: ruiu
Subscribers: llvm-commits
Differential Revision: https://reviews.llvm.org/D54812
git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@347587 91177308-0d34-0410-b5e6-96231b3b80d8
| C++ | apache-2.0 | llvm-mirror/lld,llvm-mirror/lld |
8e3d0547ac93fc49076330d231109d30168a0b45 | src/software/SfM/main_PairGenerator.cpp | src/software/SfM/main_PairGenerator.cpp | // This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2019 Romuald PERROT
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/matching_image_collection/Pair_Builder.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <iostream>
/**
* @brief Current list of available pair mode
*
*/
enum EPairMode
{
PAIR_EXHAUSTIVE = 0, // Build every combination of image pairs
PAIR_CONTIGUOUS = 1 // Only consecutive image pairs (useful for video mode)
};
using namespace openMVG;
using namespace openMVG::sfm;
void usage( const char* argv0 )
{
std::cerr << "Usage: " << argv0 << '\n'
<< "[-i|--input_file] A SfM_Data file\n"
<< "[-o|--output_file] Output file where pairs are stored\n"
<< "\n[Optional]\n"
<< "[-m|--pair_mode] mode Pair generation mode\n"
<< " EXHAUSTIVE: Build all possible pairs. [default]\n"
<< " CONTIGUOUS: Build pairs for contiguous images (use it with --contiguous_count parameter)\n"
<< "[-c|--contiguous_count] X Number of contiguous links\n"
<< " X: with match 0 with (1->X), ...]\n"
<< " 2: will match 0 with (1,2), 1 with (2,3), ...\n"
<< " 3: will match 0 with (1,2,3), 1 with (2,3,4), ...\n"
<< std::endl;
}
// This executable computes pairs of images to be matched
int main( int argc, char** argv )
{
CmdLine cmd;
std::string sSfMDataFilename;
std::string sOutputPairsFilename;
std::string sPairMode = "EXHAUSTIVE";
int iContiguousCount = -1;
// Mandatory elements:
cmd.add( make_option( 'i', sSfMDataFilename, "input_file" ) );
cmd.add( make_option( 'o', sOutputPairsFilename, "output_file" ) );
// Optionnal elements:
cmd.add( make_option( 'm', sPairMode, "pair_mode" ) );
cmd.add( make_option( 'c', iContiguousCount, "contiguous_count" ) );
try
{
if ( argc == 1 )
throw std::string( "Invalid command line parameter." );
cmd.process( argc, argv );
}
catch ( const std::string& s )
{
usage( argv[ 0 ] );
std::cerr << "[Error] " << s << std::endl;
return EXIT_FAILURE;
}
// 0. Parse parameters
std::cout << " You called:\n"
<< argv[ 0 ] << "\n"
<< "--input_file : " << sSfMDataFilename << "\n"
<< "--output_file : " << sOutputPairsFilename << "\n"
<< "Optional parameters\n"
<< "--pair_mode : " << sPairMode << "\n"
<< "--contiguous_count : " << iContiguousCount << "\n"
<< std::endl;
if ( sSfMDataFilename.empty() )
{
usage( argv[ 0 ] );
std::cerr << "[Error] Input file not set." << std::endl;
exit( EXIT_FAILURE );
}
if ( sOutputPairsFilename.empty() )
{
usage( argv[ 0 ] );
std::cerr << "[Error] Output file not set." << std::endl;
exit( EXIT_FAILURE );
}
EPairMode pairMode;
if ( sPairMode == "EXHAUSTIVE" )
{
pairMode = PAIR_EXHAUSTIVE;
}
else if ( sPairMode == "CONTIGUOUS" )
{
if ( iContiguousCount == -1 )
{
usage( argv[ 0 ] );
std::cerr << "[Error] Contiguous pair mode selected but contiguous_count not set." << std::endl;
exit( EXIT_FAILURE );
}
pairMode = PAIR_CONTIGUOUS;
}
// 1. Load SfM data scene
std::cout << "Loading scene.";
SfM_Data sfm_data;
if ( !Load( sfm_data, sSfMDataFilename, ESfM_Data( VIEWS | INTRINSICS ) ) )
{
std::cerr << std::endl
<< "The input SfM_Data file \"" << sSfMDataFilename << "\" cannot be read." << std::endl;
exit( EXIT_FAILURE );
}
const size_t NImage = sfm_data.GetViews().size();
// 2. Compute pairs
std::cout << "Computing pairs." << std::endl;
Pair_Set pairs;
switch ( pairMode )
{
case PAIR_EXHAUSTIVE:
{
pairs = exhaustivePairs( NImage );
break;
}
case PAIR_CONTIGUOUS:
{
pairs = contiguousWithOverlap( NImage, iContiguousCount );
break;
}
default:
{
std::cerr << "Unknown pair mode" << std::endl;
exit( EXIT_FAILURE );
}
}
// 3. Save pairs
std::cout << "Saving pairs." << std::endl;
if ( !savePairs( sOutputPairsFilename, pairs ) )
{
std::cerr << "Failed to save pairs to file: \"" << sOutputPairsFilename << "\"" << std::endl;
exit( EXIT_FAILURE );
}
return EXIT_SUCCESS;
}
| // This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2019 Romuald PERROT
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/matching_image_collection/Pair_Builder.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <iostream>
/**
* @brief Current list of available pair mode
*
*/
enum EPairMode
{
PAIR_EXHAUSTIVE = 0, // Build every combination of image pairs
PAIR_CONTIGUOUS = 1 // Only consecutive image pairs (useful for video mode)
};
using namespace openMVG;
using namespace openMVG::sfm;
void usage( const char* argv0 )
{
std::cerr << "Usage: " << argv0 << '\n'
<< "[-i|--input_file] A SfM_Data file\n"
<< "[-o|--output_file] Output file where pairs are stored\n"
<< "\n[Optional]\n"
<< "[-m|--pair_mode] mode Pair generation mode\n"
<< " EXHAUSTIVE: Build all possible pairs. [default]\n"
<< " CONTIGUOUS: Build pairs for contiguous images (use it with --contiguous_count parameter)\n"
<< "[-c|--contiguous_count] X Number of contiguous links\n"
<< " X: will match 0 with (1->X), ...]\n"
<< " 2: will match 0 with (1,2), 1 with (2,3), ...\n"
<< " 3: will match 0 with (1,2,3), 1 with (2,3,4), ...\n"
<< std::endl;
}
// This executable computes pairs of images to be matched
int main( int argc, char** argv )
{
CmdLine cmd;
std::string sSfMDataFilename;
std::string sOutputPairsFilename;
std::string sPairMode = "EXHAUSTIVE";
int iContiguousCount = -1;
// Mandatory elements:
cmd.add( make_option( 'i', sSfMDataFilename, "input_file" ) );
cmd.add( make_option( 'o', sOutputPairsFilename, "output_file" ) );
// Optionnal elements:
cmd.add( make_option( 'm', sPairMode, "pair_mode" ) );
cmd.add( make_option( 'c', iContiguousCount, "contiguous_count" ) );
try
{
if ( argc == 1 )
throw std::string( "Invalid command line parameter." );
cmd.process( argc, argv );
}
catch ( const std::string& s )
{
usage( argv[ 0 ] );
std::cerr << "[Error] " << s << std::endl;
return EXIT_FAILURE;
}
// 0. Parse parameters
std::cout << " You called:\n"
<< argv[ 0 ] << "\n"
<< "--input_file : " << sSfMDataFilename << "\n"
<< "--output_file : " << sOutputPairsFilename << "\n"
<< "Optional parameters\n"
<< "--pair_mode : " << sPairMode << "\n"
<< "--contiguous_count : " << iContiguousCount << "\n"
<< std::endl;
if ( sSfMDataFilename.empty() )
{
usage( argv[ 0 ] );
std::cerr << "[Error] Input file not set." << std::endl;
exit( EXIT_FAILURE );
}
if ( sOutputPairsFilename.empty() )
{
usage( argv[ 0 ] );
std::cerr << "[Error] Output file not set." << std::endl;
exit( EXIT_FAILURE );
}
EPairMode pairMode;
if ( sPairMode == "EXHAUSTIVE" )
{
pairMode = PAIR_EXHAUSTIVE;
}
else if ( sPairMode == "CONTIGUOUS" )
{
if ( iContiguousCount == -1 )
{
usage( argv[ 0 ] );
std::cerr << "[Error] Contiguous pair mode selected but contiguous_count not set." << std::endl;
exit( EXIT_FAILURE );
}
pairMode = PAIR_CONTIGUOUS;
}
// 1. Load SfM data scene
std::cout << "Loading scene.";
SfM_Data sfm_data;
if ( !Load( sfm_data, sSfMDataFilename, ESfM_Data( VIEWS | INTRINSICS ) ) )
{
std::cerr << std::endl
<< "The input SfM_Data file \"" << sSfMDataFilename << "\" cannot be read." << std::endl;
exit( EXIT_FAILURE );
}
const size_t NImage = sfm_data.GetViews().size();
// 2. Compute pairs
std::cout << "Computing pairs." << std::endl;
Pair_Set pairs;
switch ( pairMode )
{
case PAIR_EXHAUSTIVE:
{
pairs = exhaustivePairs( NImage );
break;
}
case PAIR_CONTIGUOUS:
{
pairs = contiguousWithOverlap( NImage, iContiguousCount );
break;
}
default:
{
std::cerr << "Unknown pair mode" << std::endl;
exit( EXIT_FAILURE );
}
}
// 3. Save pairs
std::cout << "Saving pairs." << std::endl;
if ( !savePairs( sOutputPairsFilename, pairs ) )
{
std::cerr << "Failed to save pairs to file: \"" << sOutputPairsFilename << "\"" << std::endl;
exit( EXIT_FAILURE );
}
return EXIT_SUCCESS;
}
| Fix typo | Fix typo
| C++ | mpl-2.0 | openMVG/openMVG,openMVG/openMVG,openMVG/openMVG,openMVG/openMVG,openMVG/openMVG |
653bb3d64057f11c5c9a8f539ba57be549097cee | src/wallet/test/wallet_test_fixture.cpp | src/wallet/test/wallet_test_fixture.cpp | #include "wallet/test/wallet_test_fixture.h"
#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
TestingSetup(chainName)
{
bitdb.MakeMock();
bool fFirstRun;
pwalletMain = new CWallet("wallet_test.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
RegisterWalletRPCCommands(tableRPC);
}
WalletTestingSetup::~WalletTestingSetup()
{
UnregisterValidationInterface(pwalletMain);
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
bitdb.Reset();
}
| // Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/test/wallet_test_fixture.h"
#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"
WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
TestingSetup(chainName)
{
bitdb.MakeMock();
bool fFirstRun;
pwalletMain = new CWallet("wallet_test.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
RegisterWalletRPCCommands(tableRPC);
}
WalletTestingSetup::~WalletTestingSetup()
{
UnregisterValidationInterface(pwalletMain);
delete pwalletMain;
pwalletMain = NULL;
bitdb.Flush(true);
bitdb.Reset();
}
| Add copyright header to wallet_text_fixture.cpp | Add copyright header to wallet_text_fixture.cpp
I created the file but forgot to add this header.
| C++ | mit | Kogser/bitcoin,r8921039/bitcoin,yenliangl/bitcoin,MarcoFalke/bitcoin,dscotese/bitcoin,peercoin/peercoin,sebrandon1/bitcoin,argentumproject/argentum,fsb4000/bitcoin,dgarage/bc2,nbenoit/bitcoin,spiritlinxl/BTCGPU,bitcoinec/bitcoinec,zcoinofficial/zcoin,RHavar/bitcoin,guncoin/guncoin,21E14/bitcoin,svost/bitcoin,litecoin-project/litecoin,jonasschnelli/bitcoin,OmniLayer/omnicore,bitreserve/bitcoin,zcoinofficial/zcoin,gmaxwell/bitcoin,destenson/bitcoin--bitcoin,lateminer/bitcoin,CryptArc/bitcoin,dscotese/bitcoin,qtumproject/qtum,qtumproject/qtum,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,shelvenzhou/BTCGPU,StarbuckBG/BTCGPU,tjps/bitcoin,trippysalmon/bitcoin,Michagogo/bitcoin,globaltoken/globaltoken,bitcoinsSG/bitcoin,prusnak/bitcoin,jiangyonghang/bitcoin,multicoins/marycoin,ryanxcharles/bitcoin,nbenoit/bitcoin,stamhe/bitcoin,wiggi/huntercore,goldcoin/goldcoin,core-bitcoin/bitcoin,guncoin/guncoin,174high/bitcoin,jamesob/bitcoin,joshrabinowitz/bitcoin,Rav3nPL/bitcoin,n1bor/bitcoin,BitcoinPOW/BitcoinPOW,wellenreiter01/Feathercoin,achow101/bitcoin,dgarage/bc3,Anfauglith/iop-hd,Bitcoin-ABC/bitcoin-abc,trippysalmon/bitcoin,s-matthew-english/bitcoin,BTCDDev/bitcoin,bitcoin/bitcoin,vmp32k/litecoin,particl/particl-core,Gazer022/bitcoin,BigBlueCeiling/augmentacoin,midnightmagic/bitcoin,Rav3nPL/PLNcoin,namecoin/namecoin-core,wiggi/huntercore,multicoins/marycoin,sipsorcery/bitcoin,OmniLayer/omnicore,psionin/smartcoin,Christewart/bitcoin,AdrianaDinca/bitcoin,cculianu/bitcoin-abc,namecoin/namecore,x-kalux/bitcoin_WiG-B,senadmd/coinmarketwatch,h4x3rotab/BTCGPU,Kogser/bitcoin,CryptArc/bitcoin,tjps/bitcoin,jtimon/bitcoin,jambolo/bitcoin,MarcoFalke/bitcoin,uphold/bitcoin,zcoinofficial/zcoin,EntropyFactory/creativechain-core,myriadcoin/myriadcoin,fsb4000/bitcoin,Rav3nPL/bitcoin,argentumproject/argentum,achow101/bitcoin,Bushstar/UFO-Project,btc1/bitcoin,fujicoin/fujicoin,MeshCollider/bitcoin,argentumproject/argentum,trippysalmon/bitcoin,laudaa/bitcoin,Gazer022/bitcoin,psionin/smartcoin,stamhe/bitcoin,awemany/BitcoinUnlimited,Jcing95/iop-hd,Theshadow4all/ShadowCoin,qtumproject/qtum,ericshawlinux/bitcoin,pstratem/bitcoin,BigBlueCeiling/augmentacoin,matlongsi/micropay,ElementsProject/elements,r8921039/bitcoin,lbryio/lbrycrd,rawodb/bitcoin,trippysalmon/bitcoin,dogecoin/dogecoin,fujicoin/fujicoin,AkioNak/bitcoin,gjhiggins/vcoincore,Bitcoin-ABC/bitcoin-abc,dcousens/bitcoin,ftrader-bitcoinabc/bitcoin-abc,instagibbs/bitcoin,mm-s/bitcoin,patricklodder/dogecoin,ericshawlinux/bitcoin,sarielsaz/sarielsaz,bitcoin/bitcoin,ShadowMyst/creativechain-core,shelvenzhou/BTCGPU,JeremyRubin/bitcoin,ahmedbodi/vertcoin,maaku/bitcoin,gmaxwell/bitcoin,laudaa/bitcoin,ftrader-bitcoinabc/bitcoin-abc,rnicoll/bitcoin,guncoin/guncoin,shouhuas/bitcoin,tecnovert/particl-core,randy-waterhouse/bitcoin,Gazer022/bitcoin,svost/bitcoin,psionin/smartcoin,anditto/bitcoin,elecoin/elecoin,senadmd/coinmarketwatch,pinheadmz/bitcoin,romanornr/viacoin,DigitalPandacoin/pandacoin,core-bitcoin/bitcoin,GlobalBoost/GlobalBoost,dpayne9000/Rubixz-Coin,HashUnlimited/Einsteinium-Unlimited,GlobalBoost/GlobalBoost,NicolasDorier/bitcoin,FeatherCoin/Feathercoin,awemany/BitcoinUnlimited,peercoin/peercoin,chaincoin/chaincoin,segsignal/bitcoin,Bitcoin-ABC/bitcoin-abc,StarbuckBG/BTCGPU,kazcw/bitcoin,rnicoll/bitcoin,bitreserve/bitcoin,tecnovert/particl-core,elecoin/elecoin,wangxinxi/litecoin,randy-waterhouse/bitcoin,gjhiggins/vcoincore,ElementsProject/elements,Xekyo/bitcoin,Sjors/bitcoin,ftrader-bitcoinabc/bitcoin-abc,jnewbery/bitcoin,Rav3nPL/PLNcoin,thrasher-/litecoin,ftrader-bitcoinabc/bitcoin-abc,OmniLayer/omnicore,mb300sd/bitcoin,StarbuckBG/BTCGPU,uphold/bitcoin,maaku/bitcoin,sdaftuar/bitcoin,dcousens/bitcoin,laudaa/bitcoin,GroestlCoin/bitcoin,bitcoin/bitcoin,x-kalux/bitcoin_WiG-B,Cocosoft/bitcoin,peercoin/peercoin,Theshadow4all/ShadowCoin,domob1812/bitcoin,sarielsaz/sarielsaz,jonasschnelli/bitcoin,ixcoinofficialpage/master,FeatherCoin/Feathercoin,Mirobit/bitcoin,mruddy/bitcoin,plncoin/PLNcoin_Core,bitbrazilcoin-project/bitbrazilcoin,kallewoof/bitcoin,monacoinproject/monacoin,BitcoinHardfork/bitcoin,ixcoinofficialpage/master,Chancoin-core/CHANCOIN,myriadteam/myriadcoin,joshrabinowitz/bitcoin,mitchellcash/bitcoin,globaltoken/globaltoken,viacoin/viacoin,dgarage/bc3,kallewoof/elements,litecoin-project/litecoin,haobtc/bitcoin,Christewart/bitcoin,bitcoin/bitcoin,AkioNak/bitcoin,starwels/starwels,matlongsi/micropay,jlopp/statoshi,ftrader-bitcoinabc/bitcoin-abc,JeremyRubin/bitcoin,dpayne9000/Rubixz-Coin,jambolo/bitcoin,ericshawlinux/bitcoin,tecnovert/particl-core,lateminer/bitcoin,cculianu/bitcoin-abc,simonmulser/bitcoin,isle2983/bitcoin,GlobalBoost/GlobalBoost,BitzenyCoreDevelopers/bitzeny,apoelstra/bitcoin,brandonrobertz/namecoin-core,multicoins/marycoin,prusnak/bitcoin,NicolasDorier/bitcoin,ppcoin/ppcoin,plncoin/PLNcoin_Core,Bitcoin-ABC/bitcoin-abc,ajtowns/bitcoin,Flowdalic/bitcoin,stamhe/bitcoin,droark/bitcoin,paveljanik/bitcoin,chaincoin/chaincoin,dgarage/bc2,sbaks0820/bitcoin,andreaskern/bitcoin,jambolo/bitcoin,ixcoinofficialpage/master,jonasschnelli/bitcoin,thrasher-/litecoin,domob1812/namecore,aspanta/bitcoin,argentumproject/argentum,fujicoin/fujicoin,practicalswift/bitcoin,litecoin-project/litecoin,dogecoin/dogecoin,senadmd/coinmarketwatch,digibyte/digibyte,argentumproject/argentum,XertroV/bitcoin-nulldata,kazcw/bitcoin,ericshawlinux/bitcoin,wiggi/huntercore,shouhuas/bitcoin,cculianu/bitcoin-abc,r8921039/bitcoin,wiggi/huntercore,Friedbaumer/litecoin,alecalve/bitcoin,starwels/starwels,sebrandon1/bitcoin,Christewart/bitcoin,peercoin/peercoin,romanornr/viacoin,jnewbery/bitcoin,digibyte/digibyte,andreaskern/bitcoin,BitzenyCoreDevelopers/bitzeny,Cocosoft/bitcoin,alecalve/bitcoin,EthanHeilman/bitcoin,viacoin/viacoin,haobtc/bitcoin,shelvenzhou/BTCGPU,JeremyRubin/bitcoin,AkioNak/bitcoin,fsb4000/bitcoin,myriadteam/myriadcoin,zcoinofficial/zcoin,globaltoken/globaltoken,BitcoinHardfork/bitcoin,romanornr/viacoin,Jcing95/iop-hd,wangxinxi/litecoin,fujicoin/fujicoin,AkioNak/bitcoin,Friedbaumer/litecoin,thrasher-/litecoin,NicolasDorier/bitcoin,Kogser/bitcoin,Kogser/bitcoin,rnicoll/bitcoin,Mirobit/bitcoin,achow101/bitcoin,bitreserve/bitcoin,segsignal/bitcoin,kevcooper/bitcoin,andreaskern/bitcoin,bitbrazilcoin-project/bitbrazilcoin,zcoinofficial/zcoin,ryanxcharles/bitcoin,s-matthew-english/bitcoin,sipsorcery/bitcoin,ShadowMyst/creativechain-core,jiangyonghang/bitcoin,zcoinofficial/zcoin,StarbuckBG/BTCGPU,BTCGPU/BTCGPU,paveljanik/bitcoin,Kogser/bitcoin,kallewoof/bitcoin,instagibbs/bitcoin,particl/particl-core,nikkitan/bitcoin,xieta/mincoin,ryanofsky/bitcoin,BigBlueCeiling/augmentacoin,FeatherCoin/Feathercoin,wellenreiter01/Feathercoin,qtumproject/qtum,MeshCollider/bitcoin,Rav3nPL/bitcoin,chaincoin/chaincoin,yenliangl/bitcoin,GroestlCoin/bitcoin,gjhiggins/vcoincore,ElementsProject/elements,domob1812/bitcoin,goldcoin/Goldcoin-GLD,rnicoll/bitcoin,nomnombtc/bitcoin,n1bor/bitcoin,Flowdalic/bitcoin,rnicoll/dogecoin,senadmd/coinmarketwatch,ahmedbodi/vertcoin,brandonrobertz/namecoin-core,gzuser01/zetacoin-bitcoin,xieta/mincoin,jtimon/bitcoin,Bushstar/UFO-Project,StarbuckBG/BTCGPU,s-matthew-english/bitcoin,gzuser01/zetacoin-bitcoin,spiritlinxl/BTCGPU,pinheadmz/bitcoin,jiangyonghang/bitcoin,jnewbery/bitcoin,174high/bitcoin,EthanHeilman/bitcoin,laudaa/bitcoin,mruddy/bitcoin,domob1812/namecore,bespike/litecoin,mruddy/bitcoin,ryanxcharles/bitcoin,wellenreiter01/Feathercoin,psionin/smartcoin,cryptoprojects/ultimateonlinecash,kallewoof/bitcoin,bitcoin/bitcoin,h4x3rotab/BTCGPU,domob1812/huntercore,zcoinofficial/zcoin,Michagogo/bitcoin,dgarage/bc3,nlgcoin/guldencoin-official,untrustbank/litecoin,Kogser/bitcoin,litecoin-project/litecoin,bitbrazilcoin-project/bitbrazilcoin,djpnewton/bitcoin,GroestlCoin/GroestlCoin,1185/starwels,haobtc/bitcoin,DigitalPandacoin/pandacoin,Anfauglith/iop-hd,MarcoFalke/bitcoin,mitchellcash/bitcoin,n1bor/bitcoin,mitchellcash/bitcoin,afk11/bitcoin,dpayne9000/Rubixz-Coin,simonmulser/bitcoin,pataquets/namecoin-core,sarielsaz/sarielsaz,isle2983/bitcoin,rnicoll/dogecoin,anditto/bitcoin,HashUnlimited/Einsteinium-Unlimited,mincoin-project/mincoin,Friedbaumer/litecoin,UFOCoins/ufo,Christewart/bitcoin,daliwangi/bitcoin,yenliangl/bitcoin,multicoins/marycoin,lbryio/lbrycrd,cculianu/bitcoin-abc,cculianu/bitcoin-abc,jambolo/bitcoin,lbryio/lbrycrd,jmcorgan/bitcoin,prusnak/bitcoin,Sjors/bitcoin,ryanofsky/bitcoin,awemany/BitcoinUnlimited,kazcw/bitcoin,Flowdalic/bitcoin,matlongsi/micropay,ftrader-bitcoinabc/bitcoin-abc,jimmysong/bitcoin,Bushstar/UFO-Project,BigBlueCeiling/augmentacoin,jnewbery/bitcoin,thrasher-/litecoin,MazaCoin/maza,Jcing95/iop-hd,droark/bitcoin,segsignal/bitcoin,mb300sd/bitcoin,MeshCollider/bitcoin,bespike/litecoin,tecnovert/particl-core,cryptoprojects/ultimateonlinecash,uphold/bitcoin,Flowdalic/bitcoin,afk11/bitcoin,ahmedbodi/temp_vert,plncoin/PLNcoin_Core,ppcoin/ppcoin,bitreserve/bitcoin,Bushstar/UFO-Project,jiangyonghang/bitcoin,namecoin/namecore,ajtowns/bitcoin,Kogser/bitcoin,174high/bitcoin,bitcoinknots/bitcoin,plncoin/PLNcoin_Core,simonmulser/bitcoin,vmp32k/litecoin,jlopp/statoshi,peercoin/peercoin,bitbrazilcoin-project/bitbrazilcoin,spiritlinxl/BTCGPU,Cocosoft/bitcoin,sstone/bitcoin,goldcoin/goldcoin,appop/bitcoin,namecoin/namecore,psionin/smartcoin,UASF/bitcoin,Sjors/bitcoin,simonmulser/bitcoin,dgarage/bc2,Michagogo/bitcoin,sstone/bitcoin,Theshadow4all/ShadowCoin,mb300sd/bitcoin,Bitcoin-ABC/bitcoin-abc,ahmedbodi/vertcoin,xieta/mincoin,Xekyo/bitcoin,jtimon/bitcoin,mitchellcash/bitcoin,instagibbs/bitcoin,ahmedbodi/temp_vert,rebroad/bitcoin,Bitcoin-ABC/bitcoin-abc,Xekyo/bitcoin,shouhuas/bitcoin,donaloconnor/bitcoin,destenson/bitcoin--bitcoin,tjps/bitcoin,RHavar/bitcoin,earonesty/bitcoin,digibyte/digibyte,Gazer022/bitcoin,bitbrazilcoin-project/bitbrazilcoin,maaku/bitcoin,guncoin/guncoin,goldcoin/goldcoin,joshrabinowitz/bitcoin,yenliangl/bitcoin,sarielsaz/sarielsaz,mitchellcash/bitcoin,Michagogo/bitcoin,wangxinxi/litecoin,starwels/starwels,vmp32k/litecoin,alecalve/bitcoin,Cocosoft/bitcoin,dcousens/bitcoin,randy-waterhouse/bitcoin,monacoinproject/monacoin,maaku/bitcoin,myriadcoin/myriadcoin,namecoin/namecore,BTCDDev/bitcoin,GlobalBoost/GlobalBoost,digibyte/digibyte,ixcoinofficialpage/master,CryptArc/bitcoin,romanornr/viacoin,haobtc/bitcoin,Mirobit/bitcoin,btc1/bitcoin,deeponion/deeponion,paveljanik/bitcoin,domob1812/bitcoin,CryptArc/bitcoin,Theshadow4all/ShadowCoin,fanquake/bitcoin,174high/bitcoin,Christewart/bitcoin,EntropyFactory/creativechain-core,myriadteam/myriadcoin,btc1/bitcoin,sipsorcery/bitcoin,BitcoinPOW/BitcoinPOW,Theshadow4all/ShadowCoin,rawodb/bitcoin,nikkitan/bitcoin,untrustbank/litecoin,sarielsaz/sarielsaz,AkioNak/bitcoin,deeponion/deeponion,alecalve/bitcoin,MeshCollider/bitcoin,RHavar/bitcoin,particl/particl-core,donaloconnor/bitcoin,cdecker/bitcoin,digibyte/digibyte,BitcoinPOW/BitcoinPOW,multicoins/marycoin,patricklodder/dogecoin,fanquake/bitcoin,jimmysong/bitcoin,joshrabinowitz/bitcoin,brandonrobertz/namecoin-core,pinheadmz/bitcoin,sebrandon1/bitcoin,sipsorcery/bitcoin,s-matthew-english/bitcoin,Flowdalic/bitcoin,x-kalux/bitcoin_WiG-B,pstratem/bitcoin,apoelstra/bitcoin,Chancoin-core/CHANCOIN,Jcing95/iop-hd,Chancoin-core/CHANCOIN,myriadcoin/myriadcoin,21E14/bitcoin,kevcooper/bitcoin,mincoin-project/mincoin,gzuser01/zetacoin-bitcoin,Jcing95/iop-hd,myriadteam/myriadcoin,ahmedbodi/vertcoin,mm-s/bitcoin,btc1/bitcoin,GroestlCoin/bitcoin,litecoin-project/litecoin,HashUnlimited/Einsteinium-Unlimited,BitcoinPOW/BitcoinPOW,patricklodder/dogecoin,Xekyo/bitcoin,namecoin/namecore,Cocosoft/bitcoin,andreaskern/bitcoin,BitcoinPOW/BitcoinPOW,thrasher-/litecoin,Mirobit/bitcoin,vertcoin/vertcoin,UFOCoins/ufo,ajtowns/bitcoin,anditto/bitcoin,practicalswift/bitcoin,lateminer/bitcoin,dcousens/bitcoin,Bitcoin-ABC/bitcoin-abc,monacoinproject/monacoin,UFOCoins/ufo,gmaxwell/bitcoin,cdecker/bitcoin,1185/starwels,achow101/bitcoin,rebroad/bitcoin,n1bor/bitcoin,h4x3rotab/BTCGPU,segsignal/bitcoin,jmcorgan/bitcoin,myriadcoin/myriadcoin,nlgcoin/guldencoin-official,BitcoinHardfork/bitcoin,n1bor/bitcoin,kallewoof/elements,appop/bitcoin,wangxinxi/litecoin,TheBlueMatt/bitcoin,cryptoprojects/ultimateonlinecash,bitcoinknots/bitcoin,apoelstra/bitcoin,sebrandon1/bitcoin,mm-s/bitcoin,instagibbs/bitcoin,Rav3nPL/PLNcoin,ryanofsky/bitcoin,RHavar/bitcoin,qtumproject/qtum,Anfauglith/iop-hd,bitcoinsSG/bitcoin,practicalswift/bitcoin,Friedbaumer/litecoin,starwels/starwels,bitbrazilcoin-project/bitbrazilcoin,vmp32k/litecoin,UFOCoins/ufo,Exgibichi/statusquo,isle2983/bitcoin,argentumproject/argentum,jambolo/bitcoin,BTCDDev/bitcoin,DigiByte-Team/digibyte,BTCGPU/BTCGPU,deeponion/deeponion,NicolasDorier/bitcoin,domob1812/namecore,lbryio/lbrycrd,maaku/bitcoin,fujicoin/fujicoin,practicalswift/bitcoin,XertroV/bitcoin-nulldata,multicoins/marycoin,jlopp/statoshi,bitcoinsSG/bitcoin,droark/bitcoin,DigitalPandacoin/pandacoin,appop/bitcoin,domob1812/namecore,vertcoin/vertcoin,nlgcoin/guldencoin-official,BitcoinHardfork/bitcoin,instagibbs/bitcoin,cdecker/bitcoin,jiangyonghang/bitcoin,dscotese/bitcoin,achow101/bitcoin,Chancoin-core/CHANCOIN,rawodb/bitcoin,jonasschnelli/bitcoin,sdaftuar/bitcoin,earonesty/bitcoin,CryptArc/bitcoin,CryptArc/bitcoin,h4x3rotab/BTCGPU,GroestlCoin/GroestlCoin,isle2983/bitcoin,Kogser/bitcoin,Mirobit/bitcoin,myriadteam/myriadcoin,DigiByte-Team/digibyte,zcoinofficial/zcoin,goldcoin/goldcoin,OmniLayer/omnicore,ahmedbodi/temp_vert,mb300sd/bitcoin,EthanHeilman/bitcoin,untrustbank/litecoin,RHavar/bitcoin,goldcoin/goldcoin,pstratem/bitcoin,nbenoit/bitcoin,core-bitcoin/bitcoin,dscotese/bitcoin,laudaa/bitcoin,GlobalBoost/GlobalBoost,AkioNak/bitcoin,Rav3nPL/PLNcoin,awemany/BitcoinUnlimited,dgarage/bc3,practicalswift/bitcoin,dogecoin/dogecoin,sstone/bitcoin,fanquake/bitcoin,pstratem/bitcoin,core-bitcoin/bitcoin,ahmedbodi/vertcoin,EthanHeilman/bitcoin,MeshCollider/bitcoin,djpnewton/bitcoin,xieta/mincoin,BitzenyCoreDevelopers/bitzeny,BitcoinPOW/BitcoinPOW,goldcoin/Goldcoin-GLD,GroestlCoin/bitcoin,ShadowMyst/creativechain-core,r8921039/bitcoin,DigiByte-Team/digibyte,ericshawlinux/bitcoin,sdaftuar/bitcoin,aspanta/bitcoin,pataquets/namecoin-core,svost/bitcoin,destenson/bitcoin--bitcoin,lbryio/lbrycrd,fanquake/bitcoin,viacoin/viacoin,practicalswift/bitcoin,jimmysong/bitcoin,shouhuas/bitcoin,vmp32k/litecoin,trippysalmon/bitcoin,sbaks0820/bitcoin,mm-s/bitcoin,ftrader-bitcoinabc/bitcoin-abc,segsignal/bitcoin,core-bitcoin/bitcoin,sebrandon1/bitcoin,djpnewton/bitcoin,psionin/smartcoin,jamesob/bitcoin,UASF/bitcoin,BitzenyCoreDevelopers/bitzeny,UASF/bitcoin,core-bitcoin/bitcoin,simonmulser/bitcoin,randy-waterhouse/bitcoin,elecoin/elecoin,GroestlCoin/GroestlCoin,wellenreiter01/Feathercoin,spiritlinxl/BTCGPU,BigBlueCeiling/augmentacoin,XertroV/bitcoin-nulldata,kallewoof/bitcoin,globaltoken/globaltoken,21E14/bitcoin,kevcooper/bitcoin,xieta/mincoin,bitreserve/bitcoin,wiggi/huntercore,mitchellcash/bitcoin,ElementsProject/elements,midnightmagic/bitcoin,x-kalux/bitcoin_WiG-B,Theshadow4all/ShadowCoin,21E14/bitcoin,Bitcoin-ABC/bitcoin-abc,Rav3nPL/PLNcoin,wiggi/huntercore,patricklodder/dogecoin,BitcoinHardfork/bitcoin,sdaftuar/bitcoin,daliwangi/bitcoin,vertcoin/vertcoin,argentumproject/argentum,yenliangl/bitcoin,ElementsProject/elements,Kogser/bitcoin,MazaCoin/maza,ftrader-bitcoinabc/bitcoin-abc,rebroad/bitcoin,untrustbank/litecoin,shouhuas/bitcoin,1185/starwels,djpnewton/bitcoin,pataquets/namecoin-core,Bushstar/UFO-Project,daliwangi/bitcoin,Kogser/bitcoin,ElementsProject/elements,dgarage/bc3,MarcoFalke/bitcoin,starwels/starwels,haobtc/bitcoin,BTCGPU/BTCGPU,destenson/bitcoin--bitcoin,namecoin/namecoin-core,tecnovert/particl-core,NicolasDorier/bitcoin,Jcing95/iop-hd,Gazer022/bitcoin,zcoinofficial/zcoin,ericshawlinux/bitcoin,ShadowMyst/creativechain-core,bespike/litecoin,jmcorgan/bitcoin,fsb4000/bitcoin,peercoin/peercoin,randy-waterhouse/bitcoin,goldcoin/Goldcoin-GLD,bitcoinknots/bitcoin,qtumproject/qtum,untrustbank/litecoin,andreaskern/bitcoin,jlopp/statoshi,GlobalBoost/GlobalBoost,Cocosoft/bitcoin,XertroV/bitcoin-nulldata,tdudz/elements,StarbuckBG/BTCGPU,domob1812/namecore,anditto/bitcoin,apoelstra/bitcoin,MazaCoin/maza,s-matthew-english/bitcoin,21E14/bitcoin,nlgcoin/guldencoin-official,MarcoFalke/bitcoin,jamesob/bitcoin,starwels/starwels,BTCDDev/bitcoin,plncoin/PLNcoin_Core,sstone/bitcoin,jlopp/statoshi,awemany/BitcoinUnlimited,gjhiggins/vcoincore,domob1812/bitcoin,NicolasDorier/bitcoin,goldcoin/Goldcoin-GLD,destenson/bitcoin--bitcoin,anditto/bitcoin,donaloconnor/bitcoin,ajtowns/bitcoin,randy-waterhouse/bitcoin,MazaCoin/maza,particl/particl-core,GlobalBoost/GlobalBoost,djpnewton/bitcoin,gjhiggins/vcoincore,wellenreiter01/Feathercoin,domob1812/huntercore,EntropyFactory/creativechain-core,DigiByte-Team/digibyte,Rav3nPL/PLNcoin,Bitcoin-ABC/bitcoin-abc,fujicoin/fujicoin,tjps/bitcoin,tdudz/elements,afk11/bitcoin,ftrader-bitcoinabc/bitcoin-abc,cdecker/bitcoin,fanquake/bitcoin,ahmedbodi/vertcoin,elecoin/elecoin,paveljanik/bitcoin,zcoinofficial/zcoin,stamhe/bitcoin,JeremyRubin/bitcoin,monacoinproject/monacoin,Rav3nPL/bitcoin,x-kalux/bitcoin_WiG-B,Exgibichi/statusquo,Kogser/bitcoin,spiritlinxl/BTCGPU,guncoin/guncoin,Anfauglith/iop-hd,midnightmagic/bitcoin,MazaCoin/maza,aspanta/bitcoin,bespike/litecoin,ShadowMyst/creativechain-core,Friedbaumer/litecoin,TheBlueMatt/bitcoin,rnicoll/bitcoin,destenson/bitcoin--bitcoin,TheBlueMatt/bitcoin,nikkitan/bitcoin,rebroad/bitcoin,dcousens/bitcoin,shelvenzhou/BTCGPU,ryanxcharles/bitcoin,kallewoof/elements,ppcoin/ppcoin,nikkitan/bitcoin,Anfauglith/iop-hd,tjps/bitcoin,kallewoof/bitcoin,paveljanik/bitcoin,h4x3rotab/BTCGPU,rawodb/bitcoin,domob1812/bitcoin,nomnombtc/bitcoin,bitcoinknots/bitcoin,bitcoinec/bitcoinec,AdrianaDinca/bitcoin,pstratem/bitcoin,rnicoll/dogecoin,pataquets/namecoin-core,droark/bitcoin,cryptoprojects/ultimateonlinecash,DigitalPandacoin/pandacoin,globaltoken/globaltoken,nomnombtc/bitcoin,tdudz/elements,BTCGPU/BTCGPU,UASF/bitcoin,nikkitan/bitcoin,Michagogo/bitcoin,midnightmagic/bitcoin,brandonrobertz/namecoin-core,earonesty/bitcoin,vertcoin/vertcoin,senadmd/coinmarketwatch,shelvenzhou/BTCGPU,btc1/bitcoin,litecoin-project/litecoin,mruddy/bitcoin,domob1812/huntercore,svost/bitcoin,apoelstra/bitcoin,myriadteam/myriadcoin,jimmysong/bitcoin,appop/bitcoin,174high/bitcoin,AdrianaDinca/bitcoin,pinheadmz/bitcoin,ajtowns/bitcoin,deeponion/deeponion,DigiByte-Team/digibyte,lateminer/bitcoin,stamhe/bitcoin,earonesty/bitcoin,AdrianaDinca/bitcoin,monacoinproject/monacoin,apoelstra/bitcoin,GroestlCoin/GroestlCoin,Bitcoin-ABC/bitcoin-abc,aspanta/bitcoin,midnightmagic/bitcoin,prusnak/bitcoin,sbaks0820/bitcoin,nomnombtc/bitcoin,appop/bitcoin,svost/bitcoin,RHavar/bitcoin,goldcoin/Goldcoin-GLD,matlongsi/micropay,deeponion/deeponion,gzuser01/zetacoin-bitcoin,brandonrobertz/namecoin-core,Friedbaumer/litecoin,matlongsi/micropay,domob1812/huntercore,ixcoinofficialpage/master,kallewoof/bitcoin,monacoinproject/monacoin,droark/bitcoin,TheBlueMatt/bitcoin,r8921039/bitcoin,simonmulser/bitcoin,nomnombtc/bitcoin,1185/starwels,jnewbery/bitcoin,uphold/bitcoin,domob1812/namecore,kazcw/bitcoin,TheBlueMatt/bitcoin,ppcoin/ppcoin,domob1812/bitcoin,pataquets/namecoin-core,digibyte/digibyte,globaltoken/globaltoken,GroestlCoin/GroestlCoin,tjps/bitcoin,romanornr/viacoin,dogecoin/dogecoin,AdrianaDinca/bitcoin,1185/starwels,vmp32k/litecoin,MazaCoin/maza,174high/bitcoin,myriadcoin/myriadcoin,cculianu/bitcoin-abc,domob1812/huntercore,ryanxcharles/bitcoin,goldcoin/Goldcoin-GLD,afk11/bitcoin,BTCGPU/BTCGPU,shelvenzhou/BTCGPU,Bushstar/UFO-Project,GroestlCoin/GroestlCoin,trippysalmon/bitcoin,nbenoit/bitcoin,mincoin-project/mincoin,stamhe/bitcoin,namecoin/namecoin-core,patricklodder/dogecoin,bitcoinec/bitcoinec,donaloconnor/bitcoin,kazcw/bitcoin,elecoin/elecoin,jmcorgan/bitcoin,brandonrobertz/namecoin-core,pataquets/namecoin-core,midnightmagic/bitcoin,ahmedbodi/temp_vert,ixcoinofficialpage/master,Xekyo/bitcoin,jambolo/bitcoin,sdaftuar/bitcoin,tecnovert/particl-core,segsignal/bitcoin,viacoin/viacoin,cryptoprojects/ultimateonlinecash,GroestlCoin/bitcoin,nomnombtc/bitcoin,mruddy/bitcoin,sbaks0820/bitcoin,chaincoin/chaincoin,mincoin-project/mincoin,afk11/bitcoin,aspanta/bitcoin,laudaa/bitcoin,shouhuas/bitcoin,namecoin/namecoin-core,ryanofsky/bitcoin,rnicoll/dogecoin,gmaxwell/bitcoin,Xekyo/bitcoin,mm-s/bitcoin,ryanofsky/bitcoin,qtumproject/qtum,sstone/bitcoin,rnicoll/dogecoin,wangxinxi/litecoin,s-matthew-english/bitcoin,EntropyFactory/creativechain-core,viacoin/viacoin,jtimon/bitcoin,isle2983/bitcoin,jtimon/bitcoin,daliwangi/bitcoin,n1bor/bitcoin,Sjors/bitcoin,joshrabinowitz/bitcoin,BitzenyCoreDevelopers/bitzeny,fsb4000/bitcoin,jonasschnelli/bitcoin,sipsorcery/bitcoin,Bitcoin-ABC/bitcoin-abc,joshrabinowitz/bitcoin,nlgcoin/guldencoin-official,nbenoit/bitcoin,svost/bitcoin,sdaftuar/bitcoin,BTCDDev/bitcoin,Exgibichi/statusquo,OmniLayer/omnicore,bitcoinsSG/bitcoin,sebrandon1/bitcoin,ahmedbodi/temp_vert,Michagogo/bitcoin,sstone/bitcoin,alecalve/bitcoin,mm-s/bitcoin,mb300sd/bitcoin,dscotese/bitcoin,daliwangi/bitcoin,gzuser01/zetacoin-bitcoin,Rav3nPL/bitcoin,jamesob/bitcoin,earonesty/bitcoin,DigitalPandacoin/pandacoin,namecoin/namecore,BitzenyCoreDevelopers/bitzeny,bitcoinknots/bitcoin,earonesty/bitcoin,pinheadmz/bitcoin,Sjors/bitcoin,jlopp/statoshi,Chancoin-core/CHANCOIN,dogecoin/dogecoin,Kogser/bitcoin,dgarage/bc2,GroestlCoin/bitcoin,jamesob/bitcoin,BTCDDev/bitcoin,wellenreiter01/Feathercoin,Christewart/bitcoin,sarielsaz/sarielsaz,nikkitan/bitcoin,dpayne9000/Rubixz-Coin,jamesob/bitcoin,kallewoof/elements,gzuser01/zetacoin-bitcoin,jiangyonghang/bitcoin,FeatherCoin/Feathercoin,dcousens/bitcoin,Bitcoin-ABC/bitcoin-abc,namecoin/namecoin-core,namecoin/namecoin-core,MeshCollider/bitcoin,lbryio/lbrycrd,tdudz/elements,HashUnlimited/Einsteinium-Unlimited,Exgibichi/statusquo,bitcoinsSG/bitcoin,h4x3rotab/BTCGPU,domob1812/huntercore,FeatherCoin/Feathercoin,particl/particl-core,kevcooper/bitcoin,JeremyRubin/bitcoin,lateminer/bitcoin,rebroad/bitcoin,vertcoin/vertcoin,Rav3nPL/bitcoin,djpnewton/bitcoin,appop/bitcoin,r8921039/bitcoin,fanquake/bitcoin,kazcw/bitcoin,jtimon/bitcoin,guncoin/guncoin,gjhiggins/vcoincore,elecoin/elecoin,TheBlueMatt/bitcoin,Exgibichi/statusquo,bitcoinec/bitcoinec,Gazer022/bitcoin,uphold/bitcoin,gmaxwell/bitcoin,bespike/litecoin,dpayne9000/Rubixz-Coin,jimmysong/bitcoin,matlongsi/micropay,pstratem/bitcoin,jimmysong/bitcoin,dgarage/bc3,wangxinxi/litecoin,mincoin-project/mincoin,dogecoin/dogecoin,spiritlinxl/BTCGPU,dpayne9000/Rubixz-Coin,cdecker/bitcoin,rebroad/bitcoin,FeatherCoin/Feathercoin,rnicoll/bitcoin,ajtowns/bitcoin,XertroV/bitcoin-nulldata,Anfauglith/iop-hd,Exgibichi/statusquo,21E14/bitcoin,instagibbs/bitcoin,AdrianaDinca/bitcoin,awemany/BitcoinUnlimited,1185/starwels,UASF/bitcoin,isle2983/bitcoin,romanornr/viacoin,tdudz/elements,Chancoin-core/CHANCOIN,ahmedbodi/temp_vert,mincoin-project/mincoin,sipsorcery/bitcoin,bitcoinsSG/bitcoin,ryanofsky/bitcoin,x-kalux/bitcoin_WiG-B,prusnak/bitcoin,UASF/bitcoin,chaincoin/chaincoin,kallewoof/elements,dscotese/bitcoin,Flowdalic/bitcoin,BigBlueCeiling/augmentacoin,jmcorgan/bitcoin,myriadcoin/myriadcoin,paveljanik/bitcoin,donaloconnor/bitcoin,EthanHeilman/bitcoin,cdecker/bitcoin,senadmd/coinmarketwatch,xieta/mincoin,ShadowMyst/creativechain-core,sbaks0820/bitcoin,bitreserve/bitcoin,tdudz/elements,droark/bitcoin,maaku/bitcoin,EthanHeilman/bitcoin,DigiByte-Team/digibyte,kallewoof/elements,viacoin/viacoin,plncoin/PLNcoin_Core,goldcoin/goldcoin,deeponion/deeponion,fsb4000/bitcoin,cryptoprojects/ultimateonlinecash,DigitalPandacoin/pandacoin,kevcooper/bitcoin,ryanxcharles/bitcoin,Mirobit/bitcoin,andreaskern/bitcoin,jmcorgan/bitcoin,anditto/bitcoin,lateminer/bitcoin,afk11/bitcoin,thrasher-/litecoin,uphold/bitcoin,rawodb/bitcoin,OmniLayer/omnicore,achow101/bitcoin,pinheadmz/bitcoin,bespike/litecoin,HashUnlimited/Einsteinium-Unlimited,cculianu/bitcoin-abc,aspanta/bitcoin,gmaxwell/bitcoin,alecalve/bitcoin,prusnak/bitcoin,donaloconnor/bitcoin,bitcoin/bitcoin,nlgcoin/guldencoin-official,kevcooper/bitcoin,rawodb/bitcoin,MarcoFalke/bitcoin,untrustbank/litecoin,EntropyFactory/creativechain-core,UFOCoins/ufo,haobtc/bitcoin,dgarage/bc2,BitcoinHardfork/bitcoin,BTCGPU/BTCGPU,bitcoinec/bitcoinec,yenliangl/bitcoin,vertcoin/vertcoin,bitcoinec/bitcoinec,nbenoit/bitcoin,daliwangi/bitcoin,chaincoin/chaincoin,dgarage/bc2,JeremyRubin/bitcoin,EntropyFactory/creativechain-core,HashUnlimited/Einsteinium-Unlimited,UFOCoins/ufo,sbaks0820/bitcoin,mb300sd/bitcoin,particl/particl-core,btc1/bitcoin,XertroV/bitcoin-nulldata,mruddy/bitcoin,lbryio/lbrycrd |
ee167908fffc899bb5bdb40f2f3694e07e101614 | downloadplugin.cpp | downloadplugin.cpp | #include "downloadplugin.h"
#include <QDebug>
#include <QFile>
#include <QUuid>
#include <QFileInfo>
#include <QTimer>
#include <QDesktopServices>
#include "json.h"
using QtJson::JsonObject;
using QtJson::JsonArray;
DownloadPlugin::DownloadPlugin(QObject * parent)
: DownloadInterface (parent)
{
}
Q_EXPORT_PLUGIN2(DownloadPlugin, DownloadPlugin)
DownloadPlugin::~DownloadPlugin()
{
}
QString DownloadPlugin::name(void) const
{
return "DownloadPlugin";
}
QString DownloadPlugin::version() const
{
return "1.0";
}
void DownloadPlugin::setDefaultParameters()
{
m_existPolicy = DownloadInterface::ExistThenOverwrite;
m_partialPolicy = DownloadInterface::PartialThenContinue;
m_userAgent = "DownloadPlugin/0.0.2";
m_bandwidthLimit = 30*1024;
m_queueSize = 2;
m_filePath = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
void DownloadPlugin::append(const QString &_url)
{
QUrl url = QUrl::fromEncoded(_url.toLocal8Bit());
bool fileExist = false;
bool tempExist = false;
QString fileName = "";
QString filePath = saveFilename(url, fileExist, fileName, tempExist);
if (fileExist && m_existPolicy == DownloadInterface::ExistThenCancel) {
qDebug() << fileName << "exist. Cancel download";
emit status(_url, "Cancel", "File already exist", filePath);
return;
}
DownloadItem item;
item.url = _url;
item.key = fileName;
item.path = filePath;
item.temp = filePath + ".part";
item.tempExist = tempExist;
if (downloadQueue.isEmpty())
QTimer::singleShot(0, this, SLOT(startNextDownload()));
downloadQueue.enqueue(item);
}
void DownloadPlugin::append(const QStringList &urlList)
{
foreach (QString url, urlList){
append(url);
}
if (downloadQueue.isEmpty())
QTimer::singleShot(0, this, SIGNAL(finished()));
}
void DownloadPlugin::pause(const QString &url)
{
stopDownload(url, true);
}
void DownloadPlugin::pause(const QStringList &urlList)
{
foreach (QString url, urlList){
pause(url);
}
}
void DownloadPlugin::resume(const QString &url)
{
append(url);
}
void DownloadPlugin::resume(const QStringList & urlList)
{
foreach (QString url, urlList){
resume(url);
}
}
void DownloadPlugin::stop(const QString &url)
{
stopDownload(url, false);
}
void DownloadPlugin::stop(const QStringList &urlList)
{
foreach (QString url, urlList){
stop(url);
}
}
void DownloadPlugin::stopDownload(const QString &url, bool pause)
{
QNetworkReply *reply = urlHash[url];
disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgress(qint64,qint64)));
disconnect(reply, SIGNAL(finished()),
this, SLOT(downloadFinished()));
disconnect(reply, SIGNAL(readyRead()),
this, SLOT(downloadReadyRead()));
disconnect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(downloadError(QNetworkReply::NetworkError)));
disconnect(reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(downloadSslErrors(QList<QSslError>)));
DownloadItem item = downloadHash[reply];
reply->abort();
item.file->write( reply->readAll());
item.file->close();
if (!pause)
QFile::remove(item.temp);
downloadHash.remove(reply);
urlHash.remove(url);
if (pause)
downloadQueue.enqueue(item);
startNextDownload();
reply->deleteLater();
}
void DownloadPlugin::startNextDownload()
{
if (downloadQueue.isEmpty()) {
emit finishedAll();
return;
}
if (downloadHash.size() < m_queueSize)
{
DownloadItem item = downloadQueue.dequeue();
QNetworkRequest request(item.url);
request.setRawHeader("User-Agent", m_userAgent);
if (item.tempExist && m_partialPolicy == DownloadInterface::PartialThenContinue) {
item.file = new QFile(item.temp);
if (!item.file->open(QIODevice::ReadWrite)) {
qDebug() << "Download error" << item.file->errorString();
emit status(item.url, "Error", item.file->errorString(), item.path);
startNextDownload();
return;
}
item.file->seek(item.file->size());
item.tempSize = item.file->size();
QByteArray rangeHeaderValue = "bytes=" + QByteArray::number(item.tempSize) + "-";
request.setRawHeader("Range",rangeHeaderValue);
}
else {
if (item.tempExist) {
QFile::remove(item.temp);
}
item.file = new QFile(item.temp);
if (!item.file->open(QIODevice::ReadWrite)) {
qDebug() << "Download error" << item.file->errorString();
emit status(item.url, "Error", item.file->errorString(), item.path);
startNextDownload();
return;
}
item.tempSize = 0;
}
QNetworkReply *reply = manager.get(request);
connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgress(qint64,qint64)));
connect(reply, SIGNAL(finished()),
this, SLOT(downloadFinished()));
connect(reply, SIGNAL(readyRead()),
this, SLOT(downloadReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(downloadError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(downloadSslErrors(QList<QSslError>)));
qDebug() << "startNextDownload" << item.url << item.temp;
emit status(item.url, "Download", "Start downloading file", item.url);
item.time.start();
downloadHash[reply] = item;
urlHash[item.url] = reply;
startNextDownload();
}
}
void DownloadPlugin::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
qint64 actualReceived = item.tempSize + bytesReceived;
qint64 actualTotal = item.tempSize + bytesTotal;
double speed = actualReceived * 1000.0 / item.time.elapsed();
QString unit;
if (speed < 1024) {
unit = "bytes/sec";
} else if (speed < 1024*1024) {
speed /= 1024;
unit = "kB/s";
} else {
speed /= 1024*1024;
unit = "MB/s";
}
int percent = actualReceived * 100 / actualTotal;
//qDebug() << "downloadProgress" << item.url << bytesReceived << bytesTotal << percent << speed << unit;
emit progress(item.url, actualReceived, actualTotal, percent, speed, unit);
}
void DownloadPlugin::downloadReadyRead()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
item.file->write(reply->readAll());
}
void DownloadPlugin::downloadFinished()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
item.file->close();
item.file->deleteLater();
if (reply->error() == QNetworkReply::NoError) {
if (QFile::exists(item.path))
QFile::remove(item.path);
QFile::rename(item.temp, item.path);
completedList.append(item);
qDebug() << "downloadFinished" << item.url << item.path;
emit status(item.url, "Complete", "Download file completed", item.url);
emit finished(item.url, item.path);
}
downloadHash.remove(reply);
urlHash.remove(item.url);
startNextDownload();
reply->deleteLater();
}
void DownloadPlugin::downloadError(QNetworkReply::NetworkError)
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
qDebug() << "downloadError: " << item.url << reply->errorString();
emit status(item.url, "Error", reply->errorString(), item.url);
emit progress(item.url, 0, 0, 0, 0, "bytes/sec");
}
void DownloadPlugin::downloadSslErrors(QList<QSslError>)
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
reply->ignoreSslErrors();
}
void DownloadPlugin::setBandwidthLimit(int size)
{
}
void DownloadPlugin::addSocket(QIODevice *socket)
{
}
void DownloadPlugin::removeSocket(QIODevice *socket)
{
}
void DownloadPlugin::transfer()
{
}
void DownloadPlugin::scheduleTransfer()
{
}
QString DownloadPlugin::saveFilename(const QUrl &url, bool &exist, QString &fileName, bool &tempExist)
{
QString path = url.path();
QFileInfo fi = QFileInfo(path);
QString basename = fi.baseName();
QString suffix = fi.completeSuffix();
if (basename.isEmpty())
basename = QUuid::createUuid();
QString filePath = m_filePath + "/" + basename + "." + suffix;
// check if complete file exist
if (QFile::exists(filePath))
{
exist = true;
if (m_existPolicy == DownloadInterface::ExistThenRename) {
qDebug() << "File" << filePath << "exist. Rename";
int i = 0;
basename += '(';
while (QFile::exists(m_filePath + "/" + basename + "(" + QString::number(i) + ")" + suffix))
++i;
basename += QString::number(i) + ")";
filePath = m_filePath + "/" + basename + "." + suffix;
}
else if (m_existPolicy == DownloadInterface::ExistThenOverwrite) {
qDebug() << "File" << filePath << "exist. Overwrite";
}
}
// check if part file exist
QString filePart = filePath + ".part";
if (QFile::exists(filePart))
{
tempExist = true;
}
fileName = basename + "." + suffix;
return filePath;
}
QString DownloadPlugin::getStatus() const
{
QtJson::JsonArray queueList;
for (int i = 0; i < downloadQueue.size(); i++) {
DownloadItem item = downloadQueue.at(i);
QtJson::JsonObject queueItem;
queueItem["key"] = item.key;
queueItem["url"] = item.url;
queueItem["path"] = item.path;
queueItem["temp"] = item.temp;
queueList.append(queueItem);
}
QtJson::JsonArray downloadingList;
QHashIterator<QNetworkReply*, DownloadItem> i(downloadHash);
while (i.hasNext()) {
i.next();
DownloadItem item = i.value();
QtJson::JsonObject downloadingItem;
downloadingItem["key"] = item.key;
downloadingItem["url"] = item.url;
downloadingItem["path"] = item.path;
downloadingItem["temp"] = item.temp;
downloadingList.append(downloadingItem);
}
QtJson::JsonArray completeList;
for (int i = 0; i < completedList.size(); i++) {
DownloadItem item = completedList.at(i);
QtJson::JsonObject completeItem;
completeItem["key"] = item.key;
completeItem["url"] = item.url;
completeItem["path"] = item.path;
completeItem["temp"] = item.temp;
completeList.append(completeItem);
}
QtJson::JsonObject obj;
obj["queue"] = queueList;
obj["queueSize"] = queueList.size();
obj["active"] = downloadingList;
obj["activeSize"] = downloadingList.size();
obj["complete"] = completeList;
obj["completeSize"] = completeList.size();
QByteArray data = QtJson::serialize(obj);
return QString::fromUtf8(data);
}
| #include "downloadplugin.h"
#include <QDebug>
#include <QFile>
#include <QUuid>
#include <QFileInfo>
#include <QTimer>
#include <QDesktopServices>
#include "json.h"
using QtJson::JsonObject;
using QtJson::JsonArray;
DownloadPlugin::DownloadPlugin(QObject * parent)
: DownloadInterface (parent)
{
}
Q_EXPORT_PLUGIN2(DownloadPlugin, DownloadPlugin)
DownloadPlugin::~DownloadPlugin()
{
}
QString DownloadPlugin::name() const
{
return "DownloadPlugin";
}
QString DownloadPlugin::version() const
{
return "1.0";
}
void DownloadPlugin::setDefaultParameters()
{
m_existPolicy = DownloadInterface::ExistThenOverwrite;
m_partialPolicy = DownloadInterface::PartialThenContinue;
m_userAgent = "DownloadPlugin/0.0.2";
m_bandwidthLimit = 30*1024;
m_queueSize = 2;
m_filePath = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
void DownloadPlugin::append(const QString &_url)
{
QUrl url = QUrl::fromEncoded(_url.toLocal8Bit());
bool fileExist = false;
bool tempExist = false;
QString fileName = "";
QString filePath = saveFilename(url, fileExist, fileName, tempExist);
if (fileExist && m_existPolicy == DownloadInterface::ExistThenCancel) {
qDebug() << fileName << "exist. Cancel download";
emit status(_url, "Cancel", "File already exist", filePath);
return;
}
DownloadItem item;
item.url = _url;
item.key = fileName;
item.path = filePath;
item.temp = filePath + ".part";
item.tempExist = tempExist;
if (downloadQueue.isEmpty())
QTimer::singleShot(0, this, SLOT(startNextDownload()));
downloadQueue.enqueue(item);
}
void DownloadPlugin::append(const QStringList &urlList)
{
foreach (QString url, urlList){
append(url);
}
if (downloadQueue.isEmpty())
QTimer::singleShot(0, this, SIGNAL(finished()));
}
void DownloadPlugin::pause(const QString &url)
{
stopDownload(url, true);
}
void DownloadPlugin::pause(const QStringList &urlList)
{
foreach (QString url, urlList){
pause(url);
}
}
void DownloadPlugin::resume(const QString &url)
{
append(url);
}
void DownloadPlugin::resume(const QStringList & urlList)
{
foreach (QString url, urlList){
resume(url);
}
}
void DownloadPlugin::stop(const QString &url)
{
stopDownload(url, false);
}
void DownloadPlugin::stop(const QStringList &urlList)
{
foreach (QString url, urlList){
stop(url);
}
}
void DownloadPlugin::stopDownload(const QString &url, bool pause)
{
QNetworkReply *reply = urlHash[url];
disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgress(qint64,qint64)));
disconnect(reply, SIGNAL(finished()),
this, SLOT(downloadFinished()));
disconnect(reply, SIGNAL(readyRead()),
this, SLOT(downloadReadyRead()));
disconnect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(downloadError(QNetworkReply::NetworkError)));
disconnect(reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(downloadSslErrors(QList<QSslError>)));
DownloadItem item = downloadHash[reply];
reply->abort();
item.file->write( reply->readAll());
item.file->close();
if (!pause)
QFile::remove(item.temp);
downloadHash.remove(reply);
urlHash.remove(url);
if (pause)
downloadQueue.enqueue(item);
startNextDownload();
reply->deleteLater();
}
void DownloadPlugin::startNextDownload()
{
if (downloadQueue.isEmpty()) {
emit finishedAll();
return;
}
if (downloadHash.size() < m_queueSize)
{
DownloadItem item = downloadQueue.dequeue();
QNetworkRequest request(item.url);
request.setRawHeader("User-Agent", m_userAgent);
if (item.tempExist && m_partialPolicy == DownloadInterface::PartialThenContinue) {
item.file = new QFile(item.temp);
if (!item.file->open(QIODevice::ReadWrite)) {
qDebug() << "Download error" << item.file->errorString();
emit status(item.url, "Error", item.file->errorString(), item.path);
startNextDownload();
return;
}
item.file->seek(item.file->size());
item.tempSize = item.file->size();
QByteArray rangeHeaderValue = "bytes=" + QByteArray::number(item.tempSize) + "-";
request.setRawHeader("Range",rangeHeaderValue);
}
else {
if (item.tempExist) {
QFile::remove(item.temp);
}
item.file = new QFile(item.temp);
if (!item.file->open(QIODevice::ReadWrite)) {
qDebug() << "Download error" << item.file->errorString();
emit status(item.url, "Error", item.file->errorString(), item.path);
startNextDownload();
return;
}
item.tempSize = 0;
}
QNetworkReply *reply = manager.get(request);
connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgress(qint64,qint64)));
connect(reply, SIGNAL(finished()),
this, SLOT(downloadFinished()));
connect(reply, SIGNAL(readyRead()),
this, SLOT(downloadReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(downloadError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(downloadSslErrors(QList<QSslError>)));
qDebug() << "startNextDownload" << item.url << item.temp;
emit status(item.url, "Download", "Start downloading file", item.url);
item.time.start();
downloadHash[reply] = item;
urlHash[item.url] = reply;
startNextDownload();
}
}
void DownloadPlugin::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
qint64 actualReceived = item.tempSize + bytesReceived;
qint64 actualTotal = item.tempSize + bytesTotal;
double speed = actualReceived * 1000.0 / item.time.elapsed();
QString unit;
if (speed < 1024) {
unit = "bytes/sec";
} else if (speed < 1024*1024) {
speed /= 1024;
unit = "kB/s";
} else {
speed /= 1024*1024;
unit = "MB/s";
}
int percent = actualReceived * 100 / actualTotal;
//qDebug() << "downloadProgress" << item.url << bytesReceived << bytesTotal << percent << speed << unit;
emit progress(item.url, actualReceived, actualTotal, percent, speed, unit);
}
void DownloadPlugin::downloadReadyRead()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
item.file->write(reply->readAll());
}
void DownloadPlugin::downloadFinished()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
item.file->close();
item.file->deleteLater();
if (reply->error() == QNetworkReply::NoError) {
if (QFile::exists(item.path))
QFile::remove(item.path);
QFile::rename(item.temp, item.path);
completedList.append(item);
qDebug() << "downloadFinished" << item.url << item.path;
emit status(item.url, "Complete", "Download file completed", item.url);
emit finished(item.url, item.path);
}
downloadHash.remove(reply);
urlHash.remove(item.url);
startNextDownload();
reply->deleteLater();
}
void DownloadPlugin::downloadError(QNetworkReply::NetworkError)
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
DownloadItem item = downloadHash[reply];
qDebug() << "downloadError: " << item.url << reply->errorString();
emit status(item.url, "Error", reply->errorString(), item.url);
emit progress(item.url, 0, 0, 0, 0, "bytes/sec");
}
void DownloadPlugin::downloadSslErrors(QList<QSslError>)
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
reply->ignoreSslErrors();
}
void DownloadPlugin::setBandwidthLimit(int size)
{
}
void DownloadPlugin::addSocket(QIODevice *socket)
{
}
void DownloadPlugin::removeSocket(QIODevice *socket)
{
}
void DownloadPlugin::transfer()
{
}
void DownloadPlugin::scheduleTransfer()
{
}
QString DownloadPlugin::saveFilename(const QUrl &url, bool &exist, QString &fileName, bool &tempExist)
{
QString path = url.path();
QFileInfo fi = QFileInfo(path);
QString basename = fi.baseName();
QString suffix = fi.completeSuffix();
if (basename.isEmpty())
basename = QUuid::createUuid();
QString filePath = m_filePath + "/" + basename + "." + suffix;
// check if complete file exist
if (QFile::exists(filePath))
{
exist = true;
if (m_existPolicy == DownloadInterface::ExistThenRename) {
qDebug() << "File" << filePath << "exist. Rename";
int i = 0;
basename += '(';
while (QFile::exists(m_filePath + "/" + basename + "(" + QString::number(i) + ")" + suffix))
++i;
basename += QString::number(i) + ")";
filePath = m_filePath + "/" + basename + "." + suffix;
}
else if (m_existPolicy == DownloadInterface::ExistThenOverwrite) {
qDebug() << "File" << filePath << "exist. Overwrite";
QFile::remove(filePath);
}
}
// check if part file exist
QString filePart = filePath + ".part";
if (QFile::exists(filePart))
{
tempExist = true;
}
fileName = basename + "." + suffix;
return filePath;
}
QString DownloadPlugin::getStatus() const
{
QtJson::JsonArray queueList;
for (int i = 0; i < downloadQueue.size(); i++) {
DownloadItem item = downloadQueue.at(i);
QtJson::JsonObject queueItem;
queueItem["key"] = item.key;
queueItem["url"] = item.url;
queueItem["path"] = item.path;
queueItem["temp"] = item.temp;
queueList.append(queueItem);
}
QtJson::JsonArray downloadingList;
QHashIterator<QNetworkReply*, DownloadItem> i(downloadHash);
while (i.hasNext()) {
i.next();
DownloadItem item = i.value();
QtJson::JsonObject downloadingItem;
downloadingItem["key"] = item.key;
downloadingItem["url"] = item.url;
downloadingItem["path"] = item.path;
downloadingItem["temp"] = item.temp;
downloadingList.append(downloadingItem);
}
QtJson::JsonArray completeList;
for (int i = 0; i < completedList.size(); i++) {
DownloadItem item = completedList.at(i);
QtJson::JsonObject completeItem;
completeItem["key"] = item.key;
completeItem["url"] = item.url;
completeItem["path"] = item.path;
completeItem["temp"] = item.temp;
completeList.append(completeItem);
}
QtJson::JsonObject obj;
obj["queue"] = queueList;
obj["queueSize"] = queueList.size();
obj["active"] = downloadingList;
obj["activeSize"] = downloadingList.size();
obj["complete"] = completeList;
obj["completeSize"] = completeList.size();
QByteArray data = QtJson::serialize(obj);
return QString::fromUtf8(data);
}
| delete file if exists when ExistThenOverwrite | delete file if exists when ExistThenOverwrite
| C++ | mit | arifsetiawan/qt-download-plugin |
fb3929079f10ed28e90ee8b74e77d695b493129e | echo_srv/server.cc | echo_srv/server.cc | #include "server.hh"
WebSock_Server::WebSock_Server(string ip, int port, int max){
clients = new client_info[max];
max_ = max;
for(int i=0;i<max;i++){
clients[i].fd = -1;
}
bzero(&serv_address, sizeof(serv_address));
serv_address.sin_family = AF_INET;
inet_pton(AF_INET, ip.c_str(), &(serv_address.sin_addr));
serv_address.sin_port = htons(port);
}
int WebSock_Server::start(){
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket");
return -1;
}
if(bind_res = bind(listenfd,(struct sockaddr*)&serv_address,
sizeof(serv_address))<0){
perror("bind");
return -1;
}
if(listen_res = listen(listenfd, 100)<0){
perror("listen");
return -1;
}
cout<<"\nWebSocket SERVER started...\n";
return 1;
}
WebSock_Server::~WebSock_Server(){
delete [] clients;
}
int WebSock_Server::recv_size(int fd, int *size)
{
if(ioctl(fd,FIONREAD, size)>=0)
return 1;
perror("ioctl:");
return -1;
}
string WebSock_Server::get_string(string buf, string phrase){
size_t pos = buf.find(phrase);
if(pos == string::npos){
return "";
}
int len = phrase.length();
string key = "";
for(int i=pos+len ;; i++){
if(buf[i]=='\r' || buf[i]=='\n' || i == buf.length())
break;
key.push_back(buf[i]);
}
return key;
}
string WebSock_Server::create_srv_handshake(int i){
string response = "";
response+="HTTP/1.1 101 Switching Protocols\r\n";
response+="Upgarde: " + clients[i].upgrade + "\r\n";
response+="Connection: " + clients[i].connection + "\r\n";
response+="Sec-WebSocket-Accept: "+get_accept(clients[i].websock_key) + "\r\n";
response+="Protocol: chat\r\n\r\n";
return response;
}
bool WebSock_Server::parse_request(string buf, int i){
clients[i].checked = true;
if((clients[i].host = get_string(buf, "Host: "))== ""){
return false;
}
if((clients[i].upgrade = get_string(buf, "Upgrade: ")) == ""){
return false;
}
if((clients[i].connection = get_string(buf, "Connection: ")) == ""){
return false;
}
if((clients[i].websock_key = get_string(buf,"Sec-WebSocket-Key: ")) == ""){
return false;
}
if((clients[i].websock_version = get_string(buf,"Sec-WebSocket-Version: ")) == ""){
return false;
}
if((clients[i].origin = get_string(buf, "Origin: ")) == ""){
return false;
}
return true;
}
int WebSock_Server::accept_conn()
{
client_info *info;
int connfd;
int ident;
if(listenfd<0 || bind_res<0 || listen_res <0)
{
cout<<"\n Error: cannot accept connection!!!\n";
return -1;
}
for(int i = 0; i<max_; i++)
{
if(clients[i].fd<0)
{
ident =i;
info = &clients[i];
}
}
socklen_t addr_size = sizeof(info->address);
if((connfd = accept(listenfd, &(info->address), &addr_size)) < 0)
{
perror("accept()");
return -1;
}else info->fd = connfd;
fd_set rset, wset;
FD_ZERO(&rset);
FD_SET(connfd, &rset);
if(select(8*sizeof(rset),&rset,NULL,NULL,NULL)<0)
{
perror("select()");
close(connfd);
info->fd = -1;
return -1;
}
char *buf;
int size;
bool no_error = true;
if(FD_ISSET(connfd,&rset) && (recv_size(connfd, &size) > 0))
{
buf = new char[size];
if(recv(connfd, buf, size, 0)<0)
{
no_error = false;
perror("recv()");
}
else if(parse_request(buf, ident))
{
string response = create_srv_handshake(ident);
if ((send(connfd, &response[0], response.length(), 0)) < 0)
{
no_error = false;
perror("send()");
}
}
}
delete [] buf;
if(!no_error)
{
close(connfd);
info->fd = -1;
return -1;
}
cout<<"\n Connection accepted...\n";
return ident;
}
| #include "server.hh"
WebSock_Server::WebSock_Server(string ip, int port, int max){
clients = new client_info[max];
max_ = max;
for(int i=0;i<max;i++){
clients[i].fd = -1;
}
bzero(&serv_address, sizeof(serv_address));
serv_address.sin_family = AF_INET;
inet_pton(AF_INET, ip.c_str(), &(serv_address.sin_addr));
serv_address.sin_port = htons(port);
}
int WebSock_Server::start(){
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("socket");
return -1;
}
if(bind_res = bind(listenfd,(struct sockaddr*)&serv_address,
sizeof(serv_address))<0){
perror("bind");
return -1;
}
if(listen_res = listen(listenfd, 100)<0){
perror("listen");
return -1;
}
cout<<"\nWebSocket SERVER started...\n";
return 1;
}
WebSock_Server::~WebSock_Server(){
delete [] clients;
}
int WebSock_Server::recv_size(int fd, int *size)
{
if(ioctl(fd,FIONREAD, size)>=0)
return 1;
perror("ioctl:");
return -1;
}
string WebSock_Server::get_string(string buf, string phrase){
size_t pos = buf.find(phrase);
if(pos == string::npos){
return "";
}
int len = phrase.length();
string key = "";
for(int i=pos+len ;; i++){
if(buf[i]=='\r' || buf[i]=='\n' || i == buf.length())
break;
key.push_back(buf[i]);
}
return key;
}
string WebSock_Server::create_srv_handshake(int i){
string response = "";
response+="HTTP/1.1 101 Switching Protocols\r\n";
response+="Upgarde: " + clients[i].upgrade + "\r\n";
response+="Connection: " + clients[i].connection + "\r\n";
response+="Sec-WebSocket-Accept: "+get_accept(clients[i].websock_key) + "\r\n";
response+="Protocol: chat\r\n\r\n";
return response;
}
bool WebSock_Server::parse_request(string buf, int i){
clients[i].checked = true;
if((clients[i].host = get_string(buf, "Host: "))== ""){
return false;
}
if((clients[i].upgrade = get_string(buf, "Upgrade: ")) == ""){
return false;
}
if((clients[i].connection = get_string(buf, "Connection: ")) == ""){
return false;
}
if((clients[i].websock_key = get_string(buf,"Sec-WebSocket-Key: ")) == ""){
return false;
}
if((clients[i].websock_version = get_string(buf,"Sec-WebSocket-Version: ")) == ""){
return false;
}
if((clients[i].origin = get_string(buf, "Origin: ")) == ""){
return false;
}
return true;
}
int WebSock_Server::accept_conn()
{
client_info *info;
int connfd;
int ident;
if(listenfd<0 || bind_res<0 || listen_res <0)
{
cout<<"\n Error: cannot accept connection!!!\n";
return -1;
}
for(int i = 0; i<max_; i++)
{
if(clients[i].fd<0)
{
ident =i;
info = &clients[i];
}
}
socklen_t addr_size = sizeof(info->address);
if((connfd = accept(listenfd, &(info->address), &addr_size)) < 0)
{
perror("accept()");
return -1;
}else info->fd = connfd;
fd_set rset, wset;
FD_ZERO(&rset);
FD_SET(connfd, &rset);
if(select(1+sizeof(rset),&rset,NULL,NULL,NULL)<0)
{
perror("select()");
close(connfd);
info->fd = -1;
return -1;
}
char *buf;
int size;
bool no_error = true;
if(FD_ISSET(connfd,&rset) && (recv_size(connfd, &size) > 0))
{
buf = new char[size];
if(recv(connfd, buf, size, 0)<0)
{
no_error = false;
perror("recv()");
}
else if(parse_request(buf, ident))
{
string response = create_srv_handshake(ident);
if ((send(connfd, &response[0], response.length(), 0)) < 0)
{
no_error = false;
perror("send()");
}
}
}
delete [] buf;
if(!no_error)
{
close(connfd);
info->fd = -1;
return -1;
}
cout<<"\n Connection accepted...\n";
return ident;
}
| Update server.cc | Update server.cc | C++ | bsd-2-clause | anton4o123/websocket-library |
484582ad0ef09aaf864069e0403440ea2aeaac7b | SSPSolution/SSPSolution/LeverEntity.cpp | SSPSolution/SSPSolution/LeverEntity.cpp | #include "LeverEntity.h"
LeverEntity::LeverEntity(){}
LeverEntity::~LeverEntity(){}
int LeverEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, float interactionDistance)
{
int result = 0;
this->InitializeBase(entityID, pComp, gComp, nullptr);
this->m_isActive = 0;
this->m_needSync = false;
this->m_range = interactionDistance;
this->SyncComponents();
return result;
}
int LeverEntity::Update(float dT, InputHandler * inputHandler)
{
int result = 0;
if (m_animationActive)
{
static float lastFrameRotValue = 0;
PhysicsComponent* ptr = this->GetPhysicsComponent();
DirectX::XMMATRIX rot;
float frameRot = m_animSpeed * dT;
if (m_targetRot == 0)
{
if (m_currRot + frameRot < m_targetRot)
{
m_currRot += frameRot;
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(frameRot));
lastFrameRotValue = m_currRot;
}
else {
m_animationActive = false;
m_currRot = m_targetRot;
this->m_subject.Notify(this->m_entityID, EVENT(EVENT::LEVER_DEACTIVE + this->m_isActive));
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LEVER, pos, false, false);
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(m_targetRot - lastFrameRotValue));
}
}
else
{
if (m_currRot - frameRot > m_targetRot)
{
m_currRot -= frameRot;
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(-frameRot));
lastFrameRotValue = m_currRot;
}
else {
m_animationActive = false;
m_currRot = m_targetRot;
this->m_subject.Notify(this->m_entityID, EVENT(EVENT::LEVER_DEACTIVE + this->m_isActive));
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LEVER, pos, false, false);
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(m_targetRot + (lastFrameRotValue * -1)));
}
}
ptr->PC_OBB.ort = DirectX::XMMatrixMultiply(ptr->PC_OBB.ort, rot);
this->SyncComponents();
}
return result;
}
int LeverEntity::React(int entityID, EVENT reactEvent)
{
int result = 0;
//If a lever receives a LEVER::ACTIVATED or BUTTON::ACTIVATE event, deactivate this lever
if (reactEvent == EVENT::LEVER_ACTIVE || reactEvent == EVENT::BUTTON_ACTIVE)
{
this->m_isActive = false;
if (m_currRot == m_activatedRotation) //check if the animation needs to be reset
{
m_animationActive = true;
m_targetRot = 0;
}
this->SyncComponents();
}
return result;
}
int LeverEntity::CheckPressed(DirectX::XMFLOAT3 playerPos)
{
if (m_animationActive)
return 0;
if (abs(DirectX::XMVectorGetX(this->m_pComp->PC_pos) - playerPos.x) < this->m_range
&& abs(DirectX::XMVectorGetY(this->m_pComp->PC_pos) - playerPos.y) < this->m_range
&& abs(DirectX::XMVectorGetZ(this->m_pComp->PC_pos) - playerPos.z) < this->m_range)
{
this->m_isActive = !this->m_isActive;
if (m_isActive){
m_targetRot = m_activatedRotation;
}
else{
m_targetRot = 0;
}
m_animationActive = true;
this->m_needSync = true;
}
return 0;
}
void LeverEntity::SetSyncState(LeverSyncState * newSyncState)
{
if (newSyncState != nullptr)
{
//The player is always the cause of the state change
this->m_isActive = newSyncState->isActive;
//this->m_animationActive = newSyncState->isAnimationActive;
this->m_animationActive = !this->m_animationActive;
//this->m_subject.Notify(this->m_entityID, EVENT(EVENT::LEVER_DEACTIVE + this->m_isActive));
if (m_isActive) {
m_targetRot = m_activatedRotation;
}
else {
m_targetRot = 0;
}
m_animationActive = true;
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LEVER, pos, false, false);
}
}
LeverSyncState * LeverEntity::GetSyncState()
{
LeverSyncState* result = nullptr;
if (this->m_needSync)
{
result = new LeverSyncState{this->m_entityID, this->m_isActive};
this->m_needSync = false;
}
return result;
}
| #include "LeverEntity.h"
LeverEntity::LeverEntity(){}
LeverEntity::~LeverEntity(){}
int LeverEntity::Initialize(int entityID, PhysicsComponent * pComp, GraphicsComponent * gComp, float interactionDistance)
{
int result = 0;
this->InitializeBase(entityID, pComp, gComp, nullptr);
this->m_isActive = 0;
this->m_needSync = false;
this->m_range = interactionDistance;
this->SyncComponents();
return result;
}
int LeverEntity::Update(float dT, InputHandler * inputHandler)
{
int result = 0;
if (m_animationActive)
{
static float lastFrameRotValue = 0;
PhysicsComponent* ptr = this->GetPhysicsComponent();
DirectX::XMMATRIX rot;
float frameRot = m_animSpeed * dT;
if (m_targetRot == 0)
{
if (m_currRot + frameRot < m_targetRot)
{
m_currRot += frameRot;
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(frameRot));
lastFrameRotValue = m_currRot;
}
else {
m_animationActive = false;
m_currRot = m_targetRot;
this->m_subject.Notify(this->m_entityID, EVENT(EVENT::LEVER_DEACTIVE + this->m_isActive));
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LEVER, pos, false, false);
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(m_targetRot - lastFrameRotValue));
}
}
else
{
if (m_currRot - frameRot > m_targetRot)
{
m_currRot -= frameRot;
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(-frameRot));
lastFrameRotValue = m_currRot;
}
else {
m_animationActive = false;
m_currRot = m_targetRot;
this->m_subject.Notify(this->m_entityID, EVENT(EVENT::LEVER_DEACTIVE + this->m_isActive));
DirectX::XMFLOAT3 pos;
DirectX::XMStoreFloat3(&pos, this->GetPhysicsComponent()->PC_pos);
SoundHandler::instance().PlaySound3D(Sounds3D::GENERAL_LEVER, pos, false, false);
rot = DirectX::XMMatrixRotationAxis(ptr->PC_OBB.ort.r[2], DirectX::XMConvertToRadians(m_targetRot + (lastFrameRotValue * -1)));
}
}
ptr->PC_OBB.ort = DirectX::XMMatrixMultiply(ptr->PC_OBB.ort, rot);
this->SyncComponents();
}
return result;
}
int LeverEntity::React(int entityID, EVENT reactEvent)
{
int result = 0;
//If a lever receives a LEVER::ACTIVATED or BUTTON::ACTIVATE event, deactivate this lever
if (reactEvent == EVENT::LEVER_ACTIVE || reactEvent == EVENT::BUTTON_ACTIVE)
{
this->m_isActive = false;
if (m_currRot == m_activatedRotation) //check if the animation needs to be reset
{
m_animationActive = true;
m_targetRot = 0;
}
this->SyncComponents();
}
return result;
}
int LeverEntity::CheckPressed(DirectX::XMFLOAT3 playerPos)
{
if (m_animationActive)
return 0;
if (abs(DirectX::XMVectorGetX(this->m_pComp->PC_pos) - playerPos.x) < this->m_range
&& abs(DirectX::XMVectorGetY(this->m_pComp->PC_pos) - playerPos.y) < this->m_range
&& abs(DirectX::XMVectorGetZ(this->m_pComp->PC_pos) - playerPos.z) < this->m_range)
{
this->m_isActive = !this->m_isActive;
if (m_isActive){
m_targetRot = m_activatedRotation;
}
else{
m_targetRot = 0;
}
m_animationActive = true;
this->m_needSync = true;
}
return 0;
}
void LeverEntity::SetSyncState(LeverSyncState * newSyncState)
{
if (newSyncState != nullptr)
{
//The player is always the cause of the state change
this->m_isActive = newSyncState->isActive;
//this->m_animationActive = newSyncState->isAnimationActive;
this->m_animationActive = !this->m_animationActive;
//this->m_subject.Notify(this->m_entityID, EVENT(EVENT::LEVER_DEACTIVE + this->m_isActive));
if (m_isActive){
m_targetRot = m_activatedRotation;
}
else{
m_targetRot = 0;
}
m_animationActive = true;
}
}
LeverSyncState * LeverEntity::GetSyncState()
{
LeverSyncState* result = nullptr;
if (this->m_needSync)
{
result = new LeverSyncState{this->m_entityID, this->m_isActive};
this->m_needSync = false;
}
return result;
}
| REMOVE play sound on SetSyncState for lever | REMOVE play sound on SetSyncState for lever
| C++ | apache-2.0 | Chringo/SSP,Chringo/SSP |
13cd9d579520b647c54d131f32e1622c1e59fb92 | src/Decryptor.cpp | src/Decryptor.cpp | #include "stdafx.h"
using std::vector;
static Decryptor* instance = nullptr;
/* static */
Decryptor*
Decryptor::Get()
{
return instance;
}
/* static */
void
Decryptor::Create(GMPDecryptorHost* aHost)
{
assert(!Get());
instance = new Decryptor(aHost);
}
Decryptor::Decryptor(GMPDecryptorHost* aHost)
: mHost(aHost)
, mNum(0)
, mDecryptNumber(0)
{
memset(&mEcount, 0, AES_BLOCK_SIZE);
}
void
Decryptor::Init(GMPDecryptorCallback* aCallback)
{
mCallback = aCallback;
}
#ifdef TEST_GMP_STORAGE
static const std::string SessionIdRecordName = "sessionid";
class ReadShutdownTimeTask : public ReadContinuation {
public:
ReadShutdownTimeTask(Decryptor* aDecryptor,
const std::string& aSessionId)
: mDecryptor(aDecryptor)
, mSessionId(aSessionId)
{
}
void ReadComplete(GMPErr aErr, const std::string& aData) override {
if (!aData.size()) {
mDecryptor->SendSessionMessage(mSessionId, "First run");
} else {
GMPTimestamp s = _atoi64(aData.c_str());
GMPTimestamp t = 0;
GMPGetCurrentTime(&t);
t -= s;
std::string msg = "ClearKey CDM last shutdown " + std::to_string(t/ 1000) + "s ago.";
mDecryptor->SendSessionMessage(mSessionId, msg);
}
}
Decryptor* mDecryptor;
std::string mSessionId;
};
#endif
void
Decryptor::SendSessionMessage(const std::string& aSessionId,
const std::string& aMessage)
{
mCallback->SessionMessage(aSessionId.c_str(),
aSessionId.size(),
(const uint8_t*)aMessage.c_str(),
aMessage.size(),
nullptr,
0);
}
#ifdef TEST_GMP_STORAGE
void
Decryptor::SessionIdReady(uint32_t aPromiseId,
uint32_t aSessionId,
const std::vector<uint8_t>& aInitData)
{
std::string sid = std::to_string(aSessionId);
mCallback->ResolveNewSessionPromise(aPromiseId, sid.c_str(), sid.size());
mCallback->SessionMessage(sid.c_str(), sid.size(),
aInitData.data(), aInitData.size(),
"", 0);
uint32_t nextId = aSessionId + 1;
WriteRecord(SessionIdRecordName, std::to_string(nextId), nullptr);
#ifdef TEST_GMP_TIMER
std::string msg = "Message for you sir! (Sent by a timer)";
GMPTimestamp t = 0;
auto err = GMPGetCurrentTime(&t);
if (GMP_SUCCEEDED(err)) {
msg += " time=" + std::to_string(t);
}
GMPTask* task = new MessageTask(mCallback, sid, msg);
GMPSetTimer(task, 3000);
#endif
#if defined(TEST_GMP_ASYNC_SHUTDOWN)
ReadRecord(SHUTDOWN_TIME_RECORD, new ReadShutdownTimeTask(this, sid));
#endif
}
class ReadSessionId : public ReadContinuation {
public:
ReadSessionId(Decryptor* aDecryptor,
uint32_t aPromiseId,
const std::string& aInitDataType,
vector<uint8_t>& aInitData,
GMPSessionType aSessionType)
: mDecryptor(aDecryptor)
, mPromiseId(aPromiseId)
, mInitDataType(aInitDataType)
, mInitData(std::move(aInitData))
{
}
void ReadComplete(GMPErr aErr, const std::string& aData) override {
uint32_t sid = atoi(aData.c_str());
mDecryptor->SessionIdReady(mPromiseId,
sid,
mInitData);
delete this;
}
std::string mSessionId;
private:
Decryptor* mDecryptor;
uint32_t mPromiseId;
std::string mInitDataType;
vector<uint8_t> mInitData;
};
#endif // TEST_GMP_STORAGE
void
Decryptor::CreateSession(uint32_t aPromiseId,
const char* aInitDataType,
uint32_t aInitDataTypeSize,
const uint8_t* aInitData,
uint32_t aInitDataSize,
GMPSessionType aSessionType)
{
#ifdef TEST_GMP_STORAGE
const std::string initDataType(aInitDataType, aInitDataTypeSize);
vector<uint8_t> initData;
initData.insert(initData.end(), aInitData, aInitData+aInitDataSize);
auto err = ReadRecord(SessionIdRecordName,
new ReadSessionId(this,
aPromiseId,
initDataType,
initData,
aSessionType));
if (GMP_FAILED(err)) {
std::string msg = "ClearKeyGMP: Failed to read from storage.";
mCallback->SessionError(nullptr, 0,
kGMPInvalidStateError,
42,
msg.c_str(),
msg.size());
}
#else
static uint32_t gSessionCount = 1;
std::string sid = std::to_string(gSessionCount++);
mCallback->ResolveNewSessionPromise(aPromiseId, sid.c_str(), sid.size());
mCallback->SessionMessage(sid.c_str(), sid.size(),
aInitData, aInitDataSize,
"", 0);
#endif
}
void
Decryptor::LoadSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::UpdateSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength,
const uint8_t* aResponse,
uint32_t aResponseSize)
{
// Notify Gecko of all the keys that are ready to decode with. Gecko
// will only try to decrypt data for keyIds which the GMP/CDM has said
// are usable. So don't forget to do this, otherwise the CDM won't be
// asked to decode/decrypt anything!
eme_key_set keys;
ExtractKeysFromJWKSet(std::string((const char*)aResponse, aResponseSize), keys);
for (auto itr = keys.begin(); itr != keys.end(); itr++) {
eme_key_id id = itr->first;
eme_key key = itr->second;
mKeySet[id] = key;
mCallback->KeyIdUsable(aSessionId,
aSessionIdLength,
(uint8_t*)id.c_str(),
id.length());
}
#ifdef TEST_DECODING
mCallback->SetCapabilities(GMP_EME_CAP_DECRYPT_AND_DECODE_AUDIO |
GMP_EME_CAP_DECRYPT_AND_DECODE_VIDEO);
#else
mCallback->SetCapabilities(GMP_EME_CAP_DECRYPT_AUDIO |
GMP_EME_CAP_DECRYPT_VIDEO);
#endif
std::string msg = "ClearKeyGMP says UpdateSession is throwing fake error/exception";
mCallback->SessionError(aSessionId, aSessionIdLength,
kGMPInvalidStateError,
42,
msg.c_str(),
msg.size());
}
void
Decryptor::CloseSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
// Drop keys for session_id.
// G. implementation:
// https://code.google.com/p/chromium/codesearch#chromium/src/media/cdm/aes_decryptor.cc&sq=package:chromium&q=ReleaseSession&l=300&type=cs
mKeySet.clear();
//mHost->OnSessionClosed(session_id);
//mActiveSessionId = ~0;
}
void
Decryptor::RemoveSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::SetServerCertificate(uint32_t aPromiseId,
const uint8_t* aServerCert,
uint32_t aServerCertSize)
{
}
void
Decryptor::Decrypt(GMPBuffer* aBuffer,
GMPEncryptedBufferMetadata* aMetadata)
{
vector<uint8_t> decrypted;
if (!Decrypt(aBuffer->Data(),
aBuffer->Size(),
aMetadata,
decrypted)) {
mCallback->Decrypted(aBuffer, GMPCryptoErr);
} else {
memcpy(aBuffer->Data(), decrypted.data(), aBuffer->Size());
mCallback->Decrypted(aBuffer, GMPNoErr);
}
}
bool
Decryptor::Decrypt(const uint8_t* aEncryptedBuffer,
const uint32_t aLength,
const GMPEncryptedBufferMetadata* aCryptoData,
vector<uint8_t>& aOutDecrypted)
{
std::string kid((const char*)aCryptoData->KeyId(), aCryptoData->KeyIdSize());
if (mKeySet.find(kid) == mKeySet.end()) {
// No key for that id.
return false;
}
const std::string key = mKeySet[kid];
if (AES_set_encrypt_key((uint8_t*)key.c_str(), 128, &mKey)) {
LOG(L"Failed to set decryption key!\n");
return false;
}
// Make one pass copying all encrypted data into a single buffer, then
// another pass to decrypt it. Then another pass copying it into the
// output buffer.
vector<uint8_t> data;
uint32_t index = 0;
const uint32_t num_subsamples = aCryptoData->NumSubsamples();
const uint16_t* clear_bytes = aCryptoData->ClearBytes();
const uint32_t* cipher_bytes = aCryptoData->CipherBytes();
for (uint32_t i=0; i<num_subsamples; i++) {
index += clear_bytes[i];
const uint8_t* start = aEncryptedBuffer + index;
const uint8_t* end = start + cipher_bytes[i];
data.insert(data.end(), start, end);
index += cipher_bytes[i];
}
// Ensure the data length is a multiple of 16, and the extra data is
// filled with 0's
int32_t extra = (data.size() + AES_BLOCK_SIZE) % AES_BLOCK_SIZE;
data.insert(data.end(), extra, uint8_t(0));
// Decrypt the buffer.
const uint32_t iterations = data.size() / AES_BLOCK_SIZE;
vector<uint8_t> decrypted;
decrypted.resize(data.size());
uint8_t iv[AES_BLOCK_SIZE] = {0};
memcpy(iv, aCryptoData->IV(), aCryptoData->IVSize());
for (uint32_t i=0; i<iterations; i++) {
uint8_t* in = data.data() + i*AES_BLOCK_SIZE;
assert(in + AES_BLOCK_SIZE <= data.data() + data.size());
uint8_t* out = decrypted.data() + i*AES_BLOCK_SIZE;
assert(out + AES_BLOCK_SIZE <= decrypted.data() + decrypted.size());
AES_ctr128_encrypt(in,
out,
AES_BLOCK_SIZE,
&mKey,
iv,
mEcount,
&mNum);
}
// Re-assemble the decrypted buffer.
aOutDecrypted.clear();
aOutDecrypted.resize(aLength);
uint8_t* dst = aOutDecrypted.data();
const uint8_t* src = aEncryptedBuffer;
index = 0;
uint32_t decrypted_index = 0;
for (uint32_t i = 0; i < num_subsamples; i++) {
memcpy(dst+index, src+index, clear_bytes[i]);
index += clear_bytes[i];
memcpy(dst+index, decrypted.data()+decrypted_index, cipher_bytes[i]);
decrypted_index+= cipher_bytes[i];
index += cipher_bytes[i];
assert(index <= aLength);
assert(decrypted_index <= aLength);
}
mDecryptNumber++;
return true;
}
void
Decryptor::DecryptingComplete()
{
mCallback = nullptr;
}
| #include "stdafx.h"
using std::vector;
static Decryptor* instance = nullptr;
/* static */
Decryptor*
Decryptor::Get()
{
return instance;
}
/* static */
void
Decryptor::Create(GMPDecryptorHost* aHost)
{
assert(!Get());
instance = new Decryptor(aHost);
}
Decryptor::Decryptor(GMPDecryptorHost* aHost)
: mHost(aHost)
, mNum(0)
, mDecryptNumber(0)
{
memset(&mEcount, 0, AES_BLOCK_SIZE);
}
void
Decryptor::Init(GMPDecryptorCallback* aCallback)
{
mCallback = aCallback;
}
#ifdef TEST_GMP_STORAGE
static const std::string SessionIdRecordName = "sessionid";
class ReadShutdownTimeTask : public ReadContinuation {
public:
ReadShutdownTimeTask(Decryptor* aDecryptor,
const std::string& aSessionId)
: mDecryptor(aDecryptor)
, mSessionId(aSessionId)
{
}
void ReadComplete(GMPErr aErr, const std::string& aData) override {
if (!aData.size()) {
mDecryptor->SendSessionMessage(mSessionId, "First run");
} else {
GMPTimestamp s = _atoi64(aData.c_str());
GMPTimestamp t = 0;
GMPGetCurrentTime(&t);
t -= s;
std::string msg = "ClearKey CDM last shutdown " + std::to_string(t/ 1000) + "s ago.";
mDecryptor->SendSessionMessage(mSessionId, msg);
}
}
Decryptor* mDecryptor;
std::string mSessionId;
};
#endif
void
Decryptor::SendSessionMessage(const std::string& aSessionId,
const std::string& aMessage)
{
mCallback->SessionMessage(aSessionId.c_str(),
aSessionId.size(),
(const uint8_t*)aMessage.c_str(),
aMessage.size(),
nullptr,
0);
}
#ifdef TEST_GMP_STORAGE
void
Decryptor::SessionIdReady(uint32_t aPromiseId,
uint32_t aSessionId,
const std::vector<uint8_t>& aInitData)
{
std::string sid = std::to_string(aSessionId);
mCallback->ResolveNewSessionPromise(aPromiseId, sid.c_str(), sid.size());
mCallback->SessionMessage(sid.c_str(), sid.size(),
aInitData.data(), aInitData.size(),
"", 0);
uint32_t nextId = aSessionId + 1;
WriteRecord(SessionIdRecordName, std::to_string(nextId), nullptr);
#if defined(TEST_GMP_ASYNC_SHUTDOWN)
ReadRecord(SHUTDOWN_TIME_RECORD, new ReadShutdownTimeTask(this, sid));
#endif
}
class ReadSessionId : public ReadContinuation {
public:
ReadSessionId(Decryptor* aDecryptor,
uint32_t aPromiseId,
const std::string& aInitDataType,
vector<uint8_t>& aInitData,
GMPSessionType aSessionType)
: mDecryptor(aDecryptor)
, mPromiseId(aPromiseId)
, mInitDataType(aInitDataType)
, mInitData(std::move(aInitData))
{
}
void ReadComplete(GMPErr aErr, const std::string& aData) override {
uint32_t sid = atoi(aData.c_str());
mDecryptor->SessionIdReady(mPromiseId,
sid,
mInitData);
delete this;
}
std::string mSessionId;
private:
Decryptor* mDecryptor;
uint32_t mPromiseId;
std::string mInitDataType;
vector<uint8_t> mInitData;
};
#endif // TEST_GMP_STORAGE
void
Decryptor::CreateSession(uint32_t aPromiseId,
const char* aInitDataType,
uint32_t aInitDataTypeSize,
const uint8_t* aInitData,
uint32_t aInitDataSize,
GMPSessionType aSessionType)
{
#ifdef TEST_GMP_STORAGE
const std::string initDataType(aInitDataType, aInitDataTypeSize);
vector<uint8_t> initData;
initData.insert(initData.end(), aInitData, aInitData+aInitDataSize);
auto err = ReadRecord(SessionIdRecordName,
new ReadSessionId(this,
aPromiseId,
initDataType,
initData,
aSessionType));
if (GMP_FAILED(err)) {
std::string msg = "ClearKeyGMP: Failed to read from storage.";
mCallback->SessionError(nullptr, 0,
kGMPInvalidStateError,
42,
msg.c_str(),
msg.size());
}
#else
static uint32_t gSessionCount = 1;
std::string sid = std::to_string(gSessionCount++);
mCallback->ResolveNewSessionPromise(aPromiseId, sid.c_str(), sid.size());
mCallback->SessionMessage(sid.c_str(), sid.size(),
aInitData, aInitDataSize,
"", 0);
#endif
#ifdef TEST_GMP_TIMER
std::string msg = "Message for you sir! (Sent by a timer)";
GMPTimestamp t = 0;
auto err = GMPGetCurrentTime(&t);
if (GMP_SUCCEEDED(err)) {
msg += " time=" + std::to_string(t);
}
GMPTask* task = new MessageTask(mCallback, sid, msg);
GMPSetTimer(task, 3000);
#endif
}
void
Decryptor::LoadSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::UpdateSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength,
const uint8_t* aResponse,
uint32_t aResponseSize)
{
// Notify Gecko of all the keys that are ready to decode with. Gecko
// will only try to decrypt data for keyIds which the GMP/CDM has said
// are usable. So don't forget to do this, otherwise the CDM won't be
// asked to decode/decrypt anything!
eme_key_set keys;
ExtractKeysFromJWKSet(std::string((const char*)aResponse, aResponseSize), keys);
for (auto itr = keys.begin(); itr != keys.end(); itr++) {
eme_key_id id = itr->first;
eme_key key = itr->second;
mKeySet[id] = key;
mCallback->KeyIdUsable(aSessionId,
aSessionIdLength,
(uint8_t*)id.c_str(),
id.length());
}
#ifdef TEST_DECODING
mCallback->SetCapabilities(GMP_EME_CAP_DECRYPT_AND_DECODE_AUDIO |
GMP_EME_CAP_DECRYPT_AND_DECODE_VIDEO);
#else
mCallback->SetCapabilities(GMP_EME_CAP_DECRYPT_AUDIO |
GMP_EME_CAP_DECRYPT_VIDEO);
#endif
std::string msg = "ClearKeyGMP says UpdateSession is throwing fake error/exception";
mCallback->SessionError(aSessionId, aSessionIdLength,
kGMPInvalidStateError,
42,
msg.c_str(),
msg.size());
}
void
Decryptor::CloseSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
// Drop keys for session_id.
// G. implementation:
// https://code.google.com/p/chromium/codesearch#chromium/src/media/cdm/aes_decryptor.cc&sq=package:chromium&q=ReleaseSession&l=300&type=cs
mKeySet.clear();
//mHost->OnSessionClosed(session_id);
//mActiveSessionId = ~0;
}
void
Decryptor::RemoveSession(uint32_t aPromiseId,
const char* aSessionId,
uint32_t aSessionIdLength)
{
}
void
Decryptor::SetServerCertificate(uint32_t aPromiseId,
const uint8_t* aServerCert,
uint32_t aServerCertSize)
{
}
void
Decryptor::Decrypt(GMPBuffer* aBuffer,
GMPEncryptedBufferMetadata* aMetadata)
{
vector<uint8_t> decrypted;
if (!Decrypt(aBuffer->Data(),
aBuffer->Size(),
aMetadata,
decrypted)) {
mCallback->Decrypted(aBuffer, GMPCryptoErr);
} else {
memcpy(aBuffer->Data(), decrypted.data(), aBuffer->Size());
mCallback->Decrypted(aBuffer, GMPNoErr);
}
}
bool
Decryptor::Decrypt(const uint8_t* aEncryptedBuffer,
const uint32_t aLength,
const GMPEncryptedBufferMetadata* aCryptoData,
vector<uint8_t>& aOutDecrypted)
{
std::string kid((const char*)aCryptoData->KeyId(), aCryptoData->KeyIdSize());
if (mKeySet.find(kid) == mKeySet.end()) {
// No key for that id.
return false;
}
const std::string key = mKeySet[kid];
if (AES_set_encrypt_key((uint8_t*)key.c_str(), 128, &mKey)) {
LOG(L"Failed to set decryption key!\n");
return false;
}
// Make one pass copying all encrypted data into a single buffer, then
// another pass to decrypt it. Then another pass copying it into the
// output buffer.
vector<uint8_t> data;
uint32_t index = 0;
const uint32_t num_subsamples = aCryptoData->NumSubsamples();
const uint16_t* clear_bytes = aCryptoData->ClearBytes();
const uint32_t* cipher_bytes = aCryptoData->CipherBytes();
for (uint32_t i=0; i<num_subsamples; i++) {
index += clear_bytes[i];
const uint8_t* start = aEncryptedBuffer + index;
const uint8_t* end = start + cipher_bytes[i];
data.insert(data.end(), start, end);
index += cipher_bytes[i];
}
// Ensure the data length is a multiple of 16, and the extra data is
// filled with 0's
int32_t extra = (data.size() + AES_BLOCK_SIZE) % AES_BLOCK_SIZE;
data.insert(data.end(), extra, uint8_t(0));
// Decrypt the buffer.
const uint32_t iterations = data.size() / AES_BLOCK_SIZE;
vector<uint8_t> decrypted;
decrypted.resize(data.size());
uint8_t iv[AES_BLOCK_SIZE] = {0};
memcpy(iv, aCryptoData->IV(), aCryptoData->IVSize());
for (uint32_t i=0; i<iterations; i++) {
uint8_t* in = data.data() + i*AES_BLOCK_SIZE;
assert(in + AES_BLOCK_SIZE <= data.data() + data.size());
uint8_t* out = decrypted.data() + i*AES_BLOCK_SIZE;
assert(out + AES_BLOCK_SIZE <= decrypted.data() + decrypted.size());
AES_ctr128_encrypt(in,
out,
AES_BLOCK_SIZE,
&mKey,
iv,
mEcount,
&mNum);
}
// Re-assemble the decrypted buffer.
aOutDecrypted.clear();
aOutDecrypted.resize(aLength);
uint8_t* dst = aOutDecrypted.data();
const uint8_t* src = aEncryptedBuffer;
index = 0;
uint32_t decrypted_index = 0;
for (uint32_t i = 0; i < num_subsamples; i++) {
memcpy(dst+index, src+index, clear_bytes[i]);
index += clear_bytes[i];
memcpy(dst+index, decrypted.data()+decrypted_index, cipher_bytes[i]);
decrypted_index+= cipher_bytes[i];
index += cipher_bytes[i];
assert(index <= aLength);
assert(decrypted_index <= aLength);
}
mDecryptNumber++;
return true;
}
void
Decryptor::DecryptingComplete()
{
mCallback = nullptr;
}
| Make testing timer not depend on testing storage, since it doesn't. | Make testing timer not depend on testing storage, since it doesn't.
| C++ | apache-2.0 | cpearce/gmp-clearkey,cpearce/gmp-clearkey,cpearce/gmp-clearkey |
a2118e22baaaeb3b4e6c3f00fa7216ffecb342a9 | android/runtime/v8/src/native/JNIUtil.cpp | android/runtime/v8/src/native/JNIUtil.cpp | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <jni.h>
#include <stdio.h>
#include "JNIUtil.h"
#include "AndroidUtil.h"
#define TAG "JNIUtil"
namespace titanium {
JavaVM* JNIUtil::javaVm = NULL;
jclass JNIUtil::classClass = NULL;
jclass JNIUtil::objectClass = NULL;
jclass JNIUtil::stringClass = NULL;
jclass JNIUtil::numberClass = NULL;
jclass JNIUtil::shortClass = NULL;
jclass JNIUtil::integerClass = NULL;
jclass JNIUtil::longClass = NULL;
jclass JNIUtil::floatClass = NULL;
jclass JNIUtil::doubleClass = NULL;
jclass JNIUtil::booleanClass = NULL;
jclass JNIUtil::arrayListClass = NULL;
jclass JNIUtil::hashMapClass = NULL;
jclass JNIUtil::dateClass = NULL;
jclass JNIUtil::setClass = NULL;
jclass JNIUtil::outOfMemoryError = NULL;
jclass JNIUtil::nullPointerException = NULL;
jclass JNIUtil::krollProxyClass = NULL;
jclass JNIUtil::v8ObjectClass = NULL;
jclass JNIUtil::managedV8ReferenceClass = NULL;
jclass JNIUtil::assetsClass = NULL;
jclass JNIUtil::eventListenerClass = NULL;
jclass JNIUtil::v8FunctionClass = NULL;
jmethodID JNIUtil::classGetNameMethod = NULL;
jmethodID JNIUtil::arrayListInitMethod = NULL;
jmethodID JNIUtil::arrayListAddMethod = NULL;
jmethodID JNIUtil::arrayListGetMethod = NULL;
jmethodID JNIUtil::arrayListRemoveMethod = NULL;
jmethodID JNIUtil::hashMapInitMethod = NULL;
jmethodID JNIUtil::hashMapGetMethod = NULL;
jmethodID JNIUtil::hashMapPutMethod = NULL;
jmethodID JNIUtil::hashMapKeySetMethod = NULL;
jmethodID JNIUtil::hashMapRemoveMethod = NULL;
jmethodID JNIUtil::setToArrayMethod = NULL;
jmethodID JNIUtil::dateInitMethod = NULL;
jmethodID JNIUtil::dateGetTimeMethod = NULL;
jmethodID JNIUtil::doubleInitMethod = NULL;
jmethodID JNIUtil::booleanInitMethod = NULL;
jmethodID JNIUtil::longInitMethod = NULL;
jmethodID JNIUtil::numberDoubleValueMethod = NULL;
jfieldID JNIUtil::managedV8ReferencePtrField = NULL;
jmethodID JNIUtil::krollProxyCreateMethod = NULL;
jmethodID JNIUtil::v8ObjectInitMethod = NULL;
jmethodID JNIUtil::assetsReadResourceMethod = NULL;
jmethodID JNIUtil::eventListenerPostEventMethod = NULL;
jmethodID JNIUtil::v8FunctionInitMethod = NULL;
JNIEnv* JNIScope::current = NULL;
/* static */
JNIEnv* JNIUtil::getJNIEnv()
{
JNIEnv *env;
int status = javaVm->GetEnv((void **) &env, JNI_VERSION_1_4);
if (status < 0) {
return NULL;
}
return env;
}
void JNIUtil::terminateVM()
{
javaVm->DestroyJavaVM();
}
jobjectArray JNIUtil::newObjectArray(int length, jobject initial)
{
JNIEnv* env = JNIScope::getEnv();
if (env) {
return env->NewObjectArray(length, objectClass, initial);
}
return NULL;
}
void JNIUtil::throwException(jclass clazz, const char *message)
{
JNIEnv* env = JNIScope::getEnv();
if (!env || !clazz) {
return;
}
env->ExceptionClear();
env->ThrowNew(clazz, message);
}
void JNIUtil::throwException(const char *className, const char *message)
{
JNIEnv* env = JNIScope::getEnv();
if (!env) {
return;
}
jclass clazz = findClass(className);
throwException(clazz, message);
env->DeleteLocalRef(clazz);
}
void JNIUtil::throwOutOfMemoryError(const char *message)
{
throwException(outOfMemoryError, message);
}
void JNIUtil::throwNullPointerException(const char *message)
{
throwException(nullPointerException, message);
}
jclass JNIUtil::findClass(const char *className)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) {
LOGE(TAG, "Couldn't initialize JNIEnv");
return NULL;
}
jclass javaClass = env->FindClass(className);
if (!javaClass) {
LOGE(TAG, "Couldn't find Java class: %s", className);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return NULL;
} else {
jclass globalClass = (jclass) env->NewGlobalRef(javaClass);
env->DeleteLocalRef(javaClass);
return globalClass;
}
}
jmethodID JNIUtil::getMethodID(jclass javaClass, const char *methodName, const char *signature, bool isStatic)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) {
LOGE(TAG, "Couldn't initialize JNIEnv");
return NULL;
}
jmethodID javaMethodID;
if (isStatic) {
javaMethodID = env->GetStaticMethodID(javaClass, methodName, signature);
} else {
javaMethodID = env->GetMethodID(javaClass, methodName, signature);
}
if (!javaMethodID) {
LOGE(TAG, "Couldn't find Java method ID: %s %s", methodName, signature);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
}
return javaMethodID;
}
jfieldID JNIUtil::getFieldID(jclass javaClass, const char *fieldName, const char *signature)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) {
LOGE(TAG, "Couldn't initialize JNIEnv");
return NULL;
}
jfieldID javaFieldID = env->GetFieldID(javaClass, fieldName, signature);
if (!javaFieldID) {
LOGE(TAG, "Couldn't find Java field ID: %s %s", fieldName, signature);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
}
return javaFieldID;
}
jstring JNIUtil::getClassName(jclass javaClass)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) return NULL;
return (jstring) env->CallObjectMethod(javaClass, classGetNameMethod);
}
void JNIUtil::logClassName(const char *format, jclass javaClass, bool errorLevel)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) return;
jstring jClassName = (jstring) env->CallObjectMethod(javaClass, classGetNameMethod);
jboolean isCopy;
const char* chars = env->GetStringUTFChars(jClassName, &isCopy);
if (errorLevel) {
LOGE(TAG, format, chars);
} else {
LOGD(TAG, format, chars);
}
env->ReleaseStringUTFChars(jClassName, chars);
}
void JNIUtil::initCache()
{
LOG_TIMER(TAG, "initializing JNI cache");
JNIEnv *env = JNIScope::getEnv();
classClass = findClass("java/lang/Class");
objectClass = findClass("java/lang/Object");
numberClass = findClass("java/lang/Number");
stringClass = findClass("java/lang/String");
shortClass = findClass("java/lang/Short");
integerClass = findClass("java/lang/Integer");
longClass = findClass("java/lang/Long");
floatClass = findClass("java/lang/Float");
doubleClass = findClass("java/lang/Double");
booleanClass = findClass("java/lang/Boolean");
arrayListClass = findClass("java/util/ArrayList");
hashMapClass = findClass("java/util/HashMap");
dateClass = findClass("java/util/Date");
setClass = findClass("java/util/Set");
outOfMemoryError = findClass("java/lang/OutOfMemoryError");
nullPointerException = findClass("java/lang/NullPointerException");
krollProxyClass = findClass("org/appcelerator/kroll/KrollProxy");
v8ObjectClass = findClass("org/appcelerator/kroll/runtime/v8/V8Object");
managedV8ReferenceClass = findClass("org/appcelerator/kroll/runtime/v8/ManagedV8Reference");
assetsClass = findClass("org/appcelerator/kroll/runtime/Assets");
eventListenerClass = findClass("org/appcelerator/kroll/runtime/v8/EventListener");
v8FunctionClass = findClass("org/appcelerator/kroll/runtime/v8/V8Function");
classGetNameMethod = getMethodID(classClass, "getName", "()Ljava/lang/String;", false);
arrayListInitMethod = getMethodID(arrayListClass, "<init>", "()V", false);
arrayListAddMethod = getMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z", false);
arrayListGetMethod = getMethodID(arrayListClass, "get", "(I)Ljava/lang/Object;", false);
arrayListRemoveMethod = getMethodID(arrayListClass, "remove", "(I)Ljava/lang/Object;", false);
hashMapInitMethod = getMethodID(hashMapClass, "<init>", "(I)V", false);
hashMapGetMethod = getMethodID(hashMapClass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false);
hashMapPutMethod = getMethodID(hashMapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;",
false);
hashMapKeySetMethod = getMethodID(hashMapClass, "keySet", "()Ljava/util/Set;", false);
hashMapRemoveMethod = getMethodID(hashMapClass, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false);
setToArrayMethod = getMethodID(setClass, "toArray", "()[Ljava/lang/Object;", false);
dateInitMethod = getMethodID(dateClass, "<init>", "(J)V", false);
dateGetTimeMethod = getMethodID(dateClass, "getTime", "()J", false);
doubleInitMethod = getMethodID(doubleClass, "<init>", "(D)V", false);
booleanInitMethod = getMethodID(booleanClass, "<init>", "(Z)V", false);
longInitMethod = getMethodID(longClass, "<init>", "(J)V", false);
numberDoubleValueMethod = getMethodID(numberClass, "doubleValue", "()D", false);
v8ObjectInitMethod = getMethodID(v8ObjectClass, "<init>", "(J)V", false);
managedV8ReferencePtrField = getFieldID(managedV8ReferenceClass, "ptr", "J");
krollProxyCreateMethod = getMethodID(krollProxyClass, "create",
"(Ljava/lang/Class;[Ljava/lang/Object;JLjava/lang/String;)Lorg/appcelerator/kroll/KrollProxy;", true);
assetsReadResourceMethod = getMethodID(assetsClass, "readResource", "(Ljava/lang/String;)[C", true);
eventListenerPostEventMethod = getMethodID(eventListenerClass, "postEvent",
"(Ljava/util/HashMap;)V", false);
v8FunctionInitMethod = getMethodID(v8FunctionClass, "<init>", "(j)V", false);
}
}
| /**
* Appcelerator Titanium Mobile
* Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include <jni.h>
#include <stdio.h>
#include "JNIUtil.h"
#include "AndroidUtil.h"
#define TAG "JNIUtil"
namespace titanium {
JavaVM* JNIUtil::javaVm = NULL;
jclass JNIUtil::classClass = NULL;
jclass JNIUtil::objectClass = NULL;
jclass JNIUtil::stringClass = NULL;
jclass JNIUtil::numberClass = NULL;
jclass JNIUtil::shortClass = NULL;
jclass JNIUtil::integerClass = NULL;
jclass JNIUtil::longClass = NULL;
jclass JNIUtil::floatClass = NULL;
jclass JNIUtil::doubleClass = NULL;
jclass JNIUtil::booleanClass = NULL;
jclass JNIUtil::arrayListClass = NULL;
jclass JNIUtil::hashMapClass = NULL;
jclass JNIUtil::dateClass = NULL;
jclass JNIUtil::setClass = NULL;
jclass JNIUtil::outOfMemoryError = NULL;
jclass JNIUtil::nullPointerException = NULL;
jclass JNIUtil::krollProxyClass = NULL;
jclass JNIUtil::v8ObjectClass = NULL;
jclass JNIUtil::managedV8ReferenceClass = NULL;
jclass JNIUtil::assetsClass = NULL;
jclass JNIUtil::eventListenerClass = NULL;
jclass JNIUtil::v8FunctionClass = NULL;
jmethodID JNIUtil::classGetNameMethod = NULL;
jmethodID JNIUtil::arrayListInitMethod = NULL;
jmethodID JNIUtil::arrayListAddMethod = NULL;
jmethodID JNIUtil::arrayListGetMethod = NULL;
jmethodID JNIUtil::arrayListRemoveMethod = NULL;
jmethodID JNIUtil::hashMapInitMethod = NULL;
jmethodID JNIUtil::hashMapGetMethod = NULL;
jmethodID JNIUtil::hashMapPutMethod = NULL;
jmethodID JNIUtil::hashMapKeySetMethod = NULL;
jmethodID JNIUtil::hashMapRemoveMethod = NULL;
jmethodID JNIUtil::setToArrayMethod = NULL;
jmethodID JNIUtil::dateInitMethod = NULL;
jmethodID JNIUtil::dateGetTimeMethod = NULL;
jmethodID JNIUtil::doubleInitMethod = NULL;
jmethodID JNIUtil::booleanInitMethod = NULL;
jmethodID JNIUtil::longInitMethod = NULL;
jmethodID JNIUtil::numberDoubleValueMethod = NULL;
jfieldID JNIUtil::managedV8ReferencePtrField = NULL;
jmethodID JNIUtil::krollProxyCreateMethod = NULL;
jmethodID JNIUtil::v8ObjectInitMethod = NULL;
jmethodID JNIUtil::assetsReadResourceMethod = NULL;
jmethodID JNIUtil::eventListenerPostEventMethod = NULL;
jmethodID JNIUtil::v8FunctionInitMethod = NULL;
JNIEnv* JNIScope::current = NULL;
/* static */
JNIEnv* JNIUtil::getJNIEnv()
{
JNIEnv *env;
int status = javaVm->GetEnv((void **) &env, JNI_VERSION_1_4);
if (status < 0) {
return NULL;
}
return env;
}
void JNIUtil::terminateVM()
{
javaVm->DestroyJavaVM();
}
jobjectArray JNIUtil::newObjectArray(int length, jobject initial)
{
JNIEnv* env = JNIScope::getEnv();
if (env) {
return env->NewObjectArray(length, objectClass, initial);
}
return NULL;
}
void JNIUtil::throwException(jclass clazz, const char *message)
{
JNIEnv* env = JNIScope::getEnv();
if (!env || !clazz) {
return;
}
env->ExceptionClear();
env->ThrowNew(clazz, message);
}
void JNIUtil::throwException(const char *className, const char *message)
{
JNIEnv* env = JNIScope::getEnv();
if (!env) {
return;
}
jclass clazz = findClass(className);
throwException(clazz, message);
env->DeleteLocalRef(clazz);
}
void JNIUtil::throwOutOfMemoryError(const char *message)
{
throwException(outOfMemoryError, message);
}
void JNIUtil::throwNullPointerException(const char *message)
{
throwException(nullPointerException, message);
}
jclass JNIUtil::findClass(const char *className)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) {
LOGE(TAG, "Couldn't initialize JNIEnv");
return NULL;
}
jclass javaClass = env->FindClass(className);
if (!javaClass) {
LOGE(TAG, "Couldn't find Java class: %s", className);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return NULL;
} else {
jclass globalClass = (jclass) env->NewGlobalRef(javaClass);
env->DeleteLocalRef(javaClass);
return globalClass;
}
}
jmethodID JNIUtil::getMethodID(jclass javaClass, const char *methodName, const char *signature, bool isStatic)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) {
LOGE(TAG, "Couldn't initialize JNIEnv");
return NULL;
}
jmethodID javaMethodID;
if (isStatic) {
javaMethodID = env->GetStaticMethodID(javaClass, methodName, signature);
} else {
javaMethodID = env->GetMethodID(javaClass, methodName, signature);
}
if (!javaMethodID) {
LOGE(TAG, "Couldn't find Java method ID: %s %s", methodName, signature);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
}
return javaMethodID;
}
jfieldID JNIUtil::getFieldID(jclass javaClass, const char *fieldName, const char *signature)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) {
LOGE(TAG, "Couldn't initialize JNIEnv");
return NULL;
}
jfieldID javaFieldID = env->GetFieldID(javaClass, fieldName, signature);
if (!javaFieldID) {
LOGE(TAG, "Couldn't find Java field ID: %s %s", fieldName, signature);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
}
return javaFieldID;
}
jstring JNIUtil::getClassName(jclass javaClass)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) return NULL;
return (jstring) env->CallObjectMethod(javaClass, classGetNameMethod);
}
void JNIUtil::logClassName(const char *format, jclass javaClass, bool errorLevel)
{
JNIEnv *env = JNIScope::getEnv();
if (!env) return;
jstring jClassName = (jstring) env->CallObjectMethod(javaClass, classGetNameMethod);
jboolean isCopy;
const char* chars = env->GetStringUTFChars(jClassName, &isCopy);
if (errorLevel) {
LOGE(TAG, format, chars);
} else {
LOGD(TAG, format, chars);
}
env->ReleaseStringUTFChars(jClassName, chars);
}
void JNIUtil::initCache()
{
LOG_TIMER(TAG, "initializing JNI cache");
JNIEnv *env = JNIScope::getEnv();
classClass = findClass("java/lang/Class");
objectClass = findClass("java/lang/Object");
numberClass = findClass("java/lang/Number");
stringClass = findClass("java/lang/String");
shortClass = findClass("java/lang/Short");
integerClass = findClass("java/lang/Integer");
longClass = findClass("java/lang/Long");
floatClass = findClass("java/lang/Float");
doubleClass = findClass("java/lang/Double");
booleanClass = findClass("java/lang/Boolean");
arrayListClass = findClass("java/util/ArrayList");
hashMapClass = findClass("java/util/HashMap");
dateClass = findClass("java/util/Date");
setClass = findClass("java/util/Set");
outOfMemoryError = findClass("java/lang/OutOfMemoryError");
nullPointerException = findClass("java/lang/NullPointerException");
krollProxyClass = findClass("org/appcelerator/kroll/KrollProxy");
v8ObjectClass = findClass("org/appcelerator/kroll/runtime/v8/V8Object");
managedV8ReferenceClass = findClass("org/appcelerator/kroll/runtime/v8/ManagedV8Reference");
assetsClass = findClass("org/appcelerator/kroll/runtime/Assets");
eventListenerClass = findClass("org/appcelerator/kroll/runtime/v8/EventListener");
v8FunctionClass = findClass("org/appcelerator/kroll/runtime/v8/V8Function");
classGetNameMethod = getMethodID(classClass, "getName", "()Ljava/lang/String;", false);
arrayListInitMethod = getMethodID(arrayListClass, "<init>", "()V", false);
arrayListAddMethod = getMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z", false);
arrayListGetMethod = getMethodID(arrayListClass, "get", "(I)Ljava/lang/Object;", false);
arrayListRemoveMethod = getMethodID(arrayListClass, "remove", "(I)Ljava/lang/Object;", false);
hashMapInitMethod = getMethodID(hashMapClass, "<init>", "(I)V", false);
hashMapGetMethod = getMethodID(hashMapClass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;", false);
hashMapPutMethod = getMethodID(hashMapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;",
false);
hashMapKeySetMethod = getMethodID(hashMapClass, "keySet", "()Ljava/util/Set;", false);
hashMapRemoveMethod = getMethodID(hashMapClass, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;", false);
setToArrayMethod = getMethodID(setClass, "toArray", "()[Ljava/lang/Object;", false);
dateInitMethod = getMethodID(dateClass, "<init>", "(J)V", false);
dateGetTimeMethod = getMethodID(dateClass, "getTime", "()J", false);
doubleInitMethod = getMethodID(doubleClass, "<init>", "(D)V", false);
booleanInitMethod = getMethodID(booleanClass, "<init>", "(Z)V", false);
longInitMethod = getMethodID(longClass, "<init>", "(J)V", false);
numberDoubleValueMethod = getMethodID(numberClass, "doubleValue", "()D", false);
v8ObjectInitMethod = getMethodID(v8ObjectClass, "<init>", "(J)V", false);
managedV8ReferencePtrField = getFieldID(managedV8ReferenceClass, "ptr", "J");
krollProxyCreateMethod = getMethodID(krollProxyClass, "create",
"(Ljava/lang/Class;[Ljava/lang/Object;JLjava/lang/String;)Lorg/appcelerator/kroll/KrollProxy;", true);
assetsReadResourceMethod = getMethodID(assetsClass, "readResource", "(Ljava/lang/String;)[C", true);
eventListenerPostEventMethod = getMethodID(eventListenerClass, "postEvent",
"(Ljava/util/HashMap;)V", false);
v8FunctionInitMethod = getMethodID(v8FunctionClass, "<init>", "(J)V", false);
}
}
| fix constructor signature for v8FunctionInitMethod | fix constructor signature for v8FunctionInitMethod
| C++ | apache-2.0 | collinprice/titanium_mobile,jhaynie/titanium_mobile,openbaoz/titanium_mobile,FokkeZB/titanium_mobile,FokkeZB/titanium_mobile,KoketsoMabuela92/titanium_mobile,hieupham007/Titanium_Mobile,formalin14/titanium_mobile,jhaynie/titanium_mobile,falkolab/titanium_mobile,benbahrenburg/titanium_mobile,bhatfield/titanium_mobile,indera/titanium_mobile,emilyvon/titanium_mobile,formalin14/titanium_mobile,linearhub/titanium_mobile,cheekiatng/titanium_mobile,AngelkPetkov/titanium_mobile,sriks/titanium_mobile,taoger/titanium_mobile,pinnamur/titanium_mobile,shopmium/titanium_mobile,collinprice/titanium_mobile,KoketsoMabuela92/titanium_mobile,pinnamur/titanium_mobile,cheekiatng/titanium_mobile,csg-coder/titanium_mobile,benbahrenburg/titanium_mobile,peymanmortazavi/titanium_mobile,AngelkPetkov/titanium_mobile,rblalock/titanium_mobile,AngelkPetkov/titanium_mobile,smit1625/titanium_mobile,indera/titanium_mobile,falkolab/titanium_mobile,kopiro/titanium_mobile,rblalock/titanium_mobile,prop/titanium_mobile,perdona/titanium_mobile,smit1625/titanium_mobile,bhatfield/titanium_mobile,mano-mykingdom/titanium_mobile,KangaCoders/titanium_mobile,linearhub/titanium_mobile,KangaCoders/titanium_mobile,FokkeZB/titanium_mobile,KangaCoders/titanium_mobile,jvkops/titanium_mobile,rblalock/titanium_mobile,peymanmortazavi/titanium_mobile,falkolab/titanium_mobile,taoger/titanium_mobile,csg-coder/titanium_mobile,ashcoding/titanium_mobile,kopiro/titanium_mobile,prop/titanium_mobile,pinnamur/titanium_mobile,openbaoz/titanium_mobile,collinprice/titanium_mobile,pinnamur/titanium_mobile,mvitr/titanium_mobile,hieupham007/Titanium_Mobile,rblalock/titanium_mobile,cheekiatng/titanium_mobile,formalin14/titanium_mobile,bhatfield/titanium_mobile,bright-sparks/titanium_mobile,bright-sparks/titanium_mobile,openbaoz/titanium_mobile,bright-sparks/titanium_mobile,jhaynie/titanium_mobile,openbaoz/titanium_mobile,jvkops/titanium_mobile,mano-mykingdom/titanium_mobile,jhaynie/titanium_mobile,FokkeZB/titanium_mobile,smit1625/titanium_mobile,collinprice/titanium_mobile,mvitr/titanium_mobile,pec1985/titanium_mobile,KoketsoMabuela92/titanium_mobile,jvkops/titanium_mobile,prop/titanium_mobile,csg-coder/titanium_mobile,perdona/titanium_mobile,kopiro/titanium_mobile,kopiro/titanium_mobile,collinprice/titanium_mobile,bright-sparks/titanium_mobile,falkolab/titanium_mobile,taoger/titanium_mobile,linearhub/titanium_mobile,KoketsoMabuela92/titanium_mobile,rblalock/titanium_mobile,prop/titanium_mobile,mano-mykingdom/titanium_mobile,kopiro/titanium_mobile,AngelkPetkov/titanium_mobile,mvitr/titanium_mobile,KoketsoMabuela92/titanium_mobile,collinprice/titanium_mobile,pec1985/titanium_mobile,bhatfield/titanium_mobile,jvkops/titanium_mobile,pec1985/titanium_mobile,cheekiatng/titanium_mobile,pinnamur/titanium_mobile,openbaoz/titanium_mobile,sriks/titanium_mobile,emilyvon/titanium_mobile,KangaCoders/titanium_mobile,KangaCoders/titanium_mobile,jvkops/titanium_mobile,falkolab/titanium_mobile,emilyvon/titanium_mobile,csg-coder/titanium_mobile,hieupham007/Titanium_Mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,sriks/titanium_mobile,pinnamur/titanium_mobile,csg-coder/titanium_mobile,cheekiatng/titanium_mobile,AngelkPetkov/titanium_mobile,csg-coder/titanium_mobile,pec1985/titanium_mobile,perdona/titanium_mobile,peymanmortazavi/titanium_mobile,ashcoding/titanium_mobile,linearhub/titanium_mobile,emilyvon/titanium_mobile,bhatfield/titanium_mobile,FokkeZB/titanium_mobile,bright-sparks/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,linearhub/titanium_mobile,smit1625/titanium_mobile,falkolab/titanium_mobile,benbahrenburg/titanium_mobile,smit1625/titanium_mobile,peymanmortazavi/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,openbaoz/titanium_mobile,hieupham007/Titanium_Mobile,ashcoding/titanium_mobile,mvitr/titanium_mobile,jvkops/titanium_mobile,bhatfield/titanium_mobile,jhaynie/titanium_mobile,shopmium/titanium_mobile,pec1985/titanium_mobile,formalin14/titanium_mobile,KangaCoders/titanium_mobile,taoger/titanium_mobile,benbahrenburg/titanium_mobile,csg-coder/titanium_mobile,KoketsoMabuela92/titanium_mobile,ashcoding/titanium_mobile,shopmium/titanium_mobile,indera/titanium_mobile,ashcoding/titanium_mobile,prop/titanium_mobile,FokkeZB/titanium_mobile,hieupham007/Titanium_Mobile,sriks/titanium_mobile,pec1985/titanium_mobile,KoketsoMabuela92/titanium_mobile,ashcoding/titanium_mobile,prop/titanium_mobile,smit1625/titanium_mobile,bright-sparks/titanium_mobile,openbaoz/titanium_mobile,FokkeZB/titanium_mobile,benbahrenburg/titanium_mobile,pec1985/titanium_mobile,linearhub/titanium_mobile,linearhub/titanium_mobile,hieupham007/Titanium_Mobile,perdona/titanium_mobile,indera/titanium_mobile,taoger/titanium_mobile,kopiro/titanium_mobile,indera/titanium_mobile,pinnamur/titanium_mobile,formalin14/titanium_mobile,hieupham007/Titanium_Mobile,kopiro/titanium_mobile,bhatfield/titanium_mobile,pinnamur/titanium_mobile,KoketsoMabuela92/titanium_mobile,AngelkPetkov/titanium_mobile,peymanmortazavi/titanium_mobile,KangaCoders/titanium_mobile,indera/titanium_mobile,bhatfield/titanium_mobile,prop/titanium_mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,rblalock/titanium_mobile,csg-coder/titanium_mobile,kopiro/titanium_mobile,emilyvon/titanium_mobile,perdona/titanium_mobile,perdona/titanium_mobile,indera/titanium_mobile,taoger/titanium_mobile,mvitr/titanium_mobile,collinprice/titanium_mobile,benbahrenburg/titanium_mobile,jhaynie/titanium_mobile,AngelkPetkov/titanium_mobile,rblalock/titanium_mobile,jvkops/titanium_mobile,mvitr/titanium_mobile,FokkeZB/titanium_mobile,prop/titanium_mobile,pec1985/titanium_mobile,smit1625/titanium_mobile,rblalock/titanium_mobile,perdona/titanium_mobile,sriks/titanium_mobile,jhaynie/titanium_mobile,collinprice/titanium_mobile,taoger/titanium_mobile,jhaynie/titanium_mobile,emilyvon/titanium_mobile,formalin14/titanium_mobile,mano-mykingdom/titanium_mobile,taoger/titanium_mobile,sriks/titanium_mobile,cheekiatng/titanium_mobile,hieupham007/Titanium_Mobile,mvitr/titanium_mobile,peymanmortazavi/titanium_mobile,sriks/titanium_mobile,peymanmortazavi/titanium_mobile,linearhub/titanium_mobile,cheekiatng/titanium_mobile,bright-sparks/titanium_mobile,smit1625/titanium_mobile,formalin14/titanium_mobile,KangaCoders/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,jvkops/titanium_mobile,formalin14/titanium_mobile,emilyvon/titanium_mobile,sriks/titanium_mobile,pinnamur/titanium_mobile,shopmium/titanium_mobile,ashcoding/titanium_mobile,openbaoz/titanium_mobile,AngelkPetkov/titanium_mobile,pec1985/titanium_mobile,shopmium/titanium_mobile,falkolab/titanium_mobile,falkolab/titanium_mobile,indera/titanium_mobile,cheekiatng/titanium_mobile,benbahrenburg/titanium_mobile,perdona/titanium_mobile,emilyvon/titanium_mobile,benbahrenburg/titanium_mobile,mano-mykingdom/titanium_mobile |
cc70c3b454a722083b92546ee092104da5317455 | tensorflow/core/util/use_cudnn.cc | tensorflow/core/util/use_cudnn.cc | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/util/use_cudnn.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/env_var.h"
#if GOOGLE_CUDA
#include "third_party/gpus/cudnn/cudnn.h"
#endif // GOOGLE_CUDA
namespace tensorflow {
#define ADD_BOOL_CUDNN_FLAG(func_name, flag_name, default_value) \
bool func_name() { \
bool value = default_value; \
Status status = ReadBoolFromEnvVar(#flag_name, default_value, &value); \
if (!status.ok()) { \
LOG(ERROR) << status; \
} \
return value; \
}
bool CudnnUseFrontend() {
#if GOOGLE_CUDA && CUDNN_VERSION >= 8100
static bool result = [] {
bool value = false;
Status status = ReadBoolFromEnvVar("TF_CUDNN_USE_FRONTEND", false, &value);
if (!status.ok()) {
LOG(ERROR) << status;
}
return value;
}();
return result;
#else
return false;
#endif // GOOGLE_CUDA && CUDNN_VERSION >= 8100
}
ADD_BOOL_CUDNN_FLAG(CudnnUseAutotune, TF_CUDNN_USE_AUTOTUNE, true);
// Whether to auto-tuning Cudnn RNN forward and backward pass to pick
// statistically the best cudnnRNNAlgo_t and cudnnMathType_t.
// The flag is disabled when TF_DEBUG_CUDNN_RNN is turned on.
ADD_BOOL_CUDNN_FLAG(CudnnRnnUseAutotune, TF_CUDNN_RNN_USE_AUTOTUNE, true);
ADD_BOOL_CUDNN_FLAG(CudnnDisableConv1x1Optimization,
TF_CUDNN_DISABLE_CONV_1X1_OPTIMIZATION, false);
// Whether to run Cudnn RNN forward and backward in debug mode, where users can
// force a specified cudnnRNNAlgo_t and cudnnMathType_t, when used together with
// the following two env vars:
// TF_DEBUG_CUDNN_RNN_USE_TENSOR_OPS
// TF_DEBUG_CUDNN_RNN_ALGO
// By default it is disabled and only intended for testing and profiling.
ADD_BOOL_CUDNN_FLAG(DebugCudnnRnn, TF_DEBUG_CUDNN_RNN, false);
// If using TENSOR_OP_MATH in Cudnn RNN for both forward and backward pass. Only
// effective when TF_DEBUG_CUDNN_RNN is true.
// Note none of the persistent RNN algorithm support TENSOR_OP_MATH before
// Cudnn 7.1. See Nvidia Cudnn manual for more details.
ADD_BOOL_CUDNN_FLAG(DebugCudnnRnnUseTensorOps,
TF_DEBUG_CUDNN_RNN_USE_TENSOR_OPS, false);
#undef ADD_BOOL_CUDNN_FLAG
#define ADD_INT64_CUDNN_FLAG(func_name, flag_name, default_value) \
int64 func_name() { \
int64 value = default_value; \
Status status = ReadInt64FromEnvVar(#flag_name, default_value, &value); \
if (!status.ok()) { \
LOG(ERROR) << status; \
} \
return value; \
}
// Cudnn RNN algorithm to use for both forward and backward pass. Only effective
// when TF_DEBUG_CUDNN_RNN is true. See Nvidia Cudnn manual for allowed
// cudnnRNNAlgo_t.
ADD_INT64_CUDNN_FLAG(DebugCudnnRnnAlgo, TF_DEBUG_CUDNN_RNN_ALGO, -1);
#undef ADD_INT64_CUDNN_FLAG
bool IsCudnnSupportedFilterSize(const int32 filter_rows,
const int32 filter_cols, const int32 in_depth,
const int32 out_depth) {
return in_depth == out_depth && filter_rows == filter_cols &&
(filter_rows == 1 || filter_rows == 3 || filter_rows == 5 ||
filter_rows == 7);
}
} // namespace tensorflow
| /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/util/use_cudnn.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/env_var.h"
#if GOOGLE_CUDA
#include "third_party/gpus/cudnn/cudnn.h"
#endif // GOOGLE_CUDA
namespace tensorflow {
#define ADD_BOOL_CUDNN_FLAG(func_name, flag_name, default_value) \
bool func_name() { \
bool value = default_value; \
Status status = ReadBoolFromEnvVar(#flag_name, default_value, &value); \
if (!status.ok()) { \
LOG(ERROR) << status; \
} \
return value; \
}
bool CudnnUseFrontend() {
static bool result = [] {
bool value = false;
#if GOOGLE_CUDA && CUDNN_VERSION >= 8100
Status status = ReadBoolFromEnvVar("TF_CUDNN_USE_FRONTEND", false, &value);
if (!status.ok()) {
LOG(ERROR) << status;
}
#endif // GOOGLE_CUDA && CUDNN_VERSION >= 8100
return value;
}();
return result;
}
ADD_BOOL_CUDNN_FLAG(CudnnUseAutotune, TF_CUDNN_USE_AUTOTUNE, true);
// Whether to auto-tuning Cudnn RNN forward and backward pass to pick
// statistically the best cudnnRNNAlgo_t and cudnnMathType_t.
// The flag is disabled when TF_DEBUG_CUDNN_RNN is turned on.
ADD_BOOL_CUDNN_FLAG(CudnnRnnUseAutotune, TF_CUDNN_RNN_USE_AUTOTUNE, true);
ADD_BOOL_CUDNN_FLAG(CudnnDisableConv1x1Optimization,
TF_CUDNN_DISABLE_CONV_1X1_OPTIMIZATION, false);
// Whether to run Cudnn RNN forward and backward in debug mode, where users can
// force a specified cudnnRNNAlgo_t and cudnnMathType_t, when used together with
// the following two env vars:
// TF_DEBUG_CUDNN_RNN_USE_TENSOR_OPS
// TF_DEBUG_CUDNN_RNN_ALGO
// By default it is disabled and only intended for testing and profiling.
ADD_BOOL_CUDNN_FLAG(DebugCudnnRnn, TF_DEBUG_CUDNN_RNN, false);
// If using TENSOR_OP_MATH in Cudnn RNN for both forward and backward pass. Only
// effective when TF_DEBUG_CUDNN_RNN is true.
// Note none of the persistent RNN algorithm support TENSOR_OP_MATH before
// Cudnn 7.1. See Nvidia Cudnn manual for more details.
ADD_BOOL_CUDNN_FLAG(DebugCudnnRnnUseTensorOps,
TF_DEBUG_CUDNN_RNN_USE_TENSOR_OPS, false);
#undef ADD_BOOL_CUDNN_FLAG
#define ADD_INT64_CUDNN_FLAG(func_name, flag_name, default_value) \
int64 func_name() { \
int64 value = default_value; \
Status status = ReadInt64FromEnvVar(#flag_name, default_value, &value); \
if (!status.ok()) { \
LOG(ERROR) << status; \
} \
return value; \
}
// Cudnn RNN algorithm to use for both forward and backward pass. Only effective
// when TF_DEBUG_CUDNN_RNN is true. See Nvidia Cudnn manual for allowed
// cudnnRNNAlgo_t.
ADD_INT64_CUDNN_FLAG(DebugCudnnRnnAlgo, TF_DEBUG_CUDNN_RNN_ALGO, -1);
#undef ADD_INT64_CUDNN_FLAG
bool IsCudnnSupportedFilterSize(const int32 filter_rows,
const int32 filter_cols, const int32 in_depth,
const int32 out_depth) {
return in_depth == out_depth && filter_rows == filter_cols &&
(filter_rows == 1 || filter_rows == 3 || filter_rows == 5 ||
filter_rows == 7);
}
} // namespace tensorflow
| Update the lambda func | Update the lambda func
| C++ | apache-2.0 | tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,sarvex/tensorflow,sarvex/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,sarvex/tensorflow,Intel-Corporation/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,Intel-Corporation/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,yongtang/tensorflow,karllessard/tensorflow,tensorflow/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,paolodedios/tensorflow |
0e838c3cea0db3babf2694e3798045e0d8a37a87 | fpga_interchange/xdc.cc | fpga_interchange/xdc.cc | /*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2019 gatecat <[email protected]>
* Copyright (C) 2021 Symbiflow Authors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "xdc.h"
#include <string>
#include "context.h"
#include "log.h"
// Include tcl.h late because it messed with #define's and lets them leave the
// scope of the header.
#include <tcl.h>
NEXTPNR_NAMESPACE_BEGIN
static int obj_set_from_any(Tcl_Interp *interp, Tcl_Obj *objPtr) { return TCL_ERROR; }
static void set_tcl_obj_string(Tcl_Obj *objPtr, const std::string &s)
{
NPNR_ASSERT(objPtr->bytes == nullptr);
// Need to have space for the end null byte.
objPtr->bytes = Tcl_Alloc(s.size() + 1);
// Length is length of string, not including the end null byte.
objPtr->length = s.size();
std::copy(s.begin(), s.end(), objPtr->bytes);
objPtr->bytes[objPtr->length] = '\0';
}
static void port_update_string(Tcl_Obj *objPtr)
{
const Context *ctx = static_cast<const Context *>(objPtr->internalRep.twoPtrValue.ptr1);
PortInfo *port_info = static_cast<PortInfo *>(objPtr->internalRep.twoPtrValue.ptr2);
std::string port_name = port_info->name.str(ctx);
set_tcl_obj_string(objPtr, port_name);
}
static void cell_update_string(Tcl_Obj *objPtr)
{
const Context *ctx = static_cast<const Context *>(objPtr->internalRep.twoPtrValue.ptr1);
CellInfo *cell_info = static_cast<CellInfo *>(objPtr->internalRep.twoPtrValue.ptr2);
std::string cell_name = cell_info->name.str(ctx);
set_tcl_obj_string(objPtr, cell_name);
}
static void obj_dup(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr)
{
dupPtr->internalRep.twoPtrValue = srcPtr->internalRep.twoPtrValue;
}
static void obj_free(Tcl_Obj *objPtr) {}
static void Tcl_SetStringResult(Tcl_Interp *interp, const std::string &s)
{
char *copy = Tcl_Alloc(s.size() + 1);
std::copy(s.begin(), s.end(), copy);
copy[s.size()] = '\0';
Tcl_SetResult(interp, copy, TCL_DYNAMIC);
}
static Tcl_ObjType port_object = {
"port", obj_free, obj_dup, port_update_string, obj_set_from_any,
};
static Tcl_ObjType cell_object = {
"cell", obj_free, obj_dup, cell_update_string, obj_set_from_any,
};
static int get_ports(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
const Context *ctx = static_cast<const Context *>(data);
if (objc == 1) {
// Return list of all ports.
Tcl_SetStringResult(interp, "Unimplemented");
return TCL_ERROR;
} else if (objc == 2) {
const char *arg0 = Tcl_GetString(objv[1]);
IdString port_name = ctx->id(arg0);
auto iter = ctx->ports.find(port_name);
if (iter == ctx->ports.end()) {
Tcl_SetStringResult(interp, "Could not find port " + port_name.str(ctx));
return TCL_ERROR;
}
Tcl_Obj *result = Tcl_NewObj();
result->typePtr = &port_object;
result->internalRep.twoPtrValue.ptr1 = (void *)(ctx);
result->internalRep.twoPtrValue.ptr2 = (void *)(&iter->second);
result->bytes = nullptr;
port_update_string(result);
Tcl_SetObjResult(interp, result);
return TCL_OK;
} else {
return TCL_ERROR;
}
}
static int get_cells(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
const Context *ctx = static_cast<const Context *>(data);
if (objc == 1) {
// Return list of all ports.
Tcl_SetStringResult(interp, "Unimplemented");
return TCL_ERROR;
} else if (objc == 2) {
const char *arg0 = Tcl_GetString(objv[1]);
IdString cell_name = ctx->id(arg0);
auto iter = ctx->cells.find(cell_name);
if (iter == ctx->cells.end()) {
Tcl_SetStringResult(interp, "Could not find cell " + cell_name.str(ctx));
return TCL_ERROR;
}
Tcl_Obj *result = Tcl_NewObj();
result->typePtr = &cell_object;
result->internalRep.twoPtrValue.ptr1 = (void *)(ctx);
result->internalRep.twoPtrValue.ptr2 = (void *)(iter->second.get());
result->bytes = nullptr;
cell_update_string(result);
Tcl_SetObjResult(interp, result);
return TCL_OK;
} else {
return TCL_ERROR;
}
}
static int set_property(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
// set_property <property> <value> <object>
if (objc != 4) {
Tcl_SetStringResult(interp, "Only simple 'set_property <property> <value> <object>' is supported");
return TCL_ERROR;
}
const char *property = Tcl_GetString(objv[1]);
const char *value = Tcl_GetString(objv[2]);
const Tcl_Obj *object = objv[3];
if (object->typePtr == &port_object) {
const Context *ctx = static_cast<const Context *>(object->internalRep.twoPtrValue.ptr1);
PortInfo *port_info = static_cast<PortInfo *>(object->internalRep.twoPtrValue.ptr2);
NPNR_ASSERT(port_info->net != nullptr);
CellInfo *cell = ctx->port_cells.at(port_info->name);
cell->attrs[ctx->id(property)] = Property(value);
} else if (object->typePtr == &cell_object) {
const Context *ctx = static_cast<const Context *>(object->internalRep.twoPtrValue.ptr1);
CellInfo *cell = static_cast<CellInfo *>(object->internalRep.twoPtrValue.ptr2);
cell->attrs[ctx->id(property)] = Property(value);
} else {
return TCL_ERROR;
}
return TCL_OK;
}
TclInterp::TclInterp(Context *ctx)
{
interp = Tcl_CreateInterp();
NPNR_ASSERT(Tcl_Init(interp) == TCL_OK);
Tcl_RegisterObjType(&port_object);
NPNR_ASSERT(Tcl_Eval(interp, "rename unknown _original_unknown") == TCL_OK);
NPNR_ASSERT(Tcl_Eval(interp, "proc unknown args {\n"
" set result [scan [lindex $args 0] \"%d\" value]\n"
" if { $result == 1 && [llength $args] == 1 } {\n"
" return \\[$value\\]\n"
" } else {\n"
" uplevel 1 [list _original_unknown {*}$args]\n"
" }\n"
"}") == TCL_OK);
Tcl_CreateObjCommand(interp, "get_ports", get_ports, ctx, nullptr);
Tcl_CreateObjCommand(interp, "get_cells", get_cells, ctx, nullptr);
Tcl_CreateObjCommand(interp, "set_property", set_property, ctx, nullptr);
}
TclInterp::~TclInterp() { Tcl_DeleteInterp(interp); }
NEXTPNR_NAMESPACE_END
| /*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2019 gatecat <[email protected]>
* Copyright (C) 2021 Symbiflow Authors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "xdc.h"
#include <string>
#include "context.h"
#include "log.h"
// Include tcl.h late because it messed with #define's and lets them leave the
// scope of the header.
#include <tcl.h>
NEXTPNR_NAMESPACE_BEGIN
static int obj_set_from_any(Tcl_Interp *interp, Tcl_Obj *objPtr) { return TCL_ERROR; }
static void set_tcl_obj_string(Tcl_Obj *objPtr, const std::string &s)
{
NPNR_ASSERT(objPtr->bytes == nullptr);
// Need to have space for the end null byte.
objPtr->bytes = Tcl_Alloc(s.size() + 1);
// Length is length of string, not including the end null byte.
objPtr->length = s.size();
std::copy(s.begin(), s.end(), objPtr->bytes);
objPtr->bytes[objPtr->length] = '\0';
}
static void port_update_string(Tcl_Obj *objPtr)
{
const Context *ctx = static_cast<const Context *>(objPtr->internalRep.twoPtrValue.ptr1);
PortInfo *port_info = static_cast<PortInfo *>(objPtr->internalRep.twoPtrValue.ptr2);
std::string port_name = port_info->name.str(ctx);
set_tcl_obj_string(objPtr, port_name);
}
static void cell_update_string(Tcl_Obj *objPtr)
{
const Context *ctx = static_cast<const Context *>(objPtr->internalRep.twoPtrValue.ptr1);
CellInfo *cell_info = static_cast<CellInfo *>(objPtr->internalRep.twoPtrValue.ptr2);
std::string cell_name = cell_info->name.str(ctx);
set_tcl_obj_string(objPtr, cell_name);
}
static void obj_dup(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr)
{
dupPtr->internalRep.twoPtrValue = srcPtr->internalRep.twoPtrValue;
}
static void obj_free(Tcl_Obj *objPtr) {}
static void Tcl_SetStringResult(Tcl_Interp *interp, const std::string &s)
{
char *copy = Tcl_Alloc(s.size() + 1);
std::copy(s.begin(), s.end(), copy);
copy[s.size()] = '\0';
Tcl_SetResult(interp, copy, TCL_DYNAMIC);
}
static Tcl_ObjType port_object = {
"port", obj_free, obj_dup, port_update_string, obj_set_from_any,
};
static Tcl_ObjType cell_object = {
"cell", obj_free, obj_dup, cell_update_string, obj_set_from_any,
};
static int get_ports(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
const Context *ctx = static_cast<const Context *>(data);
if (objc == 1) {
// Return list of all ports.
Tcl_SetStringResult(interp, "Unimplemented");
return TCL_ERROR;
} else if (objc == 2) {
const char *arg0 = Tcl_GetString(objv[1]);
IdString port_name = ctx->id(arg0);
auto iter = ctx->ports.find(port_name);
if (iter == ctx->ports.end()) {
Tcl_SetStringResult(interp, "Could not find port " + port_name.str(ctx));
return TCL_ERROR;
}
Tcl_Obj *result = Tcl_NewObj();
result->typePtr = &port_object;
result->internalRep.twoPtrValue.ptr1 = (void *)(ctx);
result->internalRep.twoPtrValue.ptr2 = (void *)(&iter->second);
result->bytes = nullptr;
port_update_string(result);
Tcl_SetObjResult(interp, result);
return TCL_OK;
} else {
return TCL_ERROR;
}
}
static int get_cells(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
const Context *ctx = static_cast<const Context *>(data);
if (objc == 1) {
// Return list of all ports.
Tcl_SetStringResult(interp, "Unimplemented");
return TCL_ERROR;
} else if (objc == 2) {
const char *arg0 = Tcl_GetString(objv[1]);
IdString cell_name = ctx->id(arg0);
auto iter = ctx->cells.find(cell_name);
if (iter == ctx->cells.end()) {
Tcl_SetStringResult(interp, "Could not find cell " + cell_name.str(ctx));
return TCL_ERROR;
}
Tcl_Obj *result = Tcl_NewObj();
result->typePtr = &cell_object;
result->internalRep.twoPtrValue.ptr1 = (void *)(ctx);
result->internalRep.twoPtrValue.ptr2 = (void *)(iter->second.get());
result->bytes = nullptr;
cell_update_string(result);
Tcl_SetObjResult(interp, result);
return TCL_OK;
} else {
return TCL_ERROR;
}
}
static int set_property(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
// set_property <property> <value> <object>
if (objc != 4) {
Tcl_SetStringResult(interp, "Only simple 'set_property <property> <value> <object>' is supported");
return TCL_ERROR;
}
const char *property = Tcl_GetString(objv[1]);
const char *value = Tcl_GetString(objv[2]);
const Tcl_Obj *object = objv[3];
if (object->typePtr == &port_object) {
const Context *ctx = static_cast<const Context *>(object->internalRep.twoPtrValue.ptr1);
PortInfo *port_info = static_cast<PortInfo *>(object->internalRep.twoPtrValue.ptr2);
NPNR_ASSERT(port_info->net != nullptr);
CellInfo *cell = ctx->port_cells.at(port_info->name);
cell->attrs[ctx->id(property)] = Property(value);
} else if (object->typePtr == &cell_object) {
const Context *ctx = static_cast<const Context *>(object->internalRep.twoPtrValue.ptr1);
CellInfo *cell = static_cast<CellInfo *>(object->internalRep.twoPtrValue.ptr2);
cell->attrs[ctx->id(property)] = Property(value);
} else {
return TCL_ERROR;
}
return TCL_OK;
}
static int create_clock(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
// FIXME: add implementation
return TCL_OK;
}
TclInterp::TclInterp(Context *ctx)
{
interp = Tcl_CreateInterp();
NPNR_ASSERT(Tcl_Init(interp) == TCL_OK);
Tcl_RegisterObjType(&port_object);
NPNR_ASSERT(Tcl_Eval(interp, "rename unknown _original_unknown") == TCL_OK);
NPNR_ASSERT(Tcl_Eval(interp, "proc unknown args {\n"
" set result [scan [lindex $args 0] \"%d\" value]\n"
" if { $result == 1 && [llength $args] == 1 } {\n"
" return \\[$value\\]\n"
" } else {\n"
" uplevel 1 [list _original_unknown {*}$args]\n"
" }\n"
"}") == TCL_OK);
Tcl_CreateObjCommand(interp, "get_ports", get_ports, ctx, nullptr);
Tcl_CreateObjCommand(interp, "get_cells", get_cells, ctx, nullptr);
Tcl_CreateObjCommand(interp, "set_property", set_property, ctx, nullptr);
Tcl_CreateObjCommand(interp, "create_clock", create_clock, ctx, nullptr);
}
TclInterp::~TclInterp() { Tcl_DeleteInterp(interp); }
NEXTPNR_NAMESPACE_END
| Add dummy function to parse creat_clock in XDC files | Add dummy function to parse creat_clock in XDC files
Signed-off-by: Maciej Dudek <[email protected]>
| C++ | isc | SymbiFlow/nextpnr,SymbiFlow/nextpnr,YosysHQ/nextpnr,SymbiFlow/nextpnr,YosysHQ/nextpnr,YosysHQ/nextpnr,YosysHQ/nextpnr,SymbiFlow/nextpnr |
242858b76779e01034087019110c5bc6b705d0de | src/GrayScott.cpp | src/GrayScott.cpp | #include <map>
#include <vector>
#include "GrayScott.h"
#include "Drawer.h"
#include "Util.h"
#include <algorithm>
#define MAX_ROLLING_MULTIPLIER (2.0 / (35 * 5 + 1))
#define NUM_INIT_ISLANDS 5
#define ISLAND_SIZE 20
#define MAX_SPEED 40 // determined empirically to allow 30fps
#ifdef __arm__
#define vmul(x, y) vmulq_f32(x, y)
#define vadd(x, y) vaddq_f32(x, y)
#define vsub(x, y) vsubq_f32(x, y)
#define vdup(x) vdupq_n_f32(x)
#define vld(x) vld1q_f32(x)
#define vst(x, y) vst1q_f32(x, y)
#define vprint(name, v) { GSType arr[VEC_N]; vst1q_f32(arr, v); std::cout << name << ": "; for (size_t i=0; i < VEC_N; ++i) { std::cout << arr[i] << " "; }; std::cout << std::endl; }
#endif
GrayScottDrawer::GrayScottDrawer(int width, int height, int palSize)
: Drawer("GrayScott", width, height, palSize), m_colorIndex(0) {
m_settings.insert(std::make_pair("speed",10));
m_settings.insert(std::make_pair("colorSpeed",0));
m_settings.insert(std::make_pair("params",1));
m_settingsRanges.insert(std::make_pair("speed", std::make_pair(5,10)));
m_settingsRanges.insert(std::make_pair("colorSpeed", std::make_pair(0,0)));
m_settingsRanges.insert(std::make_pair("params", std::make_pair(0,8)));
for (size_t q = 0; q < 2; ++q) {
m_u[q] = new Array2D<GSType>(width, height);
m_v[q] = new Array2D<GSType>(width, height);
}
m_q = true;
m_lastMaxV = 0.5;
reset();
}
GrayScottDrawer::~GrayScottDrawer() {
for (size_t q = 0; q < 2; ++q) {
delete[] m_u[q];
delete[] m_v[q];
}
}
void GrayScottDrawer::reset() {
for (size_t q = 0; q < 2; ++q) {
for (size_t i = 0; i < m_width * m_height; ++i) {
m_u[q]->get(i) = 1.0;
m_v[q]->get(i) = 0.0;
}
}
for (size_t i = 0; i < NUM_INIT_ISLANDS; ++i) {
size_t ix = random2() % (m_width - ISLAND_SIZE);
size_t iy = random2() % (m_height - ISLAND_SIZE);
for (size_t x = ix; x < ix + ISLAND_SIZE; ++x) {
for (size_t y = iy; y < iy + ISLAND_SIZE; ++y) {
size_t index = x + y * m_width;
m_u[m_q]->get(index) = 0.5;
m_v[m_q]->get(index) = 0.25;
}
}
}
// params from http://mrob.com/pub/comp/xmorphia
GSType F, k, scale;
switch(m_settings["params"]) {
case 0:
F = 0.022;
k = 0.049;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 1:
F = 0.026;
k = 0.051;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 2:
F = 0.026;
k = 0.052;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 3:
F = 0.022;
k = 0.048;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 4:
F = 0.018;
k = 0.045;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 5:
F = 0.010;
k = 0.033;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
// sometimes end quickly on smaller panels
case 6:
F = 0.014;
k = 0.041;
scale = std::exp(randomFloat(std::log(0.5), std::log(5)));
break;
case 7:
F = 0.006;
k = 0.045;
scale = std::exp(randomFloat(std::log(0.6), std::log(5)));
break;
case 8:
F = 0.010;
k = 0.047;
scale = std::exp(randomFloat(std::log(0.5), std::log(5)));
break;
// case 9:
// m_F = 0.006;
// m_k = 0.043;
// m_scale = std::exp(randomFloat(std::log(0.6), std::log(6)));
// break;
}
m_scale = scale;
m_du = 0.08 * m_scale;
m_dv = 0.04 * m_scale;
m_dt = 1 / m_scale;
m_F = F;
m_k = k;
m_speed = std::min((size_t)MAX_SPEED, (size_t)(m_settings["speed"] * m_scale));
std::cout << "GrayScott with param set #" << m_settings["params"] <<
std::setprecision(4) << " F=" << F << " k=" << k << " scale=" << m_scale <<
" total speed=" << m_speed << std::endl;
}
#ifdef __arm__
template <bool CHECK_BOUNDS>
inline
GSTypeN laplacian(const Array2D<GSType> *arr, int x, int y, const GSTypeN& curr) {
const GSType* raw = arr->rawData();
size_t w = arr->width();
size_t h = arr->height();
size_t index = x + y * w;
const GSType* pos = raw + index;
GSTypeN left, right, top, bottom;
GSTypeN fourN = vdup(4);
if (CHECK_BOUNDS) {
GSTypeN sum;
left = vld(raw + y * w + (x - 1 + w) % w);
right = vld(raw + y * w + (x + 1) % w);
top = vld(raw + ((y - 1 + h) % h) * w + x);
bottom = vld(raw + ((y + 1) % h) * w + x);
sum = vadd(left, right);
sum = vadd(sum, bottom);
sum = vadd(sum, top);
sum = vsub(sum, vmul(curr, fourN));
return sum;
} else {
GSTypeN sum;
left = vld(pos - 1);
right = vld(pos + 1);
top = vld(pos - w);
bottom = vld(pos + w);
sum = vadd(left, right);
sum = vadd(sum, bottom);
sum = vadd(sum, top);
sum = vsub(sum, vmul(curr, fourN));
return sum;
}
}
template <bool CHECK_BOUNDS>
inline
void updateUV(Array2D<GSType> *u[], Array2D<GSType> *v[],
bool q, size_t x, size_t y,
const GSTypeN& dt, const GSTypeN& du,
const GSTypeN& dv, const GSTypeN& F,
const GSTypeN& F_k) {
const GSType* uIn = u[q]->rawData();
const GSType* vIn = v[q]->rawData();
GSType* uOut = u[1-q]->rawData();
GSType* vOut = v[1-q]->rawData();
size_t index = y * u[q]->width() + x;
GSTypeN currU = vld(uIn + index);
GSTypeN currV = vld(vIn + index);
GSTypeN oneN = vdup(1);
// get vector of floats for laplacian transform
GSTypeN d2u = laplacian<CHECK_BOUNDS>(u[q], x, y, currU);
GSTypeN d2v = laplacian<CHECK_BOUNDS>(v[q], x, y, currV);
// uvv = u*v*v
GSTypeN uvv = vmul(currU, vmul(currV, currV));
// uOut[curr] = u + dt * du * d2u;
// uOut[curr] += dt * (-d2 + F * (1 - u));
GSTypeN uRD = vadd(currU, vmul(vmul(dt, du), d2u));
uRD = vadd(uRD, vmul(dt, vsub(vmul(F, vsub(oneN, currU)), uvv)));
vst(uOut + index, uRD);
// vOut[curr] = v + dt * dv * d2v;
// vOut[curr] += dt * (d2 - (F + k) * v);
GSTypeN vRD = vadd(currV, vmul(vmul(dt, dv), d2v));
vRD = vadd(vRD, vmul(dt, vsub(uvv, vmul(F_k, currV))));
vst(vOut + index, vRD);
}
void GrayScottDrawer::draw(int* colIndices) {
Drawer::draw(colIndices);
GSType zoom = 1;
GSTypeN dt = vdup(m_dt);
GSTypeN du = vdup(m_du);
GSTypeN dv = vdup(m_dv);
GSTypeN F = vdup(m_F);
GSTypeN F_k = vadd(F, vdup(m_k));
for (size_t f = 0; f < m_speed; ++f) {
// std::cout << *m_v[m_q] << std::endl;
for (size_t y = 1; y < m_height - 1; ++y) {
for (size_t x = VEC_N; x < m_width - VEC_N; x += VEC_N) {
updateUV<false>(m_u, m_v, m_q, x, y, dt, du, dv, F, F_k);
}
}
// borders are a special case
for (size_t y = 0; y < m_height; y += m_height - 1) {
for (size_t x = 0; x < m_width; x += VEC_N) {
updateUV<true>(m_u, m_v, m_q, x, y, dt, du, dv, F, F_k);
}
}
for (size_t y = 0; y < m_height; y += 1) {
for (size_t x = 0; x < m_width; x += m_width - VEC_N) {
updateUV<true>(m_u, m_v, m_q, x, y, dt, du, dv, F, F_k);
}
}
m_q = 1 - m_q;
}
#else
void GrayScottDrawer::draw(int* colIndices) {
Drawer::draw(colIndices);
GSType zoom = 1;
for (size_t f = 0; f < m_speed; ++f) {
auto& uIn = *m_u[m_q];
auto& vIn = *m_v[m_q];
auto& uOut = *m_u[1-m_q];
auto& vOut = *m_v[1-m_q];
for (size_t y = 0; y < m_height; ++y) {
for (size_t x = 0; x < m_width; ++x) {
size_t curr = x + y * m_width;
size_t left = (x - 1 + m_width) % m_width + y * m_width;
size_t right = (x + 1) % m_width + y * m_width;
size_t top = x + ((y - 1 + m_width) % m_height) * m_width;
size_t bottom = x + ((y + 1) % m_height) * m_width;
const GSType &u = uIn[curr];
const GSType &v = vIn[curr];
GSType d2 = u * v * v;
GSType d2u = uIn[left] + uIn[right] + uIn[top] + uIn[bottom] - 4 * u;
GSType d2v = vIn[left] + vIn[right] + vIn[top] + vIn[bottom] - 4 * v;
// diffusion
uOut[curr] = u + m_dt * m_du * d2u;
vOut[curr] = v + m_dt * m_dv * d2v;
// reaction
uOut[curr] += m_dt * (-d2 + m_F * (1 - u));
vOut[curr] += m_dt * (d2 - (m_F + m_k) * v);
}
}
m_q = 1 - m_q;
}
#endif
GSType maxv = 0;
for (size_t y = 0; y < m_height; ++y) {
for (size_t x = 0; x < m_width; x += VEC_N) {
size_t index = y * m_width + x;
maxv = std::max(maxv, m_v[m_q]->get(index));
}
}
maxv = m_lastMaxV + MAX_ROLLING_MULTIPLIER * (maxv - m_lastMaxV); // adapted from rolling EMA equation
for (size_t y = 0; y < m_height; ++y) {
for (size_t x = 0; x < m_width; ++x) {
size_t index = x + y * m_width;
GSType v = mapValue(m_v[m_q]->get(index), 0.0, maxv, 0.0, 1.0);
colIndices[index] = v * (m_palSize - 1);
}
}
for (size_t x = 0; x < m_width; ++x) {
for (size_t y = 0; y < m_height; ++y) {
colIndices[x + y * m_width] += m_colorIndex;
}
}
m_colorIndex += m_settings["colorSpeed"];
m_lastMaxV = maxv;
}
| #include <map>
#include <vector>
#include "GrayScott.h"
#include "Drawer.h"
#include "Util.h"
#include <algorithm>
#define MAX_ROLLING_MULTIPLIER (2.0 / (35 * 5 + 1))
#define NUM_INIT_ISLANDS 5
#define ISLAND_SIZE 20
#define MAX_SPEED 40 // determined empirically to allow 30fps
#ifdef __arm__
#define vmul(x, y) vmulq_f32(x, y)
#define vadd(x, y) vaddq_f32(x, y)
#define vsub(x, y) vsubq_f32(x, y)
#define vdup(x) vdupq_n_f32(x)
#define vld(x) vld1q_f32(x)
#define vst(x, y) vst1q_f32(x, y)
#define vprint(name, v) { GSType arr[VEC_N]; vst1q_f32(arr, v); std::cout << name << ": "; for (size_t i=0; i < VEC_N; ++i) { std::cout << arr[i] << " "; }; std::cout << std::endl; }
#endif
GrayScottDrawer::GrayScottDrawer(int width, int height, int palSize)
: Drawer("GrayScott", width, height, palSize), m_colorIndex(0) {
m_settings.insert(std::make_pair("speed",10));
m_settings.insert(std::make_pair("colorSpeed",0));
m_settings.insert(std::make_pair("params",1));
m_settingsRanges.insert(std::make_pair("speed", std::make_pair(5,10)));
m_settingsRanges.insert(std::make_pair("colorSpeed", std::make_pair(5,15)));
m_settingsRanges.insert(std::make_pair("params", std::make_pair(0,8)));
for (size_t q = 0; q < 2; ++q) {
m_u[q] = new Array2D<GSType>(width, height);
m_v[q] = new Array2D<GSType>(width, height);
}
m_q = true;
m_lastMaxV = 0.5;
reset();
}
GrayScottDrawer::~GrayScottDrawer() {
for (size_t q = 0; q < 2; ++q) {
delete[] m_u[q];
delete[] m_v[q];
}
}
void GrayScottDrawer::reset() {
for (size_t q = 0; q < 2; ++q) {
for (size_t i = 0; i < m_width * m_height; ++i) {
m_u[q]->get(i) = 1.0;
m_v[q]->get(i) = 0.0;
}
}
for (size_t i = 0; i < NUM_INIT_ISLANDS; ++i) {
size_t ix = random2() % (m_width - ISLAND_SIZE);
size_t iy = random2() % (m_height - ISLAND_SIZE);
for (size_t x = ix; x < ix + ISLAND_SIZE; ++x) {
for (size_t y = iy; y < iy + ISLAND_SIZE; ++y) {
size_t index = x + y * m_width;
m_u[m_q]->get(index) = 0.5;
m_v[m_q]->get(index) = 0.25;
}
}
}
// params from http://mrob.com/pub/comp/xmorphia
GSType F, k, scale;
switch(m_settings["params"]) {
case 0:
F = 0.022;
k = 0.049;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 1:
F = 0.026;
k = 0.051;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 2:
F = 0.026;
k = 0.052;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 3:
F = 0.022;
k = 0.048;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 4:
F = 0.018;
k = 0.045;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
case 5:
F = 0.010;
k = 0.033;
scale = std::exp(randomFloat(std::log(0.5), std::log(20)));
break;
// sometimes end quickly on smaller panels
case 6:
F = 0.014;
k = 0.041;
scale = std::exp(randomFloat(std::log(0.5), std::log(5)));
break;
case 7:
F = 0.006;
k = 0.045;
scale = std::exp(randomFloat(std::log(1.0), std::log(5)));
break;
case 8:
F = 0.010;
k = 0.047;
scale = std::exp(randomFloat(std::log(1.0), std::log(5)));
break;
// case 9:
// m_F = 0.006;
// m_k = 0.043;
// m_scale = std::exp(randomFloat(std::log(0.6), std::log(6)));
// break;
}
m_scale = scale;
m_du = 0.08 * m_scale;
m_dv = 0.04 * m_scale;
m_dt = 1 / m_scale;
m_F = F;
m_k = k;
m_speed = std::min((size_t)MAX_SPEED, (size_t)(m_settings["speed"] * m_scale));
std::cout << "GrayScott with param set #" << m_settings["params"] <<
std::setprecision(4) << " F=" << F << " k=" << k << " scale=" << m_scale <<
" total speed=" << m_speed << std::endl;
}
#ifdef __arm__
template <bool CHECK_BOUNDS>
inline
GSTypeN laplacian(const Array2D<GSType> *arr, int x, int y, const GSTypeN& curr) {
const GSType* raw = arr->rawData();
size_t w = arr->width();
size_t h = arr->height();
size_t index = x + y * w;
const GSType* pos = raw + index;
GSTypeN left, right, top, bottom;
GSTypeN fourN = vdup(4);
if (CHECK_BOUNDS) {
GSTypeN sum;
left = vld(raw + y * w + (x - 1 + w) % w);
right = vld(raw + y * w + (x + 1) % w);
top = vld(raw + ((y - 1 + h) % h) * w + x);
bottom = vld(raw + ((y + 1) % h) * w + x);
sum = vadd(left, right);
sum = vadd(sum, bottom);
sum = vadd(sum, top);
sum = vsub(sum, vmul(curr, fourN));
return sum;
} else {
GSTypeN sum;
left = vld(pos - 1);
right = vld(pos + 1);
top = vld(pos - w);
bottom = vld(pos + w);
sum = vadd(left, right);
sum = vadd(sum, bottom);
sum = vadd(sum, top);
sum = vsub(sum, vmul(curr, fourN));
return sum;
}
}
template <bool CHECK_BOUNDS>
inline
void updateUV(Array2D<GSType> *u[], Array2D<GSType> *v[],
bool q, size_t x, size_t y,
const GSTypeN& dt, const GSTypeN& du,
const GSTypeN& dv, const GSTypeN& F,
const GSTypeN& F_k) {
const GSType* uIn = u[q]->rawData();
const GSType* vIn = v[q]->rawData();
GSType* uOut = u[1-q]->rawData();
GSType* vOut = v[1-q]->rawData();
size_t index = y * u[q]->width() + x;
GSTypeN currU = vld(uIn + index);
GSTypeN currV = vld(vIn + index);
GSTypeN oneN = vdup(1);
// get vector of floats for laplacian transform
GSTypeN d2u = laplacian<CHECK_BOUNDS>(u[q], x, y, currU);
GSTypeN d2v = laplacian<CHECK_BOUNDS>(v[q], x, y, currV);
// uvv = u*v*v
GSTypeN uvv = vmul(currU, vmul(currV, currV));
// uOut[curr] = u + dt * du * d2u;
// uOut[curr] += dt * (-d2 + F * (1 - u));
GSTypeN uRD = vadd(currU, vmul(vmul(dt, du), d2u));
uRD = vadd(uRD, vmul(dt, vsub(vmul(F, vsub(oneN, currU)), uvv)));
vst(uOut + index, uRD);
// vOut[curr] = v + dt * dv * d2v;
// vOut[curr] += dt * (d2 - (F + k) * v);
GSTypeN vRD = vadd(currV, vmul(vmul(dt, dv), d2v));
vRD = vadd(vRD, vmul(dt, vsub(uvv, vmul(F_k, currV))));
vst(vOut + index, vRD);
}
void GrayScottDrawer::draw(int* colIndices) {
Drawer::draw(colIndices);
GSType zoom = 1;
GSTypeN dt = vdup(m_dt);
GSTypeN du = vdup(m_du);
GSTypeN dv = vdup(m_dv);
GSTypeN F = vdup(m_F);
GSTypeN F_k = vadd(F, vdup(m_k));
for (size_t f = 0; f < m_speed; ++f) {
// std::cout << *m_v[m_q] << std::endl;
for (size_t y = 1; y < m_height - 1; ++y) {
for (size_t x = VEC_N; x < m_width - VEC_N; x += VEC_N) {
updateUV<false>(m_u, m_v, m_q, x, y, dt, du, dv, F, F_k);
}
}
// borders are a special case
for (size_t y = 0; y < m_height; y += m_height - 1) {
for (size_t x = 0; x < m_width; x += VEC_N) {
updateUV<true>(m_u, m_v, m_q, x, y, dt, du, dv, F, F_k);
}
}
for (size_t y = 0; y < m_height; y += 1) {
for (size_t x = 0; x < m_width; x += m_width - VEC_N) {
updateUV<true>(m_u, m_v, m_q, x, y, dt, du, dv, F, F_k);
}
}
m_q = 1 - m_q;
}
#else
void GrayScottDrawer::draw(int* colIndices) {
Drawer::draw(colIndices);
GSType zoom = 1;
for (size_t f = 0; f < m_speed; ++f) {
auto& uIn = *m_u[m_q];
auto& vIn = *m_v[m_q];
auto& uOut = *m_u[1-m_q];
auto& vOut = *m_v[1-m_q];
for (size_t y = 0; y < m_height; ++y) {
for (size_t x = 0; x < m_width; ++x) {
size_t curr = x + y * m_width;
size_t left = (x - 1 + m_width) % m_width + y * m_width;
size_t right = (x + 1) % m_width + y * m_width;
size_t top = x + ((y - 1 + m_width) % m_height) * m_width;
size_t bottom = x + ((y + 1) % m_height) * m_width;
const GSType &u = uIn[curr];
const GSType &v = vIn[curr];
GSType d2 = u * v * v;
GSType d2u = uIn[left] + uIn[right] + uIn[top] + uIn[bottom] - 4 * u;
GSType d2v = vIn[left] + vIn[right] + vIn[top] + vIn[bottom] - 4 * v;
// diffusion
uOut[curr] = u + m_dt * m_du * d2u;
vOut[curr] = v + m_dt * m_dv * d2v;
// reaction
uOut[curr] += m_dt * (-d2 + m_F * (1 - u));
vOut[curr] += m_dt * (d2 - (m_F + m_k) * v);
}
}
m_q = 1 - m_q;
}
#endif
GSType maxv = 0;
for (size_t y = 0; y < m_height; ++y) {
for (size_t x = 0; x < m_width; x += VEC_N) {
size_t index = y * m_width + x;
maxv = std::max(maxv, m_v[m_q]->get(index));
}
}
maxv = m_lastMaxV + MAX_ROLLING_MULTIPLIER * (maxv - m_lastMaxV); // adapted from rolling EMA equation
for (size_t y = 0; y < m_height; ++y) {
for (size_t x = 0; x < m_width; ++x) {
size_t index = x + y * m_width;
GSType v = mapValue(m_v[m_q]->get(index), 0.0, maxv, 0.0, 1.0);
colIndices[index] = v * (m_palSize - 1);
}
}
for (size_t x = 0; x < m_width; ++x) {
for (size_t y = 0; y < m_height; ++y) {
colIndices[x + y * m_width] += m_colorIndex;
}
}
m_colorIndex += m_settings["colorSpeed"];
m_lastMaxV = maxv;
}
| change gray scott param ranges | change gray scott param ranges
| C++ | mit | gregfriedland/AuroraV6,gregfriedland/AuroraV6 |
22760105ab009ee5c59dc8c1d2f1fe4a3299e51a | Utilities/vxl/vnl/tests/test_resize.cxx | Utilities/vxl/vnl/tests/test_resize.cxx | // This is vxl/vnl/tests/test_resize.cxx
/*
fsm
*/
#include <vcl_iostream.h>
#include <vnl/vnl_vector.h>
#include <vnl/vnl_matrix.h>
#include <testlib/testlib_test.h>
#if 0
# include <vnl/vnl_resize.h>
# define vnl_resize_v vnl_resize
# define vnl_resize_m vnl_resize
#else
# define vnl_resize_v(v, n) (v).resize(n)
# define vnl_resize_m(A, m, n) (A).resize(m, n)
#endif
void test_resize()
{
{
vnl_vector<double> X(3);
X.fill(2);
TEST("fill 2", X(0)+X(1)+X(2), 6.0);
vcl_cout << "X = " << X << vcl_endl;
vnl_resize_v(X, 5);
TEST("size", X.size(), 5);
// After resize, old data is lost, so the following test must fail:
// TEST("resize", X(0)+X(1)+X(2)+X(3)+X(4), 6.0);
vcl_cout << "X = " << X << vcl_endl;
}
{
vnl_matrix<double> M(3, 4);
M.fill(2);
TEST("fill 2", M(0,0)+M(1,1)+M(2,2)+M(2,3), 8.0);
vcl_cout << "M = " << vcl_endl << M << vcl_endl;
vnl_resize_m(M, 5, 7);
TEST("size", M.rows(), 5);
TEST("size", M.cols(), 7);
// After resize, old data is lost, so the following test must fail:
// TEST("resize", M(0,0)+M(1,1)+M(2,2)+M(3,3)+M(4,4), 6.0);
vcl_cout << "M = " << vcl_endl << M << vcl_endl;
}
}
TESTMAIN(test_resize);
| // This is vxl/vnl/tests/test_resize.cxx
/*
fsm
*/
#include <vcl_iostream.h>
#include <vnl/vnl_vector.h>
#include <vnl/vnl_matrix.h>
#include <testlib/testlib_test.h>
#if 0
# include <vnl/vnl_resize.h>
# define vnl_resize_v vnl_resize
# define vnl_resize_m vnl_resize
#else
# define vnl_resize_v(v, n) (v).resize(n)
# define vnl_resize_m(A, m, n) (A).resize(m, n)
#endif
void test_resize()
{
{
vnl_vector<double> X(3);
X.fill(2);
TEST("fill 2", X(0)+X(1)+X(2), 6.0);
vcl_cout << "X = " << X << vcl_endl;
vnl_resize_v(X, 5);
TEST("size", X.size(), 5);
// After resize, old data is lost, so the following test must fail:
// TEST("resize", X(0)+X(1)+X(2)+X(3)+X(4), 6.0);
// avoid UMR from output
X(0) = X(1) = X(2) = X(3) = X(4) = 0.0;
vcl_cout << "X = " << X << vcl_endl;
}
{
vnl_matrix<double> M(3, 4);
M.fill(2);
TEST("fill 2", M(0,0)+M(1,1)+M(2,2)+M(2,3), 8.0);
vcl_cout << "M = " << vcl_endl << M << vcl_endl;
vnl_resize_m(M, 5, 7);
TEST("size", M.rows(), 5);
TEST("size", M.cols(), 7);
// After resize, old data is lost, so the following test must fail:
// TEST("resize", M(0,0)+M(1,1)+M(2,2)+M(3,3)+M(4,4), 6.0);
vcl_cout << "M = " << vcl_endl << M << vcl_endl;
}
}
TESTMAIN(test_resize);
| fix UMR purify error | BUG: fix UMR purify error
| C++ | apache-2.0 | fuentesdt/InsightToolkit-dev,BlueBrain/ITK,cpatrick/ITK-RemoteIO,vfonov/ITK,BRAINSia/ITK,wkjeong/ITK,BlueBrain/ITK,rhgong/itk-with-dom,CapeDrew/DCMTK-ITK,stnava/ITK,ajjl/ITK,stnava/ITK,ajjl/ITK,msmolens/ITK,daviddoria/itkHoughTransform,LucHermitte/ITK,fuentesdt/InsightToolkit-dev,jmerkow/ITK,hjmjohnson/ITK,Kitware/ITK,heimdali/ITK,BRAINSia/ITK,heimdali/ITK,paulnovo/ITK,hinerm/ITK,malaterre/ITK,vfonov/ITK,msmolens/ITK,ajjl/ITK,msmolens/ITK,richardbeare/ITK,heimdali/ITK,itkvideo/ITK,zachary-williamson/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,fedral/ITK,fuentesdt/InsightToolkit-dev,paulnovo/ITK,thewtex/ITK,daviddoria/itkHoughTransform,CapeDrew/DCMTK-ITK,stnava/ITK,CapeDrew/DITK,Kitware/ITK,thewtex/ITK,Kitware/ITK,atsnyder/ITK,blowekamp/ITK,cpatrick/ITK-RemoteIO,CapeDrew/DCMTK-ITK,fbudin69500/ITK,ajjl/ITK,itkvideo/ITK,hinerm/ITK,BRAINSia/ITK,spinicist/ITK,eile/ITK,cpatrick/ITK-RemoteIO,blowekamp/ITK,cpatrick/ITK-RemoteIO,wkjeong/ITK,paulnovo/ITK,BlueBrain/ITK,blowekamp/ITK,atsnyder/ITK,vfonov/ITK,fuentesdt/InsightToolkit-dev,fedral/ITK,fbudin69500/ITK,wkjeong/ITK,eile/ITK,itkvideo/ITK,ajjl/ITK,CapeDrew/DITK,hendradarwin/ITK,rhgong/itk-with-dom,jmerkow/ITK,rhgong/itk-with-dom,CapeDrew/DCMTK-ITK,jmerkow/ITK,cpatrick/ITK-RemoteIO,richardbeare/ITK,jcfr/ITK,rhgong/itk-with-dom,fbudin69500/ITK,ajjl/ITK,LucHermitte/ITK,CapeDrew/DITK,LucHermitte/ITK,blowekamp/ITK,LucHermitte/ITK,rhgong/itk-with-dom,vfonov/ITK,cpatrick/ITK-RemoteIO,rhgong/itk-with-dom,biotrump/ITK,rhgong/itk-with-dom,blowekamp/ITK,atsnyder/ITK,Kitware/ITK,biotrump/ITK,CapeDrew/DCMTK-ITK,stnava/ITK,BlueBrain/ITK,fuentesdt/InsightToolkit-dev,CapeDrew/DITK,thewtex/ITK,richardbeare/ITK,thewtex/ITK,jmerkow/ITK,biotrump/ITK,hendradarwin/ITK,BRAINSia/ITK,zachary-williamson/ITK,CapeDrew/DCMTK-ITK,CapeDrew/DCMTK-ITK,heimdali/ITK,biotrump/ITK,stnava/ITK,eile/ITK,ajjl/ITK,paulnovo/ITK,PlutoniumHeart/ITK,biotrump/ITK,stnava/ITK,heimdali/ITK,fuentesdt/InsightToolkit-dev,malaterre/ITK,InsightSoftwareConsortium/ITK,fbudin69500/ITK,GEHC-Surgery/ITK,BRAINSia/ITK,LucasGandel/ITK,hjmjohnson/ITK,cpatrick/ITK-RemoteIO,GEHC-Surgery/ITK,blowekamp/ITK,spinicist/ITK,jcfr/ITK,eile/ITK,hjmjohnson/ITK,eile/ITK,biotrump/ITK,GEHC-Surgery/ITK,CapeDrew/DCMTK-ITK,rhgong/itk-with-dom,stnava/ITK,daviddoria/itkHoughTransform,GEHC-Surgery/ITK,wkjeong/ITK,LucHermitte/ITK,LucasGandel/ITK,zachary-williamson/ITK,hinerm/ITK,LucasGandel/ITK,PlutoniumHeart/ITK,zachary-williamson/ITK,vfonov/ITK,thewtex/ITK,fedral/ITK,spinicist/ITK,malaterre/ITK,blowekamp/ITK,PlutoniumHeart/ITK,BRAINSia/ITK,stnava/ITK,wkjeong/ITK,hinerm/ITK,GEHC-Surgery/ITK,fbudin69500/ITK,jmerkow/ITK,msmolens/ITK,fuentesdt/InsightToolkit-dev,wkjeong/ITK,msmolens/ITK,atsnyder/ITK,malaterre/ITK,PlutoniumHeart/ITK,CapeDrew/DITK,PlutoniumHeart/ITK,msmolens/ITK,msmolens/ITK,InsightSoftwareConsortium/ITK,hendradarwin/ITK,paulnovo/ITK,jmerkow/ITK,BlueBrain/ITK,jmerkow/ITK,malaterre/ITK,biotrump/ITK,blowekamp/ITK,InsightSoftwareConsortium/ITK,daviddoria/itkHoughTransform,InsightSoftwareConsortium/ITK,spinicist/ITK,atsnyder/ITK,richardbeare/ITK,hinerm/ITK,heimdali/ITK,spinicist/ITK,GEHC-Surgery/ITK,hendradarwin/ITK,vfonov/ITK,LucasGandel/ITK,wkjeong/ITK,thewtex/ITK,paulnovo/ITK,CapeDrew/DITK,itkvideo/ITK,eile/ITK,LucasGandel/ITK,CapeDrew/DITK,CapeDrew/DITK,eile/ITK,hendradarwin/ITK,jmerkow/ITK,Kitware/ITK,malaterre/ITK,PlutoniumHeart/ITK,hinerm/ITK,biotrump/ITK,itkvideo/ITK,spinicist/ITK,hinerm/ITK,heimdali/ITK,daviddoria/itkHoughTransform,hjmjohnson/ITK,fedral/ITK,itkvideo/ITK,BlueBrain/ITK,GEHC-Surgery/ITK,daviddoria/itkHoughTransform,jcfr/ITK,stnava/ITK,fbudin69500/ITK,Kitware/ITK,BlueBrain/ITK,spinicist/ITK,hendradarwin/ITK,heimdali/ITK,eile/ITK,malaterre/ITK,msmolens/ITK,LucHermitte/ITK,spinicist/ITK,fuentesdt/InsightToolkit-dev,hjmjohnson/ITK,fedral/ITK,daviddoria/itkHoughTransform,zachary-williamson/ITK,LucasGandel/ITK,hjmjohnson/ITK,PlutoniumHeart/ITK,LucHermitte/ITK,atsnyder/ITK,fedral/ITK,LucasGandel/ITK,daviddoria/itkHoughTransform,zachary-williamson/ITK,jcfr/ITK,jcfr/ITK,itkvideo/ITK,spinicist/ITK,jcfr/ITK,richardbeare/ITK,CapeDrew/DCMTK-ITK,hinerm/ITK,Kitware/ITK,atsnyder/ITK,zachary-williamson/ITK,thewtex/ITK,paulnovo/ITK,daviddoria/itkHoughTransform,vfonov/ITK,wkjeong/ITK,zachary-williamson/ITK,GEHC-Surgery/ITK,jcfr/ITK,LucHermitte/ITK,fedral/ITK,cpatrick/ITK-RemoteIO,atsnyder/ITK,fbudin69500/ITK,hjmjohnson/ITK,jcfr/ITK,LucasGandel/ITK,fedral/ITK,malaterre/ITK,InsightSoftwareConsortium/ITK,zachary-williamson/ITK,hendradarwin/ITK,richardbeare/ITK,itkvideo/ITK,richardbeare/ITK,BRAINSia/ITK,paulnovo/ITK,atsnyder/ITK,eile/ITK,BlueBrain/ITK,itkvideo/ITK,ajjl/ITK,fuentesdt/InsightToolkit-dev,vfonov/ITK,CapeDrew/DITK,malaterre/ITK,hendradarwin/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,fbudin69500/ITK,hinerm/ITK |
061fce3055e6d5cb9aad74350353632a40ad229b | test/product_trsm.cpp | test/product_trsm.cpp | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#define VERIFY_TRSM(TRI,XB) { \
(XB).setRandom(); ref = (XB); \
(TRI).solveInPlace(XB); \
VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \
}
template<typename Scalar> void trsm(int size,int cols)
{
typedef typename NumTraits<Scalar>::Real RealScalar;
Matrix<Scalar,Dynamic,Dynamic,ColMajor> cmLhs(size,size);
Matrix<Scalar,Dynamic,Dynamic,RowMajor> rmLhs(size,size);
Matrix<Scalar,Dynamic,Dynamic,ColMajor> cmRhs(size,cols), ref(size,cols);
Matrix<Scalar,Dynamic,Dynamic,RowMajor> rmRhs(size,cols);
cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().cwise() += static_cast<RealScalar>(1);
rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().cwise() += static_cast<RealScalar>(1);
VERIFY_TRSM(cmLhs.conjugate().template triangularView<LowerTriangular>(), cmRhs);
VERIFY_TRSM(cmLhs .template triangularView<UpperTriangular>(), cmRhs);
VERIFY_TRSM(cmLhs .template triangularView<LowerTriangular>(), rmRhs);
VERIFY_TRSM(cmLhs.conjugate().template triangularView<UpperTriangular>(), rmRhs);
VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLowerTriangular>(), cmRhs);
VERIFY_TRSM(cmLhs .template triangularView<UnitUpperTriangular>(), rmRhs);
VERIFY_TRSM(rmLhs .template triangularView<LowerTriangular>(), cmRhs);
VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpperTriangular>(), rmRhs);
}
void test_product_trsm()
{
for(int i = 0; i < g_repeat ; i++)
{
CALL_SUBTEST_1((trsm<float>(ei_random<int>(1,320),ei_random<int>(1,320))));
CALL_SUBTEST_2((trsm<std::complex<double> >(ei_random<int>(1,320),ei_random<int>(1,320))));
}
}
| // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#define VERIFY_TRSM(TRI,XB) { \
(XB).setRandom(); ref = (XB); \
(TRI).solveInPlace(XB); \
VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \
}
#define VERIFY_TRSM_ONTHERIGHT(TRI,XB) { \
(XB).setRandom(); ref = (XB); \
(TRI).transpose().template solveInPlace<OnTheRight>(XB.transpose()); \
VERIFY_IS_APPROX((XB).transpose() * (TRI).transpose().toDenseMatrix(), ref.transpose()); \
}
template<typename Scalar> void trsm(int size,int cols)
{
typedef typename NumTraits<Scalar>::Real RealScalar;
Matrix<Scalar,Dynamic,Dynamic,ColMajor> cmLhs(size,size);
Matrix<Scalar,Dynamic,Dynamic,RowMajor> rmLhs(size,size);
Matrix<Scalar,Dynamic,Dynamic,ColMajor> cmRhs(size,cols), ref(size,cols);
Matrix<Scalar,Dynamic,Dynamic,RowMajor> rmRhs(size,cols);
cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().cwise() += static_cast<RealScalar>(1);
rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().cwise() += static_cast<RealScalar>(1);
VERIFY_TRSM(cmLhs.conjugate().template triangularView<LowerTriangular>(), cmRhs);
VERIFY_TRSM(cmLhs .template triangularView<UpperTriangular>(), cmRhs);
VERIFY_TRSM(cmLhs .template triangularView<LowerTriangular>(), rmRhs);
VERIFY_TRSM(cmLhs.conjugate().template triangularView<UpperTriangular>(), rmRhs);
VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLowerTriangular>(), cmRhs);
VERIFY_TRSM(cmLhs .template triangularView<UnitUpperTriangular>(), rmRhs);
VERIFY_TRSM(rmLhs .template triangularView<LowerTriangular>(), cmRhs);
VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpperTriangular>(), rmRhs);
VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<LowerTriangular>(), cmRhs);
VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<UpperTriangular>(), cmRhs);
VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<LowerTriangular>(), rmRhs);
VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UpperTriangular>(), rmRhs);
VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UnitLowerTriangular>(), cmRhs);
VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<UnitUpperTriangular>(), rmRhs);
VERIFY_TRSM_ONTHERIGHT(rmLhs .template triangularView<LowerTriangular>(), cmRhs);
VERIFY_TRSM_ONTHERIGHT(rmLhs.conjugate().template triangularView<UnitUpperTriangular>(), rmRhs);
}
void test_product_trsm()
{
for(int i = 0; i < g_repeat ; i++)
{
CALL_SUBTEST_1((trsm<float>(ei_random<int>(1,320),ei_random<int>(1,320))));
CALL_SUBTEST_2((trsm<std::complex<double> >(ei_random<int>(1,320),ei_random<int>(1,320))));
}
}
| add checks for on the right triangular solving with matrices | add checks for on the right triangular solving with matrices
| C++ | bsd-3-clause | TSC21/Eigen,pasuka/eigen,pasuka/eigen,TSC21/Eigen,toastedcrumpets/eigen,pasuka/eigen,ROCmSoftwarePlatform/hipeigen,ritsu1228/eigen,ritsu1228/eigen,pasuka/eigen,pasuka/eigen,Zefz/eigen,ritsu1228/eigen,toastedcrumpets/eigen,TSC21/Eigen,ROCmSoftwarePlatform/hipeigen,toastedcrumpets/eigen,Zefz/eigen,ROCmSoftwarePlatform/hipeigen,ROCmSoftwarePlatform/hipeigen,TSC21/Eigen,ritsu1228/eigen,ritsu1228/eigen,Zefz/eigen,Zefz/eigen,toastedcrumpets/eigen |
71d6af9f46f4216bba5ddf956e645d28e669f087 | test/sqlite.gtest.cpp | test/sqlite.gtest.cpp | #include <gtest/gtest.h>
#include <chrono>
#include "stl.hpp"
#include "src/sqlite/db.hpp"
#include <iostream>
using std::cout;
using std::endl;
using namespace mx3::sqlite;
TEST(sqlite_lib, can_query_version_info) {
EXPECT_EQ(libversion(), "3.8.10.2");
EXPECT_EQ(sourceid(), "2015-05-20 18:17:19 2ef4f3a5b1d1d0c4338f8243d40a2452cc1f7fe4");
EXPECT_EQ(libversion_number(), 3008010);
}
TEST(sqlite_db, can_open_close) {
const auto db = Db::open(":memory:");
}
TEST(sqlite_db, affinity) {
const vector<std::pair<string, Affinity>> test_cases {
{"INT", Affinity::INTEGER},
{"INTEGER", Affinity::INTEGER},
{"TINYINT", Affinity::INTEGER},
{"SMALLINT", Affinity::INTEGER},
{"MEDIUMINT", Affinity::INTEGER},
{"BIGINT", Affinity::INTEGER},
{"UNSIGNED BIG INT", Affinity::INTEGER},
{"INT2", Affinity::INTEGER},
{"INT8", Affinity::INTEGER},
{"CHARACTER(20)", Affinity::TEXT},
{"VARCHAR(255)", Affinity::TEXT},
{"VARYING CHARACTER(255)", Affinity::TEXT},
{"NCHAR(55)", Affinity::TEXT},
{"NATIVE CHARACTER(70)", Affinity::TEXT},
{"NVARCHAR(100)", Affinity::TEXT},
{"TEXT", Affinity::TEXT},
{"CLOB", Affinity::TEXT},
{"BLOB", Affinity::NONE},
{"", Affinity::NONE},
{"REAL", Affinity::REAL},
{"DOUBLE", Affinity::REAL},
{"DOUBLE PRECISION", Affinity::REAL},
{"FLOAT", Affinity::REAL},
{"NUMERIC", Affinity::NUMERIC},
{"DECIMAL(10,5)", Affinity::NUMERIC},
{"BOOLEAN", Affinity::NUMERIC},
{"DATE", Affinity::NUMERIC},
{"DATETIME", Affinity::NUMERIC},
// Not a recognized type, but `int` matches `point`.
{"FLOATING POINT", Affinity::INTEGER},
// String doesn't match any of the sqlite types.
{"STRING", Affinity::NUMERIC}
};
for (const auto& tc : test_cases) {
const auto db = Db::open(":memory:");
db->exec("CREATE TABLE `aff_test` (`test_col` " + tc.first + ")");
const auto info = db->table_info("aff_test").value();
EXPECT_EQ(info.columns[0].name, "test_col");
EXPECT_EQ(info.columns[0].type, tc.first);
EXPECT_EQ(info.columns[0].type_affinity(), tc.second);
}
}
TEST(sqlite_db, can_do_busy_timeout) {
auto db = Db::open(":memory:");
db->busy_timeout(nullopt);
db->busy_timeout(std::chrono::seconds {5});
}
TEST(sqlite_db, wal_hook) {
auto db = Db::open(":memory:");
db->wal_hook([] (const string&, int) {
});
db = nullptr;
}
TEST(sqlite_db, schema_info) {
auto db = Db::open(":memory:");
auto schema_info = db->schema_info();
EXPECT_EQ(schema_info.size(), 0);
string name = "my_table";
string sql = "CREATE TABLE " + name + " (table_id INTEGER, name TEXT NOT NULL, data BLOB, price FLOAT DEFAULT 1.4, PRIMARY KEY (table_id))";
db->exec(sql);
schema_info = db->schema_info();
auto t = schema_info[0];
EXPECT_EQ(t.name, name);
EXPECT_EQ(t.sql, sql);
EXPECT_EQ(t.columns.size(), 4);
const auto& c = t.columns;
EXPECT_EQ(c[0].name, "table_id");
EXPECT_EQ(c[0].type, "INTEGER");
EXPECT_EQ(c[0].notnull, false);
EXPECT_EQ(c[0].dflt_value, nullopt);
EXPECT_EQ(c[0].is_pk(), true);
EXPECT_EQ(c[1].name, "name");
EXPECT_EQ(c[1].type, "TEXT");
EXPECT_EQ(c[1].notnull, true);
EXPECT_EQ(c[1].dflt_value, nullopt);
EXPECT_EQ(c[1].is_pk(), false);
EXPECT_EQ(c[2].name, "data");
EXPECT_EQ(c[2].type, "BLOB");
EXPECT_EQ(c[2].notnull, false);
EXPECT_EQ(c[2].dflt_value, nullopt);
EXPECT_EQ(c[2].is_pk(), false);
EXPECT_EQ(c[3].name, "price");
EXPECT_EQ(c[3].type, "FLOAT");
EXPECT_EQ(c[3].notnull, false);
EXPECT_EQ(c[3].dflt_value, string {"1.4"});
EXPECT_EQ(c[3].is_pk(), false);
}
TEST(sqlite_db, get_set_user_version) {
auto db = Db::open_memory();
int32_t version = db->user_version();
EXPECT_EQ(version, 0);
db->set_user_version(493);
version = db->user_version();
EXPECT_EQ(version, 493);
version = db->user_version();
EXPECT_EQ(version, 493);
db->set_user_version(77);
version = db->user_version();
EXPECT_EQ(version, 77);
}
TEST(sqlite_db, get_schema_version) {
auto db = Db::open_memory();
int32_t v1 = db->schema_version();
db->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
int32_t v2 = db->schema_version();
EXPECT_FALSE( v1 == v2 );
}
// this test relies on the fact that closing a in memory database loses all of its data
TEST(sqlite_db, dtor_closes_db) {
{
auto db1 = Db::open_memory();
db1->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
db1->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
auto cursor = db1->prepare("SELECT * from `abc`;")->exec_query();
EXPECT_EQ(cursor.is_valid(), true);
}
{
auto db2 = Db::open_memory();
db2->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
auto cursor = db2->prepare("SELECT * from `abc`;")->exec_query();
EXPECT_EQ(cursor.is_valid(), false);
}
}
TEST(sqlite_db, can_exec) {
auto db = Db::open_memory();
db->exec("SELECT * from sqlite_master");
}
TEST(sqlite_db, can_exec_scalar) {
auto db = Db::open_memory();
auto result = db->exec_scalar("PRAGMA user_version;");
EXPECT_EQ(result, 0);
db->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
result = db->exec_scalar("SELECT COUNT(*) FROM sqlite_master");
EXPECT_EQ(result, 1);
EXPECT_THROW( db->exec_scalar("SELCT * from sqlite_master'"), std::runtime_error );
}
TEST(sqlite_db, throw_on_bad_exec) {
auto db = Db::open_memory();
EXPECT_THROW( db->exec("SELCT * from'"), std::runtime_error );
}
TEST(sqlite_db, exec_works) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto r1 = db->prepare("UPDATE `abc` SET `name` = 'first' WHERE `name` = 'first'")->exec();
EXPECT_EQ(r1, 0);
auto r2 = db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
EXPECT_EQ(r2, 1);
// should throw an error
auto s2 = db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')");
EXPECT_THROW(s2->exec(), std::runtime_error);
}
TEST(sqlite_db, update_hook_insert) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
size_t times_called = 0;
db->update_hook([&] (Db::Change change) {
times_called++;
EXPECT_EQ(change.type, ChangeType::INSERT);
EXPECT_EQ(change.table_name, "abc");
});
db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
EXPECT_EQ(times_called, 1);
}
TEST(sqlite_db, update_hook_delete) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
int64_t insert_row_id = db->last_insert_rowid();
size_t times_called = 0;
db->update_hook([&] (Db::Change change) {
times_called++;
EXPECT_EQ(insert_row_id, change.rowid);
EXPECT_EQ(change.type, ChangeType::DELETE);
EXPECT_EQ(change.table_name, "abc");
});
db->prepare("DELETE FROM `abc` WHERE 1")->exec();
EXPECT_EQ(times_called, 1);
}
TEST(sqlite_db, update_hook_update) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
int64_t insert_row_id = db->last_insert_rowid();
size_t times_called = 0;
db->update_hook([&] (Db::Change change) {
times_called++;
EXPECT_EQ(insert_row_id, change.rowid);
EXPECT_EQ(change.type, ChangeType::UPDATE);
EXPECT_EQ(change.table_name, "abc");
});
auto stmt = db->prepare("UPDATE `abc` SET `name` = 'second' WHERE rowid = ?1");
stmt->bind(1, insert_row_id);
stmt->exec();
EXPECT_EQ(times_called, 1);
}
TEST(sqlite_stmt, param_count) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto stmt = db->prepare("SELECT * from `abc` WHERE name = ?1");
EXPECT_EQ(stmt->param_count(), 1);
stmt = db->prepare("SELECT * from `abc`");
EXPECT_EQ(stmt->param_count(), 0);
stmt = db->prepare("SELECT * from `abc` WHERE name = ?1 OR name = ?1 OR name = ?1");
EXPECT_EQ(stmt->param_count(), 1);
stmt = db->prepare("SELECT * from `abc` WHERE name = ?");
EXPECT_EQ(stmt->param_count(), 1);
stmt = db->prepare("SELECT * from `abc` WHERE name = ? OR name = ?2");
EXPECT_EQ(stmt->param_count(), 2);
}
TEST(sqlite_stmt, param_name) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto stmt = db->prepare("SELECT * from `abc` WHERE name = ?1");
EXPECT_EQ(stmt->param_name(1).value_or(""), "?1");
stmt = db->prepare("SELECT * from `abc` WHERE name = ?");
EXPECT_EQ(stmt->param_name(1), nullopt);
stmt = db->prepare("SELECT * from `abc` WHERE name = :name");
EXPECT_EQ(stmt->param_name(1).value_or(""), ":name");
}
TEST(sqlite_stmt, param_index) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto stmt = db->prepare("SELECT * from `abc` WHERE name = ?1");
EXPECT_EQ(stmt->param_index("?1"), 1);
EXPECT_THROW(stmt->param_index(":not_a_param"), std::runtime_error);
stmt = db->prepare("SELECT * from `abc` WHERE name = :name");
EXPECT_EQ(stmt->param_index(":name"), 1);
EXPECT_THROW(stmt->param_index("?name"), std::runtime_error);
EXPECT_THROW(stmt->param_index("name"), std::runtime_error);
}
TEST(sqlite_stmt, get_values) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (`s` TEXT, `b` BLOB, `d` DOUBLE, `i` INTEGER)");
auto insert_stmt = db->prepare("INSERT INTO `abc` (s, b, d, i) VALUES (?, ?, ?, ?)");
vector<uint8_t> b {1,0,2,3};
double d = 1.5;
int64_t i = 8;
string s = "Steven";
insert_stmt->bind(1, s);
insert_stmt->bind(2, b);
insert_stmt->bind(3, d);
insert_stmt->bind(4, i);
insert_stmt->exec();
auto cursor = db->prepare("SELECT b, d, i, s from `abc`")->exec_query();
vector<Value> expected_values { b, d, i, s };
auto real_values = cursor.values();
EXPECT_EQ(real_values, expected_values);
vector<string> expected_names { "b", "d", "i", "s" };
auto real_names = cursor.column_names();
EXPECT_EQ(expected_names, real_names);
std::map<string, Value> expected_value_map {
{"b", b},
{"d", d},
{"i", i},
{"s", s}
};
auto real_map = cursor.value_map();
EXPECT_EQ(real_map, expected_value_map);
}
| #include <gtest/gtest.h>
#include <chrono>
#include "stl.hpp"
#include "src/sqlite/db.hpp"
#include <iostream>
using std::cout;
using std::endl;
using namespace mx3::sqlite;
TEST(sqlite_lib, can_query_version_info) {
EXPECT_EQ(libversion(), "3.8.11.1");
EXPECT_EQ(sourceid(), "2015-07-29 20:00:57 cf538e2783e468bbc25e7cb2a9ee64d3e0e80b2f");
EXPECT_EQ(libversion_number(), 3008011);
}
TEST(sqlite_db, can_open_close) {
const auto db = Db::open(":memory:");
}
TEST(sqlite_db, affinity) {
const vector<std::pair<string, Affinity>> test_cases {
{"INT", Affinity::INTEGER},
{"INTEGER", Affinity::INTEGER},
{"TINYINT", Affinity::INTEGER},
{"SMALLINT", Affinity::INTEGER},
{"MEDIUMINT", Affinity::INTEGER},
{"BIGINT", Affinity::INTEGER},
{"UNSIGNED BIG INT", Affinity::INTEGER},
{"INT2", Affinity::INTEGER},
{"INT8", Affinity::INTEGER},
{"CHARACTER(20)", Affinity::TEXT},
{"VARCHAR(255)", Affinity::TEXT},
{"VARYING CHARACTER(255)", Affinity::TEXT},
{"NCHAR(55)", Affinity::TEXT},
{"NATIVE CHARACTER(70)", Affinity::TEXT},
{"NVARCHAR(100)", Affinity::TEXT},
{"TEXT", Affinity::TEXT},
{"CLOB", Affinity::TEXT},
{"BLOB", Affinity::NONE},
{"", Affinity::NONE},
{"REAL", Affinity::REAL},
{"DOUBLE", Affinity::REAL},
{"DOUBLE PRECISION", Affinity::REAL},
{"FLOAT", Affinity::REAL},
{"NUMERIC", Affinity::NUMERIC},
{"DECIMAL(10,5)", Affinity::NUMERIC},
{"BOOLEAN", Affinity::NUMERIC},
{"DATE", Affinity::NUMERIC},
{"DATETIME", Affinity::NUMERIC},
// Not a recognized type, but `int` matches `point`.
{"FLOATING POINT", Affinity::INTEGER},
// String doesn't match any of the sqlite types.
{"STRING", Affinity::NUMERIC}
};
for (const auto& tc : test_cases) {
const auto db = Db::open(":memory:");
db->exec("CREATE TABLE `aff_test` (`test_col` " + tc.first + ")");
const auto info = db->table_info("aff_test").value();
EXPECT_EQ(info.columns[0].name, "test_col");
EXPECT_EQ(info.columns[0].type, tc.first);
EXPECT_EQ(info.columns[0].type_affinity(), tc.second);
}
}
TEST(sqlite_db, can_do_busy_timeout) {
auto db = Db::open(":memory:");
db->busy_timeout(nullopt);
db->busy_timeout(std::chrono::seconds {5});
}
TEST(sqlite_db, wal_hook) {
auto db = Db::open(":memory:");
db->wal_hook([] (const string&, int) {
});
db = nullptr;
}
TEST(sqlite_db, schema_info) {
auto db = Db::open(":memory:");
auto schema_info = db->schema_info();
EXPECT_EQ(schema_info.size(), 0);
string name = "my_table";
string sql = "CREATE TABLE " + name + " (table_id INTEGER, name TEXT NOT NULL, data BLOB, price FLOAT DEFAULT 1.4, PRIMARY KEY (table_id))";
db->exec(sql);
schema_info = db->schema_info();
auto t = schema_info[0];
EXPECT_EQ(t.name, name);
EXPECT_EQ(t.sql, sql);
EXPECT_EQ(t.columns.size(), 4);
const auto& c = t.columns;
EXPECT_EQ(c[0].name, "table_id");
EXPECT_EQ(c[0].type, "INTEGER");
EXPECT_EQ(c[0].notnull, false);
EXPECT_EQ(c[0].dflt_value, nullopt);
EXPECT_EQ(c[0].is_pk(), true);
EXPECT_EQ(c[1].name, "name");
EXPECT_EQ(c[1].type, "TEXT");
EXPECT_EQ(c[1].notnull, true);
EXPECT_EQ(c[1].dflt_value, nullopt);
EXPECT_EQ(c[1].is_pk(), false);
EXPECT_EQ(c[2].name, "data");
EXPECT_EQ(c[2].type, "BLOB");
EXPECT_EQ(c[2].notnull, false);
EXPECT_EQ(c[2].dflt_value, nullopt);
EXPECT_EQ(c[2].is_pk(), false);
EXPECT_EQ(c[3].name, "price");
EXPECT_EQ(c[3].type, "FLOAT");
EXPECT_EQ(c[3].notnull, false);
EXPECT_EQ(c[3].dflt_value, string {"1.4"});
EXPECT_EQ(c[3].is_pk(), false);
}
TEST(sqlite_db, get_set_user_version) {
auto db = Db::open_memory();
int32_t version = db->user_version();
EXPECT_EQ(version, 0);
db->set_user_version(493);
version = db->user_version();
EXPECT_EQ(version, 493);
version = db->user_version();
EXPECT_EQ(version, 493);
db->set_user_version(77);
version = db->user_version();
EXPECT_EQ(version, 77);
}
TEST(sqlite_db, get_schema_version) {
auto db = Db::open_memory();
int32_t v1 = db->schema_version();
db->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
int32_t v2 = db->schema_version();
EXPECT_FALSE( v1 == v2 );
}
// this test relies on the fact that closing a in memory database loses all of its data
TEST(sqlite_db, dtor_closes_db) {
{
auto db1 = Db::open_memory();
db1->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
db1->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
auto cursor = db1->prepare("SELECT * from `abc`;")->exec_query();
EXPECT_EQ(cursor.is_valid(), true);
}
{
auto db2 = Db::open_memory();
db2->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
auto cursor = db2->prepare("SELECT * from `abc`;")->exec_query();
EXPECT_EQ(cursor.is_valid(), false);
}
}
TEST(sqlite_db, can_exec) {
auto db = Db::open_memory();
db->exec("SELECT * from sqlite_master");
}
TEST(sqlite_db, can_exec_scalar) {
auto db = Db::open_memory();
auto result = db->exec_scalar("PRAGMA user_version;");
EXPECT_EQ(result, 0);
db->exec("CREATE TABLE IF NOT EXISTS abc (name TEXT);");
result = db->exec_scalar("SELECT COUNT(*) FROM sqlite_master");
EXPECT_EQ(result, 1);
EXPECT_THROW( db->exec_scalar("SELCT * from sqlite_master'"), std::runtime_error );
}
TEST(sqlite_db, throw_on_bad_exec) {
auto db = Db::open_memory();
EXPECT_THROW( db->exec("SELCT * from'"), std::runtime_error );
}
TEST(sqlite_db, exec_works) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto r1 = db->prepare("UPDATE `abc` SET `name` = 'first' WHERE `name` = 'first'")->exec();
EXPECT_EQ(r1, 0);
auto r2 = db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
EXPECT_EQ(r2, 1);
// should throw an error
auto s2 = db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')");
EXPECT_THROW(s2->exec(), std::runtime_error);
}
TEST(sqlite_db, update_hook_insert) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
size_t times_called = 0;
db->update_hook([&] (Db::Change change) {
times_called++;
EXPECT_EQ(change.type, ChangeType::INSERT);
EXPECT_EQ(change.table_name, "abc");
});
db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
EXPECT_EQ(times_called, 1);
}
TEST(sqlite_db, update_hook_delete) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
int64_t insert_row_id = db->last_insert_rowid();
size_t times_called = 0;
db->update_hook([&] (Db::Change change) {
times_called++;
EXPECT_EQ(insert_row_id, change.rowid);
EXPECT_EQ(change.type, ChangeType::DELETE);
EXPECT_EQ(change.table_name, "abc");
});
db->prepare("DELETE FROM `abc` WHERE 1")->exec();
EXPECT_EQ(times_called, 1);
}
TEST(sqlite_db, update_hook_update) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
db->prepare("INSERT INTO `abc` (`name`) VALUES ('first')")->exec();
int64_t insert_row_id = db->last_insert_rowid();
size_t times_called = 0;
db->update_hook([&] (Db::Change change) {
times_called++;
EXPECT_EQ(insert_row_id, change.rowid);
EXPECT_EQ(change.type, ChangeType::UPDATE);
EXPECT_EQ(change.table_name, "abc");
});
auto stmt = db->prepare("UPDATE `abc` SET `name` = 'second' WHERE rowid = ?1");
stmt->bind(1, insert_row_id);
stmt->exec();
EXPECT_EQ(times_called, 1);
}
TEST(sqlite_stmt, param_count) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto stmt = db->prepare("SELECT * from `abc` WHERE name = ?1");
EXPECT_EQ(stmt->param_count(), 1);
stmt = db->prepare("SELECT * from `abc`");
EXPECT_EQ(stmt->param_count(), 0);
stmt = db->prepare("SELECT * from `abc` WHERE name = ?1 OR name = ?1 OR name = ?1");
EXPECT_EQ(stmt->param_count(), 1);
stmt = db->prepare("SELECT * from `abc` WHERE name = ?");
EXPECT_EQ(stmt->param_count(), 1);
stmt = db->prepare("SELECT * from `abc` WHERE name = ? OR name = ?2");
EXPECT_EQ(stmt->param_count(), 2);
}
TEST(sqlite_stmt, param_name) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto stmt = db->prepare("SELECT * from `abc` WHERE name = ?1");
EXPECT_EQ(stmt->param_name(1).value_or(""), "?1");
stmt = db->prepare("SELECT * from `abc` WHERE name = ?");
EXPECT_EQ(stmt->param_name(1), nullopt);
stmt = db->prepare("SELECT * from `abc` WHERE name = :name");
EXPECT_EQ(stmt->param_name(1).value_or(""), ":name");
}
TEST(sqlite_stmt, param_index) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (name TEXT, PRIMARY KEY(name) )");
auto stmt = db->prepare("SELECT * from `abc` WHERE name = ?1");
EXPECT_EQ(stmt->param_index("?1"), 1);
EXPECT_THROW(stmt->param_index(":not_a_param"), std::runtime_error);
stmt = db->prepare("SELECT * from `abc` WHERE name = :name");
EXPECT_EQ(stmt->param_index(":name"), 1);
EXPECT_THROW(stmt->param_index("?name"), std::runtime_error);
EXPECT_THROW(stmt->param_index("name"), std::runtime_error);
}
TEST(sqlite_stmt, get_values) {
auto db = Db::open_memory();
db->exec("CREATE TABLE abc (`s` TEXT, `b` BLOB, `d` DOUBLE, `i` INTEGER)");
auto insert_stmt = db->prepare("INSERT INTO `abc` (s, b, d, i) VALUES (?, ?, ?, ?)");
vector<uint8_t> b {1,0,2,3};
double d = 1.5;
int64_t i = 8;
string s = "Steven";
insert_stmt->bind(1, s);
insert_stmt->bind(2, b);
insert_stmt->bind(3, d);
insert_stmt->bind(4, i);
insert_stmt->exec();
auto cursor = db->prepare("SELECT b, d, i, s from `abc`")->exec_query();
vector<Value> expected_values { b, d, i, s };
auto real_values = cursor.values();
EXPECT_EQ(real_values, expected_values);
vector<string> expected_names { "b", "d", "i", "s" };
auto real_names = cursor.column_names();
EXPECT_EQ(expected_names, real_names);
std::map<string, Value> expected_value_map {
{"b", b},
{"d", d},
{"i", i},
{"s", s}
};
auto real_map = cursor.value_map();
EXPECT_EQ(real_map, expected_value_map);
}
| update sqlite version tests after upgrade | test: update sqlite version tests after upgrade
| C++ | mit | libmx3/mx3,libmx3/mx3,libmx3/mx3 |
3868af7758f093d9919eb95157c4c6ef43597ad3 | src/UDPSocket.cpp | src/UDPSocket.cpp |
#include "network_os.h"
#include "net/UDPSocket.hpp"
namespace network {
UDPSocket::UDPSocket() : bound(false), handle(0), af(NETA_UNDEF) { }
UDPSocket::~UDPSocket() {
Close();
}
bool UDPSocket::Init(ADDRTYPE afn) {
if(handle) {
Close();
}
this->af = afn;
int sc;
sc = socket(afn, SOCK_DGRAM, IPPROTO_UDP);
if(INVALID_SOCKET == sc) {
return false;
}
handle = sc;
return true;
}
bool UDPSocket::Bind(NetworkAddress & local) {
if(!handle) { return false; }
long v = 1;
if(setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, (char*)&v, sizeof(long))) {
return false;
}
if(bind(handle, (struct sockaddr*)&local.addr, local.Length())) {
return false;
}
laddr = local;
bound = true;
return true;
}
void UDPSocket::Close() {
if(!handle) { return; }
#ifdef WIN32
closesocket(handle);
#else
close(handle);
#endif
handle = 0;
}
bool UDPSocket::IsBound() const {
return this->bound;
}
bool UDPSocket::SetNonBlocking()
{
unsigned long iMode = 1;
if(!handle) { return false; }
#ifdef WIN32
ioctlsocket(handle, FIONBIO, &iMode);
#else
ioctl(handle, FIONBIO, &iMode);
#endif
return true;
}
int UDPSocket::SendTo(const NetworkAddress & r, const char * b, size_t l) {
if(!handle) { return -1; }
return sendto(handle, b, l, 0, (struct sockaddr*)&r.addr, r.Length());
}
int UDPSocket::SendTo(const NetworkAddress & r, const std::string & s) {
if(!handle) { return -1; }
return sendto(handle, s.data(), s.length(), 0, (struct sockaddr*)&r.addr, r.Length());
}
int UDPSocket::RecvFrom(NetworkAddress & r, char * b, size_t l) {
if(!handle) { return -1; }
r.af = this->af;
int x = r.Length();
int i = recvfrom(handle, b, l, 0, (struct sockaddr*)&r.addr, &x);
if(i < 0) {
#ifdef WIN32
if(WSAGetLastError() == WSAEWOULDBLOCK) {
#else
if(errno == EAGAIN || errno == EWOULDBLOCK) {
#endif
return 0;
}
}
return i;
}
int UDPSocket::RecvFrom(NetworkAddress & r, std::string & s) {
if(!handle) { return -1; }
r.af = this->af;
int x = r.Length();
char f[2000]; // MTU of most networks is limited to 1500, so this should be enough space ;)
int i = recvfrom(handle, f, 2000, 0, (struct sockaddr*)&r.addr, &x);
if(i > 0) {
s.assign(f, i);
} else if(i < 0) {
#ifdef WIN32
if(WSAGetLastError() == WSAEWOULDBLOCK) {
#else
if(errno == EAGAIN || errno == EWOULDBLOCK) {
#endif
return 0;
}
}
return i;
}
}
|
#include "network_os.h"
#include "net/UDPSocket.hpp"
namespace network {
UDPSocket::UDPSocket() : bound(false), handle(0), af(NETA_UNDEF) { }
UDPSocket::~UDPSocket() {
Close();
}
bool UDPSocket::Init(ADDRTYPE afn) {
if(handle) {
Close();
}
this->af = afn;
int sc;
sc = socket(afn, SOCK_DGRAM, IPPROTO_UDP);
if(INVALID_SOCKET == sc) {
return false;
}
handle = sc;
return true;
}
bool UDPSocket::Bind(NetworkAddress & local) {
if(!handle) { return false; }
long v = 1;
if(setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, (char*)&v, sizeof(long))) {
return false;
}
if(bind(handle, (struct sockaddr*)&local.addr, local.Length())) {
return false;
}
laddr = local;
bound = true;
return true;
}
void UDPSocket::Close() {
if(!handle) { return; }
#ifdef WIN32
closesocket(handle);
#else
close(handle);
#endif
handle = 0;
}
bool UDPSocket::IsBound() const {
return this->bound;
}
bool UDPSocket::SetNonBlocking()
{
unsigned long iMode = 1;
if(!handle) { return false; }
#ifdef WIN32
ioctlsocket(handle, FIONBIO, &iMode);
#else
ioctl(handle, FIONBIO, &iMode);
#endif
return true;
}
int UDPSocket::SendTo(const NetworkAddress & r, const char * b, size_t l) {
if(!handle) { return -1; }
return sendto(handle, b, l, 0, (struct sockaddr*)&r.addr, r.Length());
}
int UDPSocket::SendTo(const NetworkAddress & r, const std::string & s) {
if(!handle) { return -1; }
return sendto(handle, s.data(), s.length(), 0, (struct sockaddr*)&r.addr, r.Length());
}
int UDPSocket::RecvFrom(NetworkAddress & r, char * b, size_t l) {
if(!handle) { return -1; }
r.af = this->af;
socklen_t x = r.Length();
int i = recvfrom(handle, b, l, 0, (struct sockaddr*)&r.addr, &x);
if(i < 0) {
#ifdef WIN32
if(WSAGetLastError() == WSAEWOULDBLOCK) {
#else
if(errno == EAGAIN || errno == EWOULDBLOCK) {
#endif
return 0;
}
}
return i;
}
int UDPSocket::RecvFrom(NetworkAddress & r, std::string & s) {
if(!handle) { return -1; }
r.af = this->af;
socklen_t x = r.Length();
char f[2000]; // MTU of most networks is limited to 1500, so this should be enough space ;)
int i = recvfrom(handle, f, 2000, 0, (struct sockaddr*)&r.addr, &x);
if(i > 0) {
s.assign(f, i);
} else if(i < 0) {
#ifdef WIN32
if(WSAGetLastError() == WSAEWOULDBLOCK) {
#else
if(errno == EAGAIN || errno == EWOULDBLOCK) {
#endif
return 0;
}
}
return i;
}
}
| Use socklen_t in UDP | Use socklen_t in UDP
| C++ | mit | Meisaka/NetPort |
2d5c445df4b7245ed2dd65bd3d988e46e4e27f8e | test/test_charset.cpp | test/test_charset.cpp | #include "task.h"
#include "utest.h"
#include "text/config.h"
#include "vision/color.h"
#include "math/epsilon.h"
#include "tasks/charset.h"
using namespace nano;
NANO_BEGIN_MODULE(test_charset)
NANO_CASE(construction)
{
// <charset, color mode, number of outputs/classes/characters>
std::vector<std::tuple<charset_type, color_mode, tensor_size_t>> configs;
configs.emplace_back(charset_type::digit, color_mode::luma, tensor_size_t(10));
configs.emplace_back(charset_type::lalpha, color_mode::rgba, tensor_size_t(26));
configs.emplace_back(charset_type::ualpha, color_mode::luma, tensor_size_t(26));
configs.emplace_back(charset_type::alpha, color_mode::luma, tensor_size_t(52));
configs.emplace_back(charset_type::alphanum, color_mode::rgba, tensor_size_t(62));
for (const auto& config : configs)
{
const auto type = std::get<0>(config);
const auto mode = std::get<1>(config);
const auto irows = tensor_size_t(17);
const auto icols = tensor_size_t(16);
const auto osize = std::get<2>(config);
const auto count = size_t(2 * osize);
const auto fsize = size_t(1); // folds
const auto idims = tensor3d_dims_t{(mode == color_mode::rgba) ? 4 : 1, irows, icols};
const auto odims = tensor3d_dims_t{osize, 1, 1};
auto task = get_tasks().get("synth-charset", to_params(
"type", type, "color", mode, "irows", irows, "icols", icols, "count", count));
NANO_CHECK_EQUAL(task->load(), true);
NANO_CHECK_EQUAL(task->idims(), idims);
NANO_CHECK_EQUAL(task->odims(), odims);
NANO_CHECK_EQUAL(task->fsize(), fsize);
NANO_CHECK_EQUAL(task->size(), count);
}
}
NANO_CASE(from_params)
{
auto task = get_tasks().get("synth-charset", "type=alpha,color=rgb,irows=18,icols=17,count=102");
NANO_CHECK(task->load());
const auto idims = tensor3d_dims_t{3, 18, 17};
const auto odims = tensor3d_dims_t{52, 1, 1};
const auto target_sum = scalar_t(2) - static_cast<scalar_t>(nano::size(odims));
NANO_CHECK_EQUAL(task->idims(), idims);
NANO_CHECK_EQUAL(task->odims(), odims);
NANO_CHECK_EQUAL(task->fsize(), size_t(1));
NANO_CHECK_EQUAL(task->size(), size_t(102));
NANO_CHECK_EQUAL(
task->size({0, protocol::train}) +
task->size({0, protocol::valid}) +
task->size({0, protocol::test}),
size_t(102));
for (const auto p : {protocol::train, protocol::valid, protocol::test})
{
const auto size = task->size({0, p});
for (size_t i = 0; i < size; ++ i)
{
const auto sample = task->get({0, p}, i);
const auto& input = sample.m_input;
const auto& target = sample.m_target;
NANO_CHECK_EQUAL(input.dims(), idims);
NANO_CHECK_EQUAL(target.dims(), odims);
NANO_CHECK_CLOSE(target.vector().sum(), target_sum, epsilon0<scalar_t>());
}
}
const size_t max_duplicates = 0;
NANO_CHECK_LESS_EQUAL(nano::check_duplicates(*task), max_duplicates);
NANO_CHECK_LESS_EQUAL(nano::check_intersection(*task), max_duplicates);
}
NANO_CASE(shuffle)
{
auto task = get_tasks().get("synth-charset", "type=alpha,color=rgb,irows=18,icols=17,count=102");
NANO_CHECK(task->load());
for (const auto p : {protocol::train, protocol::valid, protocol::test})
{
const auto fold = fold_t{0, p};
const auto size = task->size(fold);
std::map<size_t, size_t> iohashes;
for (size_t i = 0; i < size; ++ i)
{
iohashes[task->ihash(fold, i)] = task->ohash(fold, i);
}
for (auto t = 0; t < 8; ++ t)
{
task->shuffle(fold);
NANO_REQUIRE_EQUAL(task->size(fold), size);
for (size_t i = 0; i < size; ++ i)
{
const auto ihash = task->ihash(fold, i);
const auto ohash = task->ohash(fold, i);
const auto it = iohashes.find(ihash);
NANO_REQUIRE(it != iohashes.end());
NANO_CHECK_EQUAL(it->second, ohash);
}
}
}
}
NANO_END_MODULE()
| #include "task.h"
#include "utest.h"
#include "text/config.h"
#include "vision/color.h"
#include "math/epsilon.h"
#include "tasks/charset.h"
using namespace nano;
NANO_BEGIN_MODULE(test_charset)
NANO_CASE(construction)
{
// <charset, color mode, number of outputs/classes/characters>
std::vector<std::tuple<charset_type, color_mode, tensor_size_t>> configs;
configs.emplace_back(charset_type::digit, color_mode::luma, tensor_size_t(10));
configs.emplace_back(charset_type::lalpha, color_mode::rgba, tensor_size_t(26));
configs.emplace_back(charset_type::ualpha, color_mode::luma, tensor_size_t(26));
configs.emplace_back(charset_type::alpha, color_mode::luma, tensor_size_t(52));
configs.emplace_back(charset_type::alphanum, color_mode::rgba, tensor_size_t(62));
for (const auto& config : configs)
{
const auto type = std::get<0>(config);
const auto mode = std::get<1>(config);
const auto irows = tensor_size_t(17);
const auto icols = tensor_size_t(16);
const auto osize = std::get<2>(config);
const auto count = size_t(2 * osize);
const auto fsize = size_t(1); // folds
const auto idims = tensor3d_dims_t{(mode == color_mode::rgba) ? 4 : 1, irows, icols};
const auto odims = tensor3d_dims_t{osize, 1, 1};
auto task = get_tasks().get("synth-charset", to_params(
"type", type, "color", mode, "irows", irows, "icols", icols, "count", count));
NANO_CHECK_EQUAL(task->load(), true);
NANO_CHECK_EQUAL(task->idims(), idims);
NANO_CHECK_EQUAL(task->odims(), odims);
NANO_CHECK_EQUAL(task->fsize(), fsize);
NANO_CHECK_EQUAL(task->size(), count);
}
}
NANO_CASE(from_params)
{
auto task = get_tasks().get("synth-charset", "type=alpha,color=rgb,irows=18,icols=17,count=102");
NANO_CHECK(task->load());
const auto idims = tensor3d_dims_t{3, 18, 17};
const auto odims = tensor3d_dims_t{52, 1, 1};
const auto target_sum = scalar_t(2) - static_cast<scalar_t>(nano::size(odims));
NANO_CHECK_EQUAL(task->idims(), idims);
NANO_CHECK_EQUAL(task->odims(), odims);
NANO_CHECK_EQUAL(task->fsize(), size_t(1));
NANO_CHECK_EQUAL(task->size(), size_t(102));
NANO_CHECK_EQUAL(
task->size({0, protocol::train}) +
task->size({0, protocol::valid}) +
task->size({0, protocol::test}),
size_t(102));
for (const auto p : {protocol::train, protocol::valid, protocol::test})
{
const auto size = task->size({0, p});
for (size_t i = 0; i < size; ++ i)
{
const auto sample = task->get({0, p}, i);
const auto& input = sample.m_input;
const auto& target = sample.m_target;
NANO_CHECK_EQUAL(input.dims(), idims);
NANO_CHECK_EQUAL(target.dims(), odims);
NANO_CHECK_CLOSE(target.vector().sum(), target_sum, epsilon0<scalar_t>());
}
}
const size_t max_duplicates = 0;
NANO_CHECK_LESS_EQUAL(nano::check_duplicates(*task), max_duplicates);
NANO_CHECK_LESS_EQUAL(nano::check_intersection(*task), max_duplicates);
}
NANO_CASE(shuffle)
{
auto task = get_tasks().get("synth-charset", "type=alpha,color=rgb,irows=18,icols=17,count=102");
NANO_CHECK(task->load());
for (const auto p : {protocol::train, protocol::valid, protocol::test})
{
const auto fold = fold_t{0, p};
const auto size = task->size(fold);
std::map<size_t, size_t> iohashes;
for (size_t i = 0; i < size; ++ i)
{
iohashes[task->ihash(fold, i)] = task->ohash(fold, i);
}
for (auto t = 0; t < 8; ++ t)
{
task->shuffle(fold);
NANO_REQUIRE_EQUAL(task->size(fold), size);
for (size_t i = 0; i < size; ++ i)
{
const auto ihash = task->ihash(fold, i);
const auto ohash = task->ohash(fold, i);
const auto it = iohashes.find(ihash);
NANO_REQUIRE(it != iohashes.end());
NANO_CHECK_EQUAL(it->second, ohash);
}
}
}
}
NANO_CASE(minibatch)
{
auto task = get_tasks().get("synth-charset", "type=alpha,color=rgb,irows=18,icols=17,count=102");
NANO_CHECK(task->load());
for (const auto p : {protocol::train, protocol::valid, protocol::test})
{
const auto fold = fold_t{0, p};
const auto size = task->size(fold);
for (size_t count = 1; count < std::min(size_t(8), size); ++ count)
{
const auto minibatch = task->get(fold, size_t(0), count);
NANO_CHECK_EQUAL(minibatch.idims(), task->idims());
NANO_CHECK_EQUAL(minibatch.odims(), task->odims());
NANO_CHECK_EQUAL(minibatch.count(), static_cast<tensor_size_t>(count));
for (auto i = 0; i < static_cast<tensor_size_t>(count); ++ i)
{
const auto sample = task->get(fold, static_cast<size_t>(i));
const auto epsilon = epsilon0<scalar_t>();
NANO_CHECK_EIGEN_CLOSE(sample.m_input.array(), minibatch.idata(i).array(), epsilon);
NANO_CHECK_EIGEN_CLOSE(sample.m_target.array(), minibatch.odata(i).array(), epsilon);
}
}
}
}
NANO_END_MODULE()
| add unit test for minibatch generation | add unit test for minibatch generation
| C++ | mit | accosmin/nano,accosmin/nanocv,accosmin/nanocv,accosmin/nanocv,accosmin/nano,accosmin/nano |
f66fc7ec279294b57a570d2bc76549256dd4fd71 | test/test_charset.cpp | test/test_charset.cpp | #include "utest.hpp"
#include "tasks/task_charset.h"
NANO_BEGIN_MODULE(test_charset)
NANO_CASE(construction)
{
using namespace nano;
// <charset, color mode, number of outputs/classes/characters>
std::vector<std::tuple<charset, color_mode, tensor_size_t>> configs;
configs.emplace_back(charset::digit, color_mode::luma, tensor_size_t(10));
configs.emplace_back(charset::lalpha, color_mode::rgba, tensor_size_t(26));
configs.emplace_back(charset::ualpha, color_mode::luma, tensor_size_t(26));
configs.emplace_back(charset::alpha, color_mode::luma, tensor_size_t(52));
configs.emplace_back(charset::alphanum, color_mode::rgba, tensor_size_t(62));
for (const auto& config : configs)
{
const auto type = std::get<0>(config);
const auto mode = std::get<1>(config);
const auto irows = size_t(17);
const auto icols = size_t(16);
const auto osize = std::get<2>(config);
const auto count = size_t(10 * osize);
const auto fsize = size_t(1); // folds
charset_task_t task(type, mode, irows, icols, count);
NANO_CHECK_EQUAL(task.load(), true);
NANO_CHECK_EQUAL(task.irows(), irows);
NANO_CHECK_EQUAL(task.icols(), icols);
NANO_CHECK_EQUAL(task.osize(), osize);
NANO_CHECK_EQUAL(task.n_folds(), fsize);
NANO_CHECK_EQUAL(task.color(), mode);
NANO_CHECK_EQUAL(task.n_images(), count);
NANO_CHECK_EQUAL(task.n_samples(), count);
for (size_t i = 0; i < task.n_images(); ++ i)
{
NANO_CHECK_EQUAL(task.image(i).mode(), mode);
NANO_CHECK_EQUAL(task.image(i).rows(), irows);
NANO_CHECK_EQUAL(task.image(i).cols(), icols);
}
}
}
NANO_CASE(from_params)
{
using namespace nano;
charset_task_t task("type=alpha,color=rgb,irows=23,icols=29,count=102");
NANO_CHECK(task.load());
NANO_CHECK_EQUAL(task.irows(), 23);
NANO_CHECK_EQUAL(task.icols(), 29);
NANO_CHECK_EQUAL(task.idims(), 3);
NANO_CHECK_EQUAL(task.osize(), 52);
NANO_CHECK_EQUAL(task.n_folds(), size_t(1));
NANO_CHECK_EQUAL(task.n_samples(), size_t(102));
NANO_CHECK_EQUAL(
task.n_samples({0, protocol::train}) +
task.n_samples({0, protocol::valid}) +
task.n_samples({0, protocol::test}),
size_t(102));
for (const auto p : {protocol::train, protocol::valid, protocol::test})
{
const auto size = task.n_samples({0, p});
for (size_t i = 0; i < size; ++ i)
{
const auto input = task.input({0, p}, i);
const auto target = task.target({0, p}, i);
NANO_CHECK_EQUAL(input.size<0>(), 3);
NANO_CHECK_EQUAL(input.size<1>(), 23);
NANO_CHECK_EQUAL(input.size<2>(), 29);
NANO_CHECK_EQUAL(target.size(), 52);
}
}
}
NANO_END_MODULE()
| #include "utest.hpp"
#include "task_iterator.h"
#include "tasks/task_charset.h"
using namespace nano;
NANO_BEGIN_MODULE(test_charset)
NANO_CASE(construction)
{
// <charset, color mode, number of outputs/classes/characters>
std::vector<std::tuple<charset, color_mode, tensor_size_t>> configs;
configs.emplace_back(charset::digit, color_mode::luma, tensor_size_t(10));
configs.emplace_back(charset::lalpha, color_mode::rgba, tensor_size_t(26));
configs.emplace_back(charset::ualpha, color_mode::luma, tensor_size_t(26));
configs.emplace_back(charset::alpha, color_mode::luma, tensor_size_t(52));
configs.emplace_back(charset::alphanum, color_mode::rgba, tensor_size_t(62));
for (const auto& config : configs)
{
const auto type = std::get<0>(config);
const auto mode = std::get<1>(config);
const auto irows = size_t(17);
const auto icols = size_t(16);
const auto osize = std::get<2>(config);
const auto count = size_t(10 * osize);
const auto fsize = size_t(1); // folds
charset_task_t task(type, mode, irows, icols, count);
NANO_CHECK_EQUAL(task.load(), true);
NANO_CHECK_EQUAL(task.irows(), irows);
NANO_CHECK_EQUAL(task.icols(), icols);
NANO_CHECK_EQUAL(task.osize(), osize);
NANO_CHECK_EQUAL(task.n_folds(), fsize);
NANO_CHECK_EQUAL(task.color(), mode);
NANO_CHECK_EQUAL(task.n_images(), count);
NANO_CHECK_EQUAL(task.n_samples(), count);
for (size_t i = 0; i < task.n_images(); ++ i)
{
NANO_CHECK_EQUAL(task.image(i).mode(), mode);
NANO_CHECK_EQUAL(task.image(i).rows(), irows);
NANO_CHECK_EQUAL(task.image(i).cols(), icols);
}
}
}
NANO_CASE(minibatch_iterator)
{
charset_task_t task(charset::digit, color_mode::rgba, 16, 16, 10000);
NANO_CHECK_EQUAL(task.load(), true);
const auto batch = size_t(123);
const auto fold = fold_t{0, protocol::train};
const auto fold_size = task.n_samples(fold);
minibatch_iterator_t<shuffle::off> it(task, fold, batch);
for (size_t i = 0; i < 1000; ++ i)
{
NANO_CHECK_LESS(it.begin(), it.end());
NANO_CHECK_LESS_EQUAL(it.end(), fold_size);
NANO_CHECK_LESS_EQUAL(it.end(), it.begin() + batch);
const auto end = it.end();
it.next();
if (end == fold_size)
{
NANO_CHECK_EQUAL(it.begin(), size_t(0));
NANO_CHECK_EQUAL(it.end(), batch);
}
else
{
NANO_CHECK_EQUAL(end, it.begin());
}
}
}
NANO_CASE(from_params)
{
charset_task_t task("type=alpha,color=rgb,irows=23,icols=29,count=102");
NANO_CHECK(task.load());
NANO_CHECK_EQUAL(task.irows(), 23);
NANO_CHECK_EQUAL(task.icols(), 29);
NANO_CHECK_EQUAL(task.idims(), 3);
NANO_CHECK_EQUAL(task.osize(), 52);
NANO_CHECK_EQUAL(task.n_folds(), size_t(1));
NANO_CHECK_EQUAL(task.n_samples(), size_t(102));
NANO_CHECK_EQUAL(
task.n_samples({0, protocol::train}) +
task.n_samples({0, protocol::valid}) +
task.n_samples({0, protocol::test}),
size_t(102));
for (const auto p : {protocol::train, protocol::valid, protocol::test})
{
const auto size = task.n_samples({0, p});
for (size_t i = 0; i < size; ++ i)
{
const auto input = task.input({0, p}, i);
const auto target = task.target({0, p}, i);
NANO_CHECK_EQUAL(input.size<0>(), 3);
NANO_CHECK_EQUAL(input.size<1>(), 23);
NANO_CHECK_EQUAL(input.size<2>(), 29);
NANO_CHECK_EQUAL(target.size(), 52);
}
}
}
NANO_END_MODULE()
| extend unit test | extend unit test
| C++ | mit | accosmin/nano,accosmin/nanocv,accosmin/nanocv,accosmin/nano,accosmin/nano,accosmin/nanocv |
79330bcbded064b76ac7fb78850d72b04c7ba73d | tntdb/src/oracle/connection.cpp | tntdb/src/oracle/connection.cpp | /*
* Copyright (C) 2007 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <tntdb/oracle/connection.h>
#include <tntdb/oracle/statement.h>
#include <tntdb/oracle/error.h>
#include <tntdb/result.h>
#include <tntdb/statement.h>
#include <cxxtools/log.h>
log_define("tntdb.oracle.connection")
namespace tntdb
{
namespace oracle
{
namespace error
{
log_define("tntdb.oracle.error")
inline void checkError(OCIError* errhp, sword ret, const char* function)
{
switch (ret)
{
case OCI_SUCCESS:
break;
case OCI_SUCCESS_WITH_INFO:
log_warn(function << ": OCI_SUCCESS_WITH_INFO");
break;
case OCI_NEED_DATA:
log_warn(function << ": OCI_NEED_DATA");
throw Error(errhp, function);
case OCI_NO_DATA:
log_warn(function << ": OCI_NO_DATA");
throw NotFound();
case OCI_ERROR:
throw Error(errhp, function);
case OCI_INVALID_HANDLE:
log_error("OCI_INVALID_HANDLE");
throw InvalidHandle(function);
case OCI_STILL_EXECUTING:
log_error("OCI_STILL_EXECUTING");
throw StillExecuting(function);
case OCI_CONTINUE:
log_error("OCI_CONTINUE");
throw ErrorContinue(function);
}
}
}
void Connection::checkError(sword ret, const char* function) const
{
error::checkError(getErrorHandle(), ret, function);
}
void Connection::logon(const std::string& dblink, const std::string& user, const std::string& password)
{
log_debug("logon \"" << dblink << "\" user=\"" << user << '"');
sword ret;
log_debug("create oracle environment");
ret = OCIEnvCreate(&envhp, OCI_OBJECT, 0, 0, 0, 0, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create environment handle");
log_debug("environment handle => " << envhp);
log_debug("allocate error handle");
ret = OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create error handle");
log_debug("error handle => " << errhp);
log_debug("allocate server handle");
ret = OCIHandleAlloc(envhp, (void**)&srvhp, OCI_HTYPE_SERVER, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SERVER)");
log_debug("server handle => " << srvhp);
log_debug("allocate service handle");
ret = OCIHandleAlloc(envhp, (void**)&svchp, OCI_HTYPE_SVCCTX, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SVCCTX)");
log_debug("service handle => " << svchp);
log_debug("attach to server");
ret = OCIServerAttach(srvhp, errhp, reinterpret_cast<const text*>(dblink.data()), dblink.size(), 0);
checkError(ret, "OCIServerAttach");
/* set attribute server context in the service context */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, srvhp, 0, OCI_ATTR_SERVER, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SERVER)");
log_debug("allocate session handle");
ret = OCIHandleAlloc((dvoid*)envhp, (dvoid**)&usrhp, OCI_HTYPE_SESSION, 0, (dvoid**)0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SESSION)");
/* set username attribute in user session handle */
log_debug("set username attribute in session handle");
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(user.data())),
user.size(), OCI_ATTR_USERNAME, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_USERNAME)");
/* set password attribute in user session handle */
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(password.data())),
password.size(), OCI_ATTR_PASSWORD, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_PASSWORD)");
/* start session */
log_debug("start session");
ret = OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT);
checkError(ret, "OCISessionBegin");
/* set user session attrubte in the service context handle */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, usrhp, 0, OCI_ATTR_SESSION, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SESSION)");
}
namespace
{
std::string extractAttribute(std::string& value, const std::string& key)
{
std::string::size_type p0 = value.find(key);
if (p0 == std::string::npos)
return std::string();
if (p0 > 0 && value.at(p0 - 1) != ';')
return std::string();
std::string::size_type p1 = value.find(';', p0);
if (p1 == std::string::npos)
p1 = value.size();
std::string::size_type n = p1 - p0;
std::string ret(value, p0 + key.size(), n - key.size());
if (p0 > 0)
value.erase(p0 - 1, n + 1);
else
value.erase(p0, n);
return ret;
}
}
Connection::Connection(const char* conninfo_)
: envhp(0),
srvhp(0),
errhp(0),
usrhp(0),
svchp(0),
transactionActive(0)
{
std::string conninfo(conninfo_);
std::string user = extractAttribute(conninfo, "user=");
std::string passwd = extractAttribute(conninfo, "passwd=");
logon(conninfo, user, passwd);
}
Connection::~Connection()
{
if (envhp)
{
sword ret;
clearStatementCache();
pingStmt = tntdb::Statement();
try
{
log_debug("OCIServerDetach");
ret = OCIServerDetach(srvhp, errhp, OCI_DEFAULT);
checkError(ret, "OCIServerDetach");
}
catch (const std::exception& e)
{
log_error(e.what());
}
try
{
log_debug("OCISessionEnd");
ret = OCISessionEnd(svchp, errhp, usrhp, OCI_DEFAULT);
checkError(ret, "OCISessionEnd");
}
catch (const std::exception& e)
{
log_error(e.what());
}
log_debug("OCIHandleFree(" << envhp << ')');
ret = OCIHandleFree(envhp, OCI_HTYPE_ENV);
if (ret == OCI_SUCCESS)
log_debug("handle released");
else
log_error("OCIHandleFree failed");
}
}
void Connection::beginTransaction()
{
//log_debug("OCITransStart(" << svchp << ", " << errhp << ')');
//checkError(OCITransStart(svchp, errhp, 10, OCI_TRANS_NEW), "OCITransStart");
++transactionActive;
}
void Connection::commitTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransCommit(" << srvhp << ", " << errhp << ')');
checkError(OCITransCommit(svchp, errhp, OCI_DEFAULT), "OCITransCommit");
}
}
void Connection::rollbackTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransRollback(" << srvhp << ", " << errhp << ')');
checkError(OCITransRollback(svchp, errhp, OCI_DEFAULT), "OCITransRollback");
}
}
Connection::size_type Connection::execute(const std::string& query)
{
return prepare(query).execute();
}
tntdb::Result Connection::select(const std::string& query)
{
return prepare(query).select();
}
Row Connection::selectRow(const std::string& query)
{
return prepare(query).selectRow();
}
Value Connection::selectValue(const std::string& query)
{
return prepare(query).selectValue();
}
tntdb::Statement Connection::prepare(const std::string& query)
{
return tntdb::Statement(new Statement(this, query));
}
bool Connection::ping()
{
try
{
if (!pingStmt)
pingStmt = prepare("select 1 from dual");
pingStmt.selectValue();
return true;
}
catch (const Error&)
{
return false;
}
}
}
}
| /*
* Copyright (C) 2007 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <tntdb/oracle/connection.h>
#include <tntdb/oracle/statement.h>
#include <tntdb/oracle/error.h>
#include <tntdb/result.h>
#include <tntdb/statement.h>
#include <cxxtools/log.h>
log_define("tntdb.oracle.connection")
namespace tntdb
{
namespace oracle
{
namespace error
{
log_define("tntdb.oracle.error")
inline void checkError(OCIError* errhp, sword ret, const char* function)
{
switch (ret)
{
case OCI_SUCCESS:
break;
case OCI_SUCCESS_WITH_INFO:
log_warn(function << ": OCI_SUCCESS_WITH_INFO");
break;
case OCI_NEED_DATA:
log_warn(function << ": OCI_NEED_DATA");
throw Error(errhp, function);
case OCI_NO_DATA:
log_warn(function << ": OCI_NO_DATA");
throw NotFound();
case OCI_ERROR:
throw Error(errhp, function);
case OCI_INVALID_HANDLE:
log_error("OCI_INVALID_HANDLE");
throw InvalidHandle(function);
case OCI_STILL_EXECUTING:
log_error("OCI_STILL_EXECUTING");
throw StillExecuting(function);
case OCI_CONTINUE:
log_error("OCI_CONTINUE");
throw ErrorContinue(function);
}
}
}
void Connection::checkError(sword ret, const char* function) const
{
error::checkError(getErrorHandle(), ret, function);
}
void Connection::logon(const std::string& dblink, const std::string& user, const std::string& password)
{
log_debug("logon \"" << dblink << "\" user=\"" << user << '"');
sword ret;
log_debug("create oracle environment");
ret = OCIEnvCreate(&envhp, OCI_OBJECT, 0, 0, 0, 0, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create environment handle");
log_debug("environment handle => " << envhp);
log_debug("allocate error handle");
ret = OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create error handle");
log_debug("error handle => " << errhp);
log_debug("allocate server handle");
ret = OCIHandleAlloc(envhp, (void**)&srvhp, OCI_HTYPE_SERVER, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SERVER)");
log_debug("server handle => " << srvhp);
log_debug("allocate service handle");
ret = OCIHandleAlloc(envhp, (void**)&svchp, OCI_HTYPE_SVCCTX, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SVCCTX)");
log_debug("service handle => " << svchp);
log_debug("attach to server");
ret = OCIServerAttach(srvhp, errhp, reinterpret_cast<const text*>(dblink.data()), dblink.size(), 0);
checkError(ret, "OCIServerAttach");
/* set attribute server context in the service context */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, srvhp, 0, OCI_ATTR_SERVER, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SERVER)");
log_debug("allocate session handle");
ret = OCIHandleAlloc((dvoid*)envhp, (dvoid**)&usrhp, OCI_HTYPE_SESSION, 0, (dvoid**)0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SESSION)");
/* set username attribute in user session handle */
log_debug("set username attribute in session handle");
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(user.data())),
user.size(), OCI_ATTR_USERNAME, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_USERNAME)");
/* set password attribute in user session handle */
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(password.data())),
password.size(), OCI_ATTR_PASSWORD, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_PASSWORD)");
/* start session */
log_debug("start session");
ret = OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT);
checkError(ret, "OCISessionBegin");
/* set user session attrubte in the service context handle */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, usrhp, 0, OCI_ATTR_SESSION, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SESSION)");
}
namespace
{
std::string extractAttribute(std::string& value, const std::string& key)
{
std::string::size_type p0 = value.find(key);
if (p0 == std::string::npos)
return std::string();
if (p0 > 0 && value.at(p0 - 1) != ';')
return std::string();
std::string::size_type p1 = value.find(';', p0);
if (p1 == std::string::npos)
p1 = value.size();
std::string::size_type n = p1 - p0;
std::string ret(value, p0 + key.size(), n - key.size());
if (p0 > 0)
value.erase(p0 - 1, n + 1);
else
value.erase(p0, n);
return ret;
}
}
Connection::Connection(const char* conninfo_)
: envhp(0),
srvhp(0),
errhp(0),
usrhp(0),
svchp(0),
transactionActive(0)
{
std::string conninfo(conninfo_);
std::string user = extractAttribute(conninfo, "user=");
std::string passwd = extractAttribute(conninfo, "passwd=");
logon(conninfo, user, passwd);
}
Connection::~Connection()
{
if (envhp)
{
sword ret;
clearStatementCache();
pingStmt = tntdb::Statement();
try
{
log_debug("OCISessionEnd");
ret = OCISessionEnd(svchp, errhp, usrhp, OCI_DEFAULT);
checkError(ret, "OCISessionEnd");
}
catch (const std::exception& e)
{
log_error(e.what());
}
try
{
log_debug("OCIServerDetach");
ret = OCIServerDetach(srvhp, errhp, OCI_DEFAULT);
checkError(ret, "OCIServerDetach");
}
catch (const std::exception& e)
{
log_error(e.what());
}
log_debug("OCIHandleFree(" << envhp << ')');
ret = OCIHandleFree(envhp, OCI_HTYPE_ENV);
if (ret == OCI_SUCCESS)
log_debug("handle released");
else
log_error("OCIHandleFree failed");
}
}
void Connection::beginTransaction()
{
//log_debug("OCITransStart(" << svchp << ", " << errhp << ')');
//checkError(OCITransStart(svchp, errhp, 10, OCI_TRANS_NEW), "OCITransStart");
++transactionActive;
}
void Connection::commitTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransCommit(" << srvhp << ", " << errhp << ')');
checkError(OCITransCommit(svchp, errhp, OCI_DEFAULT), "OCITransCommit");
}
}
void Connection::rollbackTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransRollback(" << srvhp << ", " << errhp << ')');
checkError(OCITransRollback(svchp, errhp, OCI_DEFAULT), "OCITransRollback");
}
}
Connection::size_type Connection::execute(const std::string& query)
{
return prepare(query).execute();
}
tntdb::Result Connection::select(const std::string& query)
{
return prepare(query).select();
}
Row Connection::selectRow(const std::string& query)
{
return prepare(query).selectRow();
}
Value Connection::selectValue(const std::string& query)
{
return prepare(query).selectValue();
}
tntdb::Statement Connection::prepare(const std::string& query)
{
return tntdb::Statement(new Statement(this, query));
}
bool Connection::ping()
{
try
{
if (!pingStmt)
pingStmt = prepare("select 1 from dual");
pingStmt.selectValue();
return true;
}
catch (const Error&)
{
return false;
}
}
}
}
| clean up of oracle connection in proper order | clean up of oracle connection in proper order
git-svn-id: 668645f5c615c5338f34c47d21d9e584f02cf8c0@161 8aebba32-5d12-0410-a889-bbfed4e15866
| C++ | lgpl-2.1 | maekitalo/tntdb,OlafRadicke/tntdb,OlafRadicke/tntdb,maekitalo/tntdb |
2841aaae7e5d53cc5b634873a8d689119556c875 | src/base/trace.hh | src/base/trace.hh | /*
* Copyright (c) 2014, 2019 ARM Limited
* All rights reserved
*
* Copyright (c) 2001-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Andrew Bardsley
*/
#ifndef __BASE_TRACE_HH__
#define __BASE_TRACE_HH__
#include <string>
#include "base/cprintf.hh"
#include "base/debug.hh"
#include "base/match.hh"
#include "base/types.hh"
#include "sim/core.hh"
namespace Trace {
/** Debug logging base class. Handles formatting and outputting
* time/name/message messages */
class Logger
{
protected:
/** Name match for objects to ignore */
ObjectMatch ignore;
public:
/** Log a single message */
template <typename ...Args>
void dprintf(Tick when, const std::string &name, const char *fmt,
const Args &...args)
{
dprintf_flag(when, name, "", fmt, args...);
}
/** Log a single message with a flag prefix. */
template <typename ...Args>
void dprintf_flag(Tick when, const std::string &name,
const std::string &flag,
const char *fmt, const Args &...args)
{
if (!name.empty() && ignore.match(name))
return;
std::ostringstream line;
ccprintf(line, fmt, args...);
logMessage(when, name, flag, line.str());
}
/** Dump a block of data of length len */
void dump(Tick when, const std::string &name,
const void *d, int len, const std::string &flag);
/** Log formatted message */
virtual void logMessage(Tick when, const std::string &name,
const std::string &flag, const std::string &message) = 0;
/** Return an ostream that can be used to send messages to
* the 'same place' as formatted logMessage messages. This
* can be implemented to use a logger's underlying ostream,
* to provide an ostream which formats the output in some
* way, or just set to one of std::cout, std::cerr */
virtual std::ostream &getOstream() = 0;
/** Set objects to ignore */
void setIgnore(ObjectMatch &ignore_) { ignore = ignore_; }
/** Add objects to ignore */
void addIgnore(const ObjectMatch &ignore_) { ignore.add(ignore_); }
virtual ~Logger() { }
};
/** Logging wrapper for ostreams with the format:
* <when>: <name>: <message-body> */
class OstreamLogger : public Logger
{
protected:
std::ostream &stream;
public:
OstreamLogger(std::ostream &stream_) : stream(stream_)
{ }
void logMessage(Tick when, const std::string &name,
const std::string &flag, const std::string &message) override;
std::ostream &getOstream() override { return stream; }
};
/** Get the current global debug logger. This takes ownership of the given
* logger which should be allocated using 'new' */
Logger *getDebugLogger();
/** Get the ostream from the current global logger */
std::ostream &output();
/** Delete the current global logger and assign a new one */
void setDebugLogger(Logger *logger);
/** Enable/disable debug logging */
void enable();
void disable();
} // namespace Trace
// This silly little class allows us to wrap a string in a functor
// object so that we can give a name() that DPRINTF will like
struct StringWrap
{
std::string str;
StringWrap(const std::string &s) : str(s) {}
const std::string &operator()() const { return str; }
};
// Return the global context name "global". This function gets called when
// the DPRINTF macros are used in a context without a visible name() function
const std::string &name();
// Interface for things with names. (cf. SimObject but without other
// functionality). This is useful when using DPRINTF
class Named
{
protected:
const std::string _name;
public:
Named(const std::string &name_) : _name(name_) { }
public:
const std::string &name() const { return _name; }
};
//
// DPRINTF is a debugging trace facility that allows one to
// selectively enable tracing statements. To use DPRINTF, there must
// be a function or functor called name() that returns a const
// std::string & in the current scope.
//
// If you desire that the automatic printing not occur, use DPRINTFR
// (R for raw)
//
#if TRACING_ON
#define DTRACE(x) (Debug::x)
#define DDUMP(x, data, count) do { \
using namespace Debug; \
if (DTRACE(x)) \
Trace::getDebugLogger()->dump( \
curTick(), name(), data, count, #x); \
} while (0)
#define DPRINTF(x, ...) do { \
using namespace Debug; \
if (DTRACE(x)) { \
Trace::getDebugLogger()->dprintf_flag( \
curTick(), name(), #x, __VA_ARGS__); \
} \
} while (0)
#define DPRINTFS(x, s, ...) do { \
using namespace Debug; \
if (DTRACE(x)) { \
Trace::getDebugLogger()->dprintf_flag( \
curTick(), s->name(), #x, __VA_ARGS__); \
} \
} while (0)
#define DPRINTFR(x, ...) do { \
using namespace Debug; \
if (DTRACE(x)) { \
Trace::getDebugLogger()->dprintf_flag( \
(Tick)-1, std::string(), #x, __VA_ARGS__); \
} \
} while (0)
#define DDUMPN(data, count) do { \
Trace::getDebugLogger()->dump(curTick(), name(), data, count); \
} while (0)
#define DPRINTFN(...) do { \
Trace::getDebugLogger()->dprintf(curTick(), name(), __VA_ARGS__); \
} while (0)
#define DPRINTFNR(...) do { \
Trace::getDebugLogger()->dprintf((Tick)-1, std::string(), __VA_ARGS__); \
} while (0)
#else // !TRACING_ON
#define DTRACE(x) (false)
#define DDUMP(x, data, count) do {} while (0)
#define DPRINTF(x, ...) do {} while (0)
#define DPRINTFS(x, ...) do {} while (0)
#define DPRINTFR(...) do {} while (0)
#define DDUMPN(data, count) do {} while (0)
#define DPRINTFN(...) do {} while (0)
#define DPRINTFNR(...) do {} while (0)
#endif // TRACING_ON
#endif // __BASE_TRACE_HH__
| /*
* Copyright (c) 2014, 2019 ARM Limited
* All rights reserved
*
* Copyright (c) 2001-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Nathan Binkert
* Steve Reinhardt
* Andrew Bardsley
*/
#ifndef __BASE_TRACE_HH__
#define __BASE_TRACE_HH__
#include <string>
#include "base/cprintf.hh"
#include "base/debug.hh"
#include "base/match.hh"
#include "base/types.hh"
#include "sim/core.hh"
namespace Trace {
/** Debug logging base class. Handles formatting and outputting
* time/name/message messages */
class Logger
{
protected:
/** Name match for objects to ignore */
ObjectMatch ignore;
public:
/** Log a single message */
template <typename ...Args>
void dprintf(Tick when, const std::string &name, const char *fmt,
const Args &...args)
{
dprintf_flag(when, name, "", fmt, args...);
}
/** Log a single message with a flag prefix. */
template <typename ...Args>
void dprintf_flag(Tick when, const std::string &name,
const std::string &flag,
const char *fmt, const Args &...args)
{
if (!name.empty() && ignore.match(name))
return;
std::ostringstream line;
ccprintf(line, fmt, args...);
logMessage(when, name, flag, line.str());
}
/** Dump a block of data of length len */
void dump(Tick when, const std::string &name,
const void *d, int len, const std::string &flag);
/** Log formatted message */
virtual void logMessage(Tick when, const std::string &name,
const std::string &flag, const std::string &message) = 0;
/** Return an ostream that can be used to send messages to
* the 'same place' as formatted logMessage messages. This
* can be implemented to use a logger's underlying ostream,
* to provide an ostream which formats the output in some
* way, or just set to one of std::cout, std::cerr */
virtual std::ostream &getOstream() = 0;
/** Set objects to ignore */
void setIgnore(ObjectMatch &ignore_) { ignore = ignore_; }
/** Add objects to ignore */
void addIgnore(const ObjectMatch &ignore_) { ignore.add(ignore_); }
virtual ~Logger() { }
};
/** Logging wrapper for ostreams with the format:
* <when>: <name>: <message-body> */
class OstreamLogger : public Logger
{
protected:
std::ostream &stream;
public:
OstreamLogger(std::ostream &stream_) : stream(stream_)
{ }
void logMessage(Tick when, const std::string &name,
const std::string &flag, const std::string &message) override;
std::ostream &getOstream() override { return stream; }
};
/** Get the current global debug logger. This takes ownership of the given
* logger which should be allocated using 'new' */
Logger *getDebugLogger();
/** Get the ostream from the current global logger */
std::ostream &output();
/** Delete the current global logger and assign a new one */
void setDebugLogger(Logger *logger);
/** Enable/disable debug logging */
void enable();
void disable();
} // namespace Trace
// This silly little class allows us to wrap a string in a functor
// object so that we can give a name() that DPRINTF will like
struct StringWrap
{
std::string str;
StringWrap(const std::string &s) : str(s) {}
const std::string &operator()() const { return str; }
};
// Return the global context name "global". This function gets called when
// the DPRINTF macros are used in a context without a visible name() function
const std::string &name();
// Interface for things with names. (cf. SimObject but without other
// functionality). This is useful when using DPRINTF
class Named
{
protected:
const std::string _name;
public:
Named(const std::string &name_) : _name(name_) { }
public:
const std::string &name() const { return _name; }
};
//
// DPRINTF is a debugging trace facility that allows one to
// selectively enable tracing statements. To use DPRINTF, there must
// be a function or functor called name() that returns a const
// std::string & in the current scope.
//
// If you desire that the automatic printing not occur, use DPRINTFR
// (R for raw)
//
#if TRACING_ON
#define DTRACE(x) (Debug::x)
#define DDUMP(x, data, count) do { \
using namespace Debug; \
if (DTRACE(x)) \
Trace::getDebugLogger()->dump( \
curTick(), name(), data, count, #x); \
} while (0)
#define DPRINTF(x, ...) do { \
using namespace Debug; \
if (DTRACE(x)) { \
Trace::getDebugLogger()->dprintf_flag( \
curTick(), name(), #x, __VA_ARGS__); \
} \
} while (0)
#define DPRINTFS(x, s, ...) do { \
using namespace Debug; \
if (DTRACE(x)) { \
Trace::getDebugLogger()->dprintf_flag( \
curTick(), s->name(), #x, __VA_ARGS__); \
} \
} while (0)
#define DPRINTFR(x, ...) do { \
using namespace Debug; \
if (DTRACE(x)) { \
Trace::getDebugLogger()->dprintf_flag( \
(Tick)-1, std::string(), #x, __VA_ARGS__); \
} \
} while (0)
#define DDUMPN(data, count) do { \
Trace::getDebugLogger()->dump(curTick(), name(), data, count); \
} while (0)
#define DPRINTFN(...) do { \
Trace::getDebugLogger()->dprintf(curTick(), name(), __VA_ARGS__); \
} while (0)
#define DPRINTFNR(...) do { \
Trace::getDebugLogger()->dprintf((Tick)-1, std::string(), __VA_ARGS__); \
} while (0)
#define DPRINTF_UNCONDITIONAL(x, ...) do { \
Trace::getDebugLogger()->dprintf_flag( \
curTick(), name(), #x, __VA_ARGS__); \
} while (0)
#else // !TRACING_ON
#define DTRACE(x) (false)
#define DDUMP(x, data, count) do {} while (0)
#define DPRINTF(x, ...) do {} while (0)
#define DPRINTFS(x, ...) do {} while (0)
#define DPRINTFR(...) do {} while (0)
#define DDUMPN(data, count) do {} while (0)
#define DPRINTFN(...) do {} while (0)
#define DPRINTFNR(...) do {} while (0)
#endif // TRACING_ON
#endif // __BASE_TRACE_HH__
| create DPRINTF_UNCONDITIONAL | base: create DPRINTF_UNCONDITIONAL
This is similar to DPRINTFN, but it also prints a given flag to allow
communicating to users which flag enabled a given log.
This is useful for logs which are enabled with DTRACE instead of directly
with DPRINTF.
Change-Id: Ife2d2ea88aede1cdcb713f143340a8788a755b01
Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/22005
Tested-by: kokoro <[email protected]>
Reviewed-by: Jason Lowe-Power <[email protected]>
Reviewed-by: Bobby R. Bruce <[email protected]>
Maintainer: Jason Lowe-Power <[email protected]>
| C++ | bsd-3-clause | gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5,gem5/gem5 |
cf5b1c27395f272ce1deaeee2968bfe1969bb84b | src/benchmark.cpp | src/benchmark.cpp | /* For symbol_thingey */
#include <chrono>
#define FUTURE_TRACE 0
#include <cps/future.h>
#include <iostream>
using namespace cps;
int
main(void)
{
auto start = std::chrono::high_resolution_clock::now();
const int count = 100000;
for(int i = 0; i < count; ++i) {
auto f = future<std::string>::create_shared();
auto expected = "happy";
f->on_done([expected](const std::string &v) {
// return future<std::string>::create_shared()->done("very happy");
})->done(expected);
// BOOST_CHECK(seq->as<std::string>()->get() == "very happy");
}
auto elapsed = std::chrono::high_resolution_clock::now() - start;
std::cout
<< "Average iteration: "
<< (std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count() / (float)count)
<< " ns"
<< std::endl;
return 0;
}
| /* For symbol_thingey */
#include <chrono>
#define FUTURE_TRACE 0
#include <cps/future.h>
#include <iostream>
using namespace cps;
int
main(void)
{
auto start = std::chrono::high_resolution_clock::now();
const int count = 100000;
for(int i = 0; i < count; ++i) {
auto f = future<std::string>::create_shared();
auto expected = "happy";
f->on_done([expected](const std::string &) {
})->done(expected);
}
auto elapsed = std::chrono::high_resolution_clock::now() - start;
std::cout
<< "Average iteration: "
<< (std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count() / (float)count)
<< " ns"
<< std::endl;
return 0;
}
| Clean up benchmark a bit | Clean up benchmark a bit
| C++ | mit | tm604/cps-future,tm604/cps-future |
d64f8e6e8c5466320c2d050dc695678c23b27b75 | src/binsearch.hpp | src/binsearch.hpp | #include <iterator>
template<class RandomIt, class Val>
RandomIt binsearch(RandomIt fst, RandomIt lst, const Val& val) {
if (fst == lst) return lst;
auto lft = fst, rgt = std::prev(lst);
while (lft <= rgt) {
const auto mid = std::next(lft, std::distance(lft, rgt) / 2);
if (val == *mid)
return mid;
if (val < *mid)
rgt = std::prev(mid);
else
lft = std::next(mid);
}
return lst; // not found
}
template<class RandomIt, class Val>
RandomIt xlower_bound(RandomIt fst, RandomIt lst, const Val& val) {
if (fst == lst) return lst;
auto lft = fst, rgt = std::prev(lst);
while (lft <= rgt) {
const auto mid = std::next(lft, std::distance(lft, rgt) / 2);
if (*mid < val) {
lft = std::next(mid);
} else {
rgt = std::prev(mid);
}
}
return lft; // lower bound (if it exists) or past-the-end
}
template<class RandomIt, class Val>
RandomIt xupper_bound(RandomIt fst, RandomIt lst, const Val& val) {
if (fst == lst) return lst;
auto lft = fst, rgt = std::prev(lst);
while (lft <= rgt) {
const auto mid = std::next(lft, std::distance(lft, rgt) / 2);
if (*mid <= val) {
lft = std::next(mid);
} else {
rgt = std::prev(mid);
}
}
return lft;
}
| #include <iterator>
template<class RandomIt, class Val>
RandomIt binsearch(RandomIt fst, RandomIt lst, const Val& val) {
if (fst == lst) return lst;
auto lft = fst, rgt = std::prev(lst);
while (lft <= rgt) {
const auto mid = std::next(lft, std::distance(lft, rgt) / 2);
if (val == *mid)
return mid;
if (val < *mid)
rgt = std::prev(mid);
else
lft = std::next(mid);
}
return lst; // not found
}
template<class RandomIt, class Val>
RandomIt xlower_bound(RandomIt fst, RandomIt lst, const Val& val) {
if (fst == lst) return lst;
auto lft = fst, rgt = std::prev(lst);
while (lft <= rgt) {
const auto mid = std::next(lft, std::distance(lft, rgt) / 2);
if (*mid < val) {
lft = std::next(mid);
} else {
rgt = std::prev(mid);
}
}
return lft; // lower bound (if it exists) or past-the-end
}
template<class RandomIt, class Val>
RandomIt xupper_bound(RandomIt fst, RandomIt lst, const Val& val) {
if (fst == lst) return lst;
while (fst < lst) {
const auto mid = std::next(fst, std::distance(fst, lst) / 2);
if (*mid <= val)
fst = mid + 1;
else
lst = mid;
}
return fst;
}
| Remove exrta variables from xupper_bound | Remove exrta variables from xupper_bound
| C++ | mit | all3fox/algos-cpp |
6dc181fad5f782a319a60b631272f7630e6fd180 | src/bootimage.cpp | src/bootimage.cpp | /* Copyright (c) 2008, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#include "bootimage.h"
#include "heapwalk.h"
#include "common.h"
#include "machine.h"
#include "util.h"
#include "assembler.h"
// since we aren't linking against libstdc++, we must implement this
// ourselves:
extern "C" void __cxa_pure_virtual(void) { abort(); }
using namespace vm;
namespace {
bool
endsWith(const char* suffix, const char* s, unsigned length)
{
unsigned suffixLength = strlen(suffix);
return length >= suffixLength
and memcmp(suffix, s + (length - suffixLength), suffixLength) == 0;
}
unsigned
codeMapSize(unsigned codeSize)
{
return ceiling(codeSize, BitsPerWord) * BytesPerWord;
}
object
makeCodeImage(Thread* t, BootImage* image, uint8_t* code, unsigned capacity)
{
unsigned size = 0;
t->m->processor->compileThunks(t, image, code, &size, capacity);
Zone zone(t->m->system, t->m->heap, 64 * 1024);
object constants = 0;
PROTECT(t, constants);
object calls = 0;
PROTECT(t, calls);
for (Finder::Iterator it(t->m->finder); it.hasMore();) {
unsigned nameSize;
const char* name = it.next(&nameSize);
if (endsWith(".class", name, nameSize)) {
fprintf(stderr, "%.*s\n", nameSize - 6, name);
object c = resolveClass
(t, makeByteArray(t, "%.*s", nameSize - 6, name));
PROTECT(t, c);
if (classMethodTable(t, c)) {
for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, c)); ++i) {
object method = arrayBody(t, classMethodTable(t, c), i);
if (methodCode(t, method)) {
t->m->processor->compileMethod
(t, &zone, code, &size, capacity, &constants, &calls, method);
}
}
}
}
}
for (; calls; calls = tripleThird(t, calls)) {
static_cast<ListenPromise*>(pointerValue(t, tripleSecond(t, calls)))
->listener->resolve(methodCompiled(t, tripleFirst(t, calls)));
}
image->codeSize = size;
return constants;
}
unsigned
heapMapSize(unsigned heapSize)
{
return ceiling(heapSize, BitsPerWord * 8) * BytesPerWord;
}
unsigned
objectSize(Thread* t, object o)
{
assert(t, not objectExtended(t, o));
return baseSize(t, o, objectClass(t, o));
}
void
visitRoots(Machine* m, BootImage* image, HeapWalker* w)
{
image->loader = w->visitRoot(m->loader);
image->stringMap = w->visitRoot(m->stringMap);
image->types = w->visitRoot(m->types);
m->processor->visitRoots(image, w);
}
HeapWalker*
makeHeapImage(Thread* t, BootImage* image, uintptr_t* heap, uintptr_t* map,
unsigned capacity)
{
class Visitor: public HeapVisitor {
public:
Visitor(Thread* t, uintptr_t* heap, uintptr_t* map, unsigned capacity):
t(t), currentObject(0), currentOffset(0), heap(heap), map(map),
position(0), capacity(capacity)
{ }
void visit(unsigned number) {
if (currentObject) {
unsigned index = currentObject - 1 + currentOffset;
markBit(map, index);
heap[index] = number;
}
currentObject = number;
}
virtual void root() {
currentObject = 0;
}
virtual unsigned visitNew(object p) {
if (p) {
unsigned size = objectSize(t, p);
assert(t, position + size < capacity);
memcpy(heap + position, p, size * BytesPerWord);
unsigned number = position + 1;
position += size;
visit(number);
return number;
} else {
return 0;
}
}
virtual void visitOld(object, unsigned number) {
visit(number);
}
virtual void push(unsigned offset) {
currentOffset = offset;
}
virtual void pop() {
currentObject = 0;
}
Thread* t;
unsigned currentObject;
unsigned currentOffset;
uintptr_t* heap;
uintptr_t* map;
unsigned position;
unsigned capacity;
} visitor(t, heap, map, capacity / BytesPerWord);
HeapWalker* w = makeHeapWalker(t, &visitor);
visitRoots(t->m, image, w);
image->heapSize = visitor.position * BytesPerWord;
return w;
}
void
updateConstants(Thread* t, object constants, uint8_t* code, uintptr_t* codeMap,
HeapMap* heapTable)
{
for (; constants; constants = tripleThird(t, constants)) {
intptr_t target = heapTable->find(tripleFirst(t, constants));
assert(t, target >= 0);
void* dst = static_cast<ListenPromise*>
(pointerValue(t, tripleSecond(t, constants)))->listener->resolve(target);
assert(t, reinterpret_cast<intptr_t>(dst)
>= reinterpret_cast<intptr_t>(code));
markBit(codeMap, reinterpret_cast<intptr_t>(dst)
- reinterpret_cast<intptr_t>(code));
}
}
unsigned
offset(object a, uintptr_t* b)
{
return reinterpret_cast<uintptr_t>(b) - reinterpret_cast<uintptr_t>(a);
}
void
writeBootImage(Thread* t, FILE*)
{
BootImage image;
const unsigned CodeCapacity = 32 * 1024 * 1024;
uint8_t* code = static_cast<uint8_t*>(t->m->heap->allocate(CodeCapacity));
uintptr_t* codeMap = static_cast<uintptr_t*>
(t->m->heap->allocate(codeMapSize(CodeCapacity)));
memset(codeMap, 0, codeMapSize(CodeCapacity));
object constants = makeCodeImage(t, &image, code, CodeCapacity);
const unsigned HeapCapacity = 32 * 1024 * 1024;
uintptr_t* heap = static_cast<uintptr_t*>
(t->m->heap->allocate(HeapCapacity));
uintptr_t* heapMap = static_cast<uintptr_t*>
(t->m->heap->allocate(heapMapSize(HeapCapacity)));
memset(heapMap, 0, heapMapSize(HeapCapacity));
HeapWalker* heapWalker = makeHeapImage
(t, &image, heap, heapMap, HeapCapacity);
updateConstants(t, constants, code, codeMap, heapWalker->map());
heapWalker->dispose();
image.magic = BootImage::Magic;
fprintf(stderr, "heap size %d code size %d\n",
image.heapSize, image.codeSize);
// fwrite(&image, sizeof(BootImage), 1, out);
// fwrite(heapMap, pad(heapMapSize(image.heapSize)), 1, out);
// fwrite(heap, pad(image.heapSize), 1, out);
// fwrite(codeMap, pad(codeMapSize(image.codeSize)), 1, out);
// fwrite(code, pad(image.codeSize), 1, out);
}
} // namespace
int
main(int ac, const char** av)
{
if (ac != 2) {
fprintf(stderr, "usage: %s <classpath>\n", av[0]);
return -1;
}
System* s = makeSystem(0);
Heap* h = makeHeap(s, 128 * 1024 * 1024);
Finder* f = makeFinder(s, av[1], 0);
Processor* p = makeProcessor(s, h);
Machine* m = new (h->allocate(sizeof(Machine))) Machine(s, h, f, p, 0, 0);
Thread* t = p->makeThread(m, 0, 0);
enter(t, Thread::ActiveState);
enter(t, Thread::IdleState);
writeBootImage(t, stdout);
return 0;
}
| /* Copyright (c) 2008, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
#include "bootimage.h"
#include "heapwalk.h"
#include "common.h"
#include "machine.h"
#include "util.h"
#include "assembler.h"
// since we aren't linking against libstdc++, we must implement this
// ourselves:
extern "C" void __cxa_pure_virtual(void) { abort(); }
using namespace vm;
namespace {
bool
endsWith(const char* suffix, const char* s, unsigned length)
{
unsigned suffixLength = strlen(suffix);
return length >= suffixLength
and memcmp(suffix, s + (length - suffixLength), suffixLength) == 0;
}
unsigned
codeMapSize(unsigned codeSize)
{
return ceiling(codeSize, BitsPerWord) * BytesPerWord;
}
object
makeCodeImage(Thread* t, Zone* zone, BootImage* image, uint8_t* code,
unsigned capacity)
{
unsigned size = 0;
t->m->processor->compileThunks(t, image, code, &size, capacity);
object constants = 0;
PROTECT(t, constants);
object calls = 0;
PROTECT(t, calls);
for (Finder::Iterator it(t->m->finder); it.hasMore();) {
unsigned nameSize;
const char* name = it.next(&nameSize);
if (endsWith(".class", name, nameSize)) {
fprintf(stderr, "%.*s\n", nameSize - 6, name);
object c = resolveClass
(t, makeByteArray(t, "%.*s", nameSize - 6, name));
PROTECT(t, c);
if (classMethodTable(t, c)) {
for (unsigned i = 0; i < arrayLength(t, classMethodTable(t, c)); ++i) {
object method = arrayBody(t, classMethodTable(t, c), i);
if (methodCode(t, method)) {
t->m->processor->compileMethod
(t, zone, code, &size, capacity, &constants, &calls, method);
}
}
}
}
}
for (; calls; calls = tripleThird(t, calls)) {
static_cast<ListenPromise*>(pointerValue(t, tripleSecond(t, calls)))
->listener->resolve(methodCompiled(t, tripleFirst(t, calls)));
}
image->codeSize = size;
return constants;
}
unsigned
heapMapSize(unsigned heapSize)
{
return ceiling(heapSize, BitsPerWord * 8) * BytesPerWord;
}
unsigned
objectSize(Thread* t, object o)
{
assert(t, not objectExtended(t, o));
return baseSize(t, o, objectClass(t, o));
}
void
visitRoots(Machine* m, BootImage* image, HeapWalker* w)
{
image->loader = w->visitRoot(m->loader);
image->stringMap = w->visitRoot(m->stringMap);
image->types = w->visitRoot(m->types);
m->processor->visitRoots(image, w);
}
HeapWalker*
makeHeapImage(Thread* t, BootImage* image, uintptr_t* heap, uintptr_t* map,
unsigned capacity)
{
class Visitor: public HeapVisitor {
public:
Visitor(Thread* t, uintptr_t* heap, uintptr_t* map, unsigned capacity):
t(t), currentObject(0), currentOffset(0), heap(heap), map(map),
position(0), capacity(capacity)
{ }
void visit(unsigned number) {
if (currentObject) {
unsigned index = currentObject - 1 + currentOffset;
markBit(map, index);
heap[index] = number;
}
currentObject = number;
}
virtual void root() {
currentObject = 0;
}
virtual unsigned visitNew(object p) {
if (p) {
unsigned size = objectSize(t, p);
assert(t, position + size < capacity);
memcpy(heap + position, p, size * BytesPerWord);
unsigned number = position + 1;
position += size;
visit(number);
return number;
} else {
return 0;
}
}
virtual void visitOld(object, unsigned number) {
visit(number);
}
virtual void push(unsigned offset) {
currentOffset = offset;
}
virtual void pop() {
currentObject = 0;
}
Thread* t;
unsigned currentObject;
unsigned currentOffset;
uintptr_t* heap;
uintptr_t* map;
unsigned position;
unsigned capacity;
} visitor(t, heap, map, capacity / BytesPerWord);
HeapWalker* w = makeHeapWalker(t, &visitor);
visitRoots(t->m, image, w);
image->heapSize = visitor.position * BytesPerWord;
return w;
}
void
updateConstants(Thread* t, object constants, uint8_t* code, uintptr_t* codeMap,
HeapMap* heapTable)
{
for (; constants; constants = tripleThird(t, constants)) {
intptr_t target = heapTable->find(tripleFirst(t, constants));
assert(t, target >= 0);
void* dst = static_cast<ListenPromise*>
(pointerValue(t, tripleSecond(t, constants)))->listener->resolve(target);
assert(t, reinterpret_cast<intptr_t>(dst)
>= reinterpret_cast<intptr_t>(code));
markBit(codeMap, reinterpret_cast<intptr_t>(dst)
- reinterpret_cast<intptr_t>(code));
}
}
unsigned
offset(object a, uintptr_t* b)
{
return reinterpret_cast<uintptr_t>(b) - reinterpret_cast<uintptr_t>(a);
}
void
writeBootImage(Thread* t, FILE*)
{
Zone zone(t->m->system, t->m->heap, 64 * 1024);
BootImage image;
const unsigned CodeCapacity = 32 * 1024 * 1024;
uint8_t* code = static_cast<uint8_t*>(t->m->heap->allocate(CodeCapacity));
uintptr_t* codeMap = static_cast<uintptr_t*>
(t->m->heap->allocate(codeMapSize(CodeCapacity)));
memset(codeMap, 0, codeMapSize(CodeCapacity));
object constants = makeCodeImage(t, &zone, &image, code, CodeCapacity);
const unsigned HeapCapacity = 32 * 1024 * 1024;
uintptr_t* heap = static_cast<uintptr_t*>
(t->m->heap->allocate(HeapCapacity));
uintptr_t* heapMap = static_cast<uintptr_t*>
(t->m->heap->allocate(heapMapSize(HeapCapacity)));
memset(heapMap, 0, heapMapSize(HeapCapacity));
HeapWalker* heapWalker = makeHeapImage
(t, &image, heap, heapMap, HeapCapacity);
updateConstants(t, constants, code, codeMap, heapWalker->map());
heapWalker->dispose();
image.magic = BootImage::Magic;
fprintf(stderr, "heap size %d code size %d\n",
image.heapSize, image.codeSize);
// fwrite(&image, sizeof(BootImage), 1, out);
// fwrite(heapMap, pad(heapMapSize(image.heapSize)), 1, out);
// fwrite(heap, pad(image.heapSize), 1, out);
// fwrite(codeMap, pad(codeMapSize(image.codeSize)), 1, out);
// fwrite(code, pad(image.codeSize), 1, out);
}
} // namespace
int
main(int ac, const char** av)
{
if (ac != 2) {
fprintf(stderr, "usage: %s <classpath>\n", av[0]);
return -1;
}
System* s = makeSystem(0);
Heap* h = makeHeap(s, 128 * 1024 * 1024);
Finder* f = makeFinder(s, av[1], 0);
Processor* p = makeProcessor(s, h);
Machine* m = new (h->allocate(sizeof(Machine))) Machine(s, h, f, p, 0, 0);
Thread* t = p->makeThread(m, 0, 0);
enter(t, Thread::ActiveState);
enter(t, Thread::IdleState);
writeBootImage(t, stdout);
return 0;
}
| move allocation zone from makeCodeImage to writeBootImage so it stays in scope until after updateConstants is called | move allocation zone from makeCodeImage to writeBootImage so it stays in scope until after updateConstants is called
| C++ | isc | marcinolawski/avian,MaartenR/avian,joshuawarner32/avian,MaartenR/avian,joshuawarner32/avian,ucdseniordesign/avian,getlantern/avian,dicej/avian,dicej/avian,minor-jason/avian,getlantern/avian,dicej/avian,badlogic/avian,bigfatbrowncat/avian-pack.avian,ucdseniordesign/avian,bgould/avian,lwahlmeier/avian,bgould/avian,marcinolawski/avian,bigfatbrowncat/avian-pack.avian,joshuawarner32/avian,ucdseniordesign/avian,getlantern/avian,marcinolawski/avian,badlogic/avian,MaartenR/avian,bgould/avian,minor-jason/avian,joshuawarner32/avian,getlantern/avian,MaartenR/avian,lostdj/avian,ucdseniordesign/avian,lostdj/avian,bigfatbrowncat/avian-pack.avian,badlogic/avian,minor-jason/avian,lwahlmeier/avian,lostdj/avian,dicej/avian,bigfatbrowncat/avian-pack.avian,lostdj/avian,lwahlmeier/avian,marcinolawski/avian,lwahlmeier/avian,bgould/avian,minor-jason/avian,badlogic/avian |
22374bd46a431687d58c016d4d4fd0b7776fb096 | tests/DataRefTest.cpp | tests/DataRefTest.cpp |
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkData.h"
#include "SkDataSet.h"
#include "SkDataTable.h"
#include "SkStream.h"
#include "SkOrderedReadBuffer.h"
#include "SkOrderedWriteBuffer.h"
template <typename T> class SkTUnref {
public:
SkTUnref(T* ref) : fRef(ref) {}
~SkTUnref() { fRef->unref(); }
operator T*() { return fRef; }
operator const T*() { return fRef; }
private:
T* fRef;
};
static void test_is_equal(skiatest::Reporter* reporter,
const SkDataTable* a, const SkDataTable* b) {
REPORTER_ASSERT(reporter, a->count() == b->count());
for (int i = 0; i < a->count(); ++i) {
size_t sizea, sizeb;
const void* mema = a->at(i, &sizea);
const void* memb = b->at(i, &sizeb);
REPORTER_ASSERT(reporter, sizea == sizeb);
REPORTER_ASSERT(reporter, !memcmp(mema, memb, sizea));
}
}
static void test_datatable_flatten(skiatest::Reporter* reporter,
SkDataTable* table) {
SkOrderedWriteBuffer wb(1024);
wb.writeFlattenable(table);
size_t wsize = wb.size();
SkAutoMalloc storage(wsize);
wb.writeToMemory(storage.get());
SkOrderedReadBuffer rb(storage.get(), wsize);
SkAutoTUnref<SkDataTable> newTable((SkDataTable*)rb.readFlattenable());
SkDebugf("%d entries, %d flatten-size\n", table->count(), wsize);
test_is_equal(reporter, table, newTable);
}
static void test_datatable_is_empty(skiatest::Reporter* reporter,
SkDataTable* table) {
REPORTER_ASSERT(reporter, table->isEmpty());
REPORTER_ASSERT(reporter, 0 == table->count());
test_datatable_flatten(reporter, table);
}
static void test_emptytable(skiatest::Reporter* reporter) {
SkAutoTUnref<SkDataTable> table0(SkDataTable::NewEmpty());
SkAutoTUnref<SkDataTable> table1(SkDataTable::NewCopyArrays(NULL, NULL, 0));
SkAutoTUnref<SkDataTable> table2(SkDataTable::NewCopyArray(NULL, 0, 0));
SkAutoTUnref<SkDataTable> table3(SkDataTable::NewArrayProc(NULL, 0, 0,
NULL, NULL));
test_datatable_is_empty(reporter, table0);
test_datatable_is_empty(reporter, table1);
test_datatable_is_empty(reporter, table2);
test_datatable_is_empty(reporter, table3);
test_is_equal(reporter, table0, table1);
test_is_equal(reporter, table0, table2);
test_is_equal(reporter, table0, table3);
}
static void test_simpletable(skiatest::Reporter* reporter) {
const int idata[] = { 1, 4, 9, 16, 25, 63 };
int icount = SK_ARRAY_COUNT(idata);
SkAutoTUnref<SkDataTable> itable(SkDataTable::NewCopyArray(idata,
sizeof(idata[0]),
icount));
REPORTER_ASSERT(reporter, itable->count() == icount);
for (int i = 0; i < icount; ++i) {
size_t size;
REPORTER_ASSERT(reporter, sizeof(int) == itable->atSize(i));
REPORTER_ASSERT(reporter, *itable->atT<int>(i, &size) == idata[i]);
REPORTER_ASSERT(reporter, sizeof(int) == size);
}
test_datatable_flatten(reporter, itable);
}
static void test_vartable(skiatest::Reporter* reporter) {
const char* str[] = {
"", "a", "be", "see", "deigh", "ef", "ggggggggggggggggggggggggggg"
};
int count = SK_ARRAY_COUNT(str);
size_t sizes[SK_ARRAY_COUNT(str)];
for (int i = 0; i < count; ++i) {
sizes[i] = strlen(str[i]) + 1;
}
SkAutoTUnref<SkDataTable> table(SkDataTable::NewCopyArrays(
(const void*const*)str, sizes, count));
REPORTER_ASSERT(reporter, table->count() == count);
for (int i = 0; i < count; ++i) {
size_t size;
REPORTER_ASSERT(reporter, table->atSize(i) == sizes[i]);
REPORTER_ASSERT(reporter, !strcmp(table->atT<const char>(i, &size),
str[i]));
REPORTER_ASSERT(reporter, size == sizes[i]);
const char* s = table->atStr(i);
REPORTER_ASSERT(reporter, strlen(s) == strlen(str[i]));
}
test_datatable_flatten(reporter, table);
}
static void test_tablebuilder(skiatest::Reporter* reporter) {
const char* str[] = {
"", "a", "be", "see", "deigh", "ef", "ggggggggggggggggggggggggggg"
};
int count = SK_ARRAY_COUNT(str);
SkDataTableBuilder builder(16);
for (int i = 0; i < count; ++i) {
builder.append(str[i], strlen(str[i]) + 1);
}
SkAutoTUnref<SkDataTable> table(builder.detachDataTable());
REPORTER_ASSERT(reporter, table->count() == count);
for (int i = 0; i < count; ++i) {
size_t size;
REPORTER_ASSERT(reporter, table->atSize(i) == strlen(str[i]) + 1);
REPORTER_ASSERT(reporter, !strcmp(table->atT<const char>(i, &size),
str[i]));
REPORTER_ASSERT(reporter, size == strlen(str[i]) + 1);
const char* s = table->atStr(i);
REPORTER_ASSERT(reporter, strlen(s) == strlen(str[i]));
}
test_datatable_flatten(reporter, table);
}
static void test_globaltable(skiatest::Reporter* reporter) {
static const int gData[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
};
int count = SK_ARRAY_COUNT(gData);
SkAutoTUnref<SkDataTable> table(SkDataTable::NewArrayProc(gData,
sizeof(gData[0]), count, NULL, NULL));
REPORTER_ASSERT(reporter, table->count() == count);
for (int i = 0; i < count; ++i) {
size_t size;
REPORTER_ASSERT(reporter, table->atSize(i) == sizeof(int));
REPORTER_ASSERT(reporter, *table->atT<const char>(i, &size) == i);
REPORTER_ASSERT(reporter, sizeof(int) == size);
}
test_datatable_flatten(reporter, table);
}
static void TestDataTable(skiatest::Reporter* reporter) {
test_emptytable(reporter);
test_simpletable(reporter);
test_vartable(reporter);
test_tablebuilder(reporter);
test_globaltable(reporter);
}
static void unrefAll(const SkDataSet::Pair pairs[], int count) {
for (int i = 0; i < count; ++i) {
pairs[i].fValue->unref();
}
}
// asserts that inner is a subset of outer
static void test_dataset_subset(skiatest::Reporter* reporter,
const SkDataSet& outer, const SkDataSet& inner) {
SkDataSet::Iter iter(inner);
for (; !iter.done(); iter.next()) {
SkData* outerData = outer.find(iter.key());
REPORTER_ASSERT(reporter, outerData);
REPORTER_ASSERT(reporter, outerData->equals(iter.value()));
}
}
static void test_datasets_equal(skiatest::Reporter* reporter,
const SkDataSet& ds0, const SkDataSet& ds1) {
REPORTER_ASSERT(reporter, ds0.count() == ds1.count());
test_dataset_subset(reporter, ds0, ds1);
test_dataset_subset(reporter, ds1, ds0);
}
static void test_dataset(skiatest::Reporter* reporter, const SkDataSet& ds,
int count) {
REPORTER_ASSERT(reporter, ds.count() == count);
SkDataSet::Iter iter(ds);
int index = 0;
for (; !iter.done(); iter.next()) {
// const char* name = iter.key();
// SkData* data = iter.value();
// SkDebugf("[%d] %s:%s\n", index, name, (const char*)data->bytes());
index += 1;
}
REPORTER_ASSERT(reporter, index == count);
SkDynamicMemoryWStream ostream;
ds.writeToStream(&ostream);
SkMemoryStream istream;
istream.setData(ostream.copyToData())->unref();
SkDataSet copy(&istream);
test_datasets_equal(reporter, ds, copy);
}
static void test_dataset(skiatest::Reporter* reporter) {
SkDataSet set0(NULL, 0);
SkDataSet set1("hello", SkTUnref<SkData>(SkData::NewWithCString("world")));
const SkDataSet::Pair pairs[] = {
{ "one", SkData::NewWithCString("1") },
{ "two", SkData::NewWithCString("2") },
{ "three", SkData::NewWithCString("3") },
};
SkDataSet set3(pairs, 3);
unrefAll(pairs, 3);
test_dataset(reporter, set0, 0);
test_dataset(reporter, set1, 1);
test_dataset(reporter, set3, 3);
}
static void* gGlobal;
static void delete_int_proc(const void* ptr, size_t len, void* context) {
int* data = (int*)ptr;
SkASSERT(context == gGlobal);
delete[] data;
}
static void assert_len(skiatest::Reporter* reporter, SkData* ref, size_t len) {
REPORTER_ASSERT(reporter, ref->size() == len);
}
static void assert_data(skiatest::Reporter* reporter, SkData* ref,
const void* data, size_t len) {
REPORTER_ASSERT(reporter, ref->size() == len);
REPORTER_ASSERT(reporter, !memcmp(ref->data(), data, len));
}
static void test_cstring(skiatest::Reporter* reporter) {
const char str[] = "Hello world";
size_t len = strlen(str);
SkAutoTUnref<SkData> r0(SkData::NewWithCopy(str, len + 1));
SkAutoTUnref<SkData> r1(SkData::NewWithCString(str));
REPORTER_ASSERT(reporter, r0->equals(r1));
SkAutoTUnref<SkData> r2(SkData::NewWithCString(NULL));
REPORTER_ASSERT(reporter, 1 == r2->size());
REPORTER_ASSERT(reporter, 0 == *r2->bytes());
}
static void TestData(skiatest::Reporter* reporter) {
const char* str = "We the people, in order to form a more perfect union.";
const int N = 10;
SkAutoTUnref<SkData> r0(SkData::NewEmpty());
SkAutoTUnref<SkData> r1(SkData::NewWithCopy(str, strlen(str)));
SkAutoTUnref<SkData> r2(SkData::NewWithProc(new int[N], N*sizeof(int),
delete_int_proc, gGlobal));
SkAutoTUnref<SkData> r3(SkData::NewSubset(r1, 7, 6));
assert_len(reporter, r0, 0);
assert_len(reporter, r1, strlen(str));
assert_len(reporter, r2, N * sizeof(int));
assert_len(reporter, r3, 6);
assert_data(reporter, r1, str, strlen(str));
assert_data(reporter, r3, "people", 6);
SkData* tmp = SkData::NewSubset(r1, strlen(str), 10);
assert_len(reporter, tmp, 0);
tmp->unref();
tmp = SkData::NewSubset(r1, 0, 0);
assert_len(reporter, tmp, 0);
tmp->unref();
test_cstring(reporter);
test_dataset(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Data", DataTestClass, TestData)
DEFINE_TESTCLASS("DataTable", DataTableTestClass, TestDataTable)
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkData.h"
#include "SkDataSet.h"
#include "SkDataTable.h"
#include "SkStream.h"
#include "SkOrderedReadBuffer.h"
#include "SkOrderedWriteBuffer.h"
template <typename T> class SkTUnref {
public:
SkTUnref(T* ref) : fRef(ref) {}
~SkTUnref() { fRef->unref(); }
operator T*() { return fRef; }
operator const T*() { return fRef; }
private:
T* fRef;
};
static void test_is_equal(skiatest::Reporter* reporter,
const SkDataTable* a, const SkDataTable* b) {
REPORTER_ASSERT(reporter, a->count() == b->count());
for (int i = 0; i < a->count(); ++i) {
size_t sizea, sizeb;
const void* mema = a->at(i, &sizea);
const void* memb = b->at(i, &sizeb);
REPORTER_ASSERT(reporter, sizea == sizeb);
REPORTER_ASSERT(reporter, !memcmp(mema, memb, sizea));
}
}
static void test_datatable_flatten(skiatest::Reporter* reporter,
SkDataTable* table) {
SkOrderedWriteBuffer wb(1024);
wb.writeFlattenable(table);
size_t wsize = wb.size();
SkAutoMalloc storage(wsize);
wb.writeToMemory(storage.get());
SkOrderedReadBuffer rb(storage.get(), wsize);
SkAutoTUnref<SkDataTable> newTable((SkDataTable*)rb.readFlattenable());
test_is_equal(reporter, table, newTable);
}
static void test_datatable_is_empty(skiatest::Reporter* reporter,
SkDataTable* table) {
REPORTER_ASSERT(reporter, table->isEmpty());
REPORTER_ASSERT(reporter, 0 == table->count());
test_datatable_flatten(reporter, table);
}
static void test_emptytable(skiatest::Reporter* reporter) {
SkAutoTUnref<SkDataTable> table0(SkDataTable::NewEmpty());
SkAutoTUnref<SkDataTable> table1(SkDataTable::NewCopyArrays(NULL, NULL, 0));
SkAutoTUnref<SkDataTable> table2(SkDataTable::NewCopyArray(NULL, 0, 0));
SkAutoTUnref<SkDataTable> table3(SkDataTable::NewArrayProc(NULL, 0, 0,
NULL, NULL));
test_datatable_is_empty(reporter, table0);
test_datatable_is_empty(reporter, table1);
test_datatable_is_empty(reporter, table2);
test_datatable_is_empty(reporter, table3);
test_is_equal(reporter, table0, table1);
test_is_equal(reporter, table0, table2);
test_is_equal(reporter, table0, table3);
}
static void test_simpletable(skiatest::Reporter* reporter) {
const int idata[] = { 1, 4, 9, 16, 25, 63 };
int icount = SK_ARRAY_COUNT(idata);
SkAutoTUnref<SkDataTable> itable(SkDataTable::NewCopyArray(idata,
sizeof(idata[0]),
icount));
REPORTER_ASSERT(reporter, itable->count() == icount);
for (int i = 0; i < icount; ++i) {
size_t size;
REPORTER_ASSERT(reporter, sizeof(int) == itable->atSize(i));
REPORTER_ASSERT(reporter, *itable->atT<int>(i, &size) == idata[i]);
REPORTER_ASSERT(reporter, sizeof(int) == size);
}
test_datatable_flatten(reporter, itable);
}
static void test_vartable(skiatest::Reporter* reporter) {
const char* str[] = {
"", "a", "be", "see", "deigh", "ef", "ggggggggggggggggggggggggggg"
};
int count = SK_ARRAY_COUNT(str);
size_t sizes[SK_ARRAY_COUNT(str)];
for (int i = 0; i < count; ++i) {
sizes[i] = strlen(str[i]) + 1;
}
SkAutoTUnref<SkDataTable> table(SkDataTable::NewCopyArrays(
(const void*const*)str, sizes, count));
REPORTER_ASSERT(reporter, table->count() == count);
for (int i = 0; i < count; ++i) {
size_t size;
REPORTER_ASSERT(reporter, table->atSize(i) == sizes[i]);
REPORTER_ASSERT(reporter, !strcmp(table->atT<const char>(i, &size),
str[i]));
REPORTER_ASSERT(reporter, size == sizes[i]);
const char* s = table->atStr(i);
REPORTER_ASSERT(reporter, strlen(s) == strlen(str[i]));
}
test_datatable_flatten(reporter, table);
}
static void test_tablebuilder(skiatest::Reporter* reporter) {
const char* str[] = {
"", "a", "be", "see", "deigh", "ef", "ggggggggggggggggggggggggggg"
};
int count = SK_ARRAY_COUNT(str);
SkDataTableBuilder builder(16);
for (int i = 0; i < count; ++i) {
builder.append(str[i], strlen(str[i]) + 1);
}
SkAutoTUnref<SkDataTable> table(builder.detachDataTable());
REPORTER_ASSERT(reporter, table->count() == count);
for (int i = 0; i < count; ++i) {
size_t size;
REPORTER_ASSERT(reporter, table->atSize(i) == strlen(str[i]) + 1);
REPORTER_ASSERT(reporter, !strcmp(table->atT<const char>(i, &size),
str[i]));
REPORTER_ASSERT(reporter, size == strlen(str[i]) + 1);
const char* s = table->atStr(i);
REPORTER_ASSERT(reporter, strlen(s) == strlen(str[i]));
}
test_datatable_flatten(reporter, table);
}
static void test_globaltable(skiatest::Reporter* reporter) {
static const int gData[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
};
int count = SK_ARRAY_COUNT(gData);
SkAutoTUnref<SkDataTable> table(SkDataTable::NewArrayProc(gData,
sizeof(gData[0]), count, NULL, NULL));
REPORTER_ASSERT(reporter, table->count() == count);
for (int i = 0; i < count; ++i) {
size_t size;
REPORTER_ASSERT(reporter, table->atSize(i) == sizeof(int));
REPORTER_ASSERT(reporter, *table->atT<const char>(i, &size) == i);
REPORTER_ASSERT(reporter, sizeof(int) == size);
}
test_datatable_flatten(reporter, table);
}
static void TestDataTable(skiatest::Reporter* reporter) {
test_emptytable(reporter);
test_simpletable(reporter);
test_vartable(reporter);
test_tablebuilder(reporter);
test_globaltable(reporter);
}
static void unrefAll(const SkDataSet::Pair pairs[], int count) {
for (int i = 0; i < count; ++i) {
pairs[i].fValue->unref();
}
}
// asserts that inner is a subset of outer
static void test_dataset_subset(skiatest::Reporter* reporter,
const SkDataSet& outer, const SkDataSet& inner) {
SkDataSet::Iter iter(inner);
for (; !iter.done(); iter.next()) {
SkData* outerData = outer.find(iter.key());
REPORTER_ASSERT(reporter, outerData);
REPORTER_ASSERT(reporter, outerData->equals(iter.value()));
}
}
static void test_datasets_equal(skiatest::Reporter* reporter,
const SkDataSet& ds0, const SkDataSet& ds1) {
REPORTER_ASSERT(reporter, ds0.count() == ds1.count());
test_dataset_subset(reporter, ds0, ds1);
test_dataset_subset(reporter, ds1, ds0);
}
static void test_dataset(skiatest::Reporter* reporter, const SkDataSet& ds,
int count) {
REPORTER_ASSERT(reporter, ds.count() == count);
SkDataSet::Iter iter(ds);
int index = 0;
for (; !iter.done(); iter.next()) {
// const char* name = iter.key();
// SkData* data = iter.value();
// SkDebugf("[%d] %s:%s\n", index, name, (const char*)data->bytes());
index += 1;
}
REPORTER_ASSERT(reporter, index == count);
SkDynamicMemoryWStream ostream;
ds.writeToStream(&ostream);
SkMemoryStream istream;
istream.setData(ostream.copyToData())->unref();
SkDataSet copy(&istream);
test_datasets_equal(reporter, ds, copy);
}
static void test_dataset(skiatest::Reporter* reporter) {
SkDataSet set0(NULL, 0);
SkDataSet set1("hello", SkTUnref<SkData>(SkData::NewWithCString("world")));
const SkDataSet::Pair pairs[] = {
{ "one", SkData::NewWithCString("1") },
{ "two", SkData::NewWithCString("2") },
{ "three", SkData::NewWithCString("3") },
};
SkDataSet set3(pairs, 3);
unrefAll(pairs, 3);
test_dataset(reporter, set0, 0);
test_dataset(reporter, set1, 1);
test_dataset(reporter, set3, 3);
}
static void* gGlobal;
static void delete_int_proc(const void* ptr, size_t len, void* context) {
int* data = (int*)ptr;
SkASSERT(context == gGlobal);
delete[] data;
}
static void assert_len(skiatest::Reporter* reporter, SkData* ref, size_t len) {
REPORTER_ASSERT(reporter, ref->size() == len);
}
static void assert_data(skiatest::Reporter* reporter, SkData* ref,
const void* data, size_t len) {
REPORTER_ASSERT(reporter, ref->size() == len);
REPORTER_ASSERT(reporter, !memcmp(ref->data(), data, len));
}
static void test_cstring(skiatest::Reporter* reporter) {
const char str[] = "Hello world";
size_t len = strlen(str);
SkAutoTUnref<SkData> r0(SkData::NewWithCopy(str, len + 1));
SkAutoTUnref<SkData> r1(SkData::NewWithCString(str));
REPORTER_ASSERT(reporter, r0->equals(r1));
SkAutoTUnref<SkData> r2(SkData::NewWithCString(NULL));
REPORTER_ASSERT(reporter, 1 == r2->size());
REPORTER_ASSERT(reporter, 0 == *r2->bytes());
}
static void TestData(skiatest::Reporter* reporter) {
const char* str = "We the people, in order to form a more perfect union.";
const int N = 10;
SkAutoTUnref<SkData> r0(SkData::NewEmpty());
SkAutoTUnref<SkData> r1(SkData::NewWithCopy(str, strlen(str)));
SkAutoTUnref<SkData> r2(SkData::NewWithProc(new int[N], N*sizeof(int),
delete_int_proc, gGlobal));
SkAutoTUnref<SkData> r3(SkData::NewSubset(r1, 7, 6));
assert_len(reporter, r0, 0);
assert_len(reporter, r1, strlen(str));
assert_len(reporter, r2, N * sizeof(int));
assert_len(reporter, r3, 6);
assert_data(reporter, r1, str, strlen(str));
assert_data(reporter, r3, "people", 6);
SkData* tmp = SkData::NewSubset(r1, strlen(str), 10);
assert_len(reporter, tmp, 0);
tmp->unref();
tmp = SkData::NewSubset(r1, 0, 0);
assert_len(reporter, tmp, 0);
tmp->unref();
test_cstring(reporter);
test_dataset(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Data", DataTestClass, TestData)
DEFINE_TESTCLASS("DataTable", DataTableTestClass, TestDataTable)
| remove printf | remove printf
| C++ | bsd-3-clause | csulmone/skia,csulmone/skia,csulmone/skia,csulmone/skia |
d67fb006cebbd8d4c07a6e66b4c06c64d30d527f | src/burstsort.cpp | src/burstsort.cpp | /*
* Copyright 2008 by Tommi Rantala <[email protected]>
*
* 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.
*/
/*
* Implementation of the burstsort algorithm by Sinha, Zobel et al.
*
* @article{1041517,
* author = {Ranjan Sinha and Justin Zobel},
* title = {Cache-conscious sorting of large sets of strings with dynamic tries},
* journal = {J. Exp. Algorithmics},
* volume = {9},
* year = {2004},
* issn = {1084-6654},
* pages = {1.5},
* doi = {http://doi.acm.org/10.1145/1005813.1041517},
* publisher = {ACM},
* address = {New York, NY, USA},
* }
*/
#include "util/get_char.h"
#include <vector>
#include <iostream>
#include <bitset>
#include "vector_bagwell.h"
#include "vector_brodnik.h"
#include "vector_block.h"
#include <boost/array.hpp>
using boost::array;
// Unfortunately std::numeric_limits<T>::max() cannot be used as constant
// values in template parameters.
template <typename T> struct max {};
template <> struct max<unsigned char> { enum { value = 0x100 }; };
template <> struct max<uint16_t> { enum { value = 0x10000 }; };
template <typename CharT>
struct TrieNode
{
// One subtree per alphabet. Points to either a 'TrieNode' or a
// 'Bucket' node. Use the value from is_trie to know which one.
array<void*, max<CharT>::value> buckets;
// is_trie[i] equals true if buckets[i] points to a TrieNode
// is_trie[i] equals false if buckets[i] points to a Bucket
std::bitset<max<CharT>::value> is_trie;
TrieNode() { buckets.assign(0); }
};
// The burst algorithm as described by Sinha, Zobel et al.
template <typename CharT>
struct BurstSimple
{
template <typename BucketT>
TrieNode<CharT>*
operator()(const BucketT& bucket, size_t depth) const
{
TrieNode<CharT>* new_node = new TrieNode<CharT>;
const unsigned bucket_size = bucket.size();
// Use a small cache to reduce memory stalls. Also cache the
// string pointers, in case the indexing operation of the
// container is expensive.
unsigned i=0;
for (; i < bucket_size-bucket_size%64; i+=64) {
array<CharT, 64> cache;
array<unsigned char*, 64> strings;
for (unsigned j=0; j < 64; ++j) {
strings[j] = bucket[i+j];
cache[j] = get_char<CharT>(strings[j], depth);
}
for (unsigned j=0; j < 64; ++j) {
const CharT ch = cache[j];
BucketT* sub_bucket = static_cast<BucketT*>(
new_node->buckets[ch]);
if (not sub_bucket) {
new_node->buckets[ch] = sub_bucket
= new BucketT;
}
sub_bucket->push_back(strings[j]);
}
}
for (; i < bucket_size; ++i) {
unsigned char* ptr = bucket[i];
const CharT ch = get_char<CharT>(ptr, depth);
BucketT* sub_bucket = static_cast<BucketT*>(
new_node->buckets[ch]);
if (not sub_bucket) {
new_node->buckets[ch] = sub_bucket
= new BucketT;
}
sub_bucket->push_back(ptr);
}
return new_node;
}
};
// Another burst variant: After bursting the bucket, immediately burst large
// sub buckets in a recursive fashion.
template <typename CharT>
struct BurstRecursive
{
template <typename BucketT>
TrieNode<CharT>*
operator()(const BucketT& bucket, size_t depth) const
{
TrieNode<CharT>* new_node
= BurstSimple<CharT>()(bucket, depth);
const size_t threshold = std::max(
//size_t(100), size_t(0.4f*bucket.size()));
size_t(100), bucket.size()/2);
for (unsigned i=0; i < max<CharT>::value; ++i) {
assert(new_node->is_trie[i] == false);
BucketT* sub_bucket = static_cast<BucketT*>(
new_node->buckets[i]);
if (not sub_bucket) continue;
if (not is_end(i) and sub_bucket->size() > threshold) {
new_node->buckets[i] =
BurstRecursive<CharT>()(*sub_bucket,
depth+sizeof(CharT));
delete sub_bucket;
new_node->is_trie[i] = true;
}
}
return new_node;
}
};
template <unsigned Threshold, typename BucketT,
typename BurstImpl, typename CharT>
static inline void
insert(TrieNode<CharT>* root, unsigned char** strings, size_t n)
{
for (size_t i=0; i < n; ++i) {
unsigned char* str = strings[i];
size_t depth = 0;
CharT c = get_char<CharT>(str, 0);
TrieNode<CharT>* node = root;
while (node->is_trie[c]) {
assert(not is_end(c));
node = static_cast<TrieNode<CharT>*>(node->buckets[c]);
depth += sizeof(CharT);
c = get_char<CharT>(str, depth);
}
BucketT* bucket = static_cast<BucketT*>(node->buckets[c]);
if (not bucket) {
node->buckets[c] = bucket = new BucketT;
}
bucket->push_back(str);
if (is_end(c)) continue;
if (bucket->size() > Threshold) {
node->buckets[c] = BurstImpl()(*bucket,
depth+sizeof(CharT));
node->is_trie[c] = true;
delete bucket;
}
}
}
// Use a wrapper to std::copy(). I haven't implemented iterators for some of my
// containers, instead they have optimized copy(bucket, dst).
static inline void
copy(const std::vector<unsigned char*>& bucket, unsigned char** dst)
{
std::copy(bucket.begin(), bucket.end(), dst);
}
// Traverses the trie and copies the strings back to the original string array.
// Nodes and buckets are deleted from memory during the traversal. The root
// node given to this function will also be deleted.
template <typename BucketT, typename SmallSort, typename CharT>
static unsigned char**
traverse(TrieNode<CharT>* node,
unsigned char** dst,
size_t depth,
SmallSort small_sort)
{
for (unsigned i=0; i < max<CharT>::value; ++i) {
if (node->is_trie[i]) {
dst = traverse<BucketT>(
static_cast<TrieNode<CharT>*>(node->buckets[i]),
dst, depth+sizeof(CharT), small_sort);
} else {
BucketT* bucket =
static_cast<BucketT*>(node->buckets[i]);
if (not bucket) continue;
size_t bsize = bucket->size();
copy(*bucket, dst);
if (not is_end(i)) small_sort(dst, bsize, depth);
dst += bsize;
delete bucket;
}
}
delete node;
return dst;
}
//#define SmallSort mkqsort
#define SmallSort msd_CE2
void msd_CE2(unsigned char**, size_t, size_t);
void burstsort_vector(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef std::vector<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<8000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_brodnik(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef vector_brodnik<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<16000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_bagwell(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef vector_bagwell<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<16000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_vector_block(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef vector_block<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<16000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_vector(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef std::vector<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_brodnik(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef vector_brodnik<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_bagwell(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef vector_bagwell<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_vector_block(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef vector_block<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
| /*
* Copyright 2008 by Tommi Rantala <[email protected]>
*
* 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.
*/
/*
* Implementation of the burstsort algorithm by Sinha, Zobel et al.
*
* @article{1041517,
* author = {Ranjan Sinha and Justin Zobel},
* title = {Cache-conscious sorting of large sets of strings with dynamic tries},
* journal = {J. Exp. Algorithmics},
* volume = {9},
* year = {2004},
* issn = {1084-6654},
* pages = {1.5},
* doi = {http://doi.acm.org/10.1145/1005813.1041517},
* publisher = {ACM},
* address = {New York, NY, USA},
* }
*/
#include "util/get_char.h"
#include <vector>
#include <iostream>
#include <bitset>
#include "vector_bagwell.h"
#include "vector_brodnik.h"
#include "vector_block.h"
#include <boost/array.hpp>
using boost::array;
// Unfortunately std::numeric_limits<T>::max() cannot be used as constant
// values in template parameters.
template <typename T> struct max {};
template <> struct max<unsigned char> { enum { value = 0x100 }; };
template <> struct max<uint16_t> { enum { value = 0x10000 }; };
template <typename CharT>
struct TrieNode
{
// One subtree per alphabet. Points to either a 'TrieNode' or a
// 'Bucket' node. Use the value from is_trie to know which one.
array<void*, max<CharT>::value> buckets;
// is_trie[i] equals true if buckets[i] points to a TrieNode
// is_trie[i] equals false if buckets[i] points to a Bucket
std::bitset<max<CharT>::value> is_trie;
TrieNode() { buckets.assign(0); }
};
// The burst algorithm as described by Sinha, Zobel et al.
template <typename CharT>
struct BurstSimple
{
template <typename BucketT>
TrieNode<CharT>*
operator()(const BucketT& bucket, size_t depth) const
{
TrieNode<CharT>* new_node = new TrieNode<CharT>;
const unsigned bucket_size = bucket.size();
// Use a small cache to reduce memory stalls. Also cache the
// string pointers, in case the indexing operation of the
// container is expensive.
unsigned i=0;
for (; i < bucket_size-bucket_size%64; i+=64) {
array<CharT, 64> cache;
array<unsigned char*, 64> strings;
for (unsigned j=0; j < 64; ++j) {
strings[j] = bucket[i+j];
cache[j] = get_char<CharT>(strings[j], depth);
}
for (unsigned j=0; j < 64; ++j) {
const CharT ch = cache[j];
BucketT* sub_bucket = static_cast<BucketT*>(
new_node->buckets[ch]);
if (not sub_bucket) {
new_node->buckets[ch] = sub_bucket
= new BucketT;
}
sub_bucket->push_back(strings[j]);
}
}
for (; i < bucket_size; ++i) {
unsigned char* ptr = bucket[i];
const CharT ch = get_char<CharT>(ptr, depth);
BucketT* sub_bucket = static_cast<BucketT*>(
new_node->buckets[ch]);
if (not sub_bucket) {
new_node->buckets[ch] = sub_bucket
= new BucketT;
}
sub_bucket->push_back(ptr);
}
return new_node;
}
};
// Another burst variant: After bursting the bucket, immediately burst large
// sub buckets in a recursive fashion.
template <typename CharT>
struct BurstRecursive
{
template <typename BucketT>
TrieNode<CharT>*
operator()(const BucketT& bucket, size_t depth) const
{
TrieNode<CharT>* new_node
= BurstSimple<CharT>()(bucket, depth);
const size_t threshold = std::max(
//size_t(100), size_t(0.4f*bucket.size()));
size_t(100), bucket.size()/2);
for (unsigned i=0; i < max<CharT>::value; ++i) {
assert(new_node->is_trie[i] == false);
BucketT* sub_bucket = static_cast<BucketT*>(
new_node->buckets[i]);
if (not sub_bucket) continue;
if (not is_end(i) and sub_bucket->size() > threshold) {
new_node->buckets[i] =
BurstRecursive<CharT>()(*sub_bucket,
depth+sizeof(CharT));
delete sub_bucket;
new_node->is_trie[i] = true;
}
}
return new_node;
}
};
template <unsigned Threshold, typename BucketT,
typename BurstImpl, typename CharT>
static inline void
insert(TrieNode<CharT>* root, unsigned char** strings, size_t n)
{
for (size_t i=0; i < n; ++i) {
unsigned char* str = strings[i];
size_t depth = 0;
CharT c = get_char<CharT>(str, 0);
TrieNode<CharT>* node = root;
while (node->is_trie[c]) {
assert(not is_end(c));
node = static_cast<TrieNode<CharT>*>(node->buckets[c]);
depth += sizeof(CharT);
c = get_char<CharT>(str, depth);
}
BucketT* bucket = static_cast<BucketT*>(node->buckets[c]);
if (not bucket) {
node->buckets[c] = bucket = new BucketT;
}
bucket->push_back(str);
if (is_end(c)) continue;
if (bucket->size() > Threshold) {
node->buckets[c] = BurstImpl()(*bucket,
depth+sizeof(CharT));
node->is_trie[c] = true;
delete bucket;
}
}
}
// Use a wrapper to std::copy(). I haven't implemented iterators for some of my
// containers, instead they have optimized copy(bucket, dst).
static inline void
copy(const std::vector<unsigned char*>& bucket, unsigned char** dst)
{
std::copy(bucket.begin(), bucket.end(), dst);
}
// Traverses the trie and copies the strings back to the original string array.
// Nodes and buckets are deleted from memory during the traversal. The root
// node given to this function will also be deleted.
template <typename BucketT, typename SmallSort, typename CharT>
static unsigned char**
traverse(TrieNode<CharT>* node,
unsigned char** dst,
size_t depth,
SmallSort small_sort)
{
for (unsigned i=0; i < max<CharT>::value; ++i) {
if (node->is_trie[i]) {
dst = traverse<BucketT>(
static_cast<TrieNode<CharT>*>(node->buckets[i]),
dst, depth+sizeof(CharT), small_sort);
} else {
BucketT* bucket =
static_cast<BucketT*>(node->buckets[i]);
if (not bucket) continue;
size_t bsize = bucket->size();
copy(*bucket, dst);
if (not is_end(i)) small_sort(dst, bsize, depth);
dst += bsize;
delete bucket;
}
}
delete node;
return dst;
}
//#define SmallSort mkqsort
#define SmallSort msd_CE2
void msd_CE2(unsigned char**, size_t, size_t);
void burstsort_vector(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef std::vector<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<8000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_brodnik(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef vector_brodnik<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<16000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_bagwell(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef vector_bagwell<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<16000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_vector_block(unsigned char** strings, size_t n)
{
typedef unsigned char CharT;
typedef vector_block<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<16000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_vector(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef std::vector<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_brodnik(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef vector_brodnik<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_bagwell(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef vector_bagwell<unsigned char*> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
void burstsort_superalphabet_vector_block(unsigned char** strings, size_t n)
{
typedef uint16_t CharT;
typedef vector_block<unsigned char*, 128> BucketT;
typedef BurstSimple<CharT> BurstImpl;
//typedef BurstRecursive<CharT> BurstImpl;
TrieNode<CharT>* root = new TrieNode<CharT>;
insert<32000, BucketT, BurstImpl>(root, strings, n);
traverse<BucketT>(root, strings, 0, SmallSort);
}
| use smaller container block size in burstsort_superalphabet_vector_block() | use smaller container block size in burstsort_superalphabet_vector_block()
| C++ | mit | rantala/string-sorting,rantala/string-sorting,rantala/string-sorting,rantala/string-sorting |
e54deacf1a09ccafe1bcc48ec35ce6866b2a775d | toml/get.hpp | toml/get.hpp | #ifndef TOML11_GET
#define TOML11_GET
#include "value.hpp"
#include <algorithm>
namespace toml
{
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT != toml::value_t::Unknown &&
vT != value_t::Empty), std::nullptr_t>::type = nullptr>
inline T get(const toml::value& v)
{
return static_cast<T>(v.cast<vT>());
}
// array-like type
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
(!toml::detail::is_map<T>::value) &&
toml::detail::is_container<T>::value, std::nullptr_t>::type = nullptr>
T get(const toml::value& v)
{
if(v.type() != value_t::Array)
throw type_error("get: value type: " + stringize(v.type()) +
std::string(" is not argument type: Array"));
const auto& ar = v.cast<value_t::Array>();
T tmp;
try
{
toml::resize(tmp, ar.size());
}
catch(std::invalid_argument& iv)
{
throw toml::type_error("toml::get: static array size is not enough");
}
std::transform(ar.cbegin(), ar.cend(), tmp.begin(),
[](toml::value const& elem){return get<typename T::value_type>(elem);});
return tmp;
}
// table-like case
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
toml::detail::is_map<T>::value, std::nullptr_t>::type = nullptr>
T get(const toml::value& v)
{
if(v.type() != value_t::Table)
throw type_error("get: value type: " + stringize(v.type()) +
std::string(" is not argument type: Table"));
T tmp;
const auto& tb = v.cast<value_t::Table>();
for(const auto& kv : tb){tmp.insert(kv);}
return tmp;
}
// get_or -----------------------------------------------------------------
template<typename T>
inline typename std::remove_cv<typename std::remove_reference<T>::type>::type
get_or(const toml::Table& tab, const toml::key& ky, T&& opt)
{
if(tab.count(ky) == 0) {return std::forward<T>(opt);}
return get<typename std::remove_cv<
typename std::remove_reference<T>::type>::type>(tab.find(ky)->second);
}
} // toml
#endif// TOML11_GET
| #ifndef TOML11_GET
#define TOML11_GET
#include "value.hpp"
#include <algorithm>
namespace toml
{
template<typename T, typename std::enable_if<
detail::is_exact_toml_type<T>::value, std::nullptr_t>::type = nullptr>
inline T& get(value& v)
{
constexpr value_t kind = detail::check_type<T>();
return v.cast<kind>();
}
template<typename T, typename std::enable_if<
detail::is_exact_toml_type<T>::value, std::nullptr_t>::type = nullptr>
inline T const& get(const value& v)
{
constexpr value_t kind = detail::check_type<T>();
return v.cast<kind>();
}
template<typename T, typename std::enable_if<detail::conjunction<
detail::negation<detail::is_exact_toml_type<T>>,
detail::negation<std::is_same<T, bool>>, std::is_integral<T>
>::value, std::nullptr_t>::type = nullptr>
inline T get(const value& v)
{
return static_cast<T>(v.cast<value_t::Integer>());
}
template<typename T, typename std::enable_if<detail::conjunction<
detail::negation<detail::is_exact_toml_type<T>>, std::is_floating_point<T>
>::value, std::nullptr_t>::type = nullptr>
inline T get(const value& v)
{
return static_cast<T>(v.cast<value_t::Float>());
}
// array-like type
template<typename T, typename std::enable_if<detail::conjunction<
detail::negation<detail::is_exact_toml_type<T>>, detail::is_container<T>
>::value, std::nullptr_t>::type = nullptr>
T get(const value& v)
{
const auto& ar = v.cast<value_t::Array>();
T tmp;
try
{
::toml::resize(tmp, ar.size());
}
catch(std::invalid_argument& iv)
{
throw type_error("toml::get: static array: size is not enough");
}
std::transform(ar.cbegin(), ar.cend(), tmp.begin(),
[](value const& elem){return get<typename T::value_type>(elem);});
return tmp;
}
// table-like case
template<typename T, typename std::enable_if<detail::conjunction<
detail::negation<detail::is_exact_toml_type<T>>, detail::is_map<T>
>::value, std::nullptr_t>::type = nullptr>
T get(const toml::value& v)
{
const auto& tb = v.cast<value_t::Table>();
T tmp;
for(const auto& kv : tb){tmp.insert(kv);}
return tmp;
}
// get_or -----------------------------------------------------------------
template<typename T>
inline typename std::remove_cv<typename std::remove_reference<T>::type>::type
get_or(const toml::Table& tab, const toml::key& ky, T&& opt)
{
if(tab.count(ky) == 0) {return std::forward<T>(opt);}
return get<typename std::remove_cv<
typename std::remove_reference<T>::type>::type>(tab.find(ky)->second);
}
} // toml
#endif// TOML11_GET
| simplify SFINAE expressions in toml::get | simplify SFINAE expressions in toml::get
| C++ | mit | ToruNiina/toml11 |
39ea7b3cf80372a3457c4c3d04773952d5be99af | ui/gfx/linux_util_unittest.cc | ui/gfx/linux_util_unittest.cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/linux_util.h"
#include "base/basictypes.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gfx {
TEST(LinuxUtilTest, ConvertAcceleratorsFromWindowsStyle) {
static const struct {
const char* input;
const char* output;
} cases[] = {
{ "", "" },
{ "nothing", "nothing" },
{ "foo &bar", "foo _bar" },
{ "foo &&bar", "foo &bar" },
{ "foo &&&bar", "foo &_bar" },
{ "&foo &&bar", "_foo &bar" },
{ "&foo &bar", "_foo _bar" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input);
EXPECT_EQ(cases[i].output, result);
}
}
TEST(LinuxUtilTest, RemoveWindowsStyleAccelerators) {
static const struct {
const char* input;
const char* output;
} cases[] = {
{ "", "" },
{ "nothing", "nothing" },
{ "foo &bar", "foo bar" },
{ "foo &&bar", "foo &bar" },
{ "foo &&&bar", "foo &bar" },
{ "&foo &&bar", "foo &bar" },
{ "&foo &bar", "foo bar" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
std::string result = RemoveWindowsStyleAccelerators(cases[i].input);
EXPECT_EQ(cases[i].output, result);
}
}
} // namespace gfx
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/linux_util.h"
#include "base/basictypes.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gfx {
TEST(LinuxUtilTest, ConvertAcceleratorsFromWindowsStyle) {
static const struct {
const char* input;
const char* output;
} cases[] = {
{ "", "" },
{ "nothing", "nothing" },
{ "foo &bar", "foo _bar" },
{ "foo &&bar", "foo &bar" },
{ "foo &&&bar", "foo &_bar" },
{ "&foo &&bar", "_foo &bar" },
{ "&foo &bar", "_foo _bar" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input);
EXPECT_EQ(cases[i].output, result);
}
}
TEST(LinuxUtilTest, RemoveWindowsStyleAccelerators) {
static const struct {
const char* input;
const char* output;
} cases[] = {
{ "", "" },
{ "nothing", "nothing" },
{ "foo &bar", "foo bar" },
{ "foo &&bar", "foo &bar" },
{ "foo &&&bar", "foo &bar" },
{ "&foo &&bar", "foo &bar" },
{ "&foo &bar", "foo bar" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
std::string result = RemoveWindowsStyleAccelerators(cases[i].input);
EXPECT_EQ(cases[i].output, result);
}
}
TEST(LinuxUtilTest, EscapeWindowsStyleAccelerators) {
static const struct {
const char* input;
const char* output;
} cases[] = {
{ "nothing", "nothing" },
{ "foo &bar", "foo &&bar" },
{ "foo &&bar", "foo &&&&bar" },
{ "foo &&&bar", "foo &&&&&&bar" },
{ "&foo bar", "&&foo bar" },
{ "&&foo bar", "&&&&foo bar" },
{ "&&&foo bar", "&&&&&&foo bar" },
{ "&foo &bar", "&&foo &&bar" },
{ "&&foo &&bar", "&&&&foo &&&&bar" },
{ "f&o&o ba&r", "f&&o&&o ba&&r" },
{ "foo_&_bar", "foo_&&_bar" },
{ "&_foo_bar_&", "&&_foo_bar_&&" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); ++i) {
std::string result = EscapeWindowsStyleAccelerators(cases[i].input);
EXPECT_EQ(cases[i].output, result);
}
}
} // namespace gfx
| Add unittests for EscapeWindowsStyleAccelerators() function. | ui/gfx: Add unittests for EscapeWindowsStyleAccelerators() function.
TEST=ui_unittests --gtest_filter=LinuxUtilTest*
[email protected]
Review URL: https://chromiumcodereview.appspot.com/9839094
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@128825 0039d316-1c4b-4281-b951-d872f2087c98
| C++ | bsd-3-clause | mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,anirudhSK/chromium,keishi/chromium,dushu1203/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,M4sse/chromium.src,anirudhSK/chromium,jaruba/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,keishi/chromium,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,robclark/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,keishi/chromium,dushu1203/chromium.src,keishi/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,chuan9/chromium-crosswalk,dednal/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,dushu1203/chromium.src,littlstar/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,robclark/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,keishi/chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,littlstar/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,ltilve/chromium,ltilve/chromium,hujiajie/pa-chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,robclark/chromium,ondra-novak/chromium.src,Chilledheart/chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,dednal/chromium.src,littlstar/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,keishi/chromium,keishi/chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,ltilve/chromium,zcbenz/cefode-chromium,Just-D/chromium-1,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,robclark/chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,keishi/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,dednal/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,markYoungH/chromium.src,keishi/chromium,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,Just-D/chromium-1,hujiajie/pa-chromium,zcbenz/cefode-chromium,rogerwang/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,rogerwang/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,dushu1203/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,rogerwang/chromium,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,Chilledheart/chromium,Chilledheart/chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,krieger-od/nwjs_chromium.src,robclark/chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,patrickm/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,M4sse/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,Just-D/chromium-1,keishi/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,Chilledheart/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,littlstar/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,nacl-webkit/chrome_deps,robclark/chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,robclark/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,timopulkkinen/BubbleFish,hujiajie/pa-chromium,patrickm/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dednal/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,Chilledheart/chromium,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,patrickm/chromium.src,Just-D/chromium-1,zcbenz/cefode-chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,ltilve/chromium,anirudhSK/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,robclark/chromium,zcbenz/cefode-chromium,dednal/chromium.src,keishi/chromium,Jonekee/chromium.src,M4sse/chromium.src,nacl-webkit/chrome_deps,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk-efl |
94b7d495e11f2d60c4d3fdcabbbef46fd394e522 | urbackupclient/ClientHash.cpp | urbackupclient/ClientHash.cpp | #include "ClientHash.h"
#include "../Interface/File.h"
#include "../urbackupcommon/os_functions.h"
#include <memory>
#include <cstring>
#include <assert.h>
#include "../urbackupcommon/ExtentIterator.h"
#include "../fileservplugin/chunk_settings.h"
#include "../stringtools.h"
#include "../common/adler32.h"
#include "../md5.h"
#include "../urbackupcommon/TreeHash.h"
namespace
{
bool buf_is_zero(const char* buf, size_t bsize)
{
for (size_t i = 0; i < bsize; ++i)
{
if (buf[i] != 0)
{
return false;
}
}
return true;
}
std::string build_sparse_extent_content()
{
char buf[c_small_hash_dist] = {};
_u32 small_hash = urb_adler32(urb_adler32(0, NULL, 0), buf, c_small_hash_dist);
small_hash = little_endian(small_hash);
MD5 big_hash;
for (int64 i = 0; i<c_checkpoint_dist; i += c_small_hash_dist)
{
big_hash.update(reinterpret_cast<unsigned char*>(buf), c_small_hash_dist);
}
big_hash.finalize();
std::string ret;
ret.resize(chunkhash_single_size);
char* ptr = &ret[0];
memcpy(ptr, big_hash.raw_digest_int(), big_hash_size);
ptr += big_hash_size;
for (int64 i = 0; i < c_checkpoint_dist; i += c_small_hash_dist)
{
memcpy(ptr, &small_hash, sizeof(small_hash));
ptr += sizeof(small_hash);
}
return ret;
}
}
ClientHash::ClientHash(IFile * index_hdat_file,
bool own_hdat_file,
int64 index_hdat_fs_block_size,
size_t* snapshot_sequence_id, size_t snapshot_sequence_id_reference)
: index_hdat_file(index_hdat_file),
own_hdat_file(own_hdat_file),
index_hdat_fs_block_size(index_hdat_fs_block_size),
index_chunkhash_pos(-1),
snapshot_sequence_id(snapshot_sequence_id),
snapshot_sequence_id_reference(snapshot_sequence_id_reference)
{
}
ClientHash::~ClientHash()
{
if (own_hdat_file)
{
Server->destroy(index_hdat_file);
}
}
bool ClientHash::getShaBinary(const std::string & fn, IHashFunc & hf, bool with_cbt)
{
std::auto_ptr<IFsFile> f(Server->openFile(os_file_prefix(fn), MODE_READ_SEQUENTIAL_BACKUP));
if (f.get() == NULL)
{
return false;
}
int64 skip_start = -1;
bool needs_seek = false;
const size_t bsize = 512 * 1024;
int64 fpos = 0;
_u32 rc = 1;
std::vector<char> buf;
buf.resize(bsize);
FsExtentIterator extent_iterator(f.get(), bsize);
IFsFile::SSparseExtent curr_sparse_extent = extent_iterator.nextExtent();
int64 fsize = f->Size();
bool has_more_extents = false;
std::vector<IFsFile::SFileExtent> extents;
size_t curr_extent_idx = 0;
if (with_cbt
&& fsize>c_checkpoint_dist)
{
extents = f->getFileExtents(0, index_hdat_fs_block_size, has_more_extents);
}
else
{
with_cbt = false;
}
while (fpos <= fsize && rc>0)
{
while (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset + curr_sparse_extent.size<fpos)
{
curr_sparse_extent = extent_iterator.nextExtent();
}
size_t curr_bsize = bsize;
if (fpos + static_cast<int64>(curr_bsize) > fsize)
{
curr_bsize = static_cast<size_t>(fsize - fpos);
}
if (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset <= fpos
&& curr_sparse_extent.offset + curr_sparse_extent.size >= fpos + static_cast<int64>(bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
fpos += bsize;
rc = static_cast<_u32>(bsize);
continue;
}
index_chunkhash_pos = -1;
if (!extents.empty()
&& index_hdat_file != NULL
&& fpos%c_checkpoint_dist == 0
&& curr_bsize == bsize)
{
assert(bsize == c_checkpoint_dist);
while (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size < fpos)
{
++curr_extent_idx;
if (curr_extent_idx >= extents.size()
&& has_more_extents)
{
extents = f->getFileExtents(fpos, index_hdat_fs_block_size, has_more_extents);
curr_extent_idx = 0;
}
}
if (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset <= fpos
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size >= fpos + static_cast<int64>(bsize))
{
int64 volume_pos = extents[curr_extent_idx].volume_offset + (fpos - extents[curr_extent_idx].offset);
index_chunkhash_pos = (volume_pos / c_checkpoint_dist)*(sizeof(_u16) + chunkhash_single_size);
index_chunkhash_pos_offset = static_cast<_u16>((volume_pos%c_checkpoint_dist) / 512);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference
&& index_hdat_file->Read(index_chunkhash_pos, chunkhash, sizeof(chunkhash)) == sizeof(chunkhash))
{
_u16 chunkhash_offset;
memcpy(&chunkhash_offset, chunkhash, sizeof(chunkhash_offset));
if (index_chunkhash_pos_offset == chunkhash_offset
&& !buf_is_zero(chunkhash, sizeof(chunkhash)))
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
if (memcmp(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size) == 0)
{
if (skip_start == -1)
{
skip_start = fpos;
}
}
else
{
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
hf.addHashAllAdler(chunkhash + sizeof(_u16), chunkhash_single_size, bsize);
}
fpos += bsize;
rc = bsize;
needs_seek = true;
continue;
}
}
else
{
index_chunkhash_pos = -1;
}
}
}
if (skip_start != -1
|| needs_seek)
{
f->Seek(fpos);
needs_seek = false;
}
if (curr_bsize > 0)
{
bool has_read_error = false;
rc = f->Read(buf.data(), static_cast<_u32>(curr_bsize), &has_read_error);
if (has_read_error)
{
std::string msg;
int64 code = os_last_error(msg);
Server->Log("Read error while hashing \"" + fn + "\". " + msg + " (code: " + convert(code) + ")", LL_ERROR);
return false;
}
}
else
{
rc = 0;
}
if (rc == bsize && buf_is_zero(buf.data(), bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
fpos += bsize;
rc = bsize;
if (index_chunkhash_pos != -1)
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
continue;
}
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
if (rc > 0)
{
hf.hash(buf.data(), rc);
fpos += rc;
}
}
return true;
}
void ClientHash::hash_output_all_adlers(int64 pos, const char * hash, size_t hsize)
{
if (index_chunkhash_pos != -1
&& index_hdat_file != NULL)
{
assert(hsize == chunkhash_single_size);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), hash, chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
}
| #include "ClientHash.h"
#include "../Interface/File.h"
#include "../urbackupcommon/os_functions.h"
#include <memory>
#include <cstring>
#include <assert.h>
#include "../urbackupcommon/ExtentIterator.h"
#include "../fileservplugin/chunk_settings.h"
#include "../stringtools.h"
#include "../common/adler32.h"
#include "../md5.h"
#include "../urbackupcommon/TreeHash.h"
namespace
{
bool buf_is_zero(const char* buf, size_t bsize)
{
for (size_t i = 0; i < bsize; ++i)
{
if (buf[i] != 0)
{
return false;
}
}
return true;
}
std::string build_sparse_extent_content()
{
char buf[c_small_hash_dist] = {};
_u32 small_hash = urb_adler32(urb_adler32(0, NULL, 0), buf, c_small_hash_dist);
small_hash = little_endian(small_hash);
MD5 big_hash;
for (int64 i = 0; i<c_checkpoint_dist; i += c_small_hash_dist)
{
big_hash.update(reinterpret_cast<unsigned char*>(buf), c_small_hash_dist);
}
big_hash.finalize();
std::string ret;
ret.resize(chunkhash_single_size);
char* ptr = &ret[0];
memcpy(ptr, big_hash.raw_digest_int(), big_hash_size);
ptr += big_hash_size;
for (int64 i = 0; i < c_checkpoint_dist; i += c_small_hash_dist)
{
memcpy(ptr, &small_hash, sizeof(small_hash));
ptr += sizeof(small_hash);
}
return ret;
}
}
ClientHash::ClientHash(IFile * index_hdat_file,
bool own_hdat_file,
int64 index_hdat_fs_block_size,
size_t* snapshot_sequence_id, size_t snapshot_sequence_id_reference)
: index_hdat_file(index_hdat_file),
own_hdat_file(own_hdat_file),
index_hdat_fs_block_size(index_hdat_fs_block_size),
index_chunkhash_pos(-1),
snapshot_sequence_id(snapshot_sequence_id),
snapshot_sequence_id_reference(snapshot_sequence_id_reference)
{
}
ClientHash::~ClientHash()
{
if (own_hdat_file)
{
Server->destroy(index_hdat_file);
}
}
bool ClientHash::getShaBinary(const std::string & fn, IHashFunc & hf, bool with_cbt)
{
std::auto_ptr<IFsFile> f(Server->openFile(os_file_prefix(fn), MODE_READ_SEQUENTIAL_BACKUP));
if (f.get() == NULL)
{
return false;
}
int64 skip_start = -1;
bool needs_seek = false;
const size_t bsize = 512 * 1024;
int64 fpos = 0;
_u32 rc = 1;
std::vector<char> buf;
buf.resize(bsize);
FsExtentIterator extent_iterator(f.get(), bsize);
IFsFile::SSparseExtent curr_sparse_extent = extent_iterator.nextExtent();
int64 fsize = f->Size();
bool has_more_extents = false;
std::vector<IFsFile::SFileExtent> extents;
size_t curr_extent_idx = 0;
if (with_cbt
&& fsize>c_checkpoint_dist)
{
extents = f->getFileExtents(0, index_hdat_fs_block_size, has_more_extents);
}
else
{
with_cbt = false;
}
while (fpos <= fsize && rc>0)
{
while (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset + curr_sparse_extent.size<fpos)
{
curr_sparse_extent = extent_iterator.nextExtent();
}
size_t curr_bsize = bsize;
if (fpos + static_cast<int64>(curr_bsize) > fsize)
{
curr_bsize = static_cast<size_t>(fsize - fpos);
}
if (curr_sparse_extent.offset != -1
&& curr_sparse_extent.offset <= fpos
&& curr_sparse_extent.offset + curr_sparse_extent.size >= fpos + static_cast<int64>(bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
Server->Log("Sparse extent at fpos " + convert(fpos), LL_DEBUG);
fpos += bsize;
rc = static_cast<_u32>(bsize);
continue;
}
index_chunkhash_pos = -1;
if (!extents.empty()
&& index_hdat_file != NULL
&& fpos%c_checkpoint_dist == 0
&& curr_bsize == bsize)
{
assert(bsize == c_checkpoint_dist);
while (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size < fpos)
{
++curr_extent_idx;
if (curr_extent_idx >= extents.size()
&& has_more_extents)
{
extents = f->getFileExtents(fpos, index_hdat_fs_block_size, has_more_extents);
curr_extent_idx = 0;
}
}
if (curr_extent_idx<extents.size()
&& extents[curr_extent_idx].offset <= fpos
&& extents[curr_extent_idx].offset + extents[curr_extent_idx].size >= fpos + static_cast<int64>(bsize))
{
int64 volume_pos = extents[curr_extent_idx].volume_offset + (fpos - extents[curr_extent_idx].offset);
index_chunkhash_pos = (volume_pos / c_checkpoint_dist)*(sizeof(_u16) + chunkhash_single_size);
index_chunkhash_pos_offset = static_cast<_u16>((volume_pos%c_checkpoint_dist) / 512);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference
&& index_hdat_file->Read(index_chunkhash_pos, chunkhash, sizeof(chunkhash)) == sizeof(chunkhash))
{
_u16 chunkhash_offset;
memcpy(&chunkhash_offset, chunkhash, sizeof(chunkhash_offset));
if (index_chunkhash_pos_offset == chunkhash_offset
&& !buf_is_zero(chunkhash, sizeof(chunkhash)))
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
if (memcmp(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size) == 0)
{
Server->Log("Sparse extent from CBT data at fpos " + convert(fpos), LL_DEBUG);
if (skip_start == -1)
{
skip_start = fpos;
}
}
else
{
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
Server->Log("Hash data from CBT data at fpos " + convert(fpos), LL_DEBUG);
hf.addHashAllAdler(chunkhash + sizeof(_u16), chunkhash_single_size, bsize);
}
fpos += bsize;
rc = bsize;
needs_seek = true;
continue;
}
}
else
{
index_chunkhash_pos = -1;
}
}
}
if (skip_start != -1
|| needs_seek)
{
f->Seek(fpos);
needs_seek = false;
}
if (curr_bsize > 0)
{
bool has_read_error = false;
rc = f->Read(buf.data(), static_cast<_u32>(curr_bsize), &has_read_error);
if (has_read_error)
{
std::string msg;
int64 code = os_last_error(msg);
Server->Log("Read error while hashing \"" + fn + "\". " + msg + " (code: " + convert(code) + ")", LL_ERROR);
return false;
}
}
else
{
rc = 0;
}
if (rc == bsize && buf_is_zero(buf.data(), bsize))
{
if (skip_start == -1)
{
skip_start = fpos;
}
Server->Log("Sparse extent (zeroes) at fpos " + convert(fpos), LL_DEBUG);
fpos += bsize;
rc = bsize;
if (index_chunkhash_pos != -1)
{
if (sparse_extent_content.empty())
{
sparse_extent_content = build_sparse_extent_content();
assert(sparse_extent_content.size() == chunkhash_single_size);
}
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), sparse_extent_content.data(), chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
continue;
}
if (skip_start != -1)
{
int64 skip[2];
skip[0] = skip_start;
skip[1] = fpos - skip_start;
hf.sparse_hash(reinterpret_cast<char*>(&skip), sizeof(int64) * 2);
skip_start = -1;
}
if (rc > 0)
{
hf.hash(buf.data(), rc);
fpos += rc;
}
}
return true;
}
void ClientHash::hash_output_all_adlers(int64 pos, const char * hash, size_t hsize)
{
if (index_chunkhash_pos != -1
&& index_hdat_file != NULL)
{
assert(hsize == chunkhash_single_size);
char chunkhash[sizeof(_u16) + chunkhash_single_size];
memcpy(chunkhash, &index_chunkhash_pos_offset, sizeof(index_chunkhash_pos_offset));
memcpy(chunkhash + sizeof(_u16), hash, chunkhash_single_size);
if (snapshot_sequence_id!=NULL
&& *snapshot_sequence_id == snapshot_sequence_id_reference)
{
index_hdat_file->Write(index_chunkhash_pos, chunkhash, sizeof(chunkhash));
}
}
}
| Add some debug info to client hashing | Add some debug info to client hashing
| C++ | agpl-3.0 | uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend,uroni/urbackup_backend |
351389b0d2a82df75a692de5fe2a3f31c6a62cab | tests/formats/xyz.cpp | tests/formats/xyz.cpp | #include <streambuf>
#include <fstream>
#include "catch.hpp"
#include "Chemharp.hpp"
using namespace harp;
#include <boost/filesystem.hpp>
namespace fs=boost::filesystem;
#define XYZDIR SRCDIR "/files/xyz/"
TEST_CASE("Read files in XYZ format", "[XYZ]"){
auto file = Trajectory(XYZDIR"helium.xyz");
Frame frame;
SECTION("Stream style reading"){
CHECK(file.nsteps() == 397);
file >> frame;
CHECK(frame.natoms() == 125);
// Check positions
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(0.49053f, 8.41351f, 0.0777257f));
CHECK(positions[124] == Vector3D(8.57951f, 8.65712f, 8.06678f));
// Check topology
auto topology = frame.topology();
CHECK(topology.natom_types() == 1);
CHECK(topology.natoms() == 125);
CHECK(topology[0] == Atom("He"));
}
SECTION("Method style reading"){
frame = file.read_next_step();
CHECK(frame.natoms() == 125);
// Check positions
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(0.49053f, 8.41351f, 0.0777257f));
CHECK(positions[124] == Vector3D(8.57951f, 8.65712f, 8.06678f));
// Check topology
auto topology = frame.topology();
CHECK(topology.natom_types() == 1);
CHECK(topology.natoms() == 125);
CHECK(topology[0] == Atom("He"));
}
SECTION("Read a specific step"){
// Read frame at a specific positions
frame = file.read_at_step(42);
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(-0.145821f, 8.540648f, 1.090281f));
CHECK(positions[124] == Vector3D(8.446093f, 8.168162f, 9.350953f));
auto topology = frame.topology();
CHECK(topology.natom_types() == 1);
CHECK(topology.natoms() == 125);
CHECK(topology[0] == Atom("He"));
}
SECTION("Read the whole file"){
while (not file.done()){
file >> frame;
}
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(-1.186037f, 11.439334f, 0.529939f));
CHECK(positions[124] == Vector3D(5.208778f, 12.707273f, 10.940157f));
}
}
// To use in loops in order to iterate over files in a specific directory.
struct directory_files_iterator {
typedef fs::recursive_directory_iterator iterator;
directory_files_iterator(fs::path p) : p_(p) {}
iterator begin() { return fs::recursive_directory_iterator(p_); }
iterator end() { return fs::recursive_directory_iterator(); }
fs::path p_;
};
TEST_CASE("Errors in XYZ format", "[XYZ]"){
for (auto entry : directory_files_iterator(XYZDIR"bad/")){
CHECK_THROWS_AS(
// We can throw either when creating the trajectory, or when reading
// the frame, depending on the type of error
auto file = Trajectory(entry.path().string());
file.read_next_step(),
FormatError);
}
}
TEST_CASE("Write files in XYZ format", "[XYZ]"){
const auto expected_content =
"4\n"
"Written by Chemharp\n"
"X 1 2 3\n"
"X 1 2 3\n"
"X 1 2 3\n"
"X 1 2 3\n";
Frame frame(0);
frame.topology(dummy_topology(4));
Array3D positions;
for(int i=0; i<4; i++)
positions.push_back(Vector3D(1, 2, 3));
frame.positions(positions);
auto file = Trajectory("test-tmp.xyz", "w");
file << frame;
file.close();
std::ifstream checking("test-tmp.xyz");
std::string content((std::istreambuf_iterator<char>(checking)),
std::istreambuf_iterator<char>());
checking.close();
CHECK(content == expected_content);
unlink("test-tmp.xyz");
}
| #include <streambuf>
#include <fstream>
#include "catch.hpp"
#include "Chemharp.hpp"
using namespace harp;
#include <boost/filesystem.hpp>
namespace fs=boost::filesystem;
#define XYZDIR SRCDIR "/files/xyz/"
TEST_CASE("Read files in XYZ format", "[XYZ]"){
auto file = Trajectory(XYZDIR"helium.xyz");
Frame frame;
SECTION("Stream style reading"){
CHECK(file.nsteps() == 397);
file >> frame;
CHECK(frame.natoms() == 125);
// Check positions
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(0.49053f, 8.41351f, 0.0777257f));
CHECK(positions[124] == Vector3D(8.57951f, 8.65712f, 8.06678f));
// Check topology
auto topology = frame.topology();
CHECK(topology.natom_types() == 1);
CHECK(topology.natoms() == 125);
CHECK(topology[0] == Atom("He"));
}
SECTION("Method style reading"){
frame = file.read_next_step();
CHECK(frame.natoms() == 125);
// Check positions
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(0.49053f, 8.41351f, 0.0777257f));
CHECK(positions[124] == Vector3D(8.57951f, 8.65712f, 8.06678f));
// Check topology
auto topology = frame.topology();
CHECK(topology.natom_types() == 1);
CHECK(topology.natoms() == 125);
CHECK(topology[0] == Atom("He"));
}
SECTION("Read a specific step"){
// Read frame at a specific positions
frame = file.read_at_step(42);
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(-0.145821f, 8.540648f, 1.090281f));
CHECK(positions[124] == Vector3D(8.446093f, 8.168162f, 9.350953f));
auto topology = frame.topology();
CHECK(topology.natom_types() == 1);
CHECK(topology.natoms() == 125);
CHECK(topology[0] == Atom("He"));
}
SECTION("Read the whole file"){
while (not file.done()){
file >> frame;
}
auto positions = frame.positions();
CHECK(positions[0] == Vector3D(-1.186037f, 11.439334f, 0.529939f));
CHECK(positions[124] == Vector3D(5.208778f, 12.707273f, 10.940157f));
}
}
// To use in loops in order to iterate over files in a specific directory.
struct directory_files_iterator {
typedef fs::recursive_directory_iterator iterator;
directory_files_iterator(fs::path p) : p_(p) {}
iterator begin() { return fs::recursive_directory_iterator(p_); }
iterator end() { return fs::recursive_directory_iterator(); }
fs::path p_;
};
TEST_CASE("Errors in XYZ format", "[XYZ]"){
for (auto entry : directory_files_iterator(XYZDIR"bad/")){
CHECK_THROWS_AS(
// We can throw either when creating the trajectory, or when reading
// the frame, depending on the type of error
auto file = Trajectory(entry.path().string());
file.read_next_step(),
FormatError);
}
}
TEST_CASE("Write files in XYZ format", "[XYZ]"){
const auto expected_content =
"4\n"
"Written by Chemharp\n"
"X 1 2 3\n"
"X 1 2 3\n"
"X 1 2 3\n"
"X 1 2 3\n"
"6\n"
"Written by Chemharp\n"
"X 4 5 6\n"
"X 4 5 6\n"
"X 4 5 6\n"
"X 4 5 6\n"
"X 4 5 6\n"
"X 4 5 6\n";
Array3D positions(4);
for(size_t i=0; i<4; i++)
positions[i] = Vector3D(1, 2, 3);
Frame frame;
frame.topology(dummy_topology(4));
frame.positions(positions);
auto file = Trajectory("test-tmp.xyz", "w");
file << frame;
positions.resize(6);
for(size_t i=0; i<6; i++)
positions[i] = Vector3D(4, 5, 6);
frame.topology(dummy_topology(6));
frame.positions(positions);
file << frame;
file.close();
std::ifstream checking("test-tmp.xyz");
std::string content((std::istreambuf_iterator<char>(checking)),
std::istreambuf_iterator<char>());
checking.close();
CHECK(content == expected_content);
unlink("test-tmp.xyz");
}
| Test writing more than one frame to a file in XYZ format | Test writing more than one frame to a file in XYZ format
| C++ | bsd-3-clause | chemfiles/chemfiles,Luthaf/Chemharp,chemfiles/chemfiles,Luthaf/Chemharp,lscalfi/chemfiles,Luthaf/Chemharp,lscalfi/chemfiles,chemfiles/chemfiles,lscalfi/chemfiles,chemfiles/chemfiles,lscalfi/chemfiles |
b88851628eabb00b90a745cc6cfef66dfd4384af | util/statetrace/statetrace.cc | util/statetrace/statetrace.cc | /*
* Copyright (c) 2006-2007 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <cstring>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "printer.hh"
#include "tracechild.hh"
using namespace std;
void printUsage(const char * execName)
{
cout << execName << " -h | -r -- <command> <arguments>" << endl;
}
int main(int argc, char * argv[], char * envp[])
{
TraceChild * child = genTraceChild();
string args;
int startProgramArgs;
//Parse the command line arguments
bool printInitial = false;
bool printTrace = true;
string host = "localhost";
for(int x = 1; x < argc; x++)
{
if(!strcmp(argv[x], "-h"))
{
printUsage(argv[0]);
return 0;
}
if(!strcmp(argv[x], "--host"))
{
x++;
if(x >= argc)
{
cerr << "Incorrect usage.\n" << endl;
printUsage(argv[0]);
return 1;
}
host = argv[x];
}
else if(!strcmp(argv[x], "-r"))
{
cout << "Legal register names:" << endl;
int numRegs = child->getNumRegs();
for(unsigned int x = 0; x < numRegs; x++)
{
cout << "\t" << child->getRegName(x) << endl;
}
return 0;
}
else if(!strcmp(argv[x], "-i"))
{
printInitial = true;
}
else if(!strcmp(argv[x], "-nt"))
{
printTrace = false;
}
else if(!strcmp(argv[x], "--"))
{
x++;
if(x >= argc)
{
cerr << "Incorrect usage.\n" << endl;
printUsage(argv[0]);
return 1;
}
startProgramArgs = x;
break;
}
else
{
cerr << "Incorrect usage.\n" << endl;
printUsage(argv[0]);
return 1;
}
}
if(!child->startTracing(argv[startProgramArgs],
argv + startProgramArgs))
{
cerr << "Couldn't start target program" << endl;
return 1;
}
if(printInitial)
{
child->outputStartState(cout);
}
if(printTrace)
{
// Connect to m5
bool portSet = false;
int port;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
cerr << "Error opening socket! " << strerror(errno) << endl;
return 1;
}
struct hostent *server;
server = gethostbyname(host.c_str());
if(!server)
{
cerr << "Couldn't get host ip! " << strerror(errno) << endl;
return 1;
}
struct sockaddr_in serv_addr;
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(8000);
if(connect(sock, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
cerr << "Couldn't connect to server! " << strerror(errno) << endl;
return 1;
}
child->step();
while(child->isTracing())
{
if(!child->sendState(sock))
break;
child->step();
}
}
if(!child->stopTracing())
{
cerr << "Couldn't stop child" << endl;
return 1;
}
return 0;
}
| /*
* Copyright (c) 2006-2007 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include <cstring>
#include <errno.h>
#include <fstream>
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "printer.hh"
#include "tracechild.hh"
using namespace std;
void printUsage(const char * execName)
{
cout << execName << " -h | -r -- <command> <arguments>" << endl;
}
int main(int argc, char * argv[], char * envp[])
{
TraceChild * child = genTraceChild();
string args;
int startProgramArgs;
//Parse the command line arguments
bool printInitial = false;
bool printTrace = true;
string host = "localhost";
for(int x = 1; x < argc; x++)
{
if(!strcmp(argv[x], "-h"))
{
printUsage(argv[0]);
return 0;
}
if(!strcmp(argv[x], "--host"))
{
x++;
if(x >= argc)
{
cerr << "Incorrect usage.\n" << endl;
printUsage(argv[0]);
return 1;
}
host = argv[x];
}
else if(!strcmp(argv[x], "-r"))
{
cout << "Legal register names:" << endl;
int numRegs = child->getNumRegs();
for(unsigned int x = 0; x < numRegs; x++)
{
cout << "\t" << child->getRegName(x) << endl;
}
return 0;
}
else if(!strcmp(argv[x], "-i"))
{
printInitial = true;
}
else if(!strcmp(argv[x], "-nt"))
{
printTrace = false;
}
else if(!strcmp(argv[x], "--"))
{
x++;
if(x >= argc)
{
cerr << "Incorrect usage.\n" << endl;
printUsage(argv[0]);
return 1;
}
startProgramArgs = x;
break;
}
else
{
cerr << "Incorrect usage.\n" << endl;
printUsage(argv[0]);
return 1;
}
}
if(!child->startTracing(argv[startProgramArgs],
argv + startProgramArgs))
{
cerr << "Couldn't start target program" << endl;
return 1;
}
child->step();
if(printInitial)
{
child->outputStartState(cout);
}
if(printTrace)
{
// Connect to m5
bool portSet = false;
int port;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
cerr << "Error opening socket! " << strerror(errno) << endl;
return 1;
}
struct hostent *server;
server = gethostbyname(host.c_str());
if(!server)
{
cerr << "Couldn't get host ip! " << strerror(errno) << endl;
return 1;
}
struct sockaddr_in serv_addr;
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(8000);
if(connect(sock, (sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
cerr << "Couldn't connect to server! " << strerror(errno) << endl;
return 1;
}
while(child->isTracing())
{
if(!child->sendState(sock))
break;
child->step();
}
}
if(!child->stopTracing())
{
cerr << "Couldn't stop child" << endl;
return 1;
}
return 0;
}
| Make sure the current state is loaded to print the initial stack frame. The early call to child->step() was removed earlier because it confused the new differences-only protocol ARM sendState() was using. It's necessary that that gets called at least once before attempting to print the initial stack frame, though, because otherwise statetrace doesn't know what the stack pointer is. By putting the first call to child->step() in a common spot, both needs are met. | Statetrace: Make sure the current state is loaded to print the initial stack frame.
The early call to child->step() was removed earlier because it confused the
new differences-only protocol ARM sendState() was using. It's necessary that
that gets called at least once before attempting to print the initial stack
frame, though, because otherwise statetrace doesn't know what the stack
pointer is. By putting the first call to child->step() in a common spot, both
needs are met.
| C++ | bsd-3-clause | andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin |
cf4787478caf77eb205626c64f3b9ab138e2369c | src/sim/byteswap.hh | src/sim/byteswap.hh | /*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
* Ali Saidi
* Nathan Binkert
*/
//The purpose of this file is to provide endainness conversion utility
//functions. Depending on the endianness of the guest system, either
//the LittleEndianGuest or BigEndianGuest namespace is used.
#ifndef __SIM_BYTE_SWAP_HH__
#define __SIM_BYTE_SWAP_HH__
#include "base/bigint.hh"
#include "base/misc.hh"
#include "base/types.hh"
// This lets us figure out what the byte order of the host system is
#if defined(__linux__)
#include <endian.h>
// If this is a linux system, lets used the optimized definitions if they exist.
// If one doesn't exist, we pretty much get what is listed below, so it all
// works out
#include <byteswap.h>
#elif defined (__sun)
#include <sys/isa_defs.h>
#else
#include <machine/endian.h>
#endif
#if defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#endif
enum ByteOrder {BigEndianByteOrder, LittleEndianByteOrder};
//These functions actually perform the swapping for parameters
//of various bit lengths
inline uint64_t
swap_byte64(uint64_t x)
{
#if defined(__linux__)
return bswap_64(x);
#elif defined(__APPLE__)
return OSSwapInt64(x);
#else
return (uint64_t)((((uint64_t)(x) & 0xff) << 56) |
((uint64_t)(x) & 0xff00ULL) << 40 |
((uint64_t)(x) & 0xff0000ULL) << 24 |
((uint64_t)(x) & 0xff000000ULL) << 8 |
((uint64_t)(x) & 0xff00000000ULL) >> 8 |
((uint64_t)(x) & 0xff0000000000ULL) >> 24 |
((uint64_t)(x) & 0xff000000000000ULL) >> 40 |
((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ;
#endif
}
inline uint32_t
swap_byte32(uint32_t x)
{
#if defined(__linux__)
return bswap_32(x);
#elif defined(__APPLE__)
return OSSwapInt32(x);
#else
return (uint32_t)(((uint32_t)(x) & 0xff) << 24 |
((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 |
((uint32_t)(x) & 0xff000000) >> 24);
#endif
}
inline uint16_t
swap_byte16(uint16_t x)
{
#if defined(__linux__)
return bswap_16(x);
#elif defined(__APPLE__)
return OSSwapInt16(x);
#else
return (uint16_t)(((uint16_t)(x) & 0xff) << 8 |
((uint16_t)(x) & 0xff00) >> 8);
#endif
}
// This function lets the compiler figure out how to call the
// swap_byte functions above for different data types. Since the
// sizeof() values are known at compile time, it should inline to a
// direct call to the right swap_byteNN() function.
template <typename T>
inline T swap_byte(T x) {
if (sizeof(T) == 8)
return swap_byte64((uint64_t)x);
else if (sizeof(T) == 4)
return swap_byte32((uint32_t)x);
else if (sizeof(T) == 2)
return swap_byte16((uint16_t)x);
else if (sizeof(T) == 1)
return x;
else
panic("Can't byte-swap values larger than 64 bits");
}
template<>
inline Twin64_t swap_byte<Twin64_t>(Twin64_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
template<>
inline Twin32_t swap_byte<Twin32_t>(Twin32_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
//The conversion functions with fixed endianness on both ends don't need to
//be in a namespace
template <typename T> inline T betole(T value) {return swap_byte(value);}
template <typename T> inline T letobe(T value) {return swap_byte(value);}
//For conversions not involving the guest system, we can define the functions
//conditionally based on the BYTE_ORDER macro and outside of the namespaces
#if defined(_BIG_ENDIAN) || !defined(_LITTLE_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
const ByteOrder HostByteOrder = BigEndianByteOrder;
template <typename T> inline T htole(T value) {return swap_byte(value);}
template <typename T> inline T letoh(T value) {return swap_byte(value);}
template <typename T> inline T htobe(T value) {return value;}
template <typename T> inline T betoh(T value) {return value;}
#elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN
const ByteOrder HostByteOrder = LittleEndianByteOrder;
template <typename T> inline T htole(T value) {return value;}
template <typename T> inline T letoh(T value) {return value;}
template <typename T> inline T htobe(T value) {return swap_byte(value);}
template <typename T> inline T betoh(T value) {return swap_byte(value);}
#else
#error Invalid Endianess
#endif
namespace BigEndianGuest
{
const ByteOrder GuestByteOrder = BigEndianByteOrder;
template <typename T>
inline T gtole(T value) {return betole(value);}
template <typename T>
inline T letog(T value) {return letobe(value);}
template <typename T>
inline T gtobe(T value) {return value;}
template <typename T>
inline T betog(T value) {return value;}
template <typename T>
inline T htog(T value) {return htobe(value);}
template <typename T>
inline T gtoh(T value) {return betoh(value);}
}
namespace LittleEndianGuest
{
const ByteOrder GuestByteOrder = LittleEndianByteOrder;
template <typename T>
inline T gtole(T value) {return value;}
template <typename T>
inline T letog(T value) {return value;}
template <typename T>
inline T gtobe(T value) {return letobe(value);}
template <typename T>
inline T betog(T value) {return betole(value);}
template <typename T>
inline T htog(T value) {return htole(value);}
template <typename T>
inline T gtoh(T value) {return letoh(value);}
}
#endif // __SIM_BYTE_SWAP_HH__
| /*
* Copyright (c) 2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
* Ali Saidi
* Nathan Binkert
*/
//The purpose of this file is to provide endainness conversion utility
//functions. Depending on the endianness of the guest system, either
//the LittleEndianGuest or BigEndianGuest namespace is used.
#ifndef __SIM_BYTE_SWAP_HH__
#define __SIM_BYTE_SWAP_HH__
#include "base/bigint.hh"
#include "base/misc.hh"
#include "base/types.hh"
// This lets us figure out what the byte order of the host system is
#if defined(__linux__)
#include <endian.h>
// If this is a linux system, lets used the optimized definitions if they exist.
// If one doesn't exist, we pretty much get what is listed below, so it all
// works out
#include <byteswap.h>
#elif defined (__sun)
#include <sys/isa_defs.h>
#else
#include <machine/endian.h>
#endif
#if defined(__APPLE__)
#include <libkern/OSByteOrder.h>
#endif
enum ByteOrder {BigEndianByteOrder, LittleEndianByteOrder};
//These functions actually perform the swapping for parameters
//of various bit lengths
inline uint64_t
swap_byte64(uint64_t x)
{
#if defined(__linux__)
return bswap_64(x);
#elif defined(__APPLE__)
return OSSwapInt64(x);
#else
return (uint64_t)((((uint64_t)(x) & 0xff) << 56) |
((uint64_t)(x) & 0xff00ULL) << 40 |
((uint64_t)(x) & 0xff0000ULL) << 24 |
((uint64_t)(x) & 0xff000000ULL) << 8 |
((uint64_t)(x) & 0xff00000000ULL) >> 8 |
((uint64_t)(x) & 0xff0000000000ULL) >> 24 |
((uint64_t)(x) & 0xff000000000000ULL) >> 40 |
((uint64_t)(x) & 0xff00000000000000ULL) >> 56) ;
#endif
}
inline uint32_t
swap_byte32(uint32_t x)
{
#if defined(__linux__)
return bswap_32(x);
#elif defined(__APPLE__)
return OSSwapInt32(x);
#else
return (uint32_t)(((uint32_t)(x) & 0xff) << 24 |
((uint32_t)(x) & 0xff00) << 8 | ((uint32_t)(x) & 0xff0000) >> 8 |
((uint32_t)(x) & 0xff000000) >> 24);
#endif
}
inline uint16_t
swap_byte16(uint16_t x)
{
#if defined(__linux__)
return bswap_16(x);
#elif defined(__APPLE__)
return OSSwapInt16(x);
#else
return (uint16_t)(((uint16_t)(x) & 0xff) << 8 |
((uint16_t)(x) & 0xff00) >> 8);
#endif
}
// This function lets the compiler figure out how to call the
// swap_byte functions above for different data types. Since the
// sizeof() values are known at compile time, it should inline to a
// direct call to the right swap_byteNN() function.
template <typename T>
inline T swap_byte(T x) {
if (sizeof(T) == 8)
return swap_byte64((uint64_t)x);
else if (sizeof(T) == 4)
return swap_byte32((uint32_t)x);
else if (sizeof(T) == 2)
return swap_byte16((uint16_t)x);
else if (sizeof(T) == 1)
return x;
else
panic("Can't byte-swap values larger than 64 bits");
}
template<>
inline Twin64_t swap_byte<Twin64_t>(Twin64_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
template<>
inline Twin32_t swap_byte<Twin32_t>(Twin32_t x)
{
x.a = swap_byte(x.a);
x.b = swap_byte(x.b);
return x;
}
//The conversion functions with fixed endianness on both ends don't need to
//be in a namespace
template <typename T> inline T betole(T value) {return swap_byte(value);}
template <typename T> inline T letobe(T value) {return swap_byte(value);}
//For conversions not involving the guest system, we can define the functions
//conditionally based on the BYTE_ORDER macro and outside of the namespaces
#if (defined(_BIG_ENDIAN) || !defined(_LITTLE_ENDIAN)) && BYTE_ORDER == BIG_ENDIAN
const ByteOrder HostByteOrder = BigEndianByteOrder;
template <typename T> inline T htole(T value) {return swap_byte(value);}
template <typename T> inline T letoh(T value) {return swap_byte(value);}
template <typename T> inline T htobe(T value) {return value;}
template <typename T> inline T betoh(T value) {return value;}
#elif defined(_LITTLE_ENDIAN) || BYTE_ORDER == LITTLE_ENDIAN
const ByteOrder HostByteOrder = LittleEndianByteOrder;
template <typename T> inline T htole(T value) {return value;}
template <typename T> inline T letoh(T value) {return value;}
template <typename T> inline T htobe(T value) {return swap_byte(value);}
template <typename T> inline T betoh(T value) {return swap_byte(value);}
#else
#error Invalid Endianess
#endif
namespace BigEndianGuest
{
const ByteOrder GuestByteOrder = BigEndianByteOrder;
template <typename T>
inline T gtole(T value) {return betole(value);}
template <typename T>
inline T letog(T value) {return letobe(value);}
template <typename T>
inline T gtobe(T value) {return value;}
template <typename T>
inline T betog(T value) {return value;}
template <typename T>
inline T htog(T value) {return htobe(value);}
template <typename T>
inline T gtoh(T value) {return betoh(value);}
}
namespace LittleEndianGuest
{
const ByteOrder GuestByteOrder = LittleEndianByteOrder;
template <typename T>
inline T gtole(T value) {return value;}
template <typename T>
inline T letog(T value) {return value;}
template <typename T>
inline T gtobe(T value) {return letobe(value);}
template <typename T>
inline T betog(T value) {return betole(value);}
template <typename T>
inline T htog(T value) {return htole(value);}
template <typename T>
inline T gtoh(T value) {return letoh(value);}
}
#endif // __SIM_BYTE_SWAP_HH__
| correct check for endianess | sim: correct check for endianess
Committed by: Nilay Vaish <[email protected]>
(transplanted from 20686329e67335885ee645655494e5ec952ff615)
| C++ | bsd-3-clause | andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin |
f0e4380fc70b125cedb28fe43e06fa4f4177ccf0 | tests/source/init.cpp | tests/source/init.cpp | #include <Matrix.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO("Matrix init", "[init]") {
GIVEN("The number of lines and columns") {
auto lines = 36;
auto columns = 39;
WHEN("Create instansce of Matrix") {
Matrix matrix(lines, columns);
THEN("The number of lines and columns must be preserved") {
REQUIRE(matrix.GetNumberOfLines() == lines);
REQUIRE(matrix.GetNumberOfColumns() == columns);
}
}
}
}
/*
SCENARIO("Matrix >>", "[fill]") {
std::ifstream input("A2x2.txt");
Matrix<int> A = Matrix<int>(2, 2);
REQUIRE( input >> A );
REQUIRE( A[0][0] == 1 );
REQUIRE( A[0][1] == 1 );
REQUIRE( A[1][0] == 2 );
REQUIRE( A[1][1] == 2 );
}
SCENARIO("Matrix +", "[addition]") {
Matrix<int> A = Matrix<int>(2, 2);
std::ifstream("A2x2.txt") >> A;
Matrix<int> B = Matrix<int>(2, 2);
std::ifstream("B2x2.txt") >> B;
Matrix<int> expected = Matrix<int>(2, 2);
std::ifstream("A+B2x2.txt") >> expected;
Matrix<int> result = A + B;
REQUIRE(result == expected);
}
SCENARIO("Matrix *", "[multiplication]") {
Matrix<int> A = Matrix<int>(2, 2);
std::ifstream("A2x2.txt") >> A;
Matrix<int> B = Matrix<int>(2, 2);
std::ifstream("B2x2.txt") >> B;
Matrix<int> expected = Matrix<int>(2, 2);
std::ifstream("A*B2x2.txt") >> expected;
Matrix<int> result = A * B;
REQUIRE(result == expected);
}
*/
| #include <Matrix.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO("Matrix init", "[init]") {
GIVEN("The number of lines and columns") {
auto lines = 36;
auto columns = 39;
WHEN("Create instansce of Matrix") {
Matrix matrix(lines, columns);
THEN("The number of lines and columns must be preserved") {
REQUIRE(matrix.GetNumberOfLines() == lines);
REQUIRE(matrix.GetNumberOfColumns() == columns);
}
}
}
}
SCENARIO("Matrix >>", "[fill]") {
Matrix A(2, 2);
A.InitFromFile("A2x2.txt");
REQUIRE( A[0][0] == 1 );
REQUIRE( A[0][1] == 1 );
REQUIRE( A[1][0] == 2 );
REQUIRE( A[1][1] == 2 );
}
/*
SCENARIO("Matrix +", "[addition]") {
Matrix<int> A = Matrix<int>(2, 2);
std::ifstream("A2x2.txt") >> A;
Matrix<int> B = Matrix<int>(2, 2);
std::ifstream("B2x2.txt") >> B;
Matrix<int> expected = Matrix<int>(2, 2);
std::ifstream("A+B2x2.txt") >> expected;
Matrix<int> result = A + B;
REQUIRE(result == expected);
}
SCENARIO("Matrix *", "[multiplication]") {
Matrix<int> A = Matrix<int>(2, 2);
std::ifstream("A2x2.txt") >> A;
Matrix<int> B = Matrix<int>(2, 2);
std::ifstream("B2x2.txt") >> B;
Matrix<int> expected = Matrix<int>(2, 2);
std::ifstream("A*B2x2.txt") >> expected;
Matrix<int> result = A * B;
REQUIRE(result == expected);
}
*/
| Update init.cpp | Update init.cpp | C++ | mit | ArtemKokorinStudent/External-sort,ArtemKokorinStudent/StackW |
ab6b3341df28dfda8a01370116be4b6335db8aa6 | src/odbc_result.cpp | src/odbc_result.cpp | /*
Copyright (c) 2013, Dan VerWeire<[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include <v8.h>
#include <node.h>
#include <node_version.h>
#include <time.h>
#include <uv.h>
#include "odbc.h"
#include "odbc_connection.h"
#include "odbc_result.h"
#include "odbc_statement.h"
using namespace v8;
using namespace node;
Persistent<FunctionTemplate> ODBCResult::constructor_template;
void ODBCResult::Init(v8::Handle<Object> target) {
DEBUG_PRINTF("ODBCResult::Init\n");
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
// Constructor Template
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->SetClassName(String::NewSymbol("ODBCResult"));
// Reserve space for one Handle<Value>
Local<ObjectTemplate> instance_template = constructor_template->InstanceTemplate();
instance_template->SetInternalFieldCount(1);
// Prototype Methods
NODE_SET_PROTOTYPE_METHOD(constructor_template, "fetchAll", FetchAll);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "fetch", Fetch);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "moreResultsSync", MoreResultsSync);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "closeSync", CloseSync);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "fetchAllSync", FetchAllSync);
// Attach the Database Constructor to the target object
target->Set( v8::String::NewSymbol("ODBCResult"),
constructor_template->GetFunction());
scope.Close(Undefined());
}
ODBCResult::~ODBCResult() {
this->Free();
}
void ODBCResult::Free() {
DEBUG_PRINTF("ODBCResult::Free m_hSTMT=%X\n", m_hSTMT);
if (m_hSTMT) {
uv_mutex_lock(&ODBC::g_odbcMutex);
//This doesn't actually deallocate the statement handle
//that should not be done by the result object; that should
//be done by the statement object
//SQLFreeStmt(m_hSTMT, SQL_CLOSE);
SQLFreeHandle( SQL_HANDLE_STMT, m_hSTMT);
m_hSTMT = NULL;
uv_mutex_unlock(&ODBC::g_odbcMutex);
if (bufferLength > 0) {
free(buffer);
}
}
}
Handle<Value> ODBCResult::New(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::New\n");
HandleScope scope;
REQ_EXT_ARG(0, js_henv);
REQ_EXT_ARG(1, js_hdbc);
REQ_EXT_ARG(2, js_hstmt);
HENV hENV = static_cast<HENV>(js_henv->Value());
HDBC hDBC = static_cast<HDBC>(js_hdbc->Value());
HSTMT hSTMT = static_cast<HSTMT>(js_hstmt->Value());
//create a new OBCResult object
ODBCResult* objODBCResult = new ODBCResult(hENV, hDBC, hSTMT);
DEBUG_PRINTF("ODBCResult::New m_hDBC=%X m_hDBC=%X m_hSTMT=%X\n",
objODBCResult->m_hENV,
objODBCResult->m_hDBC,
objODBCResult->m_hSTMT
);
//specify the buffer length
objODBCResult->bufferLength = MAX_VALUE_SIZE - 1;
//initialze a buffer for this object
objODBCResult->buffer = (uint16_t *) malloc(objODBCResult->bufferLength + 1);
//TODO: make sure the malloc succeeded
//set the initial colCount to 0
objODBCResult->colCount = 0;
objODBCResult->Wrap(args.Holder());
return scope.Close(args.Holder());
}
/*
* Fetch
*/
Handle<Value> ODBCResult::Fetch(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::Fetch\n");
HandleScope scope;
ODBCResult* objODBCResult = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
fetch_work_data* data = (fetch_work_data *) calloc(1, sizeof(fetch_work_data));
Local<Function> cb;
if (args.Length() == 0 || !args[0]->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("Argument 0 must be a callback function."))
);
}
cb = Local<Function>::Cast(args[0]);
data->cb = Persistent<Function>::New(cb);
data->objResult = objODBCResult;
work_req->data = data;
uv_queue_work(
uv_default_loop(),
work_req,
UV_Fetch,
(uv_after_work_cb)UV_AfterFetch);
objODBCResult->Ref();
return scope.Close(Undefined());
}
void ODBCResult::UV_Fetch(uv_work_t* work_req) {
DEBUG_PRINTF("ODBCResult::UV_Fetch\n");
fetch_work_data* data = (fetch_work_data *)(work_req->data);
data->result = SQLFetch(data->objResult->m_hSTMT);
}
void ODBCResult::UV_AfterFetch(uv_work_t* work_req, int status) {
DEBUG_PRINTF("ODBCResult::UV_AfterFetch\n");
HandleScope scope;
fetch_work_data* data = (fetch_work_data *)(work_req->data);
SQLRETURN ret = data->result;
//check to see if there was an error
if (ret == SQL_ERROR) {
ODBC::CallbackSQLError(
data->objResult->m_hENV,
data->objResult->m_hDBC,
data->objResult->m_hSTMT,
data->cb);
free(data);
free(work_req);
data->objResult->Unref();
return;
}
//check to see if we are at the end of the recordset
if (ret == SQL_NO_DATA) {
ODBC::FreeColumns(data->objResult->columns, &data->objResult->colCount);
Handle<Value> args[2];
args[0] = Null();
args[1] = Null();
data->cb->Call(Context::GetCurrent()->Global(), 2, args);
data->cb.Dispose();
free(data);
free(work_req);
data->objResult->Unref();
return;
}
if (data->objResult->colCount == 0) {
data->objResult->columns = ODBC::GetColumns(
data->objResult->m_hSTMT,
&data->objResult->colCount);
}
Handle<Value> args[2];
args[0] = Null();
args[1] = ODBC::GetRecordTuple(
data->objResult->m_hSTMT,
data->objResult->columns,
&data->objResult->colCount,
data->objResult->buffer,
data->objResult->bufferLength);
data->cb->Call(Context::GetCurrent()->Global(), 2, args);
data->cb.Dispose();
free(data);
free(work_req);
data->objResult->Unref();
return;
}
/*
* FetchAll
*/
Handle<Value> ODBCResult::FetchAll(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::FetchAll\n");
HandleScope scope;
ODBCResult* objODBCResult = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
fetch_work_data* data = (fetch_work_data *) calloc(1, sizeof(fetch_work_data));
Local<Function> cb;
if (args.Length() == 0 || !args[0]->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("Argument 0 must be a callback function."))
);
}
cb = Local<Function>::Cast(args[0]);
data->rows = Persistent<Array>::New(Array::New());
data->errorCount = 0;
data->count = 0;
data->objError = Persistent<Object>::New(Object::New());
data->cb = Persistent<Function>::New(cb);
data->objResult = objODBCResult;
work_req->data = data;
uv_queue_work(uv_default_loop(),
work_req,
UV_FetchAll,
(uv_after_work_cb)UV_AfterFetchAll);
data->objResult->Ref();
return scope.Close(Undefined());
}
void ODBCResult::UV_FetchAll(uv_work_t* work_req) {
DEBUG_PRINTF("ODBCResult::UV_FetchAll\n");
fetch_work_data* data = (fetch_work_data *)(work_req->data);
data->result = SQLFetch(data->objResult->m_hSTMT);
}
void ODBCResult::UV_AfterFetchAll(uv_work_t* work_req, int status) {
DEBUG_PRINTF("ODBCResult::UV_AfterFetchAll\n");
HandleScope scope;
fetch_work_data* data = (fetch_work_data *)(work_req->data);
ODBCResult* self = data->objResult->self();
bool doMoreWork = true;
if (self->colCount == 0) {
self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount);
}
//check to see if there was an error
if (data->result == SQL_ERROR) {
data->errorCount++;
data->objError = Persistent<Object>::New(ODBC::GetSQLError(
self->m_hENV,
self->m_hDBC,
self->m_hSTMT,
(char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll"
));
doMoreWork = false;
}
//check to see if we are at the end of the recordset
else if (data->result == SQL_NO_DATA) {
doMoreWork = false;
}
else {
data->rows->Set(
Integer::New(data->count),
ODBC::GetRecordTuple(
self->m_hSTMT,
self->columns,
&self->colCount,
self->buffer,
self->bufferLength)
);
data->count++;
}
if (doMoreWork) {
//Go back to the thread pool and fetch more data!
uv_queue_work(
uv_default_loop(),
work_req,
UV_FetchAll,
(uv_after_work_cb)UV_AfterFetchAll);
}
else {
ODBC::FreeColumns(self->columns, &self->colCount);
Handle<Value> args[2];
//TODO: we need to return the error object if there was an error
//however, on queries like "Drop...." the ret from SQLFetch is
//SQL_ERROR, but there is not valid error message. I guess it's because
//there is acually no result set...
//if (self->errorCount > 0) {
// args[0] = objError;
//}
//else {
args[0] = Null();
//}
args[1] = data->rows;
data->cb->Call(Context::GetCurrent()->Global(), 2, args);
data->cb.Dispose();
//TODO: Do we need to free self->rows somehow?
free(data);
free(work_req);
self->Unref();
}
scope.Close(Undefined());
}
/*
* FetchAllSync
*/
Handle<Value> ODBCResult::FetchAllSync(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::FetchAllSync\n");
HandleScope scope;
ODBCResult* self = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
Local<Object> objError = Object::New();
SQLRETURN ret;
int count = 0;
int errorCount = 0;
if (self->colCount == 0) {
self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount);
}
Local<Array> rows = Array::New();
//loop through all records
while (true) {
ret = SQLFetch(self->m_hSTMT);
//check to see if there was an error
if (ret == SQL_ERROR) {
errorCount++;
objError = ODBC::GetSQLError(
self->m_hENV,
self->m_hDBC,
self->m_hSTMT,
(char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll"
);
break;
}
//check to see if we are at the end of the recordset
if (ret == SQL_NO_DATA) {
ODBC::FreeColumns(self->columns, &self->colCount);
break;
}
rows->Set(
Integer::New(count),
ODBC::GetRecordTuple(
self->m_hSTMT,
self->columns,
&self->colCount,
self->buffer,
self->bufferLength)
);
count++;
}
//TODO: we need to return the error object if there was an error
//however, on queries like "Drop...." the ret from SQLFetch is
//SQL_ERROR, but there is not valid error message. I guess it's because
//there is acually no result set...
//
//we will need to throw if there is a valid error.
//if (errorCount > 0) {
// //THROW!
// args[0] = objError;
//}
return scope.Close(rows);
}
Handle<Value> ODBCResult::CloseSync(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::Close\n");
HandleScope scope;
ODBCResult* result = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
result->Free();
return scope.Close(Undefined());
}
Handle<Value> ODBCResult::MoreResultsSync(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::MoreResults\n");
HandleScope scope;
ODBCResult* result = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
//result->colCount = 0;
SQLRETURN ret = SQLMoreResults(result->m_hSTMT);
return scope.Close(SQL_SUCCEEDED(ret) ? True() : False());
}
| /*
Copyright (c) 2013, Dan VerWeire<[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include <v8.h>
#include <node.h>
#include <node_version.h>
#include <time.h>
#include <uv.h>
#include "odbc.h"
#include "odbc_connection.h"
#include "odbc_result.h"
#include "odbc_statement.h"
using namespace v8;
using namespace node;
Persistent<FunctionTemplate> ODBCResult::constructor_template;
void ODBCResult::Init(v8::Handle<Object> target) {
DEBUG_PRINTF("ODBCResult::Init\n");
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
// Constructor Template
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->SetClassName(String::NewSymbol("ODBCResult"));
// Reserve space for one Handle<Value>
Local<ObjectTemplate> instance_template = constructor_template->InstanceTemplate();
instance_template->SetInternalFieldCount(1);
// Prototype Methods
NODE_SET_PROTOTYPE_METHOD(constructor_template, "fetchAll", FetchAll);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "fetch", Fetch);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "moreResultsSync", MoreResultsSync);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "closeSync", CloseSync);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "fetchAllSync", FetchAllSync);
// Attach the Database Constructor to the target object
target->Set( v8::String::NewSymbol("ODBCResult"),
constructor_template->GetFunction());
scope.Close(Undefined());
}
ODBCResult::~ODBCResult() {
this->Free();
}
void ODBCResult::Free() {
DEBUG_PRINTF("ODBCResult::Free m_hSTMT=%X\n", m_hSTMT);
if (m_hSTMT) {
uv_mutex_lock(&ODBC::g_odbcMutex);
//This doesn't actually deallocate the statement handle
//that should not be done by the result object; that should
//be done by the statement object
//SQLFreeStmt(m_hSTMT, SQL_CLOSE);
SQLFreeHandle( SQL_HANDLE_STMT, m_hSTMT);
m_hSTMT = NULL;
uv_mutex_unlock(&ODBC::g_odbcMutex);
if (bufferLength > 0) {
free(buffer);
}
}
}
Handle<Value> ODBCResult::New(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::New\n");
HandleScope scope;
REQ_EXT_ARG(0, js_henv);
REQ_EXT_ARG(1, js_hdbc);
REQ_EXT_ARG(2, js_hstmt);
HENV hENV = static_cast<HENV>(js_henv->Value());
HDBC hDBC = static_cast<HDBC>(js_hdbc->Value());
HSTMT hSTMT = static_cast<HSTMT>(js_hstmt->Value());
//create a new OBCResult object
ODBCResult* objODBCResult = new ODBCResult(hENV, hDBC, hSTMT);
DEBUG_PRINTF("ODBCResult::New m_hDBC=%X m_hDBC=%X m_hSTMT=%X\n",
objODBCResult->m_hENV,
objODBCResult->m_hDBC,
objODBCResult->m_hSTMT
);
//specify the buffer length
objODBCResult->bufferLength = MAX_VALUE_SIZE - 1;
//initialze a buffer for this object
objODBCResult->buffer = (uint16_t *) malloc(objODBCResult->bufferLength + 1);
//TODO: make sure the malloc succeeded
//set the initial colCount to 0
objODBCResult->colCount = 0;
objODBCResult->Wrap(args.Holder());
return scope.Close(args.Holder());
}
/*
* Fetch
*/
Handle<Value> ODBCResult::Fetch(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::Fetch\n");
HandleScope scope;
ODBCResult* objODBCResult = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
fetch_work_data* data = (fetch_work_data *) calloc(1, sizeof(fetch_work_data));
Local<Function> cb;
if (args.Length() == 0 || !args[0]->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("Argument 0 must be a callback function."))
);
}
cb = Local<Function>::Cast(args[0]);
data->cb = Persistent<Function>::New(cb);
data->objResult = objODBCResult;
work_req->data = data;
uv_queue_work(
uv_default_loop(),
work_req,
UV_Fetch,
(uv_after_work_cb)UV_AfterFetch);
objODBCResult->Ref();
return scope.Close(Undefined());
}
void ODBCResult::UV_Fetch(uv_work_t* work_req) {
DEBUG_PRINTF("ODBCResult::UV_Fetch\n");
fetch_work_data* data = (fetch_work_data *)(work_req->data);
data->result = SQLFetch(data->objResult->m_hSTMT);
}
void ODBCResult::UV_AfterFetch(uv_work_t* work_req, int status) {
DEBUG_PRINTF("ODBCResult::UV_AfterFetch\n");
HandleScope scope;
fetch_work_data* data = (fetch_work_data *)(work_req->data);
SQLRETURN ret = data->result;
//check to see if there was an error
if (ret == SQL_ERROR) {
ODBC::CallbackSQLError(
data->objResult->m_hENV,
data->objResult->m_hDBC,
data->objResult->m_hSTMT,
data->cb);
free(data);
free(work_req);
data->objResult->Unref();
return;
}
//check to see if we are at the end of the recordset
if (ret == SQL_NO_DATA) {
ODBC::FreeColumns(data->objResult->columns, &data->objResult->colCount);
Handle<Value> args[2];
args[0] = Null();
args[1] = Null();
data->cb->Call(Context::GetCurrent()->Global(), 2, args);
data->cb.Dispose();
free(data);
free(work_req);
data->objResult->Unref();
return;
}
if (data->objResult->colCount == 0) {
data->objResult->columns = ODBC::GetColumns(
data->objResult->m_hSTMT,
&data->objResult->colCount);
}
Handle<Value> args[2];
args[0] = Null();
args[1] = ODBC::GetRecordTuple(
data->objResult->m_hSTMT,
data->objResult->columns,
&data->objResult->colCount,
data->objResult->buffer,
data->objResult->bufferLength);
data->cb->Call(Context::GetCurrent()->Global(), 2, args);
data->cb.Dispose();
free(data);
free(work_req);
data->objResult->Unref();
return;
}
/*
* FetchAll
*/
Handle<Value> ODBCResult::FetchAll(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::FetchAll\n");
HandleScope scope;
ODBCResult* objODBCResult = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
fetch_work_data* data = (fetch_work_data *) calloc(1, sizeof(fetch_work_data));
Local<Function> cb;
if (args.Length() == 0 || !args[0]->IsFunction()) {
return ThrowException(Exception::TypeError(
String::New("Argument 0 must be a callback function."))
);
}
cb = Local<Function>::Cast(args[0]);
data->rows = Persistent<Array>::New(Array::New());
data->errorCount = 0;
data->count = 0;
data->objError = Persistent<Object>::New(Object::New());
data->cb = Persistent<Function>::New(cb);
data->objResult = objODBCResult;
work_req->data = data;
uv_queue_work(uv_default_loop(),
work_req,
UV_FetchAll,
(uv_after_work_cb)UV_AfterFetchAll);
data->objResult->Ref();
return scope.Close(Undefined());
}
void ODBCResult::UV_FetchAll(uv_work_t* work_req) {
DEBUG_PRINTF("ODBCResult::UV_FetchAll\n");
fetch_work_data* data = (fetch_work_data *)(work_req->data);
data->result = SQLFetch(data->objResult->m_hSTMT);
}
void ODBCResult::UV_AfterFetchAll(uv_work_t* work_req, int status) {
DEBUG_PRINTF("ODBCResult::UV_AfterFetchAll\n");
HandleScope scope;
fetch_work_data* data = (fetch_work_data *)(work_req->data);
ODBCResult* self = data->objResult->self();
bool doMoreWork = true;
if (self->colCount == 0) {
self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount);
}
//check to see if there was an error
if (data->result == SQL_ERROR) {
data->errorCount++;
data->objError = Persistent<Object>::New(ODBC::GetSQLError(
self->m_hENV,
self->m_hDBC,
self->m_hSTMT,
(char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll"
));
doMoreWork = false;
}
//check to see if we are at the end of the recordset
else if (data->result == SQL_NO_DATA) {
doMoreWork = false;
}
else {
data->rows->Set(
Integer::New(data->count),
ODBC::GetRecordTuple(
self->m_hSTMT,
self->columns,
&self->colCount,
self->buffer,
self->bufferLength)
);
data->count++;
}
if (doMoreWork) {
//Go back to the thread pool and fetch more data!
uv_queue_work(
uv_default_loop(),
work_req,
UV_FetchAll,
(uv_after_work_cb)UV_AfterFetchAll);
}
else {
ODBC::FreeColumns(self->columns, &self->colCount);
Handle<Value> args[2];
//TODO: we need to return the error object if there was an error
//however, on queries like "Drop...." the ret from SQLFetch is
//SQL_ERROR, but there is not valid error message. I guess it's because
//there is acually no result set...
//if (self->errorCount > 0) {
// args[0] = objError;
//}
//else {
args[0] = Null();
//}
args[1] = data->rows;
data->cb->Call(Context::GetCurrent()->Global(), 2, args);
data->cb.Dispose();
//TODO: Do we need to free self->rows somehow?
free(data);
free(work_req);
self->Unref();
}
scope.Close(Undefined());
}
/*
* FetchAllSync
*/
Handle<Value> ODBCResult::FetchAllSync(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::FetchAllSync\n");
HandleScope scope;
ODBCResult* self = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
Local<Object> objError = Object::New();
SQLRETURN ret;
int count = 0;
int errorCount = 0;
if (self->colCount == 0) {
self->columns = ODBC::GetColumns(self->m_hSTMT, &self->colCount);
}
Local<Array> rows = Array::New();
//loop through all records
while (true) {
ret = SQLFetch(self->m_hSTMT);
//check to see if there was an error
if (ret == SQL_ERROR) {
errorCount++;
objError = ODBC::GetSQLError(
self->m_hENV,
self->m_hDBC,
self->m_hSTMT,
(char *) "[node-odbc] Error in ODBCResult::UV_AfterFetchAll"
);
break;
}
//check to see if we are at the end of the recordset
if (ret == SQL_NO_DATA) {
ODBC::FreeColumns(self->columns, &self->colCount);
break;
}
rows->Set(
Integer::New(count),
ODBC::GetRecordTuple(
self->m_hSTMT,
self->columns,
&self->colCount,
self->buffer,
self->bufferLength)
);
count++;
}
//TODO: we need to return the error object if there was an error
//however, on queries like "Drop...." the ret from SQLFetch is
//SQL_ERROR, but there is not valid error message. I guess it's because
//there is acually no result set...
//
//we will need to throw if there is a valid error.
if (errorCount > 0) {
ThrowException(Exception::Error(objError->Get(String::New("error"))->ToString()));
}
return scope.Close(rows);
}
Handle<Value> ODBCResult::CloseSync(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::Close\n");
HandleScope scope;
ODBCResult* result = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
result->Free();
return scope.Close(Undefined());
}
Handle<Value> ODBCResult::MoreResultsSync(const Arguments& args) {
DEBUG_PRINTF("ODBCResult::MoreResults\n");
HandleScope scope;
ODBCResult* result = ObjectWrap::Unwrap<ODBCResult>(args.Holder());
//result->colCount = 0;
SQLRETURN ret = SQLMoreResults(result->m_hSTMT);
return scope.Close(SQL_SUCCEEDED(ret) ? True() : False());
}
| throw exception | throw exception
| C++ | mit | elkorep/node-ibm_db,elkorep/node-ibm_db,qpresley/node-ibm_db,ibmdb/node-ibm_db,Papercloud/node-odbc,Akpotohwo/node-ibm_db,bustta/node-odbc,jbaxter0810/node-odbc,silveirado/node-ibm_db,silveirado/node-ibm_db,dfbaskin/node-odbc,dfbaskin/node-odbc,qpresley/node-ibm_db,elkorep/node-ibm_db,bzuillsmith/node-odbc,abiliooliveira/node-ibm_db,Papercloud/node-odbc,strongloop-forks/node-ibm_db,wankdanker/node-odbc,Akpotohwo/node-ibm_db,bzuillsmith/node-odbc,gmahomarf/node-odbc,qpresley/node-ibm_db,strongloop-forks/node-ibm_db,ibmdb/node-ibm_db,jbaxter0810/node-odbc,gmahomarf/node-odbc,abiliooliveira/node-ibm_db,qpresley/node-ibm_db,Papercloud/node-odbc,wankdanker/node-odbc,strongloop-forks/node-ibm_db,bustta/node-odbc,elkorep/node-ibm_db,ibmdb/node-ibm_db,bzuillsmith/node-odbc,ibmdb/node-ibm_db,dfbaskin/node-odbc,Papercloud/node-odbc,silveirado/node-ibm_db,jbaxter0810/node-odbc,bustta/node-odbc,wankdanker/node-odbc,strongloop-forks/node-ibm_db,bustta/node-odbc,Akpotohwo/node-ibm_db,Akpotohwo/node-ibm_db,qpresley/node-ibm_db,Akpotohwo/node-ibm_db,abiliooliveira/node-ibm_db,jbaxter0810/node-odbc,bzuillsmith/node-odbc,abiliooliveira/node-ibm_db,ibmdb/node-ibm_db,gmahomarf/node-odbc,wankdanker/node-odbc,silveirado/node-ibm_db,ibmdb/node-ibm_db,qpresley/node-ibm_db,dfbaskin/node-odbc,gmahomarf/node-odbc,Akpotohwo/node-ibm_db |
3350646e32ca7ff29ef48403e16e478bc8d8d089 | src/osm_profile.cpp | src/osm_profile.cpp | #include <routingkit/osm_profile.h>
namespace RoutingKit{
namespace{
bool str_eq(const char*l, const char*r){
return !strcmp(l, r);
}
bool str_wild_char_eq(const char*l, const char*r){
while(*l != '\0' && *r != '\0'){
if(*l != '?' && *r != '?' && *l != *r)
return false;
++l;
++r;
}
return *l == '\0' && *r == '\0';
}
bool starts_with(const char*prefix, const char*str){
while(*prefix != '\0' && *str == *prefix){
++prefix;
++str;
}
return *prefix == '\0';
}
void copy_str_and_make_lower_case(const char*in, char*out, unsigned out_size){
char*out_end = out + out_size-1;
while(*in && out != out_end){
if('A' <= *in && *in <= 'Z')
*out = *in - 'A' + 'a';
else
*out = *in;
++in;
++out;
}
*out = '\0';
}
// Splits the string at some separators such as ; and calls f(str) for each part.
// The ; is replaced by a '\0'. Leading spaces are removed
template<class F>
void split_str_at_osm_value_separators(char*in, const F&f){
while(*in == ' ')
++in;
const char*value_begin = in;
for(;;){
while(*in != '\0' && *in != ';')
++in;
if(*in == '\0'){
f(value_begin);
return;
}else{
*in = '\0';
f(value_begin);
++in;
while(*in == ' ')
++in;
value_begin = in;
}
}
}
}
bool is_osm_way_used_by_cars(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
const char* junction = tags["junction"];
if(junction != nullptr)
return true;
const char* highway = tags["highway"];
if(highway == nullptr)
return false;
const char*motorcar = tags["motorcar"];
if(motorcar && str_eq(motorcar, "no"))
return false;
const char*motorroad = tags["motorroad"];
if(motorroad && str_eq(motorroad, "no"))
return false;
const char*motor_vehicle = tags["motor_vehicle"];
if(motor_vehicle && str_eq(motor_vehicle, "no"))
return false;
const char*access = tags["access"];
if(access){
if(!(str_eq(access, "yes") || str_eq(access, "permissive") || str_eq(access, "delivery")|| str_eq(access, "designated") || str_eq(access, "destination")))
return false;
}
if(
str_eq(highway, "motorway") ||
str_eq(highway, "trunk") ||
str_eq(highway, "primary") ||
str_eq(highway, "secondary") ||
str_eq(highway, "tertiary") ||
str_eq(highway, "unclassified") ||
str_eq(highway, "residential") ||
str_eq(highway, "service") ||
str_eq(highway, "motorway_link") ||
str_eq(highway, "trunk_link") ||
str_eq(highway, "primary_link") ||
str_eq(highway, "secondary_link") ||
str_eq(highway, "tertiary_link") ||
str_eq(highway, "motorway_junction") ||
str_eq(highway, "living_street") ||
str_eq(highway, "residential") ||
str_eq(highway, "track") ||
str_eq(highway, "ferry")
)
return true;
if(str_eq(highway, "bicycle_road")){
auto motorcar = tags["motorcar"];
if(motorcar != nullptr)
if(str_eq(motorcar, "yes"))
return true;
return false;
}
const char* route = tags["route"];
if(str_eq(route, "ferry"))
return true;
if(
str_eq(highway, "construction") ||
str_eq(highway, "path") ||
str_eq(highway, "footway") ||
str_eq(highway, "cycleway") ||
str_eq(highway, "bridleway") ||
str_eq(highway, "pedestrian") ||
str_eq(highway, "bus_guideway") ||
str_eq(highway, "raceway") ||
str_eq(highway, "escape") ||
str_eq(highway, "steps") ||
str_eq(highway, "proposed") ||
str_eq(highway, "conveying")
)
return false;
const char* oneway = tags["oneway"];
if(oneway != nullptr){
if(str_eq(oneway, "reversible")) {
return false;
}
}
const char* maxspeed = tags["maxspeed"];
if(maxspeed != nullptr)
return true;
return false;
}
OSMWayDirectionCategory get_osm_car_direction_category(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
const char
*oneway = tags["oneway"],
*junction = tags["junction"],
*highway = tags["highway"]
;
if(oneway != nullptr){
if(str_eq(oneway, "-1") || str_eq(oneway, "reverse") || str_eq(oneway, "backward")) {
return OSMWayDirectionCategory::only_open_backwards;
} else if(str_eq(oneway, "yes") || str_eq(oneway, "true") || str_eq(oneway, "1")) {
return OSMWayDirectionCategory::only_open_forwards;
} else if(str_eq(oneway, "no") || str_eq(oneway, "false") || str_eq(oneway, "0")) {
return OSMWayDirectionCategory::open_in_both;
} else if(str_eq(oneway, "reversible")) {
return OSMWayDirectionCategory::closed;
} else {
log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has unknown oneway tag value \""+oneway+"\" for \"oneway\". Way is closed.");
}
} else if(junction != nullptr && str_eq(junction, "roundabout")) {
return OSMWayDirectionCategory::only_open_forwards;
} else if(highway != nullptr && (str_eq(highway, "motorway") || str_eq(highway, "motorway_link"))) {
return OSMWayDirectionCategory::only_open_forwards;
}
return OSMWayDirectionCategory::open_in_both;
}
namespace{
unsigned parse_maxspeed_value(uint64_t osm_way_id, const char*maxspeed, std::function<void(const std::string&)>log_message){
if(str_eq(maxspeed, "signals") || str_eq(maxspeed, "variable"))
return inf_weight;
if(str_eq(maxspeed, "none") || str_eq(maxspeed, "unlimited"))
return 130;
if(str_eq(maxspeed, "walk") || str_eq(maxspeed, "foot") || str_wild_char_eq(maxspeed, "??:walk"))
return 5;
if(str_wild_char_eq(maxspeed, "??:urban") || str_eq(maxspeed, "urban"))
return 40;
if(str_wild_char_eq(maxspeed, "??:living_street") || str_eq(maxspeed, "living_street"))
return 10;
if(str_eq(maxspeed, "de:rural") || str_eq(maxspeed, "at:rural") || str_eq(maxspeed, "ro:rural") || str_eq(maxspeed, "rural"))
return 100;
if(str_eq(maxspeed, "ru:rural") || str_eq(maxspeed, "fr:rural") || str_eq(maxspeed, "ua:rural"))
return 90;
if(str_eq(maxspeed, "ru:motorway"))
return 110;
if(str_eq(maxspeed, "at:motorway") || str_eq(maxspeed, "ro:motorway"))
return 130;
if(str_eq(maxspeed, "national"))
return 100;
if(str_eq(maxspeed, "ro:trunk"))
return 100;
if(str_eq(maxspeed, "dk:rural") || str_eq(maxspeed, "ch:rural"))
return 80;
if(str_eq(maxspeed, "it:rural") || str_eq(maxspeed, "hu:rural"))
return 90;
if(str_eq(maxspeed, "de:zone:30"))
return 30;
if('0' <= *maxspeed && *maxspeed <= '9'){
unsigned speed = 0;
while('0' <= *maxspeed && *maxspeed <= '9'){
speed *= 10;
speed += *maxspeed - '0';
++maxspeed;
}
while(*maxspeed == ' ')
++maxspeed;
if(*maxspeed == '\0' || str_eq(maxspeed, "km/h") || str_eq(maxspeed, "kmh") || str_eq(maxspeed, "kph")){
return speed;
}else if(str_eq(maxspeed, "mph")){
return speed * 1609 / 1000;
}else if(str_eq(maxspeed, "knots")){
return speed * 1852 / 1000;
}else{
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unknown unit \""+maxspeed+"\" for its \"maxspeed\" tag -> assuming \"km/h\".");
return speed;
}
}else{
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized value of \""+maxspeed+"\" for its \"maxspeed\" tag.");
}
return inf_weight;
}
}
unsigned get_osm_way_speed(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
auto maxspeed = tags["maxspeed"];
if(maxspeed != nullptr){
char lower_case_maxspeed[1024];
copy_str_and_make_lower_case(maxspeed, lower_case_maxspeed, sizeof(lower_case_maxspeed)-1);
unsigned speed = inf_weight;
split_str_at_osm_value_separators(
lower_case_maxspeed,
[&](const char*maxspeed){
min_to(speed, parse_maxspeed_value(osm_way_id, maxspeed, log_message));
}
);
if(speed == 0){
speed = 1;
log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has speed 0 km/h, setting it to 1 km/h");
}
if(speed != inf_weight)
return speed;
}
auto junction = tags["junction"];
if(junction){
return 20;
}
auto highway = tags["highway"];
if(highway){
if(str_eq(highway, "motorway"))
return 90;
if(str_eq(highway, "motorway_link"))
return 45;
if(str_eq(highway, "trunk"))
return 85;
if(str_eq(highway, "trunk_link"))
return 40;
if(str_eq(highway, "primary"))
return 65;
if(str_eq(highway, "primary_link"))
return 30;
if(str_eq(highway, "secondary"))
return 55;
if(str_eq(highway, "secondary_link"))
return 25;
if(str_eq(highway, "tertiary"))
return 40;
if(str_eq(highway, "tertiary_link"))
return 20;
if(str_eq(highway, "unclassified"))
return 25;
if(str_eq(highway, "residential"))
return 25;
if(str_eq(highway, "living_street"))
return 10;
if(str_eq(highway, "service"))
return 1;
if(str_eq(highway, "track"))
return 1;
if(str_eq(highway, "ferry"))
return 5;
}
if(maxspeed && highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
if(!maxspeed && highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
if(!maxspeed && !highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and no \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
if(maxspeed && !highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and no \"highway\" tag and an no junction tag -> assuming 50km/h.");
return 50;
}
std::string get_osm_way_name(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
auto
name = tags["name"],
ref = tags["ref"];
if(name != nullptr && ref != nullptr)
return std::string(name) + ";"+ref;
else if(name != nullptr)
return std::string(name);
else if(ref != nullptr)
return std::string(ref);
else
return std::string();
}
} // RoutingKit
| #include <routingkit/osm_profile.h>
namespace RoutingKit{
namespace{
bool str_eq(const char*l, const char*r){
return !strcmp(l, r);
}
bool str_wild_char_eq(const char*l, const char*r){
while(*l != '\0' && *r != '\0'){
if(*l != '?' && *r != '?' && *l != *r)
return false;
++l;
++r;
}
return *l == '\0' && *r == '\0';
}
bool starts_with(const char*prefix, const char*str){
while(*prefix != '\0' && *str == *prefix){
++prefix;
++str;
}
return *prefix == '\0';
}
void copy_str_and_make_lower_case(const char*in, char*out, unsigned out_size){
char*out_end = out + out_size-1;
while(*in && out != out_end){
if('A' <= *in && *in <= 'Z')
*out = *in - 'A' + 'a';
else
*out = *in;
++in;
++out;
}
*out = '\0';
}
// Splits the string at some separators such as ; and calls f(str) for each part.
// The ; is replaced by a '\0'. Leading spaces are removed
template<class F>
void split_str_at_osm_value_separators(char*in, const F&f){
while(*in == ' ')
++in;
const char*value_begin = in;
for(;;){
while(*in != '\0' && *in != ';')
++in;
if(*in == '\0'){
f(value_begin);
return;
}else{
*in = '\0';
f(value_begin);
++in;
while(*in == ' ')
++in;
value_begin = in;
}
}
}
}
bool is_osm_way_used_by_cars(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
const char* junction = tags["junction"];
if(junction != nullptr)
return true;
const char* highway = tags["highway"];
if(highway == nullptr)
return false;
const char*motorcar = tags["motorcar"];
if(motorcar && str_eq(motorcar, "no"))
return false;
const char*motorroad = tags["motorroad"];
if(motorroad && str_eq(motorroad, "no"))
return false;
const char*motor_vehicle = tags["motor_vehicle"];
if(motor_vehicle && str_eq(motor_vehicle, "no"))
return false;
const char*access = tags["access"];
if(access){
if(!(str_eq(access, "yes") || str_eq(access, "permissive") || str_eq(access, "delivery")|| str_eq(access, "designated") || str_eq(access, "destination")))
return false;
}
if(
str_eq(highway, "motorway") ||
str_eq(highway, "trunk") ||
str_eq(highway, "primary") ||
str_eq(highway, "secondary") ||
str_eq(highway, "tertiary") ||
str_eq(highway, "unclassified") ||
str_eq(highway, "residential") ||
str_eq(highway, "service") ||
str_eq(highway, "motorway_link") ||
str_eq(highway, "trunk_link") ||
str_eq(highway, "primary_link") ||
str_eq(highway, "secondary_link") ||
str_eq(highway, "tertiary_link") ||
str_eq(highway, "motorway_junction") ||
str_eq(highway, "living_street") ||
str_eq(highway, "residential") ||
str_eq(highway, "track") ||
str_eq(highway, "ferry")
)
return true;
if(str_eq(highway, "bicycle_road")){
auto motorcar = tags["motorcar"];
if(motorcar != nullptr)
if(str_eq(motorcar, "yes"))
return true;
return false;
}
const char* route = tags["route"];
if(route && str_eq(route, "ferry"))
return true;
if(
str_eq(highway, "construction") ||
str_eq(highway, "path") ||
str_eq(highway, "footway") ||
str_eq(highway, "cycleway") ||
str_eq(highway, "bridleway") ||
str_eq(highway, "pedestrian") ||
str_eq(highway, "bus_guideway") ||
str_eq(highway, "raceway") ||
str_eq(highway, "escape") ||
str_eq(highway, "steps") ||
str_eq(highway, "proposed") ||
str_eq(highway, "conveying")
)
return false;
const char* oneway = tags["oneway"];
if(oneway != nullptr){
if(str_eq(oneway, "reversible")) {
return false;
}
}
const char* maxspeed = tags["maxspeed"];
if(maxspeed != nullptr)
return true;
return false;
}
OSMWayDirectionCategory get_osm_car_direction_category(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
const char
*oneway = tags["oneway"],
*junction = tags["junction"],
*highway = tags["highway"]
;
if(oneway != nullptr){
if(str_eq(oneway, "-1") || str_eq(oneway, "reverse") || str_eq(oneway, "backward")) {
return OSMWayDirectionCategory::only_open_backwards;
} else if(str_eq(oneway, "yes") || str_eq(oneway, "true") || str_eq(oneway, "1")) {
return OSMWayDirectionCategory::only_open_forwards;
} else if(str_eq(oneway, "no") || str_eq(oneway, "false") || str_eq(oneway, "0")) {
return OSMWayDirectionCategory::open_in_both;
} else if(str_eq(oneway, "reversible")) {
return OSMWayDirectionCategory::closed;
} else {
log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has unknown oneway tag value \""+oneway+"\" for \"oneway\". Way is closed.");
}
} else if(junction != nullptr && str_eq(junction, "roundabout")) {
return OSMWayDirectionCategory::only_open_forwards;
} else if(highway != nullptr && (str_eq(highway, "motorway") || str_eq(highway, "motorway_link"))) {
return OSMWayDirectionCategory::only_open_forwards;
}
return OSMWayDirectionCategory::open_in_both;
}
namespace{
unsigned parse_maxspeed_value(uint64_t osm_way_id, const char*maxspeed, std::function<void(const std::string&)>log_message){
if(str_eq(maxspeed, "signals") || str_eq(maxspeed, "variable"))
return inf_weight;
if(str_eq(maxspeed, "none") || str_eq(maxspeed, "unlimited"))
return 130;
if(str_eq(maxspeed, "walk") || str_eq(maxspeed, "foot") || str_wild_char_eq(maxspeed, "??:walk"))
return 5;
if(str_wild_char_eq(maxspeed, "??:urban") || str_eq(maxspeed, "urban"))
return 40;
if(str_wild_char_eq(maxspeed, "??:living_street") || str_eq(maxspeed, "living_street"))
return 10;
if(str_eq(maxspeed, "de:rural") || str_eq(maxspeed, "at:rural") || str_eq(maxspeed, "ro:rural") || str_eq(maxspeed, "rural"))
return 100;
if(str_eq(maxspeed, "ru:rural") || str_eq(maxspeed, "fr:rural") || str_eq(maxspeed, "ua:rural"))
return 90;
if(str_eq(maxspeed, "ru:motorway"))
return 110;
if(str_eq(maxspeed, "at:motorway") || str_eq(maxspeed, "ro:motorway"))
return 130;
if(str_eq(maxspeed, "national"))
return 100;
if(str_eq(maxspeed, "ro:trunk"))
return 100;
if(str_eq(maxspeed, "dk:rural") || str_eq(maxspeed, "ch:rural"))
return 80;
if(str_eq(maxspeed, "it:rural") || str_eq(maxspeed, "hu:rural"))
return 90;
if(str_eq(maxspeed, "de:zone:30"))
return 30;
if('0' <= *maxspeed && *maxspeed <= '9'){
unsigned speed = 0;
while('0' <= *maxspeed && *maxspeed <= '9'){
speed *= 10;
speed += *maxspeed - '0';
++maxspeed;
}
while(*maxspeed == ' ')
++maxspeed;
if(*maxspeed == '\0' || str_eq(maxspeed, "km/h") || str_eq(maxspeed, "kmh") || str_eq(maxspeed, "kph")){
return speed;
}else if(str_eq(maxspeed, "mph")){
return speed * 1609 / 1000;
}else if(str_eq(maxspeed, "knots")){
return speed * 1852 / 1000;
}else{
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unknown unit \""+maxspeed+"\" for its \"maxspeed\" tag -> assuming \"km/h\".");
return speed;
}
}else{
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized value of \""+maxspeed+"\" for its \"maxspeed\" tag.");
}
return inf_weight;
}
}
unsigned get_osm_way_speed(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
auto maxspeed = tags["maxspeed"];
if(maxspeed != nullptr){
char lower_case_maxspeed[1024];
copy_str_and_make_lower_case(maxspeed, lower_case_maxspeed, sizeof(lower_case_maxspeed)-1);
unsigned speed = inf_weight;
split_str_at_osm_value_separators(
lower_case_maxspeed,
[&](const char*maxspeed){
min_to(speed, parse_maxspeed_value(osm_way_id, maxspeed, log_message));
}
);
if(speed == 0){
speed = 1;
log_message("Warning: OSM way "+std::to_string(osm_way_id)+" has speed 0 km/h, setting it to 1 km/h");
}
if(speed != inf_weight)
return speed;
}
auto junction = tags["junction"];
if(junction){
return 20;
}
auto highway = tags["highway"];
if(highway){
if(str_eq(highway, "motorway"))
return 90;
if(str_eq(highway, "motorway_link"))
return 45;
if(str_eq(highway, "trunk"))
return 85;
if(str_eq(highway, "trunk_link"))
return 40;
if(str_eq(highway, "primary"))
return 65;
if(str_eq(highway, "primary_link"))
return 30;
if(str_eq(highway, "secondary"))
return 55;
if(str_eq(highway, "secondary_link"))
return 25;
if(str_eq(highway, "tertiary"))
return 40;
if(str_eq(highway, "tertiary_link"))
return 20;
if(str_eq(highway, "unclassified"))
return 25;
if(str_eq(highway, "residential"))
return 25;
if(str_eq(highway, "living_street"))
return 10;
if(str_eq(highway, "service"))
return 1;
if(str_eq(highway, "track"))
return 1;
if(str_eq(highway, "ferry"))
return 5;
}
if(maxspeed && highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
if(!maxspeed && highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and an unrecognized \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
if(!maxspeed && !highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has no \"maxspeed\" and no \"highway\" tag of \""+highway+"\" and an no junction tag -> assuming 50km/h.");
if(maxspeed && !highway)
log_message("Warning: OSM way "+std::to_string(osm_way_id) +" has an unrecognized \"maxspeed\" tag of \""+maxspeed+"\" and no \"highway\" tag and an no junction tag -> assuming 50km/h.");
return 50;
}
std::string get_osm_way_name(uint64_t osm_way_id, const TagMap&tags, std::function<void(const std::string&)>log_message){
auto
name = tags["name"],
ref = tags["ref"];
if(name != nullptr && ref != nullptr)
return std::string(name) + ";"+ref;
else if(name != nullptr)
return std::string(name);
else if(ref != nullptr)
return std::string(ref);
else
return std::string();
}
} // RoutingKit
| Check if route is not null | Check if route is not null
| C++ | bsd-2-clause | RoutingKit/RoutingKit,RoutingKit/RoutingKit,RoutingKit/RoutingKit |
150b62372ec38c0d47f08941dfedd1048070689f | src/precompiled.ipp | src/precompiled.ipp | // This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_PRECOMPILED_
#define POSEIDON_PRECOMPILED_
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <rocket/cow_string.hpp>
#include <rocket/cow_vector.hpp>
#include <rocket/cow_hashmap.hpp>
#include <rocket/static_vector.hpp>
#include <rocket/prehashed_string.hpp>
#include <rocket/unique_handle.hpp>
#include <rocket/unique_posix_file.hpp>
#include <rocket/unique_posix_dir.hpp>
#include <rocket/unique_posix_fd.hpp>
#include <rocket/unique_ptr.hpp>
#include <rocket/refcnt_ptr.hpp>
#include <rocket/variant.hpp>
#include <rocket/optional.hpp>
#include <rocket/array.hpp>
#include <rocket/reference_wrapper.hpp>
#include <rocket/tinyfmt.hpp>
#include <rocket/tinyfmt_str.hpp>
#include <rocket/tinyfmt_file.hpp>
#include <rocket/ascii_numget.hpp>
#include <rocket/ascii_numput.hpp>
#include <rocket/format.hpp>
#include <rocket/atomic.hpp>
#include <rocket/ascii_case.hpp>
#include <rocket/mutex.hpp>
#include <rocket/recursive_mutex.hpp>
#include <rocket/condition_variable.hpp>
#include <rocket/once_flag.hpp>
#include <iterator>
#include <utility>
#include <exception>
#include <typeinfo>
#include <type_traits>
#include <functional>
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <deque>
#include <bitset>
#include <cstdio>
#include <climits>
#include <cmath>
#include <cfenv>
#include <cfloat>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <unistd.h>
#include <endian.h>
#endif
| // This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.
#ifndef POSEIDON_PRECOMPILED_
#define POSEIDON_PRECOMPILED_
#include "version.h"
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <rocket/cow_string.hpp>
#include <rocket/cow_vector.hpp>
#include <rocket/cow_hashmap.hpp>
#include <rocket/static_vector.hpp>
#include <rocket/prehashed_string.hpp>
#include <rocket/unique_handle.hpp>
#include <rocket/unique_posix_file.hpp>
#include <rocket/unique_posix_dir.hpp>
#include <rocket/unique_posix_fd.hpp>
#include <rocket/unique_ptr.hpp>
#include <rocket/refcnt_ptr.hpp>
#include <rocket/variant.hpp>
#include <rocket/optional.hpp>
#include <rocket/array.hpp>
#include <rocket/reference_wrapper.hpp>
#include <rocket/tinyfmt.hpp>
#include <rocket/tinyfmt_str.hpp>
#include <rocket/tinyfmt_file.hpp>
#include <rocket/ascii_numget.hpp>
#include <rocket/ascii_numput.hpp>
#include <rocket/format.hpp>
#include <rocket/atomic.hpp>
#include <rocket/ascii_case.hpp>
#include <rocket/mutex.hpp>
#include <rocket/recursive_mutex.hpp>
#include <rocket/condition_variable.hpp>
#include <rocket/once_flag.hpp>
#include <iterator>
#include <utility>
#include <exception>
#include <typeinfo>
#include <type_traits>
#include <functional>
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <deque>
#include <bitset>
#include <cstdio>
#include <climits>
#include <cmath>
#include <cfenv>
#include <cfloat>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <unistd.h>
#include <endian.h>
#endif
| Include "version.h" | precompiled: Include "version.h"
| C++ | bsd-3-clause | lhmouse/poseidon,lhmouse/poseidon,lhmouse/poseidon |
d26ff66ce264b860ba877065ec9487839d9ed5cc | src/rollinghash.cpp | src/rollinghash.cpp | #include "rollinghash.h"
#include "builtinmutation.h"
#include "util.h"
// we use 1G memory
const int BLOOM_FILTER_LENGTH = (1<<29);
RollingHash::RollingHash(int window, bool allowTwoSub) {
mWindow = min(48, window);
mAllowTwoSub = allowTwoSub;
mBloomFilterArray = new char[BLOOM_FILTER_LENGTH];
memset(mBloomFilterArray, 0, BLOOM_FILTER_LENGTH * sizeof(char));
}
RollingHash::~RollingHash() {
delete mBloomFilterArray;
mBloomFilterArray = NULL;
}
void RollingHash::initMutations(vector<Mutation>& mutationList) {
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s1 = m.mLeft + m.mCenter + m.mRight;
add(s1, i);
const int margin = 4;
// handle the case mRight is incomplete, but at least margin
int left = max((size_t)mWindow+2, m.mLeft.length() + m.mCenter.length() + margin+1);
string s2 = s1.substr(left - (mWindow+2), mWindow+2);
add(s2,i);
//handle the case mleft is incomplete, but at least margin
int right = min(s1.length() - (mWindow+2), m.mLeft.length()-margin-1);
string s3 = s1.substr(right, mWindow+2);
add(s3,i);
}
}
map<long, vector<int> > RollingHash::getKeyTargets() {
return mKeyTargets;
}
bool RollingHash::add(string s, int target) {
if(s.length() < mWindow + 2)
return false;
int center = s.length() / 2;
int start = center - mWindow / 2;
// mutations cannot happen in skipStart to skipEnd
int skipStart = center - 1;
int skipEnd = center + 1;
const char* data = s.c_str();
long* hashes = new long[mWindow];
memset(hashes, 0, sizeof(long)*mWindow);
long* accum = new long[mWindow];
memset(accum, 0, sizeof(long)*mWindow);
// initialize
long origin = 0;
for(int i=0; i<mWindow; i++) {
hashes[i] = hash(data[start + i], i);
origin += hashes[i];
accum[i] = origin;
}
addHash(origin, target);
const char bases[4] = {'A', 'T', 'C', 'G'};
// make subsitution hashes, we allow up to 2 sub mutations
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
for(int b1=0; b1<4; b1++){
char base1 = bases[b1];
if(base1 == data[start + i])
continue;
long mut1 = origin - hash(data[start + i], i) + hash(base1, i);
addHash(mut1, target);
/*cout<<mut1<<":"<<i<<base1<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else
cout<<data[start + p];
}
cout<<endl;*/
if(mAllowTwoSub) {
for(int j=i+1; j<mWindow; j++) {
if(j+start >= skipStart && j+start <= skipEnd )
continue;
for(int b2=0; b2<4; b2++){
char base2 = bases[b2];
if(base2 == data[start + j])
continue;
long mut2 = mut1 - hash(data[start + j], j) + hash(base2, j);
addHash(mut2, target);
/*cout<<mut2<<":"<<i<<base1<<j<<base2<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else if(p==j)
cout<<base2;
else
cout<<data[start + p];
}
cout<<endl;*/
}
}
}
}
}
int altForDel = start - 1;
long altVal = hash(data[altForDel], 0);
// make indel hashes, we only allow 1 indel
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
// make del of i first
long mutOfDel;
if (i==0)
mutOfDel = origin - accum[i] + altVal;
else
mutOfDel = origin - accum[i] + (accum[i-1]<<1) + altVal;
if(mutOfDel != origin)
addHash(mutOfDel, target);
// make insertion
for(int b=0; b<4; b++){
char base = bases[b];
// shift the first base
long mutOfIns = origin - accum[i] + hash(base, i) + ((accum[i] - hashes[0]) >> 1);
if(mutOfIns != origin && mutOfIns != mutOfDel){
addHash(mutOfIns, target);
/*cout << mutOfIns<<", insert at " << i << " with " << base << ": ";
for(int p=1;p<=i;p++)
cout << data[start + p];
cout << base;
for(int p=i+1;p<mWindow;p++)
cout << data[start + p];
cout << endl;*/
}
}
}
delete hashes;
delete accum;
}
vector<int> RollingHash::hitTargets(const string s) {
vector<int> ret;
if(s.length() < mWindow)
return ret;
const char* data = s.c_str();
// initialize
long curHash = 0;
for(int i=0; i<mWindow; i++) {
long h = hash(data[i], i);
curHash += h;
}
addHit(ret, curHash);
for(int i=mWindow; i<s.length(); i++) {
curHash = ((curHash - hash(data[i - mWindow], 0))>>1) + hash(data[i], mWindow-1);
addHit(ret, curHash);
}
return ret;
}
inline void RollingHash::addHit(vector<int>& ret, long hash) {
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
if(mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1)] == 0 )
return;
}
if(mKeyTargets.count(hash)) {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
int val = mKeyTargets[hash][i];
bool alreadyIn = false;
for(int j=0; j<ret.size(); j++) {
if(val == ret[j]){
alreadyIn = true;
break;
}
}
if(!alreadyIn) {
ret.push_back(val);
}
}
}
}
void RollingHash::addHash(long hash, int target) {
if(mKeyTargets.count(hash) == 0)
mKeyTargets[hash] = vector<int>();
else {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
if(mKeyTargets[hash][i] == target)
return ;
}
}
mKeyTargets[hash].push_back(target);
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1) ] = 1;
}
}
inline long RollingHash::char2val(char c) {
switch (c) {
case 'A':
return 517;
case 'T':
return 433;
case 'C':
return 1123;
case 'G':
return 127;
case 'N':
return 1;
default:
return 0;
}
}
inline long RollingHash::hash(char c, int pos) {
long val = char2val(c);
const long num = 2;
return val * (num << pos );
}
void RollingHash::dump() {
map<long, vector<int> >::iterator iter;
for(iter= mKeyTargets.begin(); iter!=mKeyTargets.end(); iter++) {
if(iter->second.size() < 2)
continue;
cout << iter->first << endl;
for(int i=0; i<iter->second.size(); i++)
cout << iter->second[i] << "\t";
cout << endl;
}
}
bool RollingHash::test(){
vector<Mutation> mutationList = Mutation::parseBuiltIn();
RollingHash rh(48);
rh.initMutations(mutationList);
bool result = true;
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s = m.mLeft + m.mCenter + m.mRight;
vector<int> targets = rh.hitTargets(s);
cout << i << ", " << s << endl;
bool found = false;
for(int t=0; t<targets.size(); t++){
cout << targets[t] << "\t";
if(targets[t] == i)
found = true;
}
cout << endl;
result &= found;
}
return result;
} | #include "rollinghash.h"
#include "builtinmutation.h"
#include "util.h"
#include <memory.h>
// we use 1G memory
const int BLOOM_FILTER_LENGTH = (1<<29);
RollingHash::RollingHash(int window, bool allowTwoSub) {
mWindow = min(48, window);
mAllowTwoSub = allowTwoSub;
mBloomFilterArray = new char[BLOOM_FILTER_LENGTH];
memset(mBloomFilterArray, 0, BLOOM_FILTER_LENGTH * sizeof(char));
}
RollingHash::~RollingHash() {
delete mBloomFilterArray;
mBloomFilterArray = NULL;
}
void RollingHash::initMutations(vector<Mutation>& mutationList) {
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s1 = m.mLeft + m.mCenter + m.mRight;
add(s1, i);
const int margin = 4;
// handle the case mRight is incomplete, but at least margin
int left = max((size_t)mWindow+2, m.mLeft.length() + m.mCenter.length() + margin+1);
string s2 = s1.substr(left - (mWindow+2), mWindow+2);
add(s2,i);
//handle the case mleft is incomplete, but at least margin
int right = min(s1.length() - (mWindow+2), m.mLeft.length()-margin-1);
string s3 = s1.substr(right, mWindow+2);
add(s3,i);
}
}
map<long, vector<int> > RollingHash::getKeyTargets() {
return mKeyTargets;
}
bool RollingHash::add(string s, int target) {
if(s.length() < mWindow + 2)
return false;
int center = s.length() / 2;
int start = center - mWindow / 2;
// mutations cannot happen in skipStart to skipEnd
int skipStart = center - 1;
int skipEnd = center + 1;
const char* data = s.c_str();
long* hashes = new long[mWindow];
memset(hashes, 0, sizeof(long)*mWindow);
long* accum = new long[mWindow];
memset(accum, 0, sizeof(long)*mWindow);
// initialize
long origin = 0;
for(int i=0; i<mWindow; i++) {
hashes[i] = hash(data[start + i], i);
origin += hashes[i];
accum[i] = origin;
}
addHash(origin, target);
const char bases[4] = {'A', 'T', 'C', 'G'};
// make subsitution hashes, we allow up to 2 sub mutations
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
for(int b1=0; b1<4; b1++){
char base1 = bases[b1];
if(base1 == data[start + i])
continue;
long mut1 = origin - hash(data[start + i], i) + hash(base1, i);
addHash(mut1, target);
/*cout<<mut1<<":"<<i<<base1<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else
cout<<data[start + p];
}
cout<<endl;*/
if(mAllowTwoSub) {
for(int j=i+1; j<mWindow; j++) {
if(j+start >= skipStart && j+start <= skipEnd )
continue;
for(int b2=0; b2<4; b2++){
char base2 = bases[b2];
if(base2 == data[start + j])
continue;
long mut2 = mut1 - hash(data[start + j], j) + hash(base2, j);
addHash(mut2, target);
/*cout<<mut2<<":"<<i<<base1<<j<<base2<<":";
for(int p=0; p<mWindow; p++) {
if(p==i)
cout<<base1;
else if(p==j)
cout<<base2;
else
cout<<data[start + p];
}
cout<<endl;*/
}
}
}
}
}
int altForDel = start - 1;
long altVal = hash(data[altForDel], 0);
// make indel hashes, we only allow 1 indel
for(int i=0; i<mWindow; i++) {
if(i+start >= skipStart && i+start <= skipEnd )
continue;
// make del of i first
long mutOfDel;
if (i==0)
mutOfDel = origin - accum[i] + altVal;
else
mutOfDel = origin - accum[i] + (accum[i-1]<<1) + altVal;
if(mutOfDel != origin)
addHash(mutOfDel, target);
// make insertion
for(int b=0; b<4; b++){
char base = bases[b];
// shift the first base
long mutOfIns = origin - accum[i] + hash(base, i) + ((accum[i] - hashes[0]) >> 1);
if(mutOfIns != origin && mutOfIns != mutOfDel){
addHash(mutOfIns, target);
/*cout << mutOfIns<<", insert at " << i << " with " << base << ": ";
for(int p=1;p<=i;p++)
cout << data[start + p];
cout << base;
for(int p=i+1;p<mWindow;p++)
cout << data[start + p];
cout << endl;*/
}
}
}
delete hashes;
delete accum;
}
vector<int> RollingHash::hitTargets(const string s) {
vector<int> ret;
if(s.length() < mWindow)
return ret;
const char* data = s.c_str();
// initialize
long curHash = 0;
for(int i=0; i<mWindow; i++) {
long h = hash(data[i], i);
curHash += h;
}
addHit(ret, curHash);
for(int i=mWindow; i<s.length(); i++) {
curHash = ((curHash - hash(data[i - mWindow], 0))>>1) + hash(data[i], mWindow-1);
addHit(ret, curHash);
}
return ret;
}
inline void RollingHash::addHit(vector<int>& ret, long hash) {
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
if(mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1)] == 0 )
return;
}
if(mKeyTargets.count(hash)) {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
int val = mKeyTargets[hash][i];
bool alreadyIn = false;
for(int j=0; j<ret.size(); j++) {
if(val == ret[j]){
alreadyIn = true;
break;
}
}
if(!alreadyIn) {
ret.push_back(val);
}
}
}
}
void RollingHash::addHash(long hash, int target) {
if(mKeyTargets.count(hash) == 0)
mKeyTargets[hash] = vector<int>();
else {
for(int i=0; i<mKeyTargets[hash].size(); i++) {
if(mKeyTargets[hash][i] == target)
return ;
}
}
mKeyTargets[hash].push_back(target);
//update bloom filter array
const long bloomFilterFactors[3] = {1713137323, 371371377, 7341234131};
for(int b=0; b<3; b++) {
mBloomFilterArray[(bloomFilterFactors[b] * hash) & (BLOOM_FILTER_LENGTH-1) ] = 1;
}
}
inline long RollingHash::char2val(char c) {
switch (c) {
case 'A':
return 517;
case 'T':
return 433;
case 'C':
return 1123;
case 'G':
return 127;
case 'N':
return 1;
default:
return 0;
}
}
inline long RollingHash::hash(char c, int pos) {
long val = char2val(c);
const long num = 2;
return val * (num << pos );
}
void RollingHash::dump() {
map<long, vector<int> >::iterator iter;
for(iter= mKeyTargets.begin(); iter!=mKeyTargets.end(); iter++) {
if(iter->second.size() < 2)
continue;
cout << iter->first << endl;
for(int i=0; i<iter->second.size(); i++)
cout << iter->second[i] << "\t";
cout << endl;
}
}
bool RollingHash::test(){
vector<Mutation> mutationList = Mutation::parseBuiltIn();
RollingHash rh(48);
rh.initMutations(mutationList);
bool result = true;
for(int i=0; i<mutationList.size(); i++) {
Mutation m = mutationList[i];
string s = m.mLeft + m.mCenter + m.mRight;
vector<int> targets = rh.hitTargets(s);
cout << i << ", " << s << endl;
bool found = false;
for(int t=0; t<targets.size(); t++){
cout << targets[t] << "\t";
if(targets[t] == i)
found = true;
}
cout << endl;
result &= found;
}
return result;
}
| add memory.h include for fix linux compile error | add memory.h include for fix linux compile error
| C++ | mit | OpenGene/MutScan,OpenGene/MutScan |
191f3b3d24cbbfeec7b2c4cee27528795e11e418 | src/server_node.cpp | src/server_node.cpp | /**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/server_node.hpp>
#include <future>
#include <iostream>
#include <czmq++/czmqpp.hpp>
#include <boost/filesystem.hpp>
#include <bitcoin/node.hpp>
#include <bitcoin/server/configuration.hpp>
namespace libbitcoin {
namespace server {
using namespace bc::blockchain;
using namespace bc::chain;
using namespace bc::node;
using namespace bc::wallet;
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
using std::placeholders::_4;
server_node::server_node(const configuration& configuration)
: p2p_node(configuration),
configuration_(configuration),
last_checkpoint_height_(configuration.last_checkpoint_height())
{
#ifdef _MSC_VER
// Hack to prevent czmq from writing to stdout/stderr on Windows.
// It is necessary to prevent stdio when using our utf8-everywhere pattern.
// TODO: provide a FILE* here that we can direct to our own log/console.
zsys_set_logstream(NULL);
#endif
}
// Properties.
// ----------------------------------------------------------------------------
const settings& server_node::server_settings() const
{
return configuration_.server;
}
// Start sequence.
// ----------------------------------------------------------------------------
void server_node::start(result_handler handler)
{
// Start the network and blockchain before subscribing.
p2p_node::start(
std::bind(&server_node::handle_node_start,
shared_from_base<server_node>(), _1, handler));
}
void server_node::handle_node_start(const code& ec, result_handler handler)
{
// Subscribe to blockchain reorganizations.
subscribe_blockchain(
std::bind(&server_node::handle_new_blocks,
shared_from_base<server_node>(), _1, _2, _3, _4));
// Subscribe to transaction pool acceptances.
subscribe_transaction_pool(
std::bind(&server_node::handle_tx_accepted,
shared_from_base<server_node>(), _1, _2, _3));
// This is the end of the derived start sequence.
handler(error::success);
}
// This serves both address subscription and the block publisher.
void server_node::subscribe_blocks(block_notify_callback notify_block)
{
block_sunscriptions_.push_back(notify_block);
}
// This serves both address subscription and the tx publisher.
void server_node::subscribe_transactions(transaction_notify_callback notify_tx)
{
tx_subscriptions_.push_back(notify_tx);
}
bool server_node::handle_tx_accepted(const code& ec,
const index_list& unconfirmed, const transaction& tx)
{
if (ec == bc::error::service_stopped)
return false;
if (ec)
{
log::error(LOG_SERVICE)
<< "Failure handling new tx: " << ec.message();
return false;
}
// Fire server protocol tx subscription notifications.
for (const auto notify: tx_subscriptions_)
notify(tx);
return true;
}
bool server_node::handle_new_blocks(const code& ec, uint64_t fork_point,
const block::ptr_list& new_blocks, const block::ptr_list& replaced_blocks)
{
if (ec == bc::error::service_stopped)
return false;
if (fork_point < last_checkpoint_height_)
return false;
if (ec)
{
log::error(LOG_SERVICE)
<< "Failure handling new blocks: " << ec.message();
return false;
}
BITCOIN_ASSERT(fork_point < max_uint32 - new_blocks.size());
auto height = static_cast<uint32_t>(fork_point);
// Fire server protocol block subscription notifications.
for (auto new_block: new_blocks)
for (const auto notify: block_sunscriptions_)
notify(++height, new_block);
return true;
}
} // namespace server
} // namespace libbitcoin
| /**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-server.
*
* libbitcoin-server is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/server/server_node.hpp>
#include <future>
#include <iostream>
#include <czmq++/czmqpp.hpp>
#include <boost/filesystem.hpp>
#include <bitcoin/node.hpp>
#include <bitcoin/server/configuration.hpp>
namespace libbitcoin {
namespace server {
using namespace bc::blockchain;
using namespace bc::chain;
using namespace bc::node;
using namespace bc::wallet;
using std::placeholders::_1;
using std::placeholders::_2;
using std::placeholders::_3;
using std::placeholders::_4;
server_node::server_node(const configuration& configuration)
: p2p_node(configuration),
configuration_(configuration),
last_checkpoint_height_(configuration.last_checkpoint_height())
{
// Disable czmq signal handling.
zsys_handler_set(NULL);
#ifdef _MSC_VER
// Hack to prevent czmq from writing to stdout/stderr on Windows.
// It is necessary to prevent stdio when using our utf8-everywhere pattern.
// TODO: provide a FILE* here that we can direct to our own log/console.
zsys_set_logstream(NULL);
#endif
}
// Properties.
// ----------------------------------------------------------------------------
const settings& server_node::server_settings() const
{
return configuration_.server;
}
// Start sequence.
// ----------------------------------------------------------------------------
void server_node::start(result_handler handler)
{
// The handler is invoked sequentially.
// Start the network and blockchain before subscribing.
p2p_node::start(
std::bind(&server_node::handle_node_start,
shared_from_base<server_node>(), _1, handler));
}
void server_node::handle_node_start(const code& ec, result_handler handler)
{
// Subscribe to blockchain reorganizations.
subscribe_blockchain(
std::bind(&server_node::handle_new_blocks,
shared_from_base<server_node>(), _1, _2, _3, _4));
// Subscribe to transaction pool acceptances.
subscribe_transaction_pool(
std::bind(&server_node::handle_tx_accepted,
shared_from_base<server_node>(), _1, _2, _3));
// This is the end of the derived start sequence.
handler(error::success);
}
// This serves both address subscription and the block publisher.
void server_node::subscribe_blocks(block_notify_callback notify_block)
{
block_sunscriptions_.push_back(notify_block);
}
// This serves both address subscription and the tx publisher.
void server_node::subscribe_transactions(transaction_notify_callback notify_tx)
{
tx_subscriptions_.push_back(notify_tx);
}
bool server_node::handle_tx_accepted(const code& ec,
const index_list& unconfirmed, const transaction& tx)
{
if (ec == bc::error::service_stopped)
return false;
if (ec)
{
log::error(LOG_SERVICE)
<< "Failure handling new tx: " << ec.message();
return false;
}
// Fire server protocol tx subscription notifications.
for (const auto notify: tx_subscriptions_)
notify(tx);
return true;
}
bool server_node::handle_new_blocks(const code& ec, uint64_t fork_point,
const block::ptr_list& new_blocks, const block::ptr_list& replaced_blocks)
{
if (ec == bc::error::service_stopped)
return false;
if (fork_point < last_checkpoint_height_)
return false;
if (ec)
{
log::error(LOG_SERVICE)
<< "Failure handling new blocks: " << ec.message();
return false;
}
BITCOIN_ASSERT(fork_point < max_uint32 - new_blocks.size());
auto height = static_cast<uint32_t>(fork_point);
// Fire server protocol block subscription notifications.
for (auto new_block: new_blocks)
for (const auto notify: block_sunscriptions_)
notify(++height, new_block);
return true;
}
} // namespace server
} // namespace libbitcoin
| Disable czmq signal handling so that ours works. | Disable czmq signal handling so that ours works.
| C++ | agpl-3.0 | RojavaCrypto/libbitcoin-server,RojavaCrypto/libbitcoin-server,RojavaCrypto/libbitcoin-server |
6bafa77d257de35f5d6e71dd9e7b7449af46f15a | src/server_proc.cpp | src/server_proc.cpp | #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include "rpc.h"
#include "sck_stream.h"
#include "message_protocol.h"
using namespace std;
ServerProcess* ServerProcess::singleton = NULL;
class ServerProcess {
private:
int sockServer, sockBinder;
char* BINDER_ADDRESS;
char* BINDER_PORT;
static ServerProcess* singleton;
protected:
ServerProcess();
public:
//singleton accessor
static ServerProcess* getInstance() {
if (singleton == 0) {
singleton = new ServerProcess();
}
return singleton;
}
int getServerSockFd() {
return sockServer;
}
int startServer();
int connectToBinder();
int terminate(); // terminate server after verifying msf from binder
};
int ServerProcess::startServer() {
sockServer = setup_server("0", 0); // server is calling so no need to print the addr/port
return sockServer;
}
int ServerProcess::connectToBinder() {
BINDER_ADDRESS = getenv("BINDER_ADDRESS");
BINDER_PORT = getenv("BINDER_PORT");
int s = call_sock(BINDER_ADDRESS, BINDER_PORT);
//send info about myself and all the methods that I have
}
int rpcInit() {
// bind to the server
ServerProcess::getInstance()->startServer(); // start server in background thread
}
int main() {
//ServerProcess* server = ServerProcess::getInstance();
//ServerProcess* server = new ServerProcess();
ServerProcess::getInstance()->startServer();
int c = wait_for_conn(ServerProcess::getInstance()->getServerSockFd());
return 0;
}
| #include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include "rpc.h"
#include "sck_stream.h"
#include "message_protocol.h"
using namespace std;
ServerProcess* ServerProcess::singleton = NULL;
class ServerProcess {
private:
int sockServerFd, sockBinderFd;
char* BINDER_ADDRESS;
char* BINDER_PORT;
static ServerProcess* singleton;
protected:
ServerProcess() {
// connect to the binder
BINDER_ADDRESS = getenv("BINDER_ADDRESS");
BINDER_PORT = getenv("BINDER_PORT");
sockBinderFd = call_sock(BINDER_ADDRESS, BINDER_PORT);
}
public:
//singleton accessor
static ServerProcess* getInstance() {
if (singleton == 0) {
singleton = new ServerProcess();
}
return singleton;
}
int getServerSockFd() {
return sockServerFd;
}
int getBinderSockFd() {
return sockBinderFd;
}
int startServer();
int terminate(); // TODO terminate server after verifying msg from binder
};
// TODO start server in background thread ??
int ServerProcess::startServer() {
sockServer = setup_server("0", 0);
return sockServer;
}
int rpcInit() {
ServerProcess::getInstance()->startServer();
// TODO find out who our hostname and port number to store in our internal db and send to binder
}
int rpcRegister(char* name, int* argTypes, skeleton f);
int rpcExecute() {
//TODO - some kind of infinite accept loop;
//TODO - receive and process requests from client;
//TODO - multithreaded?
int c = wait_for_conn(ServerProcess::getInstance()->getServerSockFd());
}
int main() {
ServerProcess::getInstance()->startServer();
int c = wait_for_conn(ServerProcess::getInstance()->getServerSockFd());
return 0;
}
| Refactor server proc a little | Refactor server proc a little
| C++ | mit | cyprusad/RemoteProcedureCall,cyprusad/RemoteProcedureCall |
c5ad03fa3921bbf8dea9795825f546d7b3d06c12 | src/ssdb/binlog.cpp | src/ssdb/binlog.cpp | /*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include "binlog.h"
#include "const.h"
#include "../include.h"
#include "../util/log.h"
#include "../util/strings.h"
#include <map>
/* Binlog */
Binlog::Binlog(uint64_t seq, char type, char cmd, const leveldb::Slice &key){
buf.append((char *)(&seq), sizeof(uint64_t));
buf.push_back(type);
buf.push_back(cmd);
buf.append(key.data(), key.size());
}
uint64_t Binlog::seq() const{
return *((uint64_t *)(buf.data()));
}
char Binlog::type() const{
return buf[sizeof(uint64_t)];
}
char Binlog::cmd() const{
return buf[sizeof(uint64_t) + 1];
}
const Bytes Binlog::key() const{
return Bytes(buf.data() + HEADER_LEN, buf.size() - HEADER_LEN);
}
int Binlog::load(const Bytes &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
int Binlog::load(const leveldb::Slice &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
int Binlog::load(const std::string &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
std::string Binlog::dumps() const{
std::string str;
if(buf.size() < HEADER_LEN){
return str;
}
char buf[20];
snprintf(buf, sizeof(buf), "%" PRIu64 " ", this->seq());
str.append(buf);
switch(this->type()){
case BinlogType::NOOP:
str.append("noop ");
break;
case BinlogType::SYNC:
str.append("sync ");
break;
case BinlogType::MIRROR:
str.append("mirror ");
break;
case BinlogType::COPY:
str.append("copy ");
break;
}
switch(this->cmd()){
case BinlogCommand::NONE:
str.append("none ");
break;
case BinlogCommand::KSET:
str.append("set ");
break;
case BinlogCommand::KDEL:
str.append("del ");
break;
case BinlogCommand::HSET:
str.append("hset ");
break;
case BinlogCommand::HDEL:
str.append("hdel ");
break;
case BinlogCommand::ZSET:
str.append("zset ");
break;
case BinlogCommand::ZDEL:
str.append("zdel ");
break;
case BinlogCommand::BEGIN:
str.append("begin ");
break;
case BinlogCommand::END:
str.append("end ");
break;
case BinlogCommand::QPUSH_BACK:
str.append("qpush_back ");
break;
case BinlogCommand::QPUSH_FRONT:
str.append("qpush_front ");
break;
case BinlogCommand::QPOP_BACK:
str.append("qpop_back ");
break;
case BinlogCommand::QPOP_FRONT:
str.append("qpop_front ");
case BinlogCommand::QSET:
str.append("qset ");
break;
}
Bytes b = this->key();
str.append(hexmem(b.data(), b.size()));
return str;
}
/* SyncLogQueue */
static inline std::string encode_seq_key(uint64_t seq){
seq = big_endian(seq);
std::string ret;
ret.push_back(DataType::SYNCLOG);
ret.append((char *)&seq, sizeof(seq));
return ret;
}
static inline uint64_t decode_seq_key(const leveldb::Slice &key){
uint64_t seq = 0;
if(key.size() == (sizeof(uint64_t) + 1) && key.data()[0] == DataType::SYNCLOG){
seq = *((uint64_t *)(key.data() + 1));
seq = big_endian(seq);
}
return seq;
}
BinlogQueue::BinlogQueue(leveldb::DB *db, bool enabled, int capacity){
this->db = db;
this->min_seq = 0;
this->last_seq = 0;
this->tran_seq = 0;
this->capacity = capacity;
this->enabled = enabled;
Binlog log;
if(this->find_last(&log) == 1){
this->last_seq = log.seq();
}
// 下面这段代码是可能性能非常差!
//if(this->find_next(0, &log) == 1){
// this->min_seq = log.seq();
//}
if(this->last_seq > this->capacity){
this->min_seq = this->last_seq - this->capacity;
}else{
this->min_seq = 0;
}
if(this->find_next(this->min_seq, &log) == 1){
this->min_seq = log.seq();
}
if(this->enabled){
log_info("binlogs capacity: %d, min: %" PRIu64 ", max: %" PRIu64 ",",
this->capacity, this->min_seq, this->last_seq);
// 这个方法有性能问题
// 但是, 如果不执行清理, 如果将 capacity 修改大, 可能会导致主从同步问题
//this->clean_obsolete_binlogs();
}
// start cleaning thread
if(this->enabled){
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &BinlogQueue::log_clean_thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
}
BinlogQueue::~BinlogQueue(){
if(this->enabled){
thread_quit = true;
for(int i=0; i<100; i++){
if(thread_quit == false){
break;
}
usleep(10 * 1000);
}
}
db = NULL;
}
std::string BinlogQueue::stats() const{
std::string s;
s.append(" capacity : " + str(capacity) + "\n");
s.append(" min_seq : " + str(min_seq) + "\n");
s.append(" max_seq : " + str(last_seq) + "");
return s;
}
void BinlogQueue::begin(){
tran_seq = last_seq;
batch.Clear();
}
void BinlogQueue::rollback(){
tran_seq = 0;
}
leveldb::Status BinlogQueue::commit(){
leveldb::WriteOptions write_opts;
leveldb::Status s = db->Write(write_opts, &batch);
if(s.ok()){
last_seq = tran_seq;
tran_seq = 0;
}
return s;
}
void BinlogQueue::add_log(char type, char cmd, const leveldb::Slice &key){
if(!enabled){
return;
}
tran_seq ++;
Binlog log(tran_seq, type, cmd, key);
batch.Put(encode_seq_key(tran_seq), log.repr());
}
void BinlogQueue::add_log(char type, char cmd, const std::string &key){
if(!enabled){
return;
}
leveldb::Slice s(key);
this->add_log(type, cmd, s);
}
// leveldb put
void BinlogQueue::Put(const leveldb::Slice& key, const leveldb::Slice& value){
batch.Put(key, value);
}
// leveldb delete
void BinlogQueue::Delete(const leveldb::Slice& key){
batch.Delete(key);
}
int BinlogQueue::find_next(uint64_t next_seq, Binlog *log) const{
if(this->get(next_seq, log) == 1){
return 1;
}
uint64_t ret = 0;
std::string key_str = encode_seq_key(next_seq);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::find_last(Binlog *log) const{
uint64_t ret = 0;
std::string key_str = encode_seq_key(UINT64_MAX);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(!it->Valid()){
// Iterator::prev requires Valid, so we seek to last
it->SeekToLast();
}else{
// UINT64_MAX is not used
it->Prev();
}
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::get(uint64_t seq, Binlog *log) const{
std::string val;
leveldb::Status s = db->Get(leveldb::ReadOptions(), encode_seq_key(seq), &val);
if(s.ok()){
if(log->load(val) != -1){
return 1;
}
}
return 0;
}
int BinlogQueue::update(uint64_t seq, char type, char cmd, const std::string &key){
Binlog log(seq, type, cmd, key);
leveldb::Status s = db->Put(leveldb::WriteOptions(), encode_seq_key(seq), log.repr());
if(s.ok()){
return 0;
}
return -1;
}
int BinlogQueue::del(uint64_t seq){
leveldb::Status s = db->Delete(leveldb::WriteOptions(), encode_seq_key(seq));
if(!s.ok()){
return -1;
}
return 0;
}
void BinlogQueue::flush(){
del_range(this->min_seq, this->last_seq);
}
int BinlogQueue::del_range(uint64_t start, uint64_t end){
while(start <= end){
leveldb::WriteBatch batch;
for(int count = 0; start <= end && count < 1000; start++, count++){
batch.Delete(encode_seq_key(start));
}
leveldb::Status s = db->Write(leveldb::WriteOptions(), &batch);
if(!s.ok()){
return -1;
}
}
return 0;
}
void* BinlogQueue::log_clean_thread_func(void *arg){
BinlogQueue *logs = (BinlogQueue *)arg;
while(!logs->thread_quit){
if(!logs->db){
break;
}
assert(logs->last_seq >= logs->min_seq);
if(logs->last_seq - logs->min_seq < logs->capacity + 10000){
usleep(50 * 1000);
continue;
}
uint64_t start = logs->min_seq;
uint64_t end = logs->last_seq - logs->capacity;
logs->del_range(start, end);
logs->min_seq = end + 1;
log_info("clean %d logs[%" PRIu64 " ~ %" PRIu64 "], %d left, max: %" PRIu64 "",
end-start+1, start, end, logs->last_seq - logs->min_seq + 1, logs->last_seq);
}
log_debug("binlog clean_thread quit");
logs->thread_quit = false;
return (void *)NULL;
}
// 因为老版本可能产生了断续的binlog
// 例如, binlog-1 存在, 但后面的被删除了, 然后到 binlog-100000 时又开始存在.
void BinlogQueue::clean_obsolete_binlogs(){
std::string key_str = encode_seq_key(this->min_seq);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(it->Valid()){
it->Prev();
}
uint64_t count = 0;
while(it->Valid()){
leveldb::Slice key = it->key();
uint64_t seq = decode_seq_key(key);
if(seq == 0){
break;
}
this->del(seq);
it->Prev();
count ++;
}
delete it;
if(count > 0){
log_info("clean_obsolete_binlogs: %" PRIu64, count);
}
}
// TESTING, slow, so not used
void BinlogQueue::merge(){
std::map<std::string, uint64_t> key_map;
uint64_t start = min_seq;
uint64_t end = last_seq;
int reduce_count = 0;
int total = 0;
total = end - start + 1;
(void)total; // suppresses warning
log_trace("merge begin");
for(; start <= end; start++){
Binlog log;
if(this->get(start, &log) == 1){
if(log.type() == BinlogType::NOOP){
continue;
}
std::string key = log.key().String();
std::map<std::string, uint64_t>::iterator it = key_map.find(key);
if(it != key_map.end()){
uint64_t seq = it->second;
this->update(seq, BinlogType::NOOP, BinlogCommand::NONE, "");
//log_trace("merge update %" PRIu64 " to NOOP", seq);
reduce_count ++;
}
key_map[key] = log.seq();
}
}
log_trace("merge reduce %d of %d binlogs", reduce_count, total);
}
| /*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include "binlog.h"
#include "const.h"
#include "../include.h"
#include "../util/log.h"
#include "../util/strings.h"
#include <map>
/* Binlog */
Binlog::Binlog(uint64_t seq, char type, char cmd, const leveldb::Slice &key){
buf.append((char *)(&seq), sizeof(uint64_t));
buf.push_back(type);
buf.push_back(cmd);
buf.append(key.data(), key.size());
}
uint64_t Binlog::seq() const{
return *((uint64_t *)(buf.data()));
}
char Binlog::type() const{
return buf[sizeof(uint64_t)];
}
char Binlog::cmd() const{
return buf[sizeof(uint64_t) + 1];
}
const Bytes Binlog::key() const{
return Bytes(buf.data() + HEADER_LEN, buf.size() - HEADER_LEN);
}
int Binlog::load(const Bytes &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
int Binlog::load(const leveldb::Slice &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
int Binlog::load(const std::string &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
std::string Binlog::dumps() const{
std::string str;
if(buf.size() < HEADER_LEN){
return str;
}
char buf[20];
snprintf(buf, sizeof(buf), "%" PRIu64 " ", this->seq());
str.append(buf);
switch(this->type()){
case BinlogType::NOOP:
str.append("noop ");
break;
case BinlogType::SYNC:
str.append("sync ");
break;
case BinlogType::MIRROR:
str.append("mirror ");
break;
case BinlogType::COPY:
str.append("copy ");
break;
}
switch(this->cmd()){
case BinlogCommand::NONE:
str.append("none ");
break;
case BinlogCommand::KSET:
str.append("set ");
break;
case BinlogCommand::KDEL:
str.append("del ");
break;
case BinlogCommand::HSET:
str.append("hset ");
break;
case BinlogCommand::HDEL:
str.append("hdel ");
break;
case BinlogCommand::ZSET:
str.append("zset ");
break;
case BinlogCommand::ZDEL:
str.append("zdel ");
break;
case BinlogCommand::BEGIN:
str.append("begin ");
break;
case BinlogCommand::END:
str.append("end ");
break;
case BinlogCommand::QPUSH_BACK:
str.append("qpush_back ");
break;
case BinlogCommand::QPUSH_FRONT:
str.append("qpush_front ");
break;
case BinlogCommand::QPOP_BACK:
str.append("qpop_back ");
break;
case BinlogCommand::QPOP_FRONT:
str.append("qpop_front ");
break;
case BinlogCommand::QSET:
str.append("qset ");
break;
}
Bytes b = this->key();
str.append(hexmem(b.data(), b.size()));
return str;
}
/* SyncLogQueue */
static inline std::string encode_seq_key(uint64_t seq){
seq = big_endian(seq);
std::string ret;
ret.push_back(DataType::SYNCLOG);
ret.append((char *)&seq, sizeof(seq));
return ret;
}
static inline uint64_t decode_seq_key(const leveldb::Slice &key){
uint64_t seq = 0;
if(key.size() == (sizeof(uint64_t) + 1) && key.data()[0] == DataType::SYNCLOG){
seq = *((uint64_t *)(key.data() + 1));
seq = big_endian(seq);
}
return seq;
}
BinlogQueue::BinlogQueue(leveldb::DB *db, bool enabled, int capacity){
this->db = db;
this->min_seq = 0;
this->last_seq = 0;
this->tran_seq = 0;
this->capacity = capacity;
this->enabled = enabled;
Binlog log;
if(this->find_last(&log) == 1){
this->last_seq = log.seq();
}
// 下面这段代码是可能性能非常差!
//if(this->find_next(0, &log) == 1){
// this->min_seq = log.seq();
//}
if(this->last_seq > this->capacity){
this->min_seq = this->last_seq - this->capacity;
}else{
this->min_seq = 0;
}
if(this->find_next(this->min_seq, &log) == 1){
this->min_seq = log.seq();
}
if(this->enabled){
log_info("binlogs capacity: %d, min: %" PRIu64 ", max: %" PRIu64 ",",
this->capacity, this->min_seq, this->last_seq);
// 这个方法有性能问题
// 但是, 如果不执行清理, 如果将 capacity 修改大, 可能会导致主从同步问题
//this->clean_obsolete_binlogs();
}
// start cleaning thread
if(this->enabled){
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &BinlogQueue::log_clean_thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
}
BinlogQueue::~BinlogQueue(){
if(this->enabled){
thread_quit = true;
for(int i=0; i<100; i++){
if(thread_quit == false){
break;
}
usleep(10 * 1000);
}
}
db = NULL;
}
std::string BinlogQueue::stats() const{
std::string s;
s.append(" capacity : " + str(capacity) + "\n");
s.append(" min_seq : " + str(min_seq) + "\n");
s.append(" max_seq : " + str(last_seq) + "");
return s;
}
void BinlogQueue::begin(){
tran_seq = last_seq;
batch.Clear();
}
void BinlogQueue::rollback(){
tran_seq = 0;
}
leveldb::Status BinlogQueue::commit(){
leveldb::WriteOptions write_opts;
leveldb::Status s = db->Write(write_opts, &batch);
if(s.ok()){
last_seq = tran_seq;
tran_seq = 0;
}
return s;
}
void BinlogQueue::add_log(char type, char cmd, const leveldb::Slice &key){
if(!enabled){
return;
}
tran_seq ++;
Binlog log(tran_seq, type, cmd, key);
batch.Put(encode_seq_key(tran_seq), log.repr());
}
void BinlogQueue::add_log(char type, char cmd, const std::string &key){
if(!enabled){
return;
}
leveldb::Slice s(key);
this->add_log(type, cmd, s);
}
// leveldb put
void BinlogQueue::Put(const leveldb::Slice& key, const leveldb::Slice& value){
batch.Put(key, value);
}
// leveldb delete
void BinlogQueue::Delete(const leveldb::Slice& key){
batch.Delete(key);
}
int BinlogQueue::find_next(uint64_t next_seq, Binlog *log) const{
if(this->get(next_seq, log) == 1){
return 1;
}
uint64_t ret = 0;
std::string key_str = encode_seq_key(next_seq);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::find_last(Binlog *log) const{
uint64_t ret = 0;
std::string key_str = encode_seq_key(UINT64_MAX);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(!it->Valid()){
// Iterator::prev requires Valid, so we seek to last
it->SeekToLast();
}else{
// UINT64_MAX is not used
it->Prev();
}
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::get(uint64_t seq, Binlog *log) const{
std::string val;
leveldb::Status s = db->Get(leveldb::ReadOptions(), encode_seq_key(seq), &val);
if(s.ok()){
if(log->load(val) != -1){
return 1;
}
}
return 0;
}
int BinlogQueue::update(uint64_t seq, char type, char cmd, const std::string &key){
Binlog log(seq, type, cmd, key);
leveldb::Status s = db->Put(leveldb::WriteOptions(), encode_seq_key(seq), log.repr());
if(s.ok()){
return 0;
}
return -1;
}
int BinlogQueue::del(uint64_t seq){
leveldb::Status s = db->Delete(leveldb::WriteOptions(), encode_seq_key(seq));
if(!s.ok()){
return -1;
}
return 0;
}
void BinlogQueue::flush(){
del_range(this->min_seq, this->last_seq);
}
int BinlogQueue::del_range(uint64_t start, uint64_t end){
while(start <= end){
leveldb::WriteBatch batch;
for(int count = 0; start <= end && count < 1000; start++, count++){
batch.Delete(encode_seq_key(start));
}
leveldb::Status s = db->Write(leveldb::WriteOptions(), &batch);
if(!s.ok()){
return -1;
}
}
return 0;
}
void* BinlogQueue::log_clean_thread_func(void *arg){
BinlogQueue *logs = (BinlogQueue *)arg;
while(!logs->thread_quit){
if(!logs->db){
break;
}
assert(logs->last_seq >= logs->min_seq);
if(logs->last_seq - logs->min_seq < logs->capacity + 10000){
usleep(50 * 1000);
continue;
}
uint64_t start = logs->min_seq;
uint64_t end = logs->last_seq - logs->capacity;
logs->del_range(start, end);
logs->min_seq = end + 1;
log_info("clean %d logs[%" PRIu64 " ~ %" PRIu64 "], %d left, max: %" PRIu64 "",
end-start+1, start, end, logs->last_seq - logs->min_seq + 1, logs->last_seq);
}
log_debug("binlog clean_thread quit");
logs->thread_quit = false;
return (void *)NULL;
}
// 因为老版本可能产生了断续的binlog
// 例如, binlog-1 存在, 但后面的被删除了, 然后到 binlog-100000 时又开始存在.
void BinlogQueue::clean_obsolete_binlogs(){
std::string key_str = encode_seq_key(this->min_seq);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(it->Valid()){
it->Prev();
}
uint64_t count = 0;
while(it->Valid()){
leveldb::Slice key = it->key();
uint64_t seq = decode_seq_key(key);
if(seq == 0){
break;
}
this->del(seq);
it->Prev();
count ++;
}
delete it;
if(count > 0){
log_info("clean_obsolete_binlogs: %" PRIu64, count);
}
}
// TESTING, slow, so not used
void BinlogQueue::merge(){
std::map<std::string, uint64_t> key_map;
uint64_t start = min_seq;
uint64_t end = last_seq;
int reduce_count = 0;
int total = 0;
total = end - start + 1;
(void)total; // suppresses warning
log_trace("merge begin");
for(; start <= end; start++){
Binlog log;
if(this->get(start, &log) == 1){
if(log.type() == BinlogType::NOOP){
continue;
}
std::string key = log.key().String();
std::map<std::string, uint64_t>::iterator it = key_map.find(key);
if(it != key_map.end()){
uint64_t seq = it->second;
this->update(seq, BinlogType::NOOP, BinlogCommand::NONE, "");
//log_trace("merge update %" PRIu64 " to NOOP", seq);
reduce_count ++;
}
key_map[key] = log.seq();
}
}
log_trace("merge reduce %d of %d binlogs", reduce_count, total);
}
| fix binlog dumps bug | fix binlog dumps bug
| C++ | bsd-3-clause | ideawu/ssdb,zkidkid/ssdb,cuixin/ssdb,ideawu/ssdb,cuixin/ssdb,cuixin/ssdb,left2right/ssdb,left2right/ssdb,left2right/ssdb,left2right/ssdb,ideawu/ssdb,cuixin/ssdb,left2right/ssdb,ideawu/ssdb,ideawu/ssdb,cuixin/ssdb,zkidkid/ssdb,zkidkid/ssdb,zkidkid/ssdb,zkidkid/ssdb |
f467ed1c2c26f5d51679d1ed76b5fdd5cf188d75 | src/synchronizer.cc | src/synchronizer.cc | //
// synchronizer.cc
// P2PSP
//
// This code is distributed under the GNU General Public License (see
// THE_GENERAL_GNU_PUBLIC_LICENSE.txt for extending this information).
// Copyright (C) 2016, the P2PSP team.
// http://www.p2psp.org
//
#include "synchronizer.h"
namespace p2psp {
Synchronizer::Synchronizer()
: io_service_(),
player_socket_(io_service_),
acceptor_(io_service_)
{
}
void Synchronizer::Run(int argc, const char* argv[]) throw(boost::system::system_error)
{
boost::program_options::options_description desc("This is the synchronizer node of P2PSP.\n");
desc.add_options()
("help", "Produce this help message and exit.")
("peers",boost::program_options::value<std::vector<std::string> >(),"Peers list");
boost::program_options::variables_map vm;
try{
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
}
catch(std::exception e)
{
// If the argument passed is unknown, print the list of available arguments
std::cout<<desc<<std::endl;
}
boost::program_options::notify(vm);
if(vm.count("help"))
{
std::cout<< desc <<std::endl;
}
if(vm.count("peers"))
{
peer_list = &vm["peers"].as<std::vector<std::string> >();
// Run the RunThreads function which in turn starts the threads which connect to the peers
boost::thread(&Synchronizer::RunThreads,this);
}
}
void Synchronizer::RunThreads()
{
// Iterarate through the peer_list and start a thread to connect to the peer for every peer in peer_list
for(std::vector<std::string>::const_iterator it = peer_list->begin();it!=peer_list->end();++it)
{
thread_group_.interrupt_all();
thread_group_.add_thread(new boost::thread(&Synchronizer::ConnectToPeers,this,*it,(it-peer_list->begin())));
thread_group_.join_all(); //Wait for all threads to complete
}
}
void Synchronizer::ConnectToPeers(std::string s, int id) throw(boost::system::system_error)
{
std::vector<std::string> fields;
boost::algorithm::split(fields,s,boost::is_any_of(":"));
const boost::asio::ip::address hs = boost::asio::ip::address::from_string(fields[0]);
short port = boost::lexical_cast<short>(fields[1]);
boost::asio::ip::tcp::endpoint peer(hs,port);
boost::asio::ip::tcp::socket peer_socket (io_service_);
peer_socket.connect(peer);
peer_data[id].resize(1024);
while(1)
{
boost::asio::read(peer_socket,boost::asio::buffer(peer_data[id]));
}
}
}
| //
// synchronizer.cc
// P2PSP
//
// This code is distributed under the GNU General Public License (see
// THE_GENERAL_GNU_PUBLIC_LICENSE.txt for extending this information).
// Copyright (C) 2016, the P2PSP team.
// http://www.p2psp.org
//
#include "synchronizer.h"
namespace p2psp {
Synchronizer::Synchronizer()
: io_service_(),
player_socket_(io_service_),
acceptor_(io_service_)
{
}
void Synchronizer::Run(int argc, const char* argv[]) throw(boost::system::system_error)
{
boost::program_options::options_description desc("This is the synchronizer node of P2PSP.\n");
desc.add_options()
("help", "Produce this help message and exit.")
("peers",boost::program_options::value<std::vector<std::string> >(),"Peers list");
boost::program_options::variables_map vm;
try{
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
}
catch(std::exception e)
{
// If the argument passed is unknown, print the list of available arguments
std::cout<<desc<<std::endl;
}
boost::program_options::notify(vm);
if(vm.count("help"))
{
std::cout<< desc <<std::endl;
}
if(vm.count("peers"))
{
peer_list = &vm["peers"].as<std::vector<std::string> >();
// Run the RunThreads function which in turn starts the threads which connect to the peers
boost::thread(&Synchronizer::RunThreads,this);
}
}
void Synchronizer::RunThreads()
{
// Iterarate through the peer_list and start a thread to connect to the peer for every peer in peer_list
for(std::vector<std::string>::const_iterator it = peer_list->begin();it!=peer_list->end();++it)
{
thread_group_.interrupt_all();
thread_group_.add_thread(new boost::thread(&Synchronizer::ConnectToPeers,this,*it,(it-peer_list->begin())));
thread_group_.join_all(); //Wait for all threads to complete
}
}
void Synchronizer::ConnectToPeers(std::string s, int id) throw(boost::system::system_error)
{
std::vector<std::string> fields;
boost::algorithm::split(fields,s,boost::is_any_of(":"));
const boost::asio::ip::address hs = boost::asio::ip::address::from_string(fields[0]);
short port = boost::lexical_cast<short>(fields[1]);
boost::asio::ip::tcp::endpoint peer(hs,port);
boost::asio::ip::tcp::socket peer_socket (io_service_);
peer_socket.connect(peer);
peer_data[id].resize(1024);
while(1)
{
boost::asio::read(peer_socket,boost::asio::buffer(peer_data[id]));
}
}
void Synchronizer::Synchronize()
{
/*Here we start with a search string and keep on increasing its length until we find a constant offset from the haystack
string. Once we find the offset, we trim the corresponding peer_data vector according to the offset, so that we achieve
synchronization. Synchronization is a one time process.
*/
int start_offset=100,offset=6;
std::string needle(peer_data[0].begin()+start_offset,peer_data[0].begin()+start_offset+offset);
for(std::vector<std::vector<char> >::iterator it = peer_data.begin()+1; it!=peer_data.end();++it) //Iterating through all the elements of peer_data vector
{
std::string haystack (it->begin(),it->end());
std::size_t found,found_before;
while((found=haystack.find(needle))!=std::string::npos && found!=found_before)
{
offset++;
needle = std::string(peer_data[0].begin()+start_offset,peer_data[0].begin()+start_offset+offset); //Incremental length of the search string
found_before=found; //We stop the loop when the found variable no more changes
}
if(found == std::string::npos) //If the string matching fails, continue
continue;
it->erase(it->begin(),it->begin()+found); //Trim the first 'found' bytes of the vector
}
}
}
| Update Synchronize function | Update Synchronize function
Implemented with the assumption that first few bytes of the chunk acts as hash data
With a simple string matching we will be able to synchronize the chunks from peers
| C++ | mit | hehaichi/p2psp-experiments,hehaichi/p2psp-experiments,hehaichi/p2psp-experiments |
ca248e3f401686231b2cd3c4284e91f19aa98c3b | src/thread_pool.cxx | src/thread_pool.cxx | /*
* A queue that manages work for worker threads.
*
* author: Max Kellermann <[email protected]>
*/
#include "thread_pool.hxx"
#include "thread_queue.hxx"
#include "thread_worker.hxx"
#include "util/Exception.hxx"
#include <daemon/log.h>
#include <array>
#include <assert.h>
#include <stdlib.h>
static ThreadQueue *global_thread_queue;
static std::array<struct thread_worker, 8> worker_threads;
static void
thread_pool_init(EventLoop &event_loop)
{
global_thread_queue = thread_queue_new(event_loop);
}
static void
thread_pool_start(void)
try {
assert(global_thread_queue != nullptr);
for (auto &i : worker_threads)
thread_worker_create(i, *global_thread_queue);
} catch (...) {
daemon_log(1, "Failed to launch worker thread: %s\n",
GetFullMessage(std::current_exception()).c_str());
exit(EXIT_FAILURE);
}
ThreadQueue &
thread_pool_get_queue(EventLoop &event_loop)
{
if (global_thread_queue == nullptr) {
/* initial call - create the queue and launch worker
threads */
thread_pool_init(event_loop);
thread_pool_start();
}
return *global_thread_queue;
}
void
thread_pool_stop(void)
{
if (global_thread_queue == nullptr)
return;
thread_queue_stop(*global_thread_queue);
}
void
thread_pool_join(void)
{
if (global_thread_queue == nullptr)
return;
for (auto &i : worker_threads)
thread_worker_join(i);
}
void
thread_pool_deinit(void)
{
if (global_thread_queue == nullptr)
return;
thread_queue_free(global_thread_queue);
global_thread_queue = nullptr;
}
| /*
* A queue that manages work for worker threads.
*
* author: Max Kellermann <[email protected]>
*/
#include "thread_pool.hxx"
#include "thread_queue.hxx"
#include "thread_worker.hxx"
#include "io/Logger.hxx"
#include <array>
#include <assert.h>
#include <stdlib.h>
static ThreadQueue *global_thread_queue;
static std::array<struct thread_worker, 8> worker_threads;
static void
thread_pool_init(EventLoop &event_loop)
{
global_thread_queue = thread_queue_new(event_loop);
}
static void
thread_pool_start(void)
try {
assert(global_thread_queue != nullptr);
for (auto &i : worker_threads)
thread_worker_create(i, *global_thread_queue);
} catch (...) {
LogConcat(1, "thread_pool", "Failed to launch worker thread: ",
std::current_exception());
exit(EXIT_FAILURE);
}
ThreadQueue &
thread_pool_get_queue(EventLoop &event_loop)
{
if (global_thread_queue == nullptr) {
/* initial call - create the queue and launch worker
threads */
thread_pool_init(event_loop);
thread_pool_start();
}
return *global_thread_queue;
}
void
thread_pool_stop(void)
{
if (global_thread_queue == nullptr)
return;
thread_queue_stop(*global_thread_queue);
}
void
thread_pool_join(void)
{
if (global_thread_queue == nullptr)
return;
for (auto &i : worker_threads)
thread_worker_join(i);
}
void
thread_pool_deinit(void)
{
if (global_thread_queue == nullptr)
return;
thread_queue_free(global_thread_queue);
global_thread_queue = nullptr;
}
| use class Logger | thread_pool: use class Logger
| C++ | bsd-2-clause | CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy |
9d59dde7608bb92729231d791907a4a30fefb2d8 | src/wallOverlap.cpp | src/wallOverlap.cpp | /** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */
#include "wallOverlap.h"
#include <cmath> // isfinite
#include <sstream>
#include "utils/AABB.h" // for debug output svg html
#include "utils/SVG.h"
namespace cura
{
WallOverlapComputation::WallOverlapComputation(Polygons& polygons, int line_width)
: overlap_linker(polygons, line_width)
, line_width(line_width)
{
}
float WallOverlapComputation::getFlow(Point& from, Point& to)
{
using Point2LinkIt = PolygonProximityLinker::Point2Link::iterator;
if (!overlap_linker.isLinked(from))
{ // [from] is not linked
return 1;
}
const std::pair<Point2LinkIt, Point2LinkIt> to_links = overlap_linker.getLinks(to);
if (to_links.first == to_links.second)
{ // [to] is not linked
return 1;
}
int64_t overlap_area = 0;
// note that we don't need to loop over all from_links, because they are handled in the previous getFlow(.) call (or in the very last)
for (Point2LinkIt to_link_it = to_links.first; to_link_it != to_links.second; ++to_link_it)
{
const ProximityPointLink& to_link = to_link_it->second;
ListPolyIt to_it = to_link.a;
ListPolyIt to_other_it = to_link.b;
if (to_link.a.p() != to)
{
assert(to_link.b.p() == to && "Either part of the link should be the point in the link!");
std::swap(to_it, to_other_it);
}
ListPolyIt from_it = to_it.prev();
if (from_it.p() != from)
{
logWarning("Polygon has multiple verts at the same place: (%lli, %lli); PolygonProximityLinker fails in such a case!\n", from.X, from.Y);
}
ListPolyIt to_other_next_it = to_other_it.next(); // move towards [from]; the lines on the other side move in the other direction
// to from
// o<--o<--T<--F
// | : :
// v : :
// o-->o-->o-->o
// , ,
// ; to_other_next
// to other
bool are_in_same_general_direction = dot(from - to, to_other_it.p() - to_other_next_it.p()) > 0;
// handle multiple points linked to [to]
// o<<<T<<<F
// / |
// / |
// o>>>o>>>o
// , ,
// ; to other next
// to other
if (!are_in_same_general_direction)
{
overlap_area += handlePotentialOverlap(to_it, to_it, to_link, to_other_next_it, to_other_it);
}
// handle multiple points linked to [to_other]
// o<<<T<<<F
// | /
// | /
// o>>>o>>>o
bool all_are_in_same_general_direction = are_in_same_general_direction && dot(from - to, to_other_it.prev().p() - to_other_it.p()) > 0;
if (!all_are_in_same_general_direction)
{
overlap_area += handlePotentialOverlap(from_it, to_it, to_link, to_other_it, to_other_it);
}
// handle normal case where the segment from-to overlaps with another segment
// o<<<T<<<F
// | |
// | |
// o>>>o>>>o
// , ,
// ; to other next
// to other
if (!are_in_same_general_direction)
{
overlap_area += handlePotentialOverlap(from_it, to_it, to_link, to_other_next_it, to_other_it);
}
}
int64_t normal_area = vSize(from - to) * line_width;
float ratio = float(normal_area - overlap_area) / normal_area;
// clamp the ratio because overlap compensation might be faulty because
// WallOverlapComputation::getApproxOverlapArea only gives roughly accurate results
return std::min(1.0f, std::max(0.0f, ratio));
}
int64_t WallOverlapComputation::handlePotentialOverlap(const ListPolyIt from_it, const ListPolyIt to_it, const ProximityPointLink& to_link, const ListPolyIt from_other_it, const ListPolyIt to_other_it)
{
if (from_it == to_other_it && from_it == from_other_it)
{ // don't compute overlap with a line and itself
return 0;
}
const ProximityPointLink* from_link = overlap_linker.getLink(from_it, from_other_it);
if (!from_link)
{
return 0;
}
if (!getIsPassed(to_link, *from_link))
{ // check whether the segment is already passed
setIsPassed(to_link, *from_link);
return 0;
}
return getApproxOverlapArea(from_it.p(), to_it.p(), to_link.dist, to_other_it.p(), from_other_it.p(), from_link->dist);
}
int64_t WallOverlapComputation::getApproxOverlapArea(const Point from, const Point to, const int64_t to_dist, const Point other_from, const Point other_to, const int64_t from_dist)
{
std::optional<int64_t> link_dist_2_override; // (an approximation of) twice the length of the overlap area
// check whether the line segment overlaps with the point if one of the line segments is just a point
if (from == to)
{
if (LinearAlg2D::pointIsProjectedBeyondLine(from, other_from, other_to) != 0)
{
return 0;
}
}
else if (other_from == other_to)
{
if (LinearAlg2D::pointIsProjectedBeyondLine(other_from, from, to) != 0)
{
return 0;
}
}
else
{
short from_rel = LinearAlg2D::pointIsProjectedBeyondLine(from, other_from, other_to);
short to_rel = LinearAlg2D::pointIsProjectedBeyondLine(to, other_from, other_to);
short other_from_rel = LinearAlg2D::pointIsProjectedBeyondLine(other_from, from, to);
short other_to_rel = LinearAlg2D::pointIsProjectedBeyondLine(other_to, from, to);
if (from_rel != 0 && from_rel == to_rel && to_rel == other_from_rel && other_from_rel == other_to_rel)
{
// both segments project fully beyond or before each other
// for example:
// O<------O .
// : :
// ' O------->O
return 0;
}
if ( to_rel != 0 && to_rel == other_to_rel && from_rel == 0 && other_from_rel == 0 )
{
// only beginnings of line segments overlap
//
// from_proj
// ^^^^^
// O<---+---O
// : :
// O---+---->O
// ,,,,,
// other_from_proj
const Point other_vec = other_to - other_from;
int64_t from_proj = dot(from - other_from, other_vec) / vSize(other_vec);
const Point vec = to - from;
int64_t other_from_proj = dot(other_from - from, vec) / vSize(vec);
link_dist_2_override = from_proj + other_from_proj;
}
if ( from_rel != 0 && from_rel == other_from_rel && to_rel == 0 && other_to_rel == 0 )
{
// only ends of line segments overlap
//
// to_proj
// ^^^^^
// O<--+----O
// : :
// O-----+-->O
// ,,,,,
// other_to_proj
const Point other_vec = other_from - other_to;
int64_t to_proj = dot(to - other_to, other_vec) / vSize(other_vec);
const Point vec = from - to;
int64_t other_to_proj = dot(other_to - to, vec) / vSize(vec);
link_dist_2_override = to_proj + other_to_proj;
}
}
const Point from_middle = other_to + from; // don't divide by two just yet
const Point to_middle = other_from + to; // don't divide by two just yet
const int64_t link_dist_2 = (link_dist_2_override)? *link_dist_2_override : vSize(from_middle - to_middle); // (an approximation of) twice the length of the overlap area
const int64_t average_overlap_dist_2 = line_width * 2 - from_dist - to_dist; // dont divide by two just yet
const int64_t area = link_dist_2 * average_overlap_dist_2 / 4; // divide by 2 two times: once for the middles and once for the average_dists
return area;
}
bool WallOverlapComputation::getIsPassed(const ProximityPointLink& link_a, const ProximityPointLink& link_b)
{
return passed_links.find(SymmetricPair<ProximityPointLink>(link_a, link_b)) != passed_links.end();
}
void WallOverlapComputation::setIsPassed(const ProximityPointLink& link_a, const ProximityPointLink& link_b)
{
passed_links.emplace(link_a, link_b);
}
}//namespace cura
| /** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */
#include "wallOverlap.h"
#include <cmath> // isfinite
#include <sstream>
#include "utils/AABB.h" // for debug output svg html
#include "utils/SVG.h"
namespace cura
{
WallOverlapComputation::WallOverlapComputation(Polygons& polygons, int line_width)
: overlap_linker(polygons, line_width)
, line_width(line_width)
{
}
float WallOverlapComputation::getFlow(Point& from, Point& to)
{
using Point2LinkIt = PolygonProximityLinker::Point2Link::iterator;
if (!overlap_linker.isLinked(from))
{ // [from] is not linked
return 1;
}
const std::pair<Point2LinkIt, Point2LinkIt> to_links = overlap_linker.getLinks(to);
if (to_links.first == to_links.second)
{ // [to] is not linked
return 1;
}
int64_t overlap_area = 0;
// note that we don't need to loop over all from_links, because they are handled in the previous getFlow(.) call (or in the very last)
for (Point2LinkIt to_link_it = to_links.first; to_link_it != to_links.second; ++to_link_it)
{
const ProximityPointLink& to_link = to_link_it->second;
ListPolyIt to_it = to_link.a;
ListPolyIt to_other_it = to_link.b;
if (to_link.a.p() != to)
{
assert(to_link.b.p() == to && "Either part of the link should be the point in the link!");
std::swap(to_it, to_other_it);
}
ListPolyIt from_it = to_it.prev();
if (from_it.p() != from)
{
logWarning("Polygon has multiple verts at the same place: (%lli, %lli); PolygonProximityLinker fails in such a case!\n", from.X, from.Y);
}
ListPolyIt to_other_next_it = to_other_it.next(); // move towards [from]; the lines on the other side move in the other direction
// to from
// o<--o<--T<--F
// | : :
// v : :
// o-->o-->o-->o
// , ,
// ; to_other_next
// to other
bool are_in_same_general_direction = dot(from - to, to_other_it.p() - to_other_next_it.p()) > 0;
// handle multiple points linked to [to]
// o<<<T<<<F
// / |
// / |
// o>>>o>>>o
// , ,
// ; to other next
// to other
if (!are_in_same_general_direction)
{
overlap_area += handlePotentialOverlap(to_it, to_it, to_link, to_other_next_it, to_other_it);
}
// handle multiple points linked to [to_other]
// o<<<T<<<F
// | /
// | /
// o>>>o>>>o
bool all_are_in_same_general_direction = are_in_same_general_direction && dot(from - to, to_other_it.prev().p() - to_other_it.p()) > 0;
if (!all_are_in_same_general_direction)
{
overlap_area += handlePotentialOverlap(from_it, to_it, to_link, to_other_it, to_other_it);
}
// handle normal case where the segment from-to overlaps with another segment
// o<<<T<<<F
// | |
// | |
// o>>>o>>>o
// , ,
// ; to other next
// to other
if (!are_in_same_general_direction)
{
overlap_area += handlePotentialOverlap(from_it, to_it, to_link, to_other_next_it, to_other_it);
}
}
int64_t normal_area = vSize(from - to) * line_width;
float ratio = float(normal_area - overlap_area) / normal_area;
// clamp the ratio because overlap compensation might be faulty because
// WallOverlapComputation::getApproxOverlapArea only gives roughly accurate results
return std::min(1.0f, std::max(0.0f, ratio));
}
int64_t WallOverlapComputation::handlePotentialOverlap(const ListPolyIt from_it, const ListPolyIt to_it, const ProximityPointLink& to_link, const ListPolyIt from_other_it, const ListPolyIt to_other_it)
{
if (from_it == to_other_it && from_it == from_other_it)
{ // don't compute overlap with a line and itself
return 0;
}
const ProximityPointLink* from_link = overlap_linker.getLink(from_it, from_other_it);
if (!from_link)
{
return 0;
}
if (!getIsPassed(to_link, *from_link))
{ // check whether the segment is already passed
setIsPassed(to_link, *from_link);
return 0;
}
return getApproxOverlapArea(from_it.p(), to_it.p(), to_link.dist, to_other_it.p(), from_other_it.p(), from_link->dist);
}
int64_t WallOverlapComputation::getApproxOverlapArea(const Point from, const Point to, const int64_t to_dist, const Point other_from, const Point other_to, const int64_t from_dist)
{
std::optional<int64_t> link_dist_2_override; //(An approximation of) twice the length of the overlap area parallel to the line average.
// check whether the line segment overlaps with the point if one of the line segments is just a point
if (from == to)
{
if (LinearAlg2D::pointIsProjectedBeyondLine(from, other_from, other_to) != 0)
{
return 0;
}
}
else if (other_from == other_to)
{
if (LinearAlg2D::pointIsProjectedBeyondLine(other_from, from, to) != 0)
{
return 0;
}
}
else
{
short from_rel = LinearAlg2D::pointIsProjectedBeyondLine(from, other_from, other_to);
short to_rel = LinearAlg2D::pointIsProjectedBeyondLine(to, other_from, other_to);
short other_from_rel = LinearAlg2D::pointIsProjectedBeyondLine(other_from, from, to);
short other_to_rel = LinearAlg2D::pointIsProjectedBeyondLine(other_to, from, to);
if (from_rel != 0 && to_rel == from_rel && other_from_rel != 0 && other_to_rel == other_from_rel)
{
// both segments project fully beyond or before each other
// for example: or:
// O<------O . O------>O
// : : \
// ' O------->O O------>O
return 0;
}
if ( to_rel != 0 && to_rel == other_to_rel && from_rel == 0 && other_from_rel == 0 )
{
// only beginnings of line segments overlap
//
// from_proj
// ^^^^^
// O<---+---O
// : :
// O---+---->O
// ,,,,,
// other_from_proj
const Point other_vec = other_to - other_from;
int64_t from_proj = dot(from - other_from, other_vec) / vSize(other_vec);
const Point vec = to - from;
int64_t other_from_proj = dot(other_from - from, vec) / vSize(vec);
link_dist_2_override = from_proj + other_from_proj;
}
if ( from_rel != 0 && from_rel == other_from_rel && to_rel == 0 && other_to_rel == 0 )
{
// only ends of line segments overlap
//
// to_proj
// ^^^^^
// O<--+----O
// : :
// O-----+-->O
// ,,,,,
// other_to_proj
const Point other_vec = other_from - other_to;
int64_t to_proj = dot(to - other_to, other_vec) / vSize(other_vec);
const Point vec = from - to;
int64_t other_to_proj = dot(other_to - to, vec) / vSize(vec);
link_dist_2_override = to_proj + other_to_proj;
}
}
const Point from_middle = other_to + from; // don't divide by two just yet
const Point to_middle = other_from + to; // don't divide by two just yet
const int64_t link_dist_2 = (link_dist_2_override)? *link_dist_2_override : vSize(from_middle - to_middle); // (an approximation of) twice the length of the overlap area
const int64_t average_overlap_dist_2 = line_width * 2 - from_dist - to_dist; // dont divide by two just yet
const int64_t area = link_dist_2 * average_overlap_dist_2 / 4; // divide by 2 two times: once for the middles and once for the average_dists
return area;
}
bool WallOverlapComputation::getIsPassed(const ProximityPointLink& link_a, const ProximityPointLink& link_b)
{
return passed_links.find(SymmetricPair<ProximityPointLink>(link_a, link_b)) != passed_links.end();
}
void WallOverlapComputation::setIsPassed(const ProximityPointLink& link_a, const ProximityPointLink& link_b)
{
passed_links.emplace(link_a, link_b);
}
}//namespace cura
| Improve overlap estimation for stair-case | Improve overlap estimation for stair-case
In the case of stairs, there is no overlap either. The approximation now takes that into account at hardly any additional computational cost.
Contributes to issue CURA-1911.
| C++ | agpl-3.0 | ROBO3D/CuraEngine,totalretribution/CuraEngine,alephobjects/CuraEngine,Ultimaker/CuraEngine,totalretribution/CuraEngine,ROBO3D/CuraEngine,totalretribution/CuraEngine,Ultimaker/CuraEngine,alephobjects/CuraEngine,alephobjects/CuraEngine,ROBO3D/CuraEngine |
a0301cfbec7234c3ff4e389cd205292920c15aa8 | src/yubikeyutil.cpp | src/yubikeyutil.cpp | /*
Copyright (C) 2011-2012 Yubico AB. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "yubikeyutil.h"
#ifdef Q_WS_WIN
#include "crandom.h"
#endif
YubiKeyUtil::~YubiKeyUtil() {
}
int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen,
const char *str, size_t strLen,
size_t minSize, size_t maxSize,
bool modhex)
{
if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) {
return -1;
}
*resultLen = strLen / 2;
if (modhex) {
if (yubikey_modhex_p(str)) {
yubikey_modhex_decode((char *)result, str, strLen);
return 1;
}
} else {
if (yubikey_hex_p(str)) {
yubikey_hex_decode((char *)result, str, strLen);
return 1;
}
}
return 0;
}
int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen,
const unsigned char *str, size_t strLen,
bool modhex)
{
*resultLen = strLen * 2;
if (modhex) {
yubikey_modhex_encode((char *)result, (char *)str, strLen);
return 1;
} else {
yubikey_hex_encode((char *)result, (char *)str, strLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, false);
if(rc > 0) {
qDebug("hex encoded string: -%s- (%u)", result, sizeof(result));
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char hex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str);
size_t hexLen = strlen(hex);
//Hex decode
hexModhexDecode(result, resultLen,
hex, hexLen,
0, MAX_SIZE,
false);
}
QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, true);
if(rc > 0) {
qDebug("modhex encoded string: -%s- (%u)", result, sizeof(result));
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char modhex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str);
size_t modhexLen = strlen(modhex);
//Hex decode
hexModhexDecode(result, resultLen,
modhex, modhexLen,
0, MAX_SIZE,
true);
}
void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
*resultLen = str.size() / 2;
unsigned char val = 0;
for(size_t i = 0; i < *resultLen; i++) {
val = str.mid(i * 2, 2).toInt();
result[i] = ((val / 10) << 4) | (val % 10);
}
}
void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen,
const QString &str) {
QByteArray strByteArr = str.toLocal8Bit();
size_t strLen = strByteArr.size() + 1;
strLen = (resultLen < strLen)? resultLen : strLen;
memset(result, 0, strLen);
strncpy(result, (char *) strByteArr.data(), strLen);
}
void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^0-9a-f]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, '0', true);
} else {
*str = str->leftJustified(maxSize, '0', true);
}
}
}
void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^b-lnrt-v]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, 'c', true);
} else {
*str = str->leftJustified(maxSize, 'c', true);
}
}
}
int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) {
size_t bufSize = resultLen;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
size_t bufLen = 0;
#ifdef Q_WS_WIN
CRandom random;
random.getRand(buf, bufSize);
bufLen = sizeof(buf);
#else
char *random_places[] = {
"/dev/srandom",
"/dev/urandom",
"/dev/random",
0
};
char **random_place;
for (random_place = random_places; *random_place; random_place++) {
FILE *random_file = fopen(*random_place, "r");
if (random_file) {
size_t read_bytes = 0;
while (read_bytes < bufSize) {
size_t n = fread(&buf[read_bytes],
1, bufSize - read_bytes,
random_file);
read_bytes += n;
}
fclose(random_file);
bufLen = sizeof(buf);
break; /* from for loop */
}
}
#endif
if(bufLen > 0) {
memcpy(result, buf, bufLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::generateRandomHex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrHexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::generateRandomModhex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrModhexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::getNextHex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Hex clean
QString hexStr(str);
qstrClean(&hexStr, resultLen);
//Hex decode
unsigned char hexDecoded[MAX_SIZE];
size_t hexDecodedLen = 0;
memset(&hexDecoded, 0, sizeof(hexDecoded));
qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr);
if(hexDecodedLen <= 0) {
break;
}
qDebug() << "hexDecoded = " << QString((char*)hexDecoded)
<< " len = " << hexDecodedLen;
//Increment
for (int i = hexDecodedLen; i--; ) {
if (++hexDecoded[i]) {
break;
}
}
//Hex encode
result = qstrHexEncode(hexDecoded, hexDecodedLen);
qDebug() << "hexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomHex(resultLen);
break;
}
return result;
}
QString YubiKeyUtil::getNextModhex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Modhex clean
QString modhexStr(str);
qstrModhexClean(&modhexStr, resultLen);
//Modhex decode
unsigned char modhexDecoded[MAX_SIZE];
size_t modhexDecodedLen = 0;
memset(&modhexDecoded, 0, sizeof(modhexDecoded));
qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr);
if(modhexDecodedLen <= 0) {
break;
}
qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded)
<< " len = " << modhexDecodedLen;
//Increment
for (int i = modhexDecodedLen; i--; ) {
if (++modhexDecoded[i]) {
break;
}
}
//Modhex encode
result = qstrModhexEncode(modhexDecoded, modhexDecodedLen);
qDebug() << "modhexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomModhex(resultLen);
break;
}
return result;
}
void YubiKeyUtil::hexdump(void *buffer, int size) {
unsigned char *p = (unsigned char *)buffer;
int i;
for (i = 0; i < size; i++) {
fprintf(stderr, "\\x%02x", *p);
p++;
}
fprintf(stderr, "\n");
fflush(stderr);
}
| /*
Copyright (C) 2011-2012 Yubico AB. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "yubikeyutil.h"
#ifdef Q_WS_WIN
#include "crandom.h"
#endif
YubiKeyUtil::~YubiKeyUtil() {
}
int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen,
const char *str, size_t strLen,
size_t minSize, size_t maxSize,
bool modhex)
{
if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) {
return -1;
}
*resultLen = strLen / 2;
if (modhex) {
if (yubikey_modhex_p(str)) {
yubikey_modhex_decode((char *)result, str, strLen);
return 1;
}
} else {
if (yubikey_hex_p(str)) {
yubikey_hex_decode((char *)result, str, strLen);
return 1;
}
}
return 0;
}
int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen,
const unsigned char *str, size_t strLen,
bool modhex)
{
*resultLen = strLen * 2;
if (modhex) {
yubikey_modhex_encode((char *)result, (char *)str, strLen);
return 1;
} else {
yubikey_hex_encode((char *)result, (char *)str, strLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, false);
if(rc > 0) {
qDebug("hex encoded string: -%s- (%u)", result, sizeof(result));
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char hex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str);
size_t hexLen = strlen(hex);
//Hex decode
hexModhexDecode(result, resultLen,
hex, hexLen,
0, MAX_SIZE,
false);
}
QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) {
char result[strLen * 2 + 1];
size_t resultLen = 0;
memset(&result, 0, sizeof(result));
int rc = hexModhexEncode(result, &resultLen, str, strLen, true);
if(rc > 0) {
qDebug("modhex encoded string: -%s- (%u)", result, sizeof(result));
return QString::fromLocal8Bit(result);
}
return QString("");
}
void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
char modhex[MAX_SIZE];
YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str);
size_t modhexLen = strlen(modhex);
//Hex decode
hexModhexDecode(result, resultLen,
modhex, modhexLen,
0, MAX_SIZE,
true);
}
void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen,
const QString &str) {
if(str.size() % 2 != 0) {
return;
}
*resultLen = str.size() / 2;
unsigned char val = 0;
for(size_t i = 0; i < *resultLen; i++) {
val = str.mid(i * 2, 2).toInt();
result[i] = ((val / 10) << 4) | (val % 10);
}
}
void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen,
const QString &str) {
QByteArray strByteArr = str.toLocal8Bit();
size_t strLen = strByteArr.size() + 1;
strLen = (resultLen < strLen)? resultLen : strLen;
memset(result, 0, strLen);
strncpy(result, (char *) strByteArr.data(), strLen);
}
void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^0-9a-f]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, '0', true);
} else {
*str = str->leftJustified(maxSize, '0', true);
}
}
}
void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) {
*str = str->toLower();
QRegExp rx("[^b-lnrt-v]");
*str = str->replace(rx, QString(""));
if(maxSize > 0) {
if(reverse) {
*str = str->rightJustified(maxSize, 'c', true);
} else {
*str = str->leftJustified(maxSize, 'c', true);
}
}
}
int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) {
size_t bufSize = resultLen;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
size_t bufLen = 0;
#ifdef Q_WS_WIN
CRandom random;
random.getRand(buf, bufSize);
bufLen = sizeof(buf);
#else
const char *random_places[] = {
"/dev/srandom",
"/dev/urandom",
"/dev/random",
0
};
const char **random_place;
for (random_place = random_places; *random_place; random_place++) {
FILE *random_file = fopen(*random_place, "r");
if (random_file) {
size_t read_bytes = 0;
while (read_bytes < bufSize) {
size_t n = fread(&buf[read_bytes],
1, bufSize - read_bytes,
random_file);
read_bytes += n;
}
fclose(random_file);
bufLen = sizeof(buf);
break; /* from for loop */
}
}
#endif
if(bufLen > 0) {
memcpy(result, buf, bufLen);
return 1;
}
return 0;
}
QString YubiKeyUtil::generateRandomHex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrHexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::generateRandomModhex(size_t resultLen) {
QString result("");
if (resultLen % 2 != 0) {
return result;
}
size_t bufSize = resultLen / 2;
unsigned char buf[bufSize];
memset(&buf, 0, sizeof(buf));
if(generateRandom(buf, bufSize) > 0) {
result = qstrModhexEncode(buf, bufSize);
}
return result;
}
QString YubiKeyUtil::getNextHex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Hex clean
QString hexStr(str);
qstrClean(&hexStr, resultLen);
//Hex decode
unsigned char hexDecoded[MAX_SIZE];
size_t hexDecodedLen = 0;
memset(&hexDecoded, 0, sizeof(hexDecoded));
qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr);
if(hexDecodedLen <= 0) {
break;
}
qDebug() << "hexDecoded = " << QString((char*)hexDecoded)
<< " len = " << hexDecodedLen;
//Increment
for (int i = hexDecodedLen; i--; ) {
if (++hexDecoded[i]) {
break;
}
}
//Hex encode
result = qstrHexEncode(hexDecoded, hexDecodedLen);
qDebug() << "hexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomHex(resultLen);
break;
}
return result;
}
QString YubiKeyUtil::getNextModhex(size_t resultLen,
const QString &str, int scheme) {
QString result("");
qDebug() << "str = " << str
<< " len = " << str.length();
switch(scheme) {
case GEN_SCHEME_FIXED:
result = str;
break;
case GEN_SCHEME_INCR:
{
//Modhex clean
QString modhexStr(str);
qstrModhexClean(&modhexStr, resultLen);
//Modhex decode
unsigned char modhexDecoded[MAX_SIZE];
size_t modhexDecodedLen = 0;
memset(&modhexDecoded, 0, sizeof(modhexDecoded));
qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr);
if(modhexDecodedLen <= 0) {
break;
}
qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded)
<< " len = " << modhexDecodedLen;
//Increment
for (int i = modhexDecodedLen; i--; ) {
if (++modhexDecoded[i]) {
break;
}
}
//Modhex encode
result = qstrModhexEncode(modhexDecoded, modhexDecodedLen);
qDebug() << "modhexEncoded = " << result
<< " len = " << result.size();
}
break;
case GEN_SCHEME_RAND:
result = generateRandomModhex(resultLen);
break;
}
return result;
}
void YubiKeyUtil::hexdump(void *buffer, int size) {
unsigned char *p = (unsigned char *)buffer;
int i;
for (i = 0; i < size; i++) {
fprintf(stderr, "\\x%02x", *p);
p++;
}
fprintf(stderr, "\n");
fflush(stderr);
}
| mark as const | mark as const
| C++ | bsd-2-clause | eworm-de/yubikey-personalization-gui,Yubico/yubikey-personalization-gui,Yubico/yubikey-personalization-gui,eworm-de/yubikey-personalization-gui,Yubico/yubikey-personalization-gui,eworm-de/yubikey-personalization-gui |
f78139fe96a7b4a378d823c421f2878505d5d6c8 | TTKModule/musicbottomareawidget.cpp | TTKModule/musicbottomareawidget.cpp | #include "musicbottomareawidget.h"
#include "ui_musicapplication.h"
#include "musicapplication.h"
#include "musicuiobject.h"
#include "musicsystemtraymenu.h"
#include "musicwindowextras.h"
#include "musicfunctionuiobject.h"
#include "musictinyuiobject.h"
MusicBottomAreaWidget *MusicBottomAreaWidget::m_instance = nullptr;
MusicBottomAreaWidget::MusicBottomAreaWidget(QWidget *parent)
: QWidget(parent)
{
m_instance = this;
m_systemCloseConfig = false;
createSystemTrayIcon();
m_musicWindowExtras = new MusicWindowExtras(parent);
}
MusicBottomAreaWidget::~MusicBottomAreaWidget()
{
delete m_systemTrayMenu;
delete m_systemTray;
delete m_musicWindowExtras;
}
QString MusicBottomAreaWidget::getClassName()
{
return staticMetaObject.className();
}
MusicBottomAreaWidget *MusicBottomAreaWidget::instance()
{
return m_instance;
}
void MusicBottomAreaWidget::setupUi(Ui::MusicApplication* ui)
{
m_ui = ui;
ui->resizeLabelWidget->setPixmap(QPixmap(":/tiny/lb_resize_normal"));
ui->showCurrentSong->setEffectOnResize(true);
connect(ui->musicDesktopLrc, SIGNAL(clicked()), m_systemTrayMenu, SLOT(showDesktopLrc()));
}
void MusicBottomAreaWidget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch(reason)
{
case QSystemTrayIcon::DoubleClick:
break;
case QSystemTrayIcon::Trigger:
if(MusicApplication::instance()->isMinimized())
{
MusicApplication::instance()->showNormal();
MusicApplication::instance()->activateWindow();
}
break;
default:
break;
}
}
void MusicBottomAreaWidget::createSystemTrayIcon()
{
m_systemTray = new QSystemTrayIcon(MusicApplication::instance());
m_systemTray->setIcon(QIcon(":/image/lb_player_logo"));
m_systemTray->setToolTip(tr("TTKMusicPlayer"));
m_systemTrayMenu = new MusicSystemTrayMenu(MusicApplication::instance());
m_systemTray->setContextMenu(m_systemTrayMenu);
m_systemTray->show();
connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void MusicBottomAreaWidget::setDestopLrcVisible(bool status) const
{
m_systemTrayMenu->showDesktopLrc(status);
}
void MusicBottomAreaWidget::showPlayStatus(bool status) const
{
m_systemTrayMenu->showPlayStatus(status);
#if defined Q_OS_WIN && defined MUSIC_WINEXTRAS
m_musicWindowExtras->showPlayStatus(status);
#endif
}
void MusicBottomAreaWidget::setVolumeValue(int value) const
{
m_systemTrayMenu->setVolumeValue(value);
}
void MusicBottomAreaWidget::setLabelText(const QString &name) const
{
m_systemTrayMenu->setLabelText(name);
m_systemTray->setToolTip(name);
}
void MusicBottomAreaWidget::showMessage(const QString &title, const QString &text)
{
m_systemTray->showMessage(title, text);
}
#if defined MUSIC_DEBUG && defined Q_OS_WIN && defined MUSIC_WINEXTRAS
void MusicBottomAreaWidget::setValue(int value) const
{
m_musicWindowExtras->setValue(value);
}
void MusicBottomAreaWidget::setRange(int min, int max) const
{
m_musicWindowExtras->setRange(min, max);
}
#endif
void MusicBottomAreaWidget::setWindowConcise()
{
bool con = m_musicWindowExtras->isDisableBlurBehindWindow();
M_SETTING_PTR->setValue(MusicSettingManager::WindowConciseChoiced, con);
m_ui->topRightWidget->setVisible(!con);
m_ui->centerRightWidget->setVisible(!con);
m_ui->bottomCenterWidget->setVisible(!con);
m_ui->bottomRightWidget->setVisible(!con);
m_ui->bottomLeftContainWidget->setMinimumWidth(con ? 322 : 220);
m_ui->musicWindowConcise->setParent(con ? m_ui->background : m_ui->topRightWidget);
m_ui->musicWindowConcise->setStyleSheet(con ? MusicUIObject::MKGBtnConciseOut : MusicUIObject::MKGBtnConciseIn);
m_ui->minimization->setParent(con ? m_ui->background : m_ui->topRightWidget);
m_ui->windowClose->setParent(con ? m_ui->background : m_ui->topRightWidget);
m_ui->musicBestLove->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicDownload->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicMoreFunction->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicSound->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicDesktopLrc->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicTimeWidget->setParent(con ? m_ui->background : m_ui->bottomCenterWidget);
if(con)
{
MusicApplication *app = MusicApplication::instance();
app->setMinimumSize(322, WINDOW_HEIGHT_MIN);
app->setMaximumSize(322, WINDOW_HEIGHT_MIN);
m_ui->musicWindowConcise->move(245, 20);
m_ui->musicWindowConcise->show();
m_ui->minimization->move(270, 20);
m_ui->minimization->show();
m_ui->windowClose->move(295, 20);
m_ui->windowClose->show();
m_ui->musicPrevious->setStyleSheet(MusicUIObject::MKGTinyBtnPrevious);
m_ui->musicKey->setStyleSheet(app->isPlaying() ? MusicUIObject::MKGTinyBtnPause : MusicUIObject::MKGTinyBtnPlay);
m_ui->musicNext->setStyleSheet(MusicUIObject::MKGTinyBtnNext);
m_ui->musicPrevious->setFixedSize(28, 28);
m_ui->musicKey->setFixedSize(28, 28);
m_ui->musicNext->setFixedSize(28, 28);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicBestLove);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicDownload);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicMoreFunction);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicSound);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicDesktopLrc);
m_ui->bottomLeftContainWidgetLayout->addWidget(m_ui->musicTimeWidget);
}
else
{
QSize size = M_SETTING_PTR->value(MusicSettingManager::ScreenSize).toSize();
MusicApplication *app = MusicApplication::instance();
app->setMinimumSize(WINDOW_WIDTH_MIN, WINDOW_HEIGHT_MIN);
app->setMaximumSize(size.width(), size.height());
m_ui->musicPrevious->setStyleSheet(MusicUIObject::MKGBtnPrevious);
m_ui->musicKey->setStyleSheet(app->isPlaying() ? MusicUIObject::MKGBtnPause : MusicUIObject::MKGBtnPlay);
m_ui->musicNext->setStyleSheet(MusicUIObject::MKGBtnNext);
m_ui->musicPrevious->setFixedSize(44, 44);
m_ui->musicKey->setFixedSize(44, 44);
m_ui->musicNext->setFixedSize(44, 44);
m_ui->topRightWidgetLayout->insertWidget(11, m_ui->musicWindowConcise);
m_ui->topRightWidgetLayout->addWidget(m_ui->minimization);
m_ui->topRightWidgetLayout->addWidget(m_ui->windowClose);
m_ui->bottomRightWidgetLayout->insertWidget(0, m_ui->musicBestLove);
m_ui->bottomRightWidgetLayout->insertWidget(1, m_ui->musicDownload);
m_ui->bottomRightWidgetLayout->insertWidget(2, m_ui->musicMoreFunction);
m_ui->bottomRightWidgetLayout->insertWidget(4, m_ui->musicSound);
m_ui->bottomRightWidgetLayout->insertWidget(6, m_ui->musicDesktopLrc);
m_ui->bottomCenterWidgetLayout->addWidget(m_ui->musicTimeWidget, 3, 0, 1, 6);
}
m_musicWindowExtras->disableBlurBehindWindow( !con );
}
void MusicBottomAreaWidget::resizeWindow()
{
int h = m_ui->musiclrccontainerforinline->size().height() - m_ui->lrcDisplayAllButton->height() - 40;
m_ui->lrcDisplayAllButton->move(m_ui->lrcDisplayAllButton->x(), h/2);
}
void MusicBottomAreaWidget::lockDesktopLrc(bool lock)
{
m_systemTrayMenu->lockDesktopLrc(lock);
}
void MusicBottomAreaWidget::desktopLrcClosed()
{
m_ui->musicDesktopLrc->setChecked(false);
m_systemTrayMenu->showDesktopLrc(false);
M_SETTING_PTR->setValue(MusicSettingManager::ShowDesktopLrcChoiced, false);
}
| #include "musicbottomareawidget.h"
#include "ui_musicapplication.h"
#include "musicapplication.h"
#include "musicuiobject.h"
#include "musicsystemtraymenu.h"
#include "musicwindowextras.h"
#include "musicfunctionuiobject.h"
#include "musictinyuiobject.h"
MusicBottomAreaWidget *MusicBottomAreaWidget::m_instance = nullptr;
MusicBottomAreaWidget::MusicBottomAreaWidget(QWidget *parent)
: QWidget(parent)
{
m_instance = this;
m_systemCloseConfig = false;
createSystemTrayIcon();
m_musicWindowExtras = new MusicWindowExtras(parent);
}
MusicBottomAreaWidget::~MusicBottomAreaWidget()
{
delete m_systemTrayMenu;
delete m_systemTray;
delete m_musicWindowExtras;
}
QString MusicBottomAreaWidget::getClassName()
{
return staticMetaObject.className();
}
MusicBottomAreaWidget *MusicBottomAreaWidget::instance()
{
return m_instance;
}
void MusicBottomAreaWidget::setupUi(Ui::MusicApplication* ui)
{
m_ui = ui;
ui->resizeLabelWidget->setPixmap(QPixmap(":/tiny/lb_resize_normal"));
ui->showCurrentSong->setEffectOnResize(true);
connect(ui->musicDesktopLrc, SIGNAL(clicked()), m_systemTrayMenu, SLOT(showDesktopLrc()));
}
void MusicBottomAreaWidget::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch(reason)
{
case QSystemTrayIcon::DoubleClick:
break;
case QSystemTrayIcon::Trigger:
{
MusicApplication *w = MusicApplication::instance();
if(w->isMinimized() || w->isHidden())
{
w->showNormal();
w->activateWindow();
}
break;
}
default:
break;
}
}
void MusicBottomAreaWidget::createSystemTrayIcon()
{
m_systemTray = new QSystemTrayIcon(MusicApplication::instance());
m_systemTray->setIcon(QIcon(":/image/lb_player_logo"));
m_systemTray->setToolTip(tr("TTKMusicPlayer"));
m_systemTrayMenu = new MusicSystemTrayMenu(MusicApplication::instance());
m_systemTray->setContextMenu(m_systemTrayMenu);
m_systemTray->show();
connect(m_systemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}
void MusicBottomAreaWidget::setDestopLrcVisible(bool status) const
{
m_systemTrayMenu->showDesktopLrc(status);
}
void MusicBottomAreaWidget::showPlayStatus(bool status) const
{
m_systemTrayMenu->showPlayStatus(status);
#if defined Q_OS_WIN && defined MUSIC_WINEXTRAS
m_musicWindowExtras->showPlayStatus(status);
#endif
}
void MusicBottomAreaWidget::setVolumeValue(int value) const
{
m_systemTrayMenu->setVolumeValue(value);
}
void MusicBottomAreaWidget::setLabelText(const QString &name) const
{
m_systemTrayMenu->setLabelText(name);
m_systemTray->setToolTip(name);
}
void MusicBottomAreaWidget::showMessage(const QString &title, const QString &text)
{
m_systemTray->showMessage(title, text);
}
#if defined MUSIC_DEBUG && defined Q_OS_WIN && defined MUSIC_WINEXTRAS
void MusicBottomAreaWidget::setValue(int value) const
{
m_musicWindowExtras->setValue(value);
}
void MusicBottomAreaWidget::setRange(int min, int max) const
{
m_musicWindowExtras->setRange(min, max);
}
#endif
void MusicBottomAreaWidget::setWindowConcise()
{
bool con = m_musicWindowExtras->isDisableBlurBehindWindow();
M_SETTING_PTR->setValue(MusicSettingManager::WindowConciseChoiced, con);
m_ui->topRightWidget->setVisible(!con);
m_ui->centerRightWidget->setVisible(!con);
m_ui->bottomCenterWidget->setVisible(!con);
m_ui->bottomRightWidget->setVisible(!con);
m_ui->bottomLeftContainWidget->setMinimumWidth(con ? 322 : 220);
m_ui->musicWindowConcise->setParent(con ? m_ui->background : m_ui->topRightWidget);
m_ui->musicWindowConcise->setStyleSheet(con ? MusicUIObject::MKGBtnConciseOut : MusicUIObject::MKGBtnConciseIn);
m_ui->minimization->setParent(con ? m_ui->background : m_ui->topRightWidget);
m_ui->windowClose->setParent(con ? m_ui->background : m_ui->topRightWidget);
m_ui->musicBestLove->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicDownload->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicMoreFunction->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicSound->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicDesktopLrc->setParent(con ? m_ui->background : m_ui->bottomRightWidget);
m_ui->musicTimeWidget->setParent(con ? m_ui->background : m_ui->bottomCenterWidget);
if(con)
{
MusicApplication *app = MusicApplication::instance();
app->setMinimumSize(322, WINDOW_HEIGHT_MIN);
app->setMaximumSize(322, WINDOW_HEIGHT_MIN);
m_ui->musicWindowConcise->move(245, 20);
m_ui->musicWindowConcise->show();
m_ui->minimization->move(270, 20);
m_ui->minimization->show();
m_ui->windowClose->move(295, 20);
m_ui->windowClose->show();
m_ui->musicPrevious->setStyleSheet(MusicUIObject::MKGTinyBtnPrevious);
m_ui->musicKey->setStyleSheet(app->isPlaying() ? MusicUIObject::MKGTinyBtnPause : MusicUIObject::MKGTinyBtnPlay);
m_ui->musicNext->setStyleSheet(MusicUIObject::MKGTinyBtnNext);
m_ui->musicPrevious->setFixedSize(28, 28);
m_ui->musicKey->setFixedSize(28, 28);
m_ui->musicNext->setFixedSize(28, 28);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicBestLove);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicDownload);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicMoreFunction);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicSound);
m_ui->bottomLeftWidgetLayout->addWidget(m_ui->musicDesktopLrc);
m_ui->bottomLeftContainWidgetLayout->addWidget(m_ui->musicTimeWidget);
}
else
{
QSize size = M_SETTING_PTR->value(MusicSettingManager::ScreenSize).toSize();
MusicApplication *app = MusicApplication::instance();
app->setMinimumSize(WINDOW_WIDTH_MIN, WINDOW_HEIGHT_MIN);
app->setMaximumSize(size.width(), size.height());
m_ui->musicPrevious->setStyleSheet(MusicUIObject::MKGBtnPrevious);
m_ui->musicKey->setStyleSheet(app->isPlaying() ? MusicUIObject::MKGBtnPause : MusicUIObject::MKGBtnPlay);
m_ui->musicNext->setStyleSheet(MusicUIObject::MKGBtnNext);
m_ui->musicPrevious->setFixedSize(44, 44);
m_ui->musicKey->setFixedSize(44, 44);
m_ui->musicNext->setFixedSize(44, 44);
m_ui->topRightWidgetLayout->insertWidget(11, m_ui->musicWindowConcise);
m_ui->topRightWidgetLayout->addWidget(m_ui->minimization);
m_ui->topRightWidgetLayout->addWidget(m_ui->windowClose);
m_ui->bottomRightWidgetLayout->insertWidget(0, m_ui->musicBestLove);
m_ui->bottomRightWidgetLayout->insertWidget(1, m_ui->musicDownload);
m_ui->bottomRightWidgetLayout->insertWidget(2, m_ui->musicMoreFunction);
m_ui->bottomRightWidgetLayout->insertWidget(4, m_ui->musicSound);
m_ui->bottomRightWidgetLayout->insertWidget(6, m_ui->musicDesktopLrc);
m_ui->bottomCenterWidgetLayout->addWidget(m_ui->musicTimeWidget, 3, 0, 1, 6);
}
m_musicWindowExtras->disableBlurBehindWindow( !con );
}
void MusicBottomAreaWidget::resizeWindow()
{
int h = m_ui->musiclrccontainerforinline->size().height() - m_ui->lrcDisplayAllButton->height() - 40;
m_ui->lrcDisplayAllButton->move(m_ui->lrcDisplayAllButton->x(), h/2);
}
void MusicBottomAreaWidget::lockDesktopLrc(bool lock)
{
m_systemTrayMenu->lockDesktopLrc(lock);
}
void MusicBottomAreaWidget::desktopLrcClosed()
{
m_ui->musicDesktopLrc->setChecked(false);
m_systemTrayMenu->showDesktopLrc(false);
M_SETTING_PTR->setValue(MusicSettingManager::ShowDesktopLrcChoiced, false);
}
| Fix close hide mode[324001] | Fix close hide mode[324001]
| C++ | lgpl-2.1 | Greedysky/Musicplayer,Greedysky/Musicplayer,Greedysky/Musicplayer |
93be5eded469af6fef075bf04285a73a52977c80 | framework/framework.cpp | framework/framework.cpp |
#include "framework.h"
#include "../stages/bootup.h"
Framework* Framework::SystemFramework;
Framework::Framework()
{
#ifdef WRITE_LOG
printf( "Framework: Startup\n" );
#endif
// Init Allegro
if( !al_init() )
{
return;
}
al_init_font_addon();
if( !al_install_keyboard() || !al_install_mouse() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() )
{
return;
}
if( al_install_joystick() )
{
al_reconfigure_joysticks();
}
audioInitialised = false;
InitialiseAudioSystem();
std::string selectedLanguage;
quitProgram = false;
ProgramStages = new StageStack();
framesToProcess = 0;
Settings = new ConfigFile( "settings.cfg" );
eventQueue = al_create_event_queue();
InitialiseDisplay();
al_register_event_source( eventQueue, al_get_keyboard_event_source() );
al_register_event_source( eventQueue, al_get_mouse_event_source() );
al_register_event_source( eventQueue, al_get_joystick_event_source() );
fpsTimer = al_create_timer( 1.0 / (float)FRAMES_PER_SECOND );
al_register_event_source( eventQueue, al_get_timer_event_source( fpsTimer ) );
al_start_timer( fpsTimer );
al_hide_mouse_cursor( displaySurface );
imageMgr = new ImageManager( this );
fontMgr = new FontManager( this );
audioMgr = new AudioManager( this );
int maxDownloads = 4;
if( Settings->KeyExists( "Downloads.MaxConcurrentDownloads" ) )
{
Settings->GetIntegerValue( "Downloads.MaxConcurrentDownloads", &maxDownloads );
}
downloadMgr = new DownloadManager( this, maxDownloads );
networkMgr = new NetworkManager( this );
languageMgr = new LanguageManager();
if( Settings->KeyExists( "Application.Language" ) )
{
Settings->GetStringValue( "Application.Language", &selectedLanguage );
languageMgr->SetActiveLanguage( selectedLanguage );
}
SystemFramework = this;
extraEventsMutex = al_create_mutex();
}
Framework::~Framework()
{
Settings->Save( "settings.cfg" );
#ifdef WRITE_LOG
printf( "Framework: Shutdown\n" );
#endif
al_destroy_event_queue( eventQueue );
al_destroy_display( displaySurface );
al_destroy_mutex( extraEventsMutex );
delete imageMgr;
delete audioMgr;
delete fontMgr;
delete networkMgr;
delete downloadMgr;
// Shutdown Allegro
if( mixer != 0 )
{
al_destroy_mixer( mixer );
}
if( voice != 0 )
{
al_destroy_voice( voice );
}
al_uninstall_keyboard();
al_uninstall_mouse();
al_shutdown_primitives_addon();
al_shutdown_ttf_addon();
al_shutdown_image_addon();
al_shutdown_font_addon();
al_uninstall_audio();
al_uninstall_joystick();
}
void Framework::Run()
{
#ifdef WRITE_LOG
printf( "Framework: Run.Program Loop\n" );
#endif
// Set BootUp Stage active
ProgramStages->Push( (Stage*)new BootUp() );
while( !quitProgram )
{
ProcessEvents();
}
downloadMgr->Tidy();
}
void Framework::ProcessEvents()
{
ALLEGRO_EVENT e;
FwEvent* fwev;
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.AllegroEvents\n" );
#endif
while( al_get_next_event( eventQueue, &e ) )
{
switch( e.type )
{
case ALLEGRO_EVENT_DISPLAY_CLOSE:
quitProgram = true;
break;
case ALLEGRO_EVENT_JOYSTICK_CONFIGURATION:
al_reconfigure_joysticks();
break;
case ALLEGRO_EVENT_TIMER:
if( e.timer.source == fpsTimer )
{
framesToProcess++;
} else {
fwev = new FwEvent( &e );
ProgramStages->Current()->Event( fwev );
delete fwev;
}
break;
default:
fwev = new FwEvent( &e );
ProgramStages->Current()->Event( fwev );
delete fwev;
}
if( ProgramStages->IsEmpty() )
{
quitProgram = true;
return;
}
}
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.ExtraEvents\n" );
#endif
al_lock_mutex( extraEventsMutex );
while( extraEvents.size() > 0 )
{
fwev = extraEvents.front();
extraEvents.pop_front();
if( fwev->Type == EVENT_DOWNLOAD_COMPLETE )
{
downloadMgr->Event( fwev );
}
ProgramStages->Current()->Event( fwev );
delete fwev;
if( ProgramStages->IsEmpty() )
{
quitProgram = true;
return;
}
}
al_unlock_mutex( extraEventsMutex );
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.Update\n" );
#endif
while( framesToProcess > 0 )
{
if( ProgramStages->IsEmpty() )
{
quitProgram = true;
return;
}
ProgramStages->Current()->Update();
downloadMgr->Update();
networkMgr->Update();
framesToProcess--;
}
// Not bothered if these update every frame, only cache clearing
imageMgr->Update();
fontMgr->Update();
if( musicFilename != "" )
{
audioMgr->GetMusic( musicFilename ); // Prevent uncaching of current music
}
audioMgr->Update();
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.Render\n" );
#endif
if( !ProgramStages->IsEmpty() )
{
ProgramStages->Current()->Render();
al_flip_display();
}
}
void Framework::PushEvent( FwEvent* e )
{
al_lock_mutex( extraEventsMutex );
extraEvents.push_back( e );
al_unlock_mutex( extraEventsMutex );
}
void Framework::ShutdownFramework()
{
while( !ProgramStages->IsEmpty() )
{
delete ProgramStages->Pop();
}
quitProgram = true;
}
ImageManager* Framework::GetImageManager()
{
return imageMgr;
}
FontManager* Framework::GetFontManager()
{
return fontMgr;
}
AudioManager* Framework::GetAudioManager()
{
return audioMgr;
}
DownloadManager* Framework::GetDownloadManager()
{
return downloadMgr;
}
NetworkManager* Framework::GetNetworkManager()
{
return networkMgr;
}
LanguageManager* Framework::GetLanguageManager()
{
return languageMgr;
}
int Framework::GetDisplayWidth()
{
return al_get_display_width( displaySurface );
}
int Framework::GetDisplayHeight()
{
return al_get_display_height( displaySurface );
}
void Framework::RestoreDisplayTarget()
{
al_set_target_backbuffer( displaySurface );
}
void Framework::PlayMusic( std::string Filename, ALLEGRO_PLAYMODE Mode )
{
#ifdef WRITE_LOG
printf( "Framework: Play Music '%s'\n", Filename.c_str() );
#endif
if( voice != 0 )
{
musicStream = audioMgr->GetMusic( Filename );
if( musicStream != 0 )
{
musicFilename = Filename;
al_set_audio_stream_playmode( musicStream, Mode );
al_attach_audio_stream_to_mixer( musicStream, mixer );
al_set_audio_stream_playing( musicStream, true );
} else {
#ifdef WRITE_LOG
printf( "Framework: Could not load music '%s'\n", Filename.c_str() );
#endif
}
}
}
void Framework::StopMusic()
{
if( voice != 0 && musicStream != 0 )
{
al_set_audio_stream_playing( musicStream, false );
}
musicFilename = "";
}
void Framework::SaveSettings()
{
// Just to keep the filename consistant
Settings->Save( "settings.cfg" );
}
void Framework::SetWindowTitle( std::string* NewTitle )
{
al_set_window_title( displaySurface, NewTitle->c_str() );
}
void Framework::InitialiseAudioSystem()
{
#ifdef WRITE_LOG
printf( "Framework: Initialise Audio\n" );
#endif
voice = 0;
mixer = 0;
if( audioInitialised || al_install_audio() )
{
if( audioInitialised || al_init_acodec_addon() )
{
voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
if( voice != 0 )
{
mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
if( mixer != 0 )
{
al_attach_mixer_to_voice(mixer, voice);
} else {
al_destroy_voice( voice );
voice = 0;
}
}
}
}
}
void Framework::ShutdownAudioSystem()
{
#ifdef WRITE_LOG
printf( "Framework: Shutdown Audio\n" );
#endif
if( mixer != 0 )
{
al_detach_mixer( mixer );
al_destroy_mixer( mixer );
mixer = 0;
}
if( voice != 0 )
{
al_destroy_voice( voice );
voice = 0;
}
}
void Framework::InitialiseDisplay()
{
#ifdef WRITE_LOG
printf( "Framework: Initialise Display\n" );
#endif
int scrW = 800;
int scrH = 480;
bool scrFS = false;
if( Settings->KeyExists( "Visual.ScreenWidth" ) )
{
Settings->GetIntegerValue( "Visual.ScreenWidth", &scrW );
}
if( Settings->KeyExists( "Visual.ScreenHeight" ) )
{
Settings->GetIntegerValue( "Visual.ScreenHeight", &scrH );
}
if( Settings->KeyExists( "Visual.FullScreen" ) )
{
Settings->GetBooleanValue( "Visual.FullScreen", &scrFS );
}
if( scrFS )
{
al_set_new_display_flags( ALLEGRO_FULLSCREEN_WINDOW );
}
al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);
displaySurface = al_create_display( scrW, scrH );
if( displaySurface == 0 )
{
return;
}
al_set_blender( ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA );
al_register_event_source( eventQueue, al_get_display_event_source( displaySurface ) );
}
void Framework::ShutdownDisplay()
{
#ifdef WRITE_LOG
printf( "Framework: Shutdown Display\n" );
#endif
al_unregister_event_source( eventQueue, al_get_display_event_source( displaySurface ) );
fontMgr->Clear();
imageMgr->Clear();
al_destroy_display( displaySurface );
}
| #include "framework.h"
#include "../stages/bootup.h"
Framework* Framework::SystemFramework;
Framework::Framework()
{
#ifdef WRITE_LOG
printf( "Framework: Startup\n" );
#endif
// Init Allegro
if( !al_init() )
{
return;
}
al_init_font_addon();
if( !al_install_keyboard() || !al_install_mouse() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() )
{
return;
}
if( al_install_joystick() )
{
al_reconfigure_joysticks();
}
audioInitialised = false;
InitialiseAudioSystem();
std::string selectedLanguage;
quitProgram = false;
ProgramStages = new StageStack();
framesToProcess = 0;
Settings = new ConfigFile( "settings.cfg" );
eventQueue = al_create_event_queue();
InitialiseDisplay();
al_register_event_source( eventQueue, al_get_keyboard_event_source() );
al_register_event_source( eventQueue, al_get_mouse_event_source() );
al_register_event_source( eventQueue, al_get_joystick_event_source() );
fpsTimer = al_create_timer( 1.0 / (float)FRAMES_PER_SECOND );
al_register_event_source( eventQueue, al_get_timer_event_source( fpsTimer ) );
al_start_timer( fpsTimer );
al_hide_mouse_cursor( displaySurface );
imageMgr = new ImageManager( this );
fontMgr = new FontManager( this );
audioMgr = new AudioManager( this );
int maxDownloads = 4;
if( Settings->KeyExists( "Downloads.MaxConcurrentDownloads" ) )
{
Settings->GetIntegerValue( "Downloads.MaxConcurrentDownloads", &maxDownloads );
}
downloadMgr = new DownloadManager( this, maxDownloads );
networkMgr = new NetworkManager( this );
languageMgr = new LanguageManager();
if( Settings->KeyExists( "Application.Language" ) )
{
Settings->GetStringValue( "Application.Language", &selectedLanguage );
languageMgr->SetActiveLanguage( selectedLanguage );
}
SystemFramework = this;
extraEventsMutex = al_create_mutex();
}
Framework::~Framework()
{
#ifdef WRITE_LOG
printf( "Framework: Save Config\n" );
#endif
Settings->Save( "settings.cfg" );
#ifdef WRITE_LOG
printf( "Framework: Shutdown Managers\n" );
#endif
delete imageMgr;
delete audioMgr;
delete fontMgr;
delete networkMgr;
delete downloadMgr;
#ifdef WRITE_LOG
printf( "Framework: Shutdown Addons\n" );
#endif
al_shutdown_primitives_addon();
al_shutdown_ttf_addon();
al_shutdown_image_addon();
al_shutdown_font_addon();
#ifdef WRITE_LOG
printf( "Framework: Shutdown Allegro\n" );
#endif
ShutdownDisplay();
ShutdownAudioSystem();
al_destroy_event_queue( eventQueue );
al_destroy_mutex( extraEventsMutex );
#ifdef WRITE_LOG
printf( "Framework: Uninstall Allegro\n" );
#endif
al_uninstall_audio();
al_uninstall_keyboard();
al_uninstall_mouse();
al_uninstall_joystick();
}
void Framework::Run()
{
#ifdef WRITE_LOG
printf( "Framework: Run.Program Loop\n" );
#endif
// Set BootUp Stage active
ProgramStages->Push( (Stage*)new BootUp() );
while( !quitProgram )
{
ProcessEvents();
}
downloadMgr->Tidy();
}
void Framework::ProcessEvents()
{
ALLEGRO_EVENT e;
FwEvent* fwev;
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.AllegroEvents\n" );
#endif
while( al_get_next_event( eventQueue, &e ) )
{
switch( e.type )
{
case ALLEGRO_EVENT_DISPLAY_CLOSE:
quitProgram = true;
break;
case ALLEGRO_EVENT_JOYSTICK_CONFIGURATION:
al_reconfigure_joysticks();
break;
case ALLEGRO_EVENT_TIMER:
if( e.timer.source == fpsTimer )
{
framesToProcess++;
} else {
fwev = new FwEvent( &e );
ProgramStages->Current()->Event( fwev );
delete fwev;
}
break;
default:
fwev = new FwEvent( &e );
ProgramStages->Current()->Event( fwev );
delete fwev;
}
if( ProgramStages->IsEmpty() )
{
quitProgram = true;
return;
}
}
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.ExtraEvents\n" );
#endif
al_lock_mutex( extraEventsMutex );
while( extraEvents.size() > 0 )
{
fwev = extraEvents.front();
extraEvents.pop_front();
if( fwev->Type == EVENT_DOWNLOAD_COMPLETE )
{
downloadMgr->Event( fwev );
}
ProgramStages->Current()->Event( fwev );
delete fwev;
if( ProgramStages->IsEmpty() )
{
quitProgram = true;
return;
}
}
al_unlock_mutex( extraEventsMutex );
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.Update\n" );
#endif
while( framesToProcess > 0 )
{
if( ProgramStages->IsEmpty() )
{
quitProgram = true;
return;
}
ProgramStages->Current()->Update();
downloadMgr->Update();
networkMgr->Update();
framesToProcess--;
}
// Not bothered if these update every frame, only cache clearing
imageMgr->Update();
fontMgr->Update();
if( musicFilename != "" )
{
audioMgr->GetMusic( musicFilename ); // Prevent uncaching of current music
}
audioMgr->Update();
#ifdef WRITE_LOG
printf( "Framework: ProcessEvents.Render\n" );
#endif
if( !ProgramStages->IsEmpty() )
{
ProgramStages->Current()->Render();
al_flip_display();
}
}
void Framework::PushEvent( FwEvent* e )
{
al_lock_mutex( extraEventsMutex );
extraEvents.push_back( e );
al_unlock_mutex( extraEventsMutex );
}
void Framework::ShutdownFramework()
{
while( !ProgramStages->IsEmpty() )
{
delete ProgramStages->Pop();
}
quitProgram = true;
}
ImageManager* Framework::GetImageManager()
{
return imageMgr;
}
FontManager* Framework::GetFontManager()
{
return fontMgr;
}
AudioManager* Framework::GetAudioManager()
{
return audioMgr;
}
DownloadManager* Framework::GetDownloadManager()
{
return downloadMgr;
}
NetworkManager* Framework::GetNetworkManager()
{
return networkMgr;
}
LanguageManager* Framework::GetLanguageManager()
{
return languageMgr;
}
int Framework::GetDisplayWidth()
{
return al_get_display_width( displaySurface );
}
int Framework::GetDisplayHeight()
{
return al_get_display_height( displaySurface );
}
void Framework::RestoreDisplayTarget()
{
al_set_target_backbuffer( displaySurface );
}
void Framework::PlayMusic( std::string Filename, ALLEGRO_PLAYMODE Mode )
{
#ifdef WRITE_LOG
printf( "Framework: Play Music '%s'\n", Filename.c_str() );
#endif
if( voice != 0 )
{
musicStream = audioMgr->GetMusic( Filename );
if( musicStream != 0 )
{
musicFilename = Filename;
al_set_audio_stream_playmode( musicStream, Mode );
al_attach_audio_stream_to_mixer( musicStream, mixer );
al_set_audio_stream_playing( musicStream, true );
} else {
#ifdef WRITE_LOG
printf( "Framework: Could not load music '%s'\n", Filename.c_str() );
#endif
}
}
}
void Framework::StopMusic()
{
if( voice != 0 && musicStream != 0 )
{
al_set_audio_stream_playing( musicStream, false );
}
musicFilename = "";
}
void Framework::SaveSettings()
{
// Just to keep the filename consistant
Settings->Save( "settings.cfg" );
}
void Framework::SetWindowTitle( std::string* NewTitle )
{
al_set_window_title( displaySurface, NewTitle->c_str() );
}
void Framework::InitialiseAudioSystem()
{
#ifdef WRITE_LOG
printf( "Framework: Initialise Audio\n" );
#endif
voice = 0;
mixer = 0;
if( audioInitialised || al_install_audio() )
{
if( audioInitialised || al_init_acodec_addon() )
{
voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
if( voice != 0 )
{
mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
if( mixer != 0 )
{
al_attach_mixer_to_voice(mixer, voice);
} else {
al_destroy_voice( voice );
voice = 0;
}
}
}
}
}
void Framework::ShutdownAudioSystem()
{
#ifdef WRITE_LOG
printf( "Framework: Shutdown Audio\n" );
#endif
if( mixer != 0 )
{
al_detach_mixer( mixer );
al_destroy_mixer( mixer );
mixer = 0;
}
if( voice != 0 )
{
al_destroy_voice( voice );
voice = 0;
}
}
void Framework::InitialiseDisplay()
{
#ifdef WRITE_LOG
printf( "Framework: Initialise Display\n" );
#endif
int scrW = 800;
int scrH = 480;
bool scrFS = false;
if( Settings->KeyExists( "Visual.ScreenWidth" ) )
{
Settings->GetIntegerValue( "Visual.ScreenWidth", &scrW );
}
if( Settings->KeyExists( "Visual.ScreenHeight" ) )
{
Settings->GetIntegerValue( "Visual.ScreenHeight", &scrH );
}
if( Settings->KeyExists( "Visual.FullScreen" ) )
{
Settings->GetBooleanValue( "Visual.FullScreen", &scrFS );
}
if( scrFS )
{
al_set_new_display_flags( ALLEGRO_FULLSCREEN_WINDOW );
}
al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);
displaySurface = al_create_display( scrW, scrH );
if( displaySurface == 0 )
{
return;
}
al_set_blender( ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA );
al_register_event_source( eventQueue, al_get_display_event_source( displaySurface ) );
}
void Framework::ShutdownDisplay()
{
#ifdef WRITE_LOG
printf( "Framework: Shutdown Display\n" );
#endif
al_unregister_event_source( eventQueue, al_get_display_event_source( displaySurface ) );
fontMgr->Clear();
imageMgr->Clear();
al_destroy_display( displaySurface );
}
| Change shutdown order | Change shutdown order
Display was not closing on Pandora | C++ | mit | pmprog/SkySupreme,pmprog/SkySupreme |
5ebe03d2cf59c48f0346095d91543f914221e296 | include/bbzy_beta/type/function.hpp | include/bbzy_beta/type/function.hpp | #pragma once
#include <type_traits>
#include "../common.hpp"
#include "index_type.hpp"
#include "element_type.hpp"
#include "type_wrapper.hpp"
namespace bbzy {
namespace type {
namespace detail {
template <class FunctionT>
struct UnifiedFunctionType
{
private:
template <class HelperFunT>
struct Helper;
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
typedef RetT(*type)(ParamTs...);
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...)>
{
typedef RetT(*type)(ClassT*, ParamTs...);
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...)const>
{
typedef RetT(*type)(const ClassT*, ParamTs...);
};
public:
typedef typename Helper<Decay<FunctionT>>::type type;
};
//template <class FunctionPointerT>
//struct FunctionUnwrapper
//{
//private:
//
// typedef UnifiedFunctionType<FunctionPointerT> UtifiedFunT;
//
// template <class HelperFunT>
// struct Helper
// {
// using return_type = typename HelperFunT::result_type;
// using class_type = void;
// };
//
// //template <class RetT, class... ParamTs>
// //struct Helper<RetT(ParamTs...)>
// //{
// // using return_type = RetT;
// // using class_type = void;
//
// // using param_types = TypeWrapper<ParamTs...>;
//
// // template <size_t index>
// // using param_type = GetIndexType<index, ParamTs...>;
// // enum { param_count = sizeof...(ParamTs) };
// //};
//
// //template <class RetT, class ClassT, class... ParamTs>
// //struct Helper<RetT(ClassT::*)(ParamTs...)>
// //{
// // using return_type = RetT;
// // using class_type = ClassT;
//
// // using param_types = TypeWrapper<ParamTs...>;
//
// // template <size_t index>
// // using param_type = GetIndexType<index, ParamTs...>;
//
// // enum { param_count = sizeof...(ParamTs) };
// //};
//
// //template <class RetT, class ClassT, class... ParamTs>
// //struct Helper<RetT(ClassT::*)(ParamTs...)const>
// //{
// // using return_type = RetT;
// // using class_type = ClassT;
//
// // using param_types = TypeWrapper<ParamTs...>;
//
// // template <size_t index>
// // using param_type = GetIndexType<index, ParamTs...>;
// // enum { param_count = sizeof...(ParamTs) };
// //};
//
//public:
// typedef Helper<UtifyFunT> fun_type;
//
// typedef typename Helper<UtifyFunT>::return_type return_type;
// typedef typename Helper<UtifyFunT>::class_type class_type;
//
// enum { param_count = Helper<UtifyFunT>::param_count };
//
// using param_types = typename Helper<UtifyFunT>::param_types;
//
// template <size_t index>
// using param_type = typename Helper<UtifyFunT>::template param_type<index>;
//};
template <class FunctionT>
struct GetFunctionParamWrapper
{
private:
template <class HelperFunctionT>
struct Helper;
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
using type = TypeWrapper<ParamTs...>;
};
public:
using type = typename Helper<typename UnifiedFunctionType<FunctionT>::type>::type;
};
template <size_t index, class FunctionT>
struct GetFunctionParamType
{
private:
template <class HelperFunctionT>
struct Helper;
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
using type = typename TypeAt<index, ParamTs...>::type;
};
public:
using type = typename Helper<typename UnifiedFunctionType<FunctionT>::type>::type;
};
template <class MemberFunctionT>
struct GetMemberFunctionClassType
{
using type = EnableIf<IsMemberFunction<MemberFunctionT>::value,
ElemT<typename GetFunctionParamType<0, MemberFunctionT>::type>>;
};
template <class FunctionT>
struct IsFunction
{
private:
using DecayedFunctionT = Decay<FunctionT>;
private:
template <class HelperT>
struct Helper
{
enum {value = 0};
};
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
enum {value = 1};
};
public:
enum {value = Helper<DecayedFunctionT>::value};
};
template <class MemberFunctionT>
struct IsMemberFunction
{
private:
using DecayedMemberFunctionT = Decay<MemberFunctionT>;
private:
template <class HelperT>
struct Helper
{
enum {value = 0};
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...)>
{
enum {value = 1};
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...) const>
{
enum {value = 1};
};
public:
enum {value = Helper<DecayedMemberFunctionT>::value};
};
}
template <class FunctionT>
using UnifiedFunctionType = typename detail::UnifiedFunctionType<FunctionT>::type;
template <class FunctionT>
using UniFunT = UnifiedFunctionType<FunctionT>;
template <class FunctionT>
using GetFunctionParamWrapper = typename detail::GetFunctionParamWrapper<FunctionT>::type;
template <class FunctionT>
using GetFunPW = GetFunctionParamWrapper<FunctionT>;
template <size_t index, class FunctionT>
using GetFunctionParamType = typename detail::GetFunctionParamType<index, FunctionT>::type;
template <size_t index, class FunctionT>
using GetFunPT = GetFunctionParamType<index, FunctionT>;
template <class MemberFunctionT>
using GetMemberFunctionClassType = typename detail::GetMemberFunctionClassType<MemberFunctionT>::type;
template <class FunctionT>
using IsFunction = detail::IsFunction<FunctionT>;
template <class MemberFunctionT>
using IsMemberFunction = detail::IsMemberFunction<MemberFunctionT>;
}
}
| #pragma once
#include <type_traits>
#include "../common.hpp"
#include "index_type.hpp"
#include "element_type.hpp"
#include "type_wrapper.hpp"
namespace bbzy {
namespace type {
namespace detail {
template <class FunctionT>
struct IsFunction
{
private:
using DecayedFunctionT = Decay<FunctionT>;
private:
template <class HelperT>
struct Helper
{
enum {value = 0};
};
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
enum {value = 1};
};
public:
enum {value = Helper<DecayedFunctionT>::value};
};
template <class MemberFunctionT>
struct IsMemberFunction
{
private:
using DecayedMemberFunctionT = Decay<MemberFunctionT>;
private:
template <class HelperT>
struct Helper
{
enum {value = 0};
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...)>
{
enum {value = 1};
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...) const>
{
enum {value = 1};
};
public:
enum {value = Helper<DecayedMemberFunctionT>::value};
};
template <class FunctionT>
struct UnifiedFunctionType
{
private:
template <class HelperFunT>
struct Helper;
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
typedef RetT(*type)(ParamTs...);
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...)>
{
typedef RetT(*type)(ClassT*, ParamTs...);
};
template <class RetT, class ClassT, class... ParamTs>
struct Helper<RetT(ClassT::*)(ParamTs...)const>
{
typedef RetT(*type)(const ClassT*, ParamTs...);
};
public:
typedef typename Helper<Decay<FunctionT>>::type type;
};
//template <class FunctionPointerT>
//struct FunctionUnwrapper
//{
//private:
//
// typedef UnifiedFunctionType<FunctionPointerT> UtifiedFunT;
//
// template <class HelperFunT>
// struct Helper
// {
// using return_type = typename HelperFunT::result_type;
// using class_type = void;
// };
//
// //template <class RetT, class... ParamTs>
// //struct Helper<RetT(ParamTs...)>
// //{
// // using return_type = RetT;
// // using class_type = void;
//
// // using param_types = TypeWrapper<ParamTs...>;
//
// // template <size_t index>
// // using param_type = GetIndexType<index, ParamTs...>;
// // enum { param_count = sizeof...(ParamTs) };
// //};
//
// //template <class RetT, class ClassT, class... ParamTs>
// //struct Helper<RetT(ClassT::*)(ParamTs...)>
// //{
// // using return_type = RetT;
// // using class_type = ClassT;
//
// // using param_types = TypeWrapper<ParamTs...>;
//
// // template <size_t index>
// // using param_type = GetIndexType<index, ParamTs...>;
//
// // enum { param_count = sizeof...(ParamTs) };
// //};
//
// //template <class RetT, class ClassT, class... ParamTs>
// //struct Helper<RetT(ClassT::*)(ParamTs...)const>
// //{
// // using return_type = RetT;
// // using class_type = ClassT;
//
// // using param_types = TypeWrapper<ParamTs...>;
//
// // template <size_t index>
// // using param_type = GetIndexType<index, ParamTs...>;
// // enum { param_count = sizeof...(ParamTs) };
// //};
//
//public:
// typedef Helper<UtifyFunT> fun_type;
//
// typedef typename Helper<UtifyFunT>::return_type return_type;
// typedef typename Helper<UtifyFunT>::class_type class_type;
//
// enum { param_count = Helper<UtifyFunT>::param_count };
//
// using param_types = typename Helper<UtifyFunT>::param_types;
//
// template <size_t index>
// using param_type = typename Helper<UtifyFunT>::template param_type<index>;
//};
template <class FunctionT>
struct GetFunctionParamWrapper
{
private:
template <class HelperFunctionT>
struct Helper;
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
using type = TypeWrapper<ParamTs...>;
};
public:
using type = typename Helper<typename UnifiedFunctionType<FunctionT>::type>::type;
};
template <size_t index, class FunctionT>
struct GetFunctionParamType
{
private:
template <class HelperFunctionT>
struct Helper;
template <class RetT, class... ParamTs>
struct Helper<RetT(*)(ParamTs...)>
{
using type = typename TypeAt<index, ParamTs...>::type;
};
public:
using type = typename Helper<typename UnifiedFunctionType<FunctionT>::type>::type;
};
template <class MemberFunctionT>
struct GetMemberFunctionClassType
{
using type = EnableIf<IsMemberFunction<MemberFunctionT>::value,
ElemT<typename GetFunctionParamType<0, MemberFunctionT>::type>>;
};
}
template <class FunctionT>
using IsFunction = detail::IsFunction<FunctionT>;
template <class MemberFunctionT>
using IsMemberFunction = detail::IsMemberFunction<MemberFunctionT>;
template <class FunctionT>
using UnifiedFunctionType = typename detail::UnifiedFunctionType<FunctionT>::type;
template <class FunctionT>
using UniFunT = UnifiedFunctionType<FunctionT>;
template <class FunctionT>
using GetFunctionParamWrapper = typename detail::GetFunctionParamWrapper<FunctionT>::type;
template <class FunctionT>
using GetFunPW = GetFunctionParamWrapper<FunctionT>;
template <size_t index, class FunctionT>
using GetFunctionParamType = typename detail::GetFunctionParamType<index, FunctionT>::type;
template <size_t index, class FunctionT>
using GetFunPT = GetFunctionParamType<index, FunctionT>;
template <class MemberFunctionT>
using GetMemberFunctionClassType = typename detail::GetMemberFunctionClassType<MemberFunctionT>::type;
}
}
| Move "IsFunction" and "IsMemberFunction" | Move "IsFunction" and "IsMemberFunction"
Move "IsFunction" and "IsMemberFunction" to beginning of the file.
| C++ | apache-2.0 | bbzy/bbzy_beta,bbzy/bbzy_beta |
ef26ebf975ea8cbfa408f3db0a1a69e7feab263d | dvfs/jni/dvfs.cpp | dvfs/jni/dvfs.cpp | #include <jni.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <android/log.h>
#include "cpu/CPUOdroid.h"
#include "gpu/GPUOdroid.h"
#define CLASSNAME "DVFS-ndk"
#define POLL_RATE_IN_MICROSECOND 1000000 //1 second
int fpsLowbound;
int fpsHighBound;
int slidingWindowLength;
bool dvfsInProgress;
pthread_t threadTask;
void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength, bool _isPhoneNexus5);
void * threadFunction(void *arg);
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1);
void runThisRegularly(CPUOdroid * cpu, GPUOdroid * gpu);
extern "C"
JNIEXPORT void JNICALL
Java_com_example_dvfs_DVFSNdk_startDVFS( JNIEnv* env, jobject thiz, jint fpsLowbound, jint fpsHighBound, jint slidingWindowLength, jboolean isPhoneNexus5){
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "lowbound: %d, highbound: %d, slidingWindow: %d, isPhoneNexus5: %d", fpsLowbound, fpsHighBound, slidingWindowLength, isPhoneNexus5);
startDVFS(fpsLowbound, fpsHighBound, slidingWindowLength, isPhoneNexus5);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_dvfs_DVFSNdk_stopDVFS( JNIEnv* env, jobject thiz ){
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Stop DVFS");
dvfsInProgress = false;
}
void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength, bool _isPhoneNexus5){
fpsLowbound = _fpsLowBound;
fpsHighBound = _fpsHighBound;
slidingWindowLength = _slidingWindowLength;
dvfsInProgress = true;
pthread_create(&threadTask, NULL, threadFunction, NULL);
}
//From http://stackoverflow.com/questions/1468596/calculating-elapsed-time-in-a-c-program-in-milliseconds
/* Return 1 if the difference is negative, otherwise 0. */
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1){
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
result->tv_sec = diff / 1000000;
result->tv_usec = diff % 1000000;
return (diff<0);
}
void * threadFunction(void *arg){
CPUOdroid cpu;
GPUOdroid gpu;
struct timeval tvBegin, tvEnd, tvDiff;
while(dvfsInProgress){
gettimeofday(&tvBegin, NULL);
runThisRegularly(&cpu, &gpu);
gettimeofday(&tvEnd, NULL);
timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
int elapsedTime = tvDiff.tv_usec;
//This is to calculate how much time to sleep before the next poll
if(elapsedTime < POLL_RATE_IN_MICROSECOND){
int timeToSleep = POLL_RATE_IN_MICROSECOND - elapsedTime;
usleep(timeToSleep);
}
}
return NULL;
}
void runThisRegularly(CPUOdroid * cpu, GPUOdroid * gpu){
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Thread run");
// float util[NUM_CORES];
// cpu->getCPUUtil(util);
// __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Util %f %f %f %f", util[0], util[1], util[2], util[3]);
int fps = gpu->getFPS();
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "FPS %d", fps);
}
| #include <jni.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <android/log.h>
#include "cpu/CPUOdroid.h"
#include "gpu/GPUOdroid.h"
#define CLASSNAME "DVFS-ndk"
#define POLL_RATE_IN_MICROSECOND 1000000 //1 second
#define DO_NOT_PURSUE_FPS_VALUE -1
int fpsLowBound;
int fpsHighBound;
int slidingWindowLength;
bool dvfsInProgress;
int currentSlidingWindowPosition;
pthread_t threadTask;
void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength, bool _isPhoneNexus5);
void * threadFunction(void *arg);
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1);
int shouldPursueFPSRecalculationToThisFPS(int fps);
void processInputs(int currentFPS, int newFPSValue, bool fpsInRange);
void runThisRegularly(CPUOdroid * cpu, GPUOdroid * gpu);
extern "C"
JNIEXPORT void JNICALL
Java_com_example_dvfs_DVFSNdk_startDVFS( JNIEnv* env, jobject thiz, jint fpsLowbound, jint fpsHighBound, jint slidingWindowLength, jboolean isPhoneNexus5){
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "lowbound: %d, highbound: %d, slidingWindow: %d, isPhoneNexus5: %d", fpsLowbound, fpsHighBound, slidingWindowLength, isPhoneNexus5);
startDVFS(fpsLowbound, fpsHighBound, slidingWindowLength, isPhoneNexus5);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_dvfs_DVFSNdk_stopDVFS( JNIEnv* env, jobject thiz ){
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Stop DVFS");
dvfsInProgress = false;
}
void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength, bool _isPhoneNexus5){
fpsLowBound = _fpsLowBound;
fpsHighBound = _fpsHighBound;
slidingWindowLength = _slidingWindowLength;
dvfsInProgress = true;
pthread_create(&threadTask, NULL, threadFunction, NULL);
}
//From http://stackoverflow.com/questions/1468596/calculating-elapsed-time-in-a-c-program-in-milliseconds
/* Return 1 if the difference is negative, otherwise 0. */
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1){
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
result->tv_sec = diff / 1000000;
result->tv_usec = diff % 1000000;
return (diff<0);
}
void * threadFunction(void *arg){
CPUOdroid cpu;
GPUOdroid gpu;
struct timeval tvBegin, tvEnd, tvDiff;
while(dvfsInProgress){
gettimeofday(&tvBegin, NULL);
runThisRegularly(&cpu, &gpu);
gettimeofday(&tvEnd, NULL);
timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
int elapsedTime = tvDiff.tv_usec;
//This is to calculate how much time to sleep before the next poll
if(elapsedTime < POLL_RATE_IN_MICROSECOND){
int timeToSleep = POLL_RATE_IN_MICROSECOND - elapsedTime;
usleep(timeToSleep);
}
}
return NULL;
}
int shouldPursueFPSRecalculationToThisFPS(int fps){
if(fps > fpsHighBound){
//We need to decrease FPS
return fpsLowBound;
} else if(fps < fpsLowBound){
//We need to increase FPS
return fpsHighBound;
} else {
currentSlidingWindowPosition = 0;
return DO_NOT_PURSUE_FPS_VALUE;
}
}
void runThisRegularly(CPUOdroid * cpu, GPUOdroid * gpu){
// float util[NUM_CORES];
// cpu->getCPUUtil(util);
// __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Util %f %f %f %f", util[0], util[1], util[2], util[3]);
int currentFPS = gpu->getFPS();
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "FPS %d", currentFPS);
if(currentFPS != NO_FPS_CALCULATED){
int newValueFPS = shouldPursueFPSRecalculationToThisFPS(currentFPS);
if(newValueFPS == DO_NOT_PURSUE_FPS_VALUE){
processInputs(currentFPS, currentFPS, true);
} else {
processInputs(currentFPS, newValueFPS, false);
}
}
}
void processInputs(int currentFPS, int newFPSValue, bool fpsInRange){
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Current FPS: %d, target FPS: %d", currentFPS, newFPSValue);
//makeCPUMeetThisFPS(newFPSValue, currentFPS);
if(fpsInRange){
return;
}
__android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Outside range, sliding window increased");
currentSlidingWindowPosition++;
if(currentSlidingWindowPosition > slidingWindowLength){
currentSlidingWindowPosition = 0;
//makeGPUMeetThisFPS(newFPSValue, currentFPS);
}
}
| prepare for CPU and GPU adjustment | prepare for CPU and GPU adjustment
| C++ | mit | yeokm1/dvfs,yeokm1/dvfs |
308eb34d050343ceeaa7d921e1f92366be804896 | src/test_module.cpp | src/test_module.cpp |
#include <chaiscript/chaiscript.hpp>
#include <string>
class TestBaseType
{
public:
TestBaseType() : val(10), const_val(15) { }
TestBaseType(int) : val(10), const_val(15) {}
TestBaseType(int *) : val(10), const_val(15) {}
virtual ~TestBaseType() {}
virtual int func() { return 0; }
int base_only_func() { return -9; }
const TestBaseType &constMe() const { return *this; }
int val;
const int const_val;
private:
TestBaseType &operator=(const TestBaseType &);
};
enum TestEnum
{
TestValue1 = 1
};
int to_int(TestEnum t)
{
return t;
}
class TestDerivedType : public TestBaseType
{
public:
virtual ~TestDerivedType() {}
virtual int func() CHAISCRIPT_OVERRIDE { return 1; }
int derived_only_func() { return 19; }
private:
TestDerivedType &operator=(const TestDerivedType &);
};
class TestMoreDerivedType : public TestDerivedType
{
public:
virtual ~TestMoreDerivedType() {}
};
std::shared_ptr<TestBaseType> derived_type_factory()
{
return std::make_shared<TestDerivedType>();
}
std::shared_ptr<TestBaseType> more_derived_type_factory()
{
return std::make_shared<TestBaseType>();
}
std::shared_ptr<TestBaseType> null_factory()
{
return std::shared_ptr<TestBaseType>();
}
std::string hello_world()
{
return "Hello World";
}
int *get_new_int()
{
return new int(1);
}
// MSVC doesn't like that we are using C++ return types from our C declared module
// but this is the best way to do it for cross platform compatibility
#ifdef CHAISCRIPT_MSVC
#pragma warning(push)
#pragma warning(disable : 4190)
#endif
#ifdef __llvm__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
#endif
CHAISCRIPT_MODULE_EXPORT chaiscript::ModulePtr create_chaiscript_module_test_module()
{
chaiscript::ModulePtr m(new chaiscript::Module());
m->add(chaiscript::fun(hello_world), "hello_world");
m->add(chaiscript::user_type<TestBaseType>(), "TestBaseType");
m->add(chaiscript::user_type<TestDerivedType>(), "TestDerivedType");
m->add(chaiscript::user_type<TestMoreDerivedType>(), "TestMoreDerivedType");
m->add(chaiscript::constructor<TestBaseType ()>(), "TestBaseType");
// m->add(chaiscript::constructor<TestBaseType (int)>(), "TestBaseType");
m->add(chaiscript::constructor<TestBaseType (const TestBaseType &)>(), "TestBaseType");
m->add(chaiscript::constructor<TestBaseType (int *)>(), "TestBaseType");
m->add(chaiscript::constructor<TestDerivedType ()>(), "TestDerivedType");
m->add(chaiscript::constructor<TestDerivedType (const TestDerivedType &)>(), "TestDerivedType");
m->add(chaiscript::constructor<TestMoreDerivedType ()>(), "TestMoreDerivedType");
m->add(chaiscript::constructor<TestMoreDerivedType (const TestMoreDerivedType &)>(), "TestMoreDerivedType");
/// \todo automatic chaining of base classes?
m->add(chaiscript::base_class<TestBaseType, TestDerivedType>());
m->add(chaiscript::base_class<TestBaseType, TestMoreDerivedType>());
m->add(chaiscript::base_class<TestDerivedType, TestMoreDerivedType>());
m->add(chaiscript::fun(&TestDerivedType::derived_only_func), "derived_only_func");
m->add(chaiscript::fun(&derived_type_factory), "derived_type_factory");
m->add(chaiscript::fun(&more_derived_type_factory), "more_derived_type_factory");
m->add(chaiscript::fun(&null_factory), "null_factory");
m->add(chaiscript::fun(&TestDerivedType::func), "func");
m->add(chaiscript::fun(&TestBaseType::func), "func");
m->add(chaiscript::fun(&TestBaseType::val), "val");
m->add(chaiscript::fun(&TestBaseType::const_val), "const_val");
m->add(chaiscript::fun(&TestBaseType::base_only_func), "base_only_func");
m->add(chaiscript::fun(&get_new_int), "get_new_int");
m->add_global_const(chaiscript::const_var(TestValue1), "TestValue1");
m->add(chaiscript::user_type<TestEnum>(), "TestEnum");
m->add(chaiscript::fun(&to_int), "to_int");
m->add(chaiscript::fun(&TestBaseType::constMe), "constMe");
return m;
}
#ifdef __llvm__
#pragma clang diagnostic pop
#endif
#ifdef CHAISCRIPT_MSVC
#pragma warning(pop)
#endif
|
#include <chaiscript/chaiscript.hpp>
#include <string>
class TestBaseType
{
public:
TestBaseType() : val(10), const_val(15) { }
TestBaseType(int) : val(10), const_val(15) {}
TestBaseType(int *) : val(10), const_val(15) {}
virtual ~TestBaseType() {}
virtual int func() { return 0; }
int base_only_func() { return -9; }
const TestBaseType &constMe() const { return *this; }
int val;
const int const_val;
private:
TestBaseType &operator=(const TestBaseType &);
};
enum TestEnum
{
TestValue1 = 1
};
int to_int(TestEnum t)
{
return t;
}
class TestDerivedType : public TestBaseType
{
public:
virtual ~TestDerivedType() {}
virtual int func() CHAISCRIPT_OVERRIDE { return 1; }
int derived_only_func() { return 19; }
private:
TestDerivedType &operator=(const TestDerivedType &);
};
class TestMoreDerivedType : public TestDerivedType
{
public:
virtual ~TestMoreDerivedType() {}
};
std::shared_ptr<TestBaseType> derived_type_factory()
{
return std::make_shared<TestDerivedType>();
}
std::shared_ptr<TestBaseType> more_derived_type_factory()
{
return std::make_shared<TestMoreDerivedType>();
}
std::shared_ptr<TestBaseType> null_factory()
{
return std::shared_ptr<TestBaseType>();
}
std::string hello_world()
{
return "Hello World";
}
int *get_new_int()
{
return new int(1);
}
// MSVC doesn't like that we are using C++ return types from our C declared module
// but this is the best way to do it for cross platform compatibility
#ifdef CHAISCRIPT_MSVC
#pragma warning(push)
#pragma warning(disable : 4190)
#endif
#ifdef __llvm__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
#endif
CHAISCRIPT_MODULE_EXPORT chaiscript::ModulePtr create_chaiscript_module_test_module()
{
chaiscript::ModulePtr m(new chaiscript::Module());
m->add(chaiscript::fun(hello_world), "hello_world");
m->add(chaiscript::user_type<TestBaseType>(), "TestBaseType");
m->add(chaiscript::user_type<TestDerivedType>(), "TestDerivedType");
m->add(chaiscript::user_type<TestMoreDerivedType>(), "TestMoreDerivedType");
m->add(chaiscript::constructor<TestBaseType ()>(), "TestBaseType");
// m->add(chaiscript::constructor<TestBaseType (int)>(), "TestBaseType");
m->add(chaiscript::constructor<TestBaseType (const TestBaseType &)>(), "TestBaseType");
m->add(chaiscript::constructor<TestBaseType (int *)>(), "TestBaseType");
m->add(chaiscript::constructor<TestDerivedType ()>(), "TestDerivedType");
m->add(chaiscript::constructor<TestDerivedType (const TestDerivedType &)>(), "TestDerivedType");
m->add(chaiscript::constructor<TestMoreDerivedType ()>(), "TestMoreDerivedType");
m->add(chaiscript::constructor<TestMoreDerivedType (const TestMoreDerivedType &)>(), "TestMoreDerivedType");
/// \todo automatic chaining of base classes?
m->add(chaiscript::base_class<TestBaseType, TestDerivedType>());
m->add(chaiscript::base_class<TestBaseType, TestMoreDerivedType>());
m->add(chaiscript::base_class<TestDerivedType, TestMoreDerivedType>());
m->add(chaiscript::fun(&TestDerivedType::derived_only_func), "derived_only_func");
m->add(chaiscript::fun(&derived_type_factory), "derived_type_factory");
m->add(chaiscript::fun(&more_derived_type_factory), "more_derived_type_factory");
m->add(chaiscript::fun(&null_factory), "null_factory");
m->add(chaiscript::fun(&TestDerivedType::func), "func");
m->add(chaiscript::fun(&TestBaseType::func), "func");
m->add(chaiscript::fun(&TestBaseType::val), "val");
m->add(chaiscript::fun(&TestBaseType::const_val), "const_val");
m->add(chaiscript::fun(&TestBaseType::base_only_func), "base_only_func");
m->add(chaiscript::fun(&get_new_int), "get_new_int");
m->add_global_const(chaiscript::const_var(TestValue1), "TestValue1");
m->add(chaiscript::user_type<TestEnum>(), "TestEnum");
m->add(chaiscript::fun(&to_int), "to_int");
m->add(chaiscript::fun(&TestBaseType::constMe), "constMe");
return m;
}
#ifdef __llvm__
#pragma clang diagnostic pop
#endif
#ifdef CHAISCRIPT_MSVC
#pragma warning(pop)
#endif
| Correct test_module changes | Correct test_module changes
| C++ | bsd-3-clause | bradparks/ChaiScript__cplusplus_scripting_language,kamilzubair/ChaiScript,bradparks/ChaiScript__cplusplus_scripting_language,bradparks/ChaiScript__cplusplus_scripting_language,kamilzubair/ChaiScript,kamilzubair/ChaiScript |
cfec925fbc33a9dcbeef9eb759ce87516b7565b9 | thcrap/src/global.cpp | thcrap/src/global.cpp | /**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Globals, compile-time constants and runconfig abstractions.
*/
#include "thcrap.h"
CRITICAL_SECTION cs_file_access;
json_t* run_cfg = NULL;
const char* PROJECT_NAME(void)
{
return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
return "thcrap";
}
DWORD PROJECT_VERSION(void)
{
return 0x20180330;
}
const char* PROJECT_VERSION_STRING(void)
{
static char ver_str[11] = {0};
if(!ver_str[0]) {
str_hexdate_format(ver_str, PROJECT_VERSION());
}
return ver_str;
}
json_t* runconfig_get(void)
{
return run_cfg;
}
void runconfig_set(json_t *new_run_cfg)
{
json_decref(run_cfg);
run_cfg = json_incref(new_run_cfg);
}
const json_t *runconfig_title_get(void)
{
const json_t *id = json_object_get(run_cfg, "game");
const json_t *title = strings_get(json_string_value(id));
if(!title) {
title = json_object_get(run_cfg, "title");
}
return title ? title : (id ? id : NULL);
}
| /**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Globals, compile-time constants and runconfig abstractions.
*/
#include "thcrap.h"
CRITICAL_SECTION cs_file_access;
json_t* run_cfg = NULL;
const char* PROJECT_NAME(void)
{
return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
return "thcrap";
}
DWORD PROJECT_VERSION(void)
{
return 0x20180402;
}
const char* PROJECT_VERSION_STRING(void)
{
static char ver_str[11] = {0};
if(!ver_str[0]) {
str_hexdate_format(ver_str, PROJECT_VERSION());
}
return ver_str;
}
json_t* runconfig_get(void)
{
return run_cfg;
}
void runconfig_set(json_t *new_run_cfg)
{
json_decref(run_cfg);
run_cfg = json_incref(new_run_cfg);
}
const json_t *runconfig_title_get(void)
{
const json_t *id = json_object_get(run_cfg, "game");
const json_t *title = strings_get(json_string_value(id));
if(!title) {
title = json_object_get(run_cfg, "title");
}
return title ? title : (id ? id : NULL);
}
| Update version number | Update version number
| C++ | unlicense | thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap,thpatch/thcrap |
1e148014cbcc815c55c4f00ab7487e1ec0c090b7 | E_Libs/StdLib.cpp | E_Libs/StdLib.cpp | // StdLib.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "StdLib.h"
#include "../EScript/EScript.h"
#include "../EScript/Parser/Parser.h"
#include "../EScript/Utils/FileUtils.h"
#include "ext/JSON.h"
#include <sstream>
#include <stdlib.h>
#include <ctime>
using namespace EScript;
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if (!o) return;
if (level>maxLevel) {
std::cout << " ... \n";
return;
}
if (Array * a=dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef=a->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "]";
} else if (Map * m=dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef=m->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)
std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "}";
} else {
if (dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const identifierId seachPathsId=stringToIdentifierId("__searchPaths");
std::string file(FileUtils::condensePath(filename));
if( FileUtils::isFile(file)!=1 ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId))){
for(ERef<Iterator> itRef=searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(FileUtils::condensePath(valueRef.toString()+"/"+filename));
if( FileUtils::isFile(s)==1 ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
Object * StdLib::load(Runtime & runtime,const std::string & filename){
ERef<Block> bRef(new Block());
try {
bRef=EScript::loadScriptFile(findFile(runtime,filename),bRef.get());
} catch (Exception * e) {
runtime.setExceptionState(e);
}
if (bRef.isNull())
return NULL;
ObjRef resultRef(runtime.executeObj(bRef.get()));
/* reset the Block at this point is important as it might hold a reference to the result, which may then
be destroyed when the function is left after the resultRef-reference has already been decreased. */
bRef = NULL;
if(runtime.getState() == Runtime::STATE_RETURNING){
resultRef=runtime.getResult();
runtime.resetState();
return resultRef.detachAndDecrease();
}
return NULL;
}
//! (static)
Object * StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const identifierId mapId=stringToIdentifierId("__loadOnce_loadedFiles");
std::string condensedFilename( FileUtils::condensePath(findFile(runtime,filename)) );
Map * m=dynamic_cast<Map*>(runtime.getAttribute(mapId));
if(m==NULL){
m=Map::create();
runtime.setObjAttribute(mapId,m);
}
ObjRef obj=m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return NULL;
}
m->setValue(String::create(condensedFilename),Bool::create(true));
return load(runtime,condensedFilename);
}
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION_DECLARE(globals,"addSearchPath",1,1,{
static const identifierId seachPathsId=stringToIdentifierId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId));
if(searchPaths == NULL){
searchPaths = Array::create();
runtime.setObjAttribute(seachPathsId,searchPaths);
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return Void::get();
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION_DECLARE(globals,"assert",1,2, {
assertParamCount(runtime,parameter.count(),1,2);
if(!parameter[0]->toBool()){
runtime.exception(parameter.count()>1?parameter[1]->toString():"Assert failed.");
}
return NULL;
})
//! [ESF] string chr(number)
ES_FUNCTION_DECLARE(globals,"chr",1,1,{
std::ostringstream s;
s<< static_cast<char>(parameter[0]->toInt());
return String::create(s.str());
})
//! [ESF] number clock()
ESF_DECLARE(globals,"clock",0,0,Number::create( static_cast<double>(clock())/CLOCKS_PER_SEC))
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION_DECLARE(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(0):static_cast<time_t>(parameter[0]->toInt());
tm *d=localtime (& t );
Map * m=Map::create();
m->setValue(String::create("seconds"),Number::create(d->tm_sec));
m->setValue(String::create("minutes"),Number::create(d->tm_min));
m->setValue(String::create("hours"),Number::create(d->tm_hour));
m->setValue(String::create("mday"),Number::create(d->tm_mday));
m->setValue(String::create("mon"),Number::create(d->tm_mon+1));
m->setValue(String::create("year"),Number::create(d->tm_year+1900));
m->setValue(String::create("wday"),Number::create(d->tm_wday));
m->setValue(String::create("yday"),Number::create(d->tm_yday));
m->setValue(String::create("isdst"),Number::create(d->tm_isdst));
return m;
})
//! [ESF] string getOS()
ESF_DECLARE(globals,"getOS",0,0,String::create(StdLib::getOS()))
//! [ESF] Runtime getRuntime( )
ESF_DECLARE(globals,"getRuntime",0,0, &runtime)
//! [ESF] mixed load(string filename)
ESF_DECLARE(globals,"load",1,1,StdLib::load(runtime,parameter[0].toString()))
//! [ESF] mixed loadOnce(string filename)
ESF_DECLARE(globals,"loadOnce",1,1,StdLib::loadOnce(runtime,parameter[0].toString()))
//! [ESF] void out(...)
ES_FUNCTION_DECLARE(globals,"out",0,-1, {
for(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it)
std::cout << (*it).toString();
std::cout.flush();
return NULL;
})
//! [ESF] Block parse(string)
ES_FUNCTION_DECLARE(globals,"parse",1,1, {
assertParamCount(runtime,parameter.count(),1,1);
ERef<Block> bRef(new Block());
ERef<Parser> pRef(new Parser());
try{
pRef->parse(bRef.get(),parameter[0]->toString().c_str());
}catch(Object * e){
runtime.setExceptionState(e);
}
return bRef.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ESF_DECLARE(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION_DECLARE(globals,"print_r",0,-1, {
std::cout << "\n";
for(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it) {
if (!(*it).isNull())
print_r((*it).get());
}
return NULL;
})
//! [ESF] number system(command)
ESF_DECLARE(globals,"system",1,1,Number::create(system(parameter[0]->toString().c_str())))
//! [ESF] number time()
ESF_DECLARE(globals,"time",0,0,Number::create(static_cast<double>(time(NULL))))
//! [ESF] string toJSON(obj[,formatted=true])
ESF_DECLARE(globals,"toJSON",1,2,String::create(JSON::toJSON(parameter[0].get(),parameter[1].toBool(true))))
}
| // StdLib.cpp
// This file is part of the EScript programming language.
// See copyright notice in EScript.h
// ------------------------------------------------------
#include "StdLib.h"
#include "../EScript/EScript.h"
#include "../EScript/Parser/Parser.h"
#include "../EScript/Utils/FileUtils.h"
#include "ext/JSON.h"
#include <sstream>
#include <stdlib.h>
#include <ctime>
#if defined(__linux__)
#include <unistd.h>
#endif
using namespace EScript;
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if (!o) return;
if (level>maxLevel) {
std::cout << " ... \n";
return;
}
if (Array * a=dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef=a->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "]";
} else if (Map * m=dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef=m->getIterator();
int nr=0;
while (!itRef->end()) {
ObjRef valueRef=itRef->value();
ObjRef keyRef=itRef->key();
if (nr++>0)
std::cout << ",\n";
if (!valueRef.isNull()) {
for (int i=0;i<level;i++)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for (int i=0;i<level-1;i++)
std::cout << "\t";
std::cout << "}";
} else {
if (dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const identifierId seachPathsId=stringToIdentifierId("__searchPaths");
std::string file(FileUtils::condensePath(filename));
if( FileUtils::isFile(file)!=1 ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId))){
for(ERef<Iterator> itRef=searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(FileUtils::condensePath(valueRef.toString()+"/"+filename));
if( FileUtils::isFile(s)==1 ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
Object * StdLib::load(Runtime & runtime,const std::string & filename){
ERef<Block> bRef(new Block());
try {
bRef=EScript::loadScriptFile(findFile(runtime,filename),bRef.get());
} catch (Exception * e) {
runtime.setExceptionState(e);
}
if (bRef.isNull())
return NULL;
ObjRef resultRef(runtime.executeObj(bRef.get()));
/* reset the Block at this point is important as it might hold a reference to the result, which may then
be destroyed when the function is left after the resultRef-reference has already been decreased. */
bRef = NULL;
if(runtime.getState() == Runtime::STATE_RETURNING){
resultRef=runtime.getResult();
runtime.resetState();
return resultRef.detachAndDecrease();
}
return NULL;
}
//! (static)
Object * StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const identifierId mapId=stringToIdentifierId("__loadOnce_loadedFiles");
std::string condensedFilename( FileUtils::condensePath(findFile(runtime,filename)) );
Map * m=dynamic_cast<Map*>(runtime.getAttribute(mapId));
if(m==NULL){
m=Map::create();
runtime.setObjAttribute(mapId,m);
}
ObjRef obj=m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return NULL;
}
m->setValue(String::create(condensedFilename),Bool::create(true));
return load(runtime,condensedFilename);
}
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION_DECLARE(globals,"addSearchPath",1,1,{
static const identifierId seachPathsId=stringToIdentifierId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId));
if(searchPaths == NULL){
searchPaths = Array::create();
runtime.setObjAttribute(seachPathsId,searchPaths);
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return Void::get();
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION_DECLARE(globals,"assert",1,2, {
assertParamCount(runtime,parameter.count(),1,2);
if(!parameter[0]->toBool()){
runtime.exception(parameter.count()>1?parameter[1]->toString():"Assert failed.");
}
return NULL;
})
//! [ESF] string chr(number)
ES_FUNCTION_DECLARE(globals,"chr",1,1,{
std::ostringstream s;
s<< static_cast<char>(parameter[0]->toInt());
return String::create(s.str());
})
//! [ESF] number clock()
ESF_DECLARE(globals,"clock",0,0,Number::create( static_cast<double>(clock())/CLOCKS_PER_SEC))
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION_DECLARE(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(0):static_cast<time_t>(parameter[0]->toInt());
tm *d=localtime (& t );
Map * m=Map::create();
m->setValue(String::create("seconds"),Number::create(d->tm_sec));
m->setValue(String::create("minutes"),Number::create(d->tm_min));
m->setValue(String::create("hours"),Number::create(d->tm_hour));
m->setValue(String::create("mday"),Number::create(d->tm_mday));
m->setValue(String::create("mon"),Number::create(d->tm_mon+1));
m->setValue(String::create("year"),Number::create(d->tm_year+1900));
m->setValue(String::create("wday"),Number::create(d->tm_wday));
m->setValue(String::create("yday"),Number::create(d->tm_yday));
m->setValue(String::create("isdst"),Number::create(d->tm_isdst));
return m;
})
//! [ESF] string getOS()
ESF_DECLARE(globals,"getOS",0,0,String::create(StdLib::getOS()))
//! [ESF] Runtime getRuntime( )
ESF_DECLARE(globals,"getRuntime",0,0, &runtime)
//! [ESF] mixed load(string filename)
ESF_DECLARE(globals,"load",1,1,StdLib::load(runtime,parameter[0].toString()))
//! [ESF] mixed loadOnce(string filename)
ESF_DECLARE(globals,"loadOnce",1,1,StdLib::loadOnce(runtime,parameter[0].toString()))
//! [ESF] void out(...)
ES_FUNCTION_DECLARE(globals,"out",0,-1, {
for(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it)
std::cout << (*it).toString();
std::cout.flush();
return NULL;
})
//! [ESF] Block parse(string)
ES_FUNCTION_DECLARE(globals,"parse",1,1, {
assertParamCount(runtime,parameter.count(),1,1);
ERef<Block> bRef(new Block());
ERef<Parser> pRef(new Parser());
try{
pRef->parse(bRef.get(),parameter[0]->toString().c_str());
}catch(Object * e){
runtime.setExceptionState(e);
}
return bRef.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ESF_DECLARE(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION_DECLARE(globals,"print_r",0,-1, {
std::cout << "\n";
for(ParameterValues::const_iterator it=parameter.begin();it!=parameter.end();++it) {
if (!(*it).isNull())
print_r((*it).get());
}
return NULL;
})
//! [ESF] number system(command)
ESF_DECLARE(globals,"system",1,1,Number::create(system(parameter[0]->toString().c_str())))
#if defined(__linux__)
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION_DECLARE(globals, "exec", 2, 2, {
Array * array = assertType<Array>(runtime, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = NULL;
Number * result = Number::create(execv(parameter[0]->toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
#endif
//! [ESF] number time()
ESF_DECLARE(globals,"time",0,0,Number::create(static_cast<double>(time(NULL))))
//! [ESF] string toJSON(obj[,formatted=true])
ESF_DECLARE(globals,"toJSON",1,2,String::create(JSON::toJSON(parameter[0].get(),parameter[1].toBool(true))))
}
| Implement exec for Linux. | Implement exec for Linux.
git-svn-id: 5b5650fabc8463890bae0d4440114b12dedf0983@99 5693b1fc-3b75-4070-9b6b-3ce3692a40d5
| C++ | mit | ClaudiusJ/EScript,eikel/EScript,ClaudiusJ/EScript,EScript/EScript,EScript/EScript,eikel/EScript |
91f2ab14218fdafa2f359cd462cdd457d941fc99 | cint/cling/lib/MetaProcessor/MetaProcessor.cpp | cint/cling/lib/MetaProcessor/MetaProcessor.cpp | //------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Frontend/CompilerInstance.h"
#include <cstdio>
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
const char cmd_char = input_line[1];
// .q //Quits
if (cmd_char == 'q') {
m_Options.Quitting = true;
return true;
}
// Extract command and parameter:
// .command parameter
std::string cmd = input_line.substr(1, std::string::npos);
std::string param;
std::string::size_type endcmd = input_line.find_first_of(" \t\n", 2);
if (endcmd != std::string::npos) { // have a blank after command
cmd = input_line.substr(1, endcmd - 1);
std::string::size_type firstparam = input_line.find_first_not_of(" \t\n", endcmd);
std::string::size_type lastparam = input_line.find_last_not_of(" \t\n");
if (firstparam != std::string::npos) { // have a parameter
//
// Trim blanks from beginning and ending of parameter.
//
std::string::size_type len = (lastparam + 1) - firstparam;
// Construct our parameter.
param = input_line.substr(firstparam, len);
}
}
// .L <filename> // Load code fragment.
if (cmd_char == 'L') {
bool success = m_Interp.loadFile(param);
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
if ((cmd_char == 'x') || (cmd_char == 'X')) {
bool success = executeFile(param, result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
if (cmd == "printAST") {
if (param.empty()) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< print?"P":"Not p" << "rinting AST\n";
} else if (param == "1") {
m_Interp.enablePrintAST(true);
} else if (param == "0") {
m_Interp.enablePrintAST(false);
} else {
llvm::errs()<< ".printAST: parameter must be '0' or '1' or nothing\n";
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
if (cmd == "rawInput") {
if (param.empty()) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << m_Options.RawInput?"U":"Not u" << "sing raw input\n";
} else if (param == "1") {
m_Options.RawInput = true;
} else if (param == "0") {
m_Options.RawInput = false;
} else {
llvm::errs()<< ".rawInput: parameter must be '0' or '1' or nothing\n";
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
if (cmd_char == 'I') {
if (!param.empty())
m_Interp.AddIncludePath(param.c_str());
else {
m_Interp.DumpIncludePath();
}
return true;
}
// Cancel the multiline input that has been requested
if (cmd_char == '@') {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
if (cmd == "dynamicExtensions") {
if (param.empty()) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << dynlookup?"U":"Not u" <<"sing dynamic lookup extensions\n"
} else if (param == "1") {
m_Interp.enableDynamicLookup(true);
} else if (param == "0") {
m_Interp.enableDynamicLookup(false);
} else {
llvm::errs() << ".dynamicExtensions: param must be '0' or '1' or ";
llvm::errs() << "nothing\n"
}
return true;
}
return false;
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
//fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());
Interpreter::CompilationResult interpRes
= m_Interp.processLine(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""), true /*raw*/);
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
| //------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <[email protected]>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Frontend/CompilerInstance.h"
#include <cstdio>
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
m_Interp.processLine(input, m_Options.RawInput, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
const char cmd_char = input_line[1];
// .q //Quits
if (cmd_char == 'q') {
m_Options.Quitting = true;
return true;
}
// Extract command and parameter:
// .command parameter
std::string cmd = input_line.substr(1, std::string::npos);
std::string param;
std::string::size_type endcmd = input_line.find_first_of(" \t\n", 2);
if (endcmd != std::string::npos) { // have a blank after command
cmd = input_line.substr(1, endcmd - 1);
std::string::size_type firstparam = input_line.find_first_not_of(" \t\n", endcmd);
std::string::size_type lastparam = input_line.find_last_not_of(" \t\n");
if (firstparam != std::string::npos) { // have a parameter
//
// Trim blanks from beginning and ending of parameter.
//
std::string::size_type len = (lastparam + 1) - firstparam;
// Construct our parameter.
param = input_line.substr(firstparam, len);
}
}
// .L <filename> // Load code fragment.
if (cmd_char == 'L') {
bool success = m_Interp.loadFile(param);
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
if ((cmd_char == 'x') || (cmd_char == 'X')) {
bool success = executeFile(param, result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
if (cmd == "printAST") {
if (param.empty()) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else if (param == "1") {
m_Interp.enablePrintAST(true);
} else if (param == "0") {
m_Interp.enablePrintAST(false);
} else {
llvm::errs()<< ".printAST: parameter must be '0' or '1' or nothing\n";
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
if (cmd == "rawInput") {
if (param.empty()) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else if (param == "1") {
m_Options.RawInput = true;
} else if (param == "0") {
m_Options.RawInput = false;
} else {
llvm::errs()<< ".rawInput: parameter must be '0' or '1' or nothing\n";
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
if (cmd_char == 'I') {
if (!param.empty())
m_Interp.AddIncludePath(param.c_str());
else {
m_Interp.DumpIncludePath();
}
return true;
}
// Cancel the multiline input that has been requested
if (cmd_char == '@') {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
if (cmd == "dynamicExtensions") {
if (param.empty()) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else if (param == "1") {
m_Interp.enableDynamicLookup(true);
} else if (param == "0") {
m_Interp.enableDynamicLookup(false);
} else {
llvm::errs() << ".dynamicExtensions: param must be '0' or '1' or ";
llvm::errs() << "nothing\n";
}
return true;
}
return false;
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
//fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());
Interpreter::CompilationResult interpRes
= m_Interp.processLine(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""), true /*raw*/);
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
| Use llvm::errs() where possible | Use llvm::errs() where possible
git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@43437 27541ba8-7e3a-0410-8455-c3a389f83636
| C++ | lgpl-2.1 | bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT |
eb30c15b7ef15662e96b4a9bdb840b48ab47be83 | clang-tidy/google/ExplicitConstructorCheck.cpp | clang-tidy/google/ExplicitConstructorCheck.cpp | //===--- ExplicitConstructorCheck.cpp - clang-tidy ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ExplicitConstructorCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace google {
void ExplicitConstructorCheck::registerMatchers(MatchFinder *Finder) {
// Only register the matchers for C++; the functionality currently does not
// provide any benefit to other languages, despite being benign.
if (!getLangOpts().CPlusPlus)
return;
Finder->addMatcher(cxxConstructorDecl(unless(isInstantiated())).bind("ctor"),
this);
Finder->addMatcher(
cxxConversionDecl(unless(anyOf(isExplicit(), // Already marked explicit.
isImplicit(), // Compiler-generated.
isDeleted(), isInstantiated())))
.bind("conversion"),
this);
}
// Looks for the token matching the predicate and returns the range of the found
// token including trailing whitespace.
static SourceRange FindToken(const SourceManager &Sources,
const LangOptions &LangOpts,
SourceLocation StartLoc, SourceLocation EndLoc,
bool (*Pred)(const Token &)) {
if (StartLoc.isMacroID() || EndLoc.isMacroID())
return SourceRange();
FileID File = Sources.getFileID(Sources.getSpellingLoc(StartLoc));
StringRef Buf = Sources.getBufferData(File);
const char *StartChar = Sources.getCharacterData(StartLoc);
Lexer Lex(StartLoc, LangOpts, StartChar, StartChar, Buf.end());
Lex.SetCommentRetentionState(true);
Token Tok;
do {
Lex.LexFromRawLexer(Tok);
if (Pred(Tok)) {
Token NextTok;
Lex.LexFromRawLexer(NextTok);
return SourceRange(Tok.getLocation(), NextTok.getLocation());
}
} while (Tok.isNot(tok::eof) && Tok.getLocation() < EndLoc);
return SourceRange();
}
static bool declIsStdInitializerList(const NamedDecl *D) {
// First use the fast getName() method to avoid unnecessary calls to the
// slow getQualifiedNameAsString().
return D->getName() == "initializer_list" &&
D->getQualifiedNameAsString() == "std::initializer_list";
}
static bool isStdInitializerList(QualType Type) {
Type = Type.getCanonicalType();
if (const auto *TS = Type->getAs<TemplateSpecializationType>()) {
if (const TemplateDecl *TD = TS->getTemplateName().getAsTemplateDecl())
return declIsStdInitializerList(TD);
}
if (const auto *RT = Type->getAs<RecordType>()) {
if (const auto *Specialization =
dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
return declIsStdInitializerList(Specialization->getSpecializedTemplate());
}
return false;
}
void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
constexpr char WarningMessage[] =
"%0 must be marked explicit to avoid unintentional implicit conversions";
if (const auto *Conversion =
Result.Nodes.getNodeAs<CXXConversionDecl>("conversion")) {
SourceLocation Loc = Conversion->getLocation();
// Ignore all macros until we learn to ignore specific ones (e.g. used in
// gmock to define matchers).
if (Loc.isMacroID())
return;
diag(Loc, WarningMessage)
<< Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
return;
}
const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
// Do not be confused: isExplicit means 'explicit' keyword is present,
// isImplicit means that it's a compiler-generated constructor.
if (Ctor->isOutOfLine() || Ctor->isImplicit() || Ctor->isDeleted() ||
Ctor->getNumParams() == 0 || Ctor->getMinRequiredArguments() > 1)
return;
bool takesInitializerList = isStdInitializerList(
Ctor->getParamDecl(0)->getType().getNonReferenceType());
if (Ctor->isExplicit() &&
(Ctor->isCopyOrMoveConstructor() || takesInitializerList)) {
auto isKWExplicit = [](const Token &Tok) {
return Tok.is(tok::raw_identifier) &&
Tok.getRawIdentifier() == "explicit";
};
SourceRange ExplicitTokenRange =
FindToken(*Result.SourceManager, getLangOpts(),
Ctor->getOuterLocStart(), Ctor->getLocEnd(), isKWExplicit);
StringRef ConstructorDescription;
if (Ctor->isMoveConstructor())
ConstructorDescription = "move";
else if (Ctor->isCopyConstructor())
ConstructorDescription = "copy";
else
ConstructorDescription = "initializer-list";
auto Diag = diag(Ctor->getLocation(),
"%0 constructor should not be declared explicit")
<< ConstructorDescription;
if (ExplicitTokenRange.isValid()) {
Diag << FixItHint::CreateRemoval(
CharSourceRange::getCharRange(ExplicitTokenRange));
}
return;
}
if (Ctor->isExplicit() || Ctor->isCopyOrMoveConstructor() ||
takesInitializerList)
return;
bool SingleArgument =
Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
SourceLocation Loc = Ctor->getLocation();
diag(Loc, WarningMessage)
<< (SingleArgument
? "single-argument constructors"
: "constructors that are callable with a single argument")
<< FixItHint::CreateInsertion(Loc, "explicit ");
}
} // namespace google
} // namespace tidy
} // namespace clang
| //===--- ExplicitConstructorCheck.cpp - clang-tidy ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ExplicitConstructorCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace google {
void ExplicitConstructorCheck::registerMatchers(MatchFinder *Finder) {
// Only register the matchers for C++; the functionality currently does not
// provide any benefit to other languages, despite being benign.
if (!getLangOpts().CPlusPlus)
return;
Finder->addMatcher(
cxxConstructorDecl(unless(anyOf(isImplicit(), // Compiler-generated.
isDeleted(), isInstantiated())))
.bind("ctor"),
this);
Finder->addMatcher(
cxxConversionDecl(unless(anyOf(isExplicit(), // Already marked explicit.
isImplicit(), // Compiler-generated.
isDeleted(), isInstantiated())))
.bind("conversion"),
this);
}
// Looks for the token matching the predicate and returns the range of the found
// token including trailing whitespace.
static SourceRange FindToken(const SourceManager &Sources,
const LangOptions &LangOpts,
SourceLocation StartLoc, SourceLocation EndLoc,
bool (*Pred)(const Token &)) {
if (StartLoc.isMacroID() || EndLoc.isMacroID())
return SourceRange();
FileID File = Sources.getFileID(Sources.getSpellingLoc(StartLoc));
StringRef Buf = Sources.getBufferData(File);
const char *StartChar = Sources.getCharacterData(StartLoc);
Lexer Lex(StartLoc, LangOpts, StartChar, StartChar, Buf.end());
Lex.SetCommentRetentionState(true);
Token Tok;
do {
Lex.LexFromRawLexer(Tok);
if (Pred(Tok)) {
Token NextTok;
Lex.LexFromRawLexer(NextTok);
return SourceRange(Tok.getLocation(), NextTok.getLocation());
}
} while (Tok.isNot(tok::eof) && Tok.getLocation() < EndLoc);
return SourceRange();
}
static bool declIsStdInitializerList(const NamedDecl *D) {
// First use the fast getName() method to avoid unnecessary calls to the
// slow getQualifiedNameAsString().
return D->getName() == "initializer_list" &&
D->getQualifiedNameAsString() == "std::initializer_list";
}
static bool isStdInitializerList(QualType Type) {
Type = Type.getCanonicalType();
if (const auto *TS = Type->getAs<TemplateSpecializationType>()) {
if (const TemplateDecl *TD = TS->getTemplateName().getAsTemplateDecl())
return declIsStdInitializerList(TD);
}
if (const auto *RT = Type->getAs<RecordType>()) {
if (const auto *Specialization =
dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
return declIsStdInitializerList(Specialization->getSpecializedTemplate());
}
return false;
}
void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) {
constexpr char WarningMessage[] =
"%0 must be marked explicit to avoid unintentional implicit conversions";
if (const auto *Conversion =
Result.Nodes.getNodeAs<CXXConversionDecl>("conversion")) {
SourceLocation Loc = Conversion->getLocation();
// Ignore all macros until we learn to ignore specific ones (e.g. used in
// gmock to define matchers).
if (Loc.isMacroID())
return;
diag(Loc, WarningMessage)
<< Conversion << FixItHint::CreateInsertion(Loc, "explicit ");
return;
}
const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("ctor");
if (Ctor->isOutOfLine() || Ctor->getNumParams() == 0 ||
Ctor->getMinRequiredArguments() > 1)
return;
bool takesInitializerList = isStdInitializerList(
Ctor->getParamDecl(0)->getType().getNonReferenceType());
if (Ctor->isExplicit() &&
(Ctor->isCopyOrMoveConstructor() || takesInitializerList)) {
auto isKWExplicit = [](const Token &Tok) {
return Tok.is(tok::raw_identifier) &&
Tok.getRawIdentifier() == "explicit";
};
SourceRange ExplicitTokenRange =
FindToken(*Result.SourceManager, getLangOpts(),
Ctor->getOuterLocStart(), Ctor->getLocEnd(), isKWExplicit);
StringRef ConstructorDescription;
if (Ctor->isMoveConstructor())
ConstructorDescription = "move";
else if (Ctor->isCopyConstructor())
ConstructorDescription = "copy";
else
ConstructorDescription = "initializer-list";
auto Diag = diag(Ctor->getLocation(),
"%0 constructor should not be declared explicit")
<< ConstructorDescription;
if (ExplicitTokenRange.isValid()) {
Diag << FixItHint::CreateRemoval(
CharSourceRange::getCharRange(ExplicitTokenRange));
}
return;
}
if (Ctor->isExplicit() || Ctor->isCopyOrMoveConstructor() ||
takesInitializerList)
return;
bool SingleArgument =
Ctor->getNumParams() == 1 && !Ctor->getParamDecl(0)->isParameterPack();
SourceLocation Loc = Ctor->getLocation();
diag(Loc, WarningMessage)
<< (SingleArgument
? "single-argument constructors"
: "constructors that are callable with a single argument")
<< FixItHint::CreateInsertion(Loc, "explicit ");
}
} // namespace google
} // namespace tidy
} // namespace clang
| Verify some conditions in a matcher instead of check(). NFC | [clang-tidy] Verify some conditions in a matcher instead of check(). NFC
git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@298057 91177308-0d34-0410-b5e6-96231b3b80d8
| C++ | apache-2.0 | llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra |
6ef84041295c919055d58891722853a03a3d14fd | WangscapeTest/TestCalculatorMax.cpp | WangscapeTest/TestCalculatorMax.cpp | #include <gtest/gtest.h>
#include <random>
#include <numeric>
#include <algorithm>
#include <tilegen/alpha/CalculatorMax.h>
class TestCalculatorMax : public ::testing::Test
{
public:
tilegen::alpha::CalculatorMax cm;
std::mt19937 rng;
TestCalculatorMax()
{
std::random_device rd;
rng.seed(rd());
}
int countValue(const tilegen::alpha::CalculatorBase::Alphas& alphas, int value)
{
return std::accumulate(alphas.cbegin(), alphas.cend(), 0,
[&value](int acc, sf::Uint8 x)
{ return (x == value) ? acc + 1 : acc; });
}
ptrdiff_t validateResults(const tilegen::alpha::CalculatorBase::Weights& weights)
{
cm.updateAlphas(weights);
const auto& alphas = cm.getAlphas();
EXPECT_EQ(3, countValue(alphas, 0));
EXPECT_EQ(1, countValue(alphas, 255));
ptrdiff_t winner_index = std::distance(alphas.cbegin(), std::max_element(alphas.cbegin(), alphas.cend()));
double max_value = *std::max_element(weights.cbegin(), weights.cend());
EXPECT_EQ(max_value, weights[winner_index]);
return winner_index;
}
};
TEST_F(TestCalculatorMax, TestCalculatorMaxDeterministic)
{
validateResults({0., 0., 0., 0.});
EXPECT_EQ(0, validateResults({1., 0., 0., 0.}));
EXPECT_EQ(1, validateResults({0., 1., 0., 0.}));
EXPECT_EQ(2, validateResults({0., 0., 1., 0.}));
EXPECT_EQ(3, validateResults({0., 0., 0., 1.}));
validateResults({0., 1., 1., 0.});
validateResults({1., 0., 1., 1.});
validateResults({1., 1., 1., 1.});
}
TEST_F(TestCalculatorMax, TestCalculatorMaxRandom)
{
tilegen::alpha::CalculatorBase::Weights weights(4);
std::uniform_real_distribution<double> weight_gen(-10, 10);
for (int i = 0; i < 100; i++)
{
for (auto& w : weights)
{
w = weight_gen(rng);
}
validateResults(weights);
}
}
TEST_F(TestCalculatorMax, TestCalculatorMaxRandomBiased)
{
tilegen::alpha::CalculatorBase::Weights weights(4);
std::uniform_real_distribution<double> weight_gen(-10, 10);
for (int i = 0; i < 1000; i++)
{
for (auto& w : weights)
{
w = weight_gen(rng);
}
size_t slot = i % weights.size();
weights[slot] += 40.;
EXPECT_EQ(slot, validateResults(weights));
}
} | #include <gtest/gtest.h>
#include <random>
#include <numeric>
#include <algorithm>
#include <tilegen/alpha/CalculatorMax.h>
class TestCalculatorMax : public ::testing::Test
{
public:
tilegen::alpha::CalculatorMax cm;
std::mt19937 rng;
TestCalculatorMax()
{
std::random_device rd;
rng.seed(rd());
}
int countValue(const tilegen::alpha::CalculatorBase::Alphas& alphas, int value)
{
return std::count_if(alphas.cbegin(), alphas.cend(),
[&value](sf::Uint8 x) {return x == value; });
}
ptrdiff_t validateResults(const tilegen::alpha::CalculatorBase::Weights& weights)
{
cm.updateAlphas(weights);
const auto& alphas = cm.getAlphas();
EXPECT_EQ(3, countValue(alphas, 0));
EXPECT_EQ(1, countValue(alphas, 255));
ptrdiff_t winner_index = std::distance(alphas.cbegin(), std::max_element(alphas.cbegin(), alphas.cend()));
double max_value = *std::max_element(weights.cbegin(), weights.cend());
EXPECT_EQ(max_value, weights[winner_index]);
return winner_index;
}
};
TEST_F(TestCalculatorMax, TestCalculatorMaxDeterministic)
{
validateResults({0., 0., 0., 0.});
EXPECT_EQ(0, validateResults({1., 0., 0., 0.}));
EXPECT_EQ(1, validateResults({0., 1., 0., 0.}));
EXPECT_EQ(2, validateResults({0., 0., 1., 0.}));
EXPECT_EQ(3, validateResults({0., 0., 0., 1.}));
validateResults({0., 1., 1., 0.});
validateResults({1., 0., 1., 1.});
validateResults({1., 1., 1., 1.});
}
TEST_F(TestCalculatorMax, TestCalculatorMaxRandom)
{
tilegen::alpha::CalculatorBase::Weights weights(4);
std::uniform_real_distribution<double> weight_gen(-10, 10);
for (int i = 0; i < 100; i++)
{
for (auto& w : weights)
{
w = weight_gen(rng);
}
validateResults(weights);
}
}
TEST_F(TestCalculatorMax, TestCalculatorMaxRandomBiased)
{
tilegen::alpha::CalculatorBase::Weights weights(4);
std::uniform_real_distribution<double> weight_gen(-10, 10);
for (int i = 0; i < 1000; i++)
{
for (auto& w : weights)
{
w = weight_gen(rng);
}
size_t slot = i % weights.size();
weights[slot] += 40.;
EXPECT_EQ(slot, validateResults(weights));
}
} | Replace a std::accumulate call with std::count_if | Replace a std::accumulate call with std::count_if
| C++ | mit | Wangscape/Wangscape,serin-delaunay/Wangscape,Wangscape/Wangscape,serin-delaunay/Wangscape,Wangscape/Wangscape |
1c8a690c7de72d47d4f1bb4a33c58493ff586284 | X10_Project/Classes/CreditScene.cpp | X10_Project/Classes/CreditScene.cpp | #include "stdafx.h"
#include "ConstVars.h"
#include "FileStuff.h"
#include "CreditScene.h"
#include "SimpleAudioEngine.h"
#include "MainScene.h"
float CreditScene::ypos = 0.0f;
Scene* CreditScene::createScene()
{
Scene* scene = Scene::create();
Layer* layer = CreditScene::create();
scene->addChild(layer);
return scene;
}
bool CreditScene::init()
{
if (!Layer::init())
{
return false;
}
UserDefault::getInstance()->setBoolForKey("AllCleared", true);
ypos = 0.0f;
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_INITIAL_BACKGROUND, true);
;
Sprite* credit = Sprite::create();
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Quite Night", 40));
credit->addChild(createSentence(" ", 15));
credit->addChild(createSentence("NEXT INSTITUTE", 20));
credit->addChild(createSentence("GameDevelopment track", 20));
credit->addChild(createSentence("Experience project", 20));
credit->addChild(createSentence(" ", 15));
credit->addChild(createSentence("A GAME BY", 20));
credit->addChild(createSentence("X10", 30));
credit->addChild(createSentence("MC Kim", 30));
credit->addChild(createSentence("JW Choi", 30));
credit->addChild(createSentence("TW Kim", 30));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("It's time to have", 15));
credit->addChild(createSentence("Chickens", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Code Review", 15));
credit->addChild(createSentence("Prof. SM Koo", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Mentor", 15));
credit->addChild(createSentence("Prof. SM Koo", 20));
credit->addChild(createSentence("Prof. HS Seo", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Nojam GAG", 15));
credit->addChild(createSentence("MC Kim", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Submodule migration", 15));
credit->addChild(createSentence("HY Nam", 20));
credit->addChild(createSentence("SB Kim", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("cppson library", 15));
credit->addChild(createSentence("HY Nam", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Secdrip", 15));
credit->addChild(createSentence("JW Choi - Eumlan Magui", 20));
credit->addChild(createSentence("Game programming", 15));
credit->addChild(createSentence("TW Kim, MC Kim, JW Choi", 20));
credit->addChild(createSentence("Art work", 15));
credit->addChild(createSentence("MC Kim, TW Kim, JW Choi", 20));
credit->addChild(createSentence("Map design", 15));
credit->addChild(createSentence("JW Choi, MC Kim, TW Kim", 20));
credit->addChild(createSentence("Game balancing", 15));
credit->addChild(createSentence("JW Choi, TW Kim, MC Kim", 20));
credit->addChild(createSentence("Sound effect", 15));
credit->addChild(createSentence("TW Kim, MC Kim, JW Choi", 20));
credit->addChild(createSentence("www.freesfx.co.uk", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Special Thanks to", 20));
credit->addChild(createSentence("Prof. EJ(Silver bell) Park,", 15));
credit->addChild(createSentence("Gagyungpu team, ", 15));
credit->addChild(createSentence("DS Lee, JS Kim, YK Kim, YS Kim, MH Kim, ", 15));
credit->addChild(createSentence("Alchon, MS Chicken, DamSo Sundae,", 15));
credit->addChild(createSentence("BurgerKing, KKu muk pig", 15));
credit->addChild(createSentence("Visual Studio & Assist, Pain.NET,", 15));
credit->addChild(createSentence("Texture packer, Gold Wave,", 15));
credit->addChild(createSentence("Goolge", 15));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Special Damn to", 15));
credit->addChild(createSentence("Git", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Thank you for playing.", 30));
credit->addChild(createSentence("X10 - Quiet Night", 30));
credit->addChild(createSentence("NEXT INSTITUTE", 30));
addChild(credit);
Size size = Director::getInstance()->getVisibleSize();
credit->setPosition(size.width / 2, 100);
MoveBy* moveUp = MoveBy::create(2.0, Vec2(0, 60));
RepeatForever* action = RepeatForever::create(moveUp);
credit->runAction(action);
float endTime = 90.0f;
Sequence* seq = Sequence::create(
DelayTime::create(endTime),
CallFunc::create(CC_CALLBACK_0(CreditScene::EndScene, this)),
nullptr
);
runAction(seq);
return true;
}
void CreditScene::EndScene()
{
Director::getInstance()->replaceScene(MainScene::createScene());
return;
}
Node* CreditScene::createSentence(string str, float fontSize)
{
ypos -= fontSize * 1.2;
Node* result = Label::create(str, "arial", fontSize);
result->setPosition(0, ypos);
ypos -= fontSize * 0.5;
return result;
} | #include "stdafx.h"
#include "ConstVars.h"
#include "FileStuff.h"
#include "CreditScene.h"
#include "SimpleAudioEngine.h"
#include "MainScene.h"
float CreditScene::ypos = 0.0f;
Scene* CreditScene::createScene()
{
Scene* scene = Scene::create();
Layer* layer = CreditScene::create();
scene->addChild(layer);
return scene;
}
bool CreditScene::init()
{
if (!Layer::init())
{
return false;
}
UserDefault::getInstance()->setBoolForKey("AllCleared", true);
ypos = 0.0f;
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_INITIAL_BACKGROUND, true);
;
Sprite* credit = Sprite::create();
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Quite Night", 40));
credit->addChild(createSentence(" ", 15));
credit->addChild(createSentence("NEXT INSTITUTE", 20));
credit->addChild(createSentence("GameDevelopment track", 20));
credit->addChild(createSentence("Experience project", 20));
credit->addChild(createSentence(" ", 15));
credit->addChild(createSentence("A GAME BY", 20));
credit->addChild(createSentence("X10", 30));
credit->addChild(createSentence("MC Kim", 30));
credit->addChild(createSentence("JW Choi", 30));
credit->addChild(createSentence("TW Kim", 30));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("It's time to have", 15));
credit->addChild(createSentence("Chickens", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Code Review", 15));
credit->addChild(createSentence("Prof. SM Koo", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Mentor", 15));
credit->addChild(createSentence("Prof. SM Koo", 20));
credit->addChild(createSentence("Prof. HS Seo", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Nojam GAG", 15));
credit->addChild(createSentence("MC Kim", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Submodule migration", 15));
credit->addChild(createSentence("HY Nam", 20));
credit->addChild(createSentence("SB Kim", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("cppson library", 15));
credit->addChild(createSentence("HY Nam", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Secdrip", 15));
credit->addChild(createSentence("JW Choi - Eumlan Magui", 20));
credit->addChild(createSentence("Game programming", 15));
credit->addChild(createSentence("TW Kim, MC Kim, JW Choi", 20));
credit->addChild(createSentence("Art work", 15));
credit->addChild(createSentence("MC Kim, TW Kim, JW Choi", 20));
credit->addChild(createSentence("Map design", 15));
credit->addChild(createSentence("JW Choi, MC Kim, TW Kim", 20));
credit->addChild(createSentence("Game balancing", 15));
credit->addChild(createSentence("JW Choi, TW Kim, MC Kim", 20));
credit->addChild(createSentence("Sound effect", 15));
credit->addChild(createSentence("TW Kim, MC Kim, JW Choi", 20));
credit->addChild(createSentence("www.freesfx.co.uk", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Special Thanks to", 20));
credit->addChild(createSentence("Prof. EJ(Silver bell) Park,", 15));
credit->addChild(createSentence("Gagyungpu team, ", 15));
credit->addChild(createSentence("DS Lee, JS Kim, YK Kim, YS Kim, MH Kim, ", 15));
credit->addChild(createSentence("Alchon, MS Chicken, DamSo Sundae,", 15));
credit->addChild(createSentence("BurgerKing, KKu muk pig", 15));
credit->addChild(createSentence("Visual Studio & Assist, Pain.NET,", 15));
credit->addChild(createSentence("Texture packer, Gold Wave,", 15));
credit->addChild(createSentence("Goolge", 15));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Special Damn to", 15));
credit->addChild(createSentence("Git", 20));
credit->addChild(createSentence(" ", 20));
credit->addChild(createSentence("Thank you for playing.", 30));
credit->addChild(createSentence("X10 - Quiet Night", 30));
credit->addChild(createSentence("NEXT INSTITUTE", 30));
addChild(credit);
Size size = Director::getInstance()->getVisibleSize();
credit->setPosition(size.width / 2, 100);
MoveBy* moveUp = MoveBy::create(2.0, Vec2(0, 60));
RepeatForever* action = RepeatForever::create(moveUp);
credit->runAction(action);
float endTime = 80.0f;
Sequence* seq = Sequence::create(
DelayTime::create(endTime),
CallFunc::create(CC_CALLBACK_0(CreditScene::EndScene, this)),
nullptr
);
runAction(seq);
return true;
}
void CreditScene::EndScene()
{
Director::getInstance()->replaceScene(MainScene::createScene());
return;
}
Node* CreditScene::createSentence(string str, float fontSize)
{
ypos -= fontSize * 1.2;
Node* result = Label::create(str, "arial", fontSize);
result->setPosition(0, ypos);
ypos -= fontSize * 0.5;
return result;
} | change credit Time | change credit Time
| C++ | mit | kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10 |
8013f73d88b32244b9fe3544af9114066a3e74af | sandbox/src/win_utils.cc | sandbox/src/win_utils.cc | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/src/win_utils.h"
#include <map>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "sandbox/src/internal_types.h"
#include "sandbox/src/nt_internals.h"
namespace {
// Holds the information about a known registry key.
struct KnownReservedKey {
const wchar_t* name;
HKEY key;
};
// Contains all the known registry key by name and by handle.
const KnownReservedKey kKnownKey[] = {
{ L"HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT },
{ L"HKEY_CURRENT_USER", HKEY_CURRENT_USER },
{ L"HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE},
{ L"HKEY_USERS", HKEY_USERS},
{ L"HKEY_PERFORMANCE_DATA", HKEY_PERFORMANCE_DATA},
{ L"HKEY_PERFORMANCE_TEXT", HKEY_PERFORMANCE_TEXT},
{ L"HKEY_PERFORMANCE_NLSTEXT", HKEY_PERFORMANCE_NLSTEXT},
{ L"HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG},
{ L"HKEY_DYN_DATA", HKEY_DYN_DATA}
};
} // namespace
namespace sandbox {
HKEY GetReservedKeyFromName(const std::wstring& name) {
for (size_t i = 0; i < arraysize(kKnownKey); ++i) {
if (name == kKnownKey[i].name)
return kKnownKey[i].key;
}
return NULL;
}
bool ResolveRegistryName(std::wstring name, std::wstring* resolved_name) {
for (size_t i = 0; i < arraysize(kKnownKey); ++i) {
if (name.find(kKnownKey[i].name) == 0) {
HKEY key;
DWORD disposition;
if (ERROR_SUCCESS != ::RegCreateKeyEx(kKnownKey[i].key, L"", 0, NULL, 0,
MAXIMUM_ALLOWED, NULL, &key,
&disposition))
return false;
bool result = GetPathFromHandle(key, resolved_name);
::RegCloseKey(key);
if (!result)
return false;
*resolved_name += name.substr(wcslen(kKnownKey[i].name));
return true;
}
}
return false;
}
DWORD IsReparsePoint(const std::wstring& full_path, bool* result) {
std::wstring path = full_path;
// Remove the nt prefix.
if (0 == path.compare(0, kNTPrefixLen, kNTPrefix))
path = path.substr(kNTPrefixLen);
// Check if it's a pipe. We can't query the attributes of a pipe.
const wchar_t kPipe[] = L"pipe\\";
if (0 == path.compare(0, arraysize(kPipe) - 1, kPipe)) {
*result = FALSE;
return ERROR_SUCCESS;
}
std::wstring::size_type last_pos = std::wstring::npos;
do {
path = path.substr(0, last_pos);
DWORD attributes = ::GetFileAttributes(path.c_str());
if (INVALID_FILE_ATTRIBUTES == attributes) {
DWORD error = ::GetLastError();
if (error != ERROR_FILE_NOT_FOUND &&
error != ERROR_PATH_NOT_FOUND &&
error != ERROR_INVALID_NAME) {
// Unexpected error.
NOTREACHED();
return error;
}
} else if (FILE_ATTRIBUTE_REPARSE_POINT & attributes) {
// This is a reparse point.
*result = true;
return ERROR_SUCCESS;
}
last_pos = path.rfind(L'\\');
} while (last_pos != std::wstring::npos);
*result = false;
return ERROR_SUCCESS;
}
bool ConvertToLongPath(const std::wstring& short_path,
std::wstring* long_path) {
// Check if the path is a NT path.
bool is_nt_path = false;
std::wstring path = short_path;
if (0 == path.compare(0, kNTPrefixLen, kNTPrefix)) {
path = path.substr(kNTPrefixLen);
is_nt_path = true;
}
DWORD size = MAX_PATH;
scoped_array<wchar_t> long_path_buf(new wchar_t[size]);
DWORD return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(),
size);
while (return_value >= size) {
size *= 2;
long_path_buf.reset(new wchar_t[size]);
return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(), size);
}
DWORD last_error = ::GetLastError();
if (0 == return_value && (ERROR_FILE_NOT_FOUND == last_error ||
ERROR_PATH_NOT_FOUND == last_error ||
ERROR_INVALID_NAME == last_error)) {
// The file does not exist, but maybe a sub path needs to be expanded.
std::wstring::size_type last_slash = path.rfind(L'\\');
if (std::wstring::npos == last_slash)
return false;
std::wstring begin = path.substr(0, last_slash);
std::wstring end = path.substr(last_slash);
if (!ConvertToLongPath(begin, &begin))
return false;
// Ok, it worked. Let's reset the return value.
path = begin + end;
return_value = 1;
} else if (0 != return_value) {
path = long_path_buf.get();
}
if (return_value != 0) {
if (is_nt_path) {
*long_path = kNTPrefix;
*long_path += path;
} else {
*long_path = path;
}
return true;
}
return false;
}
bool GetPathFromHandle(HANDLE handle, std::wstring* path) {
NtQueryObjectFunction NtQueryObject = NULL;
ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject);
OBJECT_NAME_INFORMATION* name = NULL;
ULONG size = 0;
// Query the name information a first time to get the size of the name.
NTSTATUS status = NtQueryObject(handle, ObjectNameInformation, name, size,
&size);
scoped_ptr<OBJECT_NAME_INFORMATION> name_ptr;
if (size) {
name = reinterpret_cast<OBJECT_NAME_INFORMATION*>(new BYTE[size]);
name_ptr.reset(name);
// Query the name information a second time to get the name of the
// object referenced by the handle.
status = NtQueryObject(handle, ObjectNameInformation, name, size, &size);
}
if (STATUS_SUCCESS != status)
return false;
path->assign(name->ObjectName.Buffer, name->ObjectName.Length /
sizeof(name->ObjectName.Buffer[0]));
return true;
}
}; // namespace sandbox
// TODO(cpu): This is not the final code we want here but we are yet
// to understand what is going on. See bug 11789.
void ResolveNTFunctionPtr(const char* name, void* ptr) {
static HMODULE ntdll = ::GetModuleHandle(sandbox::kNtdllName);
FARPROC* function_ptr = reinterpret_cast<FARPROC*>(ptr);
*function_ptr = ::GetProcAddress(ntdll, name);
if (*function_ptr)
return;
// We have data that re-trying helps.
*function_ptr = ::GetProcAddress(ntdll, name);
CHECK(*function_ptr);
}
| // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sandbox/src/win_utils.h"
#include <map>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "sandbox/src/internal_types.h"
#include "sandbox/src/nt_internals.h"
namespace {
// Holds the information about a known registry key.
struct KnownReservedKey {
const wchar_t* name;
HKEY key;
};
// Contains all the known registry key by name and by handle.
const KnownReservedKey kKnownKey[] = {
{ L"HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT },
{ L"HKEY_CURRENT_USER", HKEY_CURRENT_USER },
{ L"HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE},
{ L"HKEY_USERS", HKEY_USERS},
{ L"HKEY_PERFORMANCE_DATA", HKEY_PERFORMANCE_DATA},
{ L"HKEY_PERFORMANCE_TEXT", HKEY_PERFORMANCE_TEXT},
{ L"HKEY_PERFORMANCE_NLSTEXT", HKEY_PERFORMANCE_NLSTEXT},
{ L"HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG},
{ L"HKEY_DYN_DATA", HKEY_DYN_DATA}
};
} // namespace
namespace sandbox {
HKEY GetReservedKeyFromName(const std::wstring& name) {
for (size_t i = 0; i < arraysize(kKnownKey); ++i) {
if (name == kKnownKey[i].name)
return kKnownKey[i].key;
}
return NULL;
}
bool ResolveRegistryName(std::wstring name, std::wstring* resolved_name) {
for (size_t i = 0; i < arraysize(kKnownKey); ++i) {
if (name.find(kKnownKey[i].name) == 0) {
HKEY key;
DWORD disposition;
if (ERROR_SUCCESS != ::RegCreateKeyEx(kKnownKey[i].key, L"", 0, NULL, 0,
MAXIMUM_ALLOWED, NULL, &key,
&disposition))
return false;
bool result = GetPathFromHandle(key, resolved_name);
::RegCloseKey(key);
if (!result)
return false;
*resolved_name += name.substr(wcslen(kKnownKey[i].name));
return true;
}
}
return false;
}
DWORD IsReparsePoint(const std::wstring& full_path, bool* result) {
std::wstring path = full_path;
// Remove the nt prefix.
if (0 == path.compare(0, kNTPrefixLen, kNTPrefix))
path = path.substr(kNTPrefixLen);
// Check if it's a pipe. We can't query the attributes of a pipe.
const wchar_t kPipe[] = L"pipe\\";
if (0 == path.compare(0, arraysize(kPipe) - 1, kPipe)) {
*result = FALSE;
return ERROR_SUCCESS;
}
std::wstring::size_type last_pos = std::wstring::npos;
do {
path = path.substr(0, last_pos);
DWORD attributes = ::GetFileAttributes(path.c_str());
if (INVALID_FILE_ATTRIBUTES == attributes) {
DWORD error = ::GetLastError();
if (error != ERROR_FILE_NOT_FOUND &&
error != ERROR_PATH_NOT_FOUND &&
error != ERROR_INVALID_NAME) {
// Unexpected error.
NOTREACHED();
return error;
}
} else if (FILE_ATTRIBUTE_REPARSE_POINT & attributes) {
// This is a reparse point.
*result = true;
return ERROR_SUCCESS;
}
last_pos = path.rfind(L'\\');
} while (last_pos != std::wstring::npos);
*result = false;
return ERROR_SUCCESS;
}
bool ConvertToLongPath(const std::wstring& short_path,
std::wstring* long_path) {
// Check if the path is a NT path.
bool is_nt_path = false;
std::wstring path = short_path;
if (0 == path.compare(0, kNTPrefixLen, kNTPrefix)) {
path = path.substr(kNTPrefixLen);
is_nt_path = true;
}
DWORD size = MAX_PATH;
scoped_array<wchar_t> long_path_buf(new wchar_t[size]);
DWORD return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(),
size);
while (return_value >= size) {
size *= 2;
long_path_buf.reset(new wchar_t[size]);
return_value = ::GetLongPathName(path.c_str(), long_path_buf.get(), size);
}
DWORD last_error = ::GetLastError();
if (0 == return_value && (ERROR_FILE_NOT_FOUND == last_error ||
ERROR_PATH_NOT_FOUND == last_error ||
ERROR_INVALID_NAME == last_error)) {
// The file does not exist, but maybe a sub path needs to be expanded.
std::wstring::size_type last_slash = path.rfind(L'\\');
if (std::wstring::npos == last_slash)
return false;
std::wstring begin = path.substr(0, last_slash);
std::wstring end = path.substr(last_slash);
if (!ConvertToLongPath(begin, &begin))
return false;
// Ok, it worked. Let's reset the return value.
path = begin + end;
return_value = 1;
} else if (0 != return_value) {
path = long_path_buf.get();
}
if (return_value != 0) {
if (is_nt_path) {
*long_path = kNTPrefix;
*long_path += path;
} else {
*long_path = path;
}
return true;
}
return false;
}
bool GetPathFromHandle(HANDLE handle, std::wstring* path) {
NtQueryObjectFunction NtQueryObject = NULL;
ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject);
OBJECT_NAME_INFORMATION* name = NULL;
ULONG size = 0;
// Query the name information a first time to get the size of the name.
NTSTATUS status = NtQueryObject(handle, ObjectNameInformation, name, size,
&size);
scoped_ptr<OBJECT_NAME_INFORMATION> name_ptr;
if (size) {
name = reinterpret_cast<OBJECT_NAME_INFORMATION*>(new BYTE[size]);
name_ptr.reset(name);
// Query the name information a second time to get the name of the
// object referenced by the handle.
status = NtQueryObject(handle, ObjectNameInformation, name, size, &size);
}
if (STATUS_SUCCESS != status)
return false;
path->assign(name->ObjectName.Buffer, name->ObjectName.Length /
sizeof(name->ObjectName.Buffer[0]));
return true;
}
}; // namespace sandbox
// TODO(cpu): This is not the final code we want here but we are yet
// to understand what is going on. See bug 11789.
void ResolveNTFunctionPtr(const char* name, void* ptr) {
HMODULE ntdll = ::GetModuleHandle(sandbox::kNtdllName);
FARPROC* function_ptr = reinterpret_cast<FARPROC*>(ptr);
*function_ptr = ::GetProcAddress(ntdll, name);
if (*function_ptr)
return;
// We have data that re-trying helps.
*function_ptr = ::GetProcAddress(ntdll, name);
CHECK(*function_ptr);
}
| Change yet again the way we do ResolveNTFunctionPtr - This version is different from last three | Change yet again the way we do ResolveNTFunctionPtr
- This version is different from last three
TEST=chrome should start and you can browse
BUG=11789
Review URL: http://codereview.chromium.org/275014
git-svn-id: http://src.chromium.org/svn/trunk/src@29039 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 6cf2e7cc8e4a267eec0d1793721a645e72173dc9 | C++ | bsd-3-clause | meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser |
119b7feb01d3f135670bb867305468a1728c474f | tools/index-test/index-test.cpp | tools/index-test/index-test.cpp | //===--- index-test.cpp - Indexing test bed -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// index-test --help - Output help info.
// index-test [options] - Read from stdin.
// index-test [options] file - Read from "file".
// index-test [options] file1 file2 - Read these files.
//
// Files must be AST files.
//
//===----------------------------------------------------------------------===//
//
// -point-at [file:column:line]
// Point at a declaration/statement/expression. If no other operation is
// specified, prints some info about it.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/Utils.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Stmt.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace clang;
static llvm::cl::list<ParsedSourceLocation>
PointAtLocation("point-at", llvm::cl::Optional,
llvm::cl::value_desc("source-location"),
llvm::cl::desc("Point at the given source location of the first AST file"));
static llvm::cl::opt<bool>
DisableFree("disable-free",
llvm::cl::desc("Disable freeing of memory on exit"),
llvm::cl::init(false));
static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input AST files>"));
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv,
"LLVM 'Clang' Indexing Test Bed: http://clang.llvm.org\n");
FileManager FileMgr;
// If no input was specified, read from stdin.
if (InputFilenames.empty())
InputFilenames.push_back("-");
// FIXME: Only the first AST file is used for now.
const std::string &InFile = InputFilenames[0];
std::string ErrMsg;
llvm::OwningPtr<ASTUnit> AST;
AST.reset(ASTUnit::LoadFromPCHFile(InFile, FileMgr, &ErrMsg));
if (!AST) {
llvm::errs() << "[" << InFile << "] Error: " << ErrMsg << '\n';
return 1;
}
struct ASTPoint {
Decl *D;
Stmt *Node;
ASTPoint() : D(0), Node(0) {}
};
ASTPoint Point;
if (!PointAtLocation.empty()) {
const std::string &Filename = PointAtLocation[0].FileName;
const FileEntry *File = FileMgr.getFile(Filename);
if (File == 0) {
llvm::errs() << "File '" << Filename << "' does not exist\n";
return 1;
}
unsigned Line = PointAtLocation[0].Line;
unsigned Col = PointAtLocation[0].Column;
SourceLocation Loc = AST->getSourceManager().getLocation(File, Line, Col);
if (Loc.isInvalid()) {
llvm::errs() << "[" << InFile << "] Error: " <<
"Couldn't resolve source location (invalid location)\n";
return 1;
}
llvm::tie(Point.D, Point.Node) =
ResolveLocationInAST(AST->getASTContext(), Loc);
if (Point.D == 0) {
llvm::errs() << "[" << InFile << "] Error: " <<
"Couldn't resolve source location (no declaration found)\n";
return 1;
}
}
if (Point.D) {
llvm::raw_ostream &OS = llvm::outs();
assert(Point.D && "If no node was found we should have exited with error");
OS << "Declaration node at point: " << Point.D->getDeclKindName() << " ";
if (NamedDecl *ND = dyn_cast<NamedDecl>(Point.D))
OS << ND->getNameAsString();
OS << "\n";
if (Point.Node) {
OS << "Statement node at point: " << Point.Node->getStmtClassName()
<< " ";
Point.Node->printPretty(OS, AST->getASTContext());
OS << "\n";
}
}
if (DisableFree)
AST.take();
// Managed static deconstruction. Useful for making things like
// -time-passes usable.
llvm::llvm_shutdown();
return 0;
}
| //===--- index-test.cpp - Indexing test bed -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility may be invoked in the following manner:
// index-test --help - Output help info.
// index-test [options] - Read from stdin.
// index-test [options] file - Read from "file".
// index-test [options] file1 file2 - Read these files.
//
// Files must be AST files.
//
//===----------------------------------------------------------------------===//
//
// -point-at [file:column:line]
// Point at a declaration/statement/expression. If no other operation is
// specified, prints some info about it.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/Utils.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Stmt.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace clang;
static llvm::cl::list<ParsedSourceLocation>
PointAtLocation("point-at", llvm::cl::Optional,
llvm::cl::value_desc("source-location"),
llvm::cl::desc("Point at the given source location of the first AST file"));
static llvm::cl::opt<bool>
DisableFree("disable-free",
llvm::cl::desc("Disable freeing of memory on exit"),
llvm::cl::init(false));
static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input AST files>"));
int main(int argc, char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
llvm::PrettyStackTraceProgram X(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv,
"LLVM 'Clang' Indexing Test Bed: http://clang.llvm.org\n");
FileManager FileMgr;
// If no input was specified, read from stdin.
if (InputFilenames.empty())
InputFilenames.push_back("-");
// FIXME: Only the first AST file is used for now.
const std::string &InFile = InputFilenames[0];
std::string ErrMsg;
llvm::OwningPtr<ASTUnit> AST;
AST.reset(ASTUnit::LoadFromPCHFile(InFile, FileMgr, &ErrMsg));
if (!AST) {
llvm::errs() << "[" << InFile << "] Error: " << ErrMsg << '\n';
return 1;
}
struct ASTPoint {
Decl *D;
Stmt *Node;
ASTPoint() : D(0), Node(0) {}
};
ASTPoint Point;
if (!PointAtLocation.empty()) {
const std::string &Filename = PointAtLocation[0].FileName;
const FileEntry *File = FileMgr.getFile(Filename);
// Safety check. Using an out-of-date AST file will only lead to crashes
// or incorrect results.
// FIXME: Check all the source files that make up the AST file.
const FileEntry *ASTFile = FileMgr.getFile(InFile);
if (File->getModificationTime() > ASTFile->getModificationTime()) {
llvm::errs() << "[" << InFile << "] Error: " <<
"Pointing at a source file which was modified after creating "
"the AST file\n";
return 1;
}
if (File == 0) {
llvm::errs() << "File '" << Filename << "' does not exist\n";
return 1;
}
unsigned Line = PointAtLocation[0].Line;
unsigned Col = PointAtLocation[0].Column;
SourceLocation Loc = AST->getSourceManager().getLocation(File, Line, Col);
if (Loc.isInvalid()) {
llvm::errs() << "[" << InFile << "] Error: " <<
"Couldn't resolve source location (invalid location)\n";
return 1;
}
llvm::tie(Point.D, Point.Node) =
ResolveLocationInAST(AST->getASTContext(), Loc);
if (Point.D == 0) {
llvm::errs() << "[" << InFile << "] Error: " <<
"Couldn't resolve source location (no declaration found)\n";
return 1;
}
}
if (Point.D) {
llvm::raw_ostream &OS = llvm::outs();
assert(Point.D && "If no node was found we should have exited with error");
OS << "Declaration node at point: " << Point.D->getDeclKindName() << " ";
if (NamedDecl *ND = dyn_cast<NamedDecl>(Point.D))
OS << ND->getNameAsString();
OS << "\n";
if (Point.Node) {
OS << "Statement node at point: " << Point.Node->getStmtClassName()
<< " ";
Point.Node->printPretty(OS, AST->getASTContext());
OS << "\n";
}
}
if (DisableFree)
AST.take();
// Managed static deconstruction. Useful for making things like
// -time-passes usable.
llvm::llvm_shutdown();
return 0;
}
| Check that index-test uses an up-to-date AST file. | Check that index-test uses an up-to-date AST file.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@74214 91177308-0d34-0410-b5e6-96231b3b80d8
| C++ | apache-2.0 | apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang |
a18b281791d7cc6e966a4f472f2176e4c4755e9b | tools/llvm-ar/ArchiveWriter.cpp | tools/llvm-ar/ArchiveWriter.cpp | //===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Builds up an LLVM archive file (.a) containing LLVM bitcode.
//
//===----------------------------------------------------------------------===//
#include "Archive.h"
#include "ArchiveInternals.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PathV1.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
#include <fstream>
#include <iomanip>
#include <ostream>
using namespace llvm;
// Write an integer using variable bit rate encoding. This saves a few bytes
// per entry in the symbol table.
static inline void writeInteger(unsigned num, std::ofstream& ARFile) {
while (1) {
if (num < 0x80) { // done?
ARFile << (unsigned char)num;
return;
}
// Nope, we are bigger than a character, output the next 7 bits and set the
// high bit to say that there is more coming...
ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
num >>= 7; // Shift out 7 bits now...
}
}
// Compute how many bytes are taken by a given VBR encoded value. This is needed
// to pre-compute the size of the symbol table.
static inline unsigned numVbrBytes(unsigned num) {
// Note that the following nested ifs are somewhat equivalent to a binary
// search. We split it in half by comparing against 2^14 first. This allows
// most reasonable values to be done in 2 comparisons instead of 1 for
// small ones and four for large ones. We expect this to access file offsets
// in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range,
// so this approach is reasonable.
if (num < 1<<14) {
if (num < 1<<7)
return 1;
else
return 2;
}
if (num < 1<<21)
return 3;
if (num < 1<<28)
return 4;
return 5; // anything >= 2^28 takes 5 bytes
}
// Create an empty archive.
Archive* Archive::CreateEmpty(StringRef FilePath, LLVMContext& C) {
Archive* result = new Archive(FilePath, C);
return result;
}
// Fill the ArchiveMemberHeader with the information from a member. If
// TruncateNames is true, names are flattened to 15 chars or less. The sz field
// is provided here instead of coming from the mbr because the member might be
// stored compressed and the compressed size is not the ArchiveMember's size.
// Furthermore compressed files have negative size fields to identify them as
// compressed.
bool
Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
int sz, bool TruncateNames) const {
// Set the permissions mode, uid and gid
hdr.init();
char buffer[32];
sprintf(buffer, "%-8o", mbr.getMode());
memcpy(hdr.mode,buffer,8);
sprintf(buffer, "%-6u", mbr.getUser());
memcpy(hdr.uid,buffer,6);
sprintf(buffer, "%-6u", mbr.getGroup());
memcpy(hdr.gid,buffer,6);
// Set the last modification date
uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
memcpy(hdr.date,buffer,12);
// Get rid of trailing blanks in the name
std::string mbrPath = mbr.getPath().str();
size_t mbrLen = mbrPath.length();
while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
mbrPath.erase(mbrLen-1,1);
mbrLen--;
}
// Set the name field in one of its various flavors.
bool writeLongName = false;
if (mbr.isStringTable()) {
memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
} else if (mbr.isSVR4SymbolTable()) {
memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
} else if (mbr.isBSD4SymbolTable()) {
memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
} else if (TruncateNames) {
const char* nm = mbrPath.c_str();
unsigned len = mbrPath.length();
size_t slashpos = mbrPath.rfind('/');
if (slashpos != std::string::npos) {
nm += slashpos + 1;
len -= slashpos +1;
}
if (len > 15)
len = 15;
memcpy(hdr.name,nm,len);
hdr.name[len] = '/';
} else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
hdr.name[mbrPath.length()] = '/';
} else {
std::string nm = "#1/";
nm += utostr(mbrPath.length());
memcpy(hdr.name,nm.data(),nm.length());
if (sz < 0)
sz -= mbrPath.length();
else
sz += mbrPath.length();
writeLongName = true;
}
// Set the size field
if (sz < 0) {
buffer[0] = '-';
sprintf(&buffer[1],"%-9u",(unsigned)-sz);
} else {
sprintf(buffer, "%-10u", (unsigned)sz);
}
memcpy(hdr.size,buffer,10);
return writeLongName;
}
// Insert a file into the archive before some other member. This also takes care
// of extracting the necessary flags and information from the file.
bool Archive::addFileBefore(StringRef filePath, iterator where,
std::string *ErrMsg) {
bool Exists;
if (sys::fs::exists(filePath.str(), Exists) || !Exists) {
if (ErrMsg)
*ErrMsg = "Can not add a non-existent file to archive";
return true;
}
ArchiveMember* mbr = new ArchiveMember(this);
mbr->data = 0;
mbr->path = filePath.str();
sys::PathWithStatus PWS(mbr->path);
const sys::FileStatus *FSInfo = PWS.getFileStatus(false, ErrMsg);
if (!FSInfo) {
delete mbr;
return true;
}
mbr->User = FSInfo->getUser();
mbr->Group = FSInfo->getGroup();
mbr->Mode = FSInfo->getMode();
mbr->ModTime = FSInfo->getTimestamp();
mbr->Size = FSInfo->getSize();
unsigned flags = 0;
bool hasSlash = filePath.str().find('/') != std::string::npos;
if (hasSlash)
flags |= ArchiveMember::HasPathFlag;
if (hasSlash || filePath.str().length() > 15)
flags |= ArchiveMember::HasLongFilenameFlag;
sys::fs::file_magic type;
if (sys::fs::identify_magic(mbr->path, type))
type = sys::fs::file_magic::unknown;
switch (type) {
case sys::fs::file_magic::bitcode:
flags |= ArchiveMember::BitcodeFlag;
break;
default:
break;
}
mbr->flags = flags;
members.insert(where,mbr);
return false;
}
// Write one member out to the file.
bool
Archive::writeMember(
const ArchiveMember& member,
std::ofstream& ARFile,
bool CreateSymbolTable,
bool TruncateNames,
std::string* ErrMsg
) {
unsigned filepos = ARFile.tellp();
filepos -= 8;
// Get the data and its size either from the
// member's in-memory data or directly from the file.
size_t fSize = member.getSize();
const char *data = (const char*)member.getData();
MemoryBuffer *mFile = 0;
if (!data) {
OwningPtr<MemoryBuffer> File;
if (error_code ec = MemoryBuffer::getFile(member.getPath(), File)) {
if (ErrMsg)
*ErrMsg = ec.message();
return true;
}
mFile = File.take();
data = mFile->getBufferStart();
fSize = mFile->getBufferSize();
}
// Now that we have the data in memory, update the
// symbol table if it's a bitcode file.
if (CreateSymbolTable && member.isBitcode()) {
std::vector<std::string> symbols;
std::string FullMemberName =
(archPath + "(" + member.getPath() + ")").str();
Module* M =
GetBitcodeSymbols(data, fSize, FullMemberName, Context, symbols, ErrMsg);
// If the bitcode parsed successfully
if ( M ) {
for (std::vector<std::string>::iterator SI = symbols.begin(),
SE = symbols.end(); SI != SE; ++SI) {
std::pair<SymTabType::iterator,bool> Res =
symTab.insert(std::make_pair(*SI,filepos));
if (Res.second) {
symTabSize += SI->length() +
numVbrBytes(SI->length()) +
numVbrBytes(filepos);
}
}
// We don't need this module any more.
delete M;
} else {
delete mFile;
if (ErrMsg)
*ErrMsg = "Can't parse bitcode member: " + member.getPath().str()
+ ": " + *ErrMsg;
return true;
}
}
int hdrSize = fSize;
// Compute the fields of the header
ArchiveMemberHeader Hdr;
bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
// Write header to archive file
ARFile.write((char*)&Hdr, sizeof(Hdr));
// Write the long filename if its long
if (writeLongName) {
ARFile.write(member.getPath().str().data(),
member.getPath().str().length());
}
// Write the (possibly compressed) member's content to the file.
ARFile.write(data,fSize);
// Make sure the member is an even length
if ((ARFile.tellp() & 1) == 1)
ARFile << ARFILE_PAD;
// Close the mapped file if it was opened
delete mFile;
return false;
}
// Write the entire archive to the file specified when the archive was created.
// This writes to a temporary file first. Options are for creating a symbol
// table, flattening the file names (no directories, 15 chars max) and
// compressing each archive member.
bool
Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames,
std::string* ErrMsg)
{
// Make sure they haven't opened up the file, not loaded it,
// but are now trying to write it which would wipe out the file.
if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
if (ErrMsg)
*ErrMsg = "Can't write an archive not opened for writing";
return true;
}
// Create a temporary file to store the archive in
sys::Path TmpArchive(archPath);
if (TmpArchive.createTemporaryFileOnDisk(ErrMsg))
return true;
// Make sure the temporary gets removed if we crash
sys::RemoveFileOnSignal(TmpArchive.str());
// Create archive file for output.
std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
std::ios::binary;
std::ofstream ArchiveFile(TmpArchive.c_str(), io_mode);
// Check for errors opening or creating archive file.
if (!ArchiveFile.is_open() || ArchiveFile.bad()) {
TmpArchive.eraseFromDisk();
if (ErrMsg)
*ErrMsg = "Error opening archive file: " + archPath;
return true;
}
// If we're creating a symbol table, reset it now
if (CreateSymbolTable) {
symTabSize = 0;
symTab.clear();
}
// Write magic string to archive.
ArchiveFile << ARFILE_MAGIC;
// Loop over all member files, and write them out. Note that this also
// builds the symbol table, symTab.
for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
if (writeMember(*I, ArchiveFile, CreateSymbolTable,
TruncateNames, ErrMsg)) {
TmpArchive.eraseFromDisk();
ArchiveFile.close();
return true;
}
}
// Close archive file.
ArchiveFile.close();
// Write the symbol table
if (CreateSymbolTable) {
// At this point we have written a file that is a legal archive but it
// doesn't have a symbol table in it. To aid in faster reading and to
// ensure compatibility with other archivers we need to put the symbol
// table first in the file. Unfortunately, this means mapping the file
// we just wrote back in and copying it to the destination file.
sys::Path FinalFilePath(archPath);
// Map in the archive we just wrote.
{
OwningPtr<MemoryBuffer> arch;
if (error_code ec = MemoryBuffer::getFile(TmpArchive.c_str(), arch)) {
if (ErrMsg)
*ErrMsg = ec.message();
return true;
}
const char* base = arch->getBufferStart();
// Open another temporary file in order to avoid invalidating the
// mmapped data
if (FinalFilePath.createTemporaryFileOnDisk(ErrMsg))
return true;
sys::RemoveFileOnSignal(FinalFilePath.str());
std::ofstream FinalFile(FinalFilePath.c_str(), io_mode);
if (!FinalFile.is_open() || FinalFile.bad()) {
TmpArchive.eraseFromDisk();
if (ErrMsg)
*ErrMsg = "Error opening archive file: " + FinalFilePath.str();
return true;
}
// Write the file magic number
FinalFile << ARFILE_MAGIC;
// If there is a foreign symbol table, put it into the file now. Most
// ar(1) implementations require the symbol table to be first but llvm-ar
// can deal with it being after a foreign symbol table. This ensures
// compatibility with other ar(1) implementations as well as allowing the
// archive to store both native .o and LLVM .bc files, both indexed.
if (foreignST) {
if (writeMember(*foreignST, FinalFile, false, false, ErrMsg)) {
FinalFile.close();
TmpArchive.eraseFromDisk();
return true;
}
}
// Copy the temporary file contents being sure to skip the file's magic
// number.
FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
arch->getBufferSize()-sizeof(ARFILE_MAGIC)+1);
// Close up shop
FinalFile.close();
} // free arch.
// Move the final file over top of TmpArchive
if (FinalFilePath.renamePathOnDisk(TmpArchive, ErrMsg))
return true;
}
// Before we replace the actual archive, we need to forget all the
// members, since they point to data in that old archive. We need to do
// this because we cannot replace an open file on Windows.
cleanUpMemory();
if (TmpArchive.renamePathOnDisk(sys::Path(archPath), ErrMsg))
return true;
// Set correct read and write permissions after temporary file is moved
// to final destination path.
if (sys::Path(archPath).makeReadableOnDisk(ErrMsg))
return true;
if (sys::Path(archPath).makeWriteableOnDisk(ErrMsg))
return true;
return false;
}
| //===-- ArchiveWriter.cpp - Write LLVM archive files ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Builds up an LLVM archive file (.a) containing LLVM bitcode.
//
//===----------------------------------------------------------------------===//
#include "Archive.h"
#include "ArchiveInternals.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PathV1.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
#include <fstream>
#include <iomanip>
#include <ostream>
using namespace llvm;
// Write an integer using variable bit rate encoding. This saves a few bytes
// per entry in the symbol table.
static inline void writeInteger(unsigned num, std::ofstream& ARFile) {
while (1) {
if (num < 0x80) { // done?
ARFile << (unsigned char)num;
return;
}
// Nope, we are bigger than a character, output the next 7 bits and set the
// high bit to say that there is more coming...
ARFile << (unsigned char)(0x80 | ((unsigned char)num & 0x7F));
num >>= 7; // Shift out 7 bits now...
}
}
// Compute how many bytes are taken by a given VBR encoded value. This is needed
// to pre-compute the size of the symbol table.
static inline unsigned numVbrBytes(unsigned num) {
// Note that the following nested ifs are somewhat equivalent to a binary
// search. We split it in half by comparing against 2^14 first. This allows
// most reasonable values to be done in 2 comparisons instead of 1 for
// small ones and four for large ones. We expect this to access file offsets
// in the 2^10 to 2^24 range and symbol lengths in the 2^0 to 2^8 range,
// so this approach is reasonable.
if (num < 1<<14) {
if (num < 1<<7)
return 1;
else
return 2;
}
if (num < 1<<21)
return 3;
if (num < 1<<28)
return 4;
return 5; // anything >= 2^28 takes 5 bytes
}
// Create an empty archive.
Archive* Archive::CreateEmpty(StringRef FilePath, LLVMContext& C) {
Archive* result = new Archive(FilePath, C);
return result;
}
// Fill the ArchiveMemberHeader with the information from a member. If
// TruncateNames is true, names are flattened to 15 chars or less. The sz field
// is provided here instead of coming from the mbr because the member might be
// stored compressed and the compressed size is not the ArchiveMember's size.
// Furthermore compressed files have negative size fields to identify them as
// compressed.
bool
Archive::fillHeader(const ArchiveMember &mbr, ArchiveMemberHeader& hdr,
int sz, bool TruncateNames) const {
// Set the permissions mode, uid and gid
hdr.init();
char buffer[32];
sprintf(buffer, "%-8o", mbr.getMode());
memcpy(hdr.mode,buffer,8);
sprintf(buffer, "%-6u", mbr.getUser());
memcpy(hdr.uid,buffer,6);
sprintf(buffer, "%-6u", mbr.getGroup());
memcpy(hdr.gid,buffer,6);
// Set the last modification date
uint64_t secondsSinceEpoch = mbr.getModTime().toEpochTime();
sprintf(buffer,"%-12u", unsigned(secondsSinceEpoch));
memcpy(hdr.date,buffer,12);
// Get rid of trailing blanks in the name
std::string mbrPath = mbr.getPath().str();
size_t mbrLen = mbrPath.length();
while (mbrLen > 0 && mbrPath[mbrLen-1] == ' ') {
mbrPath.erase(mbrLen-1,1);
mbrLen--;
}
// Set the name field in one of its various flavors.
bool writeLongName = false;
if (mbr.isStringTable()) {
memcpy(hdr.name,ARFILE_STRTAB_NAME,16);
} else if (mbr.isSVR4SymbolTable()) {
memcpy(hdr.name,ARFILE_SVR4_SYMTAB_NAME,16);
} else if (mbr.isBSD4SymbolTable()) {
memcpy(hdr.name,ARFILE_BSD4_SYMTAB_NAME,16);
} else if (TruncateNames) {
const char* nm = mbrPath.c_str();
unsigned len = mbrPath.length();
size_t slashpos = mbrPath.rfind('/');
if (slashpos != std::string::npos) {
nm += slashpos + 1;
len -= slashpos +1;
}
if (len > 15)
len = 15;
memcpy(hdr.name,nm,len);
hdr.name[len] = '/';
} else if (mbrPath.length() < 16 && mbrPath.find('/') == std::string::npos) {
memcpy(hdr.name,mbrPath.c_str(),mbrPath.length());
hdr.name[mbrPath.length()] = '/';
} else {
std::string nm = "#1/";
nm += utostr(mbrPath.length());
memcpy(hdr.name,nm.data(),nm.length());
if (sz < 0)
sz -= mbrPath.length();
else
sz += mbrPath.length();
writeLongName = true;
}
// Set the size field
if (sz < 0) {
buffer[0] = '-';
sprintf(&buffer[1],"%-9u",(unsigned)-sz);
} else {
sprintf(buffer, "%-10u", (unsigned)sz);
}
memcpy(hdr.size,buffer,10);
return writeLongName;
}
// Insert a file into the archive before some other member. This also takes care
// of extracting the necessary flags and information from the file.
bool Archive::addFileBefore(StringRef filePath, iterator where,
std::string *ErrMsg) {
if (!sys::fs::exists(filePath)) {
if (ErrMsg)
*ErrMsg = "Can not add a non-existent file to archive";
return true;
}
ArchiveMember* mbr = new ArchiveMember(this);
mbr->data = 0;
mbr->path = filePath.str();
sys::PathWithStatus PWS(mbr->path);
const sys::FileStatus *FSInfo = PWS.getFileStatus(false, ErrMsg);
if (!FSInfo) {
delete mbr;
return true;
}
mbr->User = FSInfo->getUser();
mbr->Group = FSInfo->getGroup();
mbr->Mode = FSInfo->getMode();
mbr->ModTime = FSInfo->getTimestamp();
mbr->Size = FSInfo->getSize();
unsigned flags = 0;
bool hasSlash = filePath.str().find('/') != std::string::npos;
if (hasSlash)
flags |= ArchiveMember::HasPathFlag;
if (hasSlash || filePath.str().length() > 15)
flags |= ArchiveMember::HasLongFilenameFlag;
sys::fs::file_magic type;
if (sys::fs::identify_magic(mbr->path, type))
type = sys::fs::file_magic::unknown;
switch (type) {
case sys::fs::file_magic::bitcode:
flags |= ArchiveMember::BitcodeFlag;
break;
default:
break;
}
mbr->flags = flags;
members.insert(where,mbr);
return false;
}
// Write one member out to the file.
bool
Archive::writeMember(
const ArchiveMember& member,
std::ofstream& ARFile,
bool CreateSymbolTable,
bool TruncateNames,
std::string* ErrMsg
) {
unsigned filepos = ARFile.tellp();
filepos -= 8;
// Get the data and its size either from the
// member's in-memory data or directly from the file.
size_t fSize = member.getSize();
const char *data = (const char*)member.getData();
MemoryBuffer *mFile = 0;
if (!data) {
OwningPtr<MemoryBuffer> File;
if (error_code ec = MemoryBuffer::getFile(member.getPath(), File)) {
if (ErrMsg)
*ErrMsg = ec.message();
return true;
}
mFile = File.take();
data = mFile->getBufferStart();
fSize = mFile->getBufferSize();
}
// Now that we have the data in memory, update the
// symbol table if it's a bitcode file.
if (CreateSymbolTable && member.isBitcode()) {
std::vector<std::string> symbols;
std::string FullMemberName =
(archPath + "(" + member.getPath() + ")").str();
Module* M =
GetBitcodeSymbols(data, fSize, FullMemberName, Context, symbols, ErrMsg);
// If the bitcode parsed successfully
if ( M ) {
for (std::vector<std::string>::iterator SI = symbols.begin(),
SE = symbols.end(); SI != SE; ++SI) {
std::pair<SymTabType::iterator,bool> Res =
symTab.insert(std::make_pair(*SI,filepos));
if (Res.second) {
symTabSize += SI->length() +
numVbrBytes(SI->length()) +
numVbrBytes(filepos);
}
}
// We don't need this module any more.
delete M;
} else {
delete mFile;
if (ErrMsg)
*ErrMsg = "Can't parse bitcode member: " + member.getPath().str()
+ ": " + *ErrMsg;
return true;
}
}
int hdrSize = fSize;
// Compute the fields of the header
ArchiveMemberHeader Hdr;
bool writeLongName = fillHeader(member,Hdr,hdrSize,TruncateNames);
// Write header to archive file
ARFile.write((char*)&Hdr, sizeof(Hdr));
// Write the long filename if its long
if (writeLongName) {
ARFile.write(member.getPath().str().data(),
member.getPath().str().length());
}
// Write the (possibly compressed) member's content to the file.
ARFile.write(data,fSize);
// Make sure the member is an even length
if ((ARFile.tellp() & 1) == 1)
ARFile << ARFILE_PAD;
// Close the mapped file if it was opened
delete mFile;
return false;
}
// Write the entire archive to the file specified when the archive was created.
// This writes to a temporary file first. Options are for creating a symbol
// table, flattening the file names (no directories, 15 chars max) and
// compressing each archive member.
bool
Archive::writeToDisk(bool CreateSymbolTable, bool TruncateNames,
std::string* ErrMsg)
{
// Make sure they haven't opened up the file, not loaded it,
// but are now trying to write it which would wipe out the file.
if (members.empty() && mapfile && mapfile->getBufferSize() > 8) {
if (ErrMsg)
*ErrMsg = "Can't write an archive not opened for writing";
return true;
}
// Create a temporary file to store the archive in
sys::Path TmpArchive(archPath);
if (TmpArchive.createTemporaryFileOnDisk(ErrMsg))
return true;
// Make sure the temporary gets removed if we crash
sys::RemoveFileOnSignal(TmpArchive.str());
// Create archive file for output.
std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
std::ios::binary;
std::ofstream ArchiveFile(TmpArchive.c_str(), io_mode);
// Check for errors opening or creating archive file.
if (!ArchiveFile.is_open() || ArchiveFile.bad()) {
TmpArchive.eraseFromDisk();
if (ErrMsg)
*ErrMsg = "Error opening archive file: " + archPath;
return true;
}
// If we're creating a symbol table, reset it now
if (CreateSymbolTable) {
symTabSize = 0;
symTab.clear();
}
// Write magic string to archive.
ArchiveFile << ARFILE_MAGIC;
// Loop over all member files, and write them out. Note that this also
// builds the symbol table, symTab.
for (MembersList::iterator I = begin(), E = end(); I != E; ++I) {
if (writeMember(*I, ArchiveFile, CreateSymbolTable,
TruncateNames, ErrMsg)) {
TmpArchive.eraseFromDisk();
ArchiveFile.close();
return true;
}
}
// Close archive file.
ArchiveFile.close();
// Write the symbol table
if (CreateSymbolTable) {
// At this point we have written a file that is a legal archive but it
// doesn't have a symbol table in it. To aid in faster reading and to
// ensure compatibility with other archivers we need to put the symbol
// table first in the file. Unfortunately, this means mapping the file
// we just wrote back in and copying it to the destination file.
sys::Path FinalFilePath(archPath);
// Map in the archive we just wrote.
{
OwningPtr<MemoryBuffer> arch;
if (error_code ec = MemoryBuffer::getFile(TmpArchive.c_str(), arch)) {
if (ErrMsg)
*ErrMsg = ec.message();
return true;
}
const char* base = arch->getBufferStart();
// Open another temporary file in order to avoid invalidating the
// mmapped data
if (FinalFilePath.createTemporaryFileOnDisk(ErrMsg))
return true;
sys::RemoveFileOnSignal(FinalFilePath.str());
std::ofstream FinalFile(FinalFilePath.c_str(), io_mode);
if (!FinalFile.is_open() || FinalFile.bad()) {
TmpArchive.eraseFromDisk();
if (ErrMsg)
*ErrMsg = "Error opening archive file: " + FinalFilePath.str();
return true;
}
// Write the file magic number
FinalFile << ARFILE_MAGIC;
// If there is a foreign symbol table, put it into the file now. Most
// ar(1) implementations require the symbol table to be first but llvm-ar
// can deal with it being after a foreign symbol table. This ensures
// compatibility with other ar(1) implementations as well as allowing the
// archive to store both native .o and LLVM .bc files, both indexed.
if (foreignST) {
if (writeMember(*foreignST, FinalFile, false, false, ErrMsg)) {
FinalFile.close();
TmpArchive.eraseFromDisk();
return true;
}
}
// Copy the temporary file contents being sure to skip the file's magic
// number.
FinalFile.write(base + sizeof(ARFILE_MAGIC)-1,
arch->getBufferSize()-sizeof(ARFILE_MAGIC)+1);
// Close up shop
FinalFile.close();
} // free arch.
// Move the final file over top of TmpArchive
if (FinalFilePath.renamePathOnDisk(TmpArchive, ErrMsg))
return true;
}
// Before we replace the actual archive, we need to forget all the
// members, since they point to data in that old archive. We need to do
// this because we cannot replace an open file on Windows.
cleanUpMemory();
if (TmpArchive.renamePathOnDisk(sys::Path(archPath), ErrMsg))
return true;
// Set correct read and write permissions after temporary file is moved
// to final destination path.
if (sys::Path(archPath).makeReadableOnDisk(ErrMsg))
return true;
if (sys::Path(archPath).makeWriteableOnDisk(ErrMsg))
return true;
return false;
}
| Use the simpler sys::fs::exists. | Use the simpler sys::fs::exists.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@184413 91177308-0d34-0410-b5e6-96231b3b80d8
| C++ | apache-2.0 | apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap |
c38483778896fc5789e4b554690756b4830a0472 | tools/seec-trace-print/main.cpp | tools/seec-trace-print/main.cpp | //===- tools/seec-trace-print/main.cpp ------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/GraphLayout.hpp"
#include "seec/Clang/MappedAST.hpp"
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedProcessTrace.hpp"
#include "seec/Clang/MappedStateMovement.hpp"
#include "seec/ICU/Output.hpp"
#include "seec/ICU/Resources.hpp"
#include "seec/RuntimeErrors/RuntimeErrors.hpp"
#include "seec/RuntimeErrors/UnicodeFormatter.hpp"
#include "seec/Trace/ProcessState.hpp"
#include "seec/Trace/StateMovement.hpp"
#include "seec/Trace/TraceFormat.hpp"
#include "seec/Trace/TraceReader.hpp"
#include "seec/Trace/TraceSearch.hpp"
#include "seec/Util/Error.hpp"
#include "seec/Util/MakeUnique.hpp"
#include "seec/Util/ModuleIndex.hpp"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
#include "unicode/unistr.h"
#include "OnlinePythonTutor.hpp"
#include <array>
#include <memory>
using namespace seec;
using namespace llvm;
namespace {
static cl::opt<std::string>
InputDirectory(cl::desc("<input trace>"), cl::Positional, cl::init(""));
static cl::opt<bool>
UseClangMapping("C", cl::desc("use SeeC-Clang mapped states"));
static cl::opt<std::string>
OutputDirectoryForClangMappedDot("G", cl::desc("output dot graphs to this directory"));
static cl::opt<bool>
ShowRawEvents("R", cl::desc("show raw events"));
static cl::opt<bool>
ShowStates("S", cl::desc("show recreated states"));
static cl::opt<bool>
ShowErrors("E", cl::desc("show run-time errors"));
static cl::opt<bool>
OnlinePythonTutor("P", cl::desc("output suitable for Online Python Tutor"));
}
// From clang's driver.cpp:
std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
if (!CanonicalPrefixes)
return Argv0;
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *P = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::fs::getMainExecutable(Argv0, P);
}
void WriteDotGraph(seec::cm::ProcessState const &State,
char const *Filename,
seec::cm::graph::LayoutHandler const &Handler)
{
assert(Filename && "NULL Filename.");
std::string StreamError;
llvm::raw_fd_ostream Stream {Filename, StreamError};
if (!StreamError.empty()) {
llvm::errs() << "Error opening dot file: " << StreamError << "\n";
return;
}
Stream << Handler.doLayout(State).getDotString();
}
void PrintClangMappedStates(seec::cm::ProcessTrace const &Trace)
{
seec::cm::ProcessState State(Trace);
// If we're going to output dot graph files for the states, then setup the
// output directory and layout handler now.
std::unique_ptr<seec::cm::graph::LayoutHandler> LayoutHandler;
llvm::SmallString<256> OutputForDot;
std::string FilenameString;
llvm::raw_string_ostream FilenameStream {FilenameString};
long StateNumber = 1;
if (!OutputDirectoryForClangMappedDot.empty()) {
OutputForDot = OutputDirectoryForClangMappedDot;
bool Existed;
auto const Err =
llvm::sys::fs::create_directories(llvm::StringRef(OutputForDot),
Existed);
if (Err != llvm::errc::success) {
llvm::errs() << "Couldn't create output directory.\n";
return;
}
LayoutHandler.reset(new seec::cm::graph::LayoutHandler());
LayoutHandler->addBuiltinLayoutEngines();
}
if (State.getThreadCount() == 1) {
llvm::outs() << "Using thread-level iterator.\n";
do {
// Write textual description to stdout.
llvm::outs() << State;
llvm::outs() << "\n";
// If enabled, write graphs in dot format.
if (!OutputForDot.empty()) {
// Add filename for this state.
FilenameString.clear();
FilenameStream << "state." << StateNumber++ << ".dot";
FilenameStream.flush();
llvm::sys::path::append(OutputForDot, FilenameString);
// Write the graph.
WriteDotGraph(State, OutputForDot.c_str(), *LayoutHandler);
// Remove filename for this state.
llvm::sys::path::remove_filename(OutputForDot);
}
} while (seec::cm::moveForward(State.getThread(0)));
}
else {
llvm::outs() << "Using process-level iteration.\n";
llvm::outs() << State;
}
}
void PrintClangMapped(llvm::StringRef ExecutablePath)
{
// Attempt to setup the trace reader.
auto MaybeIBA = seec::trace::InputBufferAllocator::createFor(InputDirectory);
if (MaybeIBA.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeIBA.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto IBA = seec::makeUnique<trace::InputBufferAllocator>
(MaybeIBA.move<trace::InputBufferAllocator>());
// Read the trace.
auto CMProcessTraceLoad = cm::ProcessTrace::load(ExecutablePath,
std::move(IBA));
if (CMProcessTraceLoad.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = CMProcessTraceLoad.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto CMProcessTrace = CMProcessTraceLoad.move<0>();
if (ShowStates) {
PrintClangMappedStates(*CMProcessTrace);
}
else if (OnlinePythonTutor) {
PrintOnlinePythonTutor(*CMProcessTrace);
}
}
void PrintUnmapped(llvm::StringRef ExecutablePath)
{
auto &Context = llvm::getGlobalContext();
// Attempt to setup the trace reader.
auto MaybeIBA = seec::trace::InputBufferAllocator::createFor(InputDirectory);
if (MaybeIBA.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeIBA.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto IBA = seec::makeUnique<trace::InputBufferAllocator>
(MaybeIBA.move<trace::InputBufferAllocator>());
// Load the bitcode.
auto MaybeMod = IBA->getModule(Context);
if (MaybeMod.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeMod.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto const Mod = MaybeMod.get<llvm::Module *>();
auto ModIndexPtr = std::make_shared<seec::ModuleIndex>(*Mod, true);
// Attempt to read the trace (this consumes the IBA).
auto MaybeProcTrace = trace::ProcessTrace::readFrom(std::move(IBA));
if (MaybeProcTrace.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeProcTrace.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
std::shared_ptr<trace::ProcessTrace> Trace(MaybeProcTrace.get<0>().release());
// Print the raw events from each thread trace.
if (ShowRawEvents) {
auto NumThreads = Trace->getNumThreads();
outs() << "Showing raw events:\n";
for (uint32_t i = 1; i <= NumThreads; ++i) {
auto &&Thread = Trace->getThreadTrace(i);
outs() << "Thread #" << i << ":\n";
outs() << "Functions:\n";
for (auto Offset: Thread.topLevelFunctions()) {
outs() << " @" << Offset << "\n";
outs() << " " << Thread.getFunctionTrace(Offset) << "\n";
}
outs() << "Events:\n";
for (auto &&Ev: Thread.events()) {
if (Ev.isBlockStart())
outs() << "\n";
outs() << Ev << " @" << Thread.events().offsetOf(Ev) << "\n";
}
}
}
// Recreate complete process states and print the details.
if (ShowStates) {
outs() << "Recreating states:\n";
trace::ProcessState ProcState{Trace, ModIndexPtr};
outs() << ProcState << "\n";
while (ProcState.getProcessTime() != Trace->getFinalProcessTime()) {
moveForward(ProcState);
outs() << ProcState << "\n";
}
while (ProcState.getProcessTime() != 0) {
moveBackward(ProcState);
outs() << ProcState << "\n";
}
}
// Print basic descriptions of all run-time errors.
if (ShowErrors) {
// Setup diagnostics printing for Clang diagnostics.
IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts
= new clang::DiagnosticOptions();
DiagOpts->ShowColors = true;
clang::TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
IntrusiveRefCntPtr<clang::DiagnosticsEngine> Diagnostics
= new clang::DiagnosticsEngine(
IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()),
&*DiagOpts,
&DiagnosticPrinter,
false);
Diagnostics->setSuppressSystemWarnings(true);
Diagnostics->setIgnoreAllWarnings(true);
// Setup the map to find Decls and Stmts from Instructions
seec::seec_clang::MappedModule MapMod(*ModIndexPtr,
ExecutablePath,
Diagnostics);
clang::LangOptions LangOpt;
clang::PrintingPolicy PrintPolicy(LangOpt);
PrintPolicy.ConstantArraySizeAsWritten = true;
auto NumThreads = Trace->getNumThreads();
for (uint32_t i = 1; i <= NumThreads; ++i) {
auto &&Thread = Trace->getThreadTrace(i);
std::vector<uint32_t> FunctionStack;
outs() << "Thread #" << i << ":\n";
for (auto &&Ev: Thread.events()) {
if (Ev.getType() == trace::EventType::FunctionStart) {
auto const &Record = Ev.as<trace::EventType::FunctionStart>();
auto const Info = Thread.getFunctionTrace(Record.getRecord());
FunctionStack.push_back(Info.getIndex());
}
else if (Ev.getType() == trace::EventType::FunctionEnd) {
assert(!FunctionStack.empty());
FunctionStack.pop_back();
}
else if (Ev.getType() == trace::EventType::RuntimeError) {
auto &EvRecord = Ev.as<trace::EventType::RuntimeError>();
if (!EvRecord.getIsTopLevel())
continue;
assert(!FunctionStack.empty());
// Print a textual description of the error.
auto ErrRange = rangeAfterIncluding(Thread.events(), Ev);
auto RunErr = deserializeRuntimeError(ErrRange);
if (RunErr.first) {
using namespace seec::runtime_errors;
auto MaybeDesc = Description::create(*RunErr.first);
if (MaybeDesc.assigned(0)) {
DescriptionPrinterUnicode Printer(MaybeDesc.move<0>(),
"\n",
" ");
llvm::outs() << Printer.getString() << "\n";
}
else if (MaybeDesc.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
llvm::errs() << MaybeDesc.get<seec::Error>()
.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
else {
llvm::outs() << "Couldn't get error description.\n";
}
}
// Find the Instruction responsible for this error.
auto const Prev = trace::rfind<trace::EventType::PreInstruction>
(rangeBefore(Thread.events(), Ev));
assert(Prev.assigned());
auto const InstrIndex = Prev.get<0>()->getIndex();
assert(InstrIndex.assigned());
auto const FunIndex =
ModIndexPtr->getFunctionIndex(FunctionStack.back());
assert(FunIndex);
auto const Instr = FunIndex->getInstruction(InstrIndex.get<0>());
assert(Instr);
// Show the Clang Stmt that caused the error.
auto const StmtAndAST = MapMod.getStmtAndMappedAST(Instr);
assert(StmtAndAST.first && StmtAndAST.second);
auto const &AST = StmtAndAST.second->getASTUnit();
auto const &SrcManager = AST.getSourceManager();
auto const LocStart = StmtAndAST.first->getLocStart();
auto const Filename = SrcManager.getFilename(LocStart);
auto const Line = SrcManager.getSpellingLineNumber(LocStart);
auto const Column = SrcManager.getSpellingColumnNumber(LocStart);
outs() << Filename
<< ", Line " << Line
<< " Column " << Column << ":\n";
StmtAndAST.first->printPretty(outs(),
nullptr,
PrintPolicy);
outs() << "\n";
}
}
}
}
}
int main(int argc, char **argv, char * const *envp) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
atexit(llvm_shutdown);
cl::ParseCommandLineOptions(argc, argv, "seec trace printer\n");
auto const ExecutablePath = GetExecutablePath(argv[0], true);
// Setup resource loading.
ResourceLoader Resources(ExecutablePath);
std::array<char const *, 3> ResourceList {
{"RuntimeErrors", "SeeCClang", "Trace"}
};
if (!Resources.loadResources(ResourceList)) {
llvm::errs() << "failed to load resources\n";
exit(EXIT_FAILURE);
}
if (UseClangMapping || OnlinePythonTutor) {
PrintClangMapped(ExecutablePath);
}
else {
PrintUnmapped(ExecutablePath);
}
return EXIT_SUCCESS;
}
| //===- tools/seec-trace-print/main.cpp ------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/GraphLayout.hpp"
#include "seec/Clang/MappedAST.hpp"
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedProcessTrace.hpp"
#include "seec/Clang/MappedStateMovement.hpp"
#include "seec/ICU/Output.hpp"
#include "seec/ICU/Resources.hpp"
#include "seec/RuntimeErrors/RuntimeErrors.hpp"
#include "seec/RuntimeErrors/UnicodeFormatter.hpp"
#include "seec/Trace/ProcessState.hpp"
#include "seec/Trace/StateMovement.hpp"
#include "seec/Trace/TraceFormat.hpp"
#include "seec/Trace/TraceReader.hpp"
#include "seec/Trace/TraceSearch.hpp"
#include "seec/Util/Error.hpp"
#include "seec/Util/MakeUnique.hpp"
#include "seec/Util/ModuleIndex.hpp"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/system_error.h"
#include "unicode/unistr.h"
#include "OnlinePythonTutor.hpp"
#include <array>
#include <memory>
#include <type_traits>
using namespace seec;
using namespace llvm;
namespace {
static cl::opt<std::string>
InputDirectory(cl::desc("<input trace>"), cl::Positional, cl::init(""));
static cl::opt<bool>
UseClangMapping("C", cl::desc("use SeeC-Clang mapped states"));
static cl::opt<std::string>
OutputDirectoryForClangMappedDot("G", cl::desc("output dot graphs to this directory"));
static cl::opt<bool>
ShowCounts("counts", cl::desc("show event counts"));
static cl::opt<bool>
ShowRawEvents("R", cl::desc("show raw events"));
static cl::opt<bool>
ShowStates("S", cl::desc("show recreated states"));
static cl::opt<bool>
ShowErrors("E", cl::desc("show run-time errors"));
static cl::opt<bool>
OnlinePythonTutor("P", cl::desc("output suitable for Online Python Tutor"));
}
// From clang's driver.cpp:
std::string GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
if (!CanonicalPrefixes)
return Argv0;
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *P = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::fs::getMainExecutable(Argv0, P);
}
void WriteDotGraph(seec::cm::ProcessState const &State,
char const *Filename,
seec::cm::graph::LayoutHandler const &Handler)
{
assert(Filename && "NULL Filename.");
std::string StreamError;
llvm::raw_fd_ostream Stream {Filename, StreamError};
if (!StreamError.empty()) {
llvm::errs() << "Error opening dot file: " << StreamError << "\n";
return;
}
Stream << Handler.doLayout(State).getDotString();
}
void PrintClangMappedStates(seec::cm::ProcessTrace const &Trace)
{
seec::cm::ProcessState State(Trace);
// If we're going to output dot graph files for the states, then setup the
// output directory and layout handler now.
std::unique_ptr<seec::cm::graph::LayoutHandler> LayoutHandler;
llvm::SmallString<256> OutputForDot;
std::string FilenameString;
llvm::raw_string_ostream FilenameStream {FilenameString};
long StateNumber = 1;
if (!OutputDirectoryForClangMappedDot.empty()) {
OutputForDot = OutputDirectoryForClangMappedDot;
bool Existed;
auto const Err =
llvm::sys::fs::create_directories(llvm::StringRef(OutputForDot),
Existed);
if (Err != llvm::errc::success) {
llvm::errs() << "Couldn't create output directory.\n";
return;
}
LayoutHandler.reset(new seec::cm::graph::LayoutHandler());
LayoutHandler->addBuiltinLayoutEngines();
}
if (State.getThreadCount() == 1) {
llvm::outs() << "Using thread-level iterator.\n";
do {
// Write textual description to stdout.
llvm::outs() << State;
llvm::outs() << "\n";
// If enabled, write graphs in dot format.
if (!OutputForDot.empty()) {
// Add filename for this state.
FilenameString.clear();
FilenameStream << "state." << StateNumber++ << ".dot";
FilenameStream.flush();
llvm::sys::path::append(OutputForDot, FilenameString);
// Write the graph.
WriteDotGraph(State, OutputForDot.c_str(), *LayoutHandler);
// Remove filename for this state.
llvm::sys::path::remove_filename(OutputForDot);
}
} while (seec::cm::moveForward(State.getThread(0)));
}
else {
llvm::outs() << "Using process-level iteration.\n";
llvm::outs() << State;
}
}
void PrintClangMapped(llvm::StringRef ExecutablePath)
{
// Attempt to setup the trace reader.
auto MaybeIBA = seec::trace::InputBufferAllocator::createFor(InputDirectory);
if (MaybeIBA.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeIBA.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto IBA = seec::makeUnique<trace::InputBufferAllocator>
(MaybeIBA.move<trace::InputBufferAllocator>());
// Read the trace.
auto CMProcessTraceLoad = cm::ProcessTrace::load(ExecutablePath,
std::move(IBA));
if (CMProcessTraceLoad.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = CMProcessTraceLoad.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto CMProcessTrace = CMProcessTraceLoad.move<0>();
if (ShowStates) {
PrintClangMappedStates(*CMProcessTrace);
}
else if (OnlinePythonTutor) {
PrintOnlinePythonTutor(*CMProcessTrace);
}
}
void PrintUnmapped(llvm::StringRef ExecutablePath)
{
auto &Context = llvm::getGlobalContext();
// Attempt to setup the trace reader.
auto MaybeIBA = seec::trace::InputBufferAllocator::createFor(InputDirectory);
if (MaybeIBA.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeIBA.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto IBA = seec::makeUnique<trace::InputBufferAllocator>
(MaybeIBA.move<trace::InputBufferAllocator>());
// Load the bitcode.
auto MaybeMod = IBA->getModule(Context);
if (MaybeMod.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeMod.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
auto const Mod = MaybeMod.get<llvm::Module *>();
auto ModIndexPtr = std::make_shared<seec::ModuleIndex>(*Mod, true);
// Attempt to read the trace (this consumes the IBA).
auto MaybeProcTrace = trace::ProcessTrace::readFrom(std::move(IBA));
if (MaybeProcTrace.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
auto Error = MaybeProcTrace.move<seec::Error>();
llvm::errs() << Error.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
std::shared_ptr<trace::ProcessTrace> Trace(MaybeProcTrace.get<0>().release());
if (ShowCounts) {
using namespace seec::trace;
auto const NumThreads = Trace->getNumThreads();
// Count each EventType.
typedef std::underlying_type<EventType>::type UnderlyingEventTypeTy;
auto const Highest = static_cast<UnderlyingEventTypeTy>(EventType::Highest);
uint64_t Counts[Highest];
std::memset(Counts, 0, sizeof(Counts));
for (uint32_t i = 1; i <= NumThreads; ++i) {
auto const &Thread = Trace->getThreadTrace(i);
for (auto const &Ev : Thread.events())
++Counts[static_cast<UnderlyingEventTypeTy>(Ev.getType())];
}
// Print the counts for each EventType.
outs() << "EventType\tSize\tCount\tTotal\n";
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
{ \
auto const Index = static_cast<UnderlyingEventTypeTy>(EventType::NAME); \
auto const Size = sizeof(EventRecord<EventType::NAME>); \
outs() << #NAME "\t" << Size << "\t" << Counts[Index] << "\t" \
<< (Counts[Index] * Size) << "\n"; \
}
#include "seec/Trace/Events.def"
}
// Print the raw events from each thread trace.
if (ShowRawEvents) {
auto NumThreads = Trace->getNumThreads();
outs() << "Showing raw events:\n";
for (uint32_t i = 1; i <= NumThreads; ++i) {
auto &&Thread = Trace->getThreadTrace(i);
outs() << "Thread #" << i << ":\n";
outs() << "Functions:\n";
for (auto Offset: Thread.topLevelFunctions()) {
outs() << " @" << Offset << "\n";
outs() << " " << Thread.getFunctionTrace(Offset) << "\n";
}
outs() << "Events:\n";
for (auto &&Ev: Thread.events()) {
if (Ev.isBlockStart())
outs() << "\n";
outs() << Ev << " @" << Thread.events().offsetOf(Ev) << "\n";
}
}
}
// Recreate complete process states and print the details.
if (ShowStates) {
outs() << "Recreating states:\n";
trace::ProcessState ProcState{Trace, ModIndexPtr};
outs() << ProcState << "\n";
while (ProcState.getProcessTime() != Trace->getFinalProcessTime()) {
moveForward(ProcState);
outs() << ProcState << "\n";
}
while (ProcState.getProcessTime() != 0) {
moveBackward(ProcState);
outs() << ProcState << "\n";
}
}
// Print basic descriptions of all run-time errors.
if (ShowErrors) {
// Setup diagnostics printing for Clang diagnostics.
IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts
= new clang::DiagnosticOptions();
DiagOpts->ShowColors = true;
clang::TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
IntrusiveRefCntPtr<clang::DiagnosticsEngine> Diagnostics
= new clang::DiagnosticsEngine(
IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()),
&*DiagOpts,
&DiagnosticPrinter,
false);
Diagnostics->setSuppressSystemWarnings(true);
Diagnostics->setIgnoreAllWarnings(true);
// Setup the map to find Decls and Stmts from Instructions
seec::seec_clang::MappedModule MapMod(*ModIndexPtr,
ExecutablePath,
Diagnostics);
clang::LangOptions LangOpt;
clang::PrintingPolicy PrintPolicy(LangOpt);
PrintPolicy.ConstantArraySizeAsWritten = true;
auto NumThreads = Trace->getNumThreads();
for (uint32_t i = 1; i <= NumThreads; ++i) {
auto &&Thread = Trace->getThreadTrace(i);
std::vector<uint32_t> FunctionStack;
outs() << "Thread #" << i << ":\n";
for (auto &&Ev: Thread.events()) {
if (Ev.getType() == trace::EventType::FunctionStart) {
auto const &Record = Ev.as<trace::EventType::FunctionStart>();
auto const Info = Thread.getFunctionTrace(Record.getRecord());
FunctionStack.push_back(Info.getIndex());
}
else if (Ev.getType() == trace::EventType::FunctionEnd) {
assert(!FunctionStack.empty());
FunctionStack.pop_back();
}
else if (Ev.getType() == trace::EventType::RuntimeError) {
auto &EvRecord = Ev.as<trace::EventType::RuntimeError>();
if (!EvRecord.getIsTopLevel())
continue;
assert(!FunctionStack.empty());
// Print a textual description of the error.
auto ErrRange = rangeAfterIncluding(Thread.events(), Ev);
auto RunErr = deserializeRuntimeError(ErrRange);
if (RunErr.first) {
using namespace seec::runtime_errors;
auto MaybeDesc = Description::create(*RunErr.first);
if (MaybeDesc.assigned(0)) {
DescriptionPrinterUnicode Printer(MaybeDesc.move<0>(),
"\n",
" ");
llvm::outs() << Printer.getString() << "\n";
}
else if (MaybeDesc.assigned<seec::Error>()) {
UErrorCode Status = U_ZERO_ERROR;
llvm::errs() << MaybeDesc.get<seec::Error>()
.getMessage(Status, Locale()) << "\n";
exit(EXIT_FAILURE);
}
else {
llvm::outs() << "Couldn't get error description.\n";
}
}
// Find the Instruction responsible for this error.
auto const Prev = trace::rfind<trace::EventType::PreInstruction>
(rangeBefore(Thread.events(), Ev));
assert(Prev.assigned());
auto const InstrIndex = Prev.get<0>()->getIndex();
assert(InstrIndex.assigned());
auto const FunIndex =
ModIndexPtr->getFunctionIndex(FunctionStack.back());
assert(FunIndex);
auto const Instr = FunIndex->getInstruction(InstrIndex.get<0>());
assert(Instr);
// Show the Clang Stmt that caused the error.
auto const StmtAndAST = MapMod.getStmtAndMappedAST(Instr);
assert(StmtAndAST.first && StmtAndAST.second);
auto const &AST = StmtAndAST.second->getASTUnit();
auto const &SrcManager = AST.getSourceManager();
auto const LocStart = StmtAndAST.first->getLocStart();
auto const Filename = SrcManager.getFilename(LocStart);
auto const Line = SrcManager.getSpellingLineNumber(LocStart);
auto const Column = SrcManager.getSpellingColumnNumber(LocStart);
outs() << Filename
<< ", Line " << Line
<< " Column " << Column << ":\n";
StmtAndAST.first->printPretty(outs(),
nullptr,
PrintPolicy);
outs() << "\n";
}
}
}
}
}
int main(int argc, char **argv, char * const *envp) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
atexit(llvm_shutdown);
cl::ParseCommandLineOptions(argc, argv, "seec trace printer\n");
auto const ExecutablePath = GetExecutablePath(argv[0], true);
// Setup resource loading.
ResourceLoader Resources(ExecutablePath);
std::array<char const *, 3> ResourceList {
{"RuntimeErrors", "SeeCClang", "Trace"}
};
if (!Resources.loadResources(ResourceList)) {
llvm::errs() << "failed to load resources\n";
exit(EXIT_FAILURE);
}
if (UseClangMapping || OnlinePythonTutor) {
PrintClangMapped(ExecutablePath);
}
else {
PrintUnmapped(ExecutablePath);
}
return EXIT_SUCCESS;
}
| Add "-counts" argument to seec-print, which will count and print the number of each EventType in an unmapped trace. | Add "-counts" argument to seec-print, which will count and print the number of each EventType in an unmapped trace.
| C++ | mit | mheinsen/seec,mheinsen/seec,seec-team/seec,mheinsen/seec,mheinsen/seec,seec-team/seec,seec-team/seec,mheinsen/seec,seec-team/seec,seec-team/seec |
739355f924c0d9d692db7d56c53a43650ad16a4c | include/FactorTable.hpp | include/FactorTable.hpp | ///
/// @file FactorTable.hpp
/// @brief The FactorTable class combines the lpf[n] (least prime
/// factor) and mu[n] (Möbius function) lookup tables into a
/// single factor[n] table which furthermore only contains
/// entries for numbers which are not divisible by 2, 3, 5, 7
/// and 11. The factor[n] lookup table uses up to 19.25
/// times less memory than the lpf[n] & mu[n] lookup tables!
/// factor[n] uses only 2 bytes per entry for 32-bit numbers
/// and 4 bytes per entry for 64-bit numbers.
///
/// The factor table concept was devised and implemented by
/// Christian Bau in 2003. Note that Tomás Oliveira e Silva
/// also suggests combining the mu[n] and lpf[n] lookup tables
/// in his paper. However Christian Bau's FactorTable data
/// structure uses only half as much memory and is also
/// slightly more efficient (uses fewer instructions) than the
/// data structure proposed by Tomás Oliveira e Silva.
///
/// What we store in the factor[n] lookup table:
///
/// 1) INT_MAX - 1 if n = 1
/// 2) INT_MAX if n is a prime
/// 3) 0 if moebius(n) = 0
/// 4) lpf - 1 if moebius(n) = 1
/// 5) lpf if moebius(n) = -1
///
/// factor[1] = (INT_MAX - 1) because 1 contributes to the
/// sum of the ordinary leaves S1(x, a) in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms.
/// The values above allow to replace the 1st if statement
/// below used in the S1(x, a) and S2(x, a) formulas by the
/// 2nd new if statement which is obviously faster.
///
/// * Old: if (mu[n] != 0 && prime < lpf[n])
/// * New: if (prime < factor[n])
///
/// Copyright (C) 2020 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <imath.hpp>
#include <int128_t.hpp>
#include <pod_vector.hpp>
#include <algorithm>
#include <array>
#include <cassert>
#include <limits>
#include <stdint.h>
namespace primecount {
/// AbstractFactorTable contains static lookup tables
/// and is used to convert:
/// 1) A number into a FactorTable index
/// 2) A FactorTable index into a number
///
class AbstractFactorTable
{
public:
static int64_t to_index(uint64_t number)
{
assert(number > 0);
uint64_t q = number / 2310;
uint64_t r = number % 2310;
return 480 * q + coprime_indexes_[r];
}
static int64_t to_number(uint64_t index)
{
uint64_t q = index / 480;
uint64_t r = index % 480;
return 2310 * q + coprime_[r];
}
/// Returns the 1st number > 1 that is not divisible
/// by 2, 3, 5, 7 and 11. Hence 13 is returned.
///
static int64_t get_first_coprime()
{
return to_number(1);
}
protected:
/// Find the first multiple (of prime) > low which
/// is not divisible by any prime <= 11.
///
static int64_t next_multiple(int64_t prime,
int64_t low,
int64_t* index)
{
int64_t quotient = ceil_div(low, prime);
int64_t i = std::max(*index, to_index(quotient));
int64_t multiple = 0;
for (; multiple <= low; i++)
multiple = prime * to_number(i);
*index = i;
return multiple;
}
private:
static const std::array<uint16_t, 480> coprime_;
static const std::array<int16_t, 2310> coprime_indexes_;
};
} // namespace
namespace {
using namespace primecount;
template <typename T>
class FactorTable : public AbstractFactorTable
{
public:
/// Factor numbers <= y
FactorTable(int64_t y, int threads)
{
if (y > max())
throw primecount_error("y must be <= FactorTable::max()");
y = std::max<int64_t>(1, y);
T T_MAX = std::numeric_limits<T>::max();
factor_.resize(to_index(y) + 1);
// mu(1) = 1.
// 1 has zero prime factors, hence 1 has an even
// number of prime factors. We use the least
// significant bit to indicate whether the number
// has an even or odd number of prime factors.
factor_[0] = T_MAX ^ 1;
int64_t sqrty = isqrt(y);
int64_t thread_threshold = (int64_t) 1e7;
threads = ideal_num_threads(threads, y, thread_threshold);
int64_t thread_distance = ceil_div(y, threads);
thread_distance += coprime_indexes_.size() - thread_distance % coprime_indexes_.size();
#pragma omp parallel for num_threads(threads)
for (int t = 0; t < threads; t++)
{
// Thread processes interval [low, high[
int64_t low = thread_distance * t;
int64_t high = low + thread_distance;
low = std::max(low, to_number(1));
high = std::min(high, y + 1);
if (low <= y)
{
// Default initialize memory to all bits set
int64_t size = to_index(high);
int64_t max_size = factor_.size();
size = std::min(size, max_size) - to_index(low);
std::fill_n(&factor_[low_idx], size, T_MAX);
int64_t start = get_first_coprime() - 1;
primesieve::iterator it(start);
while (true)
{
int64_t i = 1;
int64_t prime = it.next_prime();
int64_t multiple = next_multiple(prime, low, &i);
int64_t min_m = prime * get_first_coprime();
if (min_m >= high)
break;
for (; multiple < high; multiple = prime * to_number(i++))
{
int64_t mi = to_index(multiple);
// prime is smallest factor of multiple
if (factor_[mi] == T_MAX)
factor_[mi] = (T) prime;
// the least significant bit indicates
// whether multiple has an even (0) or odd (1)
// number of prime factors
else if (factor_[mi] != 0)
factor_[mi] ^= 1;
}
if (prime <= sqrty)
{
int64_t j = 0;
int64_t square = prime * prime;
multiple = next_multiple(square, low, &j);
// moebius(n) = 0
for (; multiple < high; multiple = square * to_number(j++))
factor_[to_index(multiple)] = 0;
}
}
}
}
}
/// mu_lpf(n) is a combination of the mu(n) (Möbius function)
/// and lpf(n) (least prime factor) functions.
/// mu_lpf(n) returns (with n = to_number(index)):
///
/// 1) INT_MAX - 1 if n = 1
/// 2) INT_MAX if n is a prime
/// 3) 0 if moebius(n) = 0
/// 4) lpf - 1 if moebius(n) = 1
/// 5) lpf if moebius(n) = -1
///
int64_t mu_lpf(int64_t index) const
{
return factor_[index];
}
/// Get the Möbius function value of the number
/// n = to_number(index).
///
/// https://en.wikipedia.org/wiki/Möbius_function
/// mu(n) = 1 if n is a square-free integer with an even number of prime factors.
/// mu(n) = −1 if n is a square-free integer with an odd number of prime factors.
/// mu(n) = 0 if n has a squared prime factor.
///
int64_t mu(int64_t index) const
{
if (factor_[index] == 0)
return 0;
else if (factor_[index] & 1)
return -1;
else
return 1;
}
static maxint_t max()
{
maxint_t T_MAX = std::numeric_limits<T>::max();
return ipow(T_MAX - 1, 2) - 1;
}
private:
pod_vector<T> factor_;
};
} // namespace
#endif
| ///
/// @file FactorTable.hpp
/// @brief The FactorTable class combines the lpf[n] (least prime
/// factor) and mu[n] (Möbius function) lookup tables into a
/// single factor[n] table which furthermore only contains
/// entries for numbers which are not divisible by 2, 3, 5, 7
/// and 11. The factor[n] lookup table uses up to 19.25
/// times less memory than the lpf[n] & mu[n] lookup tables!
/// factor[n] uses only 2 bytes per entry for 32-bit numbers
/// and 4 bytes per entry for 64-bit numbers.
///
/// The factor table concept was devised and implemented by
/// Christian Bau in 2003. Note that Tomás Oliveira e Silva
/// also suggests combining the mu[n] and lpf[n] lookup tables
/// in his paper. However Christian Bau's FactorTable data
/// structure uses only half as much memory and is also
/// slightly more efficient (uses fewer instructions) than the
/// data structure proposed by Tomás Oliveira e Silva.
///
/// What we store in the factor[n] lookup table:
///
/// 1) INT_MAX - 1 if n = 1
/// 2) INT_MAX if n is a prime
/// 3) 0 if moebius(n) = 0
/// 4) lpf - 1 if moebius(n) = 1
/// 5) lpf if moebius(n) = -1
///
/// factor[1] = (INT_MAX - 1) because 1 contributes to the
/// sum of the ordinary leaves S1(x, a) in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms.
/// The values above allow to replace the 1st if statement
/// below used in the S1(x, a) and S2(x, a) formulas by the
/// 2nd new if statement which is obviously faster.
///
/// * Old: if (mu[n] != 0 && prime < lpf[n])
/// * New: if (prime < factor[n])
///
/// Copyright (C) 2020 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP
#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <imath.hpp>
#include <int128_t.hpp>
#include <pod_vector.hpp>
#include <algorithm>
#include <array>
#include <cassert>
#include <limits>
#include <stdint.h>
namespace primecount {
/// AbstractFactorTable contains static lookup tables
/// and is used to convert:
/// 1) A number into a FactorTable index
/// 2) A FactorTable index into a number
///
class AbstractFactorTable
{
public:
static int64_t to_index(uint64_t number)
{
assert(number > 0);
uint64_t q = number / 2310;
uint64_t r = number % 2310;
return 480 * q + coprime_indexes_[r];
}
static int64_t to_number(uint64_t index)
{
uint64_t q = index / 480;
uint64_t r = index % 480;
return 2310 * q + coprime_[r];
}
/// Returns the 1st number > 1 that is not divisible
/// by 2, 3, 5, 7 and 11. Hence 13 is returned.
///
static int64_t get_first_coprime()
{
return to_number(1);
}
protected:
/// Find the first multiple (of prime) >= low which
/// is not divisible by any prime <= 11.
///
static int64_t next_multiple(int64_t prime,
int64_t low,
int64_t* index)
{
int64_t quotient = ceil_div(low, prime);
int64_t i = std::max(*index, to_index(quotient));
int64_t multiple = 0;
for (; multiple < low; i++)
multiple = prime * to_number(i);
*index = i;
return multiple;
}
static const std::array<uint16_t, 480> coprime_;
static const std::array<int16_t, 2310> coprime_indexes_;
};
} // namespace
namespace {
using namespace primecount;
template <typename T>
class FactorTable : public AbstractFactorTable
{
public:
/// Factor numbers <= y
FactorTable(int64_t y, int threads)
{
if (y > max())
throw primecount_error("y must be <= FactorTable::max()");
y = std::max<int64_t>(1, y);
T T_MAX = std::numeric_limits<T>::max();
factor_.resize(to_index(y) + 1);
// mu(1) = 1.
// 1 has zero prime factors, hence 1 has an even
// number of prime factors. We use the least
// significant bit to indicate whether the number
// has an even or odd number of prime factors.
factor_[0] = T_MAX ^ 1;
int64_t sqrty = isqrt(y);
int64_t thread_threshold = (int64_t) 1e7;
threads = ideal_num_threads(threads, y, thread_threshold);
int64_t thread_distance = ceil_div(y, threads);
thread_distance += coprime_indexes_.size() - thread_distance % coprime_indexes_.size();
#pragma omp parallel for num_threads(threads)
for (int t = 0; t < threads; t++)
{
// Thread processes interval [low, high]
int64_t low = thread_distance * t;
int64_t high = low + thread_distance;
low = std::max(get_first_coprime(), low + 1);
high = std::min(high, y);
if (low <= high)
{
// Default initialize memory to all bits set
int64_t low_idx = to_index(low);
int64_t size = to_index(high) + 1;
std::fill_n(&factor_[low_idx], size - low_idx, T_MAX);
int64_t start = get_first_coprime() - 1;
primesieve::iterator it(start);
while (true)
{
int64_t i = 1;
int64_t prime = it.next_prime();
int64_t multiple = next_multiple(prime, low, &i);
int64_t min_m = prime * get_first_coprime();
if (min_m > high)
break;
for (; multiple <= high; multiple = prime * to_number(i++))
{
int64_t mi = to_index(multiple);
// prime is smallest factor of multiple
if (factor_[mi] == T_MAX)
factor_[mi] = (T) prime;
// the least significant bit indicates
// whether multiple has an even (0) or odd (1)
// number of prime factors
else if (factor_[mi] != 0)
factor_[mi] ^= 1;
}
if (prime <= sqrty)
{
int64_t j = 0;
int64_t square = prime * prime;
multiple = next_multiple(square, low, &j);
// moebius(n) = 0
for (; multiple <= high; multiple = square * to_number(j++))
factor_[to_index(multiple)] = 0;
}
}
}
}
}
/// mu_lpf(n) is a combination of the mu(n) (Möbius function)
/// and lpf(n) (least prime factor) functions.
/// mu_lpf(n) returns (with n = to_number(index)):
///
/// 1) INT_MAX - 1 if n = 1
/// 2) INT_MAX if n is a prime
/// 3) 0 if moebius(n) = 0
/// 4) lpf - 1 if moebius(n) = 1
/// 5) lpf if moebius(n) = -1
///
int64_t mu_lpf(int64_t index) const
{
return factor_[index];
}
/// Get the Möbius function value of the number
/// n = to_number(index).
///
/// https://en.wikipedia.org/wiki/Möbius_function
/// mu(n) = 1 if n is a square-free integer with an even number of prime factors.
/// mu(n) = −1 if n is a square-free integer with an odd number of prime factors.
/// mu(n) = 0 if n has a squared prime factor.
///
int64_t mu(int64_t index) const
{
if (factor_[index] == 0)
return 0;
else if (factor_[index] & 1)
return -1;
else
return 1;
}
static maxint_t max()
{
maxint_t T_MAX = std::numeric_limits<T>::max();
return ipow(T_MAX - 1, 2) - 1;
}
private:
pod_vector<T> factor_;
};
} // namespace
#endif
| Fix off by 1 error | Fix off by 1 error
| C++ | bsd-2-clause | kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount |
cabe33dfb0c022a3ab1158a88b17b439497e06e2 | agency/experimental/segmented_array.hpp | agency/experimental/segmented_array.hpp | #pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/experimental/ranges/range_traits.hpp>
#include <agency/experimental/ranges/flatten.hpp>
#include <agency/experimental/ranges/all.hpp>
#include <agency/experimental/array.hpp>
#include <agency/experimental/vector.hpp>
#include <memory>
namespace agency
{
namespace experimental
{
// XXX until this thing can resize, call it an array
// XXX probably want to take a single allocator as a parameter instead of two separate allocators
template<class T, class InnerAlloc = allocator<T>, class OuterAlloc = allocator<vector<T,InnerAlloc>>>
class segmented_array
{
public:
using value_type = T;
using reference = value_type&;
using const_reference = const value_type&;
using size_type = std::size_t;
segmented_array() = default;
segmented_array(const segmented_array&) = default;
// constructs a segmented_array with a segment for each allocator
template<class Range,
__AGENCY_REQUIRES(
std::is_constructible<
InnerAlloc,
range_value_t<Range>
>::value
)>
segmented_array(size_type n,
const value_type& val,
const Range& allocators)
{
size_type num_segments = allocators.size();
assert(num_segments > 0);
if(n >= allocators.size())
{
// equally distribute allocations
size_type segment_size = (n + num_segments - 1) / num_segments;
size_type last_segment_size = n - (segment_size * (allocators.size() - 1));
// construct the full segments
auto last_alloc = --allocators.end();
for(auto alloc = allocators.begin(); alloc != last_alloc; ++alloc)
{
segments_.emplace_back(segment_size, val, *alloc);
}
// construct the last segment
segments_.emplace_back(last_segment_size, val, *last_alloc);
}
else
{
// when there are more allocators than there are elements,
// just create a segment for each element
// an alternative would be to create a single segment using the first allocator
// or choose some minimum segment size
// we might want a constructor which accepts a segment_size
auto alloc = allocators.begin();
for(size_type i = 0; i < n; ++i, ++alloc)
{
segments_.emplace_back(1, val, *alloc);
}
}
}
// constructs a segmented_array with a single segment
segmented_array(size_type n, const value_type& val = value_type())
: segmented_array(n, val, array<InnerAlloc,1>{InnerAlloc()})
{}
private:
using segment_type = vector<value_type, InnerAlloc>;
// XXX will want to parameterize the outer allocator used to store the segments
using outer_container = vector<segment_type, OuterAlloc>;
outer_container segments_;
public:
using all_t = flatten_view<outer_container>;
all_t all()
{
return flatten(segments_);
}
using const_all_t = flatten_view<const outer_container>;
const_all_t all() const
{
return flatten(segments_);
}
size_type size() const
{
return all().size();
}
using iterator = range_iterator_t<all_t>;
iterator begin()
{
return all().begin();
}
iterator end()
{
return all().end();
}
using const_iterator = range_iterator_t<const_all_t>;
const_iterator begin() const
{
return all().begin();
}
const_iterator end() const
{
return all().end();
}
using segments_view = decltype(agency::experimental::all(std::declval<const outer_container&>()));
segments_view segments() const
{
return agency::experimental::all(segments_);
}
const segment_type& segment(size_type i) const
{
return segments()[i];
}
using segment_iterator = range_iterator_t<segments_view>;
segment_iterator segments_begin() const
{
return segments().begin();
}
segment_iterator segments_end() const
{
return segments().end();
}
reference operator[](size_type i)
{
return all()[i];
}
const_reference operator[](size_type i) const
{
return all()[i];
}
};
} // end experimental
} // end agency
| #pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/experimental/ranges/range_traits.hpp>
#include <agency/experimental/ranges/flatten.hpp>
#include <agency/experimental/ranges/all.hpp>
#include <agency/experimental/array.hpp>
#include <agency/experimental/vector.hpp>
#include <memory>
namespace agency
{
namespace experimental
{
// XXX until this thing can resize, call it an array
// XXX probably want to take a single allocator as a parameter instead of two separate allocators
template<class T, class InnerAlloc = allocator<T>, class OuterAlloc = allocator<vector<T,InnerAlloc>>>
class segmented_array
{
public:
using value_type = T;
using reference = value_type&;
using const_reference = const value_type&;
using size_type = std::size_t;
segmented_array() = default;
segmented_array(const segmented_array&) = default;
// constructs a segmented_array with a segment for each allocator
template<class Range,
__AGENCY_REQUIRES(
std::is_constructible<
InnerAlloc,
range_value_t<Range>
>::value
)>
segmented_array(size_type n,
const value_type& val,
const Range& allocators)
{
size_type num_segments = allocators.size();
assert(num_segments > 0);
if(n >= allocators.size())
{
// equally distribute allocations
size_type segment_size = (n + num_segments - 1) / num_segments;
size_type last_segment_size = n - (segment_size * (allocators.size() - 1));
// construct the full segments
auto last_alloc = --allocators.end();
for(auto alloc = allocators.begin(); alloc != last_alloc; ++alloc)
{
segments_.emplace_back(segment_size, val, *alloc);
}
// construct the last segment
segments_.emplace_back(last_segment_size, val, *last_alloc);
}
else
{
// when there are more allocators than there are elements,
// just create a segment for each element
// an alternative would be to create a single segment using the first allocator
// or choose some minimum segment size
// we might want a constructor which accepts a segment_size
auto alloc = allocators.begin();
for(size_type i = 0; i < n; ++i, ++alloc)
{
segments_.emplace_back(1, val, *alloc);
}
}
}
// constructs a segmented_array with a single segment
segmented_array(size_type n, const value_type& val = value_type())
: segmented_array(n, val, array<InnerAlloc,1>{InnerAlloc()})
{}
private:
using segment_type = vector<value_type, InnerAlloc>;
// XXX will want to parameterize the outer allocator used to store the segments
using outer_container = vector<segment_type, OuterAlloc>;
outer_container segments_;
public:
using all_t = flatten_view<outer_container>;
all_t all()
{
return flatten(segments_);
}
using const_all_t = flatten_view<const outer_container>;
const_all_t all() const
{
return flatten(segments_);
}
size_type size() const
{
return all().size();
}
using iterator = range_iterator_t<all_t>;
iterator begin()
{
return all().begin();
}
iterator end()
{
return all().end();
}
using const_iterator = range_iterator_t<const_all_t>;
const_iterator begin() const
{
return all().begin();
}
const_iterator end() const
{
return all().end();
}
using segments_view = decltype(agency::experimental::all(std::declval<const outer_container&>()));
segments_view segments() const
{
return agency::experimental::all(segments_);
}
const segment_type& segment(size_type i) const
{
return segments()[i];
}
using segment_iterator = range_iterator_t<segments_view>;
segment_iterator segments_begin() const
{
return segments().begin();
}
segment_iterator segments_end() const
{
return segments().end();
}
reference operator[](size_type i)
{
return all()[i];
}
const_reference operator[](size_type i) const
{
return all()[i];
}
void clear()
{
segments_.clear();
}
bool operator==(const segmented_array& rhs) const
{
return segments_ == rhs.segments_;
}
};
} // end experimental
} // end agency
| Add segmented_array::clear() and segmented_array::operator== | Add segmented_array::clear() and segmented_array::operator==
| C++ | bsd-3-clause | egaburov/agency,egaburov/agency |
bb59616bf157430cd5dc6a56781c25ba8bdc5443 | typedecl.hpp | typedecl.hpp | #ifndef __ARRAYS_HPP__
#define __ARRAYS_HPP__
#include <string>
#include <type_traits>
#include "../static-strings/static-strings.hpp"
#ifdef __CYGWIN__
#include <sstream>
namespace std {
inline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }
}
#endif
namespace {
namespace __typedecl {
struct split_string {
std::string begin;
std::string end;
explicit operator std::string() const {
return begin + end;
}
};
inline split_string operator+(const std::string& s, const split_string& ss) {
return { s + ss.begin, ss.end };
}
inline split_string operator+(const split_string& ss, const std::string& s) {
return { ss.begin, ss.end + s };
}
using empty_ss = static_string::static_string<char>;
using space_ss = static_string::static_string<char, ' '>;
template <typename B, typename E>
struct sss {
using begin = B;
using end = E;
inline static std::string string() {
return begin::string() + end::string();
}
};
using empty_sss = sss<empty_ss, empty_ss>;
template <typename, typename>
struct sssconcat_impl;
template <char... chars, typename SSS>
struct sssconcat_impl<static_string::static_string<char, chars...>, SSS> {
using _begin = static_string::concat<
static_string::static_string<char, chars...>,
typename SSS::begin
>;
using type = sss<_begin, typename SSS::end>;
};
template <typename T1, typename T2>
using sssconcat = typename sssconcat_impl<T1, T2>::type;
template <typename T>
struct impl;
template <typename T>
struct is_basic_type {
// SFINAE!
template <typename I>
static constexpr bool test(typename I::template ssstring_with_cv_qual<empty_ss, empty_sss> *) {
return true;
}
template <typename I>
static constexpr bool test(...) {
return false;
}
enum { value = test<impl<T>>(nullptr) };
};
template <typename T, typename SuffixSSS, typename CVQualSS, bool = is_basic_type<T>::value>
struct prefix_cv_qual_if_basictype;
template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, true> {
using ssstring = typename impl<T>::template ssstring_with_cv_qual<CVQualSS, SuffixSSS>;
};
template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, false> {
using ssstring = typename impl<T>::template ssstring<sssconcat<CVQualSS, SuffixSSS>>;
};
template <typename T>
struct _prefix_cv_qual_if_basictype {
/*
* == SFINAE ==
* If impl<T> has a static member function named "value_with_cv_qual", then
* the forward() overload below is defined, and the call for forward() will
* prefer this overload over the other one that has varargs ("...").
* If impl<T> does not have such member, then the varargs overload is the
* only option.
*/
template <typename I>
inline static split_string forward(const std::string& cv_qual, const split_string& suffix, decltype(I::value_with_cv_qual)*) {
return I::value_with_cv_qual(cv_qual, suffix);
}
template <typename I>
inline static split_string forward(const std::string& cv_qual, const split_string& suffix, ...) {
return I::value(cv_qual + suffix);
}
inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
return forward<impl<T>>(cv_qual, suffix, nullptr);
}
};
template <typename T>
struct has_ssstring {
// SFINAE!
template <typename TT>
constexpr static bool test(typename TT::template ssstring<>*) { return true; }
template <typename TT>
constexpr static bool test(...) { return false; }
enum { value = test<impl<T>>(nullptr) };
};
template <typename T, typename CVQualSS, bool = has_ssstring<T>::value>
struct cvqualified_impl;
template <typename T, typename CVQualSS>
struct cvqualified_impl<T, CVQualSS, true> {
template <typename SuffixSSS = empty_sss>
using ssstring = typename prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS>::ssstring;
};
template <typename T, typename CVQualSS>
struct cvqualified_impl<T, CVQualSS, false> {};
template <typename T>
struct impl<const T> : cvqualified_impl<T, static_string::static_string<char, 'c','o','n','s','t'>> {
inline static split_string value(const split_string& suffix = {}) {
return _prefix_cv_qual_if_basictype<T>::value("const", suffix);
}
};
template <typename T>
struct impl<volatile T> : cvqualified_impl<T, static_string::static_string<char, 'v','o','l','a','t','i','l','e'>> {
inline static split_string value(const split_string& suffix = {}) {
return _prefix_cv_qual_if_basictype<T>::value("volatile", suffix);
}
};
// Required to disambiguate between <const T> and <volatile T>
template <typename T>
struct impl<const volatile T> {
inline static split_string value(const split_string& suffix = {}) {
return _prefix_cv_qual_if_basictype<T>::value("const volatile", suffix);
}
};
template <typename T>
struct is_array_or_function : std::integral_constant<
bool,
std::is_array<T>::value || std::is_function<T>::value
> {};
template <typename T, bool = is_array_or_function<T>::value>
struct parenthesize_if_array_or_function;
template <typename T>
struct parenthesize_if_array_or_function<T, false> {
inline static split_string value(const split_string& arg) {
return impl<T>::value(arg);
}
};
template <typename T>
struct parenthesize_if_array_or_function<T, true> {
inline static split_string value(const split_string& arg) {
return impl<T>::value("(" + arg + ")");
}
};
template <typename T>
struct impl<T*> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("*" + suffix);
}
};
template <typename T>
struct impl<T&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&" + suffix);
}
};
template <typename T>
struct impl<T&&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&&" + suffix);
}
};
template <typename T>
struct array_impl {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + "[]");
}
};
template <typename T>
struct impl<T[]> : array_impl<T> {};
// Required to disambiguate between <const T> and <T[]>
template <typename T>
struct impl<const T[]> : array_impl<const T> {};
// Required to disambiguate between <volatile T> and <T[]>
template <typename T>
struct impl<volatile T[]> : array_impl<volatile T> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[]>, <const T[]> and <volatile T[]>
template <typename T>
struct impl<const volatile T[]> : array_impl<const volatile T> {};
template <typename T, size_t N>
struct sized_array_impl {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + ("[" + std::to_string(N) + "]"));
}
};
template <typename T, size_t N>
struct impl<T[N]> : sized_array_impl<T, N> {};
// Required to disambiguate between <const T> and <T[N]>
template <typename T, size_t N>
struct impl<const T[N]> : sized_array_impl<const T, N> {};
// Required to disambiguate between <volatile T> and <T[N]>
template <typename T, size_t N>
struct impl<volatile T[N]> : sized_array_impl<volatile T, N> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[N]>, <const T[N]> and <volatile T[N]>
template <typename T, size_t N>
struct impl<const volatile T[N]> : sized_array_impl<const volatile T, N> {};
template <typename... T>
struct type_list_impl;
template <>
struct type_list_impl<> {
inline static std::string value() {
return "";
}
};
struct varargs;
template <>
struct type_list_impl<varargs> {
inline static std::string value() {
return "...";
}
};
template <typename T>
struct type_list_impl<T> {
inline static std::string value() {
return static_cast<std::string>(impl<T>::value());
}
};
template <typename T1, typename T2, typename... U>
struct type_list_impl<T1, T2, U...> {
inline static std::string value() {
return type_list_impl<T1>::value() + ", " + type_list_impl<T2, U...>::value();
}
};
template <bool RIsPtrOrRef, typename R, typename... A>
struct function_impl;
template <typename R, typename... A>
struct function_impl<false, R, A...> {
inline static split_string value(const split_string& infix = {}) {
return static_cast<std::string>(impl<R>::value()) + infix + "(" + type_list_impl<A...>::value() + ")";
}
};
template <typename R, typename... A>
struct function_impl<true, R, A...> {
inline static split_string value(const split_string& prefix = {}) {
return impl<R>::value(prefix + "(" + type_list_impl<A...>::value() + ")");
}
};
template <typename T>
struct is_pointer_or_reference : std::integral_constant<
bool,
std::is_pointer<T>::value || std::is_reference<T>::value
> {};
template <typename R, typename... A>
struct function_args_impl : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, A...> {};
template <typename R, typename... A>
struct impl<R(A...)> : function_args_impl<R, A...> {};
template <typename R, typename... A>
struct impl<R(A..., ...)> : function_args_impl<R, A..., varargs> {};
template <typename T>
struct str_provider;
template <typename T, bool = has_ssstring<T>::value>
struct impl_proxy;
template <typename T>
struct impl_proxy<T, true> {
inline static std::string value(const std::string& arg = "") {
using i_sss = typename impl<T>::template ssstring<>;
return i_sss::begin::string() + arg + i_sss::end::string();
}
};
template <typename T>
struct impl_proxy<T, false> {
inline static std::string value(const std::string& arg = "") {
split_string ss = impl<T>::value();
return ss.begin + arg + ss.end;
}
};
} /* namespace __typedecl */
} /* unnamed namespace */
template <typename T>
inline std::string typedecl() {
return __typedecl::impl_proxy<T>::value();
}
template <typename T>
inline std::string namedecl(const std::string& name) {
return __typedecl::impl_proxy<T>::value(' ' + name);
}
#define DEFINE_TYPEDECL(T) \
namespace { \
namespace __typedecl { \
template <> \
struct str_provider<T> { \
static constexpr const char* str() { return #T; } \
}; \
template <> \
struct impl<T> { \
using _token_ss = static_string::from_provider<str_provider<T>>; \
template <typename SuffixSSS = empty_sss> using ssstring = sssconcat<_token_ss, SuffixSSS>; \
template <typename CVQualSS, typename SuffixSSS> \
using ssstring_with_cv_qual = sssconcat< \
static_string::concat<CVQualSS, space_ss, _token_ss>, \
SuffixSSS \
>; \
inline static split_string value(const split_string& suffix = {}) { \
return #T + suffix; \
} \
inline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \
return (cv_qual + " " #T) + suffix; \
} \
}; \
} /* namespace __typedecl */ \
} /* unnamed namespace */
DEFINE_TYPEDECL(void);
DEFINE_TYPEDECL(char);
DEFINE_TYPEDECL(int);
#endif
| #ifndef __ARRAYS_HPP__
#define __ARRAYS_HPP__
#include <string>
#include <type_traits>
#include "../static-strings/static-strings.hpp"
#ifdef __CYGWIN__
#include <sstream>
namespace std {
inline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }
}
#endif
namespace {
namespace __typedecl {
struct split_string {
std::string begin;
std::string end;
explicit operator std::string() const {
return begin + end;
}
};
inline split_string operator+(const std::string& s, const split_string& ss) {
return { s + ss.begin, ss.end };
}
inline split_string operator+(const split_string& ss, const std::string& s) {
return { ss.begin, ss.end + s };
}
using empty_ss = static_string::static_string<char>;
using space_ss = static_string::static_string<char, ' '>;
template <typename B, typename E>
struct sss {
using begin = B;
using end = E;
inline static std::string string() {
return begin::string() + end::string();
}
};
using empty_sss = sss<empty_ss, empty_ss>;
template <typename, typename>
struct sssconcat_impl;
template <char... chars, typename SSS>
struct sssconcat_impl<static_string::static_string<char, chars...>, SSS> {
using _begin = static_string::concat<
static_string::static_string<char, chars...>,
typename SSS::begin
>;
using type = sss<_begin, typename SSS::end>;
};
template <typename T1, typename T2>
using sssconcat = typename sssconcat_impl<T1, T2>::type;
template <typename T>
struct impl;
template <typename T>
struct is_basic_type {
// SFINAE!
template <typename I>
static constexpr bool test(typename I::template ssstring_with_cv_qual<empty_ss, empty_sss> *) {
return true;
}
template <typename I>
static constexpr bool test(...) {
return false;
}
enum { value = test<impl<T>>(nullptr) };
};
template <typename T, typename SuffixSSS, typename CVQualSS, bool = is_basic_type<T>::value>
struct prefix_cv_qual_if_basictype;
template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, true> {
using ssstring = typename impl<T>::template ssstring_with_cv_qual<CVQualSS, SuffixSSS>;
};
template <typename T, typename SuffixSSS, typename CVQualSS>
struct prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS, false> {
using ssstring = typename impl<T>::template ssstring<sssconcat<CVQualSS, SuffixSSS>>;
};
template <typename T>
struct _prefix_cv_qual_if_basictype {
/*
* == SFINAE ==
* If impl<T> has a static member function named "value_with_cv_qual", then
* the forward() overload below is defined, and the call for forward() will
* prefer this overload over the other one that has varargs ("...").
* If impl<T> does not have such member, then the varargs overload is the
* only option.
*/
template <typename I>
inline static split_string forward(const std::string& cv_qual, const split_string& suffix, decltype(I::value_with_cv_qual)*) {
return I::value_with_cv_qual(cv_qual, suffix);
}
template <typename I>
inline static split_string forward(const std::string& cv_qual, const split_string& suffix, ...) {
return I::value(cv_qual + suffix);
}
inline static split_string value(const std::string& cv_qual, const split_string& suffix) {
return forward<impl<T>>(cv_qual, suffix, nullptr);
}
};
template <typename T>
struct has_ssstring {
// SFINAE!
template <typename TT>
constexpr static bool test(typename TT::template ssstring<>*) { return true; }
template <typename TT>
constexpr static bool test(...) { return false; }
enum { value = test<impl<T>>(nullptr) };
};
template <typename T, typename CVQualSS, bool = has_ssstring<T>::value>
struct cvqualified_impl;
template <typename T, typename CVQualSS>
struct cvqualified_impl<T, CVQualSS, true> {
template <typename SuffixSSS = empty_sss>
using ssstring = typename prefix_cv_qual_if_basictype<T, SuffixSSS, CVQualSS>::ssstring;
};
template <typename T, typename CVQualSS>
struct cvqualified_impl<T, CVQualSS, false> {};
using const_ss = static_string::static_string<char, 'c','o','n','s','t'>;
template <typename T>
struct impl<const T> : cvqualified_impl<T, const_ss> {
inline static split_string value(const split_string& suffix = {}) {
return _prefix_cv_qual_if_basictype<T>::value("const", suffix);
}
};
using volatile_ss = static_string::static_string<char, 'v','o','l','a','t','i','l','e'>;
template <typename T>
struct impl<volatile T> : cvqualified_impl<T, volatile_ss> {
inline static split_string value(const split_string& suffix = {}) {
return _prefix_cv_qual_if_basictype<T>::value("volatile", suffix);
}
};
// Required to disambiguate between <const T> and <volatile T>
template <typename T>
struct impl<const volatile T>
: cvqualified_impl<T, static_string::concat<const_ss, space_ss, volatile_ss>>
{
inline static split_string value(const split_string& suffix = {}) {
return _prefix_cv_qual_if_basictype<T>::value("const volatile", suffix);
}
};
template <typename T>
struct is_array_or_function : std::integral_constant<
bool,
std::is_array<T>::value || std::is_function<T>::value
> {};
template <typename T, bool = is_array_or_function<T>::value>
struct parenthesize_if_array_or_function;
template <typename T>
struct parenthesize_if_array_or_function<T, false> {
inline static split_string value(const split_string& arg) {
return impl<T>::value(arg);
}
};
template <typename T>
struct parenthesize_if_array_or_function<T, true> {
inline static split_string value(const split_string& arg) {
return impl<T>::value("(" + arg + ")");
}
};
template <typename T>
struct impl<T*> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("*" + suffix);
}
};
template <typename T>
struct impl<T&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&" + suffix);
}
};
template <typename T>
struct impl<T&&> {
inline static split_string value(const split_string& suffix = {}) {
return parenthesize_if_array_or_function<T>::value("&&" + suffix);
}
};
template <typename T>
struct array_impl {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + "[]");
}
};
template <typename T>
struct impl<T[]> : array_impl<T> {};
// Required to disambiguate between <const T> and <T[]>
template <typename T>
struct impl<const T[]> : array_impl<const T> {};
// Required to disambiguate between <volatile T> and <T[]>
template <typename T>
struct impl<volatile T[]> : array_impl<volatile T> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[]>, <const T[]> and <volatile T[]>
template <typename T>
struct impl<const volatile T[]> : array_impl<const volatile T> {};
template <typename T, size_t N>
struct sized_array_impl {
inline static split_string value(const split_string& prefix = {}) {
return impl<T>::value(prefix + ("[" + std::to_string(N) + "]"));
}
};
template <typename T, size_t N>
struct impl<T[N]> : sized_array_impl<T, N> {};
// Required to disambiguate between <const T> and <T[N]>
template <typename T, size_t N>
struct impl<const T[N]> : sized_array_impl<const T, N> {};
// Required to disambiguate between <volatile T> and <T[N]>
template <typename T, size_t N>
struct impl<volatile T[N]> : sized_array_impl<volatile T, N> {};
// Required to disambiguate between <const T>, <volatile T>, <const volatile T>, <T[N]>, <const T[N]> and <volatile T[N]>
template <typename T, size_t N>
struct impl<const volatile T[N]> : sized_array_impl<const volatile T, N> {};
template <typename... T>
struct type_list_impl;
template <>
struct type_list_impl<> {
inline static std::string value() {
return "";
}
};
struct varargs;
template <>
struct type_list_impl<varargs> {
inline static std::string value() {
return "...";
}
};
template <typename T>
struct type_list_impl<T> {
inline static std::string value() {
return static_cast<std::string>(impl<T>::value());
}
};
template <typename T1, typename T2, typename... U>
struct type_list_impl<T1, T2, U...> {
inline static std::string value() {
return type_list_impl<T1>::value() + ", " + type_list_impl<T2, U...>::value();
}
};
template <bool RIsPtrOrRef, typename R, typename... A>
struct function_impl;
template <typename R, typename... A>
struct function_impl<false, R, A...> {
inline static split_string value(const split_string& infix = {}) {
return static_cast<std::string>(impl<R>::value()) + infix + "(" + type_list_impl<A...>::value() + ")";
}
};
template <typename R, typename... A>
struct function_impl<true, R, A...> {
inline static split_string value(const split_string& prefix = {}) {
return impl<R>::value(prefix + "(" + type_list_impl<A...>::value() + ")");
}
};
template <typename T>
struct is_pointer_or_reference : std::integral_constant<
bool,
std::is_pointer<T>::value || std::is_reference<T>::value
> {};
template <typename R, typename... A>
struct function_args_impl : function_impl<is_pointer_or_reference<typename std::remove_cv<R>::type>::value, R, A...> {};
template <typename R, typename... A>
struct impl<R(A...)> : function_args_impl<R, A...> {};
template <typename R, typename... A>
struct impl<R(A..., ...)> : function_args_impl<R, A..., varargs> {};
template <typename T>
struct str_provider;
template <typename T, bool = has_ssstring<T>::value>
struct impl_proxy;
template <typename T>
struct impl_proxy<T, true> {
inline static std::string value(const std::string& arg = "") {
using i_sss = typename impl<T>::template ssstring<>;
return i_sss::begin::string() + arg + i_sss::end::string();
}
};
template <typename T>
struct impl_proxy<T, false> {
inline static std::string value(const std::string& arg = "") {
split_string ss = impl<T>::value();
return ss.begin + arg + ss.end;
}
};
} /* namespace __typedecl */
} /* unnamed namespace */
template <typename T>
inline std::string typedecl() {
return __typedecl::impl_proxy<T>::value();
}
template <typename T>
inline std::string namedecl(const std::string& name) {
return __typedecl::impl_proxy<T>::value(' ' + name);
}
#define DEFINE_TYPEDECL(T) \
namespace { \
namespace __typedecl { \
template <> \
struct str_provider<T> { \
static constexpr const char* str() { return #T; } \
}; \
template <> \
struct impl<T> { \
using _token_ss = static_string::from_provider<str_provider<T>>; \
template <typename SuffixSSS = empty_sss> using ssstring = sssconcat<_token_ss, SuffixSSS>; \
template <typename CVQualSS, typename SuffixSSS> \
using ssstring_with_cv_qual = sssconcat< \
static_string::concat<CVQualSS, space_ss, _token_ss>, \
SuffixSSS \
>; \
inline static split_string value(const split_string& suffix = {}) { \
return #T + suffix; \
} \
inline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \
return (cv_qual + " " #T) + suffix; \
} \
}; \
} /* namespace __typedecl */ \
} /* unnamed namespace */
DEFINE_TYPEDECL(void);
DEFINE_TYPEDECL(char);
DEFINE_TYPEDECL(int);
#endif
| Implement impl<const volatile T> with static-strings | Implement impl<const volatile T> with static-strings
| C++ | mit | erdavila/typedecl,erdavila/typedecl |
Subsets and Splits