<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include <armnn/Tensor.hpp>
#include <armnn/Types.hpp>

#include <cmath>
#include <ostream>
#include <set>

namespace armnn
{

constexpr char const* GetStatusAsCString(Status status)
{
    switch (status)
    {
        case armnn::Status::Success: return "Status::Success";
        case armnn::Status::Failure: return "Status::Failure";
        default:                     return "Unknown";
    }
}

constexpr char const* GetActivationFunctionAsCString(ActivationFunction activation)
{
    switch (activation)
    {
        case ActivationFunction::Sigmoid:       return "Sigmoid";
        case ActivationFunction::TanH:          return "TanH";
        case ActivationFunction::Linear:        return "Linear";
        case ActivationFunction::ReLu:          return "ReLu";
        case ActivationFunction::BoundedReLu:   return "BoundedReLu";
        case ActivationFunction::SoftReLu:      return "SoftReLu";
        case ActivationFunction::LeakyReLu:     return "LeakyReLu";
        case ActivationFunction::Abs:           return "Abs";
        case ActivationFunction::Sqrt:          return "Sqrt";
        case ActivationFunction::Square:        return "Square";
        case ActivationFunction::Elu:           return "Elu";
        case ActivationFunction::HardSwish:     return "HardSwish";
        default:                                return "Unknown";
    }
}

constexpr char const* GetArgMinMaxFunctionAsCString(ArgMinMaxFunction function)
{
    switch (function)
    {
        case ArgMinMaxFunction::Max:    return "Max";
        case ArgMinMaxFunction::Min:    return "Min";
        default:                        return "Unknown";
    }
}

constexpr char const* GetComparisonOperationAsCString(ComparisonOperation operation)
{
    switch (operation)
    {
        case ComparisonOperation::Equal:          return "Equal";
        case ComparisonOperation::Greater:        return "Greater";
        case ComparisonOperation::GreaterOrEqual: return "GreaterOrEqual";
        case ComparisonOperation::Less:           return "Less";
        case ComparisonOperation::LessOrEqual:    return "LessOrEqual";
        case ComparisonOperation::NotEqual:       return "NotEqual";
        default:                                  return "Unknown";
    }
}

constexpr char const* GetUnaryOperationAsCString(UnaryOperation operation)
{
    switch (operation)
    {
        case UnaryOperation::Abs:        return "Abs";
        case UnaryOperation::Exp:        return "Exp";
        case UnaryOperation::Sqrt:       return "Sqrt";
        case UnaryOperation::Rsqrt:      return "Rsqrt";
        case UnaryOperation::Neg:        return "Neg";
        case UnaryOperation::LogicalNot: return "LogicalNot";
        default:                         return "Unknown";
    }
}

constexpr char const* GetLogicalBinaryOperationAsCString(LogicalBinaryOperation operation)
{
    switch (operation)
    {
        case LogicalBinaryOperation::LogicalAnd: return "LogicalAnd";
        case LogicalBinaryOperation::LogicalOr:  return "LogicalOr";
        default:                                 return "Unknown";
    }
}

constexpr char const* GetPoolingAlgorithmAsCString(PoolingAlgorithm pooling)
{
    switch (pooling)
    {
        case PoolingAlgorithm::Average:  return "Average";
        case PoolingAlgorithm::Max:      return "Max";
        case PoolingAlgorithm::L2:       return "L2";
        default:                         return "Unknown";
    }
}

constexpr char const* GetOutputShapeRoundingAsCString(OutputShapeRounding rounding)
{
    switch (rounding)
    {
        case OutputShapeRounding::Ceiling:  return "Ceiling";
        case OutputShapeRounding::Floor:    return "Floor";
        default:                            return "Unknown";
    }
}

constexpr char const* GetPaddingMethodAsCString(PaddingMethod method)
{
    switch (method)
    {
        case PaddingMethod::Exclude:       return "Exclude";
        case PaddingMethod::IgnoreValue:   return "IgnoreValue";
        default:                           return "Unknown";
    }
}

constexpr char const* GetReduceOperationAsCString(ReduceOperation reduce_operation)
{
    switch (reduce_operation)
    {
        case ReduceOperation::Sum:  return "Sum";
        case ReduceOperation::Max:  return "Max";
        case ReduceOperation::Mean: return "Mean";
        case ReduceOperation::Min:  return "Min";
        default:                    return "Unknown";
    }
}
constexpr unsigned int GetDataTypeSize(DataType dataType)
{
    switch (dataType)
    {
        case DataType::BFloat16:
        case DataType::Float16:               return 2U;
        case DataType::Float32:
        case DataType::Signed32:              return 4U;
        case DataType::Signed64:              return 8U;
        case DataType::QAsymmU8:              return 1U;
        case DataType::QAsymmS8:              return 1U;
        case DataType::QSymmS8:               return 1U;
        ARMNN_NO_DEPRECATE_WARN_BEGIN
        case DataType::QuantizedSymm8PerAxis: return 1U;
        ARMNN_NO_DEPRECATE_WARN_END
        case DataType::QSymmS16:              return 2U;
        case DataType::Boolean:               return 1U;
        default:                              return 0U;
    }
}

template <unsigned N>
constexpr bool StrEqual(const char* strA, const char (&strB)[N])
{
    bool isEqual = true;
    for (unsigned i = 0; isEqual && (i < N); ++i)
    {
        isEqual = (strA[i] == strB[i]);
    }
    return isEqual;
}

/// Deprecated function that will be removed together with
/// the Compute enum
constexpr armnn::Compute ParseComputeDevice(const char* str)
{
    if (armnn::StrEqual(str, "CpuAcc"))
    {
        return armnn::Compute::CpuAcc;
    }
    else if (armnn::StrEqual(str, "CpuRef"))
    {
        return armnn::Compute::CpuRef;
    }
    else if (armnn::StrEqual(str, "GpuAcc"))
    {
        return armnn::Compute::GpuAcc;
    }
    else
    {
        return armnn::Compute::Undefined;
    }
}

constexpr const char* GetDataTypeName(DataType dataType)
{
    switch (dataType)
    {
        case DataType::Float16:               return "Float16";
        case DataType::Float32:               return "Float32";
        case DataType::Signed64:              return "Signed64";
        case DataType::QAsymmU8:              return "QAsymmU8";
        case DataType::QAsymmS8:              return "QAsymmS8";
        case DataType::QSymmS8:               return "QSymmS8";
        ARMNN_NO_DEPRECATE_WARN_BEGIN
        case DataType::QuantizedSymm8PerAxis: return "QSymm8PerAxis";
        ARMNN_NO_DEPRECATE_WARN_END
        case DataType::QSymmS16:              return "QSymm16";
        case DataType::Signed32:              return "Signed32";
        case DataType::Boolean:               return "Boolean";
        case DataType::BFloat16:              return "BFloat16";

        default:
            return "Unknown";
    }
}

constexpr const char* GetDataLayoutName(DataLayout dataLayout)
{
    switch (dataLayout)
    {
        case DataLayout::NCHW: return "NCHW";
        case DataLayout::NHWC: return "NHWC";
        default:               return "Unknown";
    }
}

constexpr const char* GetNormalizationAlgorithmChannelAsCString(NormalizationAlgorithmChannel channel)
{
    switch (channel)
    {
        case NormalizationAlgorithmChannel::Across: return "Across";
        case NormalizationAlgorithmChannel::Within: return "Within";
        default:                                    return "Unknown";
    }
}

constexpr const char* GetNormalizationAlgorithmMethodAsCString(NormalizationAlgorithmMethod method)
{
    switch (method)
    {
        case NormalizationAlgorithmMethod::LocalBrightness: return "LocalBrightness";
        case NormalizationAlgorithmMethod::LocalContrast:   return "LocalContrast";
        default:                                            return "Unknown";
    }
}

constexpr const char* GetResizeMethodAsCString(ResizeMethod method)
{
    switch (method)
    {
        case ResizeMethod::Bilinear:        return "Bilinear";
        case ResizeMethod::NearestNeighbor: return "NearestNeighbour";
        default:                            return "Unknown";
    }
}

template<typename T>
struct IsHalfType
    : std::integral_constant<bool, std::is_floating_point<T>::value && sizeof(T) == 2>
{};

template<typename T>
constexpr bool IsQuantizedType()
{
    return std::is_integral<T>::value;
}

constexpr bool IsQuantized8BitType(DataType dataType)
{
    ARMNN_NO_DEPRECATE_WARN_BEGIN
    return dataType == DataType::QAsymmU8        ||
           dataType == DataType::QAsymmS8        ||
           dataType == DataType::QSymmS8         ||
           dataType == DataType::QuantizedSymm8PerAxis;
    ARMNN_NO_DEPRECATE_WARN_END
}

constexpr bool IsQuantizedType(DataType dataType)
{
    return dataType == DataType::QSymmS16 || IsQuantized8BitType(dataType);
}

inline std::ostream& operator<<(std::ostream& os, Status stat)
{
    os << GetStatusAsCString(stat);
    return os;
}

inline std::ostream & operator<<(std::ostream & os, const armnn::TensorShape & shape)
{
    os << "[";
    for (uint32_t i=0; i<shape.GetNumDimensions(); ++i)
    {
        if (i!=0)
        {
            os << ",";
        }
        os << shape[i];
    }
    os << "]";
    return os;
}

/// Quantize a floating point data type into an 8-bit data type.
/// @param value - The value to quantize.
/// @param scale - The scale (must be non-zero).
/// @param offset - The offset.
/// @return - The quantized value calculated as round(value/scale)+offset.
///
template<typename QuantizedType>
QuantizedType Quantize(float value, float scale, int32_t offset);

/// Dequantize an 8-bit data type into a floating point data type.
/// @param value - The value to dequantize.
/// @param scale - The scale (must be non-zero).
/// @param offset - The offset.
/// @return - The dequantized value calculated as (value-offset)*scale.
///
template <typename QuantizedType>
float Dequantize(QuantizedType value, float scale, int32_t offset);

inline void VerifyTensorInfoDataType(const armnn::TensorInfo & info, armnn::DataType dataType)
{
    if (info.GetDataType() != dataType)
    {
        std::stringstream ss;
        ss << "Unexpected datatype:" << armnn::GetDataTypeName(info.GetDataType())
           << " for tensor:" << info.GetShape()
           << ". The type expected to be: " << armnn::GetDataTypeName(dataType);
        throw armnn::Exception(ss.str());
    }
}

} //namespace armnn
<commit_msg>Print Log and Sin Elementwise on dot graph<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include <armnn/Tensor.hpp>
#include <armnn/Types.hpp>

