<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <cmath>
#include <limits>
#include <memory>
#include <vector>

#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace {

class GpuAddTest : public OpsTestBase {
 protected:
  void SetUp() override {
    std::unique_ptr<tensorflow::Device> device_gpu(
        tensorflow::DeviceFactory::NewDevice("GPU", {},
                                             "/job:a/replica:0/task:0"));
    SetDevice(tensorflow::DEVICE_GPU, std::move(device_gpu));
  }

  template <typename T, typename BaselineType = T>
  void SetAddOp(std::vector<T> input_1, TensorShape shape_1,
                std::vector<T> input_2, TensorShape shape_2) {
    TF_ASSERT_OK(NodeDefBuilder("add_op", "AddV2")
                     .Input(FakeInput(DataTypeToEnum<T>::v()))
                     .Input(FakeInput(DataTypeToEnum<T>::v()))
                     .Attr("T", DataTypeToEnum<T>::v())
                     .Finalize(node_def()));

    TF_ASSERT_OK(InitOp());
    AddInputFromArray<T>(shape_1, input_1);
    AddInputFromArray<T>(shape_2, input_2);
  }

  template <typename T, typename BaselineType = T>
  void RunAndCompareAddOp(std::vector<T> input_1, TensorShape shape_1,
                          std::vector<T> input_2, TensorShape shape_2,
                          std::vector<T> output, TensorShape output_shape) {
    SetAddOp<T>(input_1, shape_1, input_2, shape_2);
    TF_ASSERT_OK(RunOpKernel());
    Tensor expected_tensor(allocator(), DataTypeToEnum<T>::value, output_shape);
    test::FillValues<T>(&expected_tensor, output);
    test::ExpectEqual(expected_tensor, *GetOutput(0));
  }

  template <typename T, typename BaselineType = T>
  void TestBroadcastingExpandAddOp() {
    auto input_1 = {static_cast<T>(10)};
    auto input_2 = {static_cast<T>(1), static_cast<T>(2), static_cast<T>(3),
                    static_cast<T>(4), static_cast<T>(5), static_cast<T>(6)};
    std::vector<T> expected{
        static_cast<T>(11), static_cast<T>(12), static_cast<T>(13),
        static_cast<T>(14), static_cast<T>(15), static_cast<T>(16),
    };
    auto expected_shape = TensorShape({6});
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape({1}), input_2,
                                        TensorShape({6}), expected,
                                        expected_shape);
  }

  template <typename T, typename BaselineType = T>
  void TestBroadcastingInDimAddOp() {
    auto input_1 = {static_cast<T>(10), static_cast<T>(20), static_cast<T>(30)};
    auto input_2 = {static_cast<T>(1), static_cast<T>(2), static_cast<T>(3),
                    static_cast<T>(4), static_cast<T>(5), static_cast<T>(6)};
    std::vector<T> expected{
        static_cast<T>(11), static_cast<T>(22), static_cast<T>(33),
        static_cast<T>(14), static_cast<T>(25), static_cast<T>(36),
    };
    auto expected_shape = TensorShape({2, 3});
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape({3}), input_2,
                                        TensorShape({2, 3}), expected,
                                        expected_shape);
  }

  template <typename T, typename BaselineType = T>
  void TestBroadcastingAddOp() {
    auto input_1 = {static_cast<T>(10), static_cast<T>(20)};
    auto input_2 = {static_cast<T>(1), static_cast<T>(2), static_cast<T>(3)};
    std::vector<T> expected{
        static_cast<T>(11), static_cast<T>(12), static_cast<T>(13),
        static_cast<T>(21), static_cast<T>(22), static_cast<T>(23),
    };
    auto expected_shape = TensorShape({2, 3});
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape({2, 1}), input_2,
                                        TensorShape({3}), expected,
                                        expected_shape);
  }

  template <typename T, typename BaselineType = T>
  void RunAddOp() {
    auto input_1 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    auto input_2 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    std::vector<T> expected;
    for (const T& inp : input_2) {
      expected.push_back(static_cast<T>(static_cast<BaselineType>(inp) +
                                        static_cast<BaselineType>(inp)));
    }
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape{2, 3}, input_2,
                                        TensorShape{2, 3}, expected,
                                        TensorShape{2, 3});
  }

  template <typename T, typename BaselineType = T>
  void TestEqualShapesAddOp() {
    auto input_1 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    auto input_2 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    std::vector<T> expected;
    for (const T& inp : input_2) {
      expected.push_back(static_cast<T>(static_cast<BaselineType>(inp) +
                                        static_cast<BaselineType>(inp)));
    }
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape{2, 3}, input_2,
                                        TensorShape{2, 3}, expected,
                                        TensorShape{2, 3});
  }

  template <typename T, typename BaselineType = T>
  void TestOneIsScalarAddOp() {
    auto input_1 = static_cast<T>(42);
    auto input_2 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    std::vector<T> expected;
    for (const T& inp : input_2) {
      expected.push_back(static_cast<T>(static_cast<BaselineType>(input_1) +
                                        static_cast<BaselineType>(inp)));
    }
    RunAndCompareAddOp<T, BaselineType>({input_1}, TensorShape{}, input_2,
                                        TensorShape{2, 3}, expected,
                                        TensorShape{2, 3});
  }

  template <typename T, typename RT = T>
  void TestIncompatibleShapes() {
    auto input_1 = {static_cast<T>(-0.1), static_cast<T>(-0.0),
                    static_cast<T>(0.0)};
    auto input_2 = {static_cast<T>(-0.1), static_cast<T>(0.0)};

    SetAddOp<T>(input_1, TensorShape{3}, input_2, TensorShape{2});
    auto status = RunOpKernel();
    EXPECT_FALSE(status.ok());
    EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
  }
};

TEST_F(GpuAddTest, AddFloat) { RunAddOp<float>(); }
TEST_F(GpuAddTest, AddDouble) { RunAddOp<double>(); }
TEST_F(GpuAddTest, AddHalf) { RunAddOp<Eigen::half, float>(); }
TEST_F(GpuAddTest, AddInt64) { RunAddOp<int64, int64>(); }

TEST_F(GpuAddTest, AddEqShapesFloat) { TestEqualShapesAddOp<float>(); }
TEST_F(GpuAddTest, AddEqShapesDouble) { TestEqualShapesAddOp<double>(); }
TEST_F(GpuAddTest, AddEqShapesHalf) {
  TestEqualShapesAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, AddEqShapesInt64) { TestEqualShapesAddOp<int64>(); }

TEST_F(GpuAddTest, AddScalarFloat) { TestOneIsScalarAddOp<float>(); }
TEST_F(GpuAddTest, AddScalarDouble) { TestOneIsScalarAddOp<double>(); }
TEST_F(GpuAddTest, AddScalarHalf) {
  TestOneIsScalarAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, AddScalarInt64) { TestOneIsScalarAddOp<int64>(); }

TEST_F(GpuAddTest, BCastExpandAddFloat) {
  TestBroadcastingExpandAddOp<float>();
}
TEST_F(GpuAddTest, BCastExpandAddDouble) {
  TestBroadcastingExpandAddOp<double>();
}
TEST_F(GpuAddTest, BCastExpandAddHalf) {
  TestBroadcastingExpandAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, BCastExpandAddInt64) {
  TestBroadcastingExpandAddOp<int64>();
}

TEST_F(GpuAddTest, BCastInDimAddFloat) { TestBroadcastingInDimAddOp<float>(); }
TEST_F(GpuAddTest, BCastInDimAddDouble) {
  TestBroadcastingInDimAddOp<double>();
}
TEST_F(GpuAddTest, BCastInDimAddHalf) {
  TestBroadcastingInDimAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, BCastInDimAddInt64) { TestBroadcastingInDimAddOp<int64>(); }

TEST_F(GpuAddTest, BCastAddFloat) { TestBroadcastingAddOp<float>(); }
TEST_F(GpuAddTest, BCastAddDouble) { TestBroadcastingAddOp<double>(); }
TEST_F(GpuAddTest, BCastAddHalf) {
  TestBroadcastingAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, BCastAddInt64) { TestBroadcastingAddOp<int64>(); }

TEST_F(GpuAddTest, IncompatibleShapes) { TestIncompatibleShapes<float>(); }

// TEST_F(GpuAddTest, AddV2Half) { RunAddOp<Eigen::half, float>(); }
}  // namespace
}  // end namespace tensorflow
<commit_msg>[MLIR][KernelGen] Add test for binary kernel on empty tensors.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <cmath>
#include <limits>
#include <memory>
#include <vector>

#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/framework/fake_input.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/ops_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace {

class GpuAddTest : public OpsTestBase {
 protected:
  void SetUp() override {
    std::unique_ptr<tensorflow::Device> device_gpu(
        tensorflow::DeviceFactory::NewDevice("GPU", {},
                                             "/job:a/replica:0/task:0"));
    SetDevice(tensorflow::DEVICE_GPU, std::move(device_gpu));
  }

  template <typename T, typename BaselineType = T>
  void SetAddOp(std::vector<T> input_1, TensorShape shape_1,
                std::vector<T> input_2, TensorShape shape_2) {
    TF_ASSERT_OK(NodeDefBuilder("add_op", "AddV2")
                     .Input(FakeInput(DataTypeToEnum<T>::v()))
                     .Input(FakeInput(DataTypeToEnum<T>::v()))
                     .Attr("T", DataTypeToEnum<T>::v())
                     .Finalize(node_def()));

    TF_ASSERT_OK(InitOp());
    inputs_.clear();
    AddInputFromArray<T>(shape_1, input_1);
    AddInputFromArray<T>(shape_2, input_2);
  }

