<commit_before>/*
 * Copyright (c) 2015 - 2021, Intel Corporation
 *
 * 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 Intel Corporation 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 LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include "EpochIOGroup.hpp"
#include "ApplicationSampler.hpp"
#include "record.hpp"
#include "Exception.hpp"
#include "PlatformTopo.hpp"
#include "MockPlatformTopo.hpp"
#include "MockApplicationSampler.hpp"
#include "geopm_test.hpp"

using geopm::Exception;
using geopm::ApplicationSampler;
using geopm::EpochIOGroup;
using geopm::IOGroup;
using testing::Return;
using testing::_;

class EpochIOGroupTest : public ::testing::Test
{
    protected:
        void SetUp(void);
        MockPlatformTopo m_topo;
        int m_num_cpu;
        int m_pid_0;
        int m_pid_1;
        MockApplicationSampler m_app;
        std::shared_ptr<EpochIOGroup> m_group;

};

void EpochIOGroupTest::SetUp()
{
    m_num_cpu = 4;
    m_pid_0 = 33;
    m_pid_1 = 42;
    std::vector<int> cpu_process { m_pid_0, m_pid_0, m_pid_1, m_pid_1 };
    ON_CALL(m_topo, num_domain(GEOPM_DOMAIN_CPU))
        .WillByDefault(Return(m_num_cpu));
    ON_CALL(m_app, per_cpu_process())
        .WillByDefault(Return(cpu_process));
    EXPECT_CALL(m_topo, num_domain(GEOPM_DOMAIN_CPU));
    m_group = std::make_shared<EpochIOGroup>(m_topo, m_app);
}

MATCHER_P(IsRecordEqual, other, "")
{
    return arg.time == other.time &&
           arg.process == other.process &&
           arg.event == other.event &&
           arg.signal == other.signal;
}

TEST_F(EpochIOGroupTest, valid_signals)
{
    std::vector<std::string> expected_names = {
        "EPOCH::EPOCH_COUNT",
        "EPOCH_COUNT",
    };
    // enable signals
    EXPECT_CALL(m_app, per_cpu_process());
    m_group->read_batch();

    auto signal_names = m_group->signal_names();
    for (const auto &name : expected_names) {
        EXPECT_TRUE(m_group->is_valid_signal(name));
        EXPECT_TRUE(signal_names.find(name) != signal_names.end());
        EXPECT_FALSE(m_group->signal_description(name).empty());
        // all signals are CPU domain
        EXPECT_EQ(GEOPM_DOMAIN_CPU, m_group->signal_domain_type(name));
        EXPECT_EQ(IOGroup::M_SIGNAL_BEHAVIOR_MONOTONE, m_group->signal_behavior(name));
        // read_signal is not supported
        EXPECT_THROW(m_group->read_signal(name, GEOPM_DOMAIN_CPU, 0), Exception);
    }

    // check aggregation
    EXPECT_TRUE(is_agg_min(m_group->agg_function("EPOCH_COUNT")));

    // check formatting
    EXPECT_TRUE(is_format_integer(m_group->format_function("EPOCH_COUNT")));

    // invalid inputs
    EXPECT_FALSE(m_group->is_valid_signal("INVALID"));
    EXPECT_FALSE(signal_names.find("INVALID") != signal_names.end());
    EXPECT_THROW(m_group->signal_description("INVALID"), Exception);
    EXPECT_EQ(GEOPM_DOMAIN_INVALID, m_group->signal_domain_type("INVALID"));
    EXPECT_THROW(m_group->push_signal("INVALID", GEOPM_DOMAIN_CPU, 0), Exception);
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_BOARD, 0), Exception);
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, -1), Exception);
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, m_num_cpu), Exception);
    EXPECT_THROW(m_group->read_signal("INVALID", GEOPM_DOMAIN_CPU, 0), Exception);
    EXPECT_THROW(m_group->read_signal("EPOCH_COUNT", GEOPM_DOMAIN_BOARD, 0), Exception);
    EXPECT_THROW(m_group->read_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, -1), Exception);
    EXPECT_THROW(m_group->read_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, m_num_cpu), Exception);
    EXPECT_THROW(m_group->agg_function("INVALID"), Exception);
    EXPECT_THROW(m_group->format_function("INVALID"), Exception);
}

TEST_F(EpochIOGroupTest, read_batch)
{
    // read_batch: distribute records to each process
    m_app.inject_records(R"(
# agent: monitor
TIME|PROCESS|EVENT|SIGNAL
0.286542262|33|EPOCH_COUNT|1
1.28657223|33|EPOCH_COUNT|2
1.286573997|42|EPOCH_COUNT|1
)");
    EXPECT_CALL(m_app, per_cpu_process());
    m_group->read_batch();
    // no more push allowed
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, 0), Exception);
}

TEST_F(EpochIOGroupTest, sample_count)
{
    EXPECT_CALL(m_app, per_cpu_process());
    int idx0 = -1;
    int idx1 = -1;
    idx0 = m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, 0);
    int idx = m_group->push_signal("EPOCH::EPOCH_COUNT", GEOPM_DOMAIN_CPU, 0);
    EXPECT_NE(-1, idx0);
    EXPECT_EQ(idx0, idx);
    idx1 = m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, 2);
    EXPECT_NE(-1, idx1);
    EXPECT_NE(idx0, idx1);

    // must read_batch once
    EXPECT_THROW(m_group->sample(idx0), Exception);

    m_app.inject_records(R"(
# agent: monitor
TIME|PROCESS|EVENT|SIGNAL
0.286542262|33|EPOCH_COUNT|1
1.28657223|33|EPOCH_COUNT|2
1.286573997|42|EPOCH_COUNT|1
)");
    m_group->read_batch();

    double value = m_group->sample(idx0);
    EXPECT_EQ(2.0, value);
    value = m_group->sample(idx1);
    EXPECT_EQ(1.0, value);

    // errors for sample
    EXPECT_THROW(m_group->sample(-1), Exception);
    EXPECT_THROW(m_group->sample(idx1 + 1), Exception);
}

TEST_F(EpochIOGroupTest, no_controls)
{
    EXPECT_NO_THROW(m_group->write_batch());
    EXPECT_EQ(0u, m_group->control_names().size());
    EXPECT_THROW(m_group->push_control("any", GEOPM_DOMAIN_CPU, 0), Exception);
    EXPECT_THROW(m_group->push_control("any", GEOPM_DOMAIN_CPU, 0), Exception);
}
<commit_msg>Remove dead code from EpochIOGroupTest<commit_after>/*
 * Copyright (c) 2015 - 2021, Intel Corporation
 *
 * 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 Intel Corporation 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 LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include "EpochIOGroup.hpp"
#include "ApplicationSampler.hpp"
#include "record.hpp"
#include "Exception.hpp"
#include "PlatformTopo.hpp"
#include "MockPlatformTopo.hpp"
#include "MockApplicationSampler.hpp"
#include "geopm_test.hpp"

using geopm::Exception;
using geopm::ApplicationSampler;
using geopm::EpochIOGroup;
using geopm::IOGroup;
using testing::Return;
using testing::_;

class EpochIOGroupTest : public ::testing::Test
{
    protected:
        void SetUp(void);
        MockPlatformTopo m_topo;
        int m_num_cpu;
        int m_pid_0;
        int m_pid_1;
        MockApplicationSampler m_app;
        std::shared_ptr<EpochIOGroup> m_group;

};

void EpochIOGroupTest::SetUp()
{
    m_num_cpu = 4;
    m_pid_0 = 33;
    m_pid_1 = 42;
    std::vector<int> cpu_process { m_pid_0, m_pid_0, m_pid_1, m_pid_1 };
    ON_CALL(m_topo, num_domain(GEOPM_DOMAIN_CPU))
        .WillByDefault(Return(m_num_cpu));
    ON_CALL(m_app, per_cpu_process())
        .WillByDefault(Return(cpu_process));
    EXPECT_CALL(m_topo, num_domain(GEOPM_DOMAIN_CPU));
    m_group = std::make_shared<EpochIOGroup>(m_topo, m_app);
}

TEST_F(EpochIOGroupTest, valid_signals)
{
    std::vector<std::string> expected_names = {
        "EPOCH::EPOCH_COUNT",
        "EPOCH_COUNT",
    };
    // enable signals
    EXPECT_CALL(m_app, per_cpu_process());
    m_group->read_batch();

    auto signal_names = m_group->signal_names();
    for (const auto &name : expected_names) {
        EXPECT_TRUE(m_group->is_valid_signal(name));
        EXPECT_TRUE(signal_names.find(name) != signal_names.end());
        EXPECT_FALSE(m_group->signal_description(name).empty());
        // all signals are CPU domain
        EXPECT_EQ(GEOPM_DOMAIN_CPU, m_group->signal_domain_type(name));
        EXPECT_EQ(IOGroup::M_SIGNAL_BEHAVIOR_MONOTONE, m_group->signal_behavior(name));
        // read_signal is not supported
        EXPECT_THROW(m_group->read_signal(name, GEOPM_DOMAIN_CPU, 0), Exception);
    }

    // check aggregation
    EXPECT_TRUE(is_agg_min(m_group->agg_function("EPOCH_COUNT")));

    // check formatting
    EXPECT_TRUE(is_format_integer(m_group->format_function("EPOCH_COUNT")));

    // invalid inputs
    EXPECT_FALSE(m_group->is_valid_signal("INVALID"));
    EXPECT_FALSE(signal_names.find("INVALID") != signal_names.end());
    EXPECT_THROW(m_group->signal_description("INVALID"), Exception);
    EXPECT_EQ(GEOPM_DOMAIN_INVALID, m_group->signal_domain_type("INVALID"));
    EXPECT_THROW(m_group->push_signal("INVALID", GEOPM_DOMAIN_CPU, 0), Exception);
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_BOARD, 0), Exception);
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, -1), Exception);
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, m_num_cpu), Exception);
    EXPECT_THROW(m_group->read_signal("INVALID", GEOPM_DOMAIN_CPU, 0), Exception);
    EXPECT_THROW(m_group->read_signal("EPOCH_COUNT", GEOPM_DOMAIN_BOARD, 0), Exception);
    EXPECT_THROW(m_group->read_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, -1), Exception);
    EXPECT_THROW(m_group->read_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, m_num_cpu), Exception);
    EXPECT_THROW(m_group->agg_function("INVALID"), Exception);
    EXPECT_THROW(m_group->format_function("INVALID"), Exception);
}

TEST_F(EpochIOGroupTest, read_batch)
{
    // read_batch: distribute records to each process
    m_app.inject_records(R"(
# agent: monitor
TIME|PROCESS|EVENT|SIGNAL
0.286542262|33|EPOCH_COUNT|1
1.28657223|33|EPOCH_COUNT|2
1.286573997|42|EPOCH_COUNT|1
)");
    EXPECT_CALL(m_app, per_cpu_process());
    m_group->read_batch();
    // no more push allowed
    EXPECT_THROW(m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, 0), Exception);
}

TEST_F(EpochIOGroupTest, sample_count)
{
    EXPECT_CALL(m_app, per_cpu_process());
    int idx0 = -1;
    int idx1 = -1;
    idx0 = m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, 0);
    int idx = m_group->push_signal("EPOCH::EPOCH_COUNT", GEOPM_DOMAIN_CPU, 0);
    EXPECT_NE(-1, idx0);
    EXPECT_EQ(idx0, idx);
    idx1 = m_group->push_signal("EPOCH_COUNT", GEOPM_DOMAIN_CPU, 2);
    EXPECT_NE(-1, idx1);
    EXPECT_NE(idx0, idx1);

    // must read_batch once
    EXPECT_THROW(m_group->sample(idx0), Exception);

    m_app.inject_records(R"(
# agent: monitor
TIME|PROCESS|EVENT|SIGNAL
0.286542262|33|EPOCH_COUNT|1
1.28657223|33|EPOCH_COUNT|2
1.286573997|42|EPOCH_COUNT|1
)");
    m_group->read_batch();

    double value = m_group->sample(idx0);
    EXPECT_EQ(2.0, value);
    value = m_group->sample(idx1);
    EXPECT_EQ(1.0, value);

    // errors for sample
    EXPECT_THROW(m_group->sample(-1), Exception);
    EXPECT_THROW(m_group->sample(idx1 + 1), Exception);
}

TEST_F(EpochIOGroupTest, no_controls)
{
    EXPECT_NO_THROW(m_group->write_batch());
    EXPECT_EQ(0u, m_group->control_names().size());
    EXPECT_THROW(m_group->push_control("any", GEOPM_DOMAIN_CPU, 0), Exception);
    EXPECT_THROW(m_group->push_control("any", GEOPM_DOMAIN_CPU, 0), Exception);
}
<|endoftext|>


<commit_before>/*
 The MIT License (MIT)

 Copyright (c) [2016] [BTC.COM]

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

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

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

#include "gtest/gtest.h"
#include "Common.h"
#include "Utils.h"

#include "StratumServer.h"

// #include "Kafka.h"

#ifndef WORK_WITH_STRATUM_SWITCHER

TEST(StratumServer, SessionIDManager24Bits) {
  // KafkaProducer a("", "", 0);
  // a.produce("", 0);

  SessionIDManagerT<24> m(0xFFu);
  uint32_t j, sessionID;

  // fill all session ids
  for (uint32_t i = 0; i <= 0x00FFFFFFu; i++) {
    uint32_t id = (0xFFu << 24) | i;
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, id);
  }
  ASSERT_EQ(m.ifFull(), true);

  // free the fisrt one
  j = 0xFF000000u;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);

  // free the last one
  j = 0xFFFFFFFFu;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);
}

TEST(StratumServer, SessionIDManager16Bits) {
  SessionIDManagerT<16> m(0x99u);
  uint32_t j, sessionID;

  // fill all session ids
  for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {
    uint32_t id = (0x99u << 16) | i;
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, id);
  }
  ASSERT_EQ(m.ifFull(), true);

  // free the fisrt one
  j = 0x00990000u;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);

  // free the last one
  j = 0x0099FFFFu;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);
}

TEST(StratumServer, SessionIDManager16BitsWithInterval) {
  SessionIDManagerT<16> m(0x99u);
  m.setAllocInterval(256);

  uint32_t j, sessionID;

  // fill all session ids
  // Use std::vector<bool> because the compile time of
  // std::bitset<0x100000000ull> is too long.
  {
    std::vector<bool> ids(0x100000000ull);
    for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {
      ASSERT_EQ(m.allocSessionId(&sessionID), true);
      ASSERT_EQ(ids[sessionID], false);
      ids[sessionID] = true;
    }
    ASSERT_EQ(m.ifFull(), true);
  }

  // free the fisrt one
  {
    j = 0x00990000u;
    m.freeSessionId(j);
    ASSERT_EQ(m.ifFull(), false);
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, j);
    ASSERT_EQ(m.ifFull(), true);
  }

  // free the last one
  {
    j = 0x0099FFFFu;
    m.freeSessionId(j);
    ASSERT_EQ(m.ifFull(), false);
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, j);
    ASSERT_EQ(m.ifFull(), true);
  }

  // free all
  for (uint32_t i = 0x00990000u; i <= 0x0099FFFFu; i++) {
    m.freeSessionId(i);
  }

  // fill all again
  {
    std::vector<bool> ids(0x100000000ull);
    for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {
      ASSERT_EQ(m.allocSessionId(&sessionID), true);
      ASSERT_EQ(ids[sessionID], false);
      ids[sessionID] = true;
    }
    ASSERT_EQ(m.ifFull(), true);
  }
}

TEST(StratumServer, SessionIDManager8Bits) {
  SessionIDManagerT<8> m(0x68u);
  uint32_t j, sessionID;

  // fill all session ids
  for (uint32_t i = 0; i <= 0x000000FFu; i++) {
    uint32_t id = (0x68u << 8) | i;
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, id);
  }
  ASSERT_EQ(m.ifFull(), true);

  // free the fisrt one
  j = 0x00006800u;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);

  // free the last one
  j = 0x000068FFu;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);
}

#endif // #ifndef WORK_WITH_STRATUM_SWITCHER
<commit_msg>add a testcase for StratumServerBitcoin::checkShare()<commit_after>/*
 The MIT License (MIT)

 Copyright (c) [2016] [BTC.COM]

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

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

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

#include "gtest/gtest.h"
#include "Common.h"
#include "Utils.h"

#include "StratumServer.h"
#include "bitcoin/BitcoinUtils.h"
#include "bitcoin/StratumBitcoin.h"
#include "bitcoin/StratumServerBitcoin.h"

// #include "Kafka.h"

#ifndef WORK_WITH_STRATUM_SWITCHER

TEST(StratumServer, SessionIDManager24Bits) {
  // KafkaProducer a("", "", 0);
  // a.produce("", 0);

  SessionIDManagerT<24> m(0xFFu);
  uint32_t j, sessionID;

  // fill all session ids
  for (uint32_t i = 0; i <= 0x00FFFFFFu; i++) {
    uint32_t id = (0xFFu << 24) | i;
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, id);
  }
  ASSERT_EQ(m.ifFull(), true);

  // free the fisrt one
  j = 0xFF000000u;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);

  // free the last one
  j = 0xFFFFFFFFu;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);
}

TEST(StratumServer, SessionIDManager16Bits) {
  SessionIDManagerT<16> m(0x99u);
  uint32_t j, sessionID;

  // fill all session ids
  for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {
    uint32_t id = (0x99u << 16) | i;
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, id);
  }
  ASSERT_EQ(m.ifFull(), true);

  // free the fisrt one
  j = 0x00990000u;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);

  // free the last one
  j = 0x0099FFFFu;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);
}

TEST(StratumServer, SessionIDManager16BitsWithInterval) {
  SessionIDManagerT<16> m(0x99u);
  m.setAllocInterval(256);

  uint32_t j, sessionID;

  // fill all session ids
  // Use std::vector<bool> because the compile time of
  // std::bitset<0x100000000ull> is too long.
  {
    std::vector<bool> ids(0x100000000ull);
    for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {
      ASSERT_EQ(m.allocSessionId(&sessionID), true);
      ASSERT_EQ(ids[sessionID], false);
      ids[sessionID] = true;
    }
    ASSERT_EQ(m.ifFull(), true);
  }

  // free the fisrt one
  {
    j = 0x00990000u;
    m.freeSessionId(j);
    ASSERT_EQ(m.ifFull(), false);
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, j);
    ASSERT_EQ(m.ifFull(), true);
  }

  // free the last one
  {
    j = 0x0099FFFFu;
    m.freeSessionId(j);
    ASSERT_EQ(m.ifFull(), false);
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, j);
    ASSERT_EQ(m.ifFull(), true);
  }

  // free all
  for (uint32_t i = 0x00990000u; i <= 0x0099FFFFu; i++) {
    m.freeSessionId(i);
  }

  // fill all again
  {
    std::vector<bool> ids(0x100000000ull);
    for (uint32_t i = 0; i <= 0x0000FFFFu; i++) {
      ASSERT_EQ(m.allocSessionId(&sessionID), true);
      ASSERT_EQ(ids[sessionID], false);
      ids[sessionID] = true;
    }
    ASSERT_EQ(m.ifFull(), true);
  }
}

TEST(StratumServer, SessionIDManager8Bits) {
  SessionIDManagerT<8> m(0x68u);
  uint32_t j, sessionID;

  // fill all session ids
  for (uint32_t i = 0; i <= 0x000000FFu; i++) {
    uint32_t id = (0x68u << 8) | i;
    ASSERT_EQ(m.allocSessionId(&sessionID), true);
    ASSERT_EQ(sessionID, id);
  }
  ASSERT_EQ(m.ifFull(), true);

  // free the fisrt one
  j = 0x00006800u;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);

  // free the last one
  j = 0x000068FFu;
  m.freeSessionId(j);
  ASSERT_EQ(m.ifFull(), false);
  ASSERT_EQ(m.allocSessionId(&sessionID), true);
  ASSERT_EQ(sessionID, j);
  ASSERT_EQ(m.ifFull(), true);
}

#endif // #ifndef WORK_WITH_STRATUM_SWITCHER

TEST(StratumServerBitcoin, CheckShare) {
  string sjobJson = "{\"jobId\":6645522065066147329,\"gbtHash\":\"d349be274f007c2e1ee773b33bd21ef43d2615c089b7c5460b66584881a10683\","
  "\"prevHash\":\"00000000000000000019d1d9c84df0ecc23e549b86644ad47cb92570a26b12a5\",\"prevHashBeStr\":\"a26b12a57cb9257086644ad4c23e"
  "549bc84df0ec0019d1d90000000000000000\",\"height\":558201,\"coinbase1\":\"020000000100000000000000000000000000000000000000000000000"
  "00000000000000000ffffffff4b03798408041ba3395c612f4254432e434f4d2ffabe6d6dc807e51bd76025d65ccad2ba8ba1e9fba5f09118b6b55a348638cc17b"
  "14e3909080000005fb54ad0\",\"coinbase2\":\"ffffffff036734ec4a0000000016001497cfc76442fe717f2a3f0cc9c175f7561b6619970000000000000000"
  "266a24aa21a9ed40cbdaa98da815640f815b938df95bffe0775d8078771bc47ed4f43ac4e30b0600000000000000002952534b424c4f434b3a9ad45fdcc194d788"
  "895f3ad389b583ea327f826353f7edf6b168db038372cb2700000000\",\"merkleBranch\":\"53146311555e15816f4549a893ff2eb50e60741ecccb2996bafd"
  "dcf4ee008d5ac504967e375b2522af2be8411b1b032dda0e700c2e8913d869533256ff30caccea4ba404b68e625cfd3237e07e8deddb342690b08314d2638b5272"
  "b74ab12fa3b3812908cd6bef999dea979875ba2730615be08b480e4b6f7b878000510a778c557f44bc3f21813d138d25530df85a89a38e2d2827f758ebc68a62e8"
  "225933a5af086e72d9a65fd9be526648e8bcf74271308d9d273425b47bd12db075e841ba703f4c8a20be62d036958278b16f214d7fcd35c46a9f9fb1910618fa9e"
  "029d3f96518aae34efbdabfbfbc055bffe891d93edbc7539ae9c0a22a35e87d5ccb033b89976cbb624af024b53c6a02309cb838eb285ecf675b801f1dd7f2d5c92"
  "4cb1491731c28bea800b12b94bb4f70502a40559c8edb5f73b906ba8e814f10e852ef87365a49346c4b7361b75e38f1d9b96f028880227b7186a0b114e170b170b"
  "47\",\"nVersion\":536870912,\"nBits\":389159077,\"nTime\":1547281171,\"minTime\":1547277926,\"coinbaseValue\":1256993895,\"witness"
  "Commitment\":\"6a24aa21a9ed40cbdaa98da815640f815b938df95bffe0775d8078771bc47ed4f43ac4e30b06\",\"nmcBlockHash\":\"c807e51bd76025d65"
  "ccad2ba8ba1e9fba5f09118b6b55a348638cc17b14e3909\",\"nmcBits\":402868319,\"nmcHeight\":433937,\"nmcRpcAddr\":\"http://127.0.0.1:899"
  "9\",\"nmcRpcUserpass\":\"user:pass\",\"rskBlockHashForMergedMining\":\"0x9ad45fdcc194d788895f3ad389b583ea327f826353f7edf6b168db038"
  "372cb27\",\"rskNetworkTarget\":\"0x00000000000000001386e3444eba74f8a750a71a75ed0b7fecdfd282a8cef091\",\"rskFeesForMiner\":\"0\",\""
  "rskdRpcAddress\":\"http://127.0.0.1:4444\",\"rskdRpcUserPwd\":\"user:pass\",\"isRskCleanJob\":true}";

  StratumJobBitcoin *sjob = new StratumJobBitcoin();
  sjob->unserializeFromJson(sjobJson.c_str(), sjobJson.size());

  StratumJobExBitcoin exjob(sjob, true);

  CBlockHeader header;
  std::vector<char> coinbaseBin;

  exjob.generateBlockHeader(
    &header, &coinbaseBin,
    0xfe0000c3u, "260103fe60004690",
    sjob->merkleBranch_, sjob->prevHash_,
    sjob->nBits_, sjob->nVersion_,
    0x5c39a313u, 0x07ba7929u,
    0x00013f00u
  );

  uint256 blkHash = uint256S("1028e53e8145994a9ebe4f39eb6a7e3fd4036f2f21a05a5a696e8ac6d0829ef4");
  ASSERT_EQ(blkHash, header.GetHash());
}
<|endoftext|>


<commit_before>#include <X86/Idt.hh>
#include <X86/Processor.hh>
#include <X86/ThreadContext.hh>

#include <Memory.hh>
#include <Interrupt.hh>
#include <Power.hh>
#include <Debug.hh>
#include <StackTrace.hh>
#include <Kernel/Scheduler.hh>
#include <Kernel/Thread.hh>
#include <Kernel/Process.hh>
#include <Kernel/ProcessContext.hh>

using namespace Kernel;

extern IdtPointer idtPointer;

// Idt descriptors
static IdtEntry idtEntries[NUMIDT];
IdtPointer idtPointer;

extern "C" InterruptFrame* x86_isr_dispatcher(InterruptFrame* frame);
extern "C" void x86_isr_init(int n, void (*handler)());

#include "InterruptVectorsInit.icc"

// XXX this should be refactored to be MI
//
static void
x86_isr_page_fault(InterruptFrame* frame)
{
   static int nestingFlag;

   // protect the kernel from trying to handle nested page faults
   //
   if (nestingFlag > 0)
   {
      Debug::panic("Nested page fault");
      Power::reboot();
   }

   nestingFlag++;

   uint32_t cr2 = get_cr2();

   if ((frame->error & 0x1) == 0 && Memory::handlePageFault(cr2, frame))
   {
#ifdef DEBUG
      printf("Page fault handled: %p\n", (void* )cr2);
#endif
      nestingFlag--;
      return;
   }

   printf("\n");
   frame->print();

   printf("\nPage fault: %s\n", (frame->error & (1 << 0)) ? "protection violation" : "page not present");
   printf("%s 0x%x from 0x%x in %s mode\nError Code: 0x%x\n",
	  (frame->error & (1 << 1)) ? "Writing" : "Reading",
	  cr2, frame->eip,
	  (frame->error & (1 << 2)) ? "user" : "supervisor",
	  frame->error);

   StackTrace::printStackTrace(reinterpret_cast<void*>(frame->ebp));

   x86_cli();
   Power::halt();
}

static void
x86_isr_general_protection_fault(InterruptFrame* frame)
{
   printf("\n");
   frame->print();

   printf("\nGeneral protection fault: ");

   switch ((frame->error >> 1) & 0x3)
   {
      case 0:
	 printf("GDT");
	 break;
      case 2:
	 printf("LDT");
	 break;
      case 1:
      case 3:
	 printf("IDT");
	 break;
   }

   printf(": 0x%x", (frame->error >> 3) & 0x1fff);

   if (frame->error & 0x1)
   {
      printf(" (external)");
   }

   printf("\n\n");

   StackTrace::printStackTrace(reinterpret_cast<void*>(frame->ebp));

   x86_cli();
   Power::halt();
}

static void
x86_isr_default_handler(InterruptFrame* frame)
{
   if (frame->error == 0)
   {
      printf("\n");
      frame->print();

      Debug::panic("\n\nUnhandled Interrupt: %u\n", frame->interrupt);
   }
   else
   {
      Debug::panic("\n\nUnhandled Interrupt: %u, Error Code: 0x%x\n", frame->interrupt, frame->error);
   }
}

InterruptFrame*
x86_isr_dispatcher(InterruptFrame* frame)
{
   if (frame->interrupt == 255)
   {
      // spurious
      return frame;
   }

   KASSERT(Interrupt::getInterruptLevel() > 0);

   Thread* interruptedThread = Scheduler::getCurrentThread();
   Process* interruptedProcess = interruptedThread->getProcess();
   interruptedThread->setKernelStack((uintptr_t )frame);
   interruptedThread->setReady();

   // TODO: make a list of handlers and register them there to be run from dispatcher
   if (frame->interrupt == 13)
   {
      x86_isr_general_protection_fault(frame);
   }

   if (frame->interrupt == 14)
   {
      x86_isr_page_fault(frame);
      goto exit;
   }

   // XXX hardcoded hack
   if (frame->interrupt >= 32 && frame->interrupt < 48)
   {
      Interrupt::handleInterrupt(frame->interrupt - 32);
      goto exit;
   }

   x86_isr_default_handler(frame);

  exit:
   KASSERT(Interrupt::getInterruptLevel() > 0);

   Thread* currentThread = Scheduler::getCurrentThread();
   Process* currentProcess = currentThread->getProcess();
   if (currentThread->getType() == Thread::UserThread)
   {
      ProcessContext::setKernelStack(currentThread->getKernelStack());
   }

   currentThread->setRunning();

   if (currentProcess != 0)
   {
      printf("New process scheduled! %p\n", currentProcess);
   }

   if (currentProcess != interruptedProcess)
   {
      printf("switching processcontext: %p\n", currentProcess);
      KASSERT(currentProcess != 0);
      ProcessContext* newContext = currentProcess->getContext();
      KASSERT(newContext != 0);
      newContext->switchContext();
   }
   InterruptFrame* newFrame = (InterruptFrame* )currentThread->getKernelStack();

   KASSERT(newFrame != 0);

   frame = newFrame;

   return frame;
}

void
x86_isr_init(int n, void (*handler)())
{
   idtEntries[n].baseLow = (uint16_t)((uint32_t)(handler) & 0xffff);
   idtEntries[n].baseHigh = (uint16_t)(((uint32_t)(handler) >> 16) & 0xffff);

   idtEntries[n].selector = 0x08;
   idtEntries[n].flags = 0x8e;

   // zero filled
   idtEntries[n].reserved = 0;
}

void
initInterrupts()
{
   idtPointer.base = (uint32_t )&idtEntries;
   idtPointer.limit = sizeof(IdtEntry) * NUMIDT - 1;

   // generated function
   initInterruptVectors();

   x86_idt_init();
}
<commit_msg>User processes should be killed on UH PF.<commit_after>#include <X86/Idt.hh>
#include <X86/Processor.hh>
#include <X86/ThreadContext.hh>

#include <Memory.hh>
#include <Interrupt.hh>
#include <Power.hh>
#include <Debug.hh>
#include <StackTrace.hh>
#include <Kernel/Scheduler.hh>
#include <Kernel/Thread.hh>
#include <Kernel/Process.hh>
#include <Kernel/ProcessContext.hh>

using namespace Kernel;

extern IdtPointer idtPointer;

// Idt descriptors
static IdtEntry idtEntries[NUMIDT];
IdtPointer idtPointer;

extern "C" InterruptFrame* x86_isr_dispatcher(InterruptFrame* frame);
extern "C" void x86_isr_init(int n, void (*handler)());

#include "InterruptVectorsInit.icc"

// XXX this should be refactored to be MI
//
static void
x86_isr_page_fault(InterruptFrame* frame)
{
   static int nestingFlag;

   // protect the kernel from trying to handle nested page faults
   //
   if (nestingFlag > 0)
   {
      Debug::panic("Nested page fault");
      Power::reboot();
   }

   nestingFlag++;

   uint32_t cr2 = get_cr2();

   if ((frame->error & 0x1) == 0 && Memory::handlePageFault(cr2, frame))
   {
#ifdef DEBUG
      printf("Page fault handled: %p\n", (void* )cr2);
#endif
      nestingFlag--;
      return;
   }

   bool isUser = frame->error & (1 << 2);
   if (isUser)
   {
      // XXX Kill process/thread here
//      nestingFlag--;
//      return;
   }

   printf("\n");
   frame->print();

   printf("\nPage fault: %s\n", (frame->error & (1 << 0)) ? "protection violation" : "page not present");
   printf("%s 0x%x from 0x%x in %s mode\nError Code: 0x%x\n",
	  (frame->error & (1 << 1)) ? "Writing" : "Reading",
	  cr2, frame->eip,
	  (frame->error & (1 << 2)) ? "user" : "supervisor",
	  frame->error);

   StackTrace::printStackTrace(reinterpret_cast<void*>(frame->ebp));

   x86_cli();
   Power::halt();
}

static void
x86_isr_general_protection_fault(InterruptFrame* frame)
{
   printf("\n");
   frame->print();

   printf("\nGeneral protection fault: ");

   switch ((frame->error >> 1) & 0x3)
   {
      case 0:
	 printf("GDT");
	 break;
      case 2:
	 printf("LDT");
	 break;
      case 1:
      case 3:
	 printf("IDT");
	 break;
   }

   printf(": 0x%x", (frame->error >> 3) & 0x1fff);

   if (frame->error & 0x1)
   {
      printf(" (external)");
   }

   printf("\n\n");

   StackTrace::printStackTrace(reinterpret_cast<void*>(frame->ebp));

   x86_cli();
   Power::halt();
}

static void
x86_isr_default_handler(InterruptFrame* frame)
{
   if (frame->error == 0)
   {
      printf("\n");
      frame->print();

      Debug::panic("\n\nUnhandled Interrupt: %u\n", frame->interrupt);
   }
   else
   {
      Debug::panic("\n\nUnhandled Interrupt: %u, Error Code: 0x%x\n", frame->interrupt, frame->error);
   }
}

InterruptFrame*
x86_isr_dispatcher(InterruptFrame* frame)
{
   if (frame->interrupt == 255)
   {
      // spurious
      return frame;
   }

   KASSERT(Interrupt::getInterruptLevel() > 0);

   Thread* interruptedThread = Scheduler::getCurrentThread();
   Process* interruptedProcess = interruptedThread->getProcess();
   interruptedThread->setKernelStack((uintptr_t )frame);
   interruptedThread->setReady();

   // TODO: make a list of handlers and register them there to be run from dispatcher
   if (frame->interrupt == 13)
   {
      x86_isr_general_protection_fault(frame);
   }

   if (frame->interrupt == 14)
   {
      x86_isr_page_fault(frame);
      goto exit;
   }

   // XXX hardcoded hack
   if (frame->interrupt >= 32 && frame->interrupt < 48)
   {
      Interrupt::handleInterrupt(frame->interrupt - 32);
      goto exit;
   }

   x86_isr_default_handler(frame);

  exit:
   KASSERT(Interrupt::getInterruptLevel() > 0);

   Thread* currentThread = Scheduler::getCurrentThread();
   Process* currentProcess = currentThread->getProcess();
   if (currentThread->getType() == Thread::UserThread)
   {
      ProcessContext::setKernelStack(currentThread->getKernelStack());
   }

   currentThread->setRunning();

   if (currentProcess != 0)
   {
      printf("New process scheduled! %p\n", currentProcess);
   }

   if (currentProcess != interruptedProcess)
   {
      printf("switching processcontext: %p\n", currentProcess);
      KASSERT(currentProcess != 0);
      ProcessContext* newContext = currentProcess->getContext();
      KASSERT(newContext != 0);
      newContext->switchContext();
   }
   InterruptFrame* newFrame = (InterruptFrame* )currentThread->getKernelStack();

   KASSERT(newFrame != 0);

   frame = newFrame;

   return frame;
}

void
x86_isr_init(int n, void (*handler)())
{
   idtEntries[n].baseLow = (uint16_t)((uint32_t)(handler) & 0xffff);
   idtEntries[n].baseHigh = (uint16_t)(((uint32_t)(handler) >> 16) & 0xffff);

   idtEntries[n].selector = 0x08;
   idtEntries[n].flags = 0x8e;

   // zero filled
   idtEntries[n].reserved = 0;
}

void
initInterrupts()
{
   idtPointer.base = (uint32_t )&idtEntries;
   idtPointer.limit = sizeof(IdtEntry) * NUMIDT - 1;

   // generated function
   initInterruptVectors();

   x86_idt_init();
}
<|endoftext|>


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

class Conversion
{
public:
    Conversion (int i) :
      m_i (i)
      {}

    operator bool()
    {
        return m_i != 0;
    }

private:
    int m_i;
};

class A
{
public:
    A(int i=0):
        m_a_int(i),
        m_aa_int(i+1)
    {
    }

    virtual
    ~A()
    {
    }

    int
    GetInteger() const
    {
        return m_a_int;
    }
    void
    SetInteger(int i)
    {
        m_a_int = i;
    }

protected:
    int m_a_int;
    int m_aa_int;
};

class B : public A
{
public:
    B(int ai, int bi) :
        A(ai),
        m_b_int(bi)
    {
    }

    virtual
    ~B()
    {
    }

    int
    GetIntegerB() const
    {
        return m_b_int;
    }
    void
    SetIntegerB(int i)
    {
        m_b_int = i;
    }

protected:
    int m_b_int;
};

#include <cstdio>
class C : public B
{
public:
    C(int ai, int bi, int ci) :
        B(ai, bi),
        m_c_int(ci)
    {
        printf("Within C::ctor() m_c_int=%d\n", m_c_int); // Set break point at this line.
    }

    virtual
    ~C()
    {
    }

    int
    GetIntegerC() const
    {
        return m_c_int;
    }
    void
    SetIntegerC(int i)
    {
        m_c_int = i;
    }

protected:
    int m_c_int;
};

int
main (int argc, char const *argv[])
{
    A a(12);
    B b(22,33);
    C c(44,55,66);
    A *c_as_a = &c;
    B *c_as_b = &c;
    void *a_as_void_ptr = &a;
    void *b_as_void_ptr = &b;
    void *c_as_void_ptr = &c;
    const void *a_as_const_void_ptr = &a;
    const void *b_as_const_void_ptr = &b;
    const void *c_as_const_void_ptr = &c;
    Conversion conv(1);
    if (conv)
        return b.GetIntegerB() - a.GetInteger() + c.GetInteger();
    return 0;
}
<commit_msg>Revert previous changes.<commit_after>//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

class Conversion
{
public:
    Conversion (int i) :
      m_i (i)
      {}

    operator bool()
    {
        return m_i != 0;
    }

private:
    int m_i;
};

class A
{
public:
    A(int i=0):
        m_a_int(i),
        m_aa_int(i+1)
    {
    }

    //virtual
    ~A()
    {
    }

    int
    GetInteger() const
    {
        return m_a_int;
    }
    void
    SetInteger(int i)
    {
        m_a_int = i;
    }

protected:
    int m_a_int;
    int m_aa_int;
};

class B : public A
{
public:
    B(int ai, int bi) :
        A(ai),
        m_b_int(bi)
    {
    }

    //virtual
    ~B()
    {
    }

    int
    GetIntegerB() const
    {
        return m_b_int;
    }
    void
    SetIntegerB(int i)
    {
        m_b_int = i;
    }

protected:
    int m_b_int;
};

#include <cstdio>
class C : public B
{
public:
    C(int ai, int bi, int ci) :
        B(ai, bi),
        m_c_int(ci)
    {
        printf("Within C::ctor() m_c_int=%d\n", m_c_int); // Set break point at this line.
    }

    //virtual
    ~C()
    {
    }

    int
    GetIntegerC() const
    {
        return m_c_int;
    }
    void
    SetIntegerC(int i)
    {
        m_c_int = i;
    }

protected:
    int m_c_int;
};

int
main (int argc, char const *argv[])
{
    A a(12);
    B b(22,33);
    C c(44,55,66);
    Conversion conv(1);
    if (conv)
        return b.GetIntegerB() - a.GetInteger() + c.GetInteger();
    return 0;
}
<|endoftext|>


<commit_before>//
// Created by Ivan Shynkarenka on 26.01.2016
//

#include "benchmark/cppbenchmark.h"

#include "threads/mpsc_ring_buffer.h"

#include <functional>
#include <thread>

using namespace CppCommon;

const uint64_t bytes_to_produce = 134217728;
const int item_size_from = 4;
const int item_size_to = 4096;
const int producers_from = 1;
const int producers_to = 8;
const auto settings = CppBenchmark::Settings().PairRange(item_size_from, item_size_to, [](int from, int to, int& result) { int r = result; result *= 2; return r; },
                                                         producers_from, producers_to, [](int from, int to, int& result) { int r = result; result *= 2; return r; });

template<uint64_t N>
void produce_consume(CppBenchmark::Context& context, const std::function<void()>& wait_strategy)
{
    const int item_size = context.x();
    const int producers_count = context.y();
    const uint64_t items_to_produce = bytes_to_produce / item_size;
    uint64_t crc = 0;

    // Create multiple producers / single consumer wait-free ring buffer
    MPSCRingBuffer buffer(N);

    // Start consumer thread
    auto consumer = std::thread([&buffer, &wait_strategy, item_size, items_to_produce, &crc]()
    {
        // Use big items buffer to enable items batching
        uint8_t* items = new uint8_t[N];

        for (uint64_t i = 0; i < items_to_produce;)
        {
            // Dequeue using the given waiting strategy
            size_t size;
            while (!buffer.Dequeue(items, size = N))
                wait_strategy();

            // Emulate consuming
            for (uint64_t j = 0; j < size; ++j)
                crc += items[j];

            // Increase the items counter
            i += size / item_size;
        }

        // Delete items buffer
        delete[] items;
    });

    // Start producer threads
    std::vector<std::thread> producers;
    for (int producer = 0; producer < producers_count; ++producer)
    {
        producers.push_back(std::thread([&buffer, &wait_strategy, item_size, items_to_produce, producer, producers_count]()
        {
            uint8_t item[item_size_to];

            uint64_t items = (items_to_produce / producers_count);
            for (uint64_t i = 0; i < items; ++i)
            {
                // Emulate producing
                for (int j = 0; j < item_size; ++j)
                    item[j] = (uint8_t)j;

                // Enqueue using the given waiting strategy
                while (!buffer.Enqueue(item, item_size))
                    wait_strategy();
            }
        }));
    }

    // Wait for the consumer thread
    consumer.join();

    // Wait for all producers threads
    for (auto& producer : producers)
        producer.join();

    // Update benchmark metrics
    context.metrics().AddIterations(items_to_produce - 1);
    context.metrics().AddItems(items_to_produce);
    context.metrics().AddBytes(items_to_produce * item_size);
    context.metrics().SetCustom("MPSCRingBuffer.capacity", N);
    context.metrics().SetCustom("CRC", crc);
}

BENCHMARK("MPSCRingBuffer<SpinWait>", settings)
{
    produce_consume<1048576>(context, []{});
}

BENCHMARK("MPSCRingBuffer<YieldWait>", settings)
{
    produce_consume<1048576>(context, []{ std::this_thread::yield(); });
}

BENCHMARK_MAIN()
<commit_msg>Fix compilation error<commit_after>//
// Created by Ivan Shynkarenka on 26.01.2016
//

#include "benchmark/cppbenchmark.h"

#include "threads/mpsc_ring_buffer.h"

#include <functional>
#include <thread>

using namespace CppCommon;

const uint64_t bytes_to_produce = 134217728;
const int item_size_from = 4;
const int item_size_to = 4096;
const int producers_from = 1;
const int producers_to = 8;
const auto settings = CppBenchmark::Settings().PairRange(item_size_from, item_size_to, [](int from, int to, int& result) { int r = result; result *= 2; return r; },
                                                         producers_from, producers_to, [](int from, int to, int& result) { int r = result; result *= 2; return r; });

template<uint64_t N>
void produce_consume(CppBenchmark::Context& context, const std::function<void()>& wait_strategy)
{
    const int item_size = context.x();
    const int producers_count = context.y();
    const uint64_t items_to_produce = bytes_to_produce / item_size;
    uint64_t crc = 0;

    // Create multiple producers / single consumer wait-free ring buffer
    MPSCRingBuffer buffer(N);

    // Start consumer thread
    auto consumer = std::thread([&buffer, &wait_strategy, item_size, items_to_produce, &crc]()
    {
        // Use big items buffer to enable items batching
        uint8_t* items = new uint8_t[N];

        for (uint64_t i = 0; i < items_to_produce;)
        {
            // Dequeue using the given waiting strategy
            size_t size;
            while (!buffer.Dequeue(items, size = N))
                wait_strategy();

            // Emulate consuming
            for (uint64_t j = 0; j < size; ++j)
                crc += items[j];

            // Increase the items counter
            i += size / item_size;
        }

        // Delete items buffer
        delete[] items;
    });

    // Start producer threads
    std::vector<std::thread> producers;
    for (int producer = 0; producer < producers_count; ++producer)
    {
        producers.push_back(std::thread([&buffer, &wait_strategy, item_size, items_to_produce, producers_count]()
        {
            uint8_t item[item_size_to];

            uint64_t items = (items_to_produce / producers_count);
            for (uint64_t i = 0; i < items; ++i)
            {
                // Emulate producing
                for (int j = 0; j < item_size; ++j)
                    item[j] = (uint8_t)j;

                // Enqueue using the given waiting strategy
                while (!buffer.Enqueue(item, item_size))
                    wait_strategy();
            }
        }));
    }

    // Wait for the consumer thread
    consumer.join();

    // Wait for all producers threads
    for (auto& producer : producers)
        producer.join();

    // Update benchmark metrics
    context.metrics().AddIterations(items_to_produce - 1);
    context.metrics().AddItems(items_to_produce);
    context.metrics().AddBytes(items_to_produce * item_size);
    context.metrics().SetCustom("MPSCRingBuffer.capacity", N);
    context.metrics().SetCustom("CRC", crc);
}

BENCHMARK("MPSCRingBuffer<SpinWait>", settings)
{
    produce_consume<1048576>(context, []{});
}

BENCHMARK("MPSCRingBuffer<YieldWait>", settings)
{
    produce_consume<1048576>(context, []{ std::this_thread::yield(); });
}

BENCHMARK_MAIN()
<|endoftext|>


<commit_before>/*
 * Set.h
 *
 *  Created on: 12.05.2017
 *      Author: frbe5612
 */