#include <cmath>
#include <ostream>
#include <set>

namespace armnn
{

constexpr char const* GetStatusAsCString(Status status)
{
    switch (status)
    {
        case armnn::Status::Success: return "Status::Success";
        case armnn::Status::Failure: return "Status::Failure";
        default:                     return "Unknown";
    }
}

constexpr char const* GetActivationFunctionAsCString(ActivationFunction activation)
{
    switch (activation)
    {
        case ActivationFunction::Sigmoid:       return "Sigmoid";
        case ActivationFunction::TanH:          return "TanH";
        case ActivationFunction::Linear:        return "Linear";
        case ActivationFunction::ReLu:          return "ReLu";
        case ActivationFunction::BoundedReLu:   return "BoundedReLu";
        case ActivationFunction::SoftReLu:      return "SoftReLu";
        case ActivationFunction::LeakyReLu:     return "LeakyReLu";
        case ActivationFunction::Abs:           return "Abs";
        case ActivationFunction::Sqrt:          return "Sqrt";
        case ActivationFunction::Square:        return "Square";
        case ActivationFunction::Elu:           return "Elu";
        case ActivationFunction::HardSwish:     return "HardSwish";
        default:                                return "Unknown";
    }
}

constexpr char const* GetArgMinMaxFunctionAsCString(ArgMinMaxFunction function)
{
    switch (function)
    {
        case ArgMinMaxFunction::Max:    return "Max";
        case ArgMinMaxFunction::Min:    return "Min";
        default:                        return "Unknown";
    }
}

constexpr char const* GetComparisonOperationAsCString(ComparisonOperation operation)
{
    switch (operation)
    {
        case ComparisonOperation::Equal:          return "Equal";
        case ComparisonOperation::Greater:        return "Greater";
        case ComparisonOperation::GreaterOrEqual: return "GreaterOrEqual";
        case ComparisonOperation::Less:           return "Less";
        case ComparisonOperation::LessOrEqual:    return "LessOrEqual";
        case ComparisonOperation::NotEqual:       return "NotEqual";
        default:                                  return "Unknown";
    }
}

constexpr char const* GetUnaryOperationAsCString(UnaryOperation operation)
{
    switch (operation)
    {
        case UnaryOperation::Abs:        return "Abs";
        case UnaryOperation::Exp:        return "Exp";
        case UnaryOperation::Sqrt:       return "Sqrt";
        case UnaryOperation::Rsqrt:      return "Rsqrt";
        case UnaryOperation::Neg:        return "Neg";
        case UnaryOperation::Log:        return "Log";
        case UnaryOperation::LogicalNot: return "LogicalNot";
        case UnaryOperation::Sin:        return "Sin";
        default:                         return "Unknown";
    }
}

constexpr char const* GetLogicalBinaryOperationAsCString(LogicalBinaryOperation operation)
{
    switch (operation)
    {
        case LogicalBinaryOperation::LogicalAnd: return "LogicalAnd";
        case LogicalBinaryOperation::LogicalOr:  return "LogicalOr";
        default:                                 return "Unknown";
    }
}

constexpr char const* GetPoolingAlgorithmAsCString(PoolingAlgorithm pooling)
{
    switch (pooling)
    {
        case PoolingAlgorithm::Average:  return "Average";
        case PoolingAlgorithm::Max:      return "Max";
        case PoolingAlgorithm::L2:       return "L2";
        default:                         return "Unknown";
    }
}

constexpr char const* GetOutputShapeRoundingAsCString(OutputShapeRounding rounding)
{
    switch (rounding)
    {
        case OutputShapeRounding::Ceiling:  return "Ceiling";
        case OutputShapeRounding::Floor:    return "Floor";
        default:                            return "Unknown";
    }
}

constexpr char const* GetPaddingMethodAsCString(PaddingMethod method)
{
    switch (method)
    {
        case PaddingMethod::Exclude:       return "Exclude";
        case PaddingMethod::IgnoreValue:   return "IgnoreValue";
        default:                           return "Unknown";
    }
}

constexpr char const* GetReduceOperationAsCString(ReduceOperation reduce_operation)
{
    switch (reduce_operation)
    {
        case ReduceOperation::Sum:  return "Sum";
        case ReduceOperation::Max:  return "Max";
        case ReduceOperation::Mean: return "Mean";
        case ReduceOperation::Min:  return "Min";
        default:                    return "Unknown";
    }
}
constexpr unsigned int GetDataTypeSize(DataType dataType)
{
    switch (dataType)
    {
        case DataType::BFloat16:
        case DataType::Float16:               return 2U;
        case DataType::Float32:
        case DataType::Signed32:              return 4U;
        case DataType::Signed64:              return 8U;
        case DataType::QAsymmU8:              return 1U;
        case DataType::QAsymmS8:              return 1U;
        case DataType::QSymmS8:               return 1U;
        ARMNN_NO_DEPRECATE_WARN_BEGIN
        case DataType::QuantizedSymm8PerAxis: return 1U;
        ARMNN_NO_DEPRECATE_WARN_END
        case DataType::QSymmS16:              return 2U;
        case DataType::Boolean:               return 1U;
        default:                              return 0U;
    }
}

template <unsigned N>
constexpr bool StrEqual(const char* strA, const char (&strB)[N])
{
    bool isEqual = true;
    for (unsigned i = 0; isEqual && (i < N); ++i)
    {
        isEqual = (strA[i] == strB[i]);
    }
    return isEqual;
}

/// Deprecated function that will be removed together with
/// the Compute enum
constexpr armnn::Compute ParseComputeDevice(const char* str)
{
    if (armnn::StrEqual(str, "CpuAcc"))
    {
        return armnn::Compute::CpuAcc;
    }
    else if (armnn::StrEqual(str, "CpuRef"))
    {
        return armnn::Compute::CpuRef;
    }
    else if (armnn::StrEqual(str, "GpuAcc"))
    {
        return armnn::Compute::GpuAcc;
    }
    else
    {
        return armnn::Compute::Undefined;
    }
}

constexpr const char* GetDataTypeName(DataType dataType)
{
    switch (dataType)
    {
        case DataType::Float16:               return "Float16";
        case DataType::Float32:               return "Float32";
        case DataType::Signed64:              return "Signed64";
        case DataType::QAsymmU8:              return "QAsymmU8";
        case DataType::QAsymmS8:              return "QAsymmS8";
        case DataType::QSymmS8:               return "QSymmS8";
        ARMNN_NO_DEPRECATE_WARN_BEGIN
        case DataType::QuantizedSymm8PerAxis: return "QSymm8PerAxis";
        ARMNN_NO_DEPRECATE_WARN_END
        case DataType::QSymmS16:              return "QSymm16";
        case DataType::Signed32:              return "Signed32";
        case DataType::Boolean:               return "Boolean";
        case DataType::BFloat16:              return "BFloat16";

        default:
            return "Unknown";
    }
}

constexpr const char* GetDataLayoutName(DataLayout dataLayout)
{
    switch (dataLayout)
    {
        case DataLayout::NCHW: return "NCHW";
        case DataLayout::NHWC: return "NHWC";
        default:               return "Unknown";
    }
}

constexpr const char* GetNormalizationAlgorithmChannelAsCString(NormalizationAlgorithmChannel channel)
{
    switch (channel)
    {
        case NormalizationAlgorithmChannel::Across: return "Across";
        case NormalizationAlgorithmChannel::Within: return "Within";
        default:                                    return "Unknown";
    }
}

constexpr const char* GetNormalizationAlgorithmMethodAsCString(NormalizationAlgorithmMethod method)
{
    switch (method)
    {
        case NormalizationAlgorithmMethod::LocalBrightness: return "LocalBrightness";
        case NormalizationAlgorithmMethod::LocalContrast:   return "LocalContrast";
        default:                                            return "Unknown";
    }
}

constexpr const char* GetResizeMethodAsCString(ResizeMethod method)
{
    switch (method)
    {
        case ResizeMethod::Bilinear:        return "Bilinear";
        case ResizeMethod::NearestNeighbor: return "NearestNeighbour";
        default:                            return "Unknown";
    }
}

template<typename T>
struct IsHalfType
    : std::integral_constant<bool, std::is_floating_point<T>::value && sizeof(T) == 2>
{};

template<typename T>
constexpr bool IsQuantizedType()
{
    return std::is_integral<T>::value;
}

constexpr bool IsQuantized8BitType(DataType dataType)
{
    ARMNN_NO_DEPRECATE_WARN_BEGIN
    return dataType == DataType::QAsymmU8        ||
           dataType == DataType::QAsymmS8        ||
           dataType == DataType::QSymmS8         ||
           dataType == DataType::QuantizedSymm8PerAxis;
    ARMNN_NO_DEPRECATE_WARN_END
}

constexpr bool IsQuantizedType(DataType dataType)
{
    return dataType == DataType::QSymmS16 || IsQuantized8BitType(dataType);
}

inline std::ostream& operator<<(std::ostream& os, Status stat)
{
    os << GetStatusAsCString(stat);
    return os;
}

inline std::ostream & operator<<(std::ostream & os, const armnn::TensorShape & shape)
{
    os << "[";
    for (uint32_t i=0; i<shape.GetNumDimensions(); ++i)
    {
        if (i!=0)
        {
            os << ",";
        }
        os << shape[i];
    }
    os << "]";
    return os;
}

/// Quantize a floating point data type into an 8-bit data type.
/// @param value - The value to quantize.
/// @param scale - The scale (must be non-zero).
/// @param offset - The offset.
/// @return - The quantized value calculated as round(value/scale)+offset.
///
template<typename QuantizedType>
QuantizedType Quantize(float value, float scale, int32_t offset);

/// Dequantize an 8-bit data type into a floating point data type.
/// @param value - The value to dequantize.
/// @param scale - The scale (must be non-zero).
/// @param offset - The offset.
/// @return - The dequantized value calculated as (value-offset)*scale.
///
template <typename QuantizedType>
float Dequantize(QuantizedType value, float scale, int32_t offset);

inline void VerifyTensorInfoDataType(const armnn::TensorInfo & info, armnn::DataType dataType)
{
    if (info.GetDataType() != dataType)
    {
        std::stringstream ss;
        ss << "Unexpected datatype:" << armnn::GetDataTypeName(info.GetDataType())
           << " for tensor:" << info.GetShape()
           << ". The type expected to be: " << armnn::GetDataTypeName(dataType);
        throw armnn::Exception(ss.str());
    }
}

} //namespace armnn
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Julian Ganz
 *
 * 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.
 */