  template <typename T, typename BaselineType = T>
  void RunAndCompareAddOp(std::vector<T> input_1, TensorShape shape_1,
                          std::vector<T> input_2, TensorShape shape_2,
                          std::vector<T> output, TensorShape output_shape) {
    SetAddOp<T>(input_1, shape_1, input_2, shape_2);
    TF_ASSERT_OK(RunOpKernel());
    Tensor expected_tensor(allocator(), DataTypeToEnum<T>::value, output_shape);
    test::FillValues<T>(&expected_tensor, output);
    test::ExpectEqual(expected_tensor, *GetOutput(0));
  }

  template <typename T, typename BaselineType = T>
  void TestBroadcastingExpandAddOp() {
    auto input_1 = {static_cast<T>(10)};
    auto input_2 = {static_cast<T>(1), static_cast<T>(2), static_cast<T>(3),
                    static_cast<T>(4), static_cast<T>(5), static_cast<T>(6)};
    std::vector<T> expected{
        static_cast<T>(11), static_cast<T>(12), static_cast<T>(13),
        static_cast<T>(14), static_cast<T>(15), static_cast<T>(16),
    };
    auto expected_shape = TensorShape({6});
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape({1}), input_2,
                                        TensorShape({6}), expected,
                                        expected_shape);
  }

  template <typename T, typename BaselineType = T>
  void TestBroadcastingInDimAddOp() {
    auto input_1 = {static_cast<T>(10), static_cast<T>(20), static_cast<T>(30)};
    auto input_2 = {static_cast<T>(1), static_cast<T>(2), static_cast<T>(3),
                    static_cast<T>(4), static_cast<T>(5), static_cast<T>(6)};
    std::vector<T> expected{
        static_cast<T>(11), static_cast<T>(22), static_cast<T>(33),
        static_cast<T>(14), static_cast<T>(25), static_cast<T>(36),
    };
    auto expected_shape = TensorShape({2, 3});
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape({3}), input_2,
                                        TensorShape({2, 3}), expected,
                                        expected_shape);
  }

  template <typename T, typename BaselineType = T>
  void TestBroadcastingAddOp() {
    auto input_1 = {static_cast<T>(10), static_cast<T>(20)};
    auto input_2 = {static_cast<T>(1), static_cast<T>(2), static_cast<T>(3)};
    std::vector<T> expected{
        static_cast<T>(11), static_cast<T>(12), static_cast<T>(13),
        static_cast<T>(21), static_cast<T>(22), static_cast<T>(23),
    };
    auto expected_shape = TensorShape({2, 3});
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape({2, 1}), input_2,
                                        TensorShape({3}), expected,
                                        expected_shape);
  }

  template <typename T, typename BaselineType = T>
  void RunAddOp() {
    auto input_1 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    auto input_2 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    std::vector<T> expected;
    for (const T& inp : input_2) {
      expected.push_back(static_cast<T>(static_cast<BaselineType>(inp) +
                                        static_cast<BaselineType>(inp)));
    }
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape{2, 3}, input_2,
                                        TensorShape{2, 3}, expected,
                                        TensorShape{2, 3});
  }

  template <typename T, typename BaselineType = T>
  void TestEqualShapesAddOp() {
    auto input_1 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    auto input_2 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    std::vector<T> expected;
    for (const T& inp : input_2) {
      expected.push_back(static_cast<T>(static_cast<BaselineType>(inp) +
                                        static_cast<BaselineType>(inp)));
    }
    RunAndCompareAddOp<T, BaselineType>(input_1, TensorShape{2, 3}, input_2,
                                        TensorShape{2, 3}, expected,
                                        TensorShape{2, 3});
  }

  template <typename T, typename BaselineType = T>
  void TestOneIsScalarAddOp() {
    auto input_1 = static_cast<T>(42);
    auto input_2 = {
        static_cast<T>(-std::numeric_limits<BaselineType>::infinity()),
        static_cast<T>(-0.1),
        static_cast<T>(-0.0),
        static_cast<T>(0.0),
        static_cast<T>(0.1),
        static_cast<T>(std::numeric_limits<BaselineType>::infinity())};
    std::vector<T> expected;
    for (const T& inp : input_2) {
      expected.push_back(static_cast<T>(static_cast<BaselineType>(input_1) +
                                        static_cast<BaselineType>(inp)));
    }
    RunAndCompareAddOp<T, BaselineType>({input_1}, TensorShape{}, input_2,
                                        TensorShape{2, 3}, expected,
                                        TensorShape{2, 3});
  }

  template <typename T, typename RT = T>
  void TestIncompatibleShapes() {
    auto input_1 = {static_cast<T>(-0.1), static_cast<T>(-0.0),
                    static_cast<T>(0.0)};
    auto input_2 = {static_cast<T>(-0.1), static_cast<T>(0.0)};

    SetAddOp<T>(input_1, TensorShape{3}, input_2, TensorShape{2});
    auto status = RunOpKernel();
    EXPECT_FALSE(status.ok());
    EXPECT_EQ(status.code(), error::INVALID_ARGUMENT);
  }

  template <typename T, typename BaselineType = T>
  void TestEmptyShapeWithBroadcastingAddOp() {
    TensorShape input_shape_a{2, 0, 1};
    TensorShape input_shape_b{2, 0, 5};
    TensorShape expected_shape{2, 0, 5};
    std::vector<T> empty_input = {};
    RunAndCompareAddOp<T, BaselineType>(empty_input, input_shape_a, empty_input,
                                        input_shape_b, empty_input,
                                        expected_shape);
    RunAndCompareAddOp<T, BaselineType>(empty_input, input_shape_b, empty_input,
                                        input_shape_a, empty_input,
                                        expected_shape);
  }
};

TEST_F(GpuAddTest, AddFloat) { RunAddOp<float>(); }
TEST_F(GpuAddTest, AddDouble) { RunAddOp<double>(); }
TEST_F(GpuAddTest, AddHalf) { RunAddOp<Eigen::half, float>(); }
TEST_F(GpuAddTest, AddInt64) { RunAddOp<int64, int64>(); }

TEST_F(GpuAddTest, AddEqShapesFloat) { TestEqualShapesAddOp<float>(); }
TEST_F(GpuAddTest, AddEqShapesDouble) { TestEqualShapesAddOp<double>(); }
TEST_F(GpuAddTest, AddEqShapesHalf) {
  TestEqualShapesAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, AddEqShapesInt64) { TestEqualShapesAddOp<int64>(); }

TEST_F(GpuAddTest, AddScalarFloat) { TestOneIsScalarAddOp<float>(); }
TEST_F(GpuAddTest, AddScalarDouble) { TestOneIsScalarAddOp<double>(); }
TEST_F(GpuAddTest, AddScalarHalf) {
  TestOneIsScalarAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, AddScalarInt64) { TestOneIsScalarAddOp<int64>(); }

TEST_F(GpuAddTest, BCastExpandAddFloat) {
  TestBroadcastingExpandAddOp<float>();
}
TEST_F(GpuAddTest, BCastExpandAddDouble) {
  TestBroadcastingExpandAddOp<double>();
}
TEST_F(GpuAddTest, BCastExpandAddHalf) {
  TestBroadcastingExpandAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, BCastExpandAddInt64) {
  TestBroadcastingExpandAddOp<int64>();
}

TEST_F(GpuAddTest, BCastInDimAddFloat) { TestBroadcastingInDimAddOp<float>(); }
TEST_F(GpuAddTest, BCastInDimAddDouble) {
  TestBroadcastingInDimAddOp<double>();
}
TEST_F(GpuAddTest, BCastInDimAddHalf) {
  TestBroadcastingInDimAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, BCastInDimAddInt64) { TestBroadcastingInDimAddOp<int64>(); }

TEST_F(GpuAddTest, BCastAddFloat) { TestBroadcastingAddOp<float>(); }
TEST_F(GpuAddTest, BCastAddDouble) { TestBroadcastingAddOp<double>(); }
TEST_F(GpuAddTest, BCastAddHalf) {
  TestBroadcastingAddOp<Eigen::half, float>();
}
TEST_F(GpuAddTest, BCastAddInt64) { TestBroadcastingAddOp<int64>(); }

TEST_F(GpuAddTest, IncompatibleShapes) { TestIncompatibleShapes<float>(); }

TEST_F(GpuAddTest, EmptyShapeBCastAddFloat) {
  TestEmptyShapeWithBroadcastingAddOp<float>();
}
TEST_F(GpuAddTest, EmptyShapeBCastAddDouble) {
  TestEmptyShapeWithBroadcastingAddOp<double>();
}

// TEST_F(GpuAddTest, AddV2Half) { RunAddOp<Eigen::half, float>(); }
}  // namespace
}  // end namespace tensorflow
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dbptools.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:28:47 $
 *
 *  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 _EXTENSIONS_DBP_DBPTOOLS_HXX_
#define _EXTENSIONS_DBP_DBPTOOLS_HXX_

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

//.........................................................................
namespace dbp
{
//.........................................................................

    void disambiguateName(
        const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxContainer,
        ::rtl::OUString& _rElementsName);

//.........................................................................
}   // namespace dbp
//.........................................................................

#endif // _EXTENSIONS_DBP_DBPTOOLS_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.3.472); FILE MERGED 2008/04/01 12:29:43 thb 1.3.472.2: #i85898# Stripping all external header guards 2008/03/31 12:31:27 rt 1.3.472.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: dbptools.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 _EXTENSIONS_DBP_DBPTOOLS_HXX_
#define _EXTENSIONS_DBP_DBPTOOLS_HXX_

#include <com/sun/star/container/XNameAccess.hpp>

//.........................................................................
namespace dbp
{
//.........................................................................

    void disambiguateName(
        const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxContainer,
        ::rtl::OUString& _rElementsName);

//.........................................................................
}   // namespace dbp
//.........................................................................

#endif // _EXTENSIONS_DBP_DBPTOOLS_HXX_

<|endoftext|>


<commit_before>#include "FileHelper.h"
#include "StringHelper.h"
#include "Config.h"

#include <wx/dir.h>
#include <wx/filename.h>