#ifndef BAG_HPP_
#define BAG_HPP_

#ifdef NDEBUG
#define DEBUG_MESSAGE(a) /**/
#else
#define DEBUG_MESSAGE(a) a
#endif

#include <memory>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <omp.h>

template<class T>
class Bag
{
protected:
    std::vector<std::shared_ptr<T> > m_bag;
public:

    typedef typename std::vector<std::shared_ptr<T> >::iterator iterator;

    Bag()
    {
    }

    Bag(const Bag<T> &b)
    {
        insert(b);
    }

    virtual ~Bag()
    {
        clear();
    }

    Bag<T>*  copy() const {
        return new Bag<T>(*this);
    }

    void insert(const Bag<T> &b){
        for (auto i = b.cbegin(); i != b.cend(); i++) {
            if(find(*i) > -1) {
                DEBUG_MESSAGE(std::cerr << "Element " << *i << " already present" << std::endl;)
            }
        }
        m_bag.insert(m_bag.cend(), b.cbegin(), b.cend());
    }

    void insert(iterator a, iterator b, iterator c){
        for (auto i = b; i != c; i++) {
            if(find(*i) > -1) {
                DEBUG_MESSAGE(std::cerr << "Element " << *i << " already present" << std::endl;)
            }
        }
        m_bag.insert(a, b, c);
    }