#ifndef CMOH_STRING_VIEW_HPP__
#define CMOH_STRING_VIEW_HPP__

// We try to detect whether a standard `string_view` is available, but only for
// post-C++14 (we don't expect a C++14 STL to ship it). We don't consider the
// `experimental/string_view` header, since at least one implementation (the one
// shipped with GCC), lacks `constexpr` in critical places.
#if __cplusplus > 201402L
# if __has_include(<string_view>)
#  define has_string_view 1
# endif
#endif

// local includes
#include <cmoh/char_traits.hpp>

// use one of the `string_view` implementations
#ifdef has_string_view
#include <string_view>
namespace cmoh {
    template <
        typename CharT,
        typename Traits = char_traits<CharT>
    >
    using basic_string_view = std::basic_string_view<CharT, Traits>;
}
#else

// std includes
#include <algorithm>
#include <cstddef>
#include <limits>
#include <ostream>
#include <stdexcept>

namespace cmoh {

/**
 * Predefinition of the C++17 std::basic_string_view type
 *
 * This template provides an optional type which is modeled after the
 * std::basic_string_view which is part of the C++17 standard proposal. Note
 * that only a subset of the interface is provided. Also note that the Traits
 * defaults to a custom `char_traits`, which has some additional compile
 * capabilities but is somewhat slow at run time.
 *
 * For documentation, refer to the C++17 proposal or your favorite STL
 * documentation site.
 */
template <
    typename CharT,
    typename Traits = char_traits<CharT>
>
class basic_string_view {
public:
    typedef Traits traits_type;

    // value types
    typedef CharT value_type;
    typedef CharT* pointer;
    typedef CharT const* const_pointer;
    typedef CharT& reference;
    typedef CharT const& const_reference;

    // TODO: iterator types

    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    constexpr basic_string_view() noexcept : _data(nullptr), _count(0) {}
    constexpr basic_string_view(const basic_string_view& other) noexcept =
        default;
    constexpr basic_string_view(const CharT* data, size_type count) noexcept :
        _data(data), _count(count) {}
    constexpr basic_string_view(const CharT* data) :
        _data(data), _count(traits_type::length(data)) {}

    basic_string_view& operator=( const basic_string_view& view ) = default;

    // TODO: iterators

    constexpr const_reference operator[](size_type pos) const {
        return _data[pos];
    }

    constexpr const_reference at(size_type pos) const {
        if (pos >= size())
            throw std::out_of_range("Access out-of-bounds element.");
        return _data[pos];
    }

    constexpr const_reference front() const {
        return _data[0];
    }

    constexpr const_reference back() const {
        return _data[size() - 1];
    }

    constexpr const_pointer data() const noexcept {
        return _data;
    }

    constexpr size_type size() const noexcept {
        return _count;
    }

    constexpr size_type length() const noexcept {
        return size();
    }

    constexpr size_type max_size() const noexcept {
        return std::numeric_limits<size_type>::max();
    }

    constexpr bool empty() const noexcept {
        return size() == 0;
    }

    constexpr void remove_prefix(size_type n) {
        _data+=n;
        _count-=n;
    }

    constexpr void remove_suffix(size_type n) {
        _count-=n;
    }

    constexpr void swap(basic_string_view& v) {
        const_pointer* data = v._data;
        size_type count = v._count;

        v._data = _data;
        v._count = _count;

        _data = data;
        _count = count;
    }

    size_type copy(CharT* dest, size_type count, size_type pos = 0) const {
        if (pos >= size())
            throw std::out_of_range("Access out-of-bounds element.");
        count = std::min(count, size() - pos);
        traits_type::copy(
            dest,
            &_data[pos],
            count*sizeof(value_type)/sizeof(char)
        );
        return count;
    }

    constexpr basic_string_view
    substr(size_type pos = 0, size_type count = npos) const {
        if (pos >= size())
            throw std::out_of_range("Access out-of-bounds element.");
        return basic_string_view(_data + pos, std::min(count, size() - pos));
    }

    constexpr int compare(basic_string_view v) const noexcept {
        auto retval = traits_type::compare(
            data(),
            v.data(),
            std::min(size(), v.size())
        );
        if (retval != 0)
            return retval;
        if (size() == v.size())
            return 0;
        return size() < v.size() ? -1 : 1;
    }

    constexpr int
    compare(size_type pos1, size_type count1, basic_string_view v) const {
        return substr(pos1, count1).compare(v);
    }

    constexpr int
    compare(
        size_type pos1,
        size_type count1,
        basic_string_view v,
        size_type pos2,
        size_type count2
    ) const {
        return substr(pos1, count1).compare(v.substr(pos2, count2));
    }

    constexpr int compare(const_pointer s) const {
        return compare(basic_string_view(s));
    }

    constexpr int
    compare(size_type pos1, size_type count1, const_pointer s) const {
        return substr(pos1, count1).compare(s);
    }

    constexpr int
    compare(
        size_type pos1,
        size_type count1,
        const_pointer s,
        size_type count2
    ) const {
        return substr(pos1, count1).compare(basic_string_view(s, count2));
    }

    // TODO: find, rfind, ...

    static constexpr size_type npos = size_type(-1);

private:
    value_type const* _data;
    size_type _count;
};

}

template<
    class CharT,
    class Traits
>
constexpr bool operator == (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) == 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator != (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) != 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator < (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) < 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator <= (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) <= 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator > (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) > 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator >= (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) >= 0;
}

template <
    class CharT,
    class Traits
>
std::basic_ostream<CharT, Traits>&
operator << (
    std::basic_ostream<CharT, Traits>& stream,
    cmoh::basic_string_view <CharT, Traits> view
) {
    auto len = view.size();
    auto pos = view.data();

    while (len > 0) {
        stream.put(*pos);
        ++pos;
        --len;
    }

    return stream;
}

// TODO: hash

#endif

namespace cmoh {
    typedef basic_string_view<char> string_view;
    typedef basic_string_view<wchar_t> wstring_view;
    typedef basic_string_view<char16_t> u16string_view;
    typedef basic_string_view<char32_t> u32string_view;
}

#endif
<commit_msg>Remove whitespace in declaration of operator << for basic_string_view<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Julian Ganz
 *
 * 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.
 */
#ifndef CMOH_STRING_VIEW_HPP__
#define CMOH_STRING_VIEW_HPP__

// We try to detect whether a standard `string_view` is available, but only for
// post-C++14 (we don't expect a C++14 STL to ship it). We don't consider the
// `experimental/string_view` header, since at least one implementation (the one
// shipped with GCC), lacks `constexpr` in critical places.
#if __cplusplus > 201402L
# if __has_include(<string_view>)
#  define has_string_view 1
# endif
#endif

// local includes
#include <cmoh/char_traits.hpp>

// use one of the `string_view` implementations
#ifdef has_string_view
#include <string_view>
namespace cmoh {
    template <
        typename CharT,
        typename Traits = char_traits<CharT>
    >
    using basic_string_view = std::basic_string_view<CharT, Traits>;
}
#else

// std includes
#include <algorithm>
#include <cstddef>
#include <limits>
#include <ostream>
#include <stdexcept>