#include <set>

namespace ee
{

bool FileHelper::MkDir(const std::string& dir, bool rm)
{
	bool ret = true;
	if (wxDir::Exists(dir)) {
		if (rm) {
			wxFileName::Rmdir(dir, wxPATH_RMDIR_RECURSIVE);
			ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
		}
	} else {
		ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
	}
	return ret;
}

bool FileHelper::RmFile(const std::string& filepath)
{
	return wxRemoveFile(filepath);
}

bool FileHelper::IsFileExist(const std::string& filepath)
{
	return wxFileName::FileExists(filepath);
}

bool FileHelper::IsDirExist(const std::string& filepath)
{
	return wxFileName::DirExists(filepath);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(files);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, const std::string& ignore_dir, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, const wxString& ignore_dir)
			: m_files(files)
			, m_ignore_dir(ignore_dir)
		{}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			if (dirname == m_ignore_dir) {
				return wxDIR_IGNORE;
			} else {
				return wxDIR_CONTINUE;
			}
		}

	private:
		wxArrayString& m_files;
		std::string m_ignore_dir;

	}; // DirTraverser

	DirTraverser traverser(files, ignore_dir);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files, FileType::Type type)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, FileType::Type type)
			: files(files), type(type) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			if (FileType::IsType(filename.ToStdString(), type)) {
				files.Add(filename);
			}
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& files;
		FileType::Type type;

	}; // DirTraverser

	DirTraverser traverser(files, type);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchCurrDirs(const std::string& dirpath, wxArrayString& dirs)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			m_files.Add(dirname);
			return wxDIR_IGNORE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(dirs);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

std::string FileHelper::GetFilenameAddTag(const std::string& filename, const std::string& tag,
									   const std::string& extension)
{
	std::string fixed;
	int start = filename.find_last_of('_');
	if (start != -1)
	{
		std::string check = filename.substr(start + 1, filename.find_last_of('.') - start - 1);
		if (check == tag) {
			fixed = filename;
		} else if (filename[0] == '.') {
			fixed = filename + wxT("_" + tag + "." + extension);
		} else {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		}
	}
	else
	{
		if (filename[0] == '.') {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		} else {
			int dot_pos = filename.find_last_of('.');
			if (dot_pos == -1) {
				fixed = filename + wxT("_" + tag + "." + extension);
			} else {
				fixed = filename;
				fixed.insert(dot_pos, "_" + tag);
			}
		}
	}
	return fixed;
}

std::string FileHelper::GetFilenameTag(const std::string& filepath)
{
	const size_t start = filepath.find_last_of('_') + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilename(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	const size_t start = pos_divide + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilenameWithExtension(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	return filepath.substr(pos_divide + 1);
}

std::string FileHelper::GetDirName(const std::string& dir)
{
	return GetFilenameWithExtension(dir);
}

std::string FileHelper::GetRelativePath(const std::string& dir, const std::string& absolute)
{
	wxFileName filename(absolute);
	filename.MakeRelativeTo(dir);
	return filename.GetFullPath().Lower().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& dir, const std::string& relative)
{
	wxFileName filename(relative);
	filename.MakeAbsolute(dir);
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& filepath)
{
	wxFileName filename(filepath);
#ifndef _DEBUG
	wxStandardPathsBase& stdp = wxStandardPaths::Get();
	std::string exe_path = stdp.GetExecutablePath();
	filename.MakeAbsolute(GetFileDir(exe_path));
#endif
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePathFromFile(const std::string& base, const std::string& relative)
{
	std::string dir = FileHelper::GetFileDir(base);
	return FileHelper::GetAbsolutePath(dir, relative);
}

std::string FileHelper::GetFilePathExceptExtension(const std::string& filepath)
{
	return filepath.substr(0, filepath.find_last_of('.'));
}

std::string FileHelper::GetExtension(const std::string& filepath)
{
	return filepath.substr(filepath.find_last_of('.') + 1);
}

std::string FileHelper::GetFileDir(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	if (pos_divide == -1) {
		return ".";
	} else {
		return filepath.substr(0, pos_divide);
	}
}

std::string FileHelper::GetExistFilepath(const std::string& filepath, const std::string& dir /*= wxEmptyString*/)
{
	std::string fixed = filepath;
	if (!IsFileExist(fixed))
	{
		std::string filename = fixed = GetFilenameWithExtension(fixed);
		if (!IsFileExist(fixed))
		{
			std::string cwd = wxFileName::GetCwd();

			Config* cfg = Config::Instance();
			std::set<std::string>::const_iterator
				itr = cfg->GetResPathes().begin();
			for ( ; itr != cfg->GetResPathes().end(); ++itr)
			{
				fixed = *itr + filename;
				if (IsFileExist(fixed))
					return fixed;

				fixed = cwd + *itr + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
			if (dir != wxEmptyString)
			{
				fixed = dir + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
// 			throw Exception("File: %s don't exist!", filepath.ToStdString().c_str());
			return "";
		}
		else
		{
			return fixed;
		}
	}
	else
	{
		return fixed;
	}
}

void FileHelper::FormatSeparators(std::string& filepath)
{
	const std::string oldVal = "/", newVal = "\\";
	for(std::string::size_type pos(0); pos != std::string::npos; pos += oldVal.length())
	{
		if((pos = filepath.find(oldVal, pos)) != std::string::npos)
			filepath.replace(pos, oldVal.length(), newVal);
		else
			break;
	}
}

std::string FileHelper::FormatFilepath(const std::string& filepath)
{
	std::string ret = filepath;
	StringHelper::ToLower(ret);
	FormatSeparators(ret);
	return ret;
}

std::string FileHelper::FormatFilepathAbsolute(const std::string& filepath)
{
	wxFileName filename(FormatFilepath(filepath));
	filename.Normalize();
	return filename.GetFullPath().Lower().ToStdString();
}

}<commit_msg>[FIXED] compile release<commit_after>#include "FileHelper.h"
#include "StringHelper.h"
#include "Config.h"

#include <wx/dir.h>
#include <wx/filename.h>
#ifndef _DEBUG
#include <wx/stdpaths.h>
#endif // _DEBUG

#include <set>

namespace ee
{

bool FileHelper::MkDir(const std::string& dir, bool rm)
{
	bool ret = true;
	if (wxDir::Exists(dir)) {
		if (rm) {
			wxFileName::Rmdir(dir, wxPATH_RMDIR_RECURSIVE);
			ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
		}
	} else {
		ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
	}
	return ret;
}

bool FileHelper::RmFile(const std::string& filepath)
{
	return wxRemoveFile(filepath);
}

bool FileHelper::IsFileExist(const std::string& filepath)
{
	return wxFileName::FileExists(filepath);
}

bool FileHelper::IsDirExist(const std::string& filepath)
{
	return wxFileName::DirExists(filepath);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(files);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, const std::string& ignore_dir, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, const wxString& ignore_dir)
			: m_files(files)
			, m_ignore_dir(ignore_dir)
		{}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			if (dirname == m_ignore_dir) {
				return wxDIR_IGNORE;
			} else {
				return wxDIR_CONTINUE;
			}
		}

	private:
		wxArrayString& m_files;
		std::string m_ignore_dir;

	}; // DirTraverser

	DirTraverser traverser(files, ignore_dir);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files, FileType::Type type)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, FileType::Type type)
			: files(files), type(type) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			if (FileType::IsType(filename.ToStdString(), type)) {
				files.Add(filename);
			}
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& files;
		FileType::Type type;

	}; // DirTraverser

	DirTraverser traverser(files, type);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchCurrDirs(const std::string& dirpath, wxArrayString& dirs)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			m_files.Add(dirname);
			return wxDIR_IGNORE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(dirs);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

std::string FileHelper::GetFilenameAddTag(const std::string& filename, const std::string& tag,
									   const std::string& extension)
{
	std::string fixed;
	int start = filename.find_last_of('_');
	if (start != -1)
	{
		std::string check = filename.substr(start + 1, filename.find_last_of('.') - start - 1);
		if (check == tag) {
			fixed = filename;
		} else if (filename[0] == '.') {
			fixed = filename + wxT("_" + tag + "." + extension);
		} else {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		}
	}
	else
	{
		if (filename[0] == '.') {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		} else {
			int dot_pos = filename.find_last_of('.');
			if (dot_pos == -1) {
				fixed = filename + wxT("_" + tag + "." + extension);
			} else {
				fixed = filename;
				fixed.insert(dot_pos, "_" + tag);
			}
		}
	}
	return fixed;
}

