<commit_before>/*!
 * @file bioparser_test.cpp
 *
 * @brief Bioparser unit test source file
 */

#include "bioparser_test_config.h"

#include "bioparser/bioparser.hpp"
#include "gtest/gtest.h"

class Read {
public:
    Read(uint64_t id_, const char* name_, uint32_t name_length_,
        const char* data_, uint32_t data_length_)
            : id(id_), name(name_, name_length_), data(data_, data_length_),
            quality() {
    }

    Read(uint64_t id_, const char* name_, uint32_t name_length_,
        const char* data_, uint32_t data_length_,
        const char* quality_, uint32_t quality_length_)
            : id(id_), name(name_, name_length_), data(data_, data_length_),
            quality(quality_, quality_length_) {
    }

    ~Read() {}

    uint64_t id;
    std::string name;
    std::string data;
    std::string quality;
};

void reads_summary(uint32_t& name_size, uint32_t& data_size, uint32_t& quality_size,
    const std::vector<std::unique_ptr<Read>>& reads) {

    name_size = 0;
    data_size = 0;
    quality_size = 0;
    for (const auto& it: reads) {
        name_size += it->name.size();
        data_size += it->data.size();
        quality_size += it->quality.size();
    }
}

class Overlap {
public:
    Overlap(uint64_t id_, uint32_t a_id_, uint32_t b_id_, double error, uint32_t minmers,
        uint32_t a_rc, uint32_t a_begin_, uint32_t a_end_, uint32_t a_length_,
        uint32_t b_rc, uint32_t b_begin_, uint32_t b_end_, uint32_t b_length_)
            : id(id_),
            a_id(a_id_ - 1), a_begin(a_begin_), a_end(a_end_), a_length(a_length_),
            b_id(b_id_ - 1), b_begin(b_begin_), b_end(b_end_), b_length(b_length_),
            orientation(a_rc == b_rc ? '+' : '-') {
    }

    Overlap(uint64_t id_, const char* a_name, uint32_t a_name_length,
        uint32_t a_length_, uint32_t a_begin_, uint32_t a_end_, char orientation_,
        const char* b_name, uint32_t b_name_length, uint32_t b_length_,
        uint32_t b_begin_, uint32_t b_end_, uint32_t matching_bases,
        uint32_t overlap_length, uint32_t quality)
            : id(id_),
            a_id(atoi(a_name) - 1), a_begin(a_begin_), a_end(a_end_), a_length(a_length_),
            b_id(atoi(b_name) - 1), b_begin(b_begin_), b_end(b_end_), b_length(b_length_),
            orientation(orientation_) {
    }

    ~Overlap() {}

    uint64_t id;
    uint32_t a_id;
    uint32_t a_begin;
    uint32_t a_end;
    uint32_t a_length;
    uint32_t b_id;
    uint32_t b_begin;
    uint32_t b_end;
    uint32_t b_length;
    char orientation;
};

class BioparserFastaTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Read, bioparser::FastaReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Read>> reader;
};

class BioparserFastqTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Read, bioparser::FastqReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Read>> reader;
};

class BioparserMhapTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Overlap, bioparser::MhapReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Overlap>> reader;
};

class BioparserPafTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Overlap, bioparser::PafReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Overlap>> reader;
};

TEST(BioparserTest, CreateReaderError) {
    EXPECT_DEATH((bioparser::createReader<Read, bioparser::FastaReader>("")),
        "bioparser::createReader error: unable to open file");
}

TEST_F(BioparserFastaTest, ReadWhole) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    std::vector<std::unique_ptr<Read>> reads;
    reader->read_objects(reads, -1);

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(14U, reads.size());
    EXPECT_EQ(75U, reads_name_size);
    EXPECT_EQ(109117U, reads_data_size);
    EXPECT_EQ(0U, reads_quality_size);
}

TEST_F(BioparserFastaTest, ReadInChunks) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    uint32_t size_in_bytes = 25 * 1024; // 25 kB
    std::vector<std::unique_ptr<Read>> reads;
    while (reader->read_objects(reads, size_in_bytes)) {
    }

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(14U, reads.size());
    EXPECT_EQ(75U, reads_name_size);
    EXPECT_EQ(109117U, reads_data_size);
    EXPECT_EQ(0U, reads_quality_size);
}

TEST_F(BioparserFastaTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.fastq");
    std::vector<std::unique_ptr<Read>> reads;

    EXPECT_DEATH(reader->read_objects(reads, -1),
        "bioparser::FastaReader error: invalid file format!");
}

TEST_F(BioparserFastaTest, ChunkSizeError) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    uint32_t size_in_bytes = 10 * 1024; // 10 kB
    std::vector<std::unique_ptr<Read>> reads;
    EXPECT_DEATH(reader->read_objects(reads, size_in_bytes),
        "bioparser::FastaReader error: too small chunk size!");
}

TEST_F(BioparserFastqTest, ReadWhole) {

    SetUp(bioparser_test_data_path + "sample.fastq");

    std::vector<std::unique_ptr<Read>> reads;
    reader->read_objects(reads, -1);

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(13U, reads.size());
    EXPECT_EQ(17U, reads_name_size);
    EXPECT_EQ(108140U, reads_data_size);
    EXPECT_EQ(108140U, reads_quality_size);
}

TEST_F(BioparserFastqTest, ReadInChunks) {

    SetUp(bioparser_test_data_path + "sample.fastq");

    uint32_t size_in_bytes = 50 * 1024; // 50 kB
    std::vector<std::unique_ptr<Read>> reads;
    while (reader->read_objects(reads, size_in_bytes)) {
    }

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(13U, reads.size());
    EXPECT_EQ(17U, reads_name_size);
    EXPECT_EQ(108140U, reads_data_size);
    EXPECT_EQ(108140U, reads_quality_size);
}

TEST_F(BioparserFastqTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    std::vector<std::unique_ptr<Read>> reads;

    EXPECT_DEATH(reader->read_objects(reads, -1),
        "bioparser::FastqReader error: invalid file format!");
}

TEST_F(BioparserFastqTest, ChunkSizeError) {

    SetUp(bioparser_test_data_path + "sample.fastq");

    uint32_t size_in_bytes = 10 * 1024; // 10 kB
    std::vector<std::unique_ptr<Read>> reads;
    EXPECT_DEATH(reader->read_objects(reads, size_in_bytes),
        "bioparser::FastqReader error: too small chunk size!");
}

TEST_F(BioparserMhapTest, ReadWhole) {

    SetUp(bioparser_test_data_path + "sample.mhap");

    std::vector<std::unique_ptr<Overlap>> overlaps;
    reader->read_objects(overlaps, -1);

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserMhapTest, ReadFileInChunks) {

    SetUp(bioparser_test_data_path + "sample.mhap");

    uint32_t size_in_bytes = 4 * 1024; // 1 kB
    std::vector<std::unique_ptr<Overlap>> overlaps;
    while (reader->read_objects(overlaps, size_in_bytes)) {
    }

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserMhapTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.paf");

    std::vector<std::unique_ptr<Overlap>> overlaps;

    EXPECT_DEATH(reader->read_objects(overlaps, -1),
        "bioparser::MhapReader error: invalid file format!");
}

TEST_F(BioparserPafTest, ReadFileAtOnce) {

    SetUp(bioparser_test_data_path + "sample.paf");

    std::vector<std::unique_ptr<Overlap>> overlaps;
    reader->read_objects(overlaps, -1);

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserPafTest, ReadFileInChunks) {

    SetUp(bioparser_test_data_path + "sample.paf");

    uint32_t size_in_bytes = 4 * 1024; // 1 kB
    std::vector<std::unique_ptr<Overlap>> overlaps;
    while (reader->read_objects(overlaps, size_in_bytes)) {
    }

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserPafTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.mhap");

    std::vector<std::unique_ptr<Overlap>> overlaps;

    EXPECT_DEATH(reader->read_objects(overlaps, -1),
        "bioparser::PafReader error: invalid file format!");
}
<commit_msg>Test refactor<commit_after>/*!
 * @file bioparser_test.cpp
 *
 * @brief Bioparser unit test source file
 */

#include "bioparser_test_config.h"

#include "bioparser/bioparser.hpp"
#include "gtest/gtest.h"

class Read {
public:
    Read(uint64_t id, const char* name, uint32_t name_length,
        const char* data, uint32_t data_length)
            : id_(id), name_(name, name_length), data_(data, data_length),
            quality_() {
    }

    Read(uint64_t id, const char* name, uint32_t name_length,
        const char* data, uint32_t data_length,
        const char* quality, uint32_t quality_length)
            : id_(id), name_(name, name_length), data_(data, data_length),
            quality_(quality, quality_length) {
    }

    ~Read() {}

    uint64_t id_;
    std::string name_;
    std::string data_;
    std::string quality_;
};

void reads_summary(uint32_t& name_size, uint32_t& data_size, uint32_t& quality_size,
    const std::vector<std::unique_ptr<Read>>& reads) {

    name_size = 0;
    data_size = 0;
    quality_size = 0;
    for (const auto& it: reads) {
        name_size += it->name_.size();
        data_size += it->data_.size();
        quality_size += it->quality_.size();
    }
}

class Overlap {
public:
    Overlap(uint64_t id, uint32_t a_id, uint32_t b_id, double error, uint32_t minmers,
        uint32_t a_rc, uint32_t a_begin, uint32_t a_end, uint32_t a_length,
        uint32_t b_rc, uint32_t b_begin, uint32_t b_end, uint32_t b_length)
            : id_(id),
            a_id_(a_id - 1), a_begin_(a_begin), a_end_(a_end), a_length_(a_length),
            b_id_(b_id - 1), b_begin_(b_begin), b_end_(b_end), b_length_(b_length),
            orientation_(a_rc == b_rc ? '+' : '-') {
    }