namespace cmoh {

/**
 * Predefinition of the C++17 std::basic_string_view type
 *
 * This template provides an optional type which is modeled after the
 * std::basic_string_view which is part of the C++17 standard proposal. Note
 * that only a subset of the interface is provided. Also note that the Traits
 * defaults to a custom `char_traits`, which has some additional compile
 * capabilities but is somewhat slow at run time.
 *
 * For documentation, refer to the C++17 proposal or your favorite STL
 * documentation site.
 */
template <
    typename CharT,
    typename Traits = char_traits<CharT>
>
class basic_string_view {
public:
    typedef Traits traits_type;

    // value types
    typedef CharT value_type;
    typedef CharT* pointer;
    typedef CharT const* const_pointer;
    typedef CharT& reference;
    typedef CharT const& const_reference;

    // TODO: iterator types

    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    constexpr basic_string_view() noexcept : _data(nullptr), _count(0) {}
    constexpr basic_string_view(const basic_string_view& other) noexcept =
        default;
    constexpr basic_string_view(const CharT* data, size_type count) noexcept :
        _data(data), _count(count) {}
    constexpr basic_string_view(const CharT* data) :
        _data(data), _count(traits_type::length(data)) {}

    basic_string_view& operator=( const basic_string_view& view ) = default;

    // TODO: iterators

    constexpr const_reference operator[](size_type pos) const {
        return _data[pos];
    }

    constexpr const_reference at(size_type pos) const {
        if (pos >= size())
            throw std::out_of_range("Access out-of-bounds element.");
        return _data[pos];
    }

    constexpr const_reference front() const {
        return _data[0];
    }

    constexpr const_reference back() const {
        return _data[size() - 1];
    }

    constexpr const_pointer data() const noexcept {
        return _data;
    }

    constexpr size_type size() const noexcept {
        return _count;
    }

    constexpr size_type length() const noexcept {
        return size();
    }

    constexpr size_type max_size() const noexcept {
        return std::numeric_limits<size_type>::max();
    }

    constexpr bool empty() const noexcept {
        return size() == 0;
    }

    constexpr void remove_prefix(size_type n) {
        _data+=n;
        _count-=n;
    }

    constexpr void remove_suffix(size_type n) {
        _count-=n;
    }

    constexpr void swap(basic_string_view& v) {
        const_pointer* data = v._data;
        size_type count = v._count;

        v._data = _data;
        v._count = _count;

        _data = data;
        _count = count;
    }

    size_type copy(CharT* dest, size_type count, size_type pos = 0) const {
        if (pos >= size())
            throw std::out_of_range("Access out-of-bounds element.");
        count = std::min(count, size() - pos);
        traits_type::copy(
            dest,
            &_data[pos],
            count*sizeof(value_type)/sizeof(char)
        );
        return count;
    }

    constexpr basic_string_view
    substr(size_type pos = 0, size_type count = npos) const {
        if (pos >= size())
            throw std::out_of_range("Access out-of-bounds element.");
        return basic_string_view(_data + pos, std::min(count, size() - pos));
    }

    constexpr int compare(basic_string_view v) const noexcept {
        auto retval = traits_type::compare(
            data(),
            v.data(),
            std::min(size(), v.size())
        );
        if (retval != 0)
            return retval;
        if (size() == v.size())
            return 0;
        return size() < v.size() ? -1 : 1;
    }

    constexpr int
    compare(size_type pos1, size_type count1, basic_string_view v) const {
        return substr(pos1, count1).compare(v);
    }

    constexpr int
    compare(
        size_type pos1,
        size_type count1,
        basic_string_view v,
        size_type pos2,
        size_type count2
    ) const {
        return substr(pos1, count1).compare(v.substr(pos2, count2));
    }

    constexpr int compare(const_pointer s) const {
        return compare(basic_string_view(s));
    }

    constexpr int
    compare(size_type pos1, size_type count1, const_pointer s) const {
        return substr(pos1, count1).compare(s);
    }

    constexpr int
    compare(
        size_type pos1,
        size_type count1,
        const_pointer s,
        size_type count2
    ) const {
        return substr(pos1, count1).compare(basic_string_view(s, count2));
    }

    // TODO: find, rfind, ...

    static constexpr size_type npos = size_type(-1);

private:
    value_type const* _data;
    size_type _count;
};

}

template<
    class CharT,
    class Traits
>
constexpr bool operator == (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) == 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator != (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) != 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator < (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) < 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator <= (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) <= 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator > (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) > 0;
}

template<
    class CharT,
    class Traits
>
constexpr bool operator >= (
    cmoh::basic_string_view<CharT,Traits> lhs,
    cmoh::basic_string_view<CharT,Traits> rhs
) noexcept {
    return lhs.compare(rhs) >= 0;
}

template <
    class CharT,
    class Traits
>
std::basic_ostream<CharT, Traits>&
operator << (
    std::basic_ostream<CharT, Traits>& stream,
    cmoh::basic_string_view<CharT, Traits> view
) {
    auto len = view.size();
    auto pos = view.data();

    while (len > 0) {
        stream.put(*pos);
        ++pos;
        --len;
    }

    return stream;
}

// TODO: hash

#endif

namespace cmoh {
    typedef basic_string_view<char> string_view;
    typedef basic_string_view<wchar_t> wstring_view;
    typedef basic_string_view<char16_t> u16string_view;
    typedef basic_string_view<char32_t> u32string_view;
}

#endif
<|endoftext|>


<commit_before>/**
 * \file
 * \brief Thread class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-10-27
 */

#ifndef INCLUDE_DISTORTOS_THREAD_HPP_
#define INCLUDE_DISTORTOS_THREAD_HPP_

#include "distortos/scheduler/ThreadBase.hpp"

#include <type_traits>
#include <functional>

namespace distortos
{

/**
 * \brief Thread class is a templated interface for thread
 *
 * \param Function is the function that will be executed in separate thread
 * \param Args are the arguments for Function
 */

template<typename Function, typename... Args>
class Thread : private scheduler::ThreadBase
{
public:

	/// base of Thread
	using Base = ThreadBase;

	/**
	 * \brief Thread's constructor
	 *
	 * \param [in] function is a function that will be executed in separate thread
	 * \param [in] args are arguments for function
	 */

	Thread(void* const buffer, const size_t size, const uint8_t priority, Function&& function, Args&&... args) :
			ThreadBase{buffer, size, priority},
			boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}
	{

	}

	using ThreadBase::getPriority;

	using ThreadBase::join;

	using ThreadBase::setPriority;

	using ThreadBase::start;

private:

	/**
	 * \brief Thread's internal function.
	 *
	 * Executes bound function object.
	 */

	virtual void run() override { boundFunction_(); }

	/// bound function object
	decltype(std::bind(std::declval<Function>(), std::declval<Args>()...)) boundFunction_;
};

/**
 * \brief Helper factory function to make Thread object with deduced template arguments
 *
 * \param Function is the function that will be executed
 * \param Args are the arguments for Function
 *
 * \param [in] function is a function that will be executed in separate thread
 * \param [in] args are arguments for function
 *
 * \return Thread object with deduced template arguments
 */

template<typename Function, typename... Args>
Thread<Function, Args...> makeThread(void* const buffer, const size_t size, const uint8_t priority, Function&& function,
		Args&&... args)
{
	return {buffer, size, priority, std::forward<Function>(function), std::forward<Args>(args)...};
}

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_THREAD_HPP_
<commit_msg>Thread: expose getEffectivePriority() from base class<commit_after>/**
 * \file
 * \brief Thread class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-11-11
 */

#ifndef INCLUDE_DISTORTOS_THREAD_HPP_
#define INCLUDE_DISTORTOS_THREAD_HPP_

#include "distortos/scheduler/ThreadBase.hpp"

#include <type_traits>
#include <functional>

namespace distortos
{

/**
 * \brief Thread class is a templated interface for thread
 *
 * \param Function is the function that will be executed in separate thread
 * \param Args are the arguments for Function
 */

template<typename Function, typename... Args>
class Thread : private scheduler::ThreadBase
{
public:

	/// base of Thread
	using Base = ThreadBase;

	/**
	 * \brief Thread's constructor
	 *
	 * \param [in] function is a function that will be executed in separate thread
	 * \param [in] args are arguments for function
	 */

	Thread(void* const buffer, const size_t size, const uint8_t priority, Function&& function, Args&&... args) :
			ThreadBase{buffer, size, priority},
			boundFunction_{std::bind(std::forward<Function>(function), std::forward<Args>(args)...)}
	{

	}

	using ThreadBase::getEffectivePriority;

	using ThreadBase::getPriority;

	using ThreadBase::join;

	using ThreadBase::setPriority;

	using ThreadBase::start;

private:

	/**
	 * \brief Thread's internal function.
	 *
	 * Executes bound function object.
	 */

	virtual void run() override { boundFunction_(); }