std::string FileHelper::GetFilenameTag(const std::string& filepath)
{
	const size_t start = filepath.find_last_of('_') + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilename(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	const size_t start = pos_divide + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilenameWithExtension(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	return filepath.substr(pos_divide + 1);
}

std::string FileHelper::GetDirName(const std::string& dir)
{
	return GetFilenameWithExtension(dir);
}

std::string FileHelper::GetRelativePath(const std::string& dir, const std::string& absolute)
{
	wxFileName filename(absolute);
	filename.MakeRelativeTo(dir);
	return filename.GetFullPath().Lower().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& dir, const std::string& relative)
{
	wxFileName filename(relative);
	filename.MakeAbsolute(dir);
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& filepath)
{
	wxFileName filename(filepath);
#ifndef _DEBUG
	wxStandardPathsBase& stdp = wxStandardPaths::Get();
	std::string exe_path = stdp.GetExecutablePath();
	filename.MakeAbsolute(GetFileDir(exe_path));
#endif
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePathFromFile(const std::string& base, const std::string& relative)
{
	std::string dir = FileHelper::GetFileDir(base);
	return FileHelper::GetAbsolutePath(dir, relative);
}

std::string FileHelper::GetFilePathExceptExtension(const std::string& filepath)
{
	return filepath.substr(0, filepath.find_last_of('.'));
}

std::string FileHelper::GetExtension(const std::string& filepath)
{
	return filepath.substr(filepath.find_last_of('.') + 1);
}

std::string FileHelper::GetFileDir(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	if (pos_divide == -1) {
		return ".";
	} else {
		return filepath.substr(0, pos_divide);
	}
}

std::string FileHelper::GetExistFilepath(const std::string& filepath, const std::string& dir /*= wxEmptyString*/)
{
	std::string fixed = filepath;
	if (!IsFileExist(fixed))
	{
		std::string filename = fixed = GetFilenameWithExtension(fixed);
		if (!IsFileExist(fixed))
		{
			std::string cwd = wxFileName::GetCwd();

			Config* cfg = Config::Instance();
			std::set<std::string>::const_iterator
				itr = cfg->GetResPathes().begin();
			for ( ; itr != cfg->GetResPathes().end(); ++itr)
			{
				fixed = *itr + filename;
				if (IsFileExist(fixed))
					return fixed;

				fixed = cwd + *itr + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
			if (dir != wxEmptyString)
			{
				fixed = dir + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
// 			throw Exception("File: %s don't exist!", filepath.ToStdString().c_str());
			return "";
		}
		else
		{
			return fixed;
		}
	}
	else
	{
		return fixed;
	}
}

void FileHelper::FormatSeparators(std::string& filepath)
{
	const std::string oldVal = "/", newVal = "\\";
	for(std::string::size_type pos(0); pos != std::string::npos; pos += oldVal.length())
	{
		if((pos = filepath.find(oldVal, pos)) != std::string::npos)
			filepath.replace(pos, oldVal.length(), newVal);
		else
			break;
	}
}

std::string FileHelper::FormatFilepath(const std::string& filepath)
{
	std::string ret = filepath;
	StringHelper::ToLower(ret);
	FormatSeparators(ret);
	return ret;
}

std::string FileHelper::FormatFilepathAbsolute(const std::string& filepath)
{
	wxFileName filename(FormatFilepath(filepath));
	filename.Normalize();
	return filename.GetFullPath().Lower().ToStdString();
}

}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__

#include "base/bitunion.hh"

namespace ArmISA
{
    enum ConditionCode {
        COND_EQ  =   0,
        COND_NE, //  1
        COND_CS, //  2
        COND_CC, //  3
        COND_MI, //  4
        COND_PL, //  5
        COND_VS, //  6
        COND_VC, //  7
        COND_HI, //  8
        COND_LS, //  9
        COND_GE, // 10
        COND_LT, // 11
        COND_GT, // 12
        COND_LE, // 13
        COND_AL, // 14
        COND_UC  // 15
    };

    enum MiscRegIndex {
        MISCREG_CPSR = 0,
        MISCREG_SPSR,
        MISCREG_SPSR_FIQ,
        MISCREG_SPSR_IRQ,
        MISCREG_SPSR_SVC,
        MISCREG_SPSR_MON,
        MISCREG_SPSR_UND,
        MISCREG_SPSR_ABT,
        MISCREG_FPSR,
        MISCREG_FPSID,
        MISCREG_FPSCR,
        MISCREG_FPEXC,
        MISCREG_MVFR0,
        MISCREG_MVFR1,
        MISCREG_SEV_MAILBOX,

        // CP15 registers
        MISCREG_CP15_START,
        MISCREG_SCTLR = MISCREG_CP15_START,
        MISCREG_DCCISW,
        MISCREG_DCCIMVAC,
        MISCREG_DCCMVAC,
        MISCREG_CONTEXTIDR,
        MISCREG_TPIDRURW,
        MISCREG_TPIDRURO,
        MISCREG_TPIDRPRW,
        MISCREG_CP15ISB,
        MISCREG_CP15DSB,
        MISCREG_CP15DMB,
        MISCREG_CPACR,
        MISCREG_CLIDR,
        MISCREG_CCSIDR,
        MISCREG_CSSELR,
        MISCREG_ICIALLUIS,
        MISCREG_ICIALLU,
        MISCREG_ICIMVAU,
        MISCREG_BPIMVA,
        MISCREG_BPIALLIS,
        MISCREG_BPIALL,
        MISCREG_MIDR,
        MISCREG_CP15_UNIMP_START,
        MISCREG_CTR = MISCREG_CP15_UNIMP_START,
        MISCREG_TLBTR,
        MISCREG_TCMTR,
        MISCREG_MPIDR,
        MISCREG_ID_PFR0,
        MISCREG_ID_PFR1,
        MISCREG_ID_DFR0,
        MISCREG_ID_AFR0,
        MISCREG_ID_MMFR0,
        MISCREG_ID_MMFR1,
        MISCREG_ID_MMFR2,
        MISCREG_ID_MMFR3,
        MISCREG_ID_ISAR0,
        MISCREG_ID_ISAR1,
        MISCREG_ID_ISAR2,
        MISCREG_ID_ISAR3,
        MISCREG_ID_ISAR4,
        MISCREG_ID_ISAR5,
        MISCREG_PAR,
        MISCREG_AIDR,
        MISCREG_ACTLR,
        MISCREG_DACR,
        MISCREG_DFSR,
        MISCREG_IFSR,
        MISCREG_ADFSR,
        MISCREG_AIFSR,
        MISCREG_DFAR,
        MISCREG_IFAR,
        MISCREG_DCIMVAC,
        MISCREG_DCISW,
        MISCREG_MCCSW,
        MISCREG_DCCMVAU,
        MISCREG_SCR,
        MISCREG_SDER,
        MISCREG_NSACR,
        MISCREG_TTBR0,
        MISCREG_TTBR1,
        MISCREG_TTBCR,
        MISCREG_V2PCWPR,
        MISCREG_V2PCWPW,
        MISCREG_V2PCWUR,
        MISCREG_V2PCWUW,
        MISCREG_V2POWPR,
        MISCREG_V2POWPW,
        MISCREG_V2POWUR,
        MISCREG_V2POWUW,
        MISCREG_TLBIALLIS,
        MISCREG_TLBIMVAIS,
        MISCREG_TLBIASIDIS,
        MISCREG_TLBIMVAAIS,
        MISCREG_ITLBIALL,
        MISCREG_ITLBIMVA,
        MISCREG_ITLBIASID,
        MISCREG_DTLBIALL,
        MISCREG_DTLBIMVA,
        MISCREG_DTLBIASID,
        MISCREG_TLBIALL,
        MISCREG_TLBIMVA,
        MISCREG_TLBIASID,
        MISCREG_TLBIMVAA,
        MISCREG_PRRR,
        MISCREG_NMRR,
        MISCREG_VBAR,
        MISCREG_MVBAR,
        MISCREG_ISR,
        MISCREG_FCEIDR,

        MISCREG_CP15_END,

        // Dummy indices
        MISCREG_NOP = MISCREG_CP15_END,
        MISCREG_RAZ,

        NUM_MISCREGS
    };

    MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
                               unsigned crm, unsigned opc2);

    const char * const miscRegName[NUM_MISCREGS] = {
        "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
        "spsr_mon", "spsr_und", "spsr_abt",
        "fpsr", "fpsid", "fpscr", "fpexc", "mvfr0", "mvfr1",
        "sev_mailbox",
        "sctlr", "dccisw", "dccimvac", "dccmvac",
        "contextidr", "tpidrurw", "tpidruro", "tpidrprw",
        "cp15isb", "cp15dsb", "cp15dmb", "cpacr",
        "clidr", "ccsidr", "csselr",
        "icialluis", "iciallu", "icimvau",
        "bpimva", "bpiallis", "bpiall",
        "midr", "ctr", "tlbtr", "tcmtr", "mpidr",
        "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
        "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
        "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
        "par", "aidr", "actlr", "dacr",
        "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
        "dcimvac", "dcisw", "mccsw",
        "dccmvau",
        "scr", "sder", "nsacr", "ttbr0", "ttbr1", "ttbcr",
        "v2pcwpr", "v2pcwpw", "v2pcwur", "v2pcwuw",
        "v2powpr", "v2powpw", "v2powur", "v2powuw",
        "tlbiallis", "tlbimvais", "tlbiasidis", "tlbimvaais",
        "itlbiall", "itlbimva", "itlbiasid",
        "dtlbiall", "dtlbimva", "dtlbiasid",
        "tlbiall", "tlbimva", "tlbiasid", "tlbimvaa",
        "prrr", "nmrr", "vbar", "mvbar", "isr", "fceidr",
        "nop", "raz"
    };

    BitUnion32(CPSR)
        Bitfield<31> n;
        Bitfield<30> z;
        Bitfield<29> c;
        Bitfield<28> v;
        Bitfield<27> q;
        Bitfield<26,25> it1;
        Bitfield<24> j;
        Bitfield<19, 16> ge;
        Bitfield<15,10> it2;
        Bitfield<9> e;
        Bitfield<8> a;
        Bitfield<7> i;
        Bitfield<6> f;
        Bitfield<5> t;
        Bitfield<4, 0> mode;
    EndBitUnion(CPSR)

    // This mask selects bits of the CPSR that actually go in the CondCodes
    // integer register to allow renaming.
    static const uint32_t CondCodesMask = 0xF80F0000;

    BitUnion32(SCTLR)
        Bitfield<30> te;  // Thumb Exception Enable
        Bitfield<29> afe; // Access flag enable
        Bitfield<28> tre; // TEX Remap bit
        Bitfield<27> nmfi;// Non-maskable fast interrupts enable
        Bitfield<25> ee;  // Exception Endianness bit
        Bitfield<24> ve;  // Interrupt vectors enable
        Bitfield<23> rao1;// Read as one
        Bitfield<22> u;   // Alignment (now unused)
        Bitfield<21> fi;  // Fast interrupts configuration enable
        Bitfield<18> rao2;// Read as one
        Bitfield<17> ha;  // Hardware access flag enable
        Bitfield<16> rao3;// Read as one
        Bitfield<14> rr;  // Round robin cache replacement
        Bitfield<13> v;   // Base address for exception vectors
        Bitfield<12> i;   // instruction cache enable
        Bitfield<11> z;   // branch prediction enable bit
        Bitfield<10> sw;  // Enable swp/swpb
        Bitfield<6,3> rao4;// Read as one
        Bitfield<7>  b;   // Endianness support (unused)
        Bitfield<2>  c;   // Cache enable bit
        Bitfield<1>  a;   // Alignment fault checking
        Bitfield<0>  m;   // MMU enable bit
    EndBitUnion(SCTLR)

    BitUnion32(CPACR)
        Bitfield<1, 0> cp0;
        Bitfield<3, 2> cp1;
        Bitfield<5, 4> cp2;
        Bitfield<7, 6> cp3;
        Bitfield<9, 8> cp4;
        Bitfield<11, 10> cp5;
        Bitfield<13, 12> cp6;
        Bitfield<15, 14> cp7;
        Bitfield<17, 16> cp8;
        Bitfield<19, 18> cp9;
        Bitfield<21, 20> cp10;
        Bitfield<23, 22> cp11;
        Bitfield<25, 24> cp12;
        Bitfield<27, 26> cp13;
        Bitfield<30> d32dis;
        Bitfield<31> asedis;
    EndBitUnion(CPACR)
};

#endif // __ARCH_ARM_MISCREGS_HH__
<commit_msg>ARM: Handle accesses to TTBR0 and TTBR1.<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2009 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */
#ifndef __ARCH_ARM_MISCREGS_HH__
#define __ARCH_ARM_MISCREGS_HH__

#include "base/bitunion.hh"

namespace ArmISA
{
    enum ConditionCode {
        COND_EQ  =   0,
        COND_NE, //  1
        COND_CS, //  2
        COND_CC, //  3
        COND_MI, //  4
        COND_PL, //  5
        COND_VS, //  6
        COND_VC, //  7
        COND_HI, //  8
        COND_LS, //  9
        COND_GE, // 10
        COND_LT, // 11
        COND_GT, // 12
        COND_LE, // 13
        COND_AL, // 14
        COND_UC  // 15
    };

    enum MiscRegIndex {
        MISCREG_CPSR = 0,
        MISCREG_SPSR,
        MISCREG_SPSR_FIQ,
        MISCREG_SPSR_IRQ,
        MISCREG_SPSR_SVC,
        MISCREG_SPSR_MON,
        MISCREG_SPSR_UND,
        MISCREG_SPSR_ABT,
        MISCREG_FPSR,
        MISCREG_FPSID,
        MISCREG_FPSCR,
        MISCREG_FPEXC,
        MISCREG_MVFR0,
        MISCREG_MVFR1,
        MISCREG_SEV_MAILBOX,

        // CP15 registers
        MISCREG_CP15_START,
        MISCREG_SCTLR = MISCREG_CP15_START,
        MISCREG_DCCISW,
        MISCREG_DCCIMVAC,
        MISCREG_DCCMVAC,
        MISCREG_CONTEXTIDR,
        MISCREG_TPIDRURW,
        MISCREG_TPIDRURO,
        MISCREG_TPIDRPRW,
        MISCREG_CP15ISB,
        MISCREG_CP15DSB,
        MISCREG_CP15DMB,
        MISCREG_CPACR,
        MISCREG_CLIDR,
        MISCREG_CCSIDR,
        MISCREG_CSSELR,
        MISCREG_ICIALLUIS,
        MISCREG_ICIALLU,
        MISCREG_ICIMVAU,
        MISCREG_BPIMVA,
        MISCREG_BPIALLIS,
        MISCREG_BPIALL,
        MISCREG_MIDR,
        MISCREG_TTBR0,
        MISCREG_TTBR1,
        MISCREG_CP15_UNIMP_START,
        MISCREG_CTR = MISCREG_CP15_UNIMP_START,
        MISCREG_TLBTR,
        MISCREG_TCMTR,
        MISCREG_MPIDR,
        MISCREG_ID_PFR0,
        MISCREG_ID_PFR1,
        MISCREG_ID_DFR0,
        MISCREG_ID_AFR0,
        MISCREG_ID_MMFR0,
        MISCREG_ID_MMFR1,
        MISCREG_ID_MMFR2,
        MISCREG_ID_MMFR3,
        MISCREG_ID_ISAR0,
        MISCREG_ID_ISAR1,
        MISCREG_ID_ISAR2,
        MISCREG_ID_ISAR3,
        MISCREG_ID_ISAR4,
        MISCREG_ID_ISAR5,
        MISCREG_PAR,
        MISCREG_AIDR,
        MISCREG_ACTLR,
        MISCREG_DACR,
        MISCREG_DFSR,
        MISCREG_IFSR,
        MISCREG_ADFSR,
        MISCREG_AIFSR,
        MISCREG_DFAR,
        MISCREG_IFAR,
        MISCREG_DCIMVAC,
        MISCREG_DCISW,
        MISCREG_MCCSW,
        MISCREG_DCCMVAU,
        MISCREG_SCR,
        MISCREG_SDER,
        MISCREG_NSACR,
        MISCREG_TTBCR,
        MISCREG_V2PCWPR,
        MISCREG_V2PCWPW,
        MISCREG_V2PCWUR,
        MISCREG_V2PCWUW,
        MISCREG_V2POWPR,
        MISCREG_V2POWPW,
        MISCREG_V2POWUR,
        MISCREG_V2POWUW,
        MISCREG_TLBIALLIS,
        MISCREG_TLBIMVAIS,
        MISCREG_TLBIASIDIS,
        MISCREG_TLBIMVAAIS,
        MISCREG_ITLBIALL,
        MISCREG_ITLBIMVA,
        MISCREG_ITLBIASID,
        MISCREG_DTLBIALL,
        MISCREG_DTLBIMVA,
        MISCREG_DTLBIASID,
        MISCREG_TLBIALL,
        MISCREG_TLBIMVA,
        MISCREG_TLBIASID,
        MISCREG_TLBIMVAA,
        MISCREG_PRRR,
        MISCREG_NMRR,
        MISCREG_VBAR,
        MISCREG_MVBAR,
        MISCREG_ISR,
        MISCREG_FCEIDR,

        MISCREG_CP15_END,

        // Dummy indices
        MISCREG_NOP = MISCREG_CP15_END,
        MISCREG_RAZ,

        NUM_MISCREGS
    };

    MiscRegIndex decodeCP15Reg(unsigned crn, unsigned opc1,
                               unsigned crm, unsigned opc2);

    const char * const miscRegName[NUM_MISCREGS] = {
        "cpsr", "spsr", "spsr_fiq", "spsr_irq", "spsr_svc",
        "spsr_mon", "spsr_und", "spsr_abt",
        "fpsr", "fpsid", "fpscr", "fpexc", "mvfr0", "mvfr1",
        "sev_mailbox",
        "sctlr", "dccisw", "dccimvac", "dccmvac",
        "contextidr", "tpidrurw", "tpidruro", "tpidrprw",
        "cp15isb", "cp15dsb", "cp15dmb", "cpacr",
        "clidr", "ccsidr", "csselr",
        "icialluis", "iciallu", "icimvau",
        "bpimva", "bpiallis", "bpiall",
        "midr", "ttbr0", "ttbr1", "ctr", "tlbtr", "tcmtr", "mpidr",
        "id_pfr0", "id_pfr1", "id_dfr0", "id_afr0",
        "id_mmfr0", "id_mmfr1", "id_mmfr2", "id_mmfr3",
        "id_isar0", "id_isar1", "id_isar2", "id_isar3", "id_isar4", "id_isar5",
        "par", "aidr", "actlr", "dacr",
        "dfsr", "ifsr", "adfsr", "aifsr", "dfar", "ifar",
        "dcimvac", "dcisw", "mccsw",
        "dccmvau",
        "scr", "sder", "nsacr", "ttbcr",
        "v2pcwpr", "v2pcwpw", "v2pcwur", "v2pcwuw",
        "v2powpr", "v2powpw", "v2powur", "v2powuw",
        "tlbiallis", "tlbimvais", "tlbiasidis", "tlbimvaais",
        "itlbiall", "itlbimva", "itlbiasid",
        "dtlbiall", "dtlbimva", "dtlbiasid",
        "tlbiall", "tlbimva", "tlbiasid", "tlbimvaa",
        "prrr", "nmrr", "vbar", "mvbar", "isr", "fceidr",
        "nop", "raz"
    };

    BitUnion32(CPSR)
        Bitfield<31> n;
        Bitfield<30> z;
        Bitfield<29> c;
        Bitfield<28> v;
        Bitfield<27> q;
        Bitfield<26,25> it1;
        Bitfield<24> j;
        Bitfield<19, 16> ge;
        Bitfield<15,10> it2;
        Bitfield<9> e;
        Bitfield<8> a;
        Bitfield<7> i;
        Bitfield<6> f;
        Bitfield<5> t;
        Bitfield<4, 0> mode;
    EndBitUnion(CPSR)

    // This mask selects bits of the CPSR that actually go in the CondCodes
    // integer register to allow renaming.
    static const uint32_t CondCodesMask = 0xF80F0000;

    BitUnion32(SCTLR)
        Bitfield<30> te;  // Thumb Exception Enable
        Bitfield<29> afe; // Access flag enable
        Bitfield<28> tre; // TEX Remap bit
        Bitfield<27> nmfi;// Non-maskable fast interrupts enable
        Bitfield<25> ee;  // Exception Endianness bit
        Bitfield<24> ve;  // Interrupt vectors enable
        Bitfield<23> rao1;// Read as one
        Bitfield<22> u;   // Alignment (now unused)
        Bitfield<21> fi;  // Fast interrupts configuration enable
        Bitfield<18> rao2;// Read as one
        Bitfield<17> ha;  // Hardware access flag enable
        Bitfield<16> rao3;// Read as one
        Bitfield<14> rr;  // Round robin cache replacement
        Bitfield<13> v;   // Base address for exception vectors
        Bitfield<12> i;   // instruction cache enable
        Bitfield<11> z;   // branch prediction enable bit
        Bitfield<10> sw;  // Enable swp/swpb
        Bitfield<6,3> rao4;// Read as one
        Bitfield<7>  b;   // Endianness support (unused)
        Bitfield<2>  c;   // Cache enable bit
        Bitfield<1>  a;   // Alignment fault checking
        Bitfield<0>  m;   // MMU enable bit
    EndBitUnion(SCTLR)

    BitUnion32(CPACR)
        Bitfield<1, 0> cp0;
        Bitfield<3, 2> cp1;
        Bitfield<5, 4> cp2;
        Bitfield<7, 6> cp3;
        Bitfield<9, 8> cp4;
        Bitfield<11, 10> cp5;
        Bitfield<13, 12> cp6;
        Bitfield<15, 14> cp7;
        Bitfield<17, 16> cp8;
        Bitfield<19, 18> cp9;
        Bitfield<21, 20> cp10;
        Bitfield<23, 22> cp11;
        Bitfield<25, 24> cp12;
        Bitfield<27, 26> cp13;
        Bitfield<30> d32dis;
        Bitfield<31> asedis;
    EndBitUnion(CPACR)
};

#endif // __ARCH_ARM_MISCREGS_HH__
<|endoftext|>


<commit_before>//===-- FormattersHelpers.cpp -------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// C Includes

// C++ Includes

// Other libraries and framework includes

// Project includes
#include "lldb/DataFormatters/FormattersHelpers.h"

#include "lldb/Core/ConstString.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"

using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::formatters;

void
lldb_private::formatters::AddFormat (TypeCategoryImpl::SharedPointer category_sp,
                                     lldb::Format format,
                                     ConstString type_name,
                                     TypeFormatImpl::Flags flags,
                                     bool regex)
{
    lldb::TypeFormatImplSP format_sp(new TypeFormatImpl_Format(format, flags));

    if (regex)
        category_sp->GetRegexTypeFormatsContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),format_sp);
    else
        category_sp->GetTypeFormatsContainer()->Add(type_name, format_sp);
}

void
lldb_private::formatters::AddSummary(TypeCategoryImpl::SharedPointer category_sp,
                                     TypeSummaryImplSP summary_sp,
                                     ConstString type_name,
                                     bool regex)
{
    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

void
lldb_private::formatters::AddStringSummary(TypeCategoryImpl::SharedPointer category_sp,
                                           const char* string,
                                           ConstString type_name,
                                           TypeSummaryImpl::Flags flags,
                                           bool regex)
{
    lldb::TypeSummaryImplSP summary_sp(new StringSummaryFormat(flags,
                                                               string));

    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

void
lldb_private::formatters::AddOneLineSummary (TypeCategoryImpl::SharedPointer category_sp,
                                             ConstString type_name,
                                             TypeSummaryImpl::Flags flags,
                                             bool regex)
{
    flags.SetShowMembersOneLiner(true);
    lldb::TypeSummaryImplSP summary_sp(new StringSummaryFormat(flags, ""));

    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

#ifndef LLDB_DISABLE_PYTHON
void
lldb_private::formatters::AddCXXSummary (TypeCategoryImpl::SharedPointer category_sp,
                                         CXXFunctionSummaryFormat::Callback funct,
                                         const char* description,
                                         ConstString type_name,
                                         TypeSummaryImpl::Flags flags,
                                         bool regex)
{
    lldb::TypeSummaryImplSP summary_sp(new CXXFunctionSummaryFormat(flags,funct,description));
    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

void
lldb_private::formatters::AddCXXSynthetic  (TypeCategoryImpl::SharedPointer category_sp,
                                            CXXSyntheticChildren::CreateFrontEndCallback generator,
                                            const char* description,
                                            ConstString type_name,
                                            ScriptedSyntheticChildren::Flags flags,
                                            bool regex)
{
    lldb::SyntheticChildrenSP synth_sp(new CXXSyntheticChildren(flags,description,generator));
    if (regex)
        category_sp->GetRegexTypeSyntheticsContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())), synth_sp);
    else
        category_sp->GetTypeSyntheticsContainer()->Add(type_name,synth_sp);
}

void
lldb_private::formatters::AddFilter  (TypeCategoryImpl::SharedPointer category_sp,
                                      std::vector<std::string> children,
                                      const char* description,
                                      ConstString type_name,
                                      ScriptedSyntheticChildren::Flags flags,
                                      bool regex)
{
    TypeFilterImplSP filter_sp(new TypeFilterImpl(flags));
    for (auto child : children)
        filter_sp->AddExpressionPath(child);
    if (regex)
        category_sp->GetRegexTypeFiltersContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())), filter_sp);
    else
        category_sp->GetTypeFiltersContainer()->Add(type_name,filter_sp);
}
#endif