    void insert(iterator a, std::shared_ptr<T> b){
        int i = find(b);
        if(i>-1)
        {
            DEBUG_MESSAGE(std::cerr << "Element " << b << " already present" << std::endl;)
        }
        m_bag.insert(a, b);
    }

    bool empty(){
        return m_bag.empty();
    }

    std::shared_ptr<T> front ()
    {
        return m_bag.front();
    }

    void clear()
    {
        const unsigned int size = m_bag.size();
        //TODO: When uncommented the program does not terminate
#pragma omp parallel for if(size > 39)
        for (unsigned int i = 0; i < size; i++)
        {
            m_bag[i].reset();
        }
        m_bag.clear();
    }

    unsigned int size() const
    {
        return m_bag.size();
    }

    unsigned int max_size() const
    {
        return m_bag.max_size();
    }

    const std::shared_ptr<T> operator[](unsigned int n) const
    {
        return m_bag[n];
    }

    const std::shared_ptr<T> at(unsigned int n) const
    {
        if(n < m_bag.size())
            return m_bag[n];
        throw std::invalid_argument( "Bag.hpp: index out of range" );
    }

    virtual void add(std::shared_ptr<T> el)
    {
        if(find(el) > -1){
            DEBUG_MESSAGE(std::cerr << "Element " << el << " already present" << std::endl;)
        }
        m_bag.push_back(el);
    }