	/// bound function object
	decltype(std::bind(std::declval<Function>(), std::declval<Args>()...)) boundFunction_;
};

/**
 * \brief Helper factory function to make Thread object with deduced template arguments
 *
 * \param Function is the function that will be executed
 * \param Args are the arguments for Function
 *
 * \param [in] function is a function that will be executed in separate thread
 * \param [in] args are arguments for function
 *
 * \return Thread object with deduced template arguments
 */

template<typename Function, typename... Args>
Thread<Function, Args...> makeThread(void* const buffer, const size_t size, const uint8_t priority, Function&& function,
		Args&&... args)
{
	return {buffer, size, priority, std::forward<Function>(function), std::forward<Args>(args)...};
}

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_THREAD_HPP_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: c_vari.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 14:52:45 $
 *
 *  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
 *
 ************************************************************************/

#ifndef ARY_CPP_C_VARI_HXX
#define ARY_CPP_C_VARI_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/cpp/c_ce.hxx>
    // OTHER
#include <ary/cessentl.hxx>
#include <ary/cpp/c_types4cpp.hxx>
#include <ary/cpp/c_vfflag.hxx>

namespace ary
{
namespace cpp
{

/** A C++ variable or constant declaration.
*/
class Variable : public CodeEntity
{
  public:
    // LIFECYCLE
    enum E_ClassId { class_id = 1005 };

                        Variable();
                        Variable(
                            const String  &     i_sLocalName,
                            Ce_id               i_nOwner,
                            E_Protection        i_eProtection,
                            loc::Le_id          i_nFile,
                            Type_id             i_nType,
                            VariableFlags       i_aFlags,
                            const String  &     i_sArraySize,
                            const String  &     i_sInitValue );
                        ~Variable();

    // INQUIRY
    Type_id             Type() const;
    const String  &     ArraySize() const;
    const String  &     Initialisation() const;
    E_Protection        Protection() const      { return eProtection; }

  private:
    // Interface csv::ConstProcessorClient
    virtual void        do_Accept(
                            csv::ProcessorIfc & io_processor ) const;

    // Interface ary::cpp::CodeEntity
    virtual const String  &
                        inq_LocalName() const;
    virtual Cid         inq_Owner() const;
    virtual Lid         inq_Location() const;

    // Interface ary::cpp::CppEntity
    virtual ClassId     get_AryClass() const;

    // DATA
    CeEssentials        aEssentials;
    Type_id             nType;
    E_Protection        eProtection;
    VariableFlags       aFlags;
    String              sArraySize;
    String              sInitialisation;
};

// IMPLEMENTATION
inline Type_id
Variable::Type() const
    { return nType; }
inline const String  &
Variable::ArraySize() const
    { return sArraySize; }
inline const String  &
Variable::Initialisation() const
    { return sInitialisation; }

}   // namespace cpp
}   // namespace ary
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.22); FILE MERGED 2008/03/28 16:01:06 rt 1.3.22.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: c_vari.hxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef ARY_CPP_C_VARI_HXX
#define ARY_CPP_C_VARI_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/cpp/c_ce.hxx>
    // OTHER
#include <ary/cessentl.hxx>
#include <ary/cpp/c_types4cpp.hxx>
#include <ary/cpp/c_vfflag.hxx>

namespace ary
{
namespace cpp
{

/** A C++ variable or constant declaration.
*/
class Variable : public CodeEntity
{
  public:
    // LIFECYCLE
    enum E_ClassId { class_id = 1005 };

                        Variable();
                        Variable(
                            const String  &     i_sLocalName,
                            Ce_id               i_nOwner,
                            E_Protection        i_eProtection,
                            loc::Le_id          i_nFile,
                            Type_id             i_nType,
                            VariableFlags       i_aFlags,
                            const String  &     i_sArraySize,
                            const String  &     i_sInitValue );
                        ~Variable();

    // INQUIRY
    Type_id             Type() const;
    const String  &     ArraySize() const;
    const String  &     Initialisation() const;
    E_Protection        Protection() const      { return eProtection; }

  private:
    // Interface csv::ConstProcessorClient
    virtual void        do_Accept(
                            csv::ProcessorIfc & io_processor ) const;

    // Interface ary::cpp::CodeEntity
    virtual const String  &
                        inq_LocalName() const;
    virtual Cid         inq_Owner() const;
    virtual Lid         inq_Location() const;

    // Interface ary::cpp::CppEntity
    virtual ClassId     get_AryClass() const;

    // DATA
    CeEssentials        aEssentials;
    Type_id             nType;
    E_Protection        eProtection;
    VariableFlags       aFlags;
    String              sArraySize;
    String              sInitialisation;
};

// IMPLEMENTATION
inline Type_id
Variable::Type() const
    { return nType; }
inline const String  &
Variable::ArraySize() const
    { return sArraySize; }
inline const String  &
Variable::Initialisation() const
    { return sInitialisation; }

}   // namespace cpp
}   // namespace ary
#endif
<|endoftext|>


<commit_before><commit_msg>fixed inconsistent use of preprocessor macro for entry::print<commit_after><|endoftext|>


<commit_before>//  Copyright (C) 2009-2010, Vaclav Haisman. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modifica-
//  tion, are permitted provided that the following conditions are met:
//
//  1. Redistributions of  source code must  retain the above copyright  notice,
//     this list of conditions and the following disclaimer.
//
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//  FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
//  APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
//  DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
//  OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
//  ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
//  (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef LOG4CPLUS_CONFIG_HXX
#define LOG4CPLUS_CONFIG_HXX

#if defined (_WIN32)
#  include <log4cplus/config/win32.h>
#elif (defined(__MWERKS__) && defined(__MACOS__))
#  include <log4cplus/config/macosx.h>
#else
#  include <log4cplus/config/defines.hxx>
#endif

#if ! defined (UNICODE) && ! defined (LOG4CPLUS_HAVE_VSNPRINTF_S) \
    && ! defined (LOG4CPLUS_HAVE__VSNPRINTF_S) \
    && ! defined (LOG4CPLUS_HAVE_VSNPRINTF) \
    && ! defined (LOG4CPLUS_HAVE__VSNPRINTF)
#  undef LOG4CPLUS_USE_POOR_MANS_SNPRINTF
#  define LOG4CPLUS_USE_POOR_MANS_SNPRINTF
#endif

# if ! defined (LOG4CPLUS_WORKING_LOCALE) \
  && ! defined (LOG4CPLUS_WORKING_C_LOCALE) \
  && ! defined (LOG4CPLUS_WITH_ICONV)
# define LOG4CPLUS_POOR_MANS_CHCONV
#endif

#if !defined(_WIN32)
#  define LOG4CPLUS_USE_BSD_SOCKETS
#  if !defined(LOG4CPLUS_SINGLE_THREADED)
#    define LOG4CPLUS_USE_PTHREADS
#  endif
#  if defined (INSIDE_LOG4CPLUS)
#    define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_EXPORT
#  else
#    define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_IMPORT
#  endif // defined (INSIDE_LOG4CPLUS)

#endif // !_WIN32

#if defined (LOG4CPLUS_INLINES_ARE_EXPORTED)
#  define LOG4CPLUS_INLINE_EXPORT inline
#else
#  define LOG4CPLUS_INLINE_EXPORT
#endif

#if defined (UNICODE)
#  if defined (_MSC_VER) && _MSC_VER >= 1400
#    define LOG4CPLUS_FSTREAM_ACCEPTS_WCHAR_T
#  endif
#  if defined (_MSC_VER) && _MSC_VER >= 1600
#    define LOG4CPLUS_HAVE_CODECVT_UTF8_FACET
#    define LOG4CPLUS_HAVE_CODECVT_UTF16_FACET
#  endif
#endif

// C++11 stuff

#if ! defined (__has_feature)
//! __has_feature(X) is Clangs way for testing features.
//! Define it to 0 if it does not exist.
#  define __has_feature(X) 0
#endif

#if (defined (_MSC_VER) && _MSC_VER >= 1600) \
    || defined (__GXX_EXPERIMENTAL_CXX0X__)
#  define LOG4CPLUS_HAVE_CXX11_SUPPORT
#endif

#if defined (LOG4CPLUS_HAVE_CXX11_SUPPORT) \
    || __has_feature (cxx_rvalue_references)
#  define LOG4CPLUS_HAVE_RVALUE_REFS
#endif

#if ! defined (UNICODE) && defined (__GNUC__) && __GNUC__ >= 3
#  define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, format_index, first_arg_index) \
    __attribute__ ((format (archetype, format_index, first_arg_index)))
#else
#  define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, fmt_index, first_arg_index) \
    /* empty */
#endif

#include <log4cplus/helpers/thread-config.h>

#if defined(__cplusplus)
namespace log4cplus
{

//! Per thread cleanup function. Users should call this function before
//! a thread ends its execution. It frees resources allocated in thread local
//! storage. It is important only for multi-threaded static library builds
//! of log4cplus and user threads. In all other cases the clean up is provided
//! automatically by other means.
LOG4CPLUS_EXPORT void threadCleanup ();

} // namespace log4cplus

#endif

#endif // LOG4CPLUS_CONFIG_HXX
<commit_msg>config.hxx: Detect #pragma once usability using compiler version numbers.<commit_after>//  Copyright (C) 2009-2010, Vaclav Haisman. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modifica-
//  tion, are permitted provided that the following conditions are met:
//
//  1. Redistributions of  source code must  retain the above copyright  notice,
//     this list of conditions and the following disclaimer.
//
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//  FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
//  APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
//  DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
//  OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
//  ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
//  (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
//  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef LOG4CPLUS_CONFIG_HXX
#define LOG4CPLUS_CONFIG_HXX

#if defined (_WIN32)
#  include <log4cplus/config/win32.h>
#elif (defined(__MWERKS__) && defined(__MACOS__))
#  include <log4cplus/config/macosx.h>
#else
#  include <log4cplus/config/defines.hxx>
#endif