StackFrame*
lldb_private::formatters::GetViableFrame (ExecutionContext exe_ctx)
{
    StackFrame* frame = exe_ctx.GetFramePtr();
    if (frame)
        return frame;

    Process* process = exe_ctx.GetProcessPtr();
    if (!process)
        return nullptr;

    ThreadSP thread_sp(process->GetThreadList().GetSelectedThread());
    if (thread_sp)
        return thread_sp->GetSelectedFrame().get();
    return nullptr;
}

bool
lldb_private::formatters::ExtractValueFromObjCExpression (ValueObject &valobj,
                                                          const char* target_type,
                                                          const char* selector,
                                                          uint64_t &value)
{
    if (!target_type || !*target_type)
        return false;
    if (!selector || !*selector)
        return false;
    StreamString expr;
    expr.Printf("(%s)[(id)0x%" PRIx64 " %s]",target_type,valobj.GetPointerValue(),selector);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return false;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               result_sp,
                               options);
    if (!result_sp)
        return false;
    value = result_sp->GetValueAsUnsigned(0);
    return true;
}

bool
lldb_private::formatters::ExtractSummaryFromObjCExpression (ValueObject &valobj,
                                                            const char* target_type,
                                                            const char* selector,
                                                            Stream &stream,
                                                            lldb::LanguageType lang_type)
{
    if (!target_type || !*target_type)
        return false;
    if (!selector || !*selector)
        return false;
    StreamString expr;
    expr.Printf("(%s)[(id)0x%" PRIx64 " %s]",target_type,valobj.GetPointerValue(),selector);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return false;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);
    options.SetLanguage(lldb::eLanguageTypeObjC_plus_plus);
    options.SetResultIsInternal(true);
    options.SetUseDynamic(lldb::eDynamicCanRunTarget);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               result_sp,
                               options);
    if (!result_sp)
        return false;
    stream.Printf("%s",result_sp->GetSummaryAsCString(lang_type));
    return true;
}