    virtual void push_back(std::shared_ptr<T> el)
    {
        add(el);
    }

    virtual void erase(iterator el)
    {
        m_bag.erase(el);
    }

    virtual void erase(std::shared_ptr<T> el)
    {
        int res = find(el);
        if(res < 0)
        {
            return;
        }
        m_bag.erase(m_bag.begin() + res);
    }

    int find(std::shared_ptr<T> el)
    {
        const int size = m_bag.size();
        if(size == 0) {
            return -1;
        }
        volatile bool found = false;
        int first_index = -1;
        int iteration = 0;

#pragma omp parallel if(size >=40)
        {
            int my_index = -1;
            int i;

            do
            {
#pragma omp critical(iteration)
                {
                    i = iteration++;
                }

                if(i < size && m_bag[i] == el)
                {
                    found = true;
                    my_index = i;
                }
            }
            while (!found && i < size);

#pragma omp critical(reduction)
            if(my_index != -1)
            {
                if(first_index == -1 || my_index < first_index)
                    first_index = my_index;
            }
        }
        return first_index;
    }

    template<class U>
    Bag(Bag<U> const &u)
    {
        this->m_bag = u.m_bag;
    }

    typedef typename std::vector<std::shared_ptr<T> >::const_iterator const_iterator;

    virtual const_iterator cbegin() const
    {
        return m_bag.cbegin();
    }