    Overlap(uint64_t id, const char* a_name, uint32_t a_name_length,
        uint32_t a_length, uint32_t a_begin, uint32_t a_end, char orientation,
        const char* b_name, uint32_t b_name_length, uint32_t b_length,
        uint32_t b_begin, uint32_t b_end, uint32_t matching_bases,
        uint32_t overlap_length, uint32_t quality)
            : id_(id),
            a_id_(atoi(a_name) - 1), a_begin_(a_begin), a_end_(a_end), a_length_(a_length),
            b_id_(atoi(b_name) - 1), b_begin_(b_begin), b_end_(b_end), b_length_(b_length),
            orientation_(orientation) {
    }

    ~Overlap() {}

    uint64_t id_;
    uint32_t a_id_;
    uint32_t a_begin_;
    uint32_t a_end_;
    uint32_t a_length_;
    uint32_t b_id_;
    uint32_t b_begin_;
    uint32_t b_end_;
    uint32_t b_length_;
    char orientation_;
};

class BioparserFastaTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Read, bioparser::FastaReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Read>> reader;
};

class BioparserFastqTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Read, bioparser::FastqReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Read>> reader;
};

class BioparserMhapTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Overlap, bioparser::MhapReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Overlap>> reader;
};

class BioparserPafTest: public ::testing::Test {
public:
    void SetUp(const std::string& file_name) {
        reader = bioparser::createReader<Overlap, bioparser::PafReader>(file_name);
    }

    void TearDown() {}

    std::unique_ptr<bioparser::Reader<Overlap>> reader;
};

TEST(BioparserTest, CreateReaderError) {
    EXPECT_DEATH((bioparser::createReader<Read, bioparser::FastaReader>("")),
        "bioparser::createReader error: unable to open file");
}

TEST_F(BioparserFastaTest, ReadWhole) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    std::vector<std::unique_ptr<Read>> reads;
    reader->read_objects(reads, -1);

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(14U, reads.size());
    EXPECT_EQ(75U, reads_name_size);
    EXPECT_EQ(109117U, reads_data_size);
    EXPECT_EQ(0U, reads_quality_size);
}

TEST_F(BioparserFastaTest, ReadInChunks) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    uint32_t size_in_bytes = 25 * 1024; // 25 kB
    std::vector<std::unique_ptr<Read>> reads;
    while (reader->read_objects(reads, size_in_bytes)) {
    }

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(14U, reads.size());
    EXPECT_EQ(75U, reads_name_size);
    EXPECT_EQ(109117U, reads_data_size);
    EXPECT_EQ(0U, reads_quality_size);
}

TEST_F(BioparserFastaTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.fastq");
    std::vector<std::unique_ptr<Read>> reads;

    EXPECT_DEATH(reader->read_objects(reads, -1),
        "bioparser::FastaReader error: invalid file format!");
}

TEST_F(BioparserFastaTest, ChunkSizeError) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    uint32_t size_in_bytes = 10 * 1024; // 10 kB
    std::vector<std::unique_ptr<Read>> reads;
    EXPECT_DEATH(reader->read_objects(reads, size_in_bytes),
        "bioparser::FastaReader error: too small chunk size!");
}

TEST_F(BioparserFastqTest, ReadWhole) {

    SetUp(bioparser_test_data_path + "sample.fastq");

    std::vector<std::unique_ptr<Read>> reads;
    reader->read_objects(reads, -1);

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(13U, reads.size());
    EXPECT_EQ(17U, reads_name_size);
    EXPECT_EQ(108140U, reads_data_size);
    EXPECT_EQ(108140U, reads_quality_size);
}

TEST_F(BioparserFastqTest, ReadInChunks) {

    SetUp(bioparser_test_data_path + "sample.fastq");

    uint32_t size_in_bytes = 50 * 1024; // 50 kB
    std::vector<std::unique_ptr<Read>> reads;
    while (reader->read_objects(reads, size_in_bytes)) {
    }

    uint32_t reads_name_size = 0, reads_data_size = 0, reads_quality_size = 0;
    reads_summary(reads_name_size, reads_data_size, reads_quality_size, reads);

    EXPECT_EQ(13U, reads.size());
    EXPECT_EQ(17U, reads_name_size);
    EXPECT_EQ(108140U, reads_data_size);
    EXPECT_EQ(108140U, reads_quality_size);
}

TEST_F(BioparserFastqTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.fasta");

    std::vector<std::unique_ptr<Read>> reads;

    EXPECT_DEATH(reader->read_objects(reads, -1),
        "bioparser::FastqReader error: invalid file format!");
}

TEST_F(BioparserFastqTest, ChunkSizeError) {

    SetUp(bioparser_test_data_path + "sample.fastq");

    uint32_t size_in_bytes = 10 * 1024; // 10 kB
    std::vector<std::unique_ptr<Read>> reads;
    EXPECT_DEATH(reader->read_objects(reads, size_in_bytes),
        "bioparser::FastqReader error: too small chunk size!");
}

TEST_F(BioparserMhapTest, ReadWhole) {

    SetUp(bioparser_test_data_path + "sample.mhap");

    std::vector<std::unique_ptr<Overlap>> overlaps;
    reader->read_objects(overlaps, -1);

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserMhapTest, ReadFileInChunks) {

    SetUp(bioparser_test_data_path + "sample.mhap");

    uint32_t size_in_bytes = 4 * 1024; // 1 kB
    std::vector<std::unique_ptr<Overlap>> overlaps;
    while (reader->read_objects(overlaps, size_in_bytes)) {
    }

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserMhapTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.paf");

    std::vector<std::unique_ptr<Overlap>> overlaps;

    EXPECT_DEATH(reader->read_objects(overlaps, -1),
        "bioparser::MhapReader error: invalid file format!");
}

TEST_F(BioparserPafTest, ReadFileAtOnce) {

    SetUp(bioparser_test_data_path + "sample.paf");

    std::vector<std::unique_ptr<Overlap>> overlaps;
    reader->read_objects(overlaps, -1);

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserPafTest, ReadFileInChunks) {

    SetUp(bioparser_test_data_path + "sample.paf");

    uint32_t size_in_bytes = 4 * 1024; // 1 kB
    std::vector<std::unique_ptr<Overlap>> overlaps;
    while (reader->read_objects(overlaps, size_in_bytes)) {
    }

    EXPECT_EQ(150U, overlaps.size());
}

TEST_F(BioparserPafTest, FormatError) {

    SetUp(bioparser_test_data_path + "sample.mhap");

    std::vector<std::unique_ptr<Overlap>> overlaps;

    EXPECT_DEATH(reader->read_objects(overlaps, -1),
        "bioparser::PafReader error: invalid file format!");
}
<|endoftext|>


<commit_before>/*
 * moses-perf.cc
 *
 * Measure moses performance.
 *
 * This program measures performance by repeating a caluclation multiple times,
 * but with different random seeds, and then computes the aveage runtime.
 *
 * This program takes the same arguments as the moses-exec executable.
 *
 * Linas Vepstas January 2012
 */

#include <sys/time.h>
#include "../main/moses_exec.h"

using namespace std;
using namespace opencog::moses;

void measure(vector<string> arguments)
{
    struct timeval total;
    total.tv_sec = 0;
    total.tv_usec = 0;

    int nreps = 10;

    printf("Will run %d repetitions with different random seeds\n", nreps);

    for (int i=0; i<nreps; i++)
    {
        // Each run gets a new random seed (use the -r option for this).
        vector<string> args = arguments;
        stringstream ss;
        ss << "-r" << i;
        args.push_back(ss.str());

        // Run and measure.
        struct timeval start, stop, elapsed;
        gettimeofday(&start, NULL);
        moses_exec(args);
        gettimeofday(&stop, NULL);
        timersub(&stop, &start, &elapsed);

        timeradd(&total, &elapsed, &total);
        printf("Run %d Time %ld.%06ld seconds\n", i, elapsed.tv_sec, elapsed.tv_usec);
    }
    printf("Total time %ld.%06ld seconds\n", total.tv_sec, total.tv_usec);

    time_t avg_sec = total.tv_sec / nreps;
    suseconds_t avg_usec = total.tv_sec - nreps * avg_sec;
    avg_usec *= 1000000;
    avg_usec += total.tv_usec;
    avg_usec /= nreps;

    printf("Average time %ld.%06ld seconds\n", avg_sec, avg_usec);
}

int main(int argc, char *argv[])
{
    vector<string> arguments;
    arguments.push_back("moses-exec");
    for (int i=1; i<argc; i++)
        arguments.push_back(argv[i]);

    measure(arguments);

    return 0;
}
<commit_msg>moses-perf: print root-mean-square times too<commit_after>/*
 * moses-perf.cc
 *
 * Measure moses performance.
 *
 * This program measures performance by repeating a calculation multiple times,
 * but with different random seeds, and then computes the aveage runtime.
 *
 * This program takes the same arguments as the moses-exec executable.
 *
 * Caveat: this measures elapsed wall-clock time, and not cpu time.
 *
 * Linas Vepstas January 2012
 */

#include <sys/time.h>
#include "../main/moses_exec.h"

using namespace std;
using namespace opencog::moses;