lldb::ValueObjectSP
lldb_private::formatters::CallSelectorOnObject (ValueObject &valobj,
                                                const char* return_type,
                                                const char* selector,
                                                uint64_t index)
{
    lldb::ValueObjectSP valobj_sp;
    if (!return_type || !*return_type)
        return valobj_sp;
    if (!selector || !*selector)
        return valobj_sp;
    StreamString expr_path_stream;
    valobj.GetExpressionPath(expr_path_stream, false);
    StreamString expr;
    expr.Printf("(%s)[%s %s:%" PRId64 "]",return_type,expr_path_stream.GetData(),selector,index);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return valobj_sp;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);
    options.SetUseDynamic(lldb::eDynamicCanRunTarget);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               valobj_sp,
                               options);
    return valobj_sp;
}

lldb::ValueObjectSP
lldb_private::formatters::CallSelectorOnObject (ValueObject &valobj,
                                                const char* return_type,
                                                const char* selector,
                                                const char* key)
{
    lldb::ValueObjectSP valobj_sp;
    if (!return_type || !*return_type)
        return valobj_sp;
    if (!selector || !*selector)
        return valobj_sp;
    if (!key || !*key)
        return valobj_sp;
    StreamString expr_path_stream;
    valobj.GetExpressionPath(expr_path_stream, false);
    StreamString expr;
    expr.Printf("(%s)[%s %s:%s]",return_type,expr_path_stream.GetData(),selector,key);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return valobj_sp;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);
    options.SetUseDynamic(lldb::eDynamicCanRunTarget);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               valobj_sp,
                               options);
    return valobj_sp;
}

size_t
lldb_private::formatters::ExtractIndexFromString (const char* item_name)
{
    if (!item_name || !*item_name)
        return UINT32_MAX;
    if (*item_name != '[')
        return UINT32_MAX;
    item_name++;
    char* endptr = NULL;
    unsigned long int idx = ::strtoul(item_name, &endptr, 0);
    if (idx == 0 && endptr == item_name)
        return UINT32_MAX;
    if (idx == ULONG_MAX)
        return UINT32_MAX;
    return idx;
}

lldb::addr_t
lldb_private::formatters::GetArrayAddressOrPointerValue (ValueObject& valobj)
{
    lldb::addr_t data_addr = LLDB_INVALID_ADDRESS;

    if (valobj.IsPointerType())
        data_addr = valobj.GetValueAsUnsigned(0);
    else if (valobj.IsArrayType())
        data_addr = valobj.GetAddressOf();

    return data_addr;
}
<commit_msg>Upstream some data formatter related cleanups<commit_after>//===-- FormattersHelpers.cpp -------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// C Includes

// C++ Includes

// Other libraries and framework includes

// Project includes
#include "lldb/DataFormatters/FormattersHelpers.h"

#include "lldb/Core/ConstString.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"

using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::formatters;

