text stringlengths 54 60.6k |
|---|
<commit_before>/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
// Third party includes
#include <boost/interprocess/sync/file_lock.hpp>
// VOTCA includes
#include <votca/tools/filesystem.h>
// Local VOTCA includes
#include "votca/xtp/statesaver.h"
#include "votca/xtp/topology.h"
namespace votca {
namespace xtp {
std::vector<Index> StateSaver::getFrames() const {
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ);
CheckpointReader r = cpf.getReader();
std::vector<Index> frames = std::vector<Index>{};
try {
r(frames, "frames");
} catch (std::runtime_error&) {
;
}
return frames;
}
void StateSaver::WriteFrame(const Topology& top) {
if (!tools::filesystem::FileExists(_hdf5file)) {
std::cout << "Creating statefile " << _hdf5file << std::endl;
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::CREATE);
}
boost::interprocess::file_lock flock(_hdf5file.c_str());
flock.lock();
if (!TopStepisinFrames(top.getStep())) {
std::vector<Index> frames = this->getFrames();
frames.push_back(top.getStep());
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY);
CheckpointWriter w = cpf.getWriter();
w(frames, "frames");
std::cout << "Frame with id " << top.getStep() << " was not in statefile "
<< _hdf5file << " ,adding it now." << std::endl;
}
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY);
CheckpointWriter w = cpf.getWriter("/frame_" + std::to_string(top.getStep()));
top.WriteToCpt(w);
flock.unlock();
std::cout << "Writing MD topology (step = " << top.getStep()
<< ", time = " << top.getTime() << ") to " << _hdf5file
<< std::endl;
std::cout << "... ";
std::cout << ". " << std::endl;
return;
}
Topology StateSaver::ReadFrame(Index frameid) const {
if (!tools::filesystem::FileExists(_hdf5file)) {
throw std::runtime_error("Statefile " + _hdf5file + " does not exist.");
}
std::cout << "Import MD Topology (i.e. frame " << frameid << ")"
<< " from " << _hdf5file << std::endl;
std::cout << "...";
boost::interprocess::file_lock flock(_hdf5file.c_str());
flock.lock();
if (!TopStepisinFrames(frameid)) {
throw std::runtime_error("Frame with id " + std::to_string(frameid) +
" is not in statefile.");
}
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ);
CheckpointReader r = cpf.getReader("/frame_" + std::to_string(frameid));
Topology top;
top.ReadFromCpt(r);
flock.unlock();
std::cout << ". " << std::endl;
return top;
}
bool StateSaver::TopStepisinFrames(Index frameid) const {
std::vector<Index> frames = this->getFrames();
return std::find(frames.begin(), frames.end(), frameid) != frames.end();
}
} // namespace xtp
} // namespace votca
<commit_msg>changed output a bit<commit_after>/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
// Third party includes
#include <boost/interprocess/sync/file_lock.hpp>
// VOTCA includes
#include <votca/tools/filesystem.h>
// Local VOTCA includes
#include "votca/xtp/statesaver.h"
#include "votca/xtp/topology.h"
namespace votca {
namespace xtp {
std::vector<Index> StateSaver::getFrames() const {
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ);
CheckpointReader r = cpf.getReader();
std::vector<Index> frames = std::vector<Index>{};
try {
r(frames, "frames");
} catch (std::runtime_error&) {
;
}
return frames;
}
void StateSaver::WriteFrame(const Topology& top) {
if (!tools::filesystem::FileExists(_hdf5file)) {
std::cout << "Creating statefile " << _hdf5file << std::endl;
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::CREATE);
}
boost::interprocess::file_lock flock(_hdf5file.c_str());
flock.lock();
if (!TopStepisinFrames(top.getStep())) {
std::vector<Index> frames = this->getFrames();
frames.push_back(top.getStep());
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY);
CheckpointWriter w = cpf.getWriter();
w(frames, "frames");
std::cout << "Frame with id " << top.getStep() << " was not in statefile "
<< _hdf5file << " ,adding it now." << std::endl;
}
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY);
CheckpointWriter w = cpf.getWriter("/frame_" + std::to_string(top.getStep()));
top.WriteToCpt(w);
flock.unlock();
std::cout << "Wrote MD topology (step = " << top.getStep()
<< ", time = " << top.getTime() << ") to " << _hdf5file
<< std::endl;
std::cout << "... ";
std::cout << ". " << std::endl;
return;
}
Topology StateSaver::ReadFrame(Index frameid) const {
if (!tools::filesystem::FileExists(_hdf5file)) {
throw std::runtime_error("Statefile " + _hdf5file + " does not exist.");
}
std::cout << "Import MD Topology (i.e. frame " << frameid << ")"
<< " from " << _hdf5file << std::endl;
std::cout << "...";
boost::interprocess::file_lock flock(_hdf5file.c_str());
flock.lock();
if (!TopStepisinFrames(frameid)) {
throw std::runtime_error("Frame with id " + std::to_string(frameid) +
" is not in statefile.");
}
CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ);
CheckpointReader r = cpf.getReader("/frame_" + std::to_string(frameid));
Topology top;
top.ReadFromCpt(r);
flock.unlock();
std::cout << ". " << std::endl;
return top;
}
bool StateSaver::TopStepisinFrames(Index frameid) const {
std::vector<Index> frames = this->getFrames();
return std::find(frames.begin(), frames.end(), frameid) != frames.end();
}
} // namespace xtp
} // namespace votca
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_JULIA_HPP
#define XTENSOR_JULIA_HPP
#include <cstddef>
#include <array>
#include <algorithm>
#include <exception>
#include "xtensor/xsemantic.hpp"
#include "type_conversion.hpp"
#include "jlbuffer_adaptor.hpp"
#include "jlcontainer.hpp"
namespace xt
{
/************************
* jltensor declaration *
************************/
template <class T, std::size_t N>
class jltensor;
template <class T, std::size_t N>
struct xiterable_inner_types<jltensor<T, N>>
: xcontainer_iterable_types<jltensor<T, N>>
{
};
template <class T, std::size_t N>
struct xcontainer_inner_types<jltensor<T, N>>
{
using container_type = jlbuffer_adaptor<cxx_wrap::mapped_julia_type<T>>;
using shape_type = std::array<std::size_t, N>;
using strides_type = shape_type;
using backstrides_type = shape_type;
using inner_shape_type = shape_type;
using inner_strides_type = strides_type;
using inner_backstrides_type = backstrides_type;
using temporary_type = jltensor<T, N>;
};
template <class T, std::size_t N>
class jltensor : public jlcontainer<jltensor<T, N>>,
public xcontainer_semantic<jltensor<T, N>>
{
public:
using self_type = jltensor<T, N>;
using semantic_base = xcontainer_semantic<self_type>;
using base_type = jlcontainer<self_type>;
using container_type = typename base_type::container_type;
using value_type = typename base_type::value_type;
using reference = typename base_type::reference;
using const_reference = typename base_type::const_reference;
using pointer = typename base_type::pointer;
using size_type = typename base_type::size_type;
using shape_type = typename base_type::shape_type;
using strides_type = typename base_type::strides_type;
using backstrides_type = typename base_type::backstrides_type;
using inner_shape_type = typename base_type::inner_shape_type;
using inner_strides_type = typename base_type::inner_strides_type;
using inner_backstrides_type = typename base_type::inner_backstrides_type;
jltensor();
jltensor(const self_type&);
jltensor(self_type&&) = default;
jltensor(nested_initializer_list_t<T, N> t);
explicit jltensor(const shape_type& shape);
explicit jltensor(const shape_type& shape, const_reference value);
explicit jltensor(jl_array_t* jl);
self_type& operator=(const self_type&);
self_type& operator=(self_type&&) = default;
template <class E>
jltensor(const xexpression<E>& e);
template <class E>
self_type& operator=(const xexpression<E>& e);
using base_type::begin;
using base_type::end;
private:
inner_shape_type m_shape;
inner_strides_type m_strides;
inner_backstrides_type m_backstrides;
container_type m_data;
void init_tensor(const shape_type& shape);
void init_from_julia();
inner_shape_type& shape_impl() noexcept;
const inner_shape_type& shape_impl() const noexcept;
inner_strides_type& strides_impl() noexcept;
const inner_strides_type& strides_impl() const noexcept;
inner_backstrides_type& backstrides_impl() noexcept;
const inner_backstrides_type& backstrides_impl() const noexcept;
container_type& data_impl() noexcept;
const container_type& data_impl() const noexcept;
friend class xcontainer<jltensor<T, N>>;
};
/***************************
* jltensor implementation *
***************************/
/**
* @name Constructors
*/
//@{
/**
* Allocates a jltensor that holds 1 element.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor()
: base_type()
{
m_shape = make_sequence<shape_type>(N, size_type(1));
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
m_data[0] = T();
}
/**
* Allocates a jltensor with a nested initializer list.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(nested_initializer_list_t<T, N> t)
: base_type()
{
base_type::reshape(xt::shape<shape_type>(t));
nested_copy(this->xbegin(), t);
}
/**
* Allocates an uninitialized jltensor with the specified shape and
* layout.
* @param shape the shape of the jltensor
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(const shape_type& shape)
: m_shape(shape)
{
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
}
/**
* Allocates a jltensor with the specified shape and layout. Elements
* are initialized to the specified value.
* @param shape the shape of the jltensor
* @param value the value of the elements
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(const shape_type& shape,
const_reference value)
: m_shape(shape)
{
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
std::fill(m_data.begin(), m_data.end(), value);
}
/**
* Allocates a jltensor that holds 1 element.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(jl_array_t* jl)
: base_type(jl)
{
init_from_julia();
}
//@}
/**
* @name Copy semantic
*/
//@{
/**
* The copy constructor.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(const self_type& rhs)
: base_type(), m_shape(rhs.shape())
{
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
std::copy(rhs.data().begin(), rhs.data().end(), this->data().begin());
}
/**
* The assignment operator.
*/
template <class T, std::size_t N>
inline auto jltensor<T, N>::operator=(const self_type& rhs) -> self_type&
{
self_type tmp(rhs);
*this = std::move(tmp);
return *this;
}
//@}
/**
* @name Extended copy semantic
*/
//@{
/**
* The extended copy constructor.
*/
template <class T, std::size_t N>
template <class E>
inline jltensor<T, N>::jltensor(const xexpression<E>& e)
: base_type()
{
m_shape = forward_sequence<shape_type>(e.derived_cast().shape());
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
semantic_base::assign(e);
}
/**
* The extended assignment operator.
*/
template <class T, std::size_t N>
template <class E>
inline auto jltensor<T, N>::operator=(const xexpression<E>& e) -> self_type&
{
return semantic_base::operator=(e);
}
//@}
template <class T, std::size_t N>
inline void jltensor<T, N>::init_tensor(const shape_type& shape)
{
jl_value_t* array_type = cxx_wrap::apply_array_type(cxx_wrap::static_type_mapping<value_type>::julia_type(), N);
// make tuple_type for shape
jl_svec_t* jtypes = jl_alloc_svec(N);
for (std::size_t i = 0; i < N; ++i)
{
jl_svecset(jtypes, i, cxx_wrap::julia_type<typename shape_type::value_type>());
}
jl_datatype_t* tuple_type = jl_apply_tuple_type(jtypes);
// allocate array
jl_value_t* dims = jl_new_bits((jl_value_t*)tuple_type, const_cast<void*>(reinterpret_cast<const void*>(shape.data())));
this->p_array = jl_new_array((jl_value_t*)array_type, dims);
// setup buffer adaptor
m_data = container_type(reinterpret_cast<pointer>(this->p_array->data),
static_cast<size_type>(jl_array_len(this->p_array)));
}
template <class T, std::size_t N>
inline void jltensor<T, N>::init_from_julia()
{
if (this->p_array->flags.ndims != N)
{
throw std::runtime_error("Julia array has incorrect number of dimensions");
}
std::copy(&(this->p_array->nrows), &(this->p_array->nrows) + N, m_shape.begin());
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
m_data = container_type(reinterpret_cast<pointer>(this->p_array->data),
static_cast<size_type>(jl_array_len(this->p_array)));
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::shape_impl() noexcept -> inner_shape_type&
{
return m_shape;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::shape_impl() const noexcept -> const inner_shape_type&
{
return m_shape;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::strides_impl() noexcept -> inner_strides_type&
{
return m_strides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::strides_impl() const noexcept -> const inner_strides_type&
{
return m_strides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::backstrides_impl() noexcept -> inner_backstrides_type&
{
return m_backstrides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::backstrides_impl() const noexcept -> const inner_backstrides_type&
{
return m_backstrides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::data_impl() noexcept -> container_type&
{
return m_data;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::data_impl() const noexcept -> const container_type&
{
return m_data;
}
}
namespace cxx_wrap
{
/****************************************************************
* Template specializations for ConvertToJulia and ConvertToCpp *
****************************************************************/
template <class T, std::size_t N>
struct ConvertToJulia<xt::jltensor<T, N>, false, false, false>
{
template <class U>
jl_array_t* operator()(U&& arr) const
{
return arr.wrapped();
}
};
template <class T, std::size_t N>
struct ConvertToCpp<xt::jltensor<T, N>, false, false, false>
{
xt::jltensor<T, N> operator()(jl_array_t* arr) const
{
return xt::jltensor<T, N>(arr);
}
};
// Conversions
template<class T, std::size_t N>
struct static_type_mapping<xt::jltensor<T, N>>
{
using type = jl_array_t*;
static constexpr bool is_dynamic = false;
static jl_datatype_t* julia_type()
{
return (jl_datatype_t*)apply_array_type(static_type_mapping<T>::julia_type(), N);
}
};
}
#endif
<commit_msg>Static Julia types<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_JULIA_HPP
#define XTENSOR_JULIA_HPP
#include <cstddef>
#include <array>
#include <algorithm>
#include <exception>
#include "xtensor/xsemantic.hpp"
#include "type_conversion.hpp"
#include "jlbuffer_adaptor.hpp"
#include "jlcontainer.hpp"
namespace xt
{
/************************
* jltensor declaration *
************************/
template <class T, std::size_t N>
class jltensor;
template <class T, std::size_t N>
struct xiterable_inner_types<jltensor<T, N>>
: xcontainer_iterable_types<jltensor<T, N>>
{
};
template <class T, std::size_t N>
struct xcontainer_inner_types<jltensor<T, N>>
{
using container_type = jlbuffer_adaptor<cxx_wrap::mapped_julia_type<T>>;
using shape_type = std::array<std::size_t, N>;
using strides_type = shape_type;
using backstrides_type = shape_type;
using inner_shape_type = shape_type;
using inner_strides_type = strides_type;
using inner_backstrides_type = backstrides_type;
using temporary_type = jltensor<T, N>;
};
template <class T, std::size_t N>
class jltensor : public jlcontainer<jltensor<T, N>>,
public xcontainer_semantic<jltensor<T, N>>
{
public:
using self_type = jltensor<T, N>;
using semantic_base = xcontainer_semantic<self_type>;
using base_type = jlcontainer<self_type>;
using container_type = typename base_type::container_type;
using value_type = typename base_type::value_type;
using reference = typename base_type::reference;
using const_reference = typename base_type::const_reference;
using pointer = typename base_type::pointer;
using size_type = typename base_type::size_type;
using shape_type = typename base_type::shape_type;
using strides_type = typename base_type::strides_type;
using backstrides_type = typename base_type::backstrides_type;
using inner_shape_type = typename base_type::inner_shape_type;
using inner_strides_type = typename base_type::inner_strides_type;
using inner_backstrides_type = typename base_type::inner_backstrides_type;
jltensor();
jltensor(const self_type&);
jltensor(self_type&&) = default;
jltensor(nested_initializer_list_t<T, N> t);
explicit jltensor(const shape_type& shape);
explicit jltensor(const shape_type& shape, const_reference value);
explicit jltensor(jl_array_t* jl);
self_type& operator=(const self_type&);
self_type& operator=(self_type&&) = default;
template <class E>
jltensor(const xexpression<E>& e);
template <class E>
self_type& operator=(const xexpression<E>& e);
using base_type::begin;
using base_type::end;
private:
inner_shape_type m_shape;
inner_strides_type m_strides;
inner_backstrides_type m_backstrides;
container_type m_data;
void init_tensor(const shape_type& shape);
void init_from_julia();
inner_shape_type& shape_impl() noexcept;
const inner_shape_type& shape_impl() const noexcept;
inner_strides_type& strides_impl() noexcept;
const inner_strides_type& strides_impl() const noexcept;
inner_backstrides_type& backstrides_impl() noexcept;
const inner_backstrides_type& backstrides_impl() const noexcept;
container_type& data_impl() noexcept;
const container_type& data_impl() const noexcept;
static jl_datatype_t* make_julia_shape_type();
static jl_value_t* make_julia_array_type();
friend class xcontainer<jltensor<T, N>>;
};
/***************************
* jltensor implementation *
***************************/
/**
* @name Constructors
*/
//@{
/**
* Allocates a jltensor that holds 1 element.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor()
: base_type()
{
m_shape = make_sequence<shape_type>(N, size_type(1));
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
m_data[0] = T();
}
/**
* Allocates a jltensor with a nested initializer list.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(nested_initializer_list_t<T, N> t)
: base_type()
{
base_type::reshape(xt::shape<shape_type>(t));
nested_copy(this->xbegin(), t);
}
/**
* Allocates an uninitialized jltensor with the specified shape and
* layout.
* @param shape the shape of the jltensor
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(const shape_type& shape)
: m_shape(shape)
{
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
}
/**
* Allocates a jltensor with the specified shape and layout. Elements
* are initialized to the specified value.
* @param shape the shape of the jltensor
* @param value the value of the elements
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(const shape_type& shape,
const_reference value)
: m_shape(shape)
{
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
std::fill(m_data.begin(), m_data.end(), value);
}
/**
* Allocates a jltensor that holds 1 element.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(jl_array_t* jl)
: base_type(jl)
{
init_from_julia();
}
//@}
/**
* @name Copy semantic
*/
//@{
/**
* The copy constructor.
*/
template <class T, std::size_t N>
inline jltensor<T, N>::jltensor(const self_type& rhs)
: base_type(), m_shape(rhs.shape())
{
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
std::copy(rhs.data().begin(), rhs.data().end(), this->data().begin());
}
/**
* The assignment operator.
*/
template <class T, std::size_t N>
inline auto jltensor<T, N>::operator=(const self_type& rhs) -> self_type&
{
self_type tmp(rhs);
*this = std::move(tmp);
return *this;
}
//@}
/**
* @name Extended copy semantic
*/
//@{
/**
* The extended copy constructor.
*/
template <class T, std::size_t N>
template <class E>
inline jltensor<T, N>::jltensor(const xexpression<E>& e)
: base_type()
{
m_shape = forward_sequence<shape_type>(e.derived_cast().shape());
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
init_tensor(m_shape);
semantic_base::assign(e);
}
/**
* The extended assignment operator.
*/
template <class T, std::size_t N>
template <class E>
inline auto jltensor<T, N>::operator=(const xexpression<E>& e) -> self_type&
{
return semantic_base::operator=(e);
}
//@}
template <class T, std::size_t N>
inline void jltensor<T, N>::init_tensor(const shape_type& shape)
{
static jl_value_t* array_type = make_julia_array_type();
static jl_datatype_t* tuple_type = make_julia_shape_type();
// allocate array
jl_value_t* dims = jl_new_bits((jl_value_t*)tuple_type, const_cast<void*>(reinterpret_cast<const void*>(shape.data())));
this->p_array = jl_new_array((jl_value_t*)array_type, dims);
// setup buffer adaptor
m_data = container_type(reinterpret_cast<pointer>(this->p_array->data),
static_cast<size_type>(jl_array_len(this->p_array)));
}
template <class T, std::size_t N>
inline void jltensor<T, N>::init_from_julia()
{
if (this->p_array->flags.ndims != N)
{
throw std::runtime_error("Julia array has incorrect number of dimensions");
}
std::copy(&(this->p_array->nrows), &(this->p_array->nrows) + N, m_shape.begin());
compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides);
m_data = container_type(reinterpret_cast<pointer>(this->p_array->data),
static_cast<size_type>(jl_array_len(this->p_array)));
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::shape_impl() noexcept -> inner_shape_type&
{
return m_shape;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::shape_impl() const noexcept -> const inner_shape_type&
{
return m_shape;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::strides_impl() noexcept -> inner_strides_type&
{
return m_strides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::strides_impl() const noexcept -> const inner_strides_type&
{
return m_strides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::backstrides_impl() noexcept -> inner_backstrides_type&
{
return m_backstrides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::backstrides_impl() const noexcept -> const inner_backstrides_type&
{
return m_backstrides;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::data_impl() noexcept -> container_type&
{
return m_data;
}
template <class T, std::size_t N>
inline auto jltensor<T, N>::data_impl() const noexcept -> const container_type&
{
return m_data;
}
template <class T, std::size_t N>
inline jl_datatype_t* jltensor<T, N>::make_julia_shape_type()
{
jl_svec_t* jtypes = jl_alloc_svec(N);
for (std::size_t i = 0; i < N; ++i)
{
jl_svecset(jtypes, i, cxx_wrap::julia_type<typename shape_type::value_type>());
}
return jl_apply_tuple_type(jtypes);
}
template <class T, std::size_t N>
inline jl_value_t* jltensor<T, N>::make_julia_array_type()
{
return cxx_wrap::apply_array_type(cxx_wrap::static_type_mapping<value_type>::julia_type(), N);
}
}
namespace cxx_wrap
{
/****************************************************************
* Template specializations for ConvertToJulia and ConvertToCpp *
****************************************************************/
template <class T, std::size_t N>
struct ConvertToJulia<xt::jltensor<T, N>, false, false, false>
{
template <class U>
jl_array_t* operator()(U&& arr) const
{
return arr.wrapped();
}
};
template <class T, std::size_t N>
struct ConvertToCpp<xt::jltensor<T, N>, false, false, false>
{
xt::jltensor<T, N> operator()(jl_array_t* arr) const
{
return xt::jltensor<T, N>(arr);
}
};
// Conversions
template<class T, std::size_t N>
struct static_type_mapping<xt::jltensor<T, N>>
{
using type = jl_array_t*;
static constexpr bool is_dynamic = false;
static jl_datatype_t* julia_type()
{
return (jl_datatype_t*)apply_array_type(static_type_mapping<T>::julia_type(), N);
}
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tkthrobber.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2008-04-04 10:55:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_toolkit.hxx"
#ifndef TOOLKIT_CONTROLS_TKTHROBBER_HXX
#include "toolkit/controls/tkthrobber.hxx"
#endif
#ifndef _TOOLKIT_HELPER_PROPERTY_HXX_
#include "toolkit/helper/property.hxx"
#endif
#ifndef _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#include "toolkit/helper/unopropertyarrayhelper.hxx"
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//........................................................................
namespace toolkit
{
//........................................................................
using namespace ::com::sun::star;
//====================================================================
//= UnoThrobberControlModel
//====================================================================
//--------------------------------------------------------------------
UnoThrobberControlModel::UnoThrobberControlModel()
{
ImplRegisterProperty( BASEPROPERTY_DEFAULTCONTROL );
ImplRegisterProperty( BASEPROPERTY_BACKGROUNDCOLOR );
}
//--------------------------------------------------------------------
::rtl::OUString UnoThrobberControlModel::getServiceName( ) throw ( uno::RuntimeException )
{
return ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel );
}
//--------------------------------------------------------------------
uno::Any UnoThrobberControlModel::ImplGetDefaultValue( sal_uInt16 nPropId ) const
{
switch ( nPropId )
{
case BASEPROPERTY_DEFAULTCONTROL:
return uno::makeAny( ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl ) );
default:
return UnoControlModel::ImplGetDefaultValue( nPropId );
}
}
//--------------------------------------------------------------------
::cppu::IPropertyArrayHelper& UnoThrobberControlModel::getInfoHelper()
{
static UnoPropertyArrayHelper* pHelper = NULL;
if ( !pHelper )
{
uno::Sequence< sal_Int32 > aIDs = ImplGetPropertyIds();
pHelper = new UnoPropertyArrayHelper( aIDs );
}
return *pHelper;
}
//--------------------------------------------------------------------
uno::Reference< beans::XPropertySetInfo > UnoThrobberControlModel::getPropertySetInfo()
throw( uno::RuntimeException )
{
static uno::Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//--------------------------------------------------------------------
::rtl::OUString SAL_CALL UnoThrobberControlModel::getImplementationName()
throw( uno::RuntimeException )
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControlModel" ) );
}
//--------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControlModel::getSupportedServiceNames()
throw( uno::RuntimeException )
{
uno::Sequence< ::rtl::OUString > aServices( UnoControlModel::getSupportedServiceNames() );
aServices.realloc( aServices.getLength() + 1 );
aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel );
return aServices;
}
//====================================================================
//= UnoThrobberControl
//====================================================================
//--------------------------------------------------------------------
UnoThrobberControl::UnoThrobberControl()
{
}
//--------------------------------------------------------------------
::rtl::OUString UnoThrobberControl::GetComponentServiceName()
{
return ::rtl::OUString::createFromAscii( "Throbber" );
}
//--------------------------------------------------------------------
uno::Any UnoThrobberControl::queryAggregation( const uno::Type & rType ) throw( uno::RuntimeException )
{
uno::Any aRet = UnoControlBase::queryAggregation( rType );
if ( !aRet.hasValue() )
aRet = UnoThrobberControl_Base::queryInterface( rType );
return aRet;
}
//--------------------------------------------------------------------
IMPLEMENT_FORWARD_XTYPEPROVIDER2( UnoThrobberControl, UnoControlBase, UnoThrobberControl_Base )
//--------------------------------------------------------------------
void UnoThrobberControl::dispose() throw( uno::RuntimeException )
{
::osl::ClearableMutexGuard aGuard( GetMutex() );
UnoControl::dispose();
}
//--------------------------------------------------------------------
::rtl::OUString SAL_CALL UnoThrobberControl::getImplementationName()
throw( uno::RuntimeException )
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControl" ) );
}
//--------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControl::getSupportedServiceNames()
throw( uno::RuntimeException )
{
uno::Sequence< ::rtl::OUString > aServices( UnoControlBase::getSupportedServiceNames() );
aServices.realloc( aServices.getLength() + 1 );
aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl );
return aServices;
}
//--------------------------------------------------------------------
void UnoThrobberControl::createPeer( const uno::Reference< awt::XToolkit > & rxToolkit,
const uno::Reference< awt::XWindowPeer > & rParentPeer )
throw( uno::RuntimeException )
{
UnoControl::createPeer( rxToolkit, rParentPeer );
}
//--------------------------------------------------------------------
void SAL_CALL UnoThrobberControl::start() throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( GetMutex() );
uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY );
if ( xAnimation.is() )
xAnimation->start();
}
//--------------------------------------------------------------------
void SAL_CALL UnoThrobberControl::stop() throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( GetMutex() );
uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY );
if ( xAnimation.is() )
xAnimation->stop();
}
//........................................................................
} // namespace toolkit
//........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.3.148); FILE MERGED 2008/04/01 16:00:59 thb 1.3.148.3: #i85898# Stripping all external header guards 2008/04/01 12:56:52 thb 1.3.148.2: #i85898# Stripping all external header guards 2008/03/28 15:40:17 rt 1.3.148.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tkthrobber.cxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_toolkit.hxx"
#include "toolkit/controls/tkthrobber.hxx"
#include "toolkit/helper/property.hxx"
#include "toolkit/helper/unopropertyarrayhelper.hxx"
#include <cppuhelper/typeprovider.hxx>
#include <tools/debug.hxx>
//........................................................................
namespace toolkit
{
//........................................................................
using namespace ::com::sun::star;
//====================================================================
//= UnoThrobberControlModel
//====================================================================
//--------------------------------------------------------------------
UnoThrobberControlModel::UnoThrobberControlModel()
{
ImplRegisterProperty( BASEPROPERTY_DEFAULTCONTROL );
ImplRegisterProperty( BASEPROPERTY_BACKGROUNDCOLOR );
}
//--------------------------------------------------------------------
::rtl::OUString UnoThrobberControlModel::getServiceName( ) throw ( uno::RuntimeException )
{
return ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel );
}
//--------------------------------------------------------------------
uno::Any UnoThrobberControlModel::ImplGetDefaultValue( sal_uInt16 nPropId ) const
{
switch ( nPropId )
{
case BASEPROPERTY_DEFAULTCONTROL:
return uno::makeAny( ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl ) );
default:
return UnoControlModel::ImplGetDefaultValue( nPropId );
}
}
//--------------------------------------------------------------------
::cppu::IPropertyArrayHelper& UnoThrobberControlModel::getInfoHelper()
{
static UnoPropertyArrayHelper* pHelper = NULL;
if ( !pHelper )
{
uno::Sequence< sal_Int32 > aIDs = ImplGetPropertyIds();
pHelper = new UnoPropertyArrayHelper( aIDs );
}
return *pHelper;
}
//--------------------------------------------------------------------
uno::Reference< beans::XPropertySetInfo > UnoThrobberControlModel::getPropertySetInfo()
throw( uno::RuntimeException )
{
static uno::Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
//--------------------------------------------------------------------
::rtl::OUString SAL_CALL UnoThrobberControlModel::getImplementationName()
throw( uno::RuntimeException )
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControlModel" ) );
}
//--------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControlModel::getSupportedServiceNames()
throw( uno::RuntimeException )
{
uno::Sequence< ::rtl::OUString > aServices( UnoControlModel::getSupportedServiceNames() );
aServices.realloc( aServices.getLength() + 1 );
aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel );
return aServices;
}
//====================================================================
//= UnoThrobberControl
//====================================================================
//--------------------------------------------------------------------
UnoThrobberControl::UnoThrobberControl()
{
}
//--------------------------------------------------------------------
::rtl::OUString UnoThrobberControl::GetComponentServiceName()
{
return ::rtl::OUString::createFromAscii( "Throbber" );
}
//--------------------------------------------------------------------
uno::Any UnoThrobberControl::queryAggregation( const uno::Type & rType ) throw( uno::RuntimeException )
{
uno::Any aRet = UnoControlBase::queryAggregation( rType );
if ( !aRet.hasValue() )
aRet = UnoThrobberControl_Base::queryInterface( rType );
return aRet;
}
//--------------------------------------------------------------------
IMPLEMENT_FORWARD_XTYPEPROVIDER2( UnoThrobberControl, UnoControlBase, UnoThrobberControl_Base )
//--------------------------------------------------------------------
void UnoThrobberControl::dispose() throw( uno::RuntimeException )
{
::osl::ClearableMutexGuard aGuard( GetMutex() );
UnoControl::dispose();
}
//--------------------------------------------------------------------
::rtl::OUString SAL_CALL UnoThrobberControl::getImplementationName()
throw( uno::RuntimeException )
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControl" ) );
}
//--------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControl::getSupportedServiceNames()
throw( uno::RuntimeException )
{
uno::Sequence< ::rtl::OUString > aServices( UnoControlBase::getSupportedServiceNames() );
aServices.realloc( aServices.getLength() + 1 );
aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl );
return aServices;
}
//--------------------------------------------------------------------
void UnoThrobberControl::createPeer( const uno::Reference< awt::XToolkit > & rxToolkit,
const uno::Reference< awt::XWindowPeer > & rParentPeer )
throw( uno::RuntimeException )
{
UnoControl::createPeer( rxToolkit, rParentPeer );
}
//--------------------------------------------------------------------
void SAL_CALL UnoThrobberControl::start() throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( GetMutex() );
uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY );
if ( xAnimation.is() )
xAnimation->start();
}
//--------------------------------------------------------------------
void SAL_CALL UnoThrobberControl::stop() throw ( uno::RuntimeException )
{
::osl::MutexGuard aGuard( GetMutex() );
uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY );
if ( xAnimation.is() )
xAnimation->stop();
}
//........................................................................
} // namespace toolkit
//........................................................................
<|endoftext|> |
<commit_before>//===-- Clustering.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Clustering.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include <string>
namespace llvm {
namespace exegesis {
// The clustering problem has the following characteristics:
// (A) - Low dimension (dimensions are typically proc resource units,
// typically < 10).
// (B) - Number of points : ~thousands (points are measurements of an MCInst)
// (C) - Number of clusters: ~tens.
// (D) - The number of clusters is not known /a priory/.
// (E) - The amount of noise is relatively small.
// The problem is rather small. In terms of algorithms, (D) disqualifies
// k-means and makes algorithms such as DBSCAN[1] or OPTICS[2] more applicable.
//
// We've used DBSCAN here because it's simple to implement. This is a pretty
// straightforward and inefficient implementation of the pseudocode in [2].
//
// [1] https://en.wikipedia.org/wiki/DBSCAN
// [2] https://en.wikipedia.org/wiki/OPTICS_algorithm
// Finds the points at distance less than sqrt(EpsilonSquared) of Q (not
// including Q).
void InstructionBenchmarkClustering::rangeQuery(
const size_t Q, std::vector<size_t> &Neighbors) const {
Neighbors.clear();
Neighbors.reserve(Points_.size() - 1); // The Q itself isn't a neighbor.
const auto &QMeasurements = Points_[Q].Measurements;
for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
if (P == Q)
continue;
const auto &PMeasurements = Points_[P].Measurements;
if (PMeasurements.empty()) // Error point.
continue;
if (isNeighbour(PMeasurements, QMeasurements)) {
Neighbors.push_back(P);
}
}
}
InstructionBenchmarkClustering::InstructionBenchmarkClustering(
const std::vector<InstructionBenchmark> &Points,
const double EpsilonSquared)
: Points_(Points), EpsilonSquared_(EpsilonSquared),
NoiseCluster_(ClusterId::noise()), ErrorCluster_(ClusterId::error()) {}
llvm::Error InstructionBenchmarkClustering::validateAndSetup() {
ClusterIdForPoint_.resize(Points_.size());
// Mark erroneous measurements out.
// All points must have the same number of dimensions, in the same order.
const std::vector<BenchmarkMeasure> *LastMeasurement = nullptr;
for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
const auto &Point = Points_[P];
if (!Point.Error.empty()) {
ClusterIdForPoint_[P] = ClusterId::error();
ErrorCluster_.PointIndices.push_back(P);
continue;
}
const auto *CurMeasurement = &Point.Measurements;
if (LastMeasurement) {
if (LastMeasurement->size() != CurMeasurement->size()) {
return llvm::make_error<llvm::StringError>(
"inconsistent measurement dimensions",
llvm::inconvertibleErrorCode());
}
for (size_t I = 0, E = LastMeasurement->size(); I < E; ++I) {
if (LastMeasurement->at(I).Key != CurMeasurement->at(I).Key) {
return llvm::make_error<llvm::StringError>(
"inconsistent measurement dimensions keys",
llvm::inconvertibleErrorCode());
}
}
}
LastMeasurement = CurMeasurement;
}
if (LastMeasurement) {
NumDimensions_ = LastMeasurement->size();
}
return llvm::Error::success();
}
void InstructionBenchmarkClustering::dbScan(const size_t MinPts) {
std::vector<size_t> Neighbors; // Persistent buffer to avoid allocs.
for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
if (!ClusterIdForPoint_[P].isUndef())
continue; // Previously processed in inner loop.
rangeQuery(P, Neighbors);
if (Neighbors.size() + 1 < MinPts) { // Density check.
// The region around P is not dense enough to create a new cluster, mark
// as noise for now.
ClusterIdForPoint_[P] = ClusterId::noise();
continue;
}
// Create a new cluster, add P.
Clusters_.emplace_back(ClusterId::makeValid(Clusters_.size()));
Cluster &CurrentCluster = Clusters_.back();
ClusterIdForPoint_[P] = CurrentCluster.Id; /* Label initial point */
CurrentCluster.PointIndices.push_back(P);
// Process P's neighbors.
llvm::SetVector<size_t, std::deque<size_t>> ToProcess;
ToProcess.insert(Neighbors.begin(), Neighbors.end());
while (!ToProcess.empty()) {
// Retrieve a point from the set.
const size_t Q = *ToProcess.begin();
ToProcess.erase(ToProcess.begin());
if (ClusterIdForPoint_[Q].isNoise()) {
// Change noise point to border point.
ClusterIdForPoint_[Q] = CurrentCluster.Id;
CurrentCluster.PointIndices.push_back(Q);
continue;
}
if (!ClusterIdForPoint_[Q].isUndef()) {
continue; // Previously processed.
}
// Add Q to the current custer.
ClusterIdForPoint_[Q] = CurrentCluster.Id;
CurrentCluster.PointIndices.push_back(Q);
// And extend to the neighbors of Q if the region is dense enough.
rangeQuery(Q, Neighbors);
if (Neighbors.size() + 1 >= MinPts) {
ToProcess.insert(Neighbors.begin(), Neighbors.end());
}
}
}
// assert(Neighbors.capacity() == (Points_.size() - 1));
// ^ True, but it is not quaranteed to be true in all the cases.
// Add noisy points to noise cluster.
for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
if (ClusterIdForPoint_[P].isNoise()) {
NoiseCluster_.PointIndices.push_back(P);
}
}
}
llvm::Expected<InstructionBenchmarkClustering>
InstructionBenchmarkClustering::create(
const std::vector<InstructionBenchmark> &Points, const size_t MinPts,
const double Epsilon) {
InstructionBenchmarkClustering Clustering(Points, Epsilon * Epsilon);
if (auto Error = Clustering.validateAndSetup()) {
return std::move(Error);
}
if (Clustering.ErrorCluster_.PointIndices.size() == Points.size()) {
return Clustering; // Nothing to cluster.
}
Clustering.dbScan(MinPts);
return Clustering;
}
} // namespace exegesis
} // namespace llvm
<commit_msg>[llvm-exegesis] Optimize ToProcess in dbScan<commit_after>//===-- Clustering.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Clustering.h"
#include "llvm/ADT/SmallVector.h"
#include <string>
namespace llvm {
namespace exegesis {
// The clustering problem has the following characteristics:
// (A) - Low dimension (dimensions are typically proc resource units,
// typically < 10).
// (B) - Number of points : ~thousands (points are measurements of an MCInst)
// (C) - Number of clusters: ~tens.
// (D) - The number of clusters is not known /a priory/.
// (E) - The amount of noise is relatively small.
// The problem is rather small. In terms of algorithms, (D) disqualifies
// k-means and makes algorithms such as DBSCAN[1] or OPTICS[2] more applicable.
//
// We've used DBSCAN here because it's simple to implement. This is a pretty
// straightforward and inefficient implementation of the pseudocode in [2].
//
// [1] https://en.wikipedia.org/wiki/DBSCAN
// [2] https://en.wikipedia.org/wiki/OPTICS_algorithm
// Finds the points at distance less than sqrt(EpsilonSquared) of Q (not
// including Q).
void InstructionBenchmarkClustering::rangeQuery(
const size_t Q, std::vector<size_t> &Neighbors) const {
Neighbors.clear();
Neighbors.reserve(Points_.size() - 1); // The Q itself isn't a neighbor.
const auto &QMeasurements = Points_[Q].Measurements;
for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
if (P == Q)
continue;
const auto &PMeasurements = Points_[P].Measurements;
if (PMeasurements.empty()) // Error point.
continue;
if (isNeighbour(PMeasurements, QMeasurements)) {
Neighbors.push_back(P);
}
}
}
InstructionBenchmarkClustering::InstructionBenchmarkClustering(
const std::vector<InstructionBenchmark> &Points,
const double EpsilonSquared)
: Points_(Points), EpsilonSquared_(EpsilonSquared),
NoiseCluster_(ClusterId::noise()), ErrorCluster_(ClusterId::error()) {}
llvm::Error InstructionBenchmarkClustering::validateAndSetup() {
ClusterIdForPoint_.resize(Points_.size());
// Mark erroneous measurements out.
// All points must have the same number of dimensions, in the same order.
const std::vector<BenchmarkMeasure> *LastMeasurement = nullptr;
for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
const auto &Point = Points_[P];
if (!Point.Error.empty()) {
ClusterIdForPoint_[P] = ClusterId::error();
ErrorCluster_.PointIndices.push_back(P);
continue;
}
const auto *CurMeasurement = &Point.Measurements;
if (LastMeasurement) {
if (LastMeasurement->size() != CurMeasurement->size()) {
return llvm::make_error<llvm::StringError>(
"inconsistent measurement dimensions",
llvm::inconvertibleErrorCode());
}
for (size_t I = 0, E = LastMeasurement->size(); I < E; ++I) {
if (LastMeasurement->at(I).Key != CurMeasurement->at(I).Key) {
return llvm::make_error<llvm::StringError>(
"inconsistent measurement dimensions keys",
llvm::inconvertibleErrorCode());
}
}
}
LastMeasurement = CurMeasurement;
}
if (LastMeasurement) {
NumDimensions_ = LastMeasurement->size();
}
return llvm::Error::success();
}
void InstructionBenchmarkClustering::dbScan(const size_t MinPts) {
const size_t NumPoints = Points_.size();
// Persistent buffers to avoid allocs.
std::vector<size_t> Neighbors;
std::vector<size_t> ToProcess(NumPoints);
std::vector<char> Added(NumPoints);
for (size_t P = 0; P < NumPoints; ++P) {
if (!ClusterIdForPoint_[P].isUndef())
continue; // Previously processed in inner loop.
rangeQuery(P, Neighbors);
if (Neighbors.size() + 1 < MinPts) { // Density check.
// The region around P is not dense enough to create a new cluster, mark
// as noise for now.
ClusterIdForPoint_[P] = ClusterId::noise();
continue;
}
// Create a new cluster, add P.
Clusters_.emplace_back(ClusterId::makeValid(Clusters_.size()));
Cluster &CurrentCluster = Clusters_.back();
ClusterIdForPoint_[P] = CurrentCluster.Id; /* Label initial point */
CurrentCluster.PointIndices.push_back(P);
Added[P] = 1;
// Process P's neighbors.
size_t Tail = 0;
for (size_t Q : Neighbors)
if (!Added[Q]) {
ToProcess[Tail++] = P;
Added[Q] = 1;
}
for (size_t Head = 0; Head < Tail; ++Head) {
// Retrieve a point from the set.
size_t Q = ToProcess[Head];
if (ClusterIdForPoint_[Q].isNoise()) {
// Change noise point to border point.
ClusterIdForPoint_[Q] = CurrentCluster.Id;
CurrentCluster.PointIndices.push_back(Q);
continue;
}
assert(ClusterIdForPoint_[Q].isUndef());
// Add Q to the current custer.
ClusterIdForPoint_[Q] = CurrentCluster.Id;
CurrentCluster.PointIndices.push_back(Q);
// And extend to the neighbors of Q if the region is dense enough.
rangeQuery(Q, Neighbors);
if (Neighbors.size() + 1 >= MinPts)
for (size_t P : Neighbors)
if (!Added[P]) {
ToProcess[Tail++] = P;
Added[P] = 1;
}
}
}
// assert(Neighbors.capacity() == (Points_.size() - 1));
// ^ True, but it is not quaranteed to be true in all the cases.
// Add noisy points to noise cluster.
for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) {
if (ClusterIdForPoint_[P].isNoise()) {
NoiseCluster_.PointIndices.push_back(P);
}
}
}
llvm::Expected<InstructionBenchmarkClustering>
InstructionBenchmarkClustering::create(
const std::vector<InstructionBenchmark> &Points, const size_t MinPts,
const double Epsilon) {
InstructionBenchmarkClustering Clustering(Points, Epsilon * Epsilon);
if (auto Error = Clustering.validateAndSetup()) {
return std::move(Error);
}
if (Clustering.ErrorCluster_.PointIndices.size() == Points.size()) {
return Clustering; // Nothing to cluster.
}
Clustering.dbScan(MinPts);
return Clustering;
}
} // namespace exegesis
} // namespace llvm
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2011-2012 Jose Fonseca
* All Rights Reserved.
*
* 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.
*
**************************************************************************/
/**
* Window system helpers for glretrace.
*/
#include <string.h>
#include <algorithm>
#include <map>
#include "os_thread.hpp"
#include "retrace.hpp"
#include "glproc.hpp"
#include "glstate.hpp"
#include "glretrace.hpp"
namespace glretrace {
static std::map<glfeatures::Profile, glws::Visual *>
visuals;
inline glws::Visual *
getVisual(glfeatures::Profile profile) {
std::map<glfeatures::Profile, glws::Visual *>::iterator it = visuals.find(profile);
if (it == visuals.end()) {
glws::Visual *visual = NULL;
unsigned samples = retrace::samples;
/* The requested number of samples might not be available, try fewer until we succeed */
while (!visual && samples > 0) {
visual = glws::createVisual(retrace::doubleBuffer, samples, profile);
if (!visual) {
samples--;
}
}
if (!visual) {
std::cerr << "error: failed to create OpenGL visual\n";
exit(1);
}
if (samples != retrace::samples) {
std::cerr << "warning: Using " << samples << " samples instead of the requested " << retrace::samples << "\n";
}
visuals[profile] = visual;
return visual;
}
return it->second;
}
static glws::Drawable *
createDrawableHelper(glfeatures::Profile profile, int width = 32, int height = 32,
const glws::pbuffer_info *pbInfo = NULL) {
glws::Visual *visual = getVisual(profile);
glws::Drawable *draw = glws::createDrawable(visual, width, height, pbInfo);
if (!draw) {
std::cerr << "error: failed to create OpenGL drawable\n";
exit(1);
}
if (pbInfo)
draw->pbInfo = *pbInfo;
return draw;
}
glws::Drawable *
createDrawable(glfeatures::Profile profile) {
return createDrawableHelper(profile);
}
glws::Drawable *
createDrawable(void) {
return createDrawable(defaultProfile);
}
glws::Drawable *
createPbuffer(int width, int height, const glws::pbuffer_info *pbInfo) {
// Zero area pbuffers are often accepted, but given we create window
// drawables instead, they should have non-zero area.
width = std::max(width, 1);
height = std::max(height, 1);
return createDrawableHelper(defaultProfile, width, height, pbInfo);
}
Context *
createContext(Context *shareContext, glfeatures::Profile profile) {
glws::Visual *visual = getVisual(profile);
glws::Context *shareWsContext = shareContext ? shareContext->wsContext : NULL;
glws::Context *ctx = glws::createContext(visual, shareWsContext, retrace::debug);
if (!ctx) {
std::cerr << "error: failed to create " << profile << " context.\n";
exit(1);
}
return new Context(ctx);
}
Context *
createContext(Context *shareContext) {
return createContext(shareContext, defaultProfile);
}
Context::~Context()
{
//assert(this != getCurrentContext());
if (this != getCurrentContext()) {
delete wsContext;
}
}
OS_THREAD_LOCAL Context *
currentContextPtr;
bool
makeCurrent(trace::Call &call, glws::Drawable *drawable, Context *context)
{
return makeCurrent(call, drawable, drawable, context);
}
bool
makeCurrent(trace::Call &call, glws::Drawable *drawable,
glws::Drawable *readable, Context *context)
{
Context *currentContext = currentContextPtr;
glws::Drawable *currentDrawable = currentContext ? currentContext->drawable : NULL;
glws::Drawable *currentReadable = currentContext ? currentContext->readable : NULL;
if (drawable == currentDrawable &&
readable == currentReadable &&
context == currentContext) {
return true;
}
if (currentContext) {
glFlush();
currentContext->needsFlush = false;
if (!retrace::doubleBuffer) {
frame_complete(call);
}
}
flushQueries();
beforeContextSwitch();
bool success = glws::makeCurrent(drawable, readable, context ? context->wsContext : NULL);
if (!success) {
std::cerr << "error: failed to make current OpenGL context and drawable\n";
exit(1);
}
if (context != currentContext) {
if (context) {
context->aquire();
}
currentContextPtr = context;
if (currentContext) {
currentContext->release();
}
}
if (drawable && context) {
context->drawable = drawable;
context->readable = readable;
if (!context->used) {
initContext();
context->used = true;
}
}
afterContextSwitch();
return true;
}
/**
* Grow the current drawble.
*
* We need to infer the drawable size from GL calls because the drawable sizes
* are specified by OS specific calls which we do not trace.
*/
void
updateDrawable(int width, int height) {
Context *currentContext = getCurrentContext();
if (!currentContext) {
return;
}
glws::Drawable *currentDrawable = currentContext->drawable;
if (!currentDrawable) {
return;
}
if (currentDrawable->pbuffer) {
return;
}
if (currentDrawable->visible &&
width <= currentDrawable->width &&
height <= currentDrawable->height) {
return;
}
// Ignore zero area viewports
if (width == 0 || height == 0) {
return;
}
width = std::max(width, currentDrawable->width);
height = std::max(height, currentDrawable->height);
// Check for bound framebuffer last, as this may have a performance impact.
if (currentContext->features().framebuffer_object) {
GLint framebuffer = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer);
if (framebuffer != 0) {
return;
}
}
currentDrawable->resize(width, height);
currentDrawable->show();
// Ensure the drawable dimensions, as perceived by glstate match.
if (retrace::debug) {
GLint newWidth = 0;
GLint newHeight = 0;
if (glstate::getDrawableBounds(&newWidth, &newHeight) &&
(newWidth != width || newHeight != height)) {
std::cerr
<< "error: drawable failed to resize: "
<< "expected " << width << "x" << height << ", "
<< "got " << newWidth << "x" << newHeight << "\n";
}
}
glScissor(0, 0, width, height);
}
int
parseAttrib(const trace::Value *attribs, int param, int default_, int terminator) {
const trace::Array *attribs_ = attribs ? attribs->toArray() : NULL;
if (attribs_) {
for (size_t i = 0; i + 1 < attribs_->values.size(); i += 2) {
int param_i = attribs_->values[i]->toSInt();
if (param_i == terminator) {
break;
}
if (param_i == param) {
int value = attribs_->values[i + 1]->toSInt();
return value;
}
}
}
return default_;
}
/**
* Parse GLX/WGL_ARB_create_context attribute list.
*/
glfeatures::Profile
parseContextAttribList(const trace::Value *attribs)
{
// {GLX,WGL}_CONTEXT_MAJOR_VERSION_ARB
int major_version = parseAttrib(attribs, 0x2091, 1);
// {GLX,WGL}_CONTEXT_MINOR_VERSION_ARB
int minor_version = parseAttrib(attribs, 0x2092, 0);
int profile_mask = parseAttrib(attribs, GL_CONTEXT_PROFILE_MASK, GL_CONTEXT_CORE_PROFILE_BIT);
bool core_profile = profile_mask & GL_CONTEXT_CORE_PROFILE_BIT;
if (major_version < 3 ||
(major_version == 3 && minor_version < 2)) {
core_profile = false;
}
int context_flags = parseAttrib(attribs, GL_CONTEXT_FLAGS, 0);
bool forward_compatible = context_flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT;
if (major_version < 3) {
forward_compatible = false;
}
// {GLX,WGL}_CONTEXT_ES_PROFILE_BIT_EXT
bool es_profile = profile_mask & 0x0004;
glfeatures::Profile profile;
if (es_profile) {
profile.api = glfeatures::API_GLES;
} else {
profile.api = glfeatures::API_GL;
profile.core = core_profile;
profile.forwardCompatible = forward_compatible;
}
profile.major = major_version;
profile.minor = minor_version;
return profile;
}
// WGL_ARB_render_texture / wglBindTexImageARB()
bool
bindTexImage(glws::Drawable *pBuffer, int iBuffer) {
return glws::bindTexImage(pBuffer, iBuffer);
}
// WGL_ARB_render_texture / wglReleaseTexImageARB()
bool
releaseTexImage(glws::Drawable *pBuffer, int iBuffer) {
return glws::releaseTexImage(pBuffer, iBuffer);
}
// WGL_ARB_render_texture / wglSetPbufferAttribARB()
bool
setPbufferAttrib(glws::Drawable *pBuffer, const int *attribs) {
return glws::setPbufferAttrib(pBuffer, attribs);
}
} /* namespace glretrace */
<commit_msg>glretrace: fix a comment typo<commit_after>/**************************************************************************
*
* Copyright 2011-2012 Jose Fonseca
* All Rights Reserved.
*
* 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.
*
**************************************************************************/
/**
* Window system helpers for glretrace.
*/
#include <string.h>
#include <algorithm>
#include <map>
#include "os_thread.hpp"
#include "retrace.hpp"
#include "glproc.hpp"
#include "glstate.hpp"
#include "glretrace.hpp"
namespace glretrace {
static std::map<glfeatures::Profile, glws::Visual *>
visuals;
inline glws::Visual *
getVisual(glfeatures::Profile profile) {
std::map<glfeatures::Profile, glws::Visual *>::iterator it = visuals.find(profile);
if (it == visuals.end()) {
glws::Visual *visual = NULL;
unsigned samples = retrace::samples;
/* The requested number of samples might not be available, try fewer until we succeed */
while (!visual && samples > 0) {
visual = glws::createVisual(retrace::doubleBuffer, samples, profile);
if (!visual) {
samples--;
}
}
if (!visual) {
std::cerr << "error: failed to create OpenGL visual\n";
exit(1);
}
if (samples != retrace::samples) {
std::cerr << "warning: Using " << samples << " samples instead of the requested " << retrace::samples << "\n";
}
visuals[profile] = visual;
return visual;
}
return it->second;
}
static glws::Drawable *
createDrawableHelper(glfeatures::Profile profile, int width = 32, int height = 32,
const glws::pbuffer_info *pbInfo = NULL) {
glws::Visual *visual = getVisual(profile);
glws::Drawable *draw = glws::createDrawable(visual, width, height, pbInfo);
if (!draw) {
std::cerr << "error: failed to create OpenGL drawable\n";
exit(1);
}
if (pbInfo)
draw->pbInfo = *pbInfo;
return draw;
}
glws::Drawable *
createDrawable(glfeatures::Profile profile) {
return createDrawableHelper(profile);
}
glws::Drawable *
createDrawable(void) {
return createDrawable(defaultProfile);
}
glws::Drawable *
createPbuffer(int width, int height, const glws::pbuffer_info *pbInfo) {
// Zero area pbuffers are often accepted, but given we create window
// drawables instead, they should have non-zero area.
width = std::max(width, 1);
height = std::max(height, 1);
return createDrawableHelper(defaultProfile, width, height, pbInfo);
}
Context *
createContext(Context *shareContext, glfeatures::Profile profile) {
glws::Visual *visual = getVisual(profile);
glws::Context *shareWsContext = shareContext ? shareContext->wsContext : NULL;
glws::Context *ctx = glws::createContext(visual, shareWsContext, retrace::debug);
if (!ctx) {
std::cerr << "error: failed to create " << profile << " context.\n";
exit(1);
}
return new Context(ctx);
}
Context *
createContext(Context *shareContext) {
return createContext(shareContext, defaultProfile);
}
Context::~Context()
{
//assert(this != getCurrentContext());
if (this != getCurrentContext()) {
delete wsContext;
}
}
OS_THREAD_LOCAL Context *
currentContextPtr;
bool
makeCurrent(trace::Call &call, glws::Drawable *drawable, Context *context)
{
return makeCurrent(call, drawable, drawable, context);
}
bool
makeCurrent(trace::Call &call, glws::Drawable *drawable,
glws::Drawable *readable, Context *context)
{
Context *currentContext = currentContextPtr;
glws::Drawable *currentDrawable = currentContext ? currentContext->drawable : NULL;
glws::Drawable *currentReadable = currentContext ? currentContext->readable : NULL;
if (drawable == currentDrawable &&
readable == currentReadable &&
context == currentContext) {
return true;
}
if (currentContext) {
glFlush();
currentContext->needsFlush = false;
if (!retrace::doubleBuffer) {
frame_complete(call);
}
}
flushQueries();
beforeContextSwitch();
bool success = glws::makeCurrent(drawable, readable, context ? context->wsContext : NULL);
if (!success) {
std::cerr << "error: failed to make current OpenGL context and drawable\n";
exit(1);
}
if (context != currentContext) {
if (context) {
context->aquire();
}
currentContextPtr = context;
if (currentContext) {
currentContext->release();
}
}
if (drawable && context) {
context->drawable = drawable;
context->readable = readable;
if (!context->used) {
initContext();
context->used = true;
}
}
afterContextSwitch();
return true;
}
/**
* Grow the current drawable.
*
* We need to infer the drawable size from GL calls because the drawable sizes
* are specified by OS specific calls which we do not trace.
*/
void
updateDrawable(int width, int height) {
Context *currentContext = getCurrentContext();
if (!currentContext) {
return;
}
glws::Drawable *currentDrawable = currentContext->drawable;
if (!currentDrawable) {
return;
}
if (currentDrawable->pbuffer) {
return;
}
if (currentDrawable->visible &&
width <= currentDrawable->width &&
height <= currentDrawable->height) {
return;
}
// Ignore zero area viewports
if (width == 0 || height == 0) {
return;
}
width = std::max(width, currentDrawable->width);
height = std::max(height, currentDrawable->height);
// Check for bound framebuffer last, as this may have a performance impact.
if (currentContext->features().framebuffer_object) {
GLint framebuffer = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer);
if (framebuffer != 0) {
return;
}
}
currentDrawable->resize(width, height);
currentDrawable->show();
// Ensure the drawable dimensions, as perceived by glstate match.
if (retrace::debug) {
GLint newWidth = 0;
GLint newHeight = 0;
if (glstate::getDrawableBounds(&newWidth, &newHeight) &&
(newWidth != width || newHeight != height)) {
std::cerr
<< "error: drawable failed to resize: "
<< "expected " << width << "x" << height << ", "
<< "got " << newWidth << "x" << newHeight << "\n";
}
}
glScissor(0, 0, width, height);
}
int
parseAttrib(const trace::Value *attribs, int param, int default_, int terminator) {
const trace::Array *attribs_ = attribs ? attribs->toArray() : NULL;
if (attribs_) {
for (size_t i = 0; i + 1 < attribs_->values.size(); i += 2) {
int param_i = attribs_->values[i]->toSInt();
if (param_i == terminator) {
break;
}
if (param_i == param) {
int value = attribs_->values[i + 1]->toSInt();
return value;
}
}
}
return default_;
}
/**
* Parse GLX/WGL_ARB_create_context attribute list.
*/
glfeatures::Profile
parseContextAttribList(const trace::Value *attribs)
{
// {GLX,WGL}_CONTEXT_MAJOR_VERSION_ARB
int major_version = parseAttrib(attribs, 0x2091, 1);
// {GLX,WGL}_CONTEXT_MINOR_VERSION_ARB
int minor_version = parseAttrib(attribs, 0x2092, 0);
int profile_mask = parseAttrib(attribs, GL_CONTEXT_PROFILE_MASK, GL_CONTEXT_CORE_PROFILE_BIT);
bool core_profile = profile_mask & GL_CONTEXT_CORE_PROFILE_BIT;
if (major_version < 3 ||
(major_version == 3 && minor_version < 2)) {
core_profile = false;
}
int context_flags = parseAttrib(attribs, GL_CONTEXT_FLAGS, 0);
bool forward_compatible = context_flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT;
if (major_version < 3) {
forward_compatible = false;
}
// {GLX,WGL}_CONTEXT_ES_PROFILE_BIT_EXT
bool es_profile = profile_mask & 0x0004;
glfeatures::Profile profile;
if (es_profile) {
profile.api = glfeatures::API_GLES;
} else {
profile.api = glfeatures::API_GL;
profile.core = core_profile;
profile.forwardCompatible = forward_compatible;
}
profile.major = major_version;
profile.minor = minor_version;
return profile;
}
// WGL_ARB_render_texture / wglBindTexImageARB()
bool
bindTexImage(glws::Drawable *pBuffer, int iBuffer) {
return glws::bindTexImage(pBuffer, iBuffer);
}
// WGL_ARB_render_texture / wglReleaseTexImageARB()
bool
releaseTexImage(glws::Drawable *pBuffer, int iBuffer) {
return glws::releaseTexImage(pBuffer, iBuffer);
}
// WGL_ARB_render_texture / wglSetPbufferAttribARB()
bool
setPbufferAttrib(glws::Drawable *pBuffer, const int *attribs) {
return glws::setPbufferAttrib(pBuffer, attribs);
}
} /* namespace glretrace */
<|endoftext|> |
<commit_before>/* -*- indent-tabs-mode: nil -*- */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <set>
#include <string>
#include "database.h"
#include "file_db.h"
#include "file_storage.h"
#include "sqlite_db.h"
#include "test_db.h"
#include "test_signer.h"
#include "util.h"
namespace {
using ct::DigitallySigned;
using ct::LogEntry;
using ct::LoggedCertificate;
using ct::PrecertChainEntry;
using ct::SignedTreeHead;
using ct::X509ChainEntry;
using std::string;
// A slightly shorter notation for constructing hex strings from binary blobs.
string H(const string &byte_string) {
return util::HexString(byte_string);
}
template <class T> class DBTest : public ::testing::Test {
protected:
DBTest() :
test_db_(),
test_signer_() { }
~DBTest() {}
T *db() const { return test_db_.db(); }
TestDB<T> test_db_;
TestSigner test_signer_;
};
typedef testing::Types<FileDB, SQLiteDB> Databases;
TYPED_TEST_CASE(DBTest, Databases);
TYPED_TEST(DBTest, CreatePending) {
LoggedCertificate logged_cert, lookup_cert;
this->test_signer_.CreateUnique(&logged_cert);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
string similar_hash = logged_cert.certificate_sha256_hash();
similar_hash[similar_hash.size() - 1] ^= 1;
EXPECT_EQ(Database::NOT_FOUND,
this->db()->LookupCertificateByHash(similar_hash,
&lookup_cert));
EXPECT_EQ(Database::NOT_FOUND,
this->db()->LookupCertificateByHash(this->test_signer_.UniqueHash(),
&lookup_cert));
}
TYPED_TEST(DBTest, GetPendingHashes) {
LoggedCertificate logged_cert, logged_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
std::set<string> hashes;
hashes.insert(logged_cert.certificate_sha256_hash());
hashes.insert(logged_cert2.certificate_sha256_hash());
std::set<string> pending_hashes = this->db()->PendingHashes();
EXPECT_EQ(hashes, pending_hashes);
}
TYPED_TEST(DBTest, CreatePendingDuplicate) {
LoggedCertificate logged_cert, duplicate_cert, lookup_cert;
this->test_signer_.CreateUnique(&logged_cert);
duplicate_cert.CopyFrom(logged_cert);
// Change the timestamp so that we can check that we get the right thing back.
duplicate_cert.mutable_sct()->set_timestamp(
logged_cert.sct().timestamp() + 1000);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::DUPLICATE_CERTIFICATE_HASH,
this->db()->CreatePendingCertificateEntry(duplicate_cert));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
// Check that we get the original entry back.
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
}
TYPED_TEST(DBTest, AssignSequenceNumber) {
LoggedCertificate logged_cert, lookup_cert;
this->test_signer_.CreateUnique(&logged_cert);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
EXPECT_EQ(42U, lookup_cert.sequence_number());
lookup_cert.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
}
TYPED_TEST(DBTest, AssignSequenceNumberNotPending) {
LoggedCertificate logged_cert;
this->test_signer_.CreateUnique(&logged_cert);
EXPECT_EQ(Database::ENTRY_NOT_FOUND,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 0));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::ENTRY_ALREADY_LOGGED,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
}
TYPED_TEST(DBTest, AssignSequenceNumberTwice) {
LoggedCertificate logged_cert, logged_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::SEQUENCE_NUMBER_ALREADY_IN_USE,
this->db()->AssignCertificateSequenceNumber(
logged_cert2.certificate_sha256_hash(), 42));
}
TYPED_TEST(DBTest, LookupBySequenceNumber) {
LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert2.certificate_sha256_hash(), 22));
EXPECT_EQ(Database::NOT_FOUND,
this->db()->LookupCertificateByIndex(23, &lookup_cert));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByIndex(42, &lookup_cert));
EXPECT_EQ(42U, lookup_cert.sequence_number());
lookup_cert.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByIndex(22, &lookup_cert2));
EXPECT_EQ(22U, lookup_cert2.sequence_number());
lookup_cert2.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2);
}
TYPED_TEST(DBTest, WriteTreeHead) {
SignedTreeHead sth, lookup_sth;
this->test_signer_.CreateUnique(&sth);
EXPECT_EQ(Database::NOT_FOUND, this->db()->LatestTreeHead(&lookup_sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
}
TYPED_TEST(DBTest, WriteTreeHeadDuplicateTimestamp) {
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
sth2.CopyFrom(sth);
sth2.set_tree_size(sth.tree_size() + 1);
EXPECT_EQ(Database::DUPLICATE_TREE_HEAD_TIMESTAMP,
this->db()->WriteTreeHead(sth2));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
}
TYPED_TEST(DBTest, WriteTreeHeadNewerTimestamp) {
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
this->test_signer_.CreateUnique(&sth2);
// Should be newer already but don't rely on this.
sth2.set_timestamp(sth.timestamp() + 1000);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth2, lookup_sth);
}
TYPED_TEST(DBTest, WriteTreeHeadOlderTimestamp) {
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
this->test_signer_.CreateUnique(&sth2);
// Should be newer already but don't rely on this.
sth2.set_timestamp(sth.timestamp() - 1000);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
}
TYPED_TEST(DBTest, Resume) {
LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
this->test_signer_.CreateUnique(&sth2);
sth2.set_timestamp(sth.timestamp() - 1000);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2));
Database *db2 = this->test_db_.SecondDB();
EXPECT_EQ(Database::LOOKUP_OK,
db2->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
EXPECT_EQ(42U, lookup_cert.sequence_number());
lookup_cert.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
EXPECT_EQ(Database::LOOKUP_OK,
db2->LookupCertificateByHash(
logged_cert2.certificate_sha256_hash(), &lookup_cert2));
TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2);
EXPECT_EQ(Database::LOOKUP_OK, db2->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
std::set<string> pending_hashes;
pending_hashes.insert(logged_cert2.certificate_sha256_hash());
EXPECT_EQ(pending_hashes, db2->PendingHashes());
delete db2;
}
TYPED_TEST(DBTest, ResumeEmpty) {
Database *db2 = this->test_db_.SecondDB();
LoggedCertificate lookup_cert;
EXPECT_EQ(Database::NOT_FOUND,
db2->LookupCertificateByIndex(0, &lookup_cert));
SignedTreeHead lookup_sth;
EXPECT_EQ(Database::NOT_FOUND, db2->LatestTreeHead(&lookup_sth));
EXPECT_TRUE(db2->PendingHashes().empty());
delete db2;
}
} // namespace
int main(int argc, char **argv) {
// Change the defaults. Can be overridden on command line.
// Log to stderr instead of log files.
FLAGS_logtostderr = true;
// Only log fatal messages by default.
FLAGS_minloglevel = 3;
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Refactor protobufs (leftovers from previous CL)<commit_after>/* -*- indent-tabs-mode: nil -*- */
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <set>
#include <string>
#include "database.h"
#include "file_db.h"
#include "file_storage.h"
#include "sqlite_db.h"
#include "test_db.h"
#include "test_signer.h"
#include "util.h"
namespace {
using ct::LoggedCertificate;
using ct::SignedTreeHead;
using std::string;
// A slightly shorter notation for constructing hex strings from binary blobs.
string H(const string &byte_string) {
return util::HexString(byte_string);
}
template <class T> class DBTest : public ::testing::Test {
protected:
DBTest() :
test_db_(),
test_signer_() { }
~DBTest() {}
T *db() const { return test_db_.db(); }
TestDB<T> test_db_;
TestSigner test_signer_;
};
typedef testing::Types<FileDB, SQLiteDB> Databases;
TYPED_TEST_CASE(DBTest, Databases);
TYPED_TEST(DBTest, CreatePending) {
LoggedCertificate logged_cert, lookup_cert;
this->test_signer_.CreateUnique(&logged_cert);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
string similar_hash = logged_cert.certificate_sha256_hash();
similar_hash[similar_hash.size() - 1] ^= 1;
EXPECT_EQ(Database::NOT_FOUND,
this->db()->LookupCertificateByHash(similar_hash,
&lookup_cert));
EXPECT_EQ(Database::NOT_FOUND,
this->db()->LookupCertificateByHash(this->test_signer_.UniqueHash(),
&lookup_cert));
}
TYPED_TEST(DBTest, GetPendingHashes) {
LoggedCertificate logged_cert, logged_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
std::set<string> hashes;
hashes.insert(logged_cert.certificate_sha256_hash());
hashes.insert(logged_cert2.certificate_sha256_hash());
std::set<string> pending_hashes = this->db()->PendingHashes();
EXPECT_EQ(hashes, pending_hashes);
}
TYPED_TEST(DBTest, CreatePendingDuplicate) {
LoggedCertificate logged_cert, duplicate_cert, lookup_cert;
this->test_signer_.CreateUnique(&logged_cert);
duplicate_cert.CopyFrom(logged_cert);
// Change the timestamp so that we can check that we get the right thing back.
duplicate_cert.mutable_sct()->set_timestamp(
logged_cert.sct().timestamp() + 1000);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::DUPLICATE_CERTIFICATE_HASH,
this->db()->CreatePendingCertificateEntry(duplicate_cert));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
// Check that we get the original entry back.
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
}
TYPED_TEST(DBTest, AssignSequenceNumber) {
LoggedCertificate logged_cert, lookup_cert;
this->test_signer_.CreateUnique(&logged_cert);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
EXPECT_EQ(42U, lookup_cert.sequence_number());
lookup_cert.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
}
TYPED_TEST(DBTest, AssignSequenceNumberNotPending) {
LoggedCertificate logged_cert;
this->test_signer_.CreateUnique(&logged_cert);
EXPECT_EQ(Database::ENTRY_NOT_FOUND,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 0));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::ENTRY_ALREADY_LOGGED,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
}
TYPED_TEST(DBTest, AssignSequenceNumberTwice) {
LoggedCertificate logged_cert, logged_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::SEQUENCE_NUMBER_ALREADY_IN_USE,
this->db()->AssignCertificateSequenceNumber(
logged_cert2.certificate_sha256_hash(), 42));
}
TYPED_TEST(DBTest, LookupBySequenceNumber) {
LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert2.certificate_sha256_hash(), 22));
EXPECT_EQ(Database::NOT_FOUND,
this->db()->LookupCertificateByIndex(23, &lookup_cert));
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByIndex(42, &lookup_cert));
EXPECT_EQ(42U, lookup_cert.sequence_number());
lookup_cert.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
EXPECT_EQ(Database::LOOKUP_OK,
this->db()->LookupCertificateByIndex(22, &lookup_cert2));
EXPECT_EQ(22U, lookup_cert2.sequence_number());
lookup_cert2.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2);
}
TYPED_TEST(DBTest, WriteTreeHead) {
SignedTreeHead sth, lookup_sth;
this->test_signer_.CreateUnique(&sth);
EXPECT_EQ(Database::NOT_FOUND, this->db()->LatestTreeHead(&lookup_sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
}
TYPED_TEST(DBTest, WriteTreeHeadDuplicateTimestamp) {
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
sth2.CopyFrom(sth);
sth2.set_tree_size(sth.tree_size() + 1);
EXPECT_EQ(Database::DUPLICATE_TREE_HEAD_TIMESTAMP,
this->db()->WriteTreeHead(sth2));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
}
TYPED_TEST(DBTest, WriteTreeHeadNewerTimestamp) {
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
this->test_signer_.CreateUnique(&sth2);
// Should be newer already but don't rely on this.
sth2.set_timestamp(sth.timestamp() + 1000);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth2, lookup_sth);
}
TYPED_TEST(DBTest, WriteTreeHeadOlderTimestamp) {
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
this->test_signer_.CreateUnique(&sth2);
// Should be newer already but don't rely on this.
sth2.set_timestamp(sth.timestamp() - 1000);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2));
EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
}
TYPED_TEST(DBTest, Resume) {
LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2;
this->test_signer_.CreateUnique(&logged_cert);
this->test_signer_.CreateUnique(&logged_cert2);
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert));
EXPECT_EQ(Database::OK,
this->db()->CreatePendingCertificateEntry(logged_cert2));
EXPECT_EQ(Database::OK,
this->db()->AssignCertificateSequenceNumber(
logged_cert.certificate_sha256_hash(), 42));
SignedTreeHead sth, sth2, lookup_sth;
this->test_signer_.CreateUnique(&sth);
this->test_signer_.CreateUnique(&sth2);
sth2.set_timestamp(sth.timestamp() - 1000);
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth));
EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2));
Database *db2 = this->test_db_.SecondDB();
EXPECT_EQ(Database::LOOKUP_OK,
db2->LookupCertificateByHash(
logged_cert.certificate_sha256_hash(), &lookup_cert));
EXPECT_EQ(42U, lookup_cert.sequence_number());
lookup_cert.clear_sequence_number();
TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert);
EXPECT_EQ(Database::LOOKUP_OK,
db2->LookupCertificateByHash(
logged_cert2.certificate_sha256_hash(), &lookup_cert2));
TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2);
EXPECT_EQ(Database::LOOKUP_OK, db2->LatestTreeHead(&lookup_sth));
TestSigner::TestEqualTreeHeads(sth, lookup_sth);
std::set<string> pending_hashes;
pending_hashes.insert(logged_cert2.certificate_sha256_hash());
EXPECT_EQ(pending_hashes, db2->PendingHashes());
delete db2;
}
TYPED_TEST(DBTest, ResumeEmpty) {
Database *db2 = this->test_db_.SecondDB();
LoggedCertificate lookup_cert;
EXPECT_EQ(Database::NOT_FOUND,
db2->LookupCertificateByIndex(0, &lookup_cert));
SignedTreeHead lookup_sth;
EXPECT_EQ(Database::NOT_FOUND, db2->LatestTreeHead(&lookup_sth));
EXPECT_TRUE(db2->PendingHashes().empty());
delete db2;
}
} // namespace
int main(int argc, char **argv) {
// Change the defaults. Can be overridden on command line.
// Log to stderr instead of log files.
FLAGS_logtostderr = true;
// Only log fatal messages by default.
FLAGS_minloglevel = 3;
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#include <string>
#include <sstream>
#include <time.h>
#include <sys/time.h>
#include "log_service_impl.h"
using namespace rpc;
using namespace std;
using namespace rlog;
void RLogServiceImpl::log(const i32& level, const std::string& source, const i64& msg_id, const std::string& message) {
log_piece piece;
piece.msg_id = msg_id;
piece.level = level;
piece.message = message;
const int tm_str_len = 80;
char tm_str[tm_str_len];
time_t now = time(NULL);
struct tm tm_val;
localtime_r(&now, &tm_val);
strftime(tm_str, tm_str_len - 1, "%F %T", &tm_val);
timeval tv;
gettimeofday(&tv, NULL);
l_.lock();
set<log_piece>& buffer = buffer_[source];
buffer.insert(piece);
i64& done = done_[source];
while (!buffer.empty() && buffer.begin()->msg_id <= done + 1) {
Log::log(buffer.begin()->level, 0, "remote", "%s.%03d %s: %s", tm_str, tv.tv_usec / 1000, source.c_str(), buffer.begin()->message.c_str());
done = max(done, buffer.begin()->msg_id);
buffer.erase(buffer.begin());
}
l_.unlock();
}
void RLogServiceImpl::aggregate_qps(const std::string& metric_name, const rpc::i32& increment) {
agg_qps_l_.lock();
list<agg_qps_record>& records = agg_qps_[metric_name];
agg_qps_record new_rec;
timeval tv;
gettimeofday(&tv, NULL);
double now = tv.tv_sec + tv.tv_usec / 1000.0 / 1000.0;
new_rec.tm = now;
if (records.empty()) {
new_rec.agg_count = increment;
} else {
new_rec.agg_count = records.back().agg_count + increment;
}
records.push_back(new_rec);
// only keep 5min qps info
while (now - records.front().tm > 5 * 60) {
records.erase(records.begin());
}
// report aggregate qps every 1sec
if (now - last_qps_report_tm_ > 1) {
const int report_intervals[] = {1, 5, 15, 30, 60};
ostringstream qps_ostr;
for (size_t i = 0; i < sizeof(report_intervals) / sizeof(report_intervals[0]); i++) {
double increment = -1;
const int report_interval = report_intervals[i];
for (list<agg_qps_record>::reverse_iterator it = records.rbegin(); it != records.rend(); ++it) {
if (now - it->tm < report_interval) {
increment = records.back().agg_count - it->agg_count;
} else {
break;
}
}
if (increment > 0) {
double qps = increment / report_interval;
qps_ostr << " " << report_interval << ":" << qps;
}
}
last_qps_report_tm_ = now;
if (qps_ostr.str().length() > 0) {
Log_info("qps '%s':%s", metric_name.c_str(), qps_ostr.str().c_str());
}
}
agg_qps_l_.unlock();
}
<commit_msg>minor update<commit_after>#include <string>
#include <sstream>
#include <time.h>
#include <sys/time.h>
#include "log_service_impl.h"
using namespace rpc;
using namespace std;
using namespace rlog;
void RLogServiceImpl::log(const i32& level, const std::string& source, const i64& msg_id, const std::string& message) {
log_piece piece;
piece.msg_id = msg_id;
piece.level = level;
piece.message = message;
const int tm_str_len = 80;
char tm_str[tm_str_len];
time_t now = time(NULL);
struct tm tm_val;
localtime_r(&now, &tm_val);
strftime(tm_str, tm_str_len - 1, "%F %T", &tm_val);
timeval tv;
gettimeofday(&tv, NULL);
l_.lock();
set<log_piece>& buffer = buffer_[source];
buffer.insert(piece);
i64& done = done_[source];
while (!buffer.empty() && buffer.begin()->msg_id <= done + 1) {
Log::log(buffer.begin()->level, 0, "remote", "%s.%03d %s: %s", tm_str, tv.tv_usec / 1000, source.c_str(), buffer.begin()->message.c_str());
done = max(done, buffer.begin()->msg_id);
buffer.erase(buffer.begin());
}
l_.unlock();
}
void RLogServiceImpl::aggregate_qps(const std::string& metric_name, const rpc::i32& increment) {
agg_qps_l_.lock();
list<agg_qps_record>& records = agg_qps_[metric_name];
agg_qps_record new_rec;
timeval tv;
gettimeofday(&tv, NULL);
double now = tv.tv_sec + tv.tv_usec / 1000.0 / 1000.0;
new_rec.tm = now;
if (records.empty()) {
new_rec.agg_count = increment;
} else {
new_rec.agg_count = records.back().agg_count + increment;
}
records.push_back(new_rec);
// only keep 5min qps info
while (now - records.front().tm > 5 * 60) {
records.erase(records.begin());
}
// report aggregate qps every 1sec
if (now - last_qps_report_tm_ > 1) {
const int report_intervals[] = {1, 5, 15, 30, 60};
ostringstream qps_ostr;
for (size_t i = 0; i < arraysize(report_intervals); i++) {
double increment = -1;
const int report_interval = report_intervals[i];
for (list<agg_qps_record>::reverse_iterator it = records.rbegin(); it != records.rend(); ++it) {
if (now - it->tm < report_interval) {
increment = records.back().agg_count - it->agg_count;
} else {
break;
}
}
if (increment > 0) {
double qps = increment / report_interval;
qps_ostr << " " << report_interval << ":" << qps;
}
}
last_qps_report_tm_ = now;
if (qps_ostr.str().length() > 0) {
Log_info("qps '%s':%s", metric_name.c_str(), qps_ostr.str().c_str());
}
}
agg_qps_l_.unlock();
}
<|endoftext|> |
<commit_before>#pragma once
#include "boost_defs.hpp"
#include "gcd_utility.hpp"
#include "session.hpp"
#include <boost/optional.hpp>
#include <boost/signals2.hpp>
#include <memory>
namespace krbn {
class console_user_id_monitor final {
public:
boost::signals2::signal<void(boost::optional<uid_t>)> console_user_id_changed;
console_user_id_monitor(const console_user_id_monitor&) = delete;
console_user_id_monitor(void) {
timer_ = std::make_unique<gcd_utility::main_queue_timer>(
dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC),
1 * NSEC_PER_SEC,
0,
^{
auto u = session::get_current_console_user_id();
if (uid_ && *uid_ == u) {
return;
}
console_user_id_changed(u);
uid_ = std::make_unique<boost::optional<uid_t>>(u);
});
}
~console_user_id_monitor(void) {
timer_ = nullptr;
}
private:
std::unique_ptr<gcd_utility::main_queue_timer> timer_;
std::unique_ptr<boost::optional<uid_t>> uid_;
};
} // namespace krbn
<commit_msg>add console_user_id_monitor::start<commit_after>#pragma once
#include "boost_defs.hpp"
#include "gcd_utility.hpp"
#include "session.hpp"
#include <boost/optional.hpp>
#include <boost/signals2.hpp>
#include <memory>
namespace krbn {
class console_user_id_monitor final {
public:
boost::signals2::signal<void(boost::optional<uid_t>)> console_user_id_changed;
console_user_id_monitor(const console_user_id_monitor&) = delete;
console_user_id_monitor(void) {
}
~console_user_id_monitor(void) {
stop();
}
void start(void) {
stop();
timer_ = std::make_unique<gcd_utility::main_queue_timer>(
DISPATCH_TIME_NOW,
1 * NSEC_PER_SEC,
0,
^{
auto u = session::get_current_console_user_id();
if (uid_ && *uid_ == u) {
return;
}
console_user_id_changed(u);
uid_ = std::make_unique<boost::optional<uid_t>>(u);
});
}
void stop(void) {
timer_ = nullptr;
}
private:
std::unique_ptr<gcd_utility::main_queue_timer> timer_;
std::unique_ptr<boost::optional<uid_t>> uid_;
};
} // namespace krbn
<|endoftext|> |
<commit_before>#include "GUI_ObjectSettings.hpp"
#include "GUI_ObjectList.hpp"
#include "OptionsGroup.hpp"
#include "wxExtensions.hpp"
#include "PresetBundle.hpp"
#include "libslic3r/Model.hpp"
#include <boost/algorithm/string.hpp>
#include "I18N.hpp"
#include "ConfigManipulation.hpp"
#include <wx/wupdlock.h>
namespace Slic3r
{
namespace GUI
{
OG_Settings::OG_Settings(wxWindow* parent, const bool staticbox) :
m_parent(parent)
{
wxString title = staticbox ? " " : ""; // temporary workaround - #ys_FIXME
m_og = std::make_shared<ConfigOptionsGroup>(parent, title);
}
bool OG_Settings::IsShown()
{
return m_og->sizer->IsEmpty() ? false : m_og->sizer->IsShown(size_t(0));
}
void OG_Settings::Show(const bool show)
{
m_og->Show(show);
}
void OG_Settings::Hide()
{
Show(false);
}
void OG_Settings::UpdateAndShow(const bool show)
{
Show(show);
// m_parent->Layout();
}
wxSizer* OG_Settings::get_sizer()
{
return m_og->sizer;
}
ObjectSettings::ObjectSettings(wxWindow* parent) :
OG_Settings(parent, true)
{
m_og->set_name(_(L("Additional Settings")));
m_settings_list_sizer = new wxBoxSizer(wxVERTICAL);
m_og->sizer->Add(m_settings_list_sizer, 1, wxEXPAND | wxLEFT, 5);
m_bmp_delete = ScalableBitmap(parent, "cross");
m_bmp_delete_focus = ScalableBitmap(parent, "cross_focus");
}
bool ObjectSettings::update_settings_list()
{
m_settings_list_sizer->Clear(true);
m_og_settings.resize(0);
auto objects_ctrl = wxGetApp().obj_list();
auto objects_model = wxGetApp().obj_list()->GetModel();
auto config = wxGetApp().obj_list()->config();
const auto item = objects_ctrl->GetSelection();
if (!item || !objects_model->IsSettingsItem(item) || !config || objects_ctrl->multiple_selection())
return false;
const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject;
SettingsBundle cat_options = objects_ctrl->get_item_settings_bundle(config, is_object_settings);
if (!cat_options.empty())
{
std::vector<std::string> categories;
categories.reserve(cat_options.size());
auto extra_column = [config, this](wxWindow* parent, const Line& line)
{
auto opt_key = (line.get_options())[0].opt_id; //we assume that we have one option per line
auto btn = new ScalableButton(parent, wxID_ANY, m_bmp_delete);
btn->SetToolTip(_(L("Remove parameter")));
btn->SetBitmapFocus(m_bmp_delete_focus.bmp());
btn->SetBitmapHover(m_bmp_delete_focus.bmp());
btn->Bind(wxEVT_BUTTON, [opt_key, config, this](wxEvent &event) {
wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Delete Option %s")), opt_key));
config->erase(opt_key);
wxGetApp().obj_list()->changed_object();
wxTheApp->CallAfter([this]() {
wxWindowUpdateLocker noUpdates(m_parent);
update_settings_list();
m_parent->Layout();
});
});
return btn;
};
for (auto& cat : cat_options)
{
categories.push_back(cat.first);
auto optgroup = std::make_shared<ConfigOptionsGroup>(m_og->ctrl_parent(), _(cat.first), config, false, extra_column);
optgroup->label_width = 15;
optgroup->sidetext_width = 5.5;
optgroup->m_on_change = [this, config](const t_config_option_key& opt_id, const boost::any& value) {
this->update_config_values(config);
wxGetApp().obj_list()->changed_object(); };
// call back for rescaling of the extracolumn control
optgroup->rescale_extra_column_item = [this](wxWindow* win) {
auto *ctrl = dynamic_cast<ScalableButton*>(win);
if (ctrl == nullptr)
return;
ctrl->SetBitmap_(m_bmp_delete);
ctrl->SetBitmapFocus(m_bmp_delete_focus.bmp());
ctrl->SetBitmapHover(m_bmp_delete_focus.bmp());
};
const bool is_extruders_cat = cat.first == "Extruders";
for (auto& opt : cat.second)
{
Option option = optgroup->get_option(opt);
option.opt.width = 12;
if (is_extruders_cat)
option.opt.max = wxGetApp().extruders_edited_cnt();
optgroup->append_single_option_line(option);
optgroup->get_field(opt)->m_on_change = [optgroup](const std::string& opt_id, const boost::any& value) {
// first of all take a snapshot and then change value in configuration
wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Change Option %s")), opt_id));
optgroup->on_change_OG(opt_id, value);
};
}
optgroup->reload_config();
m_settings_list_sizer->Add(optgroup->sizer, 0, wxEXPAND | wxALL, 0);
m_og_settings.push_back(optgroup);
}
if (!categories.empty()) {
objects_model->UpdateSettingsDigest(item, categories);
update_config_values(config);
}
}
else
{
objects_ctrl->select_item(objects_model->Delete(item));
return false;
}
return true;
}
void ObjectSettings::update_config_values(DynamicPrintConfig* config)
{
const auto objects_model = wxGetApp().obj_list()->GetModel();
const auto item = wxGetApp().obj_list()->GetSelection();
const auto printer_technology = wxGetApp().plater()->printer_technology();
const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject;
// update config values according to configuration hierarchy
DynamicPrintConfig main_config = printer_technology == ptFFF ?
wxGetApp().preset_bundle->prints.get_edited_preset().config :
wxGetApp().preset_bundle->sla_prints.get_edited_preset().config;
auto load_config = [this, config, &main_config]()
{
// load checked values from main_config to config
config->apply_only(main_config, config->keys(), true);
// Initialize UI components with the config values.
for (auto og : m_og_settings)
og->reload_config();
// next config check
update_config_values(config);
};
auto get_field = [this](const t_config_option_key & opt_key, int opt_index)
{
Field* field = nullptr;
for (auto og : m_og_settings) {
field = og->get_fieldc(opt_key, opt_index);
if (field != nullptr)
return field;
}
return field;
};
ConfigManipulation config_manipulation(load_config, get_field, nullptr, config);
if (!is_object_settings)
{
const int obj_idx = objects_model->GetObjectIdByItem(item);
assert(obj_idx >= 0);
DynamicPrintConfig* obj_config = &wxGetApp().model().objects[obj_idx]->config;
main_config.apply(*obj_config, true);
printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) :
config_manipulation.update_print_sla_config(&main_config) ;
}
main_config.apply(*config, true);
printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) :
config_manipulation.update_print_sla_config(&main_config) ;
printer_technology == ptFFF ? config_manipulation.toggle_print_fff_options(&main_config) :
config_manipulation.toggle_print_sla_options(&main_config) ;
}
void ObjectSettings::UpdateAndShow(const bool show)
{
OG_Settings::UpdateAndShow(show ? update_settings_list() : false);
}
void ObjectSettings::msw_rescale()
{
m_bmp_delete.msw_rescale();
m_bmp_delete_focus.msw_rescale();
for (auto group : m_og_settings)
group->msw_rescale();
}
} //namespace GUI
} //namespace Slic3r <commit_msg>Fixed application crash, when change focus from overridden option to empty space in ObjectList.<commit_after>#include "GUI_ObjectSettings.hpp"
#include "GUI_ObjectList.hpp"
#include "OptionsGroup.hpp"
#include "wxExtensions.hpp"
#include "PresetBundle.hpp"
#include "libslic3r/Model.hpp"
#include <boost/algorithm/string.hpp>
#include "I18N.hpp"
#include "ConfigManipulation.hpp"
#include <wx/wupdlock.h>
namespace Slic3r
{
namespace GUI
{
OG_Settings::OG_Settings(wxWindow* parent, const bool staticbox) :
m_parent(parent)
{
wxString title = staticbox ? " " : ""; // temporary workaround - #ys_FIXME
m_og = std::make_shared<ConfigOptionsGroup>(parent, title);
}
bool OG_Settings::IsShown()
{
return m_og->sizer->IsEmpty() ? false : m_og->sizer->IsShown(size_t(0));
}
void OG_Settings::Show(const bool show)
{
m_og->Show(show);
}
void OG_Settings::Hide()
{
Show(false);
}
void OG_Settings::UpdateAndShow(const bool show)
{
Show(show);
// m_parent->Layout();
}
wxSizer* OG_Settings::get_sizer()
{
return m_og->sizer;
}
ObjectSettings::ObjectSettings(wxWindow* parent) :
OG_Settings(parent, true)
{
m_og->set_name(_(L("Additional Settings")));
m_settings_list_sizer = new wxBoxSizer(wxVERTICAL);
m_og->sizer->Add(m_settings_list_sizer, 1, wxEXPAND | wxLEFT, 5);
m_bmp_delete = ScalableBitmap(parent, "cross");
m_bmp_delete_focus = ScalableBitmap(parent, "cross_focus");
}
bool ObjectSettings::update_settings_list()
{
m_settings_list_sizer->Clear(true);
m_og_settings.resize(0);
auto objects_ctrl = wxGetApp().obj_list();
auto objects_model = wxGetApp().obj_list()->GetModel();
auto config = wxGetApp().obj_list()->config();
const auto item = objects_ctrl->GetSelection();
if (!item || !objects_model->IsSettingsItem(item) || !config || objects_ctrl->multiple_selection())
return false;
const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject;
SettingsBundle cat_options = objects_ctrl->get_item_settings_bundle(config, is_object_settings);
if (!cat_options.empty())
{
std::vector<std::string> categories;
categories.reserve(cat_options.size());
auto extra_column = [config, this](wxWindow* parent, const Line& line)
{
auto opt_key = (line.get_options())[0].opt_id; //we assume that we have one option per line
auto btn = new ScalableButton(parent, wxID_ANY, m_bmp_delete);
btn->SetToolTip(_(L("Remove parameter")));
btn->SetBitmapFocus(m_bmp_delete_focus.bmp());
btn->SetBitmapHover(m_bmp_delete_focus.bmp());
btn->Bind(wxEVT_BUTTON, [opt_key, config, this](wxEvent &event) {
wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Delete Option %s")), opt_key));
config->erase(opt_key);
wxGetApp().obj_list()->changed_object();
wxTheApp->CallAfter([this]() {
wxWindowUpdateLocker noUpdates(m_parent);
update_settings_list();
m_parent->Layout();
});
});
return btn;
};
for (auto& cat : cat_options)
{
categories.push_back(cat.first);
auto optgroup = std::make_shared<ConfigOptionsGroup>(m_og->ctrl_parent(), _(cat.first), config, false, extra_column);
optgroup->label_width = 15;
optgroup->sidetext_width = 5.5;
optgroup->m_on_change = [this, config](const t_config_option_key& opt_id, const boost::any& value) {
this->update_config_values(config);
wxGetApp().obj_list()->changed_object(); };
// call back for rescaling of the extracolumn control
optgroup->rescale_extra_column_item = [this](wxWindow* win) {
auto *ctrl = dynamic_cast<ScalableButton*>(win);
if (ctrl == nullptr)
return;
ctrl->SetBitmap_(m_bmp_delete);
ctrl->SetBitmapFocus(m_bmp_delete_focus.bmp());
ctrl->SetBitmapHover(m_bmp_delete_focus.bmp());
};
const bool is_extruders_cat = cat.first == "Extruders";
for (auto& opt : cat.second)
{
Option option = optgroup->get_option(opt);
option.opt.width = 12;
if (is_extruders_cat)
option.opt.max = wxGetApp().extruders_edited_cnt();
optgroup->append_single_option_line(option);
optgroup->get_field(opt)->m_on_change = [optgroup](const std::string& opt_id, const boost::any& value) {
// first of all take a snapshot and then change value in configuration
wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Change Option %s")), opt_id));
optgroup->on_change_OG(opt_id, value);
};
}
optgroup->reload_config();
m_settings_list_sizer->Add(optgroup->sizer, 0, wxEXPAND | wxALL, 0);
m_og_settings.push_back(optgroup);
}
if (!categories.empty()) {
objects_model->UpdateSettingsDigest(item, categories);
update_config_values(config);
}
}
else
{
objects_ctrl->select_item(objects_model->Delete(item));
return false;
}
return true;
}
void ObjectSettings::update_config_values(DynamicPrintConfig* config)
{
const auto objects_model = wxGetApp().obj_list()->GetModel();
const auto item = wxGetApp().obj_list()->GetSelection();
const auto printer_technology = wxGetApp().plater()->printer_technology();
const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject;
if (!item || !objects_model->IsSettingsItem(item) || !config)
return;
// update config values according to configuration hierarchy
DynamicPrintConfig main_config = printer_technology == ptFFF ?
wxGetApp().preset_bundle->prints.get_edited_preset().config :
wxGetApp().preset_bundle->sla_prints.get_edited_preset().config;
auto load_config = [this, config, &main_config]()
{
// load checked values from main_config to config
config->apply_only(main_config, config->keys(), true);
// Initialize UI components with the config values.
for (auto og : m_og_settings)
og->reload_config();
// next config check
update_config_values(config);
};
auto get_field = [this](const t_config_option_key & opt_key, int opt_index)
{
Field* field = nullptr;
for (auto og : m_og_settings) {
field = og->get_fieldc(opt_key, opt_index);
if (field != nullptr)
return field;
}
return field;
};
ConfigManipulation config_manipulation(load_config, get_field, nullptr, config);
if (!is_object_settings)
{
const int obj_idx = objects_model->GetObjectIdByItem(item);
assert(obj_idx >= 0);
DynamicPrintConfig* obj_config = &wxGetApp().model().objects[obj_idx]->config;
main_config.apply(*obj_config, true);
printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) :
config_manipulation.update_print_sla_config(&main_config) ;
}
main_config.apply(*config, true);
printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) :
config_manipulation.update_print_sla_config(&main_config) ;
printer_technology == ptFFF ? config_manipulation.toggle_print_fff_options(&main_config) :
config_manipulation.toggle_print_sla_options(&main_config) ;
}
void ObjectSettings::UpdateAndShow(const bool show)
{
OG_Settings::UpdateAndShow(show ? update_settings_list() : false);
}
void ObjectSettings::msw_rescale()
{
m_bmp_delete.msw_rescale();
m_bmp_delete_focus.msw_rescale();
for (auto group : m_og_settings)
group->msw_rescale();
}
} //namespace GUI
} //namespace Slic3r <|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#include <seastar/http/routes.hh>
#include <seastar/http/reply.hh>
#include <seastar/http/exception.hh>
#include <seastar/http/json_path.hh>
namespace seastar {
namespace httpd {
using namespace std;
void verify_param(const request& req, const sstring& param) {
if (req.get_query_param(param) == "") {
throw missing_param_exception(param);
}
}
routes::routes() : _general_handler([this](std::exception_ptr eptr) mutable {
return exception_reply(eptr);
}) {}
routes::~routes() {
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto kv : _map[i]) {
delete kv.second;
}
}
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto r : _rules[i]) {
delete r.second;
}
}
}
std::unique_ptr<reply> routes::exception_reply(std::exception_ptr eptr) {
auto rep = std::make_unique<reply>();
try {
// go over the register exception handler
// if one of them handle the exception, return.
for (auto e: _exceptions) {
try {
return e.second(eptr);
} catch (...) {
// this is needed if there are more then one register exception handler
// so if the exception handler throw a new exception, they would
// get the new exception and not the original one.
eptr = std::current_exception();
}
}
std::rethrow_exception(eptr);
} catch (const base_exception& e) {
rep->set_status(e.status(), json_exception(e).to_json());
} catch (...) {
rep->set_status(reply::status_type::internal_server_error,
json_exception(std::current_exception()).to_json());
}
rep->done("json");
return rep;
}
future<std::unique_ptr<reply> > routes::handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
handler_base* handler = get_handler(str2type(req->_method),
normalize_url(path), req->param);
if (handler != nullptr) {
try {
for (auto& i : handler->_mandatory_param) {
verify_param(*req.get(), i);
}
auto r = handler->handle(path, std::move(req), std::move(rep));
return r.handle_exception(_general_handler);
} catch (const redirect_exception& _e) {
rep.reset(new reply());
rep->add_header("Location", _e.url).set_status(_e.status()).done(
"json");
} catch (...) {
rep = exception_reply(std::current_exception());
}
} else {
rep.reset(new reply());
json_exception ex(not_found_exception("Not found"));
rep->set_status(reply::status_type::not_found, ex.to_json()).done(
"json");
}
return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
}
sstring routes::normalize_url(const sstring& url) {
if (url.length() < 2 || url.at(url.length() - 1) != '/') {
return url;
}
return url.substr(0, url.length() - 1);
}
handler_base* routes::get_handler(operation_type type, const sstring& url,
parameters& params) {
handler_base* handler = get_exact_match(type, url);
if (handler != nullptr) {
return handler;
}
for (auto&& rule : _rules[type]) {
handler = rule.second->get(url, params);
if (handler != nullptr) {
return handler;
}
params.clear();
}
return nullptr;
}
routes& routes::add(operation_type type, const url& url,
handler_base* handler) {
match_rule* rule = new match_rule(handler);
rule->add_str(url._path);
if (url._param != "") {
rule->add_param(url._param, true);
}
return add(rule, type);
}
template <typename Map, typename Key>
static auto delete_rule_from(operation_type type, Key& key, Map& map) {
auto& bucket = map[type];
auto ret = bucket.find(key);
if (ret != bucket.end()) {
bucket.erase(ret);
}
return ret == bucket.end() ? nullptr : ret->second;
}
handler_base* routes::drop(operation_type type, const sstring& url) {
return delete_rule_from(type, url, _map);
}
match_rule* routes::del_cookie(rule_cookie cookie, operation_type type) {
return delete_rule_from(type, cookie, _rules);
}
void routes::add_alias(const path_description& old_path, const path_description& new_path) {
httpd::parameters p;
stringstream path;
path << old_path.path;
for (const auto& p : old_path.params) {
// the path_description path does not contains the path parameters
// so just add a fake parameter to the path for each of the parameters,
// and add the string for each fixed string part.
if (p.type == path_description::url_component_type::FIXED_STRING) {
path << p.name;
} else {
path << "/k";
}
}
auto a = get_handler(old_path.operations.method, path.str(), p);
if (!a) {
throw std::runtime_error("routes::add_alias path_description not found: " + old_path.path);
}
// if a handler is found then it must be a function_handler
new_path.set(*this, new function_handler(*static_cast<function_handler*>(a)));
}
rule_registration::rule_registration(routes& rs, match_rule& rule, operation_type op)
: _routes(rs) , _op(op)
, _cookie(_routes.add_cookie(&rule, _op)) {}
rule_registration::~rule_registration() {
_routes.del_cookie(_cookie, _op);
}
handler_registration::handler_registration(routes& rs, handler_base& h, const sstring& url, operation_type op)
: _routes(rs), _url(url), _op(op) {
_routes.put(_op, _url, &h);
}
handler_registration::~handler_registration() {
_routes.drop(_op, _url);
}
}
}
<commit_msg>http: Fix use after free<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#include <seastar/http/routes.hh>
#include <seastar/http/reply.hh>
#include <seastar/http/exception.hh>
#include <seastar/http/json_path.hh>
namespace seastar {
namespace httpd {
using namespace std;
void verify_param(const request& req, const sstring& param) {
if (req.get_query_param(param) == "") {
throw missing_param_exception(param);
}
}
routes::routes() : _general_handler([this](std::exception_ptr eptr) mutable {
return exception_reply(eptr);
}) {}
routes::~routes() {
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto kv : _map[i]) {
delete kv.second;
}
}
for (int i = 0; i < NUM_OPERATION; i++) {
for (auto r : _rules[i]) {
delete r.second;
}
}
}
std::unique_ptr<reply> routes::exception_reply(std::exception_ptr eptr) {
auto rep = std::make_unique<reply>();
try {
// go over the register exception handler
// if one of them handle the exception, return.
for (auto e: _exceptions) {
try {
return e.second(eptr);
} catch (...) {
// this is needed if there are more then one register exception handler
// so if the exception handler throw a new exception, they would
// get the new exception and not the original one.
eptr = std::current_exception();
}
}
std::rethrow_exception(eptr);
} catch (const base_exception& e) {
rep->set_status(e.status(), json_exception(e).to_json());
} catch (...) {
rep->set_status(reply::status_type::internal_server_error,
json_exception(std::current_exception()).to_json());
}
rep->done("json");
return rep;
}
future<std::unique_ptr<reply> > routes::handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) {
handler_base* handler = get_handler(str2type(req->_method),
normalize_url(path), req->param);
if (handler != nullptr) {
try {
for (auto& i : handler->_mandatory_param) {
verify_param(*req.get(), i);
}
auto r = handler->handle(path, std::move(req), std::move(rep));
return r.handle_exception(_general_handler);
} catch (const redirect_exception& _e) {
rep.reset(new reply());
rep->add_header("Location", _e.url).set_status(_e.status()).done(
"json");
} catch (...) {
rep = exception_reply(std::current_exception());
}
} else {
rep.reset(new reply());
json_exception ex(not_found_exception("Not found"));
rep->set_status(reply::status_type::not_found, ex.to_json()).done(
"json");
}
return make_ready_future<std::unique_ptr<reply>>(std::move(rep));
}
sstring routes::normalize_url(const sstring& url) {
if (url.length() < 2 || url.at(url.length() - 1) != '/') {
return url;
}
return url.substr(0, url.length() - 1);
}
handler_base* routes::get_handler(operation_type type, const sstring& url,
parameters& params) {
handler_base* handler = get_exact_match(type, url);
if (handler != nullptr) {
return handler;
}
for (auto&& rule : _rules[type]) {
handler = rule.second->get(url, params);
if (handler != nullptr) {
return handler;
}
params.clear();
}
return nullptr;
}
routes& routes::add(operation_type type, const url& url,
handler_base* handler) {
match_rule* rule = new match_rule(handler);
rule->add_str(url._path);
if (url._param != "") {
rule->add_param(url._param, true);
}
return add(rule, type);
}
template <typename Map, typename Key>
static auto delete_rule_from(operation_type type, Key& key, Map& map) {
auto& bucket = map[type];
auto ret = bucket.find(key);
using ret_type = decltype(ret->second);
if (ret != bucket.end()) {
ret_type v = ret->second;
bucket.erase(ret);
return v;
}
return static_cast<ret_type>(nullptr);
}
handler_base* routes::drop(operation_type type, const sstring& url) {
return delete_rule_from(type, url, _map);
}
match_rule* routes::del_cookie(rule_cookie cookie, operation_type type) {
return delete_rule_from(type, cookie, _rules);
}
void routes::add_alias(const path_description& old_path, const path_description& new_path) {
httpd::parameters p;
stringstream path;
path << old_path.path;
for (const auto& p : old_path.params) {
// the path_description path does not contains the path parameters
// so just add a fake parameter to the path for each of the parameters,
// and add the string for each fixed string part.
if (p.type == path_description::url_component_type::FIXED_STRING) {
path << p.name;
} else {
path << "/k";
}
}
auto a = get_handler(old_path.operations.method, path.str(), p);
if (!a) {
throw std::runtime_error("routes::add_alias path_description not found: " + old_path.path);
}
// if a handler is found then it must be a function_handler
new_path.set(*this, new function_handler(*static_cast<function_handler*>(a)));
}
rule_registration::rule_registration(routes& rs, match_rule& rule, operation_type op)
: _routes(rs) , _op(op)
, _cookie(_routes.add_cookie(&rule, _op)) {}
rule_registration::~rule_registration() {
_routes.del_cookie(_cookie, _op);
}
handler_registration::handler_registration(routes& rs, handler_base& h, const sstring& url, operation_type op)
: _routes(rs), _url(url), _op(op) {
_routes.put(_op, _url, &h);
}
handler_registration::~handler_registration() {
_routes.drop(_op, _url);
}
}
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "../libjsapi.h"
rs::jsapi::Runtime rt_;
class ScriptExceptionTests : public ::testing::Test {
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(ScriptExceptionTests, test1) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "!)(*\")(!*\"!");
script.Compile();
}, rs::jsapi::ScriptException);
}
TEST_F(ScriptExceptionTests, test2) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "var xyz = abc;");
script.Compile();
script.Execute();
}, rs::jsapi::ScriptException);
}
TEST_F(ScriptExceptionTests, test3) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "(function(){return abc;})()");
script.Compile();
rs::jsapi::Value result(rt_);
script.Execute(result);
}, rs::jsapi::ScriptException);
}<commit_msg>Added more exception tests<commit_after>#include <gtest/gtest.h>
#include "../libjsapi.h"
rs::jsapi::Runtime rt_;
class ScriptExceptionTests : public ::testing::Test {
protected:
virtual void SetUp() {
}
virtual void TearDown() {
}
};
TEST_F(ScriptExceptionTests, test1) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "!)(*\")(!*\"!");
script.Compile();
}, rs::jsapi::ScriptException);
}
TEST_F(ScriptExceptionTests, test2) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "var xyz = abc;");
script.Compile();
script.Execute();
}, rs::jsapi::ScriptException);
}
TEST_F(ScriptExceptionTests, test3) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "(function(){return abc;})()");
script.Compile();
rs::jsapi::Value result(rt_);
script.Execute(result);
}, rs::jsapi::ScriptException);
}
TEST_F(ScriptExceptionTests, test4) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "!)(*\")(!*\"!");
script.Compile();
}, rs::jsapi::ScriptException);
rs::jsapi::Script script(rt_, "(function(){return 42;})()");
script.Compile();
rs::jsapi::Value result(rt_);
script.Execute(result);
ASSERT_EQ(result().isNumber(), true);
ASSERT_EQ(result().toNumber(), 42);
}
TEST_F(ScriptExceptionTests, test5) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "var xyz = abc;");
script.Compile();
script.Execute();
}, rs::jsapi::ScriptException);
rs::jsapi::Script script(rt_, "(function(){return 42;})()");
script.Compile();
rs::jsapi::Value result(rt_);
script.Execute(result);
ASSERT_EQ(result().isNumber(), true);
ASSERT_EQ(result().toNumber(), 42);
}
TEST_F(ScriptExceptionTests, test6) {
ASSERT_THROW({
rs::jsapi::Script script(rt_, "(function(){return abc;})()");
script.Compile();
rs::jsapi::Value result(rt_);
script.Execute(result);
}, rs::jsapi::ScriptException);
rs::jsapi::Script script(rt_, "(function(){return 42;})()");
script.Compile();
rs::jsapi::Value result(rt_);
script.Execute(result);
ASSERT_EQ(result().isNumber(), true);
ASSERT_EQ(result().toNumber(), 42);
}<|endoftext|> |
<commit_before>#include <GarrysMod/Lua/Interface.h>
#include <GarrysMod/Lua/Helpers.hpp>
#include <GarrysMod/FunctionPointers.hpp>
#include <GarrysMod/InterfacePointers.hpp>
#include <detouring/classproxy.hpp>
#include <cstdint>
#include <string>
#include <unordered_set>
#include <algorithm>
#include <cctype>
#include <interface.h>
#include <filesystem.h>
#include <eiface.h>
class GModDataPack;
namespace Bootil
{
class Buffer
{
public:
virtual ~Buffer() = default; // For the VTable
void *data;
uint32_t size;
uint32_t pos;
uint32_t written;
};
class AutoBuffer : public Buffer
{
public:
virtual ~AutoBuffer() = default; // For the VTable
};
}
class LuaFile // 116 bytes
{
public:
virtual ~LuaFile() = default; // For the VTable
std::string path;
std::string parent;
std::string content;
Bootil::AutoBuffer buffer;
bool unknown1;
bool unknown2;
};
namespace luapack
{
static IFileSystem *filesystem = nullptr;
static std::unordered_set<std::string> whitelist_extensions = { "lua", "txt", "dat" };
static std::unordered_set<std::string> whitelist_pathid = { "lsv", "lua", "data" };
class GModDataPackProxy : public Detouring::ClassProxy<GModDataPack, GModDataPackProxy>
{
private:
#if defined _WIN32
typedef void( __thiscall *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );
#elif defined __linux || defined __APPLE__
typedef void( *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );
#endif
static AddOrUpdateFile_t AddOrUpdateFile_original;
static const char hook_name[];
static GarrysMod::Lua::ILuaBase *lua;
public:
static void Initialize( GarrysMod::Lua::ILuaBase *LUA )
{
lua = LUA;
AddOrUpdateFile_original = FunctionPointers::GModDataPack_AddOrUpdateFile( );
if( AddOrUpdateFile_original == nullptr )
LUA->ThrowError( "failed to find GModDataPack::AddOrUpdateFile" );
if( !Hook( AddOrUpdateFile_original, &GModDataPackProxy::AddOrUpdateFile ) )
LUA->ThrowError( "failed to hook GModDataPack::AddOrUpdateFile" );
}
static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA )
{
UnHook( AddOrUpdateFile_original );
}
void AddOrUpdateFile( LuaFile *file, bool reload )
{
LuaHelpers::PushHookRun( lua, hook_name );
lua->PushString( file->path.c_str( ) );
lua->PushBool( reload );
bool shouldcall = true;
if( LuaHelpers::CallHookRun( lua, 2, 1 ) )
shouldcall = !lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) || lua->GetBool( -1 );
lua->Pop( 1 );
if( shouldcall )
return Call( AddOrUpdateFile_original, file, reload );
}
static GModDataPackProxy Singleton;
};
GModDataPackProxy::AddOrUpdateFile_t GModDataPackProxy::AddOrUpdateFile_original = nullptr;
const char GModDataPackProxy::hook_name[] = "AddOrUpdateCSLuaFile";
GarrysMod::Lua::ILuaBase *GModDataPackProxy::lua = nullptr;
static bool IsPathAllowed( std::string &filename )
{
if( !V_RemoveDotSlashes( &filename[0], CORRECT_PATH_SEPARATOR, true ) )
return false;
filename.resize( std::strlen( filename.c_str( ) ) );
const char *extension = V_GetFileExtension( filename.c_str( ) );
if( extension == nullptr )
return false;
std::string ext = extension;
std::transform( ext.begin( ), ext.end( ), ext.begin( ), [] ( uint8_t c )
{
return static_cast<char>( std::tolower( c ) );
} );
return whitelist_extensions.find( ext ) != whitelist_extensions.end( );
}
inline bool IsPathIDAllowed( std::string &pathid )
{
std::transform( pathid.begin( ), pathid.end( ), pathid.begin( ), [] ( uint8_t c )
{
return static_cast<char>( std::tolower( c ) );
} );
return whitelist_pathid.find( pathid ) != whitelist_pathid.end( );
}
LUA_FUNCTION_STATIC( Rename )
{
LUA->CheckType( 1, GarrysMod::Lua::Type::STRING );
LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );
LUA->CheckType( 3, GarrysMod::Lua::Type::STRING );
std::string fname = LUA->GetString( 1 ), fnew = LUA->GetString( 2 ), pathid = LUA->GetString( 3 );
if( !IsPathAllowed( fname ) || !IsPathAllowed( fnew ) || !IsPathIDAllowed( pathid ) )
{
LUA->PushBool( false );
return 1;
}
LUA->PushBool( filesystem->RenameFile( fname.c_str( ), fnew.c_str( ), pathid.c_str( ) ) );
return 1;
}
static void Initialize( GarrysMod::Lua::ILuaBase *LUA )
{
filesystem = InterfacePointers::FileSystem( );
if( filesystem == nullptr )
LUA->ThrowError( "failed to initialize IFileSystem" );
GModDataPackProxy::Singleton.Initialize( LUA );
LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" );
if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
{
GModDataPackProxy::Singleton.Deinitialize(LUA);
LUA->ThrowError("luapack table not found");
}
LUA->PushCFunction( Rename );
LUA->SetField( -2, "Rename" );
LUA->Pop( 1 );
}
static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA )
{
LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" );
if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
LUA->ThrowError( "luapack table not found" );
LUA->PushNil( );
LUA->SetField( -2, "Rename" );
LUA->Pop( 1 );
GModDataPackProxy::Singleton.Deinitialize( LUA );
}
}
GMOD_MODULE_OPEN( )
{
luapack::Initialize( LUA );
return 0;
}
GMOD_MODULE_CLOSE( )
{
luapack::Deinitialize( LUA );
return 0;
}
<commit_msg>Removed OS dependent function definition<commit_after>#include <GarrysMod/Lua/Interface.h>
#include <GarrysMod/Lua/Helpers.hpp>
#include <GarrysMod/FunctionPointers.hpp>
#include <GarrysMod/InterfacePointers.hpp>
#include <detouring/classproxy.hpp>
#include <cstdint>
#include <string>
#include <unordered_set>
#include <algorithm>
#include <cctype>
#include <interface.h>
#include <filesystem.h>
#include <eiface.h>
class GModDataPack;
namespace Bootil
{
class Buffer
{
public:
virtual ~Buffer() = default; // For the VTable
void *data;
uint32_t size;
uint32_t pos;
uint32_t written;
};
class AutoBuffer : public Buffer
{
public:
virtual ~AutoBuffer() = default; // For the VTable
};
}
class LuaFile // 116 bytes
{
public:
virtual ~LuaFile() = default; // For the VTable
std::string path;
std::string parent;
std::string content;
Bootil::AutoBuffer buffer;
bool unknown1;
bool unknown2;
};
namespace luapack
{
static IFileSystem *filesystem = nullptr;
static std::unordered_set<std::string> whitelist_extensions = { "lua", "txt", "dat" };
static std::unordered_set<std::string> whitelist_pathid = { "lsv", "lua", "data" };
class GModDataPackProxy : public Detouring::ClassProxy<GModDataPack, GModDataPackProxy>
{
private:
static FunctionPointers::GModDataPack_AddOrUpdateFile_t AddOrUpdateFile_original;
static const char hook_name[];
static GarrysMod::Lua::ILuaBase *lua;
public:
static void Initialize( GarrysMod::Lua::ILuaBase *LUA )
{
lua = LUA;
AddOrUpdateFile_original = FunctionPointers::GModDataPack_AddOrUpdateFile( );
if( AddOrUpdateFile_original == nullptr )
LUA->ThrowError( "failed to find GModDataPack::AddOrUpdateFile" );
if( !Hook( AddOrUpdateFile_original, &GModDataPackProxy::AddOrUpdateFile ) )
LUA->ThrowError( "failed to hook GModDataPack::AddOrUpdateFile" );
}
static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA )
{
UnHook( AddOrUpdateFile_original );
}
void AddOrUpdateFile( LuaFile *file, bool reload )
{
LuaHelpers::PushHookRun( lua, hook_name );
lua->PushString( file->path.c_str( ) );
lua->PushBool( reload );
bool shouldcall = true;
if( LuaHelpers::CallHookRun( lua, 2, 1 ) )
shouldcall = !lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) || lua->GetBool( -1 );
lua->Pop( 1 );
if( shouldcall )
return Call( AddOrUpdateFile_original, file, reload );
}
static GModDataPackProxy Singleton;
};
FunctionPointers::GModDataPack_AddOrUpdateFile_t GModDataPackProxy::AddOrUpdateFile_original = nullptr;
const char GModDataPackProxy::hook_name[] = "AddOrUpdateCSLuaFile";
GarrysMod::Lua::ILuaBase *GModDataPackProxy::lua = nullptr;
static bool IsPathAllowed( std::string &filename )
{
if( !V_RemoveDotSlashes( &filename[0], CORRECT_PATH_SEPARATOR, true ) )
return false;
filename.resize( std::strlen( filename.c_str( ) ) );
const char *extension = V_GetFileExtension( filename.c_str( ) );
if( extension == nullptr )
return false;
std::string ext = extension;
std::transform( ext.begin( ), ext.end( ), ext.begin( ), [] ( uint8_t c )
{
return static_cast<char>( std::tolower( c ) );
} );
return whitelist_extensions.find( ext ) != whitelist_extensions.end( );
}
inline bool IsPathIDAllowed( std::string &pathid )
{
std::transform( pathid.begin( ), pathid.end( ), pathid.begin( ), [] ( uint8_t c )
{
return static_cast<char>( std::tolower( c ) );
} );
return whitelist_pathid.find( pathid ) != whitelist_pathid.end( );
}
LUA_FUNCTION_STATIC( Rename )
{
LUA->CheckType( 1, GarrysMod::Lua::Type::STRING );
LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );
LUA->CheckType( 3, GarrysMod::Lua::Type::STRING );
std::string fname = LUA->GetString( 1 ), fnew = LUA->GetString( 2 ), pathid = LUA->GetString( 3 );
if( !IsPathAllowed( fname ) || !IsPathAllowed( fnew ) || !IsPathIDAllowed( pathid ) )
{
LUA->PushBool( false );
return 1;
}
LUA->PushBool( filesystem->RenameFile( fname.c_str( ), fnew.c_str( ), pathid.c_str( ) ) );
return 1;
}
static void Initialize( GarrysMod::Lua::ILuaBase *LUA )
{
filesystem = InterfacePointers::FileSystem( );
if( filesystem == nullptr )
LUA->ThrowError( "failed to initialize IFileSystem" );
GModDataPackProxy::Singleton.Initialize( LUA );
LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" );
if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
{
GModDataPackProxy::Singleton.Deinitialize(LUA);
LUA->ThrowError("luapack table not found");
}
LUA->PushCFunction( Rename );
LUA->SetField( -2, "Rename" );
LUA->Pop( 1 );
}
static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA )
{
LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" );
if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
LUA->ThrowError( "luapack table not found" );
LUA->PushNil( );
LUA->SetField( -2, "Rename" );
LUA->Pop( 1 );
GModDataPackProxy::Singleton.Deinitialize( LUA );
}
}
GMOD_MODULE_OPEN( )
{
luapack::Initialize( LUA );
return 0;
}
GMOD_MODULE_CLOSE( )
{
luapack::Deinitialize( LUA );
return 0;
}
<|endoftext|> |
<commit_before>#include "qmljstypedescriptionreader.h"
#include "parser/qmljsparser_p.h"
#include "parser/qmljslexer_p.h"
#include "parser/qmljsengine_p.h"
#include "parser/qmljsnodepool_p.h"
#include "parser/qmljsast_p.h"
#include "parser/qmljsastvisitor_p.h"
#include "qmljsbind.h"
#include <QtCore/QIODevice>
#include <QtCore/QBuffer>
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace LanguageUtils;
TypeDescriptionReader::TypeDescriptionReader(const QString &data)
: _source(data)
, _objects(0)
{
}
TypeDescriptionReader::~TypeDescriptionReader()
{
}
bool TypeDescriptionReader::operator()(QHash<QString, FakeMetaObject::Ptr> *objects)
{
QString fileName("typeDescription");
Engine engine;
NodePool pool(fileName, &engine);
Lexer lexer(&engine);
Parser parser(&engine);
lexer.setCode(_source, /*line = */ 1);
if (!parser.parse()) {
_errorMessage = QString("%1:%2: %3").arg(
QString::number(parser.errorLineNumber()),
QString::number(parser.errorColumnNumber()),
parser.errorMessage());
return false;
}
_objects = objects;
readDocument(parser.ast());
return _errorMessage.isEmpty();
}
QString TypeDescriptionReader::errorMessage() const
{
return _errorMessage;
}
void TypeDescriptionReader::readDocument(UiProgram *ast)
{
if (!ast) {
addError(SourceLocation(), "Could not parse document");
return;
}
if (!ast->imports || ast->imports->next) {
addError(SourceLocation(), "Expected a single import");
return;
}
UiImport *import = ast->imports->import;
if (Bind::toString(import->importUri) != QLatin1String("QtQuick.tooling")) {
addError(import->importToken, "Expected import of QtQuick.tooling");
return;
}
ComponentVersion version;
const QString versionString = _source.mid(import->versionToken.offset, import->versionToken.length);
const int dotIdx = versionString.indexOf(QLatin1Char('.'));
if (dotIdx != -1) {
version = ComponentVersion(versionString.left(dotIdx).toInt(),
versionString.mid(dotIdx + 1).toInt());
}
if (version != ComponentVersion(1, 0)) {
addError(import->versionToken, "Expected version 1.0");
return;
}
if (!ast->members || !ast->members->member || ast->members->next) {
addError(SourceLocation(), "Expected document to contain a single object definition");
return;
}
UiObjectDefinition *module = dynamic_cast<UiObjectDefinition *>(ast->members->member);
if (!module) {
addError(SourceLocation(), "Expected document to contain a single object definition");
return;
}
if (Bind::toString(module->qualifiedTypeNameId) != "Module") {
addError(SourceLocation(), "Expected document to contain a Module {} member");
return;
}
readModule(module);
}
void TypeDescriptionReader::readModule(UiObjectDefinition *ast)
{
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member);
if (!component || Bind::toString(component->qualifiedTypeNameId) != "Component") {
addError(member->firstSourceLocation(), "Expected only 'Component' object definitions");
return;
}
readComponent(component);
}
}
void TypeDescriptionReader::addError(const SourceLocation &loc, const QString &message)
{
_errorMessage += QString("%1:%2: %3\n").arg(
QString::number(loc.startLine),
QString::number(loc.startColumn),
message);
}
void TypeDescriptionReader::readComponent(UiObjectDefinition *ast)
{
FakeMetaObject::Ptr fmo(new FakeMetaObject);
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member);
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) {
QString name = Bind::toString(component->qualifiedTypeNameId);
if (name == "Property") {
readProperty(component, fmo);
} else if (name == "Method" || name == "Signal") {
readSignalOrMethod(component, name == "Method", fmo);
} else if (name == "Enum") {
readEnum(component, fmo);
} else {
addError(component->firstSourceLocation(), "Expected only Property, Method, Signal and Enum object definitions");
return;
}
} else if (script) {
QString name = Bind::toString(script->qualifiedId);
if (name == "name") {
fmo->setClassName(readStringBinding(script));
} else if (name == "prototype") {
fmo->setSuperclassName(readStringBinding(script));
} else if (name == "defaultProperty") {
fmo->setDefaultPropertyName(readStringBinding(script));
} else if (name == "exports") {
readExports(script, fmo);
} else {
addError(script->firstSourceLocation(), "Expected only name, prototype, defaultProperty and exports script bindings");
return;
}
} else {
addError(member->firstSourceLocation(), "Expected only script bindings and object definitions");
return;
}
}
if (fmo->className().isEmpty()) {
addError(ast->firstSourceLocation(), "Component definition is missing a name binding");
return;
}
_objects->insert(fmo->className(), fmo);
}
void TypeDescriptionReader::readSignalOrMethod(UiObjectDefinition *ast, bool isMethod, FakeMetaObject::Ptr fmo)
{
FakeMetaMethod fmm;
// ### confusion between Method and Slot. Method should be removed.
if (isMethod)
fmm.setMethodType(FakeMetaMethod::Slot);
else
fmm.setMethodType(FakeMetaMethod::Signal);
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member);
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) {
QString name = Bind::toString(component->qualifiedTypeNameId);
if (name == "Parameter") {
readParameter(component, &fmm);
} else {
addError(component->firstSourceLocation(), "Expected only Parameter object definitions");
return;
}
} else if (script) {
QString name = Bind::toString(script->qualifiedId);
if (name == "name") {
fmm.setMethodName(readStringBinding(script));
} else if (name == "type") {
fmm.setReturnType(readStringBinding(script));
} else {
addError(script->firstSourceLocation(), "Expected only name and type script bindings");
return;
}
} else {
addError(member->firstSourceLocation(), "Expected only script bindings and object definitions");
return;
}
}
if (fmm.methodName().isEmpty()) {
addError(ast->firstSourceLocation(), "Method or Signal is missing a name script binding");
return;
}
fmo->addMethod(fmm);
}
void TypeDescriptionReader::readProperty(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo)
{
QString name;
QString type;
bool isPointer = false;
bool isReadonly = false;
bool isList = false;
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
addError(member->firstSourceLocation(), "Expected script binding");
return;
}
QString id = Bind::toString(script->qualifiedId);
if (id == "name") {
name = readStringBinding(script);
} else if (id == "type") {
type = readStringBinding(script);
} else if (id == "isPointer") {
isPointer = readBoolBinding(script);
} else if (id == "isReadonly") {
isReadonly = readBoolBinding(script);
} else if (id == "isList") {
isList = readBoolBinding(script);
} else {
addError(script->firstSourceLocation(), "Expected only type, name, isPointer, isReadonly and isList script bindings");
return;
}
}
if (name.isEmpty() || type.isEmpty()) {
addError(ast->firstSourceLocation(), "Property object is missing a name or type script binding");
return;
}
fmo->addProperty(FakeMetaProperty(name, type, isList, !isReadonly, isPointer));
}
void TypeDescriptionReader::readEnum(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo)
{
FakeMetaEnum fme;
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
addError(member->firstSourceLocation(), "Expected script binding");
return;
}
QString name = Bind::toString(script->qualifiedId);
if (name == "name") {
fme.setName(readStringBinding(script));
} else if (name == "values") {
readEnumValues(script, &fme);
} else {
addError(script->firstSourceLocation(), "Expected only name and values script bindings");
return;
}
}
fmo->addEnum(fme);
}
void TypeDescriptionReader::readParameter(UiObjectDefinition *ast, FakeMetaMethod *fmm)
{
QString name;
QString type;
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
addError(member->firstSourceLocation(), "Expected script binding");
return;
}
QString id = Bind::toString(script->qualifiedId);
if (id == "name") {
id = readStringBinding(script);
} else if (id == "type") {
type = readStringBinding(script);
} else if (id == "isPointer") {
// ### unhandled
} else if (id == "isReadonly") {
// ### unhandled
} else if (id == "isList") {
// ### unhandled
} else {
addError(script->firstSourceLocation(), "Expected only name and type script bindings");
return;
}
}
fmm->addParameter(name, type);
}
QString TypeDescriptionReader::readStringBinding(UiScriptBinding *ast)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected string after colon");
return QString();
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected string after colon");
return QString();
}
StringLiteral *stringLit = dynamic_cast<StringLiteral *>(expStmt->expression);
if (!stringLit) {
addError(expStmt->firstSourceLocation(), "Expected string after colon");
return QString();
}
return stringLit->value->asString();
}
bool TypeDescriptionReader::readBoolBinding(AST::UiScriptBinding *ast)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected boolean after colon");
return false;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected boolean after colon");
return false;
}
TrueLiteral *trueLit = dynamic_cast<TrueLiteral *>(expStmt->expression);
FalseLiteral *falseLit = dynamic_cast<FalseLiteral *>(expStmt->expression);
if (!trueLit && !falseLit) {
addError(expStmt->firstSourceLocation(), "Expected true or false after colon");
return false;
}
return trueLit;
}
void TypeDescriptionReader::readExports(UiScriptBinding *ast, FakeMetaObject::Ptr fmo)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected array of strings after colon");
return;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected array of strings after colon");
return;
}
ArrayLiteral *arrayLit = dynamic_cast<ArrayLiteral *>(expStmt->expression);
if (!arrayLit) {
addError(expStmt->firstSourceLocation(), "Expected array of strings after colon");
return;
}
for (ElementList *it = arrayLit->elements; it; it = it->next) {
StringLiteral *stringLit = dynamic_cast<StringLiteral *>(it->expression);
if (!stringLit) {
addError(arrayLit->firstSourceLocation(), "Expected array literal with only string literal members");
return;
}
QString exp = stringLit->value->asString();
int slashIdx = exp.indexOf(QLatin1Char('/'));
int spaceIdx = exp.indexOf(QLatin1Char(' '));
ComponentVersion version(exp.mid(spaceIdx + 1));
if (spaceIdx == -1 || !version.isValid()) {
addError(stringLit->firstSourceLocation(), "Expected string literal to contain 'Package/Name major.minor' or 'Name major.minor'");
continue;
}
QString package;
if (slashIdx != -1)
package = exp.left(slashIdx);
QString name = exp.mid(slashIdx + 1, spaceIdx - (slashIdx+1));
// ### relocatable exports where package is empty?
fmo->addExport(name, package, version);
}
}
void TypeDescriptionReader::readEnumValues(AST::UiScriptBinding *ast, LanguageUtils::FakeMetaEnum *fme)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected object literal after colon");
return;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected object literal after colon");
return;
}
ObjectLiteral *objectLit = dynamic_cast<ObjectLiteral *>(expStmt->expression);
if (!objectLit) {
addError(expStmt->firstSourceLocation(), "Expected object literal after colon");
return;
}
for (PropertyNameAndValueList *it = objectLit->properties; it; it = it->next) {
StringLiteralPropertyName *propName = dynamic_cast<StringLiteralPropertyName *>(it->name);
NumericLiteral *value = dynamic_cast<NumericLiteral *>(it->value);
UnaryMinusExpression *minus = dynamic_cast<UnaryMinusExpression *>(it->value);
if (minus)
value = dynamic_cast<NumericLiteral *>(minus->expression);
if (!propName || !value) {
addError(objectLit->firstSourceLocation(), "Expected object literal to contain only 'string: number' elements");
continue;
}
double v = value->value;
if (minus)
v = -v;
fme->addKey(propName->id->asString(), v);
}
}
<commit_msg>QmlJS: Fix qml type info by reintroducing workaround exports.<commit_after>#include "qmljstypedescriptionreader.h"
#include "parser/qmljsparser_p.h"
#include "parser/qmljslexer_p.h"
#include "parser/qmljsengine_p.h"
#include "parser/qmljsnodepool_p.h"
#include "parser/qmljsast_p.h"
#include "parser/qmljsastvisitor_p.h"
#include "qmljsbind.h"
#include <QtCore/QIODevice>
#include <QtCore/QBuffer>
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace LanguageUtils;
TypeDescriptionReader::TypeDescriptionReader(const QString &data)
: _source(data)
, _objects(0)
{
}
TypeDescriptionReader::~TypeDescriptionReader()
{
}
bool TypeDescriptionReader::operator()(QHash<QString, FakeMetaObject::Ptr> *objects)
{
QString fileName("typeDescription");
Engine engine;
NodePool pool(fileName, &engine);
Lexer lexer(&engine);
Parser parser(&engine);
lexer.setCode(_source, /*line = */ 1);
if (!parser.parse()) {
_errorMessage = QString("%1:%2: %3").arg(
QString::number(parser.errorLineNumber()),
QString::number(parser.errorColumnNumber()),
parser.errorMessage());
return false;
}
_objects = objects;
readDocument(parser.ast());
return _errorMessage.isEmpty();
}
QString TypeDescriptionReader::errorMessage() const
{
return _errorMessage;
}
void TypeDescriptionReader::readDocument(UiProgram *ast)
{
if (!ast) {
addError(SourceLocation(), "Could not parse document");
return;
}
if (!ast->imports || ast->imports->next) {
addError(SourceLocation(), "Expected a single import");
return;
}
UiImport *import = ast->imports->import;
if (Bind::toString(import->importUri) != QLatin1String("QtQuick.tooling")) {
addError(import->importToken, "Expected import of QtQuick.tooling");
return;
}
ComponentVersion version;
const QString versionString = _source.mid(import->versionToken.offset, import->versionToken.length);
const int dotIdx = versionString.indexOf(QLatin1Char('.'));
if (dotIdx != -1) {
version = ComponentVersion(versionString.left(dotIdx).toInt(),
versionString.mid(dotIdx + 1).toInt());
}
if (version != ComponentVersion(1, 0)) {
addError(import->versionToken, "Expected version 1.0");
return;
}
if (!ast->members || !ast->members->member || ast->members->next) {
addError(SourceLocation(), "Expected document to contain a single object definition");
return;
}
UiObjectDefinition *module = dynamic_cast<UiObjectDefinition *>(ast->members->member);
if (!module) {
addError(SourceLocation(), "Expected document to contain a single object definition");
return;
}
if (Bind::toString(module->qualifiedTypeNameId) != "Module") {
addError(SourceLocation(), "Expected document to contain a Module {} member");
return;
}
readModule(module);
}
void TypeDescriptionReader::readModule(UiObjectDefinition *ast)
{
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member);
if (!component || Bind::toString(component->qualifiedTypeNameId) != "Component") {
addError(member->firstSourceLocation(), "Expected only 'Component' object definitions");
return;
}
readComponent(component);
}
}
void TypeDescriptionReader::addError(const SourceLocation &loc, const QString &message)
{
_errorMessage += QString("%1:%2: %3\n").arg(
QString::number(loc.startLine),
QString::number(loc.startColumn),
message);
}
void TypeDescriptionReader::readComponent(UiObjectDefinition *ast)
{
FakeMetaObject::Ptr fmo(new FakeMetaObject);
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member);
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) {
QString name = Bind::toString(component->qualifiedTypeNameId);
if (name == "Property") {
readProperty(component, fmo);
} else if (name == "Method" || name == "Signal") {
readSignalOrMethod(component, name == "Method", fmo);
} else if (name == "Enum") {
readEnum(component, fmo);
} else {
addError(component->firstSourceLocation(), "Expected only Property, Method, Signal and Enum object definitions");
return;
}
} else if (script) {
QString name = Bind::toString(script->qualifiedId);
if (name == "name") {
fmo->setClassName(readStringBinding(script));
} else if (name == "prototype") {
fmo->setSuperclassName(readStringBinding(script));
} else if (name == "defaultProperty") {
fmo->setDefaultPropertyName(readStringBinding(script));
} else if (name == "exports") {
readExports(script, fmo);
} else {
addError(script->firstSourceLocation(), "Expected only name, prototype, defaultProperty and exports script bindings");
return;
}
} else {
addError(member->firstSourceLocation(), "Expected only script bindings and object definitions");
return;
}
}
if (fmo->className().isEmpty()) {
addError(ast->firstSourceLocation(), "Component definition is missing a name binding");
return;
}
// ### for backwards compatibility until fixed: export by cpp name
fmo->addExport(fmo->className(), "", ComponentVersion());
_objects->insert(fmo->className(), fmo);
}
void TypeDescriptionReader::readSignalOrMethod(UiObjectDefinition *ast, bool isMethod, FakeMetaObject::Ptr fmo)
{
FakeMetaMethod fmm;
// ### confusion between Method and Slot. Method should be removed.
if (isMethod)
fmm.setMethodType(FakeMetaMethod::Slot);
else
fmm.setMethodType(FakeMetaMethod::Signal);
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member);
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) {
QString name = Bind::toString(component->qualifiedTypeNameId);
if (name == "Parameter") {
readParameter(component, &fmm);
} else {
addError(component->firstSourceLocation(), "Expected only Parameter object definitions");
return;
}
} else if (script) {
QString name = Bind::toString(script->qualifiedId);
if (name == "name") {
fmm.setMethodName(readStringBinding(script));
} else if (name == "type") {
fmm.setReturnType(readStringBinding(script));
} else {
addError(script->firstSourceLocation(), "Expected only name and type script bindings");
return;
}
} else {
addError(member->firstSourceLocation(), "Expected only script bindings and object definitions");
return;
}
}
if (fmm.methodName().isEmpty()) {
addError(ast->firstSourceLocation(), "Method or Signal is missing a name script binding");
return;
}
fmo->addMethod(fmm);
}
void TypeDescriptionReader::readProperty(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo)
{
QString name;
QString type;
bool isPointer = false;
bool isReadonly = false;
bool isList = false;
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
addError(member->firstSourceLocation(), "Expected script binding");
return;
}
QString id = Bind::toString(script->qualifiedId);
if (id == "name") {
name = readStringBinding(script);
} else if (id == "type") {
type = readStringBinding(script);
} else if (id == "isPointer") {
isPointer = readBoolBinding(script);
} else if (id == "isReadonly") {
isReadonly = readBoolBinding(script);
} else if (id == "isList") {
isList = readBoolBinding(script);
} else {
addError(script->firstSourceLocation(), "Expected only type, name, isPointer, isReadonly and isList script bindings");
return;
}
}
if (name.isEmpty() || type.isEmpty()) {
addError(ast->firstSourceLocation(), "Property object is missing a name or type script binding");
return;
}
fmo->addProperty(FakeMetaProperty(name, type, isList, !isReadonly, isPointer));
}
void TypeDescriptionReader::readEnum(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo)
{
FakeMetaEnum fme;
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
addError(member->firstSourceLocation(), "Expected script binding");
return;
}
QString name = Bind::toString(script->qualifiedId);
if (name == "name") {
fme.setName(readStringBinding(script));
} else if (name == "values") {
readEnumValues(script, &fme);
} else {
addError(script->firstSourceLocation(), "Expected only name and values script bindings");
return;
}
}
fmo->addEnum(fme);
}
void TypeDescriptionReader::readParameter(UiObjectDefinition *ast, FakeMetaMethod *fmm)
{
QString name;
QString type;
for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) {
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
addError(member->firstSourceLocation(), "Expected script binding");
return;
}
QString id = Bind::toString(script->qualifiedId);
if (id == "name") {
id = readStringBinding(script);
} else if (id == "type") {
type = readStringBinding(script);
} else if (id == "isPointer") {
// ### unhandled
} else if (id == "isReadonly") {
// ### unhandled
} else if (id == "isList") {
// ### unhandled
} else {
addError(script->firstSourceLocation(), "Expected only name and type script bindings");
return;
}
}
fmm->addParameter(name, type);
}
QString TypeDescriptionReader::readStringBinding(UiScriptBinding *ast)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected string after colon");
return QString();
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected string after colon");
return QString();
}
StringLiteral *stringLit = dynamic_cast<StringLiteral *>(expStmt->expression);
if (!stringLit) {
addError(expStmt->firstSourceLocation(), "Expected string after colon");
return QString();
}
return stringLit->value->asString();
}
bool TypeDescriptionReader::readBoolBinding(AST::UiScriptBinding *ast)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected boolean after colon");
return false;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected boolean after colon");
return false;
}
TrueLiteral *trueLit = dynamic_cast<TrueLiteral *>(expStmt->expression);
FalseLiteral *falseLit = dynamic_cast<FalseLiteral *>(expStmt->expression);
if (!trueLit && !falseLit) {
addError(expStmt->firstSourceLocation(), "Expected true or false after colon");
return false;
}
return trueLit;
}
void TypeDescriptionReader::readExports(UiScriptBinding *ast, FakeMetaObject::Ptr fmo)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected array of strings after colon");
return;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected array of strings after colon");
return;
}
ArrayLiteral *arrayLit = dynamic_cast<ArrayLiteral *>(expStmt->expression);
if (!arrayLit) {
addError(expStmt->firstSourceLocation(), "Expected array of strings after colon");
return;
}
for (ElementList *it = arrayLit->elements; it; it = it->next) {
StringLiteral *stringLit = dynamic_cast<StringLiteral *>(it->expression);
if (!stringLit) {
addError(arrayLit->firstSourceLocation(), "Expected array literal with only string literal members");
return;
}
QString exp = stringLit->value->asString();
int slashIdx = exp.indexOf(QLatin1Char('/'));
int spaceIdx = exp.indexOf(QLatin1Char(' '));
ComponentVersion version(exp.mid(spaceIdx + 1));
if (spaceIdx == -1 || !version.isValid()) {
addError(stringLit->firstSourceLocation(), "Expected string literal to contain 'Package/Name major.minor' or 'Name major.minor'");
continue;
}
QString package;
if (slashIdx != -1)
package = exp.left(slashIdx);
QString name = exp.mid(slashIdx + 1, spaceIdx - (slashIdx+1));
// ### relocatable exports where package is empty?
fmo->addExport(name, package, version);
}
}
void TypeDescriptionReader::readEnumValues(AST::UiScriptBinding *ast, LanguageUtils::FakeMetaEnum *fme)
{
if (!ast || !ast->statement) {
addError(ast->colonToken, "Expected object literal after colon");
return;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
addError(ast->statement->firstSourceLocation(), "Expected object literal after colon");
return;
}
ObjectLiteral *objectLit = dynamic_cast<ObjectLiteral *>(expStmt->expression);
if (!objectLit) {
addError(expStmt->firstSourceLocation(), "Expected object literal after colon");
return;
}
for (PropertyNameAndValueList *it = objectLit->properties; it; it = it->next) {
StringLiteralPropertyName *propName = dynamic_cast<StringLiteralPropertyName *>(it->name);
NumericLiteral *value = dynamic_cast<NumericLiteral *>(it->value);
UnaryMinusExpression *minus = dynamic_cast<UnaryMinusExpression *>(it->value);
if (minus)
value = dynamic_cast<NumericLiteral *>(minus->expression);
if (!propName || !value) {
addError(objectLit->firstSourceLocation(), "Expected object literal to contain only 'string: number' elements");
continue;
}
double v = value->value;
if (minus)
v = -v;
fme->addKey(propName->id->asString(), v);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include "pixelboost/data/xml/xml.h"
#include "pixelboost/file/fileHelpers.h"
enum ShaderLanguage
{
kShaderLanguageGLSL,
kShaderLanguageHLSL,
};
enum ShaderType
{
kShaderTypeVertex,
kShaderTypeFragment,
};
bool ParseShaderGLSL(const std::string& input, pugi::xml_node& output)
{
output.append_child(pugi::node_cdata).set_value(input.c_str());
return true;
}
bool ParseShaderHLSL(const std::string& input, pugi::xml_node& output)
{
output.append_child(pugi::node_cdata).set_value(input.c_str());
return true;
}
bool AppendProgram(pugi::xml_node& programOutput, pugi::xml_node& programInput)
{
std::string language = programInput.attribute("language").value();
if (language == "glsl")
{
if (!ParseShaderGLSL(programInput.child_value(), programOutput))
return false;
} else if (language == "hlsl")
{
if (!ParseShaderHLSL(programInput.child_value(), programOutput))
return false;
} else {
// Unknown language
return false;
}
return true;
}
int main(int argc, const char * argv[])
{
bool status = true;
if (argc < 3)
return 1;
new pb::FileSystem(argv[0]);
pb::FileSystem::Instance()->MountReadLocation(argv[1], "/", true);
pb::FileSystem::Instance()->OverrideWriteDirectory(argv[1]);
std::string vertex, fragment;
const char* inputLocation = argv[2];
const char* outputLocation = argv[3];
pb::File* file = pb::FileSystem::Instance()->OpenFile(inputLocation);
std::string input;
if (file)
{
file->ReadAll(input);
delete file;
}
pugi::xml_document inputDocument;
pugi::xml_document outputDocument;
inputDocument.load(input.c_str());
pugi::xml_node shaderInput = inputDocument.child("shader");
pugi::xml_node shaderOutput = outputDocument.append_child("shader");
shaderOutput.append_copy(shaderInput.attribute("name"));
pugi::xml_node attributesInput = shaderInput.child("attributes");
shaderOutput.append_copy(attributesInput);
pugi::xml_node subshaderInput = shaderInput.child("subshader");
while (!subshaderInput.empty())
{
pugi::xml_node subshaderOutput = shaderOutput.append_child("subshader");
subshaderOutput.append_copy(subshaderInput.attribute("class"));
pugi::xml_node passInput = subshaderInput.child("pass");
while (!passInput.empty())
{
pugi::xml_node passOutput = subshaderOutput.append_child("pass");
pugi::xml_node programInput = passInput.child("program");
while (!programInput.empty())
{
pugi::xml_node programOutput = passOutput.append_child("program");
programOutput.append_copy(programInput.attribute("language"));
status &= AppendProgram(programOutput, programInput);
programInput = passInput.next_sibling("program");
}
passInput = passInput.next_sibling("pass");
}
subshaderInput = subshaderInput.next_sibling("subshader");
}
std::ostringstream output;
outputDocument.save(output);
file = pb::FileSystem::Instance()->OpenFile(outputLocation, pb::kFileModeWrite);
if (file)
{
file->Write(output.str());
delete file;
} else {
status = false;
}
if (!status)
return 1;
return 0;
}
<commit_msg>Update to use new pugixml<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include "pixelboost/data/xml/pugixml.hpp"
#include "pixelboost/file/fileHelpers.h"
enum ShaderLanguage
{
kShaderLanguageGLSL,
kShaderLanguageHLSL,
};
enum ShaderType
{
kShaderTypeVertex,
kShaderTypeFragment,
};
bool ParseShaderGLSL(const std::string& input, pugi::xml_node& output)
{
output.append_child(pugi::node_cdata).set_value(input.c_str());
return true;
}
bool ParseShaderHLSL(const std::string& input, pugi::xml_node& output)
{
output.append_child(pugi::node_cdata).set_value(input.c_str());
return true;
}
bool AppendProgram(pugi::xml_node& programOutput, pugi::xml_node& programInput)
{
std::string language = programInput.attribute("language").value();
if (language == "glsl")
{
if (!ParseShaderGLSL(programInput.child_value(), programOutput))
return false;
} else if (language == "hlsl")
{
if (!ParseShaderHLSL(programInput.child_value(), programOutput))
return false;
} else {
// Unknown language
return false;
}
return true;
}
int main(int argc, const char * argv[])
{
bool status = true;
if (argc < 3)
return 1;
new pb::FileSystem(argv[0]);
pb::FileSystem::Instance()->MountReadLocation(argv[1], "/", true);
pb::FileSystem::Instance()->OverrideWriteDirectory(argv[1]);
std::string vertex, fragment;
const char* inputLocation = argv[2];
const char* outputLocation = argv[3];
pb::File* file = pb::FileSystem::Instance()->OpenFile(inputLocation);
std::string input;
if (file)
{
file->ReadAll(input);
delete file;
}
pugi::xml_document inputDocument;
pugi::xml_document outputDocument;
inputDocument.load(input.c_str());
pugi::xml_node shaderInput = inputDocument.child("shader");
pugi::xml_node shaderOutput = outputDocument.append_child("shader");
shaderOutput.append_copy(shaderInput.attribute("name"));
pugi::xml_node attributesInput = shaderInput.child("attributes");
shaderOutput.append_copy(attributesInput);
pugi::xml_node subshaderInput = shaderInput.child("subshader");
while (!subshaderInput.empty())
{
pugi::xml_node subshaderOutput = shaderOutput.append_child("subshader");
subshaderOutput.append_copy(subshaderInput.attribute("class"));
pugi::xml_node passInput = subshaderInput.child("pass");
while (!passInput.empty())
{
pugi::xml_node passOutput = subshaderOutput.append_child("pass");
pugi::xml_node programInput = passInput.child("program");
while (!programInput.empty())
{
pugi::xml_node programOutput = passOutput.append_child("program");
programOutput.append_copy(programInput.attribute("language"));
status &= AppendProgram(programOutput, programInput);
programInput = passInput.next_sibling("program");
}
passInput = passInput.next_sibling("pass");
}
subshaderInput = subshaderInput.next_sibling("subshader");
}
std::ostringstream output;
outputDocument.save(output);
file = pb::FileSystem::Instance()->OpenFile(outputLocation, pb::kFileModeWrite);
if (file)
{
file->Write(output.str());
delete file;
} else {
status = false;
}
if (!status)
return 1;
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "moltengamepad.h"
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <csignal>
int parse_opts(moltengamepad::mg_options &options,int argc, char* argv[]);
volatile bool STOP_WORKING = true;
volatile bool QUIT_APPLICATION = false;
moltengamepad* app;
void signal_handler(int signum) {
if (!STOP_WORKING) {
//A long running action is to be interrupted.
STOP_WORKING = true;
return;
}
//Otherwise, we want to interrupt everything! (And let them shut down appropriately)
QUIT_APPLICATION = true;
delete app;
exit(0);
return;
}
int main(int argc, char* argv[]) {
STOP_WORKING = true;
QUIT_APPLICATION = false;
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
//signal(SIGHUP, signal_handler);
moltengamepad::mg_options options;
options.look_for_devices = true;
options.listen_for_devices = true;
options.make_keyboard = true;
options.make_mouse = false;
options.make_pointer = false;
options.dpad_as_hat = false;
options.mimic_xpad = false;
options.num_gamepads = 4;
options.config_dir = "";
options.profile_dir = "";
options.gendev_dir = "";
options.fifo_path = "";
options.uinput_path = "";
int ret = parse_opts(options,argc,argv);
if (ret > 0) return 0;
if (ret < 0) return ret;
try {
moltengamepad* mg = new moltengamepad(options);
app = mg;
mg->init();
shell_loop(mg, std::cin);
delete mg;
} catch (int e) {
return e;
}
return 0;
}
int print_version() {
std::cout << "MoltenGamepad version " << VERSION_STRING << "\n";
return 0;
}
int print_usage(char* execname) {
print_version();
std::cout << "USAGE:\n";
std::cout << "\t" << execname << " [OPTIONS]\n";
std::cout << "\n";
std::string help_text = ""\
"--help -h\n"\
"\tShow this message\n"\
"\n"\
"--version -v\n"\
"\tDisplay the version string\n"\
"\n"\
"--uinput-path -u\n"\
"\tSet where the uinput node is found on the system\n"\
"\n"\
"--fifo-path -f\n"\
"\tSet where the fifo command channel should be placed.\n"\
"\n"\
"--profiles-path -p\n"\
"\tSet where the profiles are located\n"\
"\n"\
"--gendev-path -g\n"\
"\tSet where the generic device descriptions are located\n"\
"\n"\
"--config-path -c\n"\
"\tSet where the general config files are located\n"\
"\n"\
"--num-gamepads -n\n"\
"\tSet how many virtual gamepads will be created\n"\
"\n"\
"--no-make-keys\n"\
"\tDisable the creation of a virtual keyboard\n"\
"\n"\
"--no-enumerate\n"\
"\tDisable the search for already connected devices\n"\
"\n"\
"--no-monitor\n"\
"\tDisable listening for future connected devices\n"\
"\n"\
"--dpad-as-hat\n"\
"\tOutput dpad events as a hat rather than separate buttons\n"\
"\n"\
"--mimic-xpad\n"\
"\tMake the virtual output devices appear as xpad-style XBox 360 devices\n"\
;
std::cout << help_text;
return 0;
}
int parse_opts(moltengamepad::mg_options &options, int argc, char* argv[]) {
char c = 0;
static struct option long_options[] = {
{"help", 0, 0, 'h'},
{"version", 0, 0, 'v'},
{"uinput-path", 1, 0, 'u'},
{"profiles-path", 1, 0, 'p'},
{"gendev-path", 1, 0, 'g'},
{"config-path", 1, 0, 'c'},
{"num-gamepads", 1, 0, 'n'},
{"make-fifo", 1, 0, 'm'},
{"fifo-path", 1, 0, 'f'},
{"no-make-keys", 0, 0, 0},
{"no-enumerate", 0, 0, 0},
{"no-monitor", 0, 0, 0},
{"dpad-as-hat", 0, 0, 0},
{"mimic-xpad", 0, 0, 0},
{0, 0, 0, 0},
};
int long_index;
while (c != -1) {
c = getopt_long(argc,argv,"u:p:g:n:c:f:mhv", long_options, &long_index);
switch (c) {
case 0:
if (long_index == 9) {options.make_keyboard = false;};
if (long_index == 10) {options.look_for_devices = false;};
if (long_index == 11) {options.listen_for_devices = false;};
if (long_index == 12) {options.dpad_as_hat = true;};
if (long_index == 13) {options.mimic_xpad = true;};
break;
case 'u':
options.uinput_path = std::string(optarg);
break;
case 'm':
options.make_fifo = true;
case 'f':
options.fifo_path = std::string(optarg);
break;
case 'p':
options.profile_dir = std::string(optarg);
break;
case 'g':
options.gendev_dir = std::string(optarg);
break;
case 'c':
options.config_dir = std::string(optarg);
break;
case 'h':
print_usage(argv[0]);
return 10;
break;
case 'v':
print_version();
return 10;
break;
case 'n':
try {
options.num_gamepads = std::stoi(optarg);
if (options.num_gamepads < 0 ) throw -3;
} catch (...) {
std::cerr << "could not parse numeric value for number of gamepads." << std::endl;
return -5;
}
break;
}
}
return 0;
}
<commit_msg>Fix bugs in fifo command line arguments<commit_after>#include <iostream>
#include "moltengamepad.h"
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <csignal>
int parse_opts(moltengamepad::mg_options &options,int argc, char* argv[]);
volatile bool STOP_WORKING = true;
volatile bool QUIT_APPLICATION = false;
moltengamepad* app;
void signal_handler(int signum) {
if (!STOP_WORKING) {
//A long running action is to be interrupted.
STOP_WORKING = true;
return;
}
//Otherwise, we want to interrupt everything! (And let them shut down appropriately)
QUIT_APPLICATION = true;
delete app;
exit(0);
return;
}
int main(int argc, char* argv[]) {
STOP_WORKING = true;
QUIT_APPLICATION = false;
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
//signal(SIGHUP, signal_handler);
moltengamepad::mg_options options;
options.look_for_devices = true;
options.listen_for_devices = true;
options.make_keyboard = true;
options.make_mouse = false;
options.make_pointer = false;
options.dpad_as_hat = false;
options.mimic_xpad = false;
options.num_gamepads = 4;
options.config_dir = "";
options.profile_dir = "";
options.gendev_dir = "";
options.fifo_path = "";
options.uinput_path = "";
int ret = parse_opts(options,argc,argv);
if (ret > 0) return 0;
if (ret < 0) return ret;
try {
moltengamepad* mg = new moltengamepad(options);
app = mg;
mg->init();
shell_loop(mg, std::cin);
delete mg;
} catch (int e) {
return e;
}
return 0;
}
int print_version() {
std::cout << "MoltenGamepad version " << VERSION_STRING << "\n";
return 0;
}
int print_usage(char* execname) {
print_version();
std::cout << "USAGE:\n";
std::cout << "\t" << execname << " [OPTIONS]\n";
std::cout << "\n";
std::string help_text = ""\
"--help -h\n"\
"\tShow this message\n"\
"\n"\
"--version -v\n"\
"\tDisplay the version string\n"\
"\n"\
"--uinput-path -u\n"\
"\tSet where the uinput node is found on the system\n"\
"\n"\
"--make-fifo -f\n"\
"\tCreate a fifo command channel, and exit if it can't be made.\n"\
"\n"\
"--fifo-path -f\n"\
"\tSet where the fifo command channel should be placed.\n"\
"\n"\
"--profiles-path -p\n"\
"\tSet where the profiles are located\n"\
"\n"\
"--gendev-path -g\n"\
"\tSet where the generic device descriptions are located\n"\
"\n"\
"--config-path -c\n"\
"\tSet where the general config files are located\n"\
"\n"\
"--num-gamepads -n\n"\
"\tSet how many virtual gamepads will be created\n"\
"\n"\
"--no-make-keys\n"\
"\tDisable the creation of a virtual keyboard\n"\
"\n"\
"--no-enumerate\n"\
"\tDisable the search for already connected devices\n"\
"\n"\
"--no-monitor\n"\
"\tDisable listening for future connected devices\n"\
"\n"\
"--dpad-as-hat\n"\
"\tOutput dpad events as a hat rather than separate buttons\n"\
"\n"\
"--mimic-xpad\n"\
"\tMake the virtual output devices appear as xpad-style XBox 360 devices\n"\
;
std::cout << help_text;
return 0;
}
int parse_opts(moltengamepad::mg_options &options, int argc, char* argv[]) {
char c = 0;
static struct option long_options[] = {
{"help", 0, 0, 'h'},
{"version", 0, 0, 'v'},
{"uinput-path", 1, 0, 'u'},
{"profiles-path", 1, 0, 'p'},
{"gendev-path", 1, 0, 'g'},
{"config-path", 1, 0, 'c'},
{"num-gamepads", 1, 0, 'n'},
{"make-fifo", 0, 0, 'm'},
{"fifo-path", 1, 0, 'f'},
{"no-make-keys", 0, 0, 0},
{"no-enumerate", 0, 0, 0},
{"no-monitor", 0, 0, 0},
{"dpad-as-hat", 0, 0, 0},
{"mimic-xpad", 0, 0, 0},
{0, 0, 0, 0},
};
int long_index;
while (c != -1) {
c = getopt_long(argc,argv,"u:p:g:n:c:f:mhv", long_options, &long_index);
switch (c) {
case 0:
if (long_index == 9) {options.make_keyboard = false;};
if (long_index == 10) {options.look_for_devices = false;};
if (long_index == 11) {options.listen_for_devices = false;};
if (long_index == 12) {options.dpad_as_hat = true;};
if (long_index == 13) {options.mimic_xpad = true;};
break;
case 'u':
options.uinput_path = std::string(optarg);
break;
case 'm':
options.make_fifo = true;
break;
case 'f':
options.fifo_path = std::string(optarg);
break;
case 'p':
options.profile_dir = std::string(optarg);
break;
case 'g':
options.gendev_dir = std::string(optarg);
break;
case 'c':
options.config_dir = std::string(optarg);
break;
case 'h':
print_usage(argv[0]);
return 10;
break;
case 'v':
print_version();
return 10;
break;
case 'n':
try {
options.num_gamepads = std::stoi(optarg);
if (options.num_gamepads < 0 ) throw -3;
} catch (...) {
std::cerr << "could not parse numeric value for number of gamepads." << std::endl;
return -5;
}
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017-2018 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 <chainparams.h>
#include <index/base.h>
#include <shutdown.h>
#include <tinyformat.h>
#include <ui_interface.h>
#include <util/system.h>
#include <validation.h>
#include <warnings.h>
constexpr char DB_BEST_BLOCK = 'B';
constexpr int64_t SYNC_LOG_INTERVAL = 30; // seconds
constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; // seconds
template<typename... Args>
static void FatalError(const char* fmt, const Args&... args)
{
std::string strMessage = tfm::format(fmt, args...);
SetMiscWarning(strMessage);
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
"Error: A fatal internal error occurred, see debug.log for details",
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
}
BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) :
CDBWrapper(path, n_cache_size, f_memory, f_wipe, f_obfuscate)
{}
bool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const
{
bool success = Read(DB_BEST_BLOCK, locator);
if (!success) {
locator.SetNull();
}
return success;
}
void BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator)
{
batch.Write(DB_BEST_BLOCK, locator);
}
BaseIndex::~BaseIndex()
{
Interrupt();
Stop();
}
bool BaseIndex::Init()
{
CBlockLocator locator;
if (!GetDB().ReadBestBlock(locator)) {
locator.SetNull();
}
LOCK(cs_main);
if (locator.IsNull()) {
m_best_block_index = nullptr;
} else {
m_best_block_index = FindForkInGlobalIndex(::ChainActive(), locator);
}
m_synced = m_best_block_index.load() == ::ChainActive().Tip();
return true;
}
static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
AssertLockHeld(cs_main);
if (!pindex_prev) {
return ::ChainActive().Genesis();
}
const CBlockIndex* pindex = ::ChainActive().Next(pindex_prev);
if (pindex) {
return pindex;
}
return ::ChainActive().Next(::ChainActive().FindFork(pindex_prev));
}
void BaseIndex::ThreadSync()
{
const CBlockIndex* pindex = m_best_block_index.load();
if (!m_synced) {
auto& consensus_params = Params().GetConsensus();
int64_t last_log_time = 0;
int64_t last_locator_write_time = 0;
while (true) {
if (m_interrupt) {
m_best_block_index = pindex;
// No need to handle errors in Commit. If it fails, the error will be already be
// logged. The best way to recover is to continue, as index cannot be corrupted by
// a missed commit to disk for an advanced index state.
Commit();
return;
}
{
LOCK(cs_main);
const CBlockIndex* pindex_next = NextSyncBlock(pindex);
if (!pindex_next) {
m_best_block_index = pindex;
m_synced = true;
// No need to handle errors in Commit. See rationale above.
Commit();
break;
}
if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) {
FatalError("%s: Failed to rewind index %s to a previous chain tip",
__func__, GetName());
return;
}
pindex = pindex_next;
}
int64_t current_time = GetTime();
if (last_log_time + SYNC_LOG_INTERVAL < current_time) {
LogPrintf("Syncing %s with block chain from height %d\n",
GetName(), pindex->nHeight);
last_log_time = current_time;
}
if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) {
m_best_block_index = pindex;
last_locator_write_time = current_time;
// No need to handle errors in Commit. See rationale above.
Commit();
}
CBlock block;
if (!ReadBlockFromDisk(block, pindex, consensus_params)) {
FatalError("%s: Failed to read block %s from disk",
__func__, pindex->GetBlockHash().ToString());
return;
}
if (!WriteBlock(block, pindex)) {
FatalError("%s: Failed to write block %s to index database",
__func__, pindex->GetBlockHash().ToString());
return;
}
}
}
if (pindex) {
LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight);
} else {
LogPrintf("%s is enabled\n", GetName());
}
}
bool BaseIndex::Commit()
{
CDBBatch batch(GetDB());
if (!CommitInternal(batch) || !GetDB().WriteBatch(batch)) {
return error("%s: Failed to commit latest %s state", __func__, GetName());
}
return true;
}
bool BaseIndex::CommitInternal(CDBBatch& batch)
{
LOCK(cs_main);
GetDB().WriteBestBlock(batch, ::ChainActive().GetLocator(m_best_block_index));
return true;
}
bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip)
{
assert(current_tip == m_best_block_index);
assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
// In the case of a reorg, ensure persisted block locator is not stale.
m_best_block_index = new_tip;
if (!Commit()) {
// If commit fails, revert the best block index to avoid corruption.
m_best_block_index = current_tip;
return false;
}
return true;
}
void BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex,
const std::vector<CTransactionRef>& txn_conflicted)
{
if (!m_synced) {
return;
}
const CBlockIndex* best_block_index = m_best_block_index.load();
if (!best_block_index) {
if (pindex->nHeight != 0) {
FatalError("%s: First block connected is not the genesis block (height=%d)",
__func__, pindex->nHeight);
return;
}
} else {
// Ensure block connects to an ancestor of the current best block. This should be the case
// most of the time, but may not be immediately after the sync thread catches up and sets
// m_synced. Consider the case where there is a reorg and the blocks on the stale branch are
// in the ValidationInterface queue backlog even after the sync thread has caught up to the
// new chain tip. In this unlikely event, log a warning and let the queue clear.
if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) {
LogPrintf("%s: WARNING: Block %s does not connect to an ancestor of " /* Continued */
"known best chain (tip=%s); not updating index\n",
__func__, pindex->GetBlockHash().ToString(),
best_block_index->GetBlockHash().ToString());
return;
}
if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) {
FatalError("%s: Failed to rewind index %s to a previous chain tip",
__func__, GetName());
return;
}
}
if (WriteBlock(*block, pindex)) {
m_best_block_index = pindex;
} else {
FatalError("%s: Failed to write block %s to index",
__func__, pindex->GetBlockHash().ToString());
return;
}
}
void BaseIndex::ChainStateFlushed(const CBlockLocator& locator)
{
if (!m_synced) {
return;
}
const uint256& locator_tip_hash = locator.vHave.front();
const CBlockIndex* locator_tip_index;
{
LOCK(cs_main);
locator_tip_index = LookupBlockIndex(locator_tip_hash);
}
if (!locator_tip_index) {
FatalError("%s: First block (hash=%s) in locator was not found",
__func__, locator_tip_hash.ToString());
return;
}
// This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail
// immediately after the sync thread catches up and sets m_synced. Consider the case where
// there is a reorg and the blocks on the stale branch are in the ValidationInterface queue
// backlog even after the sync thread has caught up to the new chain tip. In this unlikely
// event, log a warning and let the queue clear.
const CBlockIndex* best_block_index = m_best_block_index.load();
if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) {
LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known best " /* Continued */
"chain (tip=%s); not writing index locator\n",
__func__, locator_tip_hash.ToString(),
best_block_index->GetBlockHash().ToString());
return;
}
// No need to handle errors in Commit. If it fails, the error will be already be logged. The
// best way to recover is to continue, as index cannot be corrupted by a missed commit to disk
// for an advanced index state.
Commit();
}
bool BaseIndex::BlockUntilSyncedToCurrentChain()
{
AssertLockNotHeld(cs_main);
if (!m_synced) {
return false;
}
{
// Skip the queue-draining stuff if we know we're caught up with
// ::ChainActive().Tip().
LOCK(cs_main);
const CBlockIndex* chain_tip = ::ChainActive().Tip();
const CBlockIndex* best_block_index = m_best_block_index.load();
if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {
return true;
}
}
LogPrintf("%s: %s is catching up on block notifications\n", __func__, GetName());
SyncWithValidationInterfaceQueue();
return true;
}
void BaseIndex::Interrupt()
{
m_interrupt();
}
void BaseIndex::Start()
{
// Need to register this ValidationInterface before running Init(), so that
// callbacks are not missed if Init sets m_synced to true.
RegisterValidationInterface(this);
if (!Init()) {
FatalError("%s: %s failed to initialize", __func__, GetName());
return;
}
m_thread_sync = std::thread(&TraceThread<std::function<void()>>, GetName(),
std::bind(&BaseIndex::ThreadSync, this));
}
void BaseIndex::Stop()
{
UnregisterValidationInterface(this);
if (m_thread_sync.joinable()) {
m_thread_sync.join();
}
}
<commit_msg>index: Don't commit a best block before indexing it during sync<commit_after>// Copyright (c) 2017-2018 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 <chainparams.h>
#include <index/base.h>
#include <shutdown.h>
#include <tinyformat.h>
#include <ui_interface.h>
#include <util/system.h>
#include <validation.h>
#include <warnings.h>
constexpr char DB_BEST_BLOCK = 'B';
constexpr int64_t SYNC_LOG_INTERVAL = 30; // seconds
constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; // seconds
template<typename... Args>
static void FatalError(const char* fmt, const Args&... args)
{
std::string strMessage = tfm::format(fmt, args...);
SetMiscWarning(strMessage);
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
"Error: A fatal internal error occurred, see debug.log for details",
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
}
BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) :
CDBWrapper(path, n_cache_size, f_memory, f_wipe, f_obfuscate)
{}
bool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const
{
bool success = Read(DB_BEST_BLOCK, locator);
if (!success) {
locator.SetNull();
}
return success;
}
void BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator)
{
batch.Write(DB_BEST_BLOCK, locator);
}
BaseIndex::~BaseIndex()
{
Interrupt();
Stop();
}
bool BaseIndex::Init()
{
CBlockLocator locator;
if (!GetDB().ReadBestBlock(locator)) {
locator.SetNull();
}
LOCK(cs_main);
if (locator.IsNull()) {
m_best_block_index = nullptr;
} else {
m_best_block_index = FindForkInGlobalIndex(::ChainActive(), locator);
}
m_synced = m_best_block_index.load() == ::ChainActive().Tip();
return true;
}
static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
{
AssertLockHeld(cs_main);
if (!pindex_prev) {
return ::ChainActive().Genesis();
}
const CBlockIndex* pindex = ::ChainActive().Next(pindex_prev);
if (pindex) {
return pindex;
}
return ::ChainActive().Next(::ChainActive().FindFork(pindex_prev));
}
void BaseIndex::ThreadSync()
{
const CBlockIndex* pindex = m_best_block_index.load();
if (!m_synced) {
auto& consensus_params = Params().GetConsensus();
int64_t last_log_time = 0;
int64_t last_locator_write_time = 0;
while (true) {
if (m_interrupt) {
m_best_block_index = pindex;
// No need to handle errors in Commit. If it fails, the error will be already be
// logged. The best way to recover is to continue, as index cannot be corrupted by
// a missed commit to disk for an advanced index state.
Commit();
return;
}
{
LOCK(cs_main);
const CBlockIndex* pindex_next = NextSyncBlock(pindex);
if (!pindex_next) {
m_best_block_index = pindex;
m_synced = true;
// No need to handle errors in Commit. See rationale above.
Commit();
break;
}
if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) {
FatalError("%s: Failed to rewind index %s to a previous chain tip",
__func__, GetName());
return;
}
pindex = pindex_next;
}
int64_t current_time = GetTime();
if (last_log_time + SYNC_LOG_INTERVAL < current_time) {
LogPrintf("Syncing %s with block chain from height %d\n",
GetName(), pindex->nHeight);
last_log_time = current_time;
}
if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) {
m_best_block_index = pindex->pprev;
last_locator_write_time = current_time;
// No need to handle errors in Commit. See rationale above.
Commit();
}
CBlock block;
if (!ReadBlockFromDisk(block, pindex, consensus_params)) {
FatalError("%s: Failed to read block %s from disk",
__func__, pindex->GetBlockHash().ToString());
return;
}
if (!WriteBlock(block, pindex)) {
FatalError("%s: Failed to write block %s to index database",
__func__, pindex->GetBlockHash().ToString());
return;
}
}
}
if (pindex) {
LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight);
} else {
LogPrintf("%s is enabled\n", GetName());
}
}
bool BaseIndex::Commit()
{
CDBBatch batch(GetDB());
if (!CommitInternal(batch) || !GetDB().WriteBatch(batch)) {
return error("%s: Failed to commit latest %s state", __func__, GetName());
}
return true;
}
bool BaseIndex::CommitInternal(CDBBatch& batch)
{
LOCK(cs_main);
GetDB().WriteBestBlock(batch, ::ChainActive().GetLocator(m_best_block_index));
return true;
}
bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip)
{
assert(current_tip == m_best_block_index);
assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
// In the case of a reorg, ensure persisted block locator is not stale.
m_best_block_index = new_tip;
if (!Commit()) {
// If commit fails, revert the best block index to avoid corruption.
m_best_block_index = current_tip;
return false;
}
return true;
}
void BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex,
const std::vector<CTransactionRef>& txn_conflicted)
{
if (!m_synced) {
return;
}
const CBlockIndex* best_block_index = m_best_block_index.load();
if (!best_block_index) {
if (pindex->nHeight != 0) {
FatalError("%s: First block connected is not the genesis block (height=%d)",
__func__, pindex->nHeight);
return;
}
} else {
// Ensure block connects to an ancestor of the current best block. This should be the case
// most of the time, but may not be immediately after the sync thread catches up and sets
// m_synced. Consider the case where there is a reorg and the blocks on the stale branch are
// in the ValidationInterface queue backlog even after the sync thread has caught up to the
// new chain tip. In this unlikely event, log a warning and let the queue clear.
if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) {
LogPrintf("%s: WARNING: Block %s does not connect to an ancestor of " /* Continued */
"known best chain (tip=%s); not updating index\n",
__func__, pindex->GetBlockHash().ToString(),
best_block_index->GetBlockHash().ToString());
return;
}
if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) {
FatalError("%s: Failed to rewind index %s to a previous chain tip",
__func__, GetName());
return;
}
}
if (WriteBlock(*block, pindex)) {
m_best_block_index = pindex;
} else {
FatalError("%s: Failed to write block %s to index",
__func__, pindex->GetBlockHash().ToString());
return;
}
}
void BaseIndex::ChainStateFlushed(const CBlockLocator& locator)
{
if (!m_synced) {
return;
}
const uint256& locator_tip_hash = locator.vHave.front();
const CBlockIndex* locator_tip_index;
{
LOCK(cs_main);
locator_tip_index = LookupBlockIndex(locator_tip_hash);
}
if (!locator_tip_index) {
FatalError("%s: First block (hash=%s) in locator was not found",
__func__, locator_tip_hash.ToString());
return;
}
// This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail
// immediately after the sync thread catches up and sets m_synced. Consider the case where
// there is a reorg and the blocks on the stale branch are in the ValidationInterface queue
// backlog even after the sync thread has caught up to the new chain tip. In this unlikely
// event, log a warning and let the queue clear.
const CBlockIndex* best_block_index = m_best_block_index.load();
if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) {
LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known best " /* Continued */
"chain (tip=%s); not writing index locator\n",
__func__, locator_tip_hash.ToString(),
best_block_index->GetBlockHash().ToString());
return;
}
// No need to handle errors in Commit. If it fails, the error will be already be logged. The
// best way to recover is to continue, as index cannot be corrupted by a missed commit to disk
// for an advanced index state.
Commit();
}
bool BaseIndex::BlockUntilSyncedToCurrentChain()
{
AssertLockNotHeld(cs_main);
if (!m_synced) {
return false;
}
{
// Skip the queue-draining stuff if we know we're caught up with
// ::ChainActive().Tip().
LOCK(cs_main);
const CBlockIndex* chain_tip = ::ChainActive().Tip();
const CBlockIndex* best_block_index = m_best_block_index.load();
if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) {
return true;
}
}
LogPrintf("%s: %s is catching up on block notifications\n", __func__, GetName());
SyncWithValidationInterfaceQueue();
return true;
}
void BaseIndex::Interrupt()
{
m_interrupt();
}
void BaseIndex::Start()
{
// Need to register this ValidationInterface before running Init(), so that
// callbacks are not missed if Init sets m_synced to true.
RegisterValidationInterface(this);
if (!Init()) {
FatalError("%s: %s failed to initialize", __func__, GetName());
return;
}
m_thread_sync = std::thread(&TraceThread<std::function<void()>>, GetName(),
std::bind(&BaseIndex::ThreadSync, this));
}
void BaseIndex::Stop()
{
UnregisterValidationInterface(this);
if (m_thread_sync.joinable()) {
m_thread_sync.join();
}
}
<|endoftext|> |
<commit_before>//individual.cpp
#include <vector>
#include <cstdlib>
#include "individual.hpp"
#include "utils.hpp"
Individual::Individual(){
expression = new Node();
}
Individual::~Individual(){
delete expression;
}
Node *Individual::crossover(double crossover_rate, Individual parent){
}
void Individual::mutation(double mutation_rate){
double rate = mutation_rate*100;
if (random()%100<rate){
//aqui eu sorteio um novo tipo de nó, e com isso um novo valor de C
//também
int tipo_anterior = expression->get_type();
int new_tipo = random() %utils::SIZETYPE;
if (tipo_anterior==new_tipo) {
//caso continue igual, sorteia outro valor
}
else {
//caso mude, verifica se é func1 ou 2 e toma as devidas ações
//ou seja -> ou cria um novo filho ou deleta um para que a árvore
//não tenha pedaços que não sejam utilizados ou tenha pedaços
//faltando.
}
}
}
double Individual::fitness(vector< vector<double> > points){
double mse = 0.0;
for(int i=0; i<points.size(); i++){
mse += utils::uPow((expression->eval(points[0][i])-points[1][i] ), 2);
}
this->mse_value = utils::uSqrt(mse/(double)points.size());
return this->mse_value;
}
void Individual::print_expression_d(){
expression->print_node_d();
}
<commit_msg>1.1 Implementado fitness<commit_after>//individual.cpp
#include <vector>
#include <cstdlib>
#include <iostream>
#include "individual.hpp"
#include "utils.hpp"
Individual::Individual(){
expression = new Node();
}
Individual::~Individual(){
delete expression;
}
Node *Individual::crossover(double crossover_rate, Individual parent){
}
void Individual::mutation(double mutation_rate){
double rate = mutation_rate*100;
if (random()%100<rate){
int new_tipo = random() %utils::SIZETYPE;
std::cout << "new tipo: " << new_tipo << std::endl;
switch (new_tipo){
case utils::VAR:
expression->set_C(utils::VAR, random()%2);
break;
case utils::CTE:
expression->set_C(utils::CTE, random()%10);
break;
case utils::FUN1:
expression->set_C(utils::FUN1, random()%utils::SIZEFUNC1);
break;
case utils::FUN2:
expression->set_C(utils::FUN2, random()%utils::SIZEFUNC2);
break;
}
}
}
double Individual::fitness(std::vector<utils::DataPoint> points){
double mse = 0.0;
for(int i=0; i<points.size(); i++){
mse += utils::uPow((expression->eval(points[i])-points[i].y ), 2);
}
this->mse_value = utils::uSqrt(mse/(double)points.size());
return this->mse_value;
}
void Individual::print_expression_d(){
expression->print_node_d();
}
<|endoftext|> |
<commit_before>/*!
* FrameRecevierConfigTest.cpp
*
* Created on: Feb 4, 2015
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#include <boost/test/unit_test.hpp>
#include "FrameReceiverConfig.h"
namespace FrameReceiver
{
// This class, which is a friend of FrameReceiverConfig, allows testing of the
// correct initialization of FrameReceiverConfig
class FrameReceiverConfigTestProxy
{
public:
FrameReceiverConfigTestProxy(FrameReceiver::FrameReceiverConfig& config) :
mConfig(config)
{ }
void test_config(void)
{
BOOST_CHECK_EQUAL(mConfig.max_buffer_mem_, FrameReceiver::Defaults::default_max_buffer_mem);
BOOST_CHECK_EQUAL(mConfig.sensor_type_, FrameReceiver::Defaults::SensorTypeIllegal);
std::vector<uint16_t> port_list;
mConfig.tokenize_port_list(port_list, FrameReceiver::Defaults::default_rx_port_list);
BOOST_CHECK_EQUAL(mConfig.rx_ports_.size(), port_list.size());
for (int i = 0; i < mConfig.rx_ports_.size(); i++)
{
BOOST_CHECK_EQUAL(mConfig.rx_ports_[i], port_list[i]);
}
BOOST_CHECK_EQUAL(mConfig.rx_address_, FrameReceiver::Defaults::default_rx_address);
}
private:
FrameReceiver::FrameReceiverConfig& mConfig;
};
}
BOOST_AUTO_TEST_SUITE(FrameReceiverConfigUnitTest);
BOOST_AUTO_TEST_CASE( ValidConfigWithDefaults )
{
// Instantiate a configuration and a test proxy
FrameReceiver::FrameReceiverConfig theConfig;
FrameReceiver::FrameReceiverConfigTestProxy testProxy(theConfig);
// Use the test proxy to test that the configuration object has the correct default
// private configuration variables
testProxy.test_config();
}
BOOST_AUTO_TEST_CASE( ValidSensorNameToTypeMapping )
{
FrameReceiver::FrameReceiverConfig theConfig;
std::string p2mName = "percival2m";
std::string p13mName = "percival13m";
std::string excalibur3mName = "excalibur";
std::string badName = "foo";
// Check that the sensor name mapping to type works for all known values, and returns illegal for a bad name
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p2mName), FrameReceiver::Defaults::SensorTypePercival2M);
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p13mName), FrameReceiver::Defaults::SensorTypePercival13M);
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(excalibur3mName), FrameReceiver::Defaults::SensorTypeExcalibur);
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(badName), FrameReceiver::Defaults::SensorTypeIllegal);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Removed reference to 3M in EXCALIBUR sensor names<commit_after>/*!
* FrameRecevierConfigTest.cpp
*
* Created on: Feb 4, 2015
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#include <boost/test/unit_test.hpp>
#include "FrameReceiverConfig.h"
namespace FrameReceiver
{
// This class, which is a friend of FrameReceiverConfig, allows testing of the
// correct initialization of FrameReceiverConfig
class FrameReceiverConfigTestProxy
{
public:
FrameReceiverConfigTestProxy(FrameReceiver::FrameReceiverConfig& config) :
mConfig(config)
{ }
void test_config(void)
{
BOOST_CHECK_EQUAL(mConfig.max_buffer_mem_, FrameReceiver::Defaults::default_max_buffer_mem);
BOOST_CHECK_EQUAL(mConfig.sensor_type_, FrameReceiver::Defaults::SensorTypeIllegal);
std::vector<uint16_t> port_list;
mConfig.tokenize_port_list(port_list, FrameReceiver::Defaults::default_rx_port_list);
BOOST_CHECK_EQUAL(mConfig.rx_ports_.size(), port_list.size());
for (int i = 0; i < mConfig.rx_ports_.size(); i++)
{
BOOST_CHECK_EQUAL(mConfig.rx_ports_[i], port_list[i]);
}
BOOST_CHECK_EQUAL(mConfig.rx_address_, FrameReceiver::Defaults::default_rx_address);
}
private:
FrameReceiver::FrameReceiverConfig& mConfig;
};
}
BOOST_AUTO_TEST_SUITE(FrameReceiverConfigUnitTest);
BOOST_AUTO_TEST_CASE( ValidConfigWithDefaults )
{
// Instantiate a configuration and a test proxy
FrameReceiver::FrameReceiverConfig theConfig;
FrameReceiver::FrameReceiverConfigTestProxy testProxy(theConfig);
// Use the test proxy to test that the configuration object has the correct default
// private configuration variables
testProxy.test_config();
}
BOOST_AUTO_TEST_CASE( ValidSensorNameToTypeMapping )
{
FrameReceiver::FrameReceiverConfig theConfig;
std::string p2mName = "percival2m";
std::string p13mName = "percival13m";
std::string excaliburName = "excalibur";
std::string badName = "foo";
// Check that the sensor name mapping to type works for all known values, and returns illegal for a bad name
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p2mName), FrameReceiver::Defaults::SensorTypePercival2M);
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p13mName), FrameReceiver::Defaults::SensorTypePercival13M);
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(excaliburName), FrameReceiver::Defaults::SensorTypeExcalibur);
BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(badName), FrameReceiver::Defaults::SensorTypeIllegal);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 "src/tracing/core/trace_writer_impl.h"
#include <string.h>
#include <algorithm>
#include <type_traits>
#include <utility>
#include "perfetto/base/logging.h"
#include "perfetto/protozero/proto_utils.h"
#include "src/tracing/core/shared_memory_arbiter_impl.h"
#include "perfetto/trace/trace_packet.pbzero.h"
using protozero::proto_utils::kMessageLengthFieldSize;
using protozero::proto_utils::WriteRedundantVarInt;
using ChunkHeader = perfetto::SharedMemoryABI::ChunkHeader;
namespace perfetto {
namespace {
constexpr size_t kPacketHeaderSize = SharedMemoryABI::kPacketHeaderSize;
} // namespace
TraceWriterImpl::TraceWriterImpl(SharedMemoryArbiterImpl* shmem_arbiter,
WriterID id,
BufferID target_buffer)
: shmem_arbiter_(shmem_arbiter),
id_(id),
target_buffer_(target_buffer),
protobuf_stream_writer_(this) {
// TODO(primiano): we could handle the case of running out of TraceWriterID(s)
// more gracefully and always return a no-op TracePacket in NewTracePacket().
PERFETTO_CHECK(id_ != 0);
cur_packet_.reset(new protos::pbzero::TracePacket());
cur_packet_->Finalize(); // To avoid the DCHECK in NewTracePacket().
}
TraceWriterImpl::~TraceWriterImpl() {
if (cur_chunk_.is_valid()) {
cur_packet_->Finalize();
#if !defined(PERFETTO_BUILD_WITH_CHROMIUM)
// TODO(primiano) Remove this ifdef when https://crbug.com/844379 is
// resolved.
Flush();
#endif
}
shmem_arbiter_->ReleaseWriterID(id_);
}
void TraceWriterImpl::Flush(std::function<void()> callback) {
// Flush() cannot be called in the middle of a TracePacket.
PERFETTO_CHECK(cur_packet_->is_finalized());
if (cur_chunk_.is_valid()) {
shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_,
&patch_list_);
shmem_arbiter_->FlushPendingCommitDataRequests(callback);
} else {
PERFETTO_DCHECK(patch_list_.empty());
}
protobuf_stream_writer_.Reset({nullptr, nullptr});
}
TraceWriterImpl::TracePacketHandle TraceWriterImpl::NewTracePacket() {
// If we hit this, the caller is calling NewTracePacket() without having
// finalized the previous packet.
PERFETTO_DCHECK(cur_packet_->is_finalized());
fragmenting_packet_ = false;
// Reserve space for the size of the message. Note: this call might re-enter
// into this class invoking GetNewBuffer() if there isn't enough space or if
// this is the very first call to NewTracePacket().
static_assert(kPacketHeaderSize == kMessageLengthFieldSize,
"The packet header must match the Message header size");
// It doesn't make sense to begin a packet that is going to fragment
// immediately after (8 is just an arbitrary estimation on the minimum size of
// a realistic packet).
if (protobuf_stream_writer_.bytes_available() < kPacketHeaderSize + 8)
protobuf_stream_writer_.Reset(GetNewBuffer());
cur_packet_->Reset(&protobuf_stream_writer_);
uint8_t* header = protobuf_stream_writer_.ReserveBytes(kPacketHeaderSize);
memset(header, 0, kPacketHeaderSize);
cur_packet_->set_size_field(header);
cur_chunk_.IncrementPacketCount();
TracePacketHandle handle(cur_packet_.get());
cur_fragment_start_ = protobuf_stream_writer_.write_ptr();
fragmenting_packet_ = true;
return handle;
}
// Called by the Message. We can get here in two cases:
// 1. In the middle of writing a Message,
// when |fragmenting_packet_| == true. In this case we want to update the
// chunk header with a partial packet and start a new partial packet in the
// new chunk.
// 2. While calling ReserveBytes() for the packet header in NewTracePacket().
// In this case |fragmenting_packet_| == false and we just want a new chunk
// without creating any fragments.
protozero::ContiguousMemoryRange TraceWriterImpl::GetNewBuffer() {
if (fragmenting_packet_) {
uint8_t* const wptr = protobuf_stream_writer_.write_ptr();
PERFETTO_DCHECK(wptr >= cur_fragment_start_);
uint32_t partial_size = static_cast<uint32_t>(wptr - cur_fragment_start_);
PERFETTO_DCHECK(partial_size < cur_chunk_.size());
// Backfill the packet header with the fragment size.
PERFETTO_DCHECK(partial_size > 0);
cur_packet_->inc_size_already_written(partial_size);
cur_chunk_.SetFlag(ChunkHeader::kLastPacketContinuesOnNextChunk);
WriteRedundantVarInt(partial_size, cur_packet_->size_field());
// Descend in the stack of non-finalized nested submessages (if any) and
// detour their |size_field| into the |patch_list_|. At this point we have
// to release the chunk and they cannot write anymore into that.
// TODO(primiano): add tests to cover this logic.
for (auto* nested_msg = cur_packet_->nested_message(); nested_msg;
nested_msg = nested_msg->nested_message()) {
uint8_t* const cur_hdr = nested_msg->size_field();
// If this is false the protozero Message has already been instructed to
// write, upon Finalize(), its size into the patch list.
bool size_field_points_within_chunk =
cur_hdr >= cur_chunk_.payload_begin() &&
cur_hdr + kMessageLengthFieldSize <= cur_chunk_.end();
if (size_field_points_within_chunk) {
auto offset =
static_cast<uint16_t>(cur_hdr - cur_chunk_.payload_begin());
const ChunkID cur_chunk_id =
cur_chunk_.header()->chunk_id.load(std::memory_order_relaxed);
Patch* patch = patch_list_.emplace_back(cur_chunk_id, offset);
nested_msg->set_size_field(&patch->size_field[0]);
} else {
#if PERFETTO_DCHECK_IS_ON()
// Ensure that the size field of the message points to an element of the
// patch list.
auto patch_it = std::find_if(
patch_list_.begin(), patch_list_.end(),
[cur_hdr](const Patch& p) { return &p.size_field[0] == cur_hdr; });
PERFETTO_DCHECK(patch_it != patch_list_.end());
#endif
}
} // for(nested_msg
} // if(fragmenting_packet)
if (cur_chunk_.is_valid()) {
// ReturnCompletedChunk will consume the first patched entries from
// |patch_list_| and shrink it.
shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_,
&patch_list_);
}
// Start a new chunk.
ChunkHeader::Packets packets = {};
if (fragmenting_packet_) {
packets.count = 1;
packets.flags = ChunkHeader::kFirstPacketContinuesFromPrevChunk;
}
// The memory order of the stores below doesn't really matter. This |header|
// is just a local temporary object. The GetNewChunk() call below will copy it
// into the shared buffer with the proper barriers.
ChunkHeader header = {};
header.writer_id.store(id_, std::memory_order_relaxed);
header.chunk_id.store(next_chunk_id_++, std::memory_order_relaxed);
header.packets.store(packets, std::memory_order_relaxed);
cur_chunk_ = shmem_arbiter_->GetNewChunk(header);
uint8_t* payload_begin = cur_chunk_.payload_begin();
if (fragmenting_packet_) {
cur_packet_->set_size_field(payload_begin);
memset(payload_begin, 0, kPacketHeaderSize);
payload_begin += kPacketHeaderSize;
cur_fragment_start_ = payload_begin;
}
return protozero::ContiguousMemoryRange{payload_begin, cur_chunk_.end()};
}
WriterID TraceWriterImpl::writer_id() const {
return id_;
}
// Base class ctor/dtor definition.
TraceWriter::TraceWriter() = default;
TraceWriter::~TraceWriter() = default;
} // namespace perfetto
<commit_msg>Re-enabled TraceWriter flushing on destruction am: 34675596d8 am: a748c6a257<commit_after>/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 "src/tracing/core/trace_writer_impl.h"
#include <string.h>
#include <algorithm>
#include <type_traits>
#include <utility>
#include "perfetto/base/logging.h"
#include "perfetto/protozero/proto_utils.h"
#include "src/tracing/core/shared_memory_arbiter_impl.h"
#include "perfetto/trace/trace_packet.pbzero.h"
using protozero::proto_utils::kMessageLengthFieldSize;
using protozero::proto_utils::WriteRedundantVarInt;
using ChunkHeader = perfetto::SharedMemoryABI::ChunkHeader;
namespace perfetto {
namespace {
constexpr size_t kPacketHeaderSize = SharedMemoryABI::kPacketHeaderSize;
} // namespace
TraceWriterImpl::TraceWriterImpl(SharedMemoryArbiterImpl* shmem_arbiter,
WriterID id,
BufferID target_buffer)
: shmem_arbiter_(shmem_arbiter),
id_(id),
target_buffer_(target_buffer),
protobuf_stream_writer_(this) {
// TODO(primiano): we could handle the case of running out of TraceWriterID(s)
// more gracefully and always return a no-op TracePacket in NewTracePacket().
PERFETTO_CHECK(id_ != 0);
cur_packet_.reset(new protos::pbzero::TracePacket());
cur_packet_->Finalize(); // To avoid the DCHECK in NewTracePacket().
}
TraceWriterImpl::~TraceWriterImpl() {
if (cur_chunk_.is_valid()) {
cur_packet_->Finalize();
Flush();
}
shmem_arbiter_->ReleaseWriterID(id_);
}
void TraceWriterImpl::Flush(std::function<void()> callback) {
// Flush() cannot be called in the middle of a TracePacket.
PERFETTO_CHECK(cur_packet_->is_finalized());
if (cur_chunk_.is_valid()) {
shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_,
&patch_list_);
shmem_arbiter_->FlushPendingCommitDataRequests(callback);
} else {
PERFETTO_DCHECK(patch_list_.empty());
}
protobuf_stream_writer_.Reset({nullptr, nullptr});
}
TraceWriterImpl::TracePacketHandle TraceWriterImpl::NewTracePacket() {
// If we hit this, the caller is calling NewTracePacket() without having
// finalized the previous packet.
PERFETTO_DCHECK(cur_packet_->is_finalized());
fragmenting_packet_ = false;
// Reserve space for the size of the message. Note: this call might re-enter
// into this class invoking GetNewBuffer() if there isn't enough space or if
// this is the very first call to NewTracePacket().
static_assert(kPacketHeaderSize == kMessageLengthFieldSize,
"The packet header must match the Message header size");
// It doesn't make sense to begin a packet that is going to fragment
// immediately after (8 is just an arbitrary estimation on the minimum size of
// a realistic packet).
if (protobuf_stream_writer_.bytes_available() < kPacketHeaderSize + 8)
protobuf_stream_writer_.Reset(GetNewBuffer());
cur_packet_->Reset(&protobuf_stream_writer_);
uint8_t* header = protobuf_stream_writer_.ReserveBytes(kPacketHeaderSize);
memset(header, 0, kPacketHeaderSize);
cur_packet_->set_size_field(header);
cur_chunk_.IncrementPacketCount();
TracePacketHandle handle(cur_packet_.get());
cur_fragment_start_ = protobuf_stream_writer_.write_ptr();
fragmenting_packet_ = true;
return handle;
}
// Called by the Message. We can get here in two cases:
// 1. In the middle of writing a Message,
// when |fragmenting_packet_| == true. In this case we want to update the
// chunk header with a partial packet and start a new partial packet in the
// new chunk.
// 2. While calling ReserveBytes() for the packet header in NewTracePacket().
// In this case |fragmenting_packet_| == false and we just want a new chunk
// without creating any fragments.
protozero::ContiguousMemoryRange TraceWriterImpl::GetNewBuffer() {
if (fragmenting_packet_) {
uint8_t* const wptr = protobuf_stream_writer_.write_ptr();
PERFETTO_DCHECK(wptr >= cur_fragment_start_);
uint32_t partial_size = static_cast<uint32_t>(wptr - cur_fragment_start_);
PERFETTO_DCHECK(partial_size < cur_chunk_.size());
// Backfill the packet header with the fragment size.
PERFETTO_DCHECK(partial_size > 0);
cur_packet_->inc_size_already_written(partial_size);
cur_chunk_.SetFlag(ChunkHeader::kLastPacketContinuesOnNextChunk);
WriteRedundantVarInt(partial_size, cur_packet_->size_field());
// Descend in the stack of non-finalized nested submessages (if any) and
// detour their |size_field| into the |patch_list_|. At this point we have
// to release the chunk and they cannot write anymore into that.
// TODO(primiano): add tests to cover this logic.
for (auto* nested_msg = cur_packet_->nested_message(); nested_msg;
nested_msg = nested_msg->nested_message()) {
uint8_t* const cur_hdr = nested_msg->size_field();
// If this is false the protozero Message has already been instructed to
// write, upon Finalize(), its size into the patch list.
bool size_field_points_within_chunk =
cur_hdr >= cur_chunk_.payload_begin() &&
cur_hdr + kMessageLengthFieldSize <= cur_chunk_.end();
if (size_field_points_within_chunk) {
auto offset =
static_cast<uint16_t>(cur_hdr - cur_chunk_.payload_begin());
const ChunkID cur_chunk_id =
cur_chunk_.header()->chunk_id.load(std::memory_order_relaxed);
Patch* patch = patch_list_.emplace_back(cur_chunk_id, offset);
nested_msg->set_size_field(&patch->size_field[0]);
} else {
#if PERFETTO_DCHECK_IS_ON()
// Ensure that the size field of the message points to an element of the
// patch list.
auto patch_it = std::find_if(
patch_list_.begin(), patch_list_.end(),
[cur_hdr](const Patch& p) { return &p.size_field[0] == cur_hdr; });
PERFETTO_DCHECK(patch_it != patch_list_.end());
#endif
}
} // for(nested_msg
} // if(fragmenting_packet)
if (cur_chunk_.is_valid()) {
// ReturnCompletedChunk will consume the first patched entries from
// |patch_list_| and shrink it.
shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_,
&patch_list_);
}
// Start a new chunk.
ChunkHeader::Packets packets = {};
if (fragmenting_packet_) {
packets.count = 1;
packets.flags = ChunkHeader::kFirstPacketContinuesFromPrevChunk;
}
// The memory order of the stores below doesn't really matter. This |header|
// is just a local temporary object. The GetNewChunk() call below will copy it
// into the shared buffer with the proper barriers.
ChunkHeader header = {};
header.writer_id.store(id_, std::memory_order_relaxed);
header.chunk_id.store(next_chunk_id_++, std::memory_order_relaxed);
header.packets.store(packets, std::memory_order_relaxed);
cur_chunk_ = shmem_arbiter_->GetNewChunk(header);
uint8_t* payload_begin = cur_chunk_.payload_begin();
if (fragmenting_packet_) {
cur_packet_->set_size_field(payload_begin);
memset(payload_begin, 0, kPacketHeaderSize);
payload_begin += kPacketHeaderSize;
cur_fragment_start_ = payload_begin;
}
return protozero::ContiguousMemoryRange{payload_begin, cur_chunk_.end()};
}
WriterID TraceWriterImpl::writer_id() const {
return id_;
}
// Base class ctor/dtor definition.
TraceWriter::TraceWriter() = default;
TraceWriter::~TraceWriter() = default;
} // namespace perfetto
<|endoftext|> |
<commit_before>// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main() {
char *ptr = _strdup("Hello");
int subscript = 1;
ptr[subscript] = '3';
printf("%s\n", ptr);
fflush(0);
// CHECK: H3llo
subscript = -1;
ptr[subscript] = 42;
// CHECK: AddressSanitizer: heap-buffer-overflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T0
// CHECK: {{#0 .* main .*}}intercept_strdup.cc:[[@LINE-3]]
// CHECK: [[ADDR]] is located 1 bytes to the left of 6-byte region
// CHECK: allocated by thread T0 here:
// CHECK: #0 {{.*strdup}}
// CHECK: #1 {{.* main .*}}intercept_strdup.cc:[[@LINE-15]]
// CHECK: #2 {{.*foobar}}
// CHECK: #3 {{.*foobar}}
// CHECK: #4 {{.*foobar}}
// CHECK: #5 {{.*foobar}}
// CHECK: #6 {{.*foobar}}
// CHECK: #7 {{.*foobar}}
// CHECK: #8 {{.*foobar}}
// CHECK: #9 {{.*foobar}}
free(ptr);
}
<commit_msg>Amazingly, my guess was correct for the top two frames here. Hopefully with this, the Windows sanitizer bot will go green!<commit_after>// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: not %run %t 2>&1 | FileCheck %s
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main() {
char *ptr = _strdup("Hello");
int subscript = 1;
ptr[subscript] = '3';
printf("%s\n", ptr);
fflush(0);
// CHECK: H3llo
subscript = -1;
ptr[subscript] = 42;
// CHECK: AddressSanitizer: heap-buffer-overflow on address [[ADDR:0x[0-9a-f]+]]
// CHECK: WRITE of size 1 at [[ADDR]] thread T0
// CHECK: {{#0 .* main .*}}intercept_strdup.cc:[[@LINE-3]]
// CHECK: [[ADDR]] is located 1 bytes to the left of 6-byte region
// CHECK: allocated by thread T0 here:
// CHECK: #0 {{.*strdup}}
// CHECK: #1 {{.* main .*}}intercept_strdup.cc:[[@LINE-15]]
free(ptr);
}
<|endoftext|> |
<commit_before>/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
bitvector.cpp
Abstract:
Simple bitvector implementation
Author:
Leonardo de Moura (leonardo) 2006-10-03.
Revision History:
--*/
#include<limits.h>
#include"bit_vector.h"
#include"trace.h"
#define DEFAULT_CAPACITY 2
#define MK_MASK(_num_bits_) ((1U << _num_bits_) - 1)
void bit_vector::expand_to(unsigned new_capacity) {
if (m_data) {
m_data = (unsigned*)memory::reallocate(m_data, new_capacity * sizeof(unsigned));
} else {
m_data = alloc_svect(unsigned, new_capacity);
}
m_capacity = new_capacity;
}
void bit_vector::resize(unsigned new_size, bool val) {
if (new_size <= m_num_bits) {
m_num_bits = new_size;
return;
}
TRACE("bit_vector", tout << "expanding: " << new_size << " capacity: " << m_capacity << " num words: "
<< num_words(new_size) << "\n";);
if (num_words(new_size) > m_capacity) {
expand_to((num_words(new_size) * 3 + 1) >> 1);
}
unsigned bwidx = m_num_bits/32;
unsigned ewidx = num_words(new_size);
unsigned * begin = m_data + bwidx;
unsigned pos = m_num_bits % 32;
unsigned mask = MK_MASK(pos);
int cval;
if (val) {
*begin |= ~mask;
cval = ~0;
}
else {
*begin &= mask;
cval = 0;
}
TRACE("bit_vector",
tout << "num_bits: " << m_num_bits << "\n";
tout << "bwidx: " << bwidx << "\n";
tout << "ewidx: " << ewidx << "\n";
tout << "pos: " << pos << "\n";
tout << "mask: " << std::hex << mask << "\n" << std::dec;
tout << "cval: " << cval << "\n";);
if (bwidx < ewidx) {
memset(begin + 1, cval, (ewidx - bwidx - 1) * sizeof(unsigned));
}
m_num_bits = new_size;
}
void bit_vector::shift_right(unsigned k) {
if (k == 0)
return;
unsigned new_num_bits = m_num_bits + k;
unsigned old_num_words = num_words(m_num_bits);
unsigned new_num_words = num_words(new_num_bits);
resize(m_num_bits + k, false);
unsigned bit_shift = k % (8 * sizeof(unsigned));
unsigned word_shift = k / (8 * sizeof(unsigned));
if (word_shift > 0) {
unsigned j = old_num_words;
unsigned i = old_num_words + word_shift;
while (j > 0) {
--j; --i;
m_data[i] = m_data[j];
}
while (i > 0) {
--i;
m_data[i] = 0;
}
}
if (bit_shift > 0) {
DEBUG_CODE({
for (unsigned i = 0; i < word_shift; i++) {
SASSERT(m_data[i] == 0);
}
});
unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift;
unsigned prev = 0;
for (unsigned i = word_shift; i < new_num_words; i++) {
unsigned new_prev = (m_data[i] >> comp_shift);
m_data[i] <<= bit_shift;
m_data[i] |= prev;
prev = new_prev;
}
}
}
bool bit_vector::operator==(bit_vector const & source) const {
if (m_num_bits != source.m_num_bits)
return false;
unsigned n = num_words();
if (n == 0)
return true;
unsigned i;
for (i = 0; i < n - 1; i++) {
if (m_data[i] != source.m_data[i])
return false;
}
unsigned bit_rest = source.m_num_bits % 32;
unsigned mask = MK_MASK(bit_rest);
if (mask == 0) mask = UINT_MAX;
return (m_data[i] & mask) == (source.m_data[i] & mask);
}
bit_vector & bit_vector::operator|=(bit_vector const & source) {
if (size() < source.size())
resize(source.size(), false);
unsigned n2 = source.num_words();
SASSERT(n2 <= num_words());
unsigned bit_rest = source.m_num_bits % 32;
if (bit_rest == 0) {
unsigned i = 0;
for (i = 0; i < n2; i++)
m_data[i] |= source.m_data[i];
}
else {
unsigned i = 0;
for (i = 0; i < n2 - 1; i++)
m_data[i] |= source.m_data[i];
unsigned mask = MK_MASK(bit_rest);
m_data[i] |= source.m_data[i] & mask;
}
return *this;
}
bit_vector & bit_vector::operator&=(bit_vector const & source) {
unsigned n1 = num_words();
unsigned n2 = source.num_words();
if (n1 == 0)
return *this;
if (n2 > n1) {
for (unsigned i = 0; i < n1; i++)
m_data[i] &= source.m_data[i];
}
else {
SASSERT(n2 <= n1);
unsigned bit_rest = source.m_num_bits % 32;
unsigned i = 0;
if (bit_rest == 0) {
for (i = 0; i < n2; i++)
m_data[i] &= source.m_data[i];
}
else {
for (i = 0; i < n2 - 1; i++)
m_data[i] &= source.m_data[i];
unsigned mask = MK_MASK(bit_rest);
m_data[i] &= (source.m_data[i] & mask);
}
for (i = n2; i < n1; i++)
m_data[i] = 0;
}
return *this;
}
void bit_vector::display(std::ostream & out) const {
#if 1
unsigned i = m_num_bits;
while (i > 0) {
--i;
if (get(i))
out << "1";
else
out << "0";
}
#else
for (unsigned i = 0; i < m_num_bits; i++) {
if (get(i))
out << "1";
else
out << "0";
if ((i + 1) % 32 == 0) out << "\n";
}
#endif
}
void fr_bit_vector::reset() {
unsigned sz = size();
unsigned_vector::const_iterator it = m_one_idxs.begin();
unsigned_vector::const_iterator end = m_one_idxs.end();
for (; it != end; ++it) {
unsigned idx = *it;
if (idx < sz)
unset(idx);
}
m_one_idxs.reset();
}
<commit_msg>fix missing memset in my previous commit<commit_after>/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
bitvector.cpp
Abstract:
Simple bitvector implementation
Author:
Leonardo de Moura (leonardo) 2006-10-03.
Revision History:
--*/
#include<limits.h>
#include"bit_vector.h"
#include"trace.h"
#define DEFAULT_CAPACITY 2
#define MK_MASK(_num_bits_) ((1U << _num_bits_) - 1)
void bit_vector::expand_to(unsigned new_capacity) {
if (m_data) {
m_data = (unsigned*)memory::reallocate(m_data, new_capacity * sizeof(unsigned));
} else {
m_data = alloc_svect(unsigned, new_capacity);
}
memset(m_data + m_capacity, 0, (new_capacity - m_capacity) * sizeof(unsigned));
m_capacity = new_capacity;
}
void bit_vector::resize(unsigned new_size, bool val) {
if (new_size <= m_num_bits) {
m_num_bits = new_size;
return;
}
TRACE("bit_vector", tout << "expanding: " << new_size << " capacity: " << m_capacity << " num words: "
<< num_words(new_size) << "\n";);
if (num_words(new_size) > m_capacity) {
expand_to((num_words(new_size) * 3 + 1) >> 1);
}
unsigned bwidx = m_num_bits/32;
unsigned ewidx = num_words(new_size);
unsigned * begin = m_data + bwidx;
unsigned pos = m_num_bits % 32;
unsigned mask = MK_MASK(pos);
int cval;
if (val) {
*begin |= ~mask;
cval = ~0;
}
else {
*begin &= mask;
cval = 0;
}
TRACE("bit_vector",
tout << "num_bits: " << m_num_bits << "\n";
tout << "bwidx: " << bwidx << "\n";
tout << "ewidx: " << ewidx << "\n";
tout << "pos: " << pos << "\n";
tout << "mask: " << std::hex << mask << "\n" << std::dec;
tout << "cval: " << cval << "\n";);
if (bwidx < ewidx) {
memset(begin + 1, cval, (ewidx - bwidx - 1) * sizeof(unsigned));
}
m_num_bits = new_size;
}
void bit_vector::shift_right(unsigned k) {
if (k == 0)
return;
unsigned new_num_bits = m_num_bits + k;
unsigned old_num_words = num_words(m_num_bits);
unsigned new_num_words = num_words(new_num_bits);
resize(m_num_bits + k, false);
unsigned bit_shift = k % (8 * sizeof(unsigned));
unsigned word_shift = k / (8 * sizeof(unsigned));
if (word_shift > 0) {
unsigned j = old_num_words;
unsigned i = old_num_words + word_shift;
while (j > 0) {
--j; --i;
m_data[i] = m_data[j];
}
while (i > 0) {
--i;
m_data[i] = 0;
}
}
if (bit_shift > 0) {
DEBUG_CODE({
for (unsigned i = 0; i < word_shift; i++) {
SASSERT(m_data[i] == 0);
}
});
unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift;
unsigned prev = 0;
for (unsigned i = word_shift; i < new_num_words; i++) {
unsigned new_prev = (m_data[i] >> comp_shift);
m_data[i] <<= bit_shift;
m_data[i] |= prev;
prev = new_prev;
}
}
}
bool bit_vector::operator==(bit_vector const & source) const {
if (m_num_bits != source.m_num_bits)
return false;
unsigned n = num_words();
if (n == 0)
return true;
unsigned i;
for (i = 0; i < n - 1; i++) {
if (m_data[i] != source.m_data[i])
return false;
}
unsigned bit_rest = source.m_num_bits % 32;
unsigned mask = MK_MASK(bit_rest);
if (mask == 0) mask = UINT_MAX;
return (m_data[i] & mask) == (source.m_data[i] & mask);
}
bit_vector & bit_vector::operator|=(bit_vector const & source) {
if (size() < source.size())
resize(source.size(), false);
unsigned n2 = source.num_words();
SASSERT(n2 <= num_words());
unsigned bit_rest = source.m_num_bits % 32;
if (bit_rest == 0) {
unsigned i = 0;
for (i = 0; i < n2; i++)
m_data[i] |= source.m_data[i];
}
else {
unsigned i = 0;
for (i = 0; i < n2 - 1; i++)
m_data[i] |= source.m_data[i];
unsigned mask = MK_MASK(bit_rest);
m_data[i] |= source.m_data[i] & mask;
}
return *this;
}
bit_vector & bit_vector::operator&=(bit_vector const & source) {
unsigned n1 = num_words();
unsigned n2 = source.num_words();
if (n1 == 0)
return *this;
if (n2 > n1) {
for (unsigned i = 0; i < n1; i++)
m_data[i] &= source.m_data[i];
}
else {
SASSERT(n2 <= n1);
unsigned bit_rest = source.m_num_bits % 32;
unsigned i = 0;
if (bit_rest == 0) {
for (i = 0; i < n2; i++)
m_data[i] &= source.m_data[i];
}
else {
for (i = 0; i < n2 - 1; i++)
m_data[i] &= source.m_data[i];
unsigned mask = MK_MASK(bit_rest);
m_data[i] &= (source.m_data[i] & mask);
}
for (i = n2; i < n1; i++)
m_data[i] = 0;
}
return *this;
}
void bit_vector::display(std::ostream & out) const {
#if 1
unsigned i = m_num_bits;
while (i > 0) {
--i;
if (get(i))
out << "1";
else
out << "0";
}
#else
for (unsigned i = 0; i < m_num_bits; i++) {
if (get(i))
out << "1";
else
out << "0";
if ((i + 1) % 32 == 0) out << "\n";
}
#endif
}
void fr_bit_vector::reset() {
unsigned sz = size();
unsigned_vector::const_iterator it = m_one_idxs.begin();
unsigned_vector::const_iterator end = m_one_idxs.end();
for (; it != end; ++it) {
unsigned idx = *it;
if (idx < sz)
unset(idx);
}
m_one_idxs.reset();
}
<|endoftext|> |
<commit_before># i n c l u d e < |