void measure(vector<string> arguments)
{
    struct timeval total;
    total.tv_sec = 0;
    total.tv_usec = 0;

    double tsq = 0.0; // for computing variance

    int nreps = 10;

    printf("Will run %d repetitions with different random seeds\n", nreps);
    fflush (stdout);

    for (int i=0; i<nreps; i++)
    {
        // Each run gets a new random seed (use the -r option for this).
        vector<string> args = arguments;
        stringstream ss;
        ss << "-r" << i;
        args.push_back(ss.str());

        // Run and measure.
        struct timeval start, stop, elapsed;
        gettimeofday(&start, NULL);
        moses_exec(args);
        gettimeofday(&stop, NULL);
        timersub(&stop, &start, &elapsed);

        timeradd(&total, &elapsed, &total);
        printf("Run %d Time %ld.%06ld seconds\n", i, elapsed.tv_sec, elapsed.tv_usec);
        fflush (stdout);

        // We also want the variance...
        tsq += elapsed.tv_sec * elapsed.tv_sec;
        tsq += 1.0e-6 * ((double) 2 * elapsed.tv_sec * elapsed.tv_usec);
        tsq += 1.0e-12 * ((double) elapsed.tv_usec * elapsed.tv_usec);
    }
    printf("Total time %ld.%06ld seconds\n", total.tv_sec, total.tv_usec);

    time_t avg_sec = total.tv_sec / nreps;
    suseconds_t avg_usec = total.tv_sec - nreps * avg_sec;
    avg_usec *= 1000000;
    avg_usec += total.tv_usec;
    avg_usec /= nreps;

    printf("Average time %ld.%06ld seconds\n", avg_sec, avg_usec);

    // Now compute the rms.
    double avg = avg_sec + 1.0e-6 *((double) avg_usec);
    tsq /= nreps;
    tsq -= avg*avg;
    tsq = sqrt(tsq);

    printf("RMS time: %f seconds\n", tsq);
}

int main(int argc, char *argv[])
{
    vector<string> arguments;
    arguments.push_back("moses-exec");
    for (int i=1; i<argc; i++)
        arguments.push_back(argv[i]);

    measure(arguments);

    return 0;
}
<|endoftext|>


<commit_before>
// The files containing the tree of child classes of |Body| must be included in
// the order of inheritance to avoid circular dependencies.  This class will end
// up being reincluded as part of the implementation of its parent.
#ifndef PRINCIPIA_PHYSICS_MASSIVE_BODY_HPP_
#include "physics/massive_body.hpp"
#else
#ifndef PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#define PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_

#include <experimental/optional>
#include <vector>

#include "geometry/grassmann.hpp"
#include "geometry/rotation.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"

namespace principia {
namespace physics {
namespace internal_rotating_body {

using geometry::AngularVelocity;
using geometry::Instant;
using geometry::Rotation;
using geometry::Vector;
using quantities::Angle;
using quantities::AngularFrequency;
using quantities::Length;

template<typename Frame>
class RotatingBody : public MassiveBody {
  static_assert(Frame::is_inertial, "Frame must be inertial");

 public:
  class Parameters {
   public:
    // |reference_angle| is the angle of the prime meridian at
    // |reference_instant|.  |angular_frequency| gives the rate of rotation of
    // the body around the pole (it may be negative, as is the convention for
    // planets and satellites whose rotation is retrograde).  The direction of
    // the pole is specified in |Frame| using |right_ascension_of_pole| and
    // |declination_of_pole|.
    Parameters(Length const& mean_radius,
               Angle const& reference_angle,
               Instant const& reference_instant,
               AngularFrequency const& angular_frequency,
               Angle const& right_ascension_of_pole,
               Angle const& declination_of_pole);

   private:
    Length const mean_radius_;
    Angle const reference_angle_;
    Instant const reference_instant_;
    AngularFrequency const angular_frequency_;
    Angle const right_ascension_of_pole_;
    Angle const declination_of_pole_;
    template<typename F>
    friend class RotatingBody;
  };

  RotatingBody(MassiveBody::Parameters const& massive_body_parameters,
               Parameters const& parameters);
  ~RotatingBody() = default;

  // Returns the radius passed at construction.
  Length mean_radius() const override;

  // Returns the direction defined by the right ascension and declination passed
  // at construction.
  Vector<double, Frame> const& polar_axis() const;

  // Returns the right ascension passed at construction.
  Angle const& right_ascension_of_pole() const;

  // Returns the declination at construction.
  Angle const& declination_of_pole() const;

  // Returns the angular frequency passed at construction.
  AngularFrequency const& angular_frequency() const;

  // Returns the angular velocity defined by the right ascension, declination,
  // and angular frequency passed at construction.
  AngularVelocity<Frame> const& angular_velocity() const;

  // Returns the position at time |t|.
  Angle AngleAt(Instant const& t) const;

  // Returns the rotation relating the reference frame of the surface of this
  // body to |Frame|.  The reference frame of the surface is defined as follows:
  //   - the z axis is the |polar_axis|;
  //   - the x axis points from the centre of the body to the reference
  //     meridian;
  //   - the reference frame has the same handedness as |Frame|.
  // Following this definition,
  //   Displacement<SurfaceFrame>(RadiusLatitudeLongitude(r, φ, λ))
  // converts planetocentric coordinates to a displacement from the body centre
  // in the surface frame.  Note that RadiusLatitudeLongitude should *not* be
  // used for planetographic coordinates, which use a latitude defined from
  // a reference ellipsoid, and a longitude around the negative pole---except
  // for the Earth, the Moon, and the Sun.
  // In the case of the Earth, see geodetic vs. geocentric latitudes.
  template<typename SurfaceFrame>
  Rotation<SurfaceFrame, Frame> FromSurfaceFrame(Instant const& t) const;

  // Returns the rotation at time |t|.
  Rotation<Frame, Frame> RotationAt(Instant const& t) const;

  // Returns false.
  bool is_massless() const override;

  // Returns true.
  bool is_oblate() const override;

  void WriteToMessage(not_null<serialization::Body*> message) const override;

  void WriteToMessage(
      not_null<serialization::MassiveBody*> message) const override;

  // Fails if the |RotatingBody| extension is absent from the message.
  static not_null<std::unique_ptr<RotatingBody<Frame>>> ReadFromMessage(
      serialization::RotatingBody const& message,
      MassiveBody::Parameters const& massive_body_parameters);

 private:
  Parameters const parameters_;
  Vector<double, Frame> const polar_axis_;
  AngularVelocity<Frame> const angular_velocity_;
};

}  // namespace internal_rotating_body

using internal_rotating_body::RotatingBody;

}  // namespace physics
}  // namespace principia

#include "physics/rotating_body_body.hpp"

#endif  // PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#endif  // PRINCIPIA_PHYSICS_MASSIVE_BODY_HPP_
<commit_msg>why were there 7 deletes in that line O_o<commit_after>
// The files containing the tree of child classes of |Body| must be included in
// the order of inheritance to avoid circular dependencies.  This class will end
// up being reincluded as part of the implementation of its parent.
#ifndef PRINCIPIA_PHYSICS_MASSIVE_BODY_HPP_
#include "physics/massive_body.hpp"
#else
#ifndef PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#define PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_

#include <experimental/optional>
#include <vector>

#include "geometry/grassmann.hpp"
#include "geometry/rotation.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"

namespace principia {
namespace physics {
namespace internal_rotating_body {

using geometry::AngularVelocity;
using geometry::Instant;
using geometry::Rotation;
using geometry::Vector;
using quantities::Angle;
using quantities::AngularFrequency;
using quantities::Length;

template<typename Frame>
class RotatingBody : public MassiveBody {
  static_assert(Frame::is_inertial, "Frame must be inertial");

 public:
  class Parameters {
   public:
    // |reference_angle| is the angle of the prime meridian at
    // |reference_instant|.  |angular_frequency| gives the rate of rotation of
    // the body around the pole (it may be negative, as is the convention for
    // planets and satellites whose rotation is retrograde).  The direction of
    // the pole is specified in |Frame| using |right_ascension_of_pole| and
    // |declination_of_pole|.
    Parameters(Length const& mean_radius,
               Angle const& reference_angle,
               Instant const& reference_instant,
               AngularFrequency const& angular_frequency,
               Angle const& right_ascension_of_pole,
               Angle const& declination_of_pole);

   private:
    Length const mean_radius_;
    Angle const reference_angle_;
    Instant const reference_instant_;
    AngularFrequency const angular_frequency_;
    Angle const right_ascension_of_pole_;
    Angle const declination_of_pole_;
    template<typename F>
    friend class RotatingBody;
  };

  RotatingBody(MassiveBody::Parameters const& massive_body_parameters,
               Parameters const& parameters);
  ~RotatingBody() = default;

  // Returns the radius passed at construction.
  Length mean_radius() const override;

  // Returns the direction defined by the right ascension and declination passed
  // at construction.
  Vector<double, Frame> const& polar_axis() const;

  // Returns the right ascension passed at construction.
  Angle const& right_ascension_of_pole() const;

  // Returns the declination at construction.
  Angle const& declination_of_pole() const;

  // Returns the angular frequency passed at construction.
  AngularFrequency const& angular_frequency() const;

  // Returns the angular velocity defined by the right ascension, declination,
  // and angular frequency passed at construction.
  AngularVelocity<Frame> const& angular_velocity() const;

  // Returns the position at time |t|.
  Angle AngleAt(Instant const& t) const;

  // Returns the rotation relating the reference frame of the surface of this
  // body to |Frame|.  The reference frame of the surface is defined as follows:
  //   - the z axis is the |polar_axis|;
  //   - the x axis points from the centre of the body to the reference
  //     meridian;
  //   - the reference frame has the same handedness as |Frame|.
  // Following this definition,
  //   Displacement<SurfaceFrame>(RadiusLatitudeLongitude(r, φ, λ))
  // converts planetocentric coordinates to a displacement from the body centre
  // in the surface frame.  Note that RadiusLatitudeLongitude should *not* be
  // used for planetographic coordinates, which use a latitude defined from
  // a reference ellipsoid, and a longitude around the negative pole---except
  // for the Earth, the Moon, and the Sun.
  // In the case of the Earth, see geodetic vs. geocentric latitudes.
  template<typename SurfaceFrame>
  Rotation<SurfaceFrame, Frame> FromSurfaceFrame(Instant const& t) const;