void
lldb_private::formatters::AddFormat (TypeCategoryImpl::SharedPointer category_sp,
                                     lldb::Format format,
                                     ConstString type_name,
                                     TypeFormatImpl::Flags flags,
                                     bool regex)
{
    lldb::TypeFormatImplSP format_sp(new TypeFormatImpl_Format(format, flags));

    if (regex)
        category_sp->GetRegexTypeFormatsContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),format_sp);
    else
        category_sp->GetTypeFormatsContainer()->Add(type_name, format_sp);
}

void
lldb_private::formatters::AddSummary(TypeCategoryImpl::SharedPointer category_sp,
                                     TypeSummaryImplSP summary_sp,
                                     ConstString type_name,
                                     bool regex)
{
    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

void
lldb_private::formatters::AddStringSummary(TypeCategoryImpl::SharedPointer category_sp,
                                           const char* string,
                                           ConstString type_name,
                                           TypeSummaryImpl::Flags flags,
                                           bool regex)
{
    lldb::TypeSummaryImplSP summary_sp(new StringSummaryFormat(flags,
                                                               string));

    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

void
lldb_private::formatters::AddOneLineSummary (TypeCategoryImpl::SharedPointer category_sp,
                                             ConstString type_name,
                                             TypeSummaryImpl::Flags flags,
                                             bool regex)
{
    flags.SetShowMembersOneLiner(true);
    lldb::TypeSummaryImplSP summary_sp(new StringSummaryFormat(flags, ""));

    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

#ifndef LLDB_DISABLE_PYTHON
void
lldb_private::formatters::AddCXXSummary (TypeCategoryImpl::SharedPointer category_sp,
                                         CXXFunctionSummaryFormat::Callback funct,
                                         const char* description,
                                         ConstString type_name,
                                         TypeSummaryImpl::Flags flags,
                                         bool regex)
{
    lldb::TypeSummaryImplSP summary_sp(new CXXFunctionSummaryFormat(flags,funct,description));
    if (regex)
        category_sp->GetRegexTypeSummariesContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())),summary_sp);
    else
        category_sp->GetTypeSummariesContainer()->Add(type_name, summary_sp);
}

void
lldb_private::formatters::AddCXXSynthetic  (TypeCategoryImpl::SharedPointer category_sp,
                                            CXXSyntheticChildren::CreateFrontEndCallback generator,
                                            const char* description,
                                            ConstString type_name,
                                            ScriptedSyntheticChildren::Flags flags,
                                            bool regex)
{
    lldb::SyntheticChildrenSP synth_sp(new CXXSyntheticChildren(flags,description,generator));
    if (regex)
        category_sp->GetRegexTypeSyntheticsContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())), synth_sp);
    else
        category_sp->GetTypeSyntheticsContainer()->Add(type_name,synth_sp);
}

void
lldb_private::formatters::AddFilter  (TypeCategoryImpl::SharedPointer category_sp,
                                      std::vector<std::string> children,
                                      const char* description,
                                      ConstString type_name,
                                      ScriptedSyntheticChildren::Flags flags,
                                      bool regex)
{
    TypeFilterImplSP filter_sp(new TypeFilterImpl(flags));
    for (auto child : children)
        filter_sp->AddExpressionPath(child);
    if (regex)
        category_sp->GetRegexTypeFiltersContainer()->Add(RegularExpressionSP(new RegularExpression(type_name.AsCString())), filter_sp);
    else
        category_sp->GetTypeFiltersContainer()->Add(type_name,filter_sp);
}
#endif

StackFrame*
lldb_private::formatters::GetViableFrame (ExecutionContext exe_ctx)
{
    StackFrame* frame = exe_ctx.GetFramePtr();
    if (frame)
        return frame;

    Process* process = exe_ctx.GetProcessPtr();
    if (!process)
        return nullptr;

    ThreadSP thread_sp(process->GetThreadList().GetSelectedThread());
    if (thread_sp)
        return thread_sp->GetSelectedFrame().get();
    return nullptr;
}

bool
lldb_private::formatters::ExtractValueFromObjCExpression (ValueObject &valobj,
                                                          const char* target_type,
                                                          const char* selector,
                                                          uint64_t &value)
{
    if (!target_type || !*target_type)
        return false;
    if (!selector || !*selector)
        return false;
    StreamString expr;
    expr.Printf("(%s)[(id)0x%" PRIx64 " %s]",target_type,valobj.GetPointerValue(),selector);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return false;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);
    options.SetLanguage(lldb::eLanguageTypeObjC_plus_plus);
    options.SetResultIsInternal(true);
    options.SetUseDynamic(lldb::eDynamicCanRunTarget);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               result_sp,
                               options);
    if (!result_sp)
        return false;
    value = result_sp->GetValueAsUnsigned(0);
    return true;
}

bool
lldb_private::formatters::ExtractSummaryFromObjCExpression (ValueObject &valobj,
                                                            const char* target_type,
                                                            const char* selector,
                                                            Stream &stream,
                                                            lldb::LanguageType lang_type)
{
    if (!target_type || !*target_type)
        return false;
    if (!selector || !*selector)
        return false;
    StreamString expr;
    expr.Printf("(%s)[(id)0x%" PRIx64 " %s]",target_type,valobj.GetPointerValue(),selector);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return false;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);
    options.SetLanguage(lldb::eLanguageTypeObjC_plus_plus);
    options.SetResultIsInternal(true);
    options.SetUseDynamic(lldb::eDynamicCanRunTarget);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               result_sp,
                               options);
    if (!result_sp)
        return false;
    stream.Printf("%s",result_sp->GetSummaryAsCString(lang_type));
    return true;
}

lldb::ValueObjectSP
lldb_private::formatters::CallSelectorOnObject (ValueObject &valobj,
                                                const char* return_type,
                                                const char* selector,
                                                uint64_t index)
{
    lldb::ValueObjectSP valobj_sp;
    if (!return_type || !*return_type)
        return valobj_sp;
    if (!selector || !*selector)
        return valobj_sp;
    StreamString expr;
    const char *colon = "";
    llvm::StringRef selector_sr(selector);
    if (selector_sr.back() != ':')
        colon = ":";
    expr.Printf("(%s)[(id)0x%" PRIx64 " %s%s%" PRId64 "]",return_type,valobj.GetPointerValue(),selector,colon,index);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return valobj_sp;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);
    options.SetLanguage(lldb::eLanguageTypeObjC_plus_plus);
    options.SetResultIsInternal(true);
    options.SetUseDynamic(lldb::eDynamicCanRunTarget);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               valobj_sp,
                               options);
    return valobj_sp;
}

lldb::ValueObjectSP
lldb_private::formatters::CallSelectorOnObject (ValueObject &valobj,
                                                const char* return_type,
                                                const char* selector,
                                                const char* key)
{
    lldb::ValueObjectSP valobj_sp;
    if (!return_type || !*return_type)
        return valobj_sp;
    if (!selector || !*selector)
        return valobj_sp;
    if (!key || !*key)
        return valobj_sp;
    StreamString expr;
    const char *colon = "";
    llvm::StringRef selector_sr(selector);
    if (selector_sr.back() != ':')
        colon = ":";
    expr.Printf("(%s)[(id)0x%" PRIx64 " %s%s%s]",return_type,valobj.GetPointerValue(),selector,colon,key);
    ExecutionContext exe_ctx (valobj.GetExecutionContextRef());
    lldb::ValueObjectSP result_sp;
    Target* target = exe_ctx.GetTargetPtr();
    StackFrame* stack_frame = GetViableFrame(exe_ctx);
    if (!target || !stack_frame)
        return valobj_sp;

    EvaluateExpressionOptions options;
    options.SetCoerceToId(false);
    options.SetUnwindOnError(true);
    options.SetKeepInMemory(true);
    options.SetLanguage(lldb::eLanguageTypeObjC_plus_plus);
    options.SetResultIsInternal(true);
    options.SetUseDynamic(lldb::eDynamicCanRunTarget);

    target->EvaluateExpression(expr.GetData(),
                               stack_frame,
                               valobj_sp,
                               options);
    return valobj_sp;
}

size_t
lldb_private::formatters::ExtractIndexFromString (const char* item_name)
{
    if (!item_name || !*item_name)
        return UINT32_MAX;
    if (*item_name != '[')
        return UINT32_MAX;
    item_name++;
    char* endptr = NULL;
    unsigned long int idx = ::strtoul(item_name, &endptr, 0);
    if (idx == 0 && endptr == item_name)
        return UINT32_MAX;
    if (idx == ULONG_MAX)
        return UINT32_MAX;
    return idx;
}

lldb::addr_t
lldb_private::formatters::GetArrayAddressOrPointerValue (ValueObject& valobj)
{
    lldb::addr_t data_addr = LLDB_INVALID_ADDRESS;

    if (valobj.IsPointerType())
        data_addr = valobj.GetValueAsUnsigned(0);
    else if (valobj.IsArrayType())
        data_addr = valobj.GetAddressOf();

    return data_addr;
}
<|endoftext|>


<commit_before>#pragma once
#include <cstdint>
#include <nlohmann/json.hpp>
#include <vector>

#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
#include "RawImgFrame.hpp"

namespace dai {

struct RawImageManipConfig : public RawBuffer {
    // NNData data is in PoBuf
    struct CropRect {
        // Normalized range 0-1
        float xmin = 0.0f, ymin = 0.0f, xmax = 0.0f, ymax = 0.0f;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropRect, xmin, ymin, xmax, ymax);
    };