#if ! defined (UNICODE) && ! defined (LOG4CPLUS_HAVE_VSNPRINTF_S) \
    && ! defined (LOG4CPLUS_HAVE__VSNPRINTF_S) \
    && ! defined (LOG4CPLUS_HAVE_VSNPRINTF) \
    && ! defined (LOG4CPLUS_HAVE__VSNPRINTF)
#  undef LOG4CPLUS_USE_POOR_MANS_SNPRINTF
#  define LOG4CPLUS_USE_POOR_MANS_SNPRINTF
#endif

# if ! defined (LOG4CPLUS_WORKING_LOCALE) \
  && ! defined (LOG4CPLUS_WORKING_C_LOCALE) \
  && ! defined (LOG4CPLUS_WITH_ICONV)
# define LOG4CPLUS_POOR_MANS_CHCONV
#endif

#if !defined(_WIN32)
#  define LOG4CPLUS_USE_BSD_SOCKETS
#  if !defined(LOG4CPLUS_SINGLE_THREADED)
#    define LOG4CPLUS_USE_PTHREADS
#  endif
#  if defined (INSIDE_LOG4CPLUS)
#    define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_EXPORT
#  else
#    define LOG4CPLUS_EXPORT LOG4CPLUS_DECLSPEC_IMPORT
#  endif // defined (INSIDE_LOG4CPLUS)

#endif // !_WIN32

#if defined (LOG4CPLUS_INLINES_ARE_EXPORTED)
#  define LOG4CPLUS_INLINE_EXPORT inline
#else
#  define LOG4CPLUS_INLINE_EXPORT
#endif

#if defined (UNICODE)
#  if defined (_MSC_VER) && _MSC_VER >= 1400
#    define LOG4CPLUS_FSTREAM_ACCEPTS_WCHAR_T
#  endif
#  if defined (_MSC_VER) && _MSC_VER >= 1600
#    define LOG4CPLUS_HAVE_CODECVT_UTF8_FACET
#    define LOG4CPLUS_HAVE_CODECVT_UTF16_FACET
#  endif
#endif

// C++11 stuff

#if ! defined (__has_feature)
//! __has_feature(X) is Clangs way for testing features.
//! Define it to 0 if it does not exist.
#  define __has_feature(X) 0
#endif

#if (defined (_MSC_VER) && _MSC_VER >= 1600) \
    || defined (__GXX_EXPERIMENTAL_CXX0X__)
#  define LOG4CPLUS_HAVE_CXX11_SUPPORT
#endif

#if defined (LOG4CPLUS_HAVE_CXX11_SUPPORT) \
    || __has_feature (cxx_rvalue_references)
#  define LOG4CPLUS_HAVE_RVALUE_REFS
#endif

#if ! defined (UNICODE) && defined (__GNUC__) && __GNUC__ >= 3
#  define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, format_index, first_arg_index) \
    __attribute__ ((format (archetype, format_index, first_arg_index)))
#else
#  define LOG4CPLUS_FORMAT_ATTRIBUTE(archetype, fmt_index, first_arg_index) \
    /* empty */
#endif

#if defined (_MSC_VER)                                             \
    || (defined (__COMO__) && __COMO_VERSION__ >= 400) /* ??? */   \
    || (defined (__DMC__) && __DMC__ >= 0x700) /* ??? */           \
    || (defined (__clang__) && __clang__major >= 3)                \
    || (defined (__GNUC__) && (__GNUC__ >= 4                       \
            || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)))
#  define LOG4CPLUS_HAVE_PRAGMA_ONCE
#  pragma once
#endif

#include <log4cplus/helpers/thread-config.h>

#if defined(__cplusplus)
namespace log4cplus
{

//! Per thread cleanup function. Users should call this function before
//! a thread ends its execution. It frees resources allocated in thread local
//! storage. It is important only for multi-threaded static library builds
//! of log4cplus and user threads. In all other cases the clean up is provided
//! automatically by other means.
LOG4CPLUS_EXPORT void threadCleanup ();

} // namespace log4cplus

#endif

#endif // LOG4CPLUS_CONFIG_HXX
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

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

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * JSON interface for the solidity compiler to be used from Javascript.
 */

#include <string>
#include <iostream>
#include <json/json.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
#include <libsolidity/ASTJsonConverter.h>

using namespace std;
using namespace dev;
using namespace solidity;

string formatError(Exception const& _exception, string const& _name, CompilerStack const& _compiler)
{
	ostringstream errorOutput;
	SourceReferenceFormatter::printExceptionInformation(errorOutput, _exception, _name, _compiler);

	Json::Value output(Json::objectValue);
	output["error"] = errorOutput.str();
	return Json::FastWriter().write(output);
}

string compile(string _input, bool optimize)
{
	StringMap sources;
	sources[""] = _input;

	Json::Value output(Json::objectValue);
	CompilerStack compiler;
	try
	{
		compiler.compile(_input, optimize);
	}
	catch (ParserError const& exception)
	{
		return formatError(exception, "Parser error", compiler);
	}
	catch (DeclarationError const& exception)
	{
		return formatError(exception, "Declaration error", compiler);
	}
	catch (TypeError const& exception)
	{
		return formatError(exception, "Type error", compiler);
	}
	catch (CompilerError const& exception)
	{
		return formatError(exception, "Compiler error", compiler);
	}
	catch (InternalCompilerError const& exception)
	{
		return formatError(exception, "Internal compiler error", compiler);
	}
	catch (Exception const& exception)
	{
		output["error"] = "Exception during compilation: " + boost::diagnostic_information(exception);
		return Json::FastWriter().write(output);
	}
	catch (...)
	{
		output["error"] = "Unknown exception during compilation.";
		return Json::FastWriter().write(output);
	}

	output["contracts"] = Json::Value(Json::objectValue);
	for (string const& contractName: compiler.getContractNames())
	{
		Json::Value contractData(Json::objectValue);
		contractData["solidity_interface"] = compiler.getSolidityInterface(contractName);
		contractData["interface"] = compiler.getInterface(contractName);
		contractData["bytecode"] = toHex(compiler.getBytecode(contractName));
		contractData["opcodes"] = eth::disassemble(compiler.getBytecode(contractName));
		ostringstream unused;
		contractData["assembly"] = compiler.streamAssembly(unused, contractName, sources);
		output["contracts"][contractName] = contractData;
	}

	output["sources"] = Json::Value(Json::objectValue);
	output["sources"][""] = Json::Value(Json::objectValue);
	output["sources"][""]["AST"] = ASTJsonConverter(compiler.getAST("")).json();

	return Json::FastWriter().write(output);
}

static string outputBuffer;

extern "C"
{
extern char const* compileJSON(char const* _input, bool optimize)
{
	outputBuffer = compile(_input, optimize);
	return outputBuffer.c_str();
}
}
<commit_msg>Style fixes.<commit_after>/*
	This file is part of cpp-ethereum.

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

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * JSON interface for the solidity compiler to be used from Javascript.
 */

#include <string>
#include <iostream>
#include <json/json.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
#include <libsolidity/ASTJsonConverter.h>

using namespace std;
using namespace dev;
using namespace solidity;

string formatError(Exception const& _exception, string const& _name, CompilerStack const& _compiler)
{
	ostringstream errorOutput;
	SourceReferenceFormatter::printExceptionInformation(errorOutput, _exception, _name, _compiler);

	Json::Value output(Json::objectValue);
	output["error"] = errorOutput.str();
	return Json::FastWriter().write(output);
}

string compile(string _input, bool _optimize)
{
	StringMap sources;
	sources[""] = _input;

	Json::Value output(Json::objectValue);
	CompilerStack compiler;
	try
	{
		compiler.compile(_input, _optimize);
	}
	catch (ParserError const& exception)
	{
		return formatError(exception, "Parser error", compiler);
	}
	catch (DeclarationError const& exception)
	{
		return formatError(exception, "Declaration error", compiler);
	}
	catch (TypeError const& exception)
	{
		return formatError(exception, "Type error", compiler);
	}
	catch (CompilerError const& exception)
	{
		return formatError(exception, "Compiler error", compiler);
	}
	catch (InternalCompilerError const& exception)
	{
		return formatError(exception, "Internal compiler error", compiler);
	}
	catch (Exception const& exception)
	{
		output["error"] = "Exception during compilation: " + boost::diagnostic_information(exception);
		return Json::FastWriter().write(output);
	}
	catch (...)
	{
		output["error"] = "Unknown exception during compilation.";
		return Json::FastWriter().write(output);
	}

	output["contracts"] = Json::Value(Json::objectValue);
	for (string const& contractName: compiler.getContractNames())
	{
		Json::Value contractData(Json::objectValue);
		contractData["solidity_interface"] = compiler.getSolidityInterface(contractName);
		contractData["interface"] = compiler.getInterface(contractName);
		contractData["bytecode"] = toHex(compiler.getBytecode(contractName));
		contractData["opcodes"] = eth::disassemble(compiler.getBytecode(contractName));
		ostringstream unused;
		contractData["assembly"] = compiler.streamAssembly(unused, contractName, sources);
		output["contracts"][contractName] = contractData;
	}

	output["sources"] = Json::Value(Json::objectValue);
	output["sources"][""] = Json::Value(Json::objectValue);
	output["sources"][""]["AST"] = ASTJsonConverter(compiler.getAST("")).json();

	return Json::FastWriter().write(output);
}

static string outputBuffer;