  // Returns the rotation at time |t|.
  Rotation<Frame, Frame> RotationAt(Instant const& t) const;

  // Returns false.
  bool is_massless() const override;

  // Returns true.
  bool is_oblate() const override;

  void WriteToMessage(not_null<serialization::Body*> message) const override;

  void WriteToMessage(
      not_null<serialization::MassiveBody*> message) const override;

  // Fails if the |RotatingBody| extension is absent from the message.
  static not_null<std::unique_ptr<RotatingBody<Frame>>> ReadFromMessage(
      serialization::RotatingBody const& message,
      MassiveBody::Parameters const& massive_body_parameters);

 private:
  Parameters const parameters_;
  Vector<double, Frame> const polar_axis_;
  AngularVelocity<Frame> const angular_velocity_;
};

}  // namespace internal_rotating_body

using internal_rotating_body::RotatingBody;

}  // namespace physics
}  // namespace principia

#include "physics/rotating_body_body.hpp"

#endif  // PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#endif  // PRINCIPIA_PHYSICS_MASSIVE_BODY_HPP_
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_RIoUring
#define ROOT_RIoUring

#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <vector>

#include <liburing.h>
#include <liburing/io_uring.h>

#include "TError.h"

namespace ROOT {
namespace Internal {

class RIoUring {
private:
   struct io_uring fRing;
   std::uint32_t fDepth = 0;

   static bool CheckIsAvailable() {
      try {
         RIoUring(1);
         return true;
      }
      catch (const std::runtime_error& err) {
         Warning("RIoUring", "io_uring is not available\n%s", err.what());
      }
      return false;
   }

public:
   // Create an io_uring instance. The ring selects an appropriate queue depth. which can be queried
   // afterwards using GetQueueDepth(). The depth is typically 1024 or lower. Throws an exception if
   // the ring could be not be initialized.
   RIoUring() {
      std::uint32_t queueDepth = 1024;
      int ret;
      while (true) {
         ret = io_uring_queue_init(queueDepth, &fRing, 0 /* no flags */);
         if (ret == 0) {
            fDepth = queueDepth;
            break; // ring setup succeeded
         }
         if (ret != -ENOMEM) {
            throw std::runtime_error("Error initializing io_uring: " + std::string(std::strerror(-ret)));
         }
         // try again with a smaller queue for ENOMEM
         // -- if it gets to 0, queue_init will fail with an invalid argument error
         queueDepth /= 2;
      }
   }

   // Create a io_uring instance that can hold at least `entriesHint` submission entries. The actual
   // queue depth is rounded up to the next power of 2. Throws an exception if the ring couldn't
   // be initialized.
   RIoUring(std::uint32_t entriesHint) {
      struct io_uring_params params = {}; /* zero initialize param struct, no flags */
      int ret = io_uring_queue_init_params(entriesHint, &fRing, &params);
      if (ret != 0) {
         throw std::runtime_error("Error initializing io_uring: " + std::string(std::strerror(-ret)));
      }
      fDepth = params.sq_entries;
   }

   RIoUring(const RIoUring&) = delete;
   RIoUring& operator=(const RIoUring&) = delete;

   ~RIoUring() {
      // todo(max) try submitting any pending events before exiting
      io_uring_queue_exit(&fRing);
   }

   /// Check if io_uring is available on this system.
   static bool IsAvailable() {
      static const bool available = RIoUring::CheckIsAvailable();
      return available;
   }

   std::uint32_t GetQueueDepth() {
      return fDepth;
   }

   /// Access the raw io_uring instance.
   struct io_uring *GetRawRing() {
      return &fRing;
   }

   /// Basic read event composed of IO data and a target file descriptor.
   struct RReadEvent {
      /// The destination for reading
      void *fBuffer = nullptr;
      /// The file offset
      std::uint64_t fOffset = 0;
      /// The number of desired bytes
      std::size_t fSize = 0;
      /// The number of actually read bytes, set by the RIoUring instance
      std::size_t fOutBytes = 0;
      /// The file descriptor
      int fFileDes = -1;
   };

   /// Submit a number of read events and wait for completion. Events are submitted in batches if
   /// the number of events is larger than the submission queue depth.
   void SubmitReadsAndWait(RReadEvent* readEvents, unsigned int nReads) {
      unsigned int batch = 0;
      unsigned int batchSize = fDepth;
      unsigned int readPos = 0;

      while (readPos < nReads) {
         if (readPos + batchSize > nReads) {
            batchSize = nReads - readPos;
         }
         // prep reads
         struct io_uring_sqe *sqe;
         for (std::size_t i = readPos; i < readPos + batchSize; ++i) {
            sqe = io_uring_get_sqe(&fRing);
            if (!sqe) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "get SQE failed for read request '" + std::to_string(i)
                  + "', error: " + std::string(strerror(errno)));
            }
            if (readEvents[i].fFileDes == -1) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "bad fd (-1) for read request '" + std::to_string(i) + "'");
            }
            if (readEvents[i].fBuffer == nullptr) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "null read buffer for read request '" + std::to_string(i) + "'");
            }
            io_uring_prep_read(sqe,
               readEvents[i].fFileDes,
               readEvents[i].fBuffer,
               readEvents[i].fSize,
               readEvents[i].fOffset
            );
            sqe->user_data = i;
         }

         // todo(max) check for any difference between submit vs. submit and wait for large nReq
         int submitted = io_uring_submit_and_wait(&fRing, batchSize);
         if (submitted <= 0) {
            throw std::runtime_error("batch " + std::to_string(batch) + ": "
               "ring submit failed, error: " + std::string(strerror(errno)));
         }
         if (submitted != static_cast<int>(batchSize)) {
            throw std::runtime_error("ring submitted " + std::to_string(submitted) +
               " events but requested " + std::to_string(batchSize));
         }
         // reap reads
         struct io_uring_cqe *cqe;
         int ret;
         for (int i = 0; i < submitted; ++i) {
            ret = io_uring_wait_cqe(&fRing, &cqe);
            if (ret < 0) {
               throw std::runtime_error("wait cqe failed, error: " + std::string(std::strerror(-ret)));
            }
            auto index = reinterpret_cast<std::size_t>(io_uring_cqe_get_data(cqe));
            if (index >= nReads) {
               throw std::runtime_error("bad cqe user data: " + std::to_string(index));
            }
            if (cqe->res < 0) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "read failed for ReadEvent[" + std::to_string(index) + "], "
                  "error: " + std::string(std::strerror(-cqe->res)));
            }
            readEvents[index].fOutBytes = static_cast<std::size_t>(cqe->res);
            io_uring_cqe_seen(&fRing, cqe);
         }
         readPos += batchSize;
         batch += 1;
      }
      return;
   }
};

} // namespace Internal
} // namespace ROOT