    struct CropConfig {
        CropRect cropRect;
        bool enableCenterCropRectangle = false;
        // if enableCenterCropRectangle -> automatically calculated crop parameters
        float cropRatio = 1.0f, widthHeightAspectRatio = 1.0f;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropConfig, cropRect, enableCenterCropRectangle, cropRatio, widthHeightAspectRatio);
    };

    struct ResizeConfig {
        int width = 0, height = 0;
        bool lockAspectRatioFill = false;
        char bgRed = 0, bgGreen = 0, bgBlue = 0;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(ResizeConfig, width, height, lockAspectRatioFill, bgRed, bgGreen, bgBlue);
    };

    struct FormatConfig {
        RawImgFrame::Type type = RawImgFrame::Type::RGB888p;
        bool flipHorizontal = false;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(FormatConfig, type, flipHorizontal);
    };

    CropConfig cropConfig;
    ResizeConfig resizeConfig;
    FormatConfig formatConfig;

    bool enableCrop = false;
    bool enableResize = false;
    bool enableFormat = false;

    void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override {
        nlohmann::json j = *this;
        metadata = nlohmann::json::to_msgpack(j);
        datatype = DatatypeEnum::ImageManipConfig;
    };

    NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawImageManipConfig, cropConfig, resizeConfig, formatConfig, enableCrop, enableResize, enableFormat);
};

}  // namespace dai<commit_msg>Add keepAspectRatio config to ImageManip<commit_after>#pragma once
#include <cstdint>
#include <nlohmann/json.hpp>
#include <vector>

#include "DatatypeEnum.hpp"
#include "RawBuffer.hpp"
#include "RawImgFrame.hpp"

namespace dai {

struct RawImageManipConfig : public RawBuffer {
    // NNData data is in PoBuf
    struct CropRect {
        // Normalized range 0-1
        float xmin = 0.0f, ymin = 0.0f, xmax = 0.0f, ymax = 0.0f;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropRect, xmin, ymin, xmax, ymax);
    };

    struct CropConfig {
        CropRect cropRect;
        bool enableCenterCropRectangle = false;
        // if enableCenterCropRectangle -> automatically calculated crop parameters
        float cropRatio = 1.0f, widthHeightAspectRatio = 1.0f;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(CropConfig, cropRect, enableCenterCropRectangle, cropRatio, widthHeightAspectRatio);
    };

    struct ResizeConfig {
        int width = 0, height = 0;
        bool lockAspectRatioFill = false;
        char bgRed = 0, bgGreen = 0, bgBlue = 0;

        /**
         * Whether to keep aspect ratio of input or not
         */
        bool keepAspectRatio = true;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(ResizeConfig, width, height, lockAspectRatioFill, bgRed, bgGreen, bgBlue, keepAspectRatio);
    };

    struct FormatConfig {
        RawImgFrame::Type type = RawImgFrame::Type::RGB888p;
        bool flipHorizontal = false;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(FormatConfig, type, flipHorizontal);
    };

    CropConfig cropConfig;
    ResizeConfig resizeConfig;
    FormatConfig formatConfig;

    bool enableCrop = false;
    bool enableResize = false;
    bool enableFormat = false;

    void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) override {
        nlohmann::json j = *this;
        metadata = nlohmann::json::to_msgpack(j);
        datatype = DatatypeEnum::ImageManipConfig;
    };

    NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawImageManipConfig, cropConfig, resizeConfig, formatConfig, enableCrop, enableResize, enableFormat);
};

}  // namespace dai<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "audio_frame_operations.h"
#include "module_common_types.h"

namespace webrtc {

namespace voe {

WebRtc_Word32
AudioFrameOperations::MonoToStereo(AudioFrame& audioFrame)
{
    if (audioFrame._audioChannel != 1)
    {
        return -1;
    }
    if ((audioFrame._payloadDataLengthInSamples << 1) >=
        AudioFrame::kMaxAudioFrameSizeSamples)
    {
        // not enough memory to expand from mono to stereo
        return -1;
    }

    int16_t payloadCopy[AudioFrame::kMaxAudioFrameSizeSamples];
    memcpy(payloadCopy, audioFrame._payloadData,
           sizeof(int16_t) * audioFrame._payloadDataLengthInSamples);

    for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
    {
        audioFrame._payloadData[2*i]   = payloadCopy[i];
        audioFrame._payloadData[2*i+1] = payloadCopy[i];
    }

    audioFrame._audioChannel = 2;

    return 0;
}

WebRtc_Word32
AudioFrameOperations::StereoToMono(AudioFrame& audioFrame)
{
    if (audioFrame._audioChannel != 2)
    {
        return -1;
    }

    for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
    {
        audioFrame._payloadData[i] = (audioFrame._payloadData[2*i] >> 1) +
            (audioFrame._payloadData[2*i+1] >> 1);
    }

    audioFrame._audioChannel = 1;

    return 0;
}

void AudioFrameOperations::SwapStereoChannels(AudioFrame* frame) {
  for (int i = 0; i < frame->_payloadDataLengthInSamples * 2; i += 2) {
    int16_t temp_data = frame->_payloadData[i];
    frame->_payloadData[i] = frame->_payloadData[i + 1];
    frame->_payloadData[i + 1] = temp_data;
  }
}

WebRtc_Word32
AudioFrameOperations::Mute(AudioFrame& audioFrame)
{
    const int sizeInBytes = sizeof(WebRtc_Word16) *
        audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
    memset(audioFrame._payloadData, 0, sizeInBytes);
    audioFrame._energy = 0;
    return 0;
}

WebRtc_Word32
AudioFrameOperations::Scale(const float left,
                            const float right,
                            AudioFrame& audioFrame)
{
    if (audioFrame._audioChannel == 1)
    {
        assert(false);
        return -1;
    }

    for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
    {
        audioFrame._payloadData[2*i] =
            (WebRtc_Word16)(left*audioFrame._payloadData[2*i]);
        audioFrame._payloadData[2*i+1] =
            (WebRtc_Word16)(right*audioFrame._payloadData[2*i+1]);
    }
    return 0;
}

WebRtc_Word32
AudioFrameOperations::ScaleWithSat(const float scale, AudioFrame& audioFrame)
{
    WebRtc_Word32 tmp(0);

    // Ensure that the output result is saturated [-32768, +32768].
    for (int i = 0;
        i < audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
        i++)
    {
        tmp = static_cast<WebRtc_Word32> (scale * audioFrame._payloadData[i]);
        if (tmp < -32768)
        {
            audioFrame._payloadData[i] = -32768;
        }
        else if (tmp > 32767)
        {
            audioFrame._payloadData[i] = 32767;
        }
        else
        {
            audioFrame._payloadData[i] = static_cast<WebRtc_Word16> (tmp);
        }
    }
    return 0;
}

}  //  namespace voe

}  //  namespace webrtc

<commit_msg>Fail silently when swapping mono.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "audio_frame_operations.h"
#include "module_common_types.h"

namespace webrtc {

namespace voe {

WebRtc_Word32
AudioFrameOperations::MonoToStereo(AudioFrame& audioFrame)
{
    if (audioFrame._audioChannel != 1)
    {
        return -1;
    }
    if ((audioFrame._payloadDataLengthInSamples << 1) >=
        AudioFrame::kMaxAudioFrameSizeSamples)
    {
        // not enough memory to expand from mono to stereo
        return -1;
    }

    int16_t payloadCopy[AudioFrame::kMaxAudioFrameSizeSamples];
    memcpy(payloadCopy, audioFrame._payloadData,
           sizeof(int16_t) * audioFrame._payloadDataLengthInSamples);

    for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
    {
        audioFrame._payloadData[2*i]   = payloadCopy[i];
        audioFrame._payloadData[2*i+1] = payloadCopy[i];
    }

    audioFrame._audioChannel = 2;

    return 0;
}

WebRtc_Word32
AudioFrameOperations::StereoToMono(AudioFrame& audioFrame)
{
    if (audioFrame._audioChannel != 2)
    {
        return -1;
    }

    for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
    {
        audioFrame._payloadData[i] = (audioFrame._payloadData[2*i] >> 1) +
            (audioFrame._payloadData[2*i+1] >> 1);
    }

    audioFrame._audioChannel = 1;

    return 0;
}

void AudioFrameOperations::SwapStereoChannels(AudioFrame* frame) {
  if (frame->_audioChannel != 2) return;

  for (int i = 0; i < frame->_payloadDataLengthInSamples * 2; i += 2) {
    int16_t temp_data = frame->_payloadData[i];
    frame->_payloadData[i] = frame->_payloadData[i + 1];
    frame->_payloadData[i + 1] = temp_data;
  }
}

WebRtc_Word32
AudioFrameOperations::Mute(AudioFrame& audioFrame)
{
    const int sizeInBytes = sizeof(WebRtc_Word16) *
        audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
    memset(audioFrame._payloadData, 0, sizeInBytes);
    audioFrame._energy = 0;
    return 0;
}

WebRtc_Word32
AudioFrameOperations::Scale(const float left,
                            const float right,
                            AudioFrame& audioFrame)
{
    if (audioFrame._audioChannel == 1)
    {
        assert(false);
        return -1;
    }

    for (int i = 0; i < audioFrame._payloadDataLengthInSamples; i++)
    {
        audioFrame._payloadData[2*i] =
            (WebRtc_Word16)(left*audioFrame._payloadData[2*i]);
        audioFrame._payloadData[2*i+1] =
            (WebRtc_Word16)(right*audioFrame._payloadData[2*i+1]);
    }
    return 0;
}

WebRtc_Word32
AudioFrameOperations::ScaleWithSat(const float scale, AudioFrame& audioFrame)
{
    WebRtc_Word32 tmp(0);

    // Ensure that the output result is saturated [-32768, +32768].
    for (int i = 0;
        i < audioFrame._payloadDataLengthInSamples * audioFrame._audioChannel;
        i++)
    {
        tmp = static_cast<WebRtc_Word32> (scale * audioFrame._payloadData[i]);
        if (tmp < -32768)
        {
            audioFrame._payloadData[i] = -32768;
        }
        else if (tmp > 32767)
        {
            audioFrame._payloadData[i] = 32767;
        }
        else
        {
            audioFrame._payloadData[i] = static_cast<WebRtc_Word16> (tmp);
        }
    }
    return 0;
}

}  //  namespace voe

}  //  namespace webrtc

<|endoftext|>