extern "C"
{
extern char const* compileJSON(char const* _input, bool _optimize)
{
	outputBuffer = compile(_input, _optimize);
	return outputBuffer.c_str();
}
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkStructuredGrid.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
// .NAME vtkStructuredGrid - topologically regular array of data
// .SECTION Description
// vtkStructuredGrid is a data object that is a concrete implementation of
// vtkDataSet. vtkStructuredGrid represents a geometric structure that is a
// topologically regular array of points. The topology is that of a cube that
// has been subdivided into a regular array of smaller cubes. Each point/cell
// can be addressed with i-j-k indices. Examples include finite difference
// grids.

#ifndef __vtkStructuredGrid_h
#define __vtkStructuredGrid_h

#include "vtkPointSet.hh"
#include "vtkStructuredData.hh"
#include "vtkBitScalars.hh"

class vtkStructuredGrid : public vtkPointSet {
public:
  vtkStructuredGrid();
  vtkStructuredGrid(const vtkStructuredGrid& sg);
  ~vtkStructuredGrid();
  char *GetClassName() {return "vtkStructuredGrid";};
  char *GetDataType() {return "vtkStructuredGrid";};
  void PrintSelf(ostream& os, vtkIndent indent);

  // dataset interface
  vtkDataSet *MakeObject() {return new vtkStructuredGrid(*this);};
  void CopyStructure(vtkDataSet *ds);
  int GetNumberOfPoints() {return vtkPointSet::GetNumberOfPoints();};
  vtkCell *GetCell(int cellId);
  int GetCellType(int cellId);
  float *GetPoint(int ptId);
  void GetPoint(int ptId, float p[3]);
  int FindCell(float x[3], vtkCell *cell, float tol2, int& subId,
               float pcoords[3],float *weights);
  int GetNumberOfCells();
  void GetCellPoints(int cellId, vtkIdList& ptIds);
  void GetPointCells(int ptId, vtkIdList& cellIds);
  void Initialize();
  int GetMaxCellSize() {return 8;}; //hexahedron is the largest

  // methods specific to structured grid
  void SetDimensions(int i, int j, int k);
  void SetDimensions(int dim[3]);

  // Description:
  // Get dimensions of this structured points dataset.
  vtkGetVectorMacro(Dimensions,int,3);

  int GetDataDimension();
  void BlankingOn();
  void BlankingOff();
  int GetBlanking() {return this->Blanking;};
  void BlankPoint(int ptId);
  void UnBlankPoint(int ptId);
  int IsPointVisible(int ptId);

protected:
  int Dimensions[3];
  int DataDescription;
  int Blanking;
  vtkBitScalars *PointVisibility;

  vtkStructuredData StructuredData; //helper class
};

inline float *vtkStructuredGrid::GetPoint(int ptId)
{
  return this->vtkPointSet::GetPoint(ptId);
}

inline void vtkStructuredGrid::GetPoint(int ptId, float p[3])
{
  this->vtkPointSet::GetPoint(ptId,p);
}

inline int vtkStructuredGrid::GetNumberOfCells()
{
  int nCells=1;
  int i;

  for (i=0; i<3; i++)
    if (this->Dimensions[i] > 1)
      nCells *= (this->Dimensions[i]-1);

  return nCells;
}

inline int vtkStructuredGrid::GetDataDimension()
{
  return this->StructuredData.GetDataDimension(this->DataDescription);
}

inline void vtkStructuredGrid::GetCellPoints(int cellId, vtkIdList& ptIds)
{
  this->StructuredData.GetCellPoints(cellId,ptIds,this->DataDescription,
                                     this->Dimensions);
}

inline void vtkStructuredGrid::GetPointCells(int ptId, vtkIdList& cellIds)
{
  this->StructuredData.GetPointCells(ptId,cellIds,this->Dimensions);
}

inline int vtkStructuredGrid::FindCell(float x[3], vtkCell *cell, float tol2,
                                      int& subId, float pcoords[3],
                                      float *weights)
{
  return this->vtkPointSet::FindCell(x,cell,tol2,subId,pcoords,weights);
}

// Description:
// Return non-zero value if specified point is visible.
inline int vtkStructuredGrid::IsPointVisible(int ptId)
{
  if (!this->Blanking) return 1;
  else return (int) this->PointVisibility->GetScalar(ptId);
}

#endif

<commit_msg>Fixed a nasty bug<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkStructuredGrid.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
// .NAME vtkStructuredGrid - topologically regular array of data
// .SECTION Description
// vtkStructuredGrid is a data object that is a concrete implementation of
// vtkDataSet. vtkStructuredGrid represents a geometric structure that is a
// topologically regular array of points. The topology is that of a cube that
// has been subdivided into a regular array of smaller cubes. Each point/cell
// can be addressed with i-j-k indices. Examples include finite difference
// grids.

#ifndef __vtkStructuredGrid_h
#define __vtkStructuredGrid_h

#include "vtkPointSet.hh"
#include "vtkStructuredData.hh"
#include "vtkBitScalars.hh"

class vtkStructuredGrid : public vtkPointSet {
public:
  vtkStructuredGrid();
  vtkStructuredGrid(const vtkStructuredGrid& sg);
  ~vtkStructuredGrid();
  char *GetClassName() {return "vtkStructuredGrid";};
  char *GetDataType() {return "vtkStructuredGrid";};
  void PrintSelf(ostream& os, vtkIndent indent);

  // dataset interface
  vtkDataSet *MakeObject() {return new vtkStructuredGrid(*this);};
  void CopyStructure(vtkDataSet *ds);
  int GetNumberOfPoints() {return vtkPointSet::GetNumberOfPoints();};
  vtkCell *GetCell(int cellId);
  int GetCellType(int cellId);
  float *GetPoint(int ptId);
  void GetPoint(int ptId, float p[3]);
  int FindCell(float x[3], vtkCell *cell, float tol2, int& subId,
               float pcoords[3],float *weights);
  int GetNumberOfCells();
  void GetCellPoints(int cellId, vtkIdList& ptIds);
  void GetPointCells(int ptId, vtkIdList& cellIds);
  void Initialize();
  int GetMaxCellSize() {return 8;}; //hexahedron is the largest

  // methods specific to structured grid
  void SetDimensions(int i, int j, int k);
  void SetDimensions(int dim[3]);

  // Description:
  // Get dimensions of this structured points dataset.
  vtkGetVectorMacro(Dimensions,int,3);

  int GetDataDimension();
  void BlankingOn();
  void BlankingOff();
  int GetBlanking() {return this->Blanking;};
  void BlankPoint(int ptId);
  void UnBlankPoint(int ptId);
  int IsPointVisible(int ptId);

protected:
  int Dimensions[3];
  int DataDescription;
  int Blanking;
  vtkBitScalars *PointVisibility;
  void AllocatePointVisibility();

  vtkStructuredData StructuredData; //helper class
};

inline float *vtkStructuredGrid::GetPoint(int ptId)
{
  return this->vtkPointSet::GetPoint(ptId);
}

inline void vtkStructuredGrid::GetPoint(int ptId, float p[3])
{
  this->vtkPointSet::GetPoint(ptId,p);
}

inline int vtkStructuredGrid::GetNumberOfCells()
{
  int nCells=1;
  int i;

  for (i=0; i<3; i++)
    if (this->Dimensions[i] > 1)
      nCells *= (this->Dimensions[i]-1);

  return nCells;
}

inline int vtkStructuredGrid::GetDataDimension()
{
  return this->StructuredData.GetDataDimension(this->DataDescription);
}

inline void vtkStructuredGrid::GetCellPoints(int cellId, vtkIdList& ptIds)
{
  this->StructuredData.GetCellPoints(cellId,ptIds,this->DataDescription,
                                     this->Dimensions);
}

inline void vtkStructuredGrid::GetPointCells(int ptId, vtkIdList& cellIds)
{
  this->StructuredData.GetPointCells(ptId,cellIds,this->Dimensions);
}

inline int vtkStructuredGrid::FindCell(float x[3], vtkCell *cell, float tol2,
                                      int& subId, float pcoords[3],
                                      float *weights)
{
  return this->vtkPointSet::FindCell(x,cell,tol2,subId,pcoords,weights);
}

// Description:
// Return non-zero value if specified point is visible.
inline int vtkStructuredGrid::IsPointVisible(int ptId)
{
  if (!this->Blanking) return 1;
  else return (int) this->PointVisibility->GetScalar(ptId);
}

#endif

<|endoftext|>


<commit_before>#include "CacheGlyph.h"
#include "TextureMid.h"
#include "DebugDraw.h"
#include "RenderAPI.h"
#include "DrawTexture.h"

#include <texpack.h>

#include <algorithm>

#include <string.h>

namespace dtex
{

static const int BUF_SZ = 128 * 128;
static const int MAX_NODE_SIZE = 256;

static const int PADDING = 1;

CacheGlyph::CacheGlyph(int width, int height, const Callback& cb)
	: m_width(width)
	, m_height(height)
	, m_cb(cb)
{
	m_buf = new uint32_t[BUF_SZ];

	m_bitmap = new uint32_t[width * height];
	m_tex    = new TextureMid(width, height, true);
	m_tp     = texpack_create(width, height, MAX_NODE_SIZE);

	InitDirtyRect();
}

CacheGlyph::~CacheGlyph()
{
	delete[] m_buf;

	delete[] m_bitmap;
	delete m_tex;
	texpack_release(m_tp);
}

void CacheGlyph::DebugDraw() const
{
	DebugDraw::Draw(m_tex->GetID(), 2);
}

void CacheGlyph::Clear()
{
	memset(m_buf, 0, BUF_SZ);

	memset(m_bitmap, 0, sizeof(uint32_t) * m_width * m_height);
	DrawTexture::Instance()->ClearTex(m_tex);
	texpack_clear(m_tp);

	m_exists.clear();
	m_nodes.clear();

	InitDirtyRect();
}

void CacheGlyph::Load(uint32_t* bitmap, int width, int height, uint64_t key)
{
	std::set<uint64_t>::iterator itr = m_exists.find(key);
	if (itr != m_exists.end()) {
		return;
	}

	texpack_pos* pos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);
	if (!pos)
	{
		Flush();
		Clear();
		pos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);
		if (!pos) {
			return;
		}
	}

	m_exists.insert(key);
	m_nodes.push_back(Node(key, pos));

	int src_ptr = 0;
	for (int y = 0; y < height; ++y) {
		for (int x = 0; x < width; ++x) {
			uint32_t src = bitmap[src_ptr++];
			uint8_t r = (src >> 24) & 0xff;
			uint8_t g = (src >> 16) & 0xff;
			uint8_t b = (src >> 8) & 0xff;
			uint8_t a = src & 0xff;
			int dst_ptr = (pos->r.ymin + PADDING + y) * m_width + pos->r.xmin + PADDING + x;
			m_bitmap[dst_ptr] = a << 24 | b << 16 | g << 8 | r;
		}
	}

	UpdateDirtyRect(pos);
}