#endif
<commit_msg>[io] better error message upon exhausting memlocked memory<commit_after>/*************************************************************************
 * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#ifndef ROOT_RIoUring
#define ROOT_RIoUring

#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <vector>

#include <liburing.h>
#include <liburing/io_uring.h>

#include "TError.h"

namespace ROOT {
namespace Internal {

class RIoUring {
private:
   struct io_uring fRing;
   std::uint32_t fDepth = 0;

   static bool CheckIsAvailable() {
      try {
         RIoUring(1);
         return true;
      }
      catch (const std::runtime_error& err) {
         Warning("RIoUring", "io_uring is not available\n%s", err.what());
      }
      return false;
   }

public:
   // Create an io_uring instance. The ring selects an appropriate queue depth. which can be queried
   // afterwards using GetQueueDepth(). The depth is typically 1024 or lower. Throws an exception if
   // the ring could be not be initialized.
   RIoUring() {
      std::uint32_t queueDepth = 1024;
      int ret;
      while (true) {
         ret = io_uring_queue_init(queueDepth, &fRing, 0 /* no flags */);
         if (ret == 0) {
            fDepth = queueDepth;
            break; // ring setup succeeded
         }
         if (ret != -ENOMEM) {
            throw std::runtime_error("Error initializing io_uring: " + std::string(std::strerror(-ret)));
         }
         // try again with a smaller queue for ENOMEM
         queueDepth /= 2;
         if (queueDepth == 0) {
            throw std::runtime_error("Fatal Error: failed to allocate memory for the smallest possible "
               "io_uring instance. 'memlock' memory has been exhausted for this user");
         }
      }
   }

   // Create a io_uring instance that can hold at least `entriesHint` submission entries. The actual
   // queue depth is rounded up to the next power of 2. Throws an exception if the ring couldn't
   // be initialized.
   RIoUring(std::uint32_t entriesHint) {
      struct io_uring_params params = {}; /* zero initialize param struct, no flags */
      int ret = io_uring_queue_init_params(entriesHint, &fRing, &params);
      if (ret != 0) {
         throw std::runtime_error("Error initializing io_uring: " + std::string(std::strerror(-ret)));
      }
      fDepth = params.sq_entries;
   }

   RIoUring(const RIoUring&) = delete;
   RIoUring& operator=(const RIoUring&) = delete;

   ~RIoUring() {
      // todo(max) try submitting any pending events before exiting
      io_uring_queue_exit(&fRing);
   }

   /// Check if io_uring is available on this system.
   static bool IsAvailable() {
      static const bool available = RIoUring::CheckIsAvailable();
      return available;
   }

   std::uint32_t GetQueueDepth() {
      return fDepth;
   }

   /// Access the raw io_uring instance.
   struct io_uring *GetRawRing() {
      return &fRing;
   }

   /// Basic read event composed of IO data and a target file descriptor.
   struct RReadEvent {
      /// The destination for reading
      void *fBuffer = nullptr;
      /// The file offset
      std::uint64_t fOffset = 0;
      /// The number of desired bytes
      std::size_t fSize = 0;
      /// The number of actually read bytes, set by the RIoUring instance
      std::size_t fOutBytes = 0;
      /// The file descriptor
      int fFileDes = -1;
   };

   /// Submit a number of read events and wait for completion. Events are submitted in batches if
   /// the number of events is larger than the submission queue depth.
   void SubmitReadsAndWait(RReadEvent* readEvents, unsigned int nReads) {
      unsigned int batch = 0;
      unsigned int batchSize = fDepth;
      unsigned int readPos = 0;

      while (readPos < nReads) {
         if (readPos + batchSize > nReads) {
            batchSize = nReads - readPos;
         }
         // prep reads
         struct io_uring_sqe *sqe;
         for (std::size_t i = readPos; i < readPos + batchSize; ++i) {
            sqe = io_uring_get_sqe(&fRing);
            if (!sqe) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "get SQE failed for read request '" + std::to_string(i)
                  + "', error: " + std::string(strerror(errno)));
            }
            if (readEvents[i].fFileDes == -1) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "bad fd (-1) for read request '" + std::to_string(i) + "'");
            }
            if (readEvents[i].fBuffer == nullptr) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "null read buffer for read request '" + std::to_string(i) + "'");
            }
            io_uring_prep_read(sqe,
               readEvents[i].fFileDes,
               readEvents[i].fBuffer,
               readEvents[i].fSize,
               readEvents[i].fOffset
            );
            sqe->user_data = i;
         }

         // todo(max) check for any difference between submit vs. submit and wait for large nReq
         int submitted = io_uring_submit_and_wait(&fRing, batchSize);
         if (submitted <= 0) {
            throw std::runtime_error("batch " + std::to_string(batch) + ": "
               "ring submit failed, error: " + std::string(strerror(errno)));
         }
         if (submitted != static_cast<int>(batchSize)) {
            throw std::runtime_error("ring submitted " + std::to_string(submitted) +
               " events but requested " + std::to_string(batchSize));
         }
         // reap reads
         struct io_uring_cqe *cqe;
         int ret;
         for (int i = 0; i < submitted; ++i) {
            ret = io_uring_wait_cqe(&fRing, &cqe);
            if (ret < 0) {
               throw std::runtime_error("wait cqe failed, error: " + std::string(std::strerror(-ret)));
            }
            auto index = reinterpret_cast<std::size_t>(io_uring_cqe_get_data(cqe));
            if (index >= nReads) {
               throw std::runtime_error("bad cqe user data: " + std::to_string(index));
            }
            if (cqe->res < 0) {
               throw std::runtime_error("batch " + std::to_string(batch) + ": "
                  + "read failed for ReadEvent[" + std::to_string(index) + "], "
                  "error: " + std::string(std::strerror(-cqe->res)));
            }
            readEvents[index].fOutBytes = static_cast<std::size_t>(cqe->res);
            io_uring_cqe_seen(&fRing, cqe);
         }
         readPos += batchSize;
         batch += 1;
      }
      return;
   }
};

} // namespace Internal
} // namespace ROOT

#endif
<|endoftext|>


<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2019  gatecat <gatecat@ds0.me>
 *  Copyright (C) 2021  Symbiflow Authors
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "xdc.h"

#include <string>

#include "context.h"
#include "log.h"

// Include tcl.h late because it messed with #define's and lets them leave the
// scope of the header.
#include <tcl.h>

NEXTPNR_NAMESPACE_BEGIN

static int port_set_from_any(Tcl_Interp *interp, Tcl_Obj *objPtr) { return TCL_ERROR; }

static void set_tcl_obj_string(Tcl_Obj *objPtr, const std::string &s)
{
    NPNR_ASSERT(objPtr->bytes == nullptr);
    // Need to have space for the end null byte.
    objPtr->bytes = Tcl_Alloc(s.size() + 1);

    // Length is length of string, not including the end null byte.
    objPtr->length = s.size();

    std::copy(s.begin(), s.end(), objPtr->bytes);
    objPtr->bytes[objPtr->length] = '\0';
}

static void port_update_string(Tcl_Obj *objPtr)
{
    const Context *ctx = static_cast<const Context *>(objPtr->internalRep.twoPtrValue.ptr1);
    PortInfo *port_info = static_cast<PortInfo *>(objPtr->internalRep.twoPtrValue.ptr2);

    std::string port_name = port_info->name.str(ctx);
    set_tcl_obj_string(objPtr, port_name);
}

static void port_dup(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr)
{
    dupPtr->internalRep.twoPtrValue = srcPtr->internalRep.twoPtrValue;
}

static void port_free(Tcl_Obj *objPtr) {}

static void Tcl_SetStringResult(Tcl_Interp *interp, const std::string &s)
{
    char *copy = Tcl_Alloc(s.size() + 1);
    std::copy(s.begin(), s.end(), copy);
    copy[s.size()] = '\0';
    Tcl_SetResult(interp, copy, TCL_DYNAMIC);
}

static Tcl_ObjType port_object = {
        "port", port_free, port_dup, port_update_string, port_set_from_any,
};

static int get_ports(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    const Context *ctx = static_cast<const Context *>(data);
    if (objc == 1) {
        // Return list of all ports.
        Tcl_SetStringResult(interp, "Unimplemented");
        return TCL_ERROR;
    } else if (objc == 2) {
        const char *arg0 = Tcl_GetString(objv[1]);
        IdString port_name = ctx->id(arg0);

        auto iter = ctx->ports.find(port_name);
        if (iter == ctx->ports.end()) {
            Tcl_SetStringResult(interp, "Could not find port " + port_name.str(ctx));
            return TCL_ERROR;
        }

        Tcl_Obj *result = Tcl_NewObj();
        result->typePtr = &port_object;
        result->internalRep.twoPtrValue.ptr1 = (void *)(ctx);
        result->internalRep.twoPtrValue.ptr2 = (void *)(&iter->second);

        result->bytes = nullptr;
        port_update_string(result);

        Tcl_SetObjResult(interp, result);
        return TCL_OK;
    } else {
        return TCL_ERROR;
    }
}

static int set_property(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    // set_property <property> <value> <object>
    if (objc != 4) {
        Tcl_SetStringResult(interp, "Only simple 'set_property <property> <value> <object>' is supported");
        return TCL_ERROR;
    }

    const char *property = Tcl_GetString(objv[1]);
    const char *value = Tcl_GetString(objv[2]);
    const Tcl_Obj *object = objv[3];

    if (object->typePtr != &port_object) {
        Tcl_SetStringResult(interp, "Only port objects are handled right now!");
        return TCL_ERROR;
    }

    const Context *ctx = static_cast<const Context *>(object->internalRep.twoPtrValue.ptr1);
    PortInfo *port_info = static_cast<PortInfo *>(object->internalRep.twoPtrValue.ptr2);
    NPNR_ASSERT(port_info->net != nullptr);
    CellInfo *cell = ctx->port_cells.at(port_info->name);

    cell->attrs[ctx->id(property)] = Property(value);

    return TCL_OK;
}

TclInterp::TclInterp(Context *ctx)
{
    interp = Tcl_CreateInterp();
    NPNR_ASSERT(Tcl_Init(interp) == TCL_OK);

    Tcl_RegisterObjType(&port_object);

    NPNR_ASSERT(Tcl_Eval(interp, "rename unknown _original_unknown") == TCL_OK);
    NPNR_ASSERT(Tcl_Eval(interp, "proc unknown args {\n"
                                 "  set result [scan [lindex $args 0] \"%d\" value]\n"
                                 "  if { $result == 1 && [llength $args] == 1 } {\n"
                                 "    return \\[$value\\]\n"
                                 "  } else {\n"
                                 "    uplevel 1 [list _original_unknown {*}$args]\n"
                                 "  }\n"
                                 "}") == TCL_OK);
    Tcl_CreateObjCommand(interp, "get_ports", get_ports, ctx, nullptr);
    Tcl_CreateObjCommand(interp, "set_property", set_property, ctx, nullptr);
}

TclInterp::~TclInterp() { Tcl_DeleteInterp(interp); }

NEXTPNR_NAMESPACE_END
<commit_msg>interchange: xdc: add get_cells command<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2019  gatecat <gatecat@ds0.me>
 *  Copyright (C) 2021  Symbiflow Authors
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "xdc.h"

#include <string>

#include "context.h"
#include "log.h"

// Include tcl.h late because it messed with #define's and lets them leave the
// scope of the header.
#include <tcl.h>

NEXTPNR_NAMESPACE_BEGIN

static int obj_set_from_any(Tcl_Interp *interp, Tcl_Obj *objPtr) { return TCL_ERROR; }

static void set_tcl_obj_string(Tcl_Obj *objPtr, const std::string &s)
{
    NPNR_ASSERT(objPtr->bytes == nullptr);
    // Need to have space for the end null byte.
    objPtr->bytes = Tcl_Alloc(s.size() + 1);

    // Length is length of string, not including the end null byte.
    objPtr->length = s.size();

    std::copy(s.begin(), s.end(), objPtr->bytes);
    objPtr->bytes[objPtr->length] = '\0';
}

static void port_update_string(Tcl_Obj *objPtr)
{
    const Context *ctx = static_cast<const Context *>(objPtr->internalRep.twoPtrValue.ptr1);
    PortInfo *port_info = static_cast<PortInfo *>(objPtr->internalRep.twoPtrValue.ptr2);

    std::string port_name = port_info->name.str(ctx);
    set_tcl_obj_string(objPtr, port_name);
}