    virtual const_iterator cend() const
    {
        return m_bag.cend();
    }

    virtual iterator begin()
    {
        return m_bag.begin();
    }

    virtual iterator end()
    {
        return m_bag.end();
    }

};

#endif /* BAG_HPP_ */
<commit_msg>Release version optimization (avoid finds)<commit_after>/*
 * Set.h
 *
 *  Created on: 12.05.2017
 *      Author: frbe5612
 */

#ifndef BAG_HPP_
#define BAG_HPP_

#ifdef NDEBUG
# define DEBUG_MESSAGE(a) /**/
#else
# define DEBUG_MESSAGE(a) a
#endif

#include <memory>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <omp.h>

template <class T>
class Bag
{
protected:
  std::vector<std::shared_ptr<T> > m_bag;
public:

  typedef typename std::vector<std::shared_ptr<T> >::iterator iterator;

  Bag()
  { }

  Bag(const Bag<T> &b)
  {
    insert(b);
  }

  virtual ~Bag()
  {
    clear();
  }

  Bag<T> * copy() const
  {
    return new Bag<T>(*this);
  }

  void insert(const Bag<T> &b)
  {
    #ifndef NDEBUG
    // The debug version check if an inserted element is already present in the collection.
    for (auto i = b.cbegin(); i != b.cend(); i++) {
      if (find(*i) > -1) {
        DEBUG_MESSAGE(std::cerr << "Element " << *i << " already present" << std::endl;
        )
      }
    }
    #endif
    m_bag.insert(m_bag.cend(), b.cbegin(), b.cend());
  }