void CacheGlyph::Flush()
{
	if (m_nodes.empty()) {
		return;
	}

	UpdateTexture();

	m_cb.load_start();
	for (int i = 0, n = m_nodes.size(); i < n; ++i) {
		const Node& node = m_nodes[i];
		m_cb.load(m_tex->GetID(), m_tex->GetWidth(), m_tex->GetHeight(), node.GetRect(), node.Key());
	}
	m_cb.load_finish();

	m_exists.clear();
	m_nodes.clear();

	InitDirtyRect();
}

void CacheGlyph::InitDirtyRect()
{
	m_dirty_rect.xmax = m_dirty_rect.ymax = 0;
	m_dirty_rect.xmin = m_width;
	m_dirty_rect.ymin = m_height;
}

void CacheGlyph::UpdateDirtyRect(const texpack_pos* pos)
{
	if (pos->r.xmin < m_dirty_rect.xmin) {
		m_dirty_rect.xmin = pos->r.xmin;
	}
	if (pos->r.ymin < m_dirty_rect.ymin) {
		m_dirty_rect.ymin = pos->r.ymin;
	}
	if (pos->r.xmax > m_dirty_rect.xmax) {
		m_dirty_rect.xmax = pos->r.xmax;
	}
	if (pos->r.ymax > m_dirty_rect.ymax) {
		m_dirty_rect.ymax = pos->r.ymax;
	}
}

void CacheGlyph::UpdateTexture()
{
	int x = m_dirty_rect.xmin,
		y = m_dirty_rect.ymin;
	int w = m_dirty_rect.xmax - m_dirty_rect.xmin,
		h = m_dirty_rect.ymax - m_dirty_rect.ymin;

	if (w * h > BUF_SZ) {
		RenderAPI::UpdateTexture(m_bitmap, m_width, m_height, m_tex->GetID());
		return;
	}

	int src = y * m_width + x,
		dst = 0;
	int line_sz = w * sizeof(uint32_t);
	for (int i = 0; i < h; ++i) {
		memcpy(&m_buf[dst], &m_bitmap[src], line_sz);
		src += m_width;
		dst += w;
	}
	RenderAPI::UpdateSubTex(m_buf, x, y, w, h, m_tex->GetID());
}

/************************************************************************/
/* class CacheGlyph::Node                                               */
/************************************************************************/

CacheGlyph::Node::
Node(uint64_t key, texpack_pos* pos)
	: m_key(key)
{
	m_rect.xmin = pos->r.xmin + PADDING;
	m_rect.ymin = pos->r.ymin + PADDING;
	m_rect.xmax = pos->r.xmax - PADDING;
	m_rect.ymax = pos->r.ymax - PADDING;
}

}<commit_msg>[ADDED] check null bmp<commit_after>#include "CacheGlyph.h"
#include "TextureMid.h"
#include "DebugDraw.h"
#include "RenderAPI.h"
#include "DrawTexture.h"

#include <texpack.h>

#include <algorithm>

#include <string.h>

namespace dtex
{

static const int BUF_SZ = 128 * 128;
static const int MAX_NODE_SIZE = 256;

static const int PADDING = 1;

CacheGlyph::CacheGlyph(int width, int height, const Callback& cb)
	: m_width(width)
	, m_height(height)
	, m_cb(cb)
{
	m_buf = new uint32_t[BUF_SZ];

	m_bitmap = new uint32_t[width * height];
	m_tex    = new TextureMid(width, height, true);
	m_tp     = texpack_create(width, height, MAX_NODE_SIZE);

	InitDirtyRect();
}

CacheGlyph::~CacheGlyph()
{
	delete[] m_buf;

	delete[] m_bitmap;
	delete m_tex;
	texpack_release(m_tp);
}

void CacheGlyph::DebugDraw() const
{
	DebugDraw::Draw(m_tex->GetID(), 2);
}

void CacheGlyph::Clear()
{
	memset(m_buf, 0, BUF_SZ);

	memset(m_bitmap, 0, sizeof(uint32_t) * m_width * m_height);
	DrawTexture::Instance()->ClearTex(m_tex);
	texpack_clear(m_tp);

	m_exists.clear();
	m_nodes.clear();

	InitDirtyRect();
}

void CacheGlyph::Load(uint32_t* bitmap, int width, int height, uint64_t key)
{
	if (!bitmap) {
		return;
	}

	std::set<uint64_t>::iterator itr = m_exists.find(key);
	if (itr != m_exists.end()) {
		return;
	}

	texpack_pos* pos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);
	if (!pos)
	{
		Flush();
		Clear();
		pos = texpack_add(m_tp, width + PADDING * 2, height + PADDING * 2, false);
		if (!pos) {
			return;
		}
	}

	m_exists.insert(key);
	m_nodes.push_back(Node(key, pos));

	int src_ptr = 0;
	for (int y = 0; y < height; ++y) {
		for (int x = 0; x < width; ++x) {
			uint32_t src = bitmap[src_ptr++];
			uint8_t r = (src >> 24) & 0xff;
			uint8_t g = (src >> 16) & 0xff;
			uint8_t b = (src >> 8) & 0xff;
			uint8_t a = src & 0xff;

			int dst_ptr = (pos->r.ymin + PADDING + y) * m_width + pos->r.xmin + PADDING + x;
			m_bitmap[dst_ptr] = a << 24 | b << 16 | g << 8 | r;
		}
	}

	UpdateDirtyRect(pos);
}

void CacheGlyph::Flush()
{
	if (m_nodes.empty()) {
		return;
	}

	UpdateTexture();

	m_cb.load_start();
	for (int i = 0, n = m_nodes.size(); i < n; ++i) {
		const Node& node = m_nodes[i];
		m_cb.load(m_tex->GetID(), m_tex->GetWidth(), m_tex->GetHeight(), node.GetRect(), node.Key());
	}
	m_cb.load_finish();

	m_exists.clear();
	m_nodes.clear();

	InitDirtyRect();
}

void CacheGlyph::InitDirtyRect()
{
	m_dirty_rect.xmax = m_dirty_rect.ymax = 0;
	m_dirty_rect.xmin = m_width;
	m_dirty_rect.ymin = m_height;
}

void CacheGlyph::UpdateDirtyRect(const texpack_pos* pos)
{
	if (pos->r.xmin < m_dirty_rect.xmin) {
		m_dirty_rect.xmin = pos->r.xmin;
	}
	if (pos->r.ymin < m_dirty_rect.ymin) {
		m_dirty_rect.ymin = pos->r.ymin;
	}
	if (pos->r.xmax > m_dirty_rect.xmax) {
		m_dirty_rect.xmax = pos->r.xmax;
	}
	if (pos->r.ymax > m_dirty_rect.ymax) {
		m_dirty_rect.ymax = pos->r.ymax;
	}
}

void CacheGlyph::UpdateTexture()
{
	int x = m_dirty_rect.xmin,
		y = m_dirty_rect.ymin;
	int w = m_dirty_rect.xmax - m_dirty_rect.xmin,
		h = m_dirty_rect.ymax - m_dirty_rect.ymin;

	if (w * h > BUF_SZ) {
		RenderAPI::UpdateTexture(m_bitmap, m_width, m_height, m_tex->GetID());
		return;
	}

	int src = y * m_width + x,
		dst = 0;
	int line_sz = w * sizeof(uint32_t);
	for (int i = 0; i < h; ++i) {
		memcpy(&m_buf[dst], &m_bitmap[src], line_sz);
		src += m_width;
		dst += w;
	}
	RenderAPI::UpdateSubTex(m_buf, x, y, w, h, m_tex->GetID());
}

/************************************************************************/
/* class CacheGlyph::Node                                               */
/************************************************************************/

CacheGlyph::Node::
Node(uint64_t key, texpack_pos* pos)
	: m_key(key)
{
	m_rect.xmin = pos->r.xmin + PADDING;
	m_rect.ymin = pos->r.ymin + PADDING;
	m_rect.xmax = pos->r.xmax - PADDING;
	m_rect.ymax = pos->r.ymax - PADDING;
}

}<|endoftext|>