static void cell_update_string(Tcl_Obj *objPtr)
{
    const Context *ctx = static_cast<const Context *>(objPtr->internalRep.twoPtrValue.ptr1);
    CellInfo *cell_info = static_cast<CellInfo *>(objPtr->internalRep.twoPtrValue.ptr2);

    std::string cell_name = cell_info->name.str(ctx);
    set_tcl_obj_string(objPtr, cell_name);
}

static void obj_dup(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr)
{
    dupPtr->internalRep.twoPtrValue = srcPtr->internalRep.twoPtrValue;
}

static void obj_free(Tcl_Obj *objPtr) {}

static void Tcl_SetStringResult(Tcl_Interp *interp, const std::string &s)
{
    char *copy = Tcl_Alloc(s.size() + 1);
    std::copy(s.begin(), s.end(), copy);
    copy[s.size()] = '\0';
    Tcl_SetResult(interp, copy, TCL_DYNAMIC);
}

static Tcl_ObjType port_object = {
        "port", obj_free, obj_dup, port_update_string, obj_set_from_any,
};

static Tcl_ObjType cell_object = {
        "cell", obj_free, obj_dup, cell_update_string, obj_set_from_any,
};

static int get_ports(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    const Context *ctx = static_cast<const Context *>(data);
    if (objc == 1) {
        // Return list of all ports.
        Tcl_SetStringResult(interp, "Unimplemented");
        return TCL_ERROR;
    } else if (objc == 2) {
        const char *arg0 = Tcl_GetString(objv[1]);
        IdString port_name = ctx->id(arg0);

        auto iter = ctx->ports.find(port_name);
        if (iter == ctx->ports.end()) {
            Tcl_SetStringResult(interp, "Could not find port " + port_name.str(ctx));
            return TCL_ERROR;
        }

        Tcl_Obj *result = Tcl_NewObj();
        result->typePtr = &port_object;
        result->internalRep.twoPtrValue.ptr1 = (void *)(ctx);
        result->internalRep.twoPtrValue.ptr2 = (void *)(&iter->second);

        result->bytes = nullptr;
        port_update_string(result);

        Tcl_SetObjResult(interp, result);
        return TCL_OK;
    } else {
        return TCL_ERROR;
    }
}

static int get_cells(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    const Context *ctx = static_cast<const Context *>(data);
    if (objc == 1) {
        // Return list of all ports.
        Tcl_SetStringResult(interp, "Unimplemented");
        return TCL_ERROR;
    } else if (objc == 2) {
        const char *arg0 = Tcl_GetString(objv[1]);
        IdString cell_name = ctx->id(arg0);

        CellInfo *cell = nullptr;
        for (auto &cell_pair : ctx->cells) {
            if (cell_pair.second.get()->name == cell_name) {
                cell = cell_pair.second.get();
                break;
            }
        }

        if (cell == nullptr) {
            Tcl_SetStringResult(interp, "Could not find cell " + cell_name.str(ctx));
            return TCL_ERROR;
        }

        Tcl_Obj *result = Tcl_NewObj();
        result->typePtr = &cell_object;
        result->internalRep.twoPtrValue.ptr1 = (void *)(ctx);
        result->internalRep.twoPtrValue.ptr2 = (void *)(cell);

        result->bytes = nullptr;
        cell_update_string(result);

        Tcl_SetObjResult(interp, result);
        return TCL_OK;
    } else {
        return TCL_ERROR;
    }
}

static int set_property(ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[])
{
    // set_property <property> <value> <object>
    if (objc != 4) {
        Tcl_SetStringResult(interp, "Only simple 'set_property <property> <value> <object>' is supported");
        return TCL_ERROR;
    }

    const char *property = Tcl_GetString(objv[1]);
    const char *value = Tcl_GetString(objv[2]);
    const Tcl_Obj *object = objv[3];

    if (object->typePtr == &port_object) {
        const Context *ctx = static_cast<const Context *>(object->internalRep.twoPtrValue.ptr1);
        PortInfo *port_info = static_cast<PortInfo *>(object->internalRep.twoPtrValue.ptr2);
        NPNR_ASSERT(port_info->net != nullptr);
        CellInfo *cell = ctx->port_cells.at(port_info->name);

        cell->attrs[ctx->id(property)] = Property(value);
    } else if (object->typePtr == &cell_object) {
        const Context *ctx = static_cast<const Context *>(object->internalRep.twoPtrValue.ptr1);
        CellInfo *cell = static_cast<CellInfo *>(object->internalRep.twoPtrValue.ptr2);

        cell->attrs[ctx->id(property)] = Property(value);
    } else {
        return TCL_ERROR;
    }

    return TCL_OK;
}

TclInterp::TclInterp(Context *ctx)
{
    interp = Tcl_CreateInterp();
    NPNR_ASSERT(Tcl_Init(interp) == TCL_OK);

    Tcl_RegisterObjType(&port_object);

    NPNR_ASSERT(Tcl_Eval(interp, "rename unknown _original_unknown") == TCL_OK);
    NPNR_ASSERT(Tcl_Eval(interp, "proc unknown args {\n"
                                 "  set result [scan [lindex $args 0] \"%d\" value]\n"
                                 "  if { $result == 1 && [llength $args] == 1 } {\n"
                                 "    return \\[$value\\]\n"
                                 "  } else {\n"
                                 "    uplevel 1 [list _original_unknown {*}$args]\n"
                                 "  }\n"
                                 "}") == TCL_OK);
    Tcl_CreateObjCommand(interp, "get_ports", get_ports, ctx, nullptr);
    Tcl_CreateObjCommand(interp, "get_cells", get_cells, ctx, nullptr);
    Tcl_CreateObjCommand(interp, "set_property", set_property, ctx, nullptr);
}

TclInterp::~TclInterp() { Tcl_DeleteInterp(interp); }

NEXTPNR_NAMESPACE_END
<|endoftext|>


<commit_before>#include "sniffer.h"

#include "util.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>
#include <pcap.h>
#include <map>

using namespace std;

static pcap_t *handle = NULL;
static int datalink;
char * interface;

const int num_channels = 12;
int current_channel = 0;

void set_monitor_mode(char * iface) {
  interface = iface;
  char * const argv[] = {(char*)("iwconfig"),iface,(char*)("mode"),(char*)("monitor"),0};
  run_command(argv);
}

const float max_time = 10;
const float round_time = 1;

float channel_prob[num_channels+1];
int channel_time[num_channels+1];
int channel_packets[num_channels+1];

void initialize(char * interface) {
  if ( handle ) {
    error("Trying to reinitialize using interface %s",interface);
    abort();
  }

  char errbuf[BUFSIZ];

  set_monitor_mode(interface);

  handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf);
  if (handle == NULL) {
    error("Couldn't open interface %s. Error: %s",interface,errbuf);
    abort();
  }

  datalink = pcap_datalink(handle);

  verbose("Opened interface %s.",interface);
  debug("Datalink is %d.", datalink);
}

struct ieee80211_radiotap_header {
        u_int8_t        it_version;     /* set to 0 */
        u_int8_t        it_pad;
        u_int16_t       it_len;         /* entire length */
        u_int32_t       it_present;     /* fields present */
} __attribute__((__packed__));

struct prism_value{
  u_int32_t did;
  u_int16_t status;
  u_int16_t len;
  u_int32_t data;
};

struct prism_header{
  u_int32_t msgcode;
  u_int32_t msglen;
  prism_value hosttime;
  prism_value mactime;
  prism_value channel;
  prism_value rssi;
  prism_value sq;
  prism_value signal;
  prism_value noise;
  prism_value rate;
  prism_value istx;
  prism_value frmlen;
};

map<string,int> mac_count[num_channels+1][4];

void handleMAC(const u_char * mac, int pos) {
  char mac_c_str[13];
  mac_c_str[0] = 0;
  for ( int i = 0 ; i < 6 ; i++ ) {
    sprintf(mac_c_str,"%s%02X",mac_c_str,mac[i]);
  }
  string mac_str(mac_c_str);
  mac_count[current_channel][pos][mac_str]++;
  debug("MAC %d : %s",pos,mac_c_str);
}

void handlePacket(const u_char* packet) {
  if ( datalink ==	DLT_PRISM_HEADER ) {
    prism_header* rth1 = (prism_header*)(packet);
    packet = packet + rth1->msglen;
  }

  // TODO: Check if the +4 should come after this line or before (during the PRISM skip)

  for ( int i = 0 ; i < 4 ; i++ ) {
    handleMAC(packet+4+(i*6),i);
  }

  channel_packets[current_channel]++;
}

class Timer {
  clock_t start_time;
public:
  void reset() { start_time = clock(); }
  float get_time() {
    return (float(clock()-start_time)/CLOCKS_PER_SEC);
  }
  Timer() { reset(); }
};

void change_channel(int channel) {
  if ( channel < 1 || channel > num_channels ) {
    error("Impossible to switch to channel %d. Quitting.",channel);
    abort();
  }
  current_channel = channel;
  char channel_no[3];
  sprintf(channel_no,"%d",channel);
  char * const argv[] = {(char*)"iwconfig",interface,(char*)"channel",channel_no,0};
  run_command(argv);
}

bool switch_to_next_channel() {
  bool ret = (current_channel==num_channels);
  static Timer ch_time;
  channel_time[current_channel]+=ch_time.get_time();
  change_channel((current_channel % num_channels) + 1);
  ch_time.reset();
  return ret;
}

void recalculate_probs() {
  const float min_speed_adder = 0.01;
  float speed[num_channels+1];
  float total_speed = 0;
  for ( int i = 1 ; i <= num_channels ; i++ ) {
    debug("Packets on channel %02d = %d",i,channel_packets);
    speed[i] = channel_packets[i]/channel_time[i];
    speed[i] += min_speed_adder;
    total_speed += speed[i];
  }

  for ( int i = 1 ; i <= num_channels ; i++ ) {
    channel_prob[i] = speed[i] / total_speed;
  }
}