  void insert(iterator a, iterator b, iterator c)
  {
    #ifndef NDEBUG
    // The debug version check if an inserted element is already present in the collection.
    for (auto i = b; i != c; i++) {
      if (find(*i) > -1) {
        DEBUG_MESSAGE(std::cerr << "Element " << *i << " already present" << std::endl;
        )
      }
    }
    #endif
    m_bag.insert(a, b, c);
  }

  void insert(iterator a, std::shared_ptr<T> b)
  {
    #ifndef NDEBUG
    // The debug version check if an inserted element is already present in the collection.
    int i = find(b);

    if (i > -1) {
      DEBUG_MESSAGE(std::cerr << "Element " << b << " already present" << std::endl;
      )
    }
    #endif
    m_bag.insert(a, b);
  }

  bool empty()
  {
    return m_bag.empty();
  }

  std::shared_ptr<T> front()
  {
    return m_bag.front();
  }

  void clear()
  {
    const unsigned int size = m_bag.size();

    #pragma omp parallel for if(size > 39)
    for (unsigned int i = 0; i < size; i++) {
      m_bag[i].reset();
    }

    m_bag.clear();
  }

  unsigned int size() const
  {
    return m_bag.size();
  }

  unsigned int max_size() const
  {
    return m_bag.max_size();
  }

  const std::shared_ptr<T> operator [] (unsigned int n) const
  {
    return m_bag[n];
  }

  const std::shared_ptr<T> at(unsigned int n) const
  {
    #ifndef NDEBUG
    if (n < m_bag.size()) {
    #endif
    return m_bag[n];

    #ifndef NDEBUG
  }

  throw std::invalid_argument("Bag.hpp: index out of range");
    #endif
  }

  virtual void add(std::shared_ptr<T> el)
  {
    #ifndef NDEBUG
    // The debug version check if an inserted element is already present in the collection.
    if (find(el) > -1) {
      DEBUG_MESSAGE(std::cerr << "Element " << el << " already present" << std::endl;
      )
    }
    #endif
    m_bag.push_back(el);
  }

  virtual void push_back(std::shared_ptr<T> el)
  {
    add(el);
  }

  virtual void erase(iterator el)
  {
    m_bag.erase(el);
  }

  virtual void erase(std::shared_ptr<T> el)
  {
    int res = find(el);

    if (res < 0) {
      return;
    }
    m_bag.erase(m_bag.begin() + res);
  }

  int find(std::shared_ptr<T> el)
  {
    const int size = m_bag.size();

    if (size == 0) {
      return -1;
    }
    volatile bool found = false;
    int first_index     = -1;
    int iteration       = 0;

    #pragma omp parallel if(size >=40)
    {
      int my_index = -1;
      int i;

      do {
        #pragma omp critical(iteration)
        {
          i = iteration++;
        }

        if (i < size && m_bag[i] == el) {
          found    = true;
          my_index = i;
        }
      } while (!found && i < size);

      #pragma omp critical(reduction)
      if (my_index != -1) {
        if (first_index == -1 || my_index < first_index)
          first_index = my_index;
      }
    }
    return first_index;
  } // find

  template <class U>
  Bag(Bag<U> const &u)
  {
    this->m_bag = u.m_bag;
  }

  typedef typename std::vector<std::shared_ptr<T> >::const_iterator const_iterator;

  virtual const_iterator cbegin() const
  {
    return m_bag.cbegin();
  }

  virtual const_iterator cend() const
  {
    return m_bag.cend();
  }

  virtual iterator begin()
  {
    return m_bag.begin();
  }

  virtual iterator end()
  {
    return m_bag.end();
  }
};

#endif /* BAG_HPP_ */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dpsave.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:35:34 $
 *
 *  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 SC_DPSAVE_HXX
#define SC_DPSAVE_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef _LIST_HXX //autogen wg. List
#include <tools/list.hxx>
#endif

#ifndef _COM_SUN_STAR_SHEET_XDIMENSIONSSUPPLIER_HPP_
#include <com/sun/star/sheet/XDimensionsSupplier.hpp>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

namespace com { namespace sun { namespace star { namespace sheet {
    struct DataPilotFieldReference;
    struct DataPilotFieldSortInfo;
    struct DataPilotFieldAutoShowInfo;
    struct DataPilotFieldLayoutInfo;
} } } }

class SvStream;
class ScDPDimensionSaveData;

// --------------------------------------------------------------------
//
//  classes to save Data Pilot settings
//

class ScDPSaveMember
{
private:
    String      aName;
    USHORT      nVisibleMode;
    USHORT      nShowDetailsMode;

public:
                            ScDPSaveMember(const String& rName);
                            ScDPSaveMember(const ScDPSaveMember& r);
                            ScDPSaveMember(SvStream& rStream);
                            ~ScDPSaveMember();

    BOOL                    operator== ( const ScDPSaveMember& r ) const;

    const String&           GetName() const { return aName; }
    BOOL                    HasIsVisible() const;
    void                    SetIsVisible(BOOL bSet);
    BOOL                    GetIsVisible() const { return BOOL(nVisibleMode); }
    BOOL                    HasShowDetails() const;
    void                    SetShowDetails(BOOL bSet);
    BOOL                    GetShowDetails() const { return BOOL(nShowDetailsMode); }

    void                    SetName( const String& rNew );  // used if the source member was renamed (groups)

    void                    WriteToSource( const com::sun::star::uno::Reference<
                                            com::sun::star::uno::XInterface>& xMember );

    void                    Store( SvStream& rStream ) const;
};

class ScDPSaveDimension
{
private:
    String      aName;
    String*     pLayoutName;        // alternative name for layout, not used (yet)
    String*     pSelectedPage;
    BOOL        bIsDataLayout;
    BOOL        bDupFlag;
    USHORT      nOrientation;
    USHORT      nFunction;          // enum GeneralFunction, for data dimensions
    long        nUsedHierarchy;
    USHORT      nShowEmptyMode;     //! at level
    BOOL        bSubTotalDefault;   //! at level
    long        nSubTotalCount;
    USHORT*     pSubTotalFuncs;     // enum GeneralFunction
    ::com::sun::star::sheet::DataPilotFieldReference* pReferenceValue;
    ::com::sun::star::sheet::DataPilotFieldSortInfo*  pSortInfo;            // (level)
    ::com::sun::star::sheet::DataPilotFieldAutoShowInfo* pAutoShowInfo;     // (level)
    ::com::sun::star::sheet::DataPilotFieldLayoutInfo* pLayoutInfo;         // (level)
    List        aMemberList;

public:
                            ScDPSaveDimension(const String& rName, BOOL bDataLayout);
                            ScDPSaveDimension(const ScDPSaveDimension& r);
                            ScDPSaveDimension(SvStream& rStream);
                            ~ScDPSaveDimension();

    BOOL                    operator== ( const ScDPSaveDimension& r ) const;

    const List&             GetMembers() const { return aMemberList; }
    void                    AddMember(ScDPSaveMember* pMember) { aMemberList.Insert(pMember, LIST_APPEND); };

    void                    SetDupFlag(BOOL bSet)   { bDupFlag = bSet; }
    BOOL                    GetDupFlag() const      { return bDupFlag; }

    const String&           GetName() const         { return aName; }
    BOOL                    IsDataLayout() const    { return bIsDataLayout; }

    void                    SetName( const String& rNew );  // used if the source dim was renamed (groups)

    void                    SetOrientation(USHORT nNew);
    void                    SetSubTotals(BOOL bSet);        // to be removed!
    void                    SetSubTotals(long nCount, const USHORT* pFuncs);
    long                    GetSubTotalsCount() const { return nSubTotalCount; }
    USHORT                  GetSubTotalFunc(long nIndex) const { return pSubTotalFuncs[nIndex]; }
    void                    SetShowEmpty(BOOL bSet);
    BOOL                    GetShowEmpty() const { return BOOL(nShowEmptyMode); }
    void                    SetFunction(USHORT nNew);       // enum GeneralFunction
    USHORT                  GetFunction() const { return nFunction; }
    void                    SetUsedHierarchy(long nNew);
    long                    GetUsedHierarchy() const { return nUsedHierarchy; }
    void                    SetLayoutName(const String* pName);
    const String&           GetLayoutName() const;
    BOOL                    HasLayoutName() const;
    void                    ResetLayoutName();

    const ::com::sun::star::sheet::DataPilotFieldReference* GetReferenceValue() const   { return pReferenceValue; }
    void                    SetReferenceValue(const ::com::sun::star::sheet::DataPilotFieldReference* pNew);

    const ::com::sun::star::sheet::DataPilotFieldSortInfo* GetSortInfo() const          { return pSortInfo; }
    void                    SetSortInfo(const ::com::sun::star::sheet::DataPilotFieldSortInfo* pNew);
    const ::com::sun::star::sheet::DataPilotFieldAutoShowInfo* GetAutoShowInfo() const  { return pAutoShowInfo; }
    void                    SetAutoShowInfo(const ::com::sun::star::sheet::DataPilotFieldAutoShowInfo* pNew);
    const ::com::sun::star::sheet::DataPilotFieldLayoutInfo* GetLayoutInfo() const      { return pLayoutInfo; }
    void                    SetLayoutInfo(const ::com::sun::star::sheet::DataPilotFieldLayoutInfo* pNew);

    void                    SetCurrentPage( const String* pPage );      // NULL = no selection (all)
    BOOL                    HasCurrentPage() const;
    const String&           GetCurrentPage() const;

    USHORT                  GetOrientation() const  { return nOrientation; }

    ScDPSaveMember*         GetExistingMemberByName(const String& rName);
    ScDPSaveMember*         GetMemberByName(const String& rName);

    void                    WriteToSource( const com::sun::star::uno::Reference<
                                            com::sun::star::uno::XInterface>& xDim );

    void                    Store( SvStream& rStream ) const;
};

class ScDPSaveData
{
private:
    List        aDimList;
    ScDPDimensionSaveData* pDimensionData;      // settings that create new dimensions
    USHORT      nColumnGrandMode;
    USHORT      nRowGrandMode;
    USHORT      nIgnoreEmptyMode;
    USHORT      nRepeatEmptyMode;
    BOOL        bFilterButton;      // not passed to DataPilotSource
    BOOL        bDrillDown;         // not passed to DataPilotSource

public:
                            ScDPSaveData();
                            ScDPSaveData(const ScDPSaveData& r);
                            ~ScDPSaveData();

    ScDPSaveData&           operator= ( const ScDPSaveData& r );

    BOOL                    operator== ( const ScDPSaveData& r ) const;

    const List&             GetDimensions() const { return aDimList; }
    void                    AddDimension(ScDPSaveDimension* pDim) { aDimList.Insert(pDim, LIST_APPEND); }

    ScDPSaveDimension*      GetDimensionByName(const String& rName);
    ScDPSaveDimension*      GetDataLayoutDimension();

    ScDPSaveDimension*      DuplicateDimension(const String& rName);
    ScDPSaveDimension&      DuplicateDimension(const ScDPSaveDimension& rDim);

    SC_DLLPUBLIC ScDPSaveDimension*     GetExistingDimensionByName(const String& rName);
    ScDPSaveDimension*      GetNewDimensionByName(const String& rName);

    void                    RemoveDimensionByName(const String& rName);

    ScDPSaveDimension*      GetInnermostDimension(USHORT nOrientation);
    long                    GetDataDimensionCount() const;

    void                    SetPosition( ScDPSaveDimension* pDim, long nNew );
    void                    SetColumnGrand( BOOL bSet );
    BOOL                    GetColumnGrand() const { return BOOL(nColumnGrandMode); }
    void                    SetRowGrand( BOOL bSet );
    BOOL                    GetRowGrand() const { return BOOL(nRowGrandMode); }
    void                    SetIgnoreEmptyRows( BOOL bSet );
    BOOL                    GetIgnoreEmptyRows() const { return BOOL(nIgnoreEmptyMode); }
    void                    SetRepeatIfEmpty( BOOL bSet );
    BOOL                    GetRepeatIfEmpty() const { return BOOL(nRepeatEmptyMode); }

    void                    SetFilterButton( BOOL bSet );
    BOOL                    GetFilterButton() const { return bFilterButton; }
    void                    SetDrillDown( BOOL bSet );
    BOOL                    GetDrillDown() const { return bDrillDown; }

    void                    WriteToSource( const com::sun::star::uno::Reference<
                                            com::sun::star::sheet::XDimensionsSupplier>& xSource );

    void                    Store( SvStream& rStream ) const;
    void                    Load( SvStream& rStream );

    BOOL                    IsEmpty() const;

    const ScDPDimensionSaveData* GetExistingDimensionData() const   { return pDimensionData; }
    ScDPDimensionSaveData*  GetDimensionData();     // create if not there
    void                    SetDimensionData( const ScDPDimensionSaveData* pNew );      // copied
};

#endif

<commit_msg>INTEGRATION: CWS dr52 (1.8.340); FILE MERGED 2006/12/20 19:22:04 nn 1.8.340.1: #i63686# use hash map for members in ScDPSaveDimension (patch from Jody)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dpsave.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-22 12:06:44 $
 *
 *  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 SC_DPSAVE_HXX
#define SC_DPSAVE_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef _LIST_HXX //autogen wg. List
#include <tools/list.hxx>
#endif