void capture_packets() {
  Timer timer;
  Timer channel_timer;
  while ( timer.get_time() < max_time ) {
    pcap_pkthdr header;
    handlePacket(pcap_next(handle, &header));
    bool is_round_over;
    if ( channel_timer.get_time() > channel_prob[current_channel] * round_time ) {
      is_round_over = switch_to_next_channel();
      channel_timer.reset();
    }
    if ( is_round_over ) {
      recalculate_probs();
    }
  }
}
<commit_msg>Do proper initialization and debug messaging<commit_after>#include "sniffer.h"

#include "util.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>
#include <pcap.h>
#include <map>

using namespace std;

static pcap_t *handle = NULL;
static int datalink;
char * interface;

const int num_channels = 12;
int current_channel = 0;

void set_monitor_mode(char * iface) {
  interface = iface;
  char * const argv[] = {(char*)("iwconfig"),iface,(char*)("mode"),(char*)("monitor"),0};
  run_command(argv);
}

const float max_time = 10;
const float round_time = 1;

float channel_prob[num_channels+1];
float channel_time[num_channels+1];
int channel_packets[num_channels+1];

void initialize(char * interface) {
  if ( handle ) {
    error("Trying to reinitialize using interface %s",interface);
    abort();
  }

  char errbuf[BUFSIZ];

  set_monitor_mode(interface);

  handle = pcap_open_live(interface, BUFSIZ, 1, 1000, errbuf);
  if (handle == NULL) {
    error("Couldn't open interface %s. Error: %s",interface,errbuf);
    abort();
  }

  datalink = pcap_datalink(handle);

  verbose("Opened interface %s.",interface);
  debug("Datalink is %d.", datalink);

  for ( int i = 1 ; i <= num_channels ; i++ ) {
    channel_prob[i] = 1.0/num_channels;
    channel_time[i] = 0;
    channel_packets[i] = 0;
  }
}

struct ieee80211_radiotap_header {
        u_int8_t        it_version;     /* set to 0 */
        u_int8_t        it_pad;
        u_int16_t       it_len;         /* entire length */
        u_int32_t       it_present;     /* fields present */
} __attribute__((__packed__));

struct prism_value{
  u_int32_t did;
  u_int16_t status;
  u_int16_t len;
  u_int32_t data;
};

struct prism_header{
  u_int32_t msgcode;
  u_int32_t msglen;
  prism_value hosttime;
  prism_value mactime;
  prism_value channel;
  prism_value rssi;
  prism_value sq;
  prism_value signal;
  prism_value noise;
  prism_value rate;
  prism_value istx;
  prism_value frmlen;
};

map<string,int> mac_count[num_channels+1][4];

void handleMAC(const u_char * mac, int pos) {
  char mac_c_str[13];
  mac_c_str[0] = 0;
  for ( int i = 0 ; i < 6 ; i++ ) {
    sprintf(mac_c_str,"%s%02X",mac_c_str,mac[i]);
  }
  string mac_str(mac_c_str);
  mac_count[current_channel][pos][mac_str]++;
  debug("MAC %d : %s",pos,mac_c_str);
}

void handlePacket(const u_char* packet) {
  if ( datalink ==	DLT_PRISM_HEADER ) {
    prism_header* rth1 = (prism_header*)(packet);
    packet = packet + rth1->msglen;
  }

  // TODO: Check if the +4 should come after this line or before (during the PRISM skip)

  for ( int i = 0 ; i < 4 ; i++ ) {
    handleMAC(packet+4+(i*6),i);
  }

  channel_packets[current_channel]++;
}

class Timer {
  clock_t start_time;
public:
  void reset() { start_time = clock(); }
  float get_time() {
    return (float(clock()-start_time)/CLOCKS_PER_SEC);
  }
  Timer() { reset(); }
};

void change_channel(int channel) {
  if ( channel < 1 || channel > num_channels ) {
    error("Impossible to switch to channel %d. Quitting.",channel);
    abort();
  }
  current_channel = channel;
  char channel_no[3];
  sprintf(channel_no,"%d",channel);
  char * const argv[] = {(char*)"iwconfig",interface,(char*)"channel",channel_no,0};
  run_command(argv);
  verbose("Changed to channel %d",channel);
}

bool switch_to_next_channel() {
  bool ret = (current_channel==num_channels);
  static Timer ch_time;
  channel_time[current_channel]+=ch_time.get_time();
  change_channel((current_channel % num_channels) + 1);
  ch_time.reset();
  return ret;
}

void recalculate_probs() {
  const float min_speed_adder = 0.01;
  float speed[num_channels+1];
  float total_speed = 0;
  for ( int i = 1 ; i <= num_channels ; i++ ) {
    debug("Packets on channel %02d = %d",i,channel_packets);
    speed[i] = channel_packets[i]/channel_time[i];
    speed[i] += min_speed_adder;
    total_speed += speed[i];
  }

  for ( int i = 1 ; i <= num_channels ; i++ ) {
    channel_prob[i] = speed[i] / total_speed;
  }
}