#ifndef _COM_SUN_STAR_SHEET_XDIMENSIONSSUPPLIER_HPP_
#include <com/sun/star/sheet/XDimensionsSupplier.hpp>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
#include <hash_map>
#include <list>

namespace com { namespace sun { namespace star { namespace sheet {
    struct DataPilotFieldReference;
    struct DataPilotFieldSortInfo;
    struct DataPilotFieldAutoShowInfo;
    struct DataPilotFieldLayoutInfo;
} } } }

class SvStream;
class ScDPDimensionSaveData;

// --------------------------------------------------------------------
//
//  classes to save Data Pilot settings
//

class ScDPSaveMember
{
private:
    String      aName;
    USHORT      nVisibleMode;
    USHORT      nShowDetailsMode;

public:
                            ScDPSaveMember(const String& rName);
                            ScDPSaveMember(const ScDPSaveMember& r);
                            ScDPSaveMember(SvStream& rStream);
                            ~ScDPSaveMember();

    BOOL                    operator== ( const ScDPSaveMember& r ) const;

    const String&           GetName() const { return aName; }
    BOOL                    HasIsVisible() const;
    void                    SetIsVisible(BOOL bSet);
    BOOL                    GetIsVisible() const { return BOOL(nVisibleMode); }
    BOOL                    HasShowDetails() const;
    void                    SetShowDetails(BOOL bSet);
    BOOL                    GetShowDetails() const { return BOOL(nShowDetailsMode); }

    void                    SetName( const String& rNew );  // used if the source member was renamed (groups)

    void                    WriteToSource( const com::sun::star::uno::Reference<
                                            com::sun::star::uno::XInterface>& xMember );

    void                    Store( SvStream& rStream ) const;
};

class ScDPSaveDimension
{
private:
    String      aName;
    String*     pLayoutName;        // alternative name for layout, not used (yet)
    String*     pSelectedPage;
    BOOL        bIsDataLayout;
    BOOL        bDupFlag;
    USHORT      nOrientation;
    USHORT      nFunction;          // enum GeneralFunction, for data dimensions
    long        nUsedHierarchy;
    USHORT      nShowEmptyMode;     //! at level
    BOOL        bSubTotalDefault;   //! at level
    long        nSubTotalCount;
    USHORT*     pSubTotalFuncs;     // enum GeneralFunction
    ::com::sun::star::sheet::DataPilotFieldReference* pReferenceValue;
    ::com::sun::star::sheet::DataPilotFieldSortInfo*  pSortInfo;            // (level)
    ::com::sun::star::sheet::DataPilotFieldAutoShowInfo* pAutoShowInfo;     // (level)
    ::com::sun::star::sheet::DataPilotFieldLayoutInfo* pLayoutInfo;         // (level)

public:
    typedef std::hash_map <String, ScDPSaveMember*, rtl::OUStringHash> MemberHash;
    typedef std::list <ScDPSaveMember*>                                MemberList;
private:
    MemberHash maMemberHash;
    MemberList maMemberList;
public:
                            ScDPSaveDimension(const String& rName, BOOL bDataLayout);
                            ScDPSaveDimension(const ScDPSaveDimension& r);
                            ScDPSaveDimension(SvStream& rStream);
                            ~ScDPSaveDimension();

    BOOL                    operator== ( const ScDPSaveDimension& r ) const;

    const MemberList&       GetMembers() const { return maMemberList; }
    void                    AddMember(ScDPSaveMember* pMember);

    void                    SetDupFlag(BOOL bSet)   { bDupFlag = bSet; }
    BOOL                    GetDupFlag() const      { return bDupFlag; }

    const String&           GetName() const         { return aName; }
    BOOL                    IsDataLayout() const    { return bIsDataLayout; }

    void                    SetName( const String& rNew );  // used if the source dim was renamed (groups)

    void                    SetOrientation(USHORT nNew);
    void                    SetSubTotals(BOOL bSet);        // to be removed!
    void                    SetSubTotals(long nCount, const USHORT* pFuncs);
    long                    GetSubTotalsCount() const { return nSubTotalCount; }
    USHORT                  GetSubTotalFunc(long nIndex) const { return pSubTotalFuncs[nIndex]; }
    void                    SetShowEmpty(BOOL bSet);
    BOOL                    GetShowEmpty() const { return BOOL(nShowEmptyMode); }
    void                    SetFunction(USHORT nNew);       // enum GeneralFunction
    USHORT                  GetFunction() const { return nFunction; }
    void                    SetUsedHierarchy(long nNew);
    long                    GetUsedHierarchy() const { return nUsedHierarchy; }
    void                    SetLayoutName(const String* pName);
    const String&           GetLayoutName() const;
    BOOL                    HasLayoutName() const;
    void                    ResetLayoutName();

    const ::com::sun::star::sheet::DataPilotFieldReference* GetReferenceValue() const   { return pReferenceValue; }
    void                    SetReferenceValue(const ::com::sun::star::sheet::DataPilotFieldReference* pNew);

    const ::com::sun::star::sheet::DataPilotFieldSortInfo* GetSortInfo() const          { return pSortInfo; }
    void                    SetSortInfo(const ::com::sun::star::sheet::DataPilotFieldSortInfo* pNew);
    const ::com::sun::star::sheet::DataPilotFieldAutoShowInfo* GetAutoShowInfo() const  { return pAutoShowInfo; }
    void                    SetAutoShowInfo(const ::com::sun::star::sheet::DataPilotFieldAutoShowInfo* pNew);
    const ::com::sun::star::sheet::DataPilotFieldLayoutInfo* GetLayoutInfo() const      { return pLayoutInfo; }
    void                    SetLayoutInfo(const ::com::sun::star::sheet::DataPilotFieldLayoutInfo* pNew);

    void                    SetCurrentPage( const String* pPage );      // NULL = no selection (all)
    BOOL                    HasCurrentPage() const;
    const String&           GetCurrentPage() const;

    USHORT                  GetOrientation() const  { return nOrientation; }

    ScDPSaveMember*         GetExistingMemberByName(const String& rName);
    ScDPSaveMember*         GetMemberByName(const String& rName);

    void                    WriteToSource( const com::sun::star::uno::Reference<
                                            com::sun::star::uno::XInterface>& xDim );

    void                    Store( SvStream& rStream ) const;
};

class ScDPSaveData
{
private:
    List        aDimList;
    ScDPDimensionSaveData* pDimensionData;      // settings that create new dimensions
    USHORT      nColumnGrandMode;
    USHORT      nRowGrandMode;
    USHORT      nIgnoreEmptyMode;
    USHORT      nRepeatEmptyMode;
    BOOL        bFilterButton;      // not passed to DataPilotSource
    BOOL        bDrillDown;         // not passed to DataPilotSource

public:
                            ScDPSaveData();
                            ScDPSaveData(const ScDPSaveData& r);
                            ~ScDPSaveData();

    ScDPSaveData&           operator= ( const ScDPSaveData& r );

    BOOL                    operator== ( const ScDPSaveData& r ) const;

    const List&             GetDimensions() const { return aDimList; }
    void                    AddDimension(ScDPSaveDimension* pDim) { aDimList.Insert(pDim, LIST_APPEND); }

    ScDPSaveDimension*      GetDimensionByName(const String& rName);
    ScDPSaveDimension*      GetDataLayoutDimension();

    ScDPSaveDimension*      DuplicateDimension(const String& rName);
    ScDPSaveDimension&      DuplicateDimension(const ScDPSaveDimension& rDim);

    SC_DLLPUBLIC ScDPSaveDimension*     GetExistingDimensionByName(const String& rName);
    ScDPSaveDimension*      GetNewDimensionByName(const String& rName);

    void                    RemoveDimensionByName(const String& rName);

    ScDPSaveDimension*      GetInnermostDimension(USHORT nOrientation);
    long                    GetDataDimensionCount() const;

    void                    SetPosition( ScDPSaveDimension* pDim, long nNew );
    void                    SetColumnGrand( BOOL bSet );
    BOOL                    GetColumnGrand() const { return BOOL(nColumnGrandMode); }
    void                    SetRowGrand( BOOL bSet );
    BOOL                    GetRowGrand() const { return BOOL(nRowGrandMode); }
    void                    SetIgnoreEmptyRows( BOOL bSet );
    BOOL                    GetIgnoreEmptyRows() const { return BOOL(nIgnoreEmptyMode); }
    void                    SetRepeatIfEmpty( BOOL bSet );
    BOOL                    GetRepeatIfEmpty() const { return BOOL(nRepeatEmptyMode); }

    void                    SetFilterButton( BOOL bSet );
    BOOL                    GetFilterButton() const { return bFilterButton; }
    void                    SetDrillDown( BOOL bSet );
    BOOL                    GetDrillDown() const { return bDrillDown; }

    void                    WriteToSource( const com::sun::star::uno::Reference<
                                            com::sun::star::sheet::XDimensionsSupplier>& xSource );

    void                    Store( SvStream& rStream ) const;
    void                    Load( SvStream& rStream );

    BOOL                    IsEmpty() const;

    const ScDPDimensionSaveData* GetExistingDimensionData() const   { return pDimensionData; }
    ScDPDimensionSaveData*  GetDimensionData();     // create if not there
    void                    SetDimensionData( const ScDPDimensionSaveData* pNew );      // copied
};

#endif

<|endoftext|>