void capture_packets() {
  Timer timer;
  Timer channel_timer;
  while ( timer.get_time() < max_time ) {
    pcap_pkthdr header;
    handlePacket(pcap_next(handle, &header));
    debug("<<<Channel timer: %f; Total timer: %f>>>",channel_timer.get_time(),timer.get_time());
    bool is_round_over;
    if ( channel_timer.get_time() > channel_prob[current_channel] * round_time ) {
      is_round_over = switch_to_next_channel();
      channel_timer.reset();
    }
    if ( is_round_over ) {
      recalculate_probs();
    }
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stlfamily.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 11:22:21 $
 *
 *  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 _SD_STLFAMILY_HXX
#define _SD_STLFAMILY_HXX

#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/XNamed.hpp>

#include <rtl/ref.hxx>

#include <cppuhelper/implbase7.hxx>

#include <svtools/style.hxx>

#include <svx/unoipset.hxx>

class SdStyleSheet;
class SdPage;
struct SdStyleFamilyImpl;

namespace css = ::com::sun::star;

class SdStyleFamily : public ::cppu::WeakImplHelper7< css::container::XNameContainer, css::container::XNamed, css::container::XIndexAccess, css::lang::XSingleServiceFactory,  css::lang::XServiceInfo, css::lang::XComponent, css::beans::XPropertySet >
{
public:
    /// creates the style family for the given SfxStyleFamily
    SdStyleFamily( const rtl::Reference< SfxStyleSheetPool >& xPool, SfxStyleFamily nFamily );

    /// creates the presentation family for the given masterpage
    SdStyleFamily( const rtl::Reference< SfxStyleSheetPool >& xPool, const SdPage* pMasterPage );

    virtual ~SdStyleFamily();

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(css::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(css::uno::RuntimeException);
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(css::uno::RuntimeException);

    // XNamed
    virtual ::rtl::OUString SAL_CALL getName(  ) throw (css::uno::RuntimeException);
    virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw (css::uno::RuntimeException);

    // XNameAccess
    virtual css::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw(css::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw(css::uno::RuntimeException);

    // XElementAccess
    virtual css::uno::Type SAL_CALL getElementType() throw(css::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements() throw(css::uno::RuntimeException);

    // XIndexAccess
    virtual sal_Int32 SAL_CALL getCount() throw(css::uno::RuntimeException) ;
    virtual css::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw(css::lang::IndexOutOfBoundsException, css::lang::WrappedTargetException, css::uno::RuntimeException);

    // XNameContainer
    virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw(css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw(css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);

    // XSingleServiceFactory
    virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance(  ) throw(css::uno::Exception, css::uno::RuntimeException);
    virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstanceWithArguments( const css::uno::Sequence< css::uno::Any >& aArguments ) throw(css::uno::Exception, css::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL dispose(  ) throw (css::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) throw (css::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) throw (css::uno::RuntimeException);

    // XPropertySet
    virtual css::uno::Reference<css::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw (css::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const css::uno::Any& aValue ) throw (css::beans::UnknownPropertyException, css::beans::PropertyVetoException, css::lang::IllegalArgumentException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual css::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const css::uno::Reference<css::beans::XPropertyChangeListener>& xListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const css::uno::Reference<css::beans::XPropertyChangeListener>& aListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener(const ::rtl::OUString& PropertyName, const css::uno::Reference<css::beans::XVetoableChangeListener>& aListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener(const ::rtl::OUString& PropertyName,const css::uno::Reference<css::beans::XVetoableChangeListener>&aListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);

private:
    void throwIfDisposed() const throw(css::uno::RuntimeException);
    SdStyleSheet* GetValidNewSheet( const css::uno::Any& rElement ) throw(css::lang::IllegalArgumentException);
    SdStyleSheet* GetSheetByName( const ::rtl::OUString& rName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException );

    SfxStyleFamily mnFamily;
    rtl::Reference< SfxStyleSheetPool > mxPool;
    SdStyleFamilyImpl*  mpImpl;
};

typedef rtl::Reference< SdStyleFamily > SdStyleFamilyRef;

#endif     // _SD_STLFAMILY_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.16); FILE MERGED 2008/03/31 13:56:41 rt 1.2.16.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: stlfamily.hxx,v $
 * $Revision: 1.3 $
 *
 * 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 _SD_STLFAMILY_HXX
#define _SD_STLFAMILY_HXX

#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/XNamed.hpp>

#include <rtl/ref.hxx>

#include <cppuhelper/implbase7.hxx>

#include <svtools/style.hxx>

#include <svx/unoipset.hxx>

class SdStyleSheet;
class SdPage;
struct SdStyleFamilyImpl;

namespace css = ::com::sun::star;

class SdStyleFamily : public ::cppu::WeakImplHelper7< css::container::XNameContainer, css::container::XNamed, css::container::XIndexAccess, css::lang::XSingleServiceFactory,  css::lang::XServiceInfo, css::lang::XComponent, css::beans::XPropertySet >
{
public:
    /// creates the style family for the given SfxStyleFamily
    SdStyleFamily( const rtl::Reference< SfxStyleSheetPool >& xPool, SfxStyleFamily nFamily );

    /// creates the presentation family for the given masterpage
    SdStyleFamily( const rtl::Reference< SfxStyleSheetPool >& xPool, const SdPage* pMasterPage );

    virtual ~SdStyleFamily();

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(css::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(css::uno::RuntimeException);
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(css::uno::RuntimeException);

    // XNamed
    virtual ::rtl::OUString SAL_CALL getName(  ) throw (css::uno::RuntimeException);
    virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw (css::uno::RuntimeException);

    // XNameAccess
    virtual css::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw(css::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw(css::uno::RuntimeException);

    // XElementAccess
    virtual css::uno::Type SAL_CALL getElementType() throw(css::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements() throw(css::uno::RuntimeException);

    // XIndexAccess
    virtual sal_Int32 SAL_CALL getCount() throw(css::uno::RuntimeException) ;
    virtual css::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw(css::lang::IndexOutOfBoundsException, css::lang::WrappedTargetException, css::uno::RuntimeException);

    // XNameContainer
    virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw(css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw(css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);

    // XSingleServiceFactory
    virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstance(  ) throw(css::uno::Exception, css::uno::RuntimeException);
    virtual css::uno::Reference< css::uno::XInterface > SAL_CALL createInstanceWithArguments( const css::uno::Sequence< css::uno::Any >& aArguments ) throw(css::uno::Exception, css::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL dispose(  ) throw (css::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& xListener ) throw (css::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& aListener ) throw (css::uno::RuntimeException);

    // XPropertySet
    virtual css::uno::Reference<css::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw (css::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const css::uno::Any& aValue ) throw (css::beans::UnknownPropertyException, css::beans::PropertyVetoException, css::lang::IllegalArgumentException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual css::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const css::uno::Reference<css::beans::XPropertyChangeListener>& xListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const css::uno::Reference<css::beans::XPropertyChangeListener>& aListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener(const ::rtl::OUString& PropertyName, const css::uno::Reference<css::beans::XVetoableChangeListener>& aListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener(const ::rtl::OUString& PropertyName,const css::uno::Reference<css::beans::XVetoableChangeListener>&aListener ) throw (css::beans::UnknownPropertyException, css::lang::WrappedTargetException, css::uno::RuntimeException);

private:
    void throwIfDisposed() const throw(css::uno::RuntimeException);
    SdStyleSheet* GetValidNewSheet( const css::uno::Any& rElement ) throw(css::lang::IllegalArgumentException);
    SdStyleSheet* GetSheetByName( const ::rtl::OUString& rName ) throw(css::container::NoSuchElementException, css::lang::WrappedTargetException );

    SfxStyleFamily mnFamily;
    rtl::Reference< SfxStyleSheetPool > mxPool;
    SdStyleFamilyImpl*  mpImpl;
};

typedef rtl::Reference< SdStyleFamily > SdStyleFamilyRef;

#endif     // _SD_STLFAMILY_HXX
<|endoftext|>


<commit_before>// 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.

#ifndef __STOUT_FLAGS_PARSE_HPP__
#define __STOUT_FLAGS_PARSE_HPP__

#include <sstream> // For istringstream.
#include <string>

#include <stout/bytes.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/json.hpp>
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>

#include <stout/os/read.hpp>

namespace flags {

template <typename T>
Try<T> parse(const std::string& value)
{
  T t;
  std::istringstream in(value);
  in >> t;

  if (in && in.eof()) {
    return t;
  }

  return Error("Failed to convert into required type");
}

template <>
inline Try<std::string> parse(const std::string& value)
{
  return value;
}

template <>
inline Try<bool> parse(const std::string& value)
{
  if (value == "true" || value == "1") {
    return true;
  } else if (value == "false" || value == "0") {
    return false;
  }
  return Error("Expecting a boolean (e.g., true or false)");
}

template <>
inline Try<Duration> parse(const std::string& value)
{
  return Duration::parse(value);
}

template <>
inline Try<Bytes> parse(const std::string& value)
{
  return Bytes::parse(value);
}

template <>
inline Try<JSON::Object> parse(const std::string& value)
{
  // A value that already starts with 'file://' will properly be
  // loaded from the file and put into 'value' but if it starts with
  // '/' we need to explicitly handle it for backwards compatibility
  // reasons (because we used to handle it before we introduced the
  // 'fetch' mechanism for flags that first fetches the data from URIs
  // such as 'file://').
  if (strings::startsWith(value, "/")) {
    LOG(WARNING) << "Specifying an absolute filename to read a command line "
                    "option out of without using 'file:// is deprecated and "
                    "will be removed in a future release. Simply adding "
                    "'file://' to the beginning of the path should eliminate "
                    "this warning.";

    Try<std::string> read = os::read(value);
    if (read.isError()) {
      return Error("Error reading file '" + value + "': " + read.error());
    }
    return JSON::parse<JSON::Object>(read.get());
  }
  return JSON::parse<JSON::Object>(value);
}

template <>
inline Try<JSON::Array> parse(const std::string& value)
{
  // A value that already starts with 'file://' will properly be
  // loaded from the file and put into 'value' but if it starts with
  // '/' we need to explicitly handle it for backwards compatibility
  // reasons (because we used to handle it before we introduced the
  // 'fetch' mechanism for flags that first fetches the data from URIs
  // such as 'file://').
  if (strings::startsWith(value, "/")) {
    LOG(WARNING) << "Specifying an absolute filename to read a command line "
                    "option out of without using 'file:// is deprecated and "
                    "will be removed in a future release. Simply adding "
                    "'file://' to the beginning of the path should eliminate "
                    "this warning.";

    Try<std::string> read = os::read(value);
    if (read.isError()) {
      return Error("Error reading file '" + value + "': " + read.error());
    }
    return JSON::parse<JSON::Array>(read.get());
  }
  return JSON::parse<JSON::Array>(value);
}

template <>
inline Try<Path> parse(const std::string& value)
{
  return Path(value);
}

} // namespace flags {

#endif // __STOUT_FLAGS_PARSE_HPP__
<commit_msg>Added net::IP parsing template to the flags parsers.<commit_after>// 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.

#ifndef __STOUT_FLAGS_PARSE_HPP__
#define __STOUT_FLAGS_PARSE_HPP__

#include <sstream> // For istringstream.
#include <string>

#include <stout/bytes.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/ip.hpp>
#include <stout/json.hpp>
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>

#include <stout/os/read.hpp>

namespace flags {

template <typename T>
Try<T> parse(const std::string& value)
{
  T t;
  std::istringstream in(value);
  in >> t;

  if (in && in.eof()) {
    return t;
  }

  return Error("Failed to convert into required type");
}

template <>
inline Try<std::string> parse(const std::string& value)
{
  return value;
}

template <>
inline Try<bool> parse(const std::string& value)
{
  if (value == "true" || value == "1") {
    return true;
  } else if (value == "false" || value == "0") {
    return false;
  }
  return Error("Expecting a boolean (e.g., true or false)");
}

template <>
inline Try<Duration> parse(const std::string& value)
{
  return Duration::parse(value);
}

template <>
inline Try<Bytes> parse(const std::string& value)
{
  return Bytes::parse(value);
}

template <>
inline Try<net::IP> parse(const std::string& value)
{
  return net::IP::parse(value, AF_INET);
}

template <>
inline Try<JSON::Object> parse(const std::string& value)
{
  // A value that already starts with 'file://' will properly be
  // loaded from the file and put into 'value' but if it starts with
  // '/' we need to explicitly handle it for backwards compatibility
  // reasons (because we used to handle it before we introduced the
  // 'fetch' mechanism for flags that first fetches the data from URIs
  // such as 'file://').
  if (strings::startsWith(value, "/")) {
    LOG(WARNING) << "Specifying an absolute filename to read a command line "
                    "option out of without using 'file:// is deprecated and "
                    "will be removed in a future release. Simply adding "
                    "'file://' to the beginning of the path should eliminate "
                    "this warning.";

    Try<std::string> read = os::read(value);
    if (read.isError()) {
      return Error("Error reading file '" + value + "': " + read.error());
    }
    return JSON::parse<JSON::Object>(read.get());
  }
  return JSON::parse<JSON::Object>(value);
}

template <>
inline Try<JSON::Array> parse(const std::string& value)
{
  // A value that already starts with 'file://' will properly be
  // loaded from the file and put into 'value' but if it starts with
  // '/' we need to explicitly handle it for backwards compatibility
  // reasons (because we used to handle it before we introduced the
  // 'fetch' mechanism for flags that first fetches the data from URIs
  // such as 'file://').
  if (strings::startsWith(value, "/")) {
    LOG(WARNING) << "Specifying an absolute filename to read a command line "
                    "option out of without using 'file:// is deprecated and "
                    "will be removed in a future release. Simply adding "
                    "'file://' to the beginning of the path should eliminate "
                    "this warning.";

    Try<std::string> read = os::read(value);
    if (read.isError()) {
      return Error("Error reading file '" + value + "': " + read.error());
    }
    return JSON::parse<JSON::Array>(read.get());
  }
  return JSON::parse<JSON::Array>(value);
}

template <>
inline Try<Path> parse(const std::string& value)
{
  return Path(value);
}

} // namespace flags {

#endif // __STOUT_FLAGS_PARSE_HPP__
<|endoftext|>