<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkBenchmark.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkString.h"

static bool union_proc(SkRegion& a, SkRegion& b) {
    SkRegion result;
    return result.op(a, b, SkRegion::kUnion_Op);
}

static bool sect_proc(SkRegion& a, SkRegion& b) {
    SkRegion result;
    return result.op(a, b, SkRegion::kIntersect_Op);
}

static bool diff_proc(SkRegion& a, SkRegion& b) {
    SkRegion result;
    return result.op(a, b, SkRegion::kDifference_Op);
}

static bool containsrgn_proc(SkRegion& a, SkRegion& b) {
    SkIRect r = a.getBounds();
    r.inset(r.width()/4, r.height()/4);
    (void)a.contains(r);

    r = b.getBounds();
    r.inset(r.width()/4, r.height()/4);
    return b.contains(r);
}

static bool sects_proc(SkRegion& a, SkRegion& b) {
    return a.intersects(b);
}

static bool containsxy_proc(SkRegion& a, SkRegion& b) {
    const SkIRect& r = a.getBounds();
    const int dx = r.width() / 8;
    const int dy = r.height() / 8;
    for (int y = r.fTop; y < r.fBottom; y += dy) {
        for (int x = r.fLeft; x < r.fRight; x += dx) {
            (void)a.contains(x, y);
        }
    }
    return true;
}

class RegionBench : public SkBenchmark {
public:
    typedef bool (*Proc)(SkRegion& a, SkRegion& b);

    SkRegion fA, fB;
    Proc     fProc;
    SkString fName;

    enum {
        W = 1024,
        H = 768,
        N = SkBENCHLOOP(2000)
    };

    SkIRect randrect(SkRandom& rand) {
        int x = rand.nextU() % W;
        int y = rand.nextU() % H;
        int w = rand.nextU() % W;
        int h = rand.nextU() % H;
        return SkIRect::MakeXYWH(x, y, w >> 1, h >> 1);
    }

    RegionBench(void* param, int count, Proc proc, const char name[]) : INHERITED(param) {
        fProc = proc;
        fName.printf("Region_%s_%d", name, count);

        SkRandom rand;
        for (int i = 0; i < count; i++) {
            fA.op(randrect(rand), SkRegion::kXOR_Op);
            fB.op(randrect(rand), SkRegion::kXOR_Op);
        }
    }

protected:
    virtual const char* onGetName() { return fName.c_str(); }

    virtual void onDraw(SkCanvas* canvas) {
        Proc proc = fProc;
        for (int i = 0; i < N; ++i) {
            proc(fA, fB);
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

#define SMALL   16

static SkBenchmark* gF0(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, union_proc, "union")); }
static SkBenchmark* gF1(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, sect_proc, "intersect")); }
static SkBenchmark* gF2(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, diff_proc, "difference")); }
static SkBenchmark* gF3(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, containsrgn_proc, "containsrgb")); }
static SkBenchmark* gF4(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, sects_proc, "intersects")); }
static SkBenchmark* gF5(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, containsxy_proc, "containsxy")); }

static BenchRegistry gR0(gF0);
static BenchRegistry gR1(gF1);
static BenchRegistry gR2(gF2);
static BenchRegistry gR3(gF3);
static BenchRegistry gR4(gF4);
static BenchRegistry gR5(gF5);
<commit_msg>make name lower-case, to match all other benches<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkBenchmark.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkString.h"

static bool union_proc(SkRegion& a, SkRegion& b) {
    SkRegion result;
    return result.op(a, b, SkRegion::kUnion_Op);
}

static bool sect_proc(SkRegion& a, SkRegion& b) {
    SkRegion result;
    return result.op(a, b, SkRegion::kIntersect_Op);
}

static bool diff_proc(SkRegion& a, SkRegion& b) {
    SkRegion result;
    return result.op(a, b, SkRegion::kDifference_Op);
}

static bool containsrgn_proc(SkRegion& a, SkRegion& b) {
    SkIRect r = a.getBounds();
    r.inset(r.width()/4, r.height()/4);
    (void)a.contains(r);

    r = b.getBounds();
    r.inset(r.width()/4, r.height()/4);
    return b.contains(r);
}

static bool sects_proc(SkRegion& a, SkRegion& b) {
    return a.intersects(b);
}

static bool containsxy_proc(SkRegion& a, SkRegion& b) {
    const SkIRect& r = a.getBounds();
    const int dx = r.width() / 8;
    const int dy = r.height() / 8;
    for (int y = r.fTop; y < r.fBottom; y += dy) {
        for (int x = r.fLeft; x < r.fRight; x += dx) {
            (void)a.contains(x, y);
        }
    }
    return true;
}

class RegionBench : public SkBenchmark {
public:
    typedef bool (*Proc)(SkRegion& a, SkRegion& b);

    SkRegion fA, fB;
    Proc     fProc;
    SkString fName;

    enum {
        W = 1024,
        H = 768,
        N = SkBENCHLOOP(2000)
    };

    SkIRect randrect(SkRandom& rand) {
        int x = rand.nextU() % W;
        int y = rand.nextU() % H;
        int w = rand.nextU() % W;
        int h = rand.nextU() % H;
        return SkIRect::MakeXYWH(x, y, w >> 1, h >> 1);
    }

    RegionBench(void* param, int count, Proc proc, const char name[]) : INHERITED(param) {
        fProc = proc;
        fName.printf("region_%s_%d", name, count);

        SkRandom rand;
        for (int i = 0; i < count; i++) {
            fA.op(randrect(rand), SkRegion::kXOR_Op);
            fB.op(randrect(rand), SkRegion::kXOR_Op);
        }
    }

protected:
    virtual const char* onGetName() { return fName.c_str(); }

    virtual void onDraw(SkCanvas* canvas) {
        Proc proc = fProc;
        for (int i = 0; i < N; ++i) {
            proc(fA, fB);
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

#define SMALL   16

static SkBenchmark* gF0(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, union_proc, "union")); }
static SkBenchmark* gF1(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, sect_proc, "intersect")); }
static SkBenchmark* gF2(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, diff_proc, "difference")); }
static SkBenchmark* gF3(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, containsrgn_proc, "containsrgb")); }
static SkBenchmark* gF4(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, sects_proc, "intersects")); }
static SkBenchmark* gF5(void* p) { return SkNEW_ARGS(RegionBench, (p, SMALL, containsxy_proc, "containsxy")); }

static BenchRegistry gR0(gF0);
static BenchRegistry gR1(gF1);
static BenchRegistry gR2(gF2);
static BenchRegistry gR3(gF3);
static BenchRegistry gR4(gF4);
static BenchRegistry gR5(gF5);
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkBenchmark.h"
#include "SkFloatBits.h"
#include "SkRandom.h"
#include "SkRect.h"
#include "SkString.h"

class ScalarBench : public SkBenchmark {
    SkString    fName;
    enum { N = 100000 };
public:
    ScalarBench(void* param, const char name[]) : INHERITED(param) {
        fName.printf("scalar_%s", name);
    }

    virtual void performTest() = 0;

protected:
    virtual int mulLoopCount() const { return 1; }

    virtual const char* onGetName() SK_OVERRIDE {
        SkASSERT(!"stop");
        return fName.c_str();
    }

    virtual void onDraw(SkCanvas* canvas) {
        int n = SkBENCHLOOP(N * this->mulLoopCount());
        for (int i = 0; i < n; i++) {
            this->performTest();
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

// we want to stop the compiler from eliminating code that it thinks is a no-op
// so we have a non-static global we increment, hoping that will convince the
// compiler to execute everything
int gScalarBench_NonStaticGlobal;

#define always_do(pred)                     \
    do {                                    \
        if (pred) {                         \
            ++gScalarBench_NonStaticGlobal; \
        }                                   \
    } while (0)

// having unknown values in our arrays can throw off the timing a lot, perhaps
// handling NaN values is a lot slower. Anyway, this guy is just meant to put
// reasonable values in our arrays.
template <typename T> void init9(T array[9]) {
    SkRandom rand;
    for (int i = 0; i < 9; i++) {
        array[i] = rand.nextSScalar1();
    }
}

class FloatComparisonBench : public ScalarBench {
public:
    FloatComparisonBench(void* param) : INHERITED(param, "compare_float") {
        init9(fArray);
    }
protected:
    virtual int mulLoopCount() const { return 4; }
    virtual void performTest() {
        always_do(fArray[6] != 0.0f || fArray[7] != 0.0f || fArray[8] != 1.0f);
        always_do(fArray[2] != 0.0f || fArray[5] != 0.0f);
    }
private:
    float fArray[9];
    typedef ScalarBench INHERITED;
};

class ForcedIntComparisonBench : public ScalarBench {
public:
    ForcedIntComparisonBench(void* param)
    : INHERITED(param, "compare_forced_int") {
        init9(fArray);
    }
protected:
    virtual int mulLoopCount() const { return 4; }
    virtual void performTest() {
        always_do(SkScalarAs2sCompliment(fArray[6]) |
                  SkScalarAs2sCompliment(fArray[7]) |
                  (SkScalarAs2sCompliment(fArray[8]) - kPersp1Int));
        always_do(SkScalarAs2sCompliment(fArray[2]) |
                  SkScalarAs2sCompliment(fArray[5]));
    }
private:
    static const int32_t kPersp1Int = 0x3f800000;
    SkScalar fArray[9];
    typedef ScalarBench INHERITED;
};

class IsFiniteScalarBench : public ScalarBench {
public:
    IsFiniteScalarBench(void* param) : INHERITED(param, "isfinite") {
        SkRandom rand;
        for (size_t i = 0; i < ARRAY_N; ++i) {
            fArray[i] = rand.nextSScalar1();
        }
    }
protected:
    virtual int mulLoopCount() const { return 1; }
    virtual void performTest() SK_OVERRIDE {
        int sum = 0;
        for (size_t i = 0; i < ARRAY_N; ++i) {
            // We pass -fArray[i], so the compiler can't cheat and treat the
            // value as an int (even though we tell it that it is a float)
            sum += SkScalarIsFinite(-fArray[i]);
        }
        // we do this so the compiler won't optimize our loop away...
        this->doSomething(fArray, sum);
    }

    virtual void doSomething(SkScalar array[], int sum) {}
private:
    enum {
        ARRAY_N = 64
    };
    SkScalar fArray[ARRAY_N];

    typedef ScalarBench INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

class RectBoundsBench : public SkBenchmark {
    enum {
        PTS = 100,
        N = SkBENCHLOOP(10000)
    };
    SkPoint fPts[PTS];

public:
    RectBoundsBench(void* param) : INHERITED(param) {
        SkRandom rand;
        for (int i = 0; i < PTS; ++i) {
            fPts[i].fX = rand.nextSScalar1();
            fPts[i].fY = rand.nextSScalar1();
        }
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return "rect_bounds";
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkRect r;
        for (int i = 0; i < N; ++i) {
            r.set(fPts, PTS);
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static SkBenchmark* S0(void* p) { return new FloatComparisonBench(p); }
static SkBenchmark* S1(void* p) { return new ForcedIntComparisonBench(p); }
static SkBenchmark* S2(void* p) { return new RectBoundsBench(p); }
static SkBenchmark* S3(void* p) { return new IsFiniteScalarBench(p); }

static BenchRegistry gReg0(S0);
static BenchRegistry gReg1(S1);
static BenchRegistry gReg2(S2);
static BenchRegistry gReg3(S3);
<commit_msg>Reverting r4239 & r4240<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkBenchmark.h"
#include "SkFloatBits.h"
#include "SkRandom.h"
#include "SkRect.h"
#include "SkString.h"

class ScalarBench : public SkBenchmark {
    SkString    fName;
    enum { N = 100000 };
public:
    ScalarBench(void* param, const char name[]) : INHERITED(param) {
        fName.printf("scalar_%s", name);
    }

    virtual void performTest() = 0;

protected:
    virtual int mulLoopCount() const { return 1; }

    virtual const char* onGetName() {
        return fName.c_str();
    }

    virtual void onDraw(SkCanvas* canvas) {
        int n = SkBENCHLOOP(N * this->mulLoopCount());
        for (int i = 0; i < n; i++) {
            this->performTest();
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

// we want to stop the compiler from eliminating code that it thinks is a no-op
// so we have a non-static global we increment, hoping that will convince the
// compiler to execute everything
int gScalarBench_NonStaticGlobal;

#define always_do(pred)                     \
    do {                                    \
        if (pred) {                         \
            ++gScalarBench_NonStaticGlobal; \
        }                                   \
    } while (0)

// having unknown values in our arrays can throw off the timing a lot, perhaps
// handling NaN values is a lot slower. Anyway, this guy is just meant to put
// reasonable values in our arrays.
template <typename T> void init9(T array[9]) {
    SkRandom rand;
    for (int i = 0; i < 9; i++) {
        array[i] = rand.nextSScalar1();
    }
}

class FloatComparisonBench : public ScalarBench {
public:
    FloatComparisonBench(void* param) : INHERITED(param, "compare_float") {
        init9(fArray);
    }
protected:
    virtual int mulLoopCount() const { return 4; }
    virtual void performTest() {
        always_do(fArray[6] != 0.0f || fArray[7] != 0.0f || fArray[8] != 1.0f);
        always_do(fArray[2] != 0.0f || fArray[5] != 0.0f);
    }
private:
    float fArray[9];
    typedef ScalarBench INHERITED;
};

class ForcedIntComparisonBench : public ScalarBench {
public:
    ForcedIntComparisonBench(void* param)
        : INHERITED(param, "compare_forced_int") {
        init9(fArray);
    }
protected:
    virtual int mulLoopCount() const { return 4; }
    virtual void performTest() {
        always_do(SkScalarAs2sCompliment(fArray[6]) |
                  SkScalarAs2sCompliment(fArray[7]) |
                  (SkScalarAs2sCompliment(fArray[8]) - kPersp1Int));
        always_do(SkScalarAs2sCompliment(fArray[2]) |
                  SkScalarAs2sCompliment(fArray[5]));
    }
private:
    static const int32_t kPersp1Int = 0x3f800000;
    SkScalar fArray[9];
    typedef ScalarBench INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

class RectBoundsBench : public SkBenchmark {
    enum {
        PTS = 100,
        N = SkBENCHLOOP(10000)
    };
    SkPoint fPts[PTS];

public:
    RectBoundsBench(void* param) : INHERITED(param) {
        SkRandom rand;
        for (int i = 0; i < PTS; ++i) {
            fPts[i].fX = rand.nextSScalar1();
            fPts[i].fY = rand.nextSScalar1();
        }
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return "rect_bounds";
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkRect r;
        for (int i = 0; i < N; ++i) {
            r.set(fPts, PTS);
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static SkBenchmark* S0(void* p) { return new FloatComparisonBench(p); }
static SkBenchmark* S1(void* p) { return new ForcedIntComparisonBench(p); }
static SkBenchmark* S2(void* p) { return new RectBoundsBench(p); }

static BenchRegistry gReg0(S0);
static BenchRegistry gReg1(S1);
static BenchRegistry gReg2(S2);
<|endoftext|>


<commit_before>#include <iostream> //for std::cerr?
#include <string>
#include <fcntl.h> //needed for (file) open()
//#include <stdlib.h> //needed for exit()
#include <stdio.h> //for printf?
#include <sys/mman.h> //for mlockall
#include "logging.h"

#include "gparse/serial.h"
#include "state.h"
#include "drivers/driver.h"
#include "drivers/kossel/kossel.h"
#include "argparse.h"

drv::Kossel driver;
State<drv::Kossel> gState(driver);

void printUsage(char* cmd) {
	#ifndef NO_USAGE_INFO
    std::cerr << "usage: " << cmd << " ttyFile" << std::endl;
    #endif
    //exit(1);
}

int main(int argc, char** argv) {
    if (argc < 2 || argparse::cmdOptionExists(argv, argv+argc, "-h") || argparse::cmdOptionExists(argv, argv+argc, "--help")) {
        printUsage(argv[0]);
        return 1;
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--quiet")) {
    	logging::disable();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--verbose")) {
    	logging::enableVerbose();
    }

    //prevent page-swaps to increase performace:
    int retval = mlockall(MCL_FUTURE|MCL_CURRENT);
    if (retval) {
    	LOGW("Warning: mlockall (prevent memory swaps) in main.cpp::main() returned non-zero: %i\n", retval);
    }

    char* serialFileName = argv[1];
    LOG("Serial file: %s\n", serialFileName);
    int fd = open(serialFileName, O_RDWR);
    gparse::comLoop(fd, gState);
    LOG("Exiting\n");
    //exit(0);
    return 0;
}
<commit_msg>Moved globals from main.cpp into int main(...)<commit_after>#include <iostream> //for std::cerr?
#include <string>
#include <fcntl.h> //needed for (file) open()
//#include <stdlib.h> //needed for exit()
#include <stdio.h> //for printf?
#include <sys/mman.h> //for mlockall
#include "logging.h"

#include "gparse/serial.h"
#include "state.h"
#include "drivers/driver.h"
#include "drivers/kossel/kossel.h"
#include "argparse.h"

void printUsage(char* cmd) {
	#ifndef NO_USAGE_INFO
    std::cerr << "usage: " << cmd << " ttyFile" << std::endl;
    #endif
    //exit(1);
}

int main(int argc, char** argv) {
    if (argc < 2 || argparse::cmdOptionExists(argv, argv+argc, "-h") || argparse::cmdOptionExists(argv, argv+argc, "--help")) {
        printUsage(argv[0]);
        return 1;
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--quiet")) {
    	logging::disable();
    }
    if (argparse::cmdOptionExists(argv, argv+argc, "--verbose")) {
    	logging::enableVerbose();
    }

    //prevent page-swaps to increase performace:
    int retval = mlockall(MCL_FUTURE|MCL_CURRENT);
    if (retval) {
    	LOGW("Warning: mlockall (prevent memory swaps) in main.cpp::main() returned non-zero: %i\n", retval);
    }

    char* serialFileName = argv[1];
    LOG("Serial file: %s\n", serialFileName);
    int fd = open(serialFileName, O_RDWR);

    drv::Kossel driver;
	State<drv::Kossel> gState(driver);

    gparse::comLoop(fd, gState);
    LOG("Exiting\n");
    //exit(0);
    return 0;
}
<|endoftext|>


<commit_before>#include <list>
#include <vector>

#include "Permuter.h"
#include "../utils/utils.h"

namespace fs_testing {
namespace permuter {

using std::list;
using std::size_t;
using std::vector;

using fs_testing::utils::disk_write;

namespace {

struct range {
  unsigned int start;
  unsigned int end;
};

static const unsigned int kRetryMultiplier = 2;
static const unsigned int kMinRetries = 1000;

}  // namespace

size_t BioVectorHash::operator() (const vector<unsigned int>& permutation)
    const {
  unsigned int seed = permutation.size();
  for (const auto& bio_pos : permutation) {
    seed ^= bio_pos + 0x9e3779b9 + (seed << 6) + (seed >> 2);
  }
  return seed;
}

bool BioVectorEqual::operator() (const std::vector<unsigned int>& a,
    const std::vector<unsigned int>& b) const {
  if (a.size() != b.size()) {
    return false;
  }
  for (unsigned int i = 0; i < a.size(); ++i) {
    if (a.at(i) != b.at(i)) {
      return false;
    }
  }
  return true;
}

void Permuter::InitDataVector(vector<disk_write> *data) {
  epochs_.clear();
  unsigned int index = 0;
  bool prev_epoch_flush_op = false;
  disk_write data_half;
  // disk_write data_flush_part1, data_write_part2;
  list<range> overlaps;
  while (index < data->size()) {
    struct epoch current_epoch;
    current_epoch.has_barrier = false;
    current_epoch.overlaps = false;

    // Get all ops in this epoch and add them to either the sync_op or async_op
    // lists.
    while (index < data->size() && !(data->at(index)).is_barrier_write()) {

      if (prev_epoch_flush_op == true) {
      	epoch_op curr_op = {index-1, data_half};
      	current_epoch.ops.push_back(curr_op);
      	current_epoch.num_meta += data_half.is_meta();
      	prev_epoch_flush_op = false;
      }

      disk_write curr = data->at(index);
      // Find overlapping ranges.
      unsigned int start = curr.metadata.write_sector;
      unsigned int end = start + curr.metadata.size;
      for (auto range_iter = overlaps.begin(); range_iter != overlaps.end();
          range_iter++) {
        range r = *range_iter;
        if ((r.start <= start && r.end >= start)
            || (r.start <= end && r.end >= end)) {
          if (r.start > start) {
            r.start = start;
          }
          if (r.end < end) {
            r.end = end;
          }
          current_epoch.overlaps = true;
          break;
        } else if (r.start > end) {
          // Since this is an ordered list, if the next spot is past where we're
          // looking now then we won't find anything past here. We may as well
          // insert an item here.
          range new_range = {start, end};
          overlaps.insert(range_iter, new_range);
        }
      }

      epoch_op curr_op = {index, data->at(index)};
      current_epoch.ops.push_back(curr_op);
      current_epoch.num_meta += data->at(index).is_meta();
      ++index;
    }

    // Check is the op at the current index is a "barrier." If it is then add it
    // to the special spot in the epoch, otherwise just push the current epoch
    // onto the list and move to the next segment of the log.
    if (index < data->size() && (data->at(index)).is_barrier_write()) {

      // Check if the op at the current index has a flush flag with data. It it has, then divide
      // it into two halves and make the data available only in the starting of the next epoch.
      // If the op has a FUA flag, then it gets normally added into the current epoch
      if ((data->at(index).has_flush_flag() || data->at(index).has_flush_seq_flag()) && data->at(index).has_write_flag() && (!data->at(index).has_FUA_flag())) {

        disk_write flag_half;
        data_half = data->at(index);

        if(data->at(index).has_flush_flag()) {
          flag_half.set_flush_flag();
          data_half.clear_flush_flag();
        }

        if(data->at(index).has_flush_seq_flag()) {
          flag_half.set_flush_seq_flag();
          data_half.clear_flush_seq_flag();
        }

        epoch_op curr_op = {index, flag_half};
        current_epoch.ops.push_back(curr_op);
        current_epoch.num_meta += flag_half.is_meta();
        epochs_.push_back(current_epoch);
        prev_epoch_flush_op = true;
        current_epoch.has_barrier = true;
        ++index;
        continue;
      }

      epoch_op curr_op = {index, data->at(index)};
      current_epoch.ops.push_back(curr_op);
      current_epoch.num_meta += data->at(index).is_meta();
      current_epoch.has_barrier = true;
      ++index;
    }
    epochs_.push_back(current_epoch);
  }
}

vector<epoch>* Permuter::GetEpochs() {
  return &epochs_;
}

bool Permuter::GenerateCrashState(vector<disk_write>& res) {
  vector<epoch_op> crash_state;
  unsigned long retries = 0;
  unsigned int exists = 0;
  bool new_state = true;
  vector<unsigned int> crash_state_hash;

  unsigned long max_retries =
    ((kRetryMultiplier * completed_permutations_.size()) < kMinRetries)
      ? kMinRetries
      : kRetryMultiplier * completed_permutations_.size();
  do {
    new_state = gen_one_state(crash_state);

    crash_state_hash.clear();
    crash_state_hash.resize(crash_state.size());
    for (unsigned int i = 0; i < crash_state.size(); ++i) {
      crash_state_hash.at(i) = crash_state.at(i).abs_index;
    }

    ++retries;
    exists = completed_permutations_.count(crash_state_hash);
    if (!new_state || retries >= max_retries) {
      // We've likely found all possible crash states so just break. The
      // constant in the multiplier was randomly chosen in the hopes that it
      // would be a good hueristic. This is more to make sure that we don't spin
      // endlessly than it is for it to be a good way to break out of trying to
      // make unique permutations.
      break;
    }
  } while (exists > 0);

  // Move the permuted crash state data over into the returned crash state
  // vector.
  res.clear();
  res.resize(crash_state.size());
  for (unsigned int i = 0; i < crash_state.size(); ++i) {
    res.at(i) = crash_state.at(i).op;
  }

  if (exists == 0) {
    completed_permutations_.insert(crash_state_hash);
    // We broke out of the above loop because this state is unique.
    return new_state;
  }

  // We broke out of the above loop because we haven't found a new state in some
  // time.
  return false;
}

}  // namespace permuter
}  // namespace fs_testing
<commit_msg>Update Permuter.cpp<commit_after>#include <list>
#include <vector>

#include "Permuter.h"
#include "../utils/utils.h"

namespace fs_testing {
namespace permuter {

using std::list;
using std::size_t;
using std::vector;

using fs_testing::utils::disk_write;

namespace {

struct range {
  unsigned int start;
  unsigned int end;
};

static const unsigned int kRetryMultiplier = 2;
static const unsigned int kMinRetries = 1000;

}  // namespace

size_t BioVectorHash::operator() (const vector<unsigned int>& permutation)
    const {
  unsigned int seed = permutation.size();
  for (const auto& bio_pos : permutation) {
    seed ^= bio_pos + 0x9e3779b9 + (seed << 6) + (seed >> 2);
  }
  return seed;
}

bool BioVectorEqual::operator() (const std::vector<unsigned int>& a,
    const std::vector<unsigned int>& b) const {
  if (a.size() != b.size()) {
    return false;
  }
  for (unsigned int i = 0; i < a.size(); ++i) {
    if (a.at(i) != b.at(i)) {
      return false;
    }
  }
  return true;
}

void Permuter::InitDataVector(vector<disk_write> *data) {
  epochs_.clear();
  unsigned int index = 0;
  bool prev_epoch_flush_op = false;
  disk_write data_half;
  // disk_write data_flush_part1, data_write_part2;
  list<range> overlaps;
  while (index < data->size()) {
    struct epoch current_epoch;
    current_epoch.has_barrier = false;
    current_epoch.overlaps = false;

    // Get all ops in this epoch and add them to either the sync_op or async_op
    // lists.
    while (index < data->size() && !(data->at(index)).is_barrier_write()) {

      if (prev_epoch_flush_op == true) {
      	epoch_op curr_op = {index-1, data_half};
      	current_epoch.ops.push_back(curr_op);
      	current_epoch.num_meta += data_half.is_meta();
      	prev_epoch_flush_op = false;
      }

      disk_write curr = data->at(index);
      // Find overlapping ranges.
      unsigned int start = curr.metadata.write_sector;
      unsigned int end = start + curr.metadata.size;
      for (auto range_iter = overlaps.begin(); range_iter != overlaps.end();
          range_iter++) {
        range r = *range_iter;
        if ((r.start <= start && r.end >= start)
            || (r.start <= end && r.end >= end)) {
          if (r.start > start) {
            r.start = start;
          }
          if (r.end < end) {
            r.end = end;
          }
          current_epoch.overlaps = true;
          break;
        } else if (r.start > end) {
          // Since this is an ordered list, if the next spot is past where we're
          // looking now then we won't find anything past here. We may as well
          // insert an item here.
          range new_range = {start, end};
          overlaps.insert(range_iter, new_range);
        }
      }

      epoch_op curr_op = {index, data->at(index)};
      current_epoch.ops.push_back(curr_op);
      current_epoch.num_meta += data->at(index).is_meta();
      ++index;
    }

    // Check is the op at the current index is a "barrier." If it is then add it
    // to the special spot in the epoch, otherwise just push the current epoch
    // onto the list and move to the next segment of the log.
    if (index < data->size() && (data->at(index)).is_barrier_write()) {

      // Check if the op at the current index has a flush flag with data. It it has, then divide
      // it into two halves and make the data available only in the start of the next epoch.
      // If the op has a FUA flag, then it gets normally added into the current epoch
      if ((data->at(index).has_flush_flag() || data->at(index).has_flush_seq_flag()) && data->at(index).has_write_flag() && (!data->at(index).has_FUA_flag())) {

        disk_write flag_half;
        data_half = data->at(index);

        if(data->at(index).has_flush_flag()) {
          flag_half.set_flush_flag();
          data_half.clear_flush_flag();
        }

        if(data->at(index).has_flush_seq_flag()) {
          flag_half.set_flush_seq_flag();
          data_half.clear_flush_seq_flag();
        }

        epoch_op curr_op = {index, flag_half};
        current_epoch.ops.push_back(curr_op);
        current_epoch.num_meta += flag_half.is_meta();
        epochs_.push_back(current_epoch);
        prev_epoch_flush_op = true;
        current_epoch.has_barrier = true;
        ++index;
        continue;
      }

      epoch_op curr_op = {index, data->at(index)};
      current_epoch.ops.push_back(curr_op);
      current_epoch.num_meta += data->at(index).is_meta();
      current_epoch.has_barrier = true;
      ++index;
    }
    epochs_.push_back(current_epoch);
  }
}

vector<epoch>* Permuter::GetEpochs() {
  return &epochs_;
}

bool Permuter::GenerateCrashState(vector<disk_write>& res) {
  vector<epoch_op> crash_state;
  unsigned long retries = 0;
  unsigned int exists = 0;
  bool new_state = true;
  vector<unsigned int> crash_state_hash;

  unsigned long max_retries =
    ((kRetryMultiplier * completed_permutations_.size()) < kMinRetries)
      ? kMinRetries
      : kRetryMultiplier * completed_permutations_.size();
  do {
    new_state = gen_one_state(crash_state);

    crash_state_hash.clear();
    crash_state_hash.resize(crash_state.size());
    for (unsigned int i = 0; i < crash_state.size(); ++i) {
      crash_state_hash.at(i) = crash_state.at(i).abs_index;
    }

    ++retries;
    exists = completed_permutations_.count(crash_state_hash);
    if (!new_state || retries >= max_retries) {
      // We've likely found all possible crash states so just break. The
      // constant in the multiplier was randomly chosen in the hopes that it
      // would be a good hueristic. This is more to make sure that we don't spin
      // endlessly than it is for it to be a good way to break out of trying to
      // make unique permutations.
      break;
    }
  } while (exists > 0);

  // Move the permuted crash state data over into the returned crash state
  // vector.
  res.clear();
  res.resize(crash_state.size());
  for (unsigned int i = 0; i < crash_state.size(); ++i) {
    res.at(i) = crash_state.at(i).op;
  }

  if (exists == 0) {
    completed_permutations_.insert(crash_state_hash);
    // We broke out of the above loop because this state is unique.
    return new_state;
  }

  // We broke out of the above loop because we haven't found a new state in some
  // time.
  return false;
}

}  // namespace permuter
}  // namespace fs_testing
<|endoftext|>


<commit_before>#include "gtest/gtest.h"

//----- Another test
TEST(StringTest, 1)
{
  ASSERT_STREQ("FOO","BAR");
}
<commit_msg>string test success<commit_after>#include "gtest/gtest.h"

//----- Another test
TEST(StringTest, 1)
{
  ASSERT_STREQ("FOO","FOO");
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <sax/SAXException.hpp>
#include <sax/SAXParseException.hpp>
#include <parsers/IDOMParser.hpp>
#include <idom/IDOM_DOMException.hpp>
#include <idom/IDOM_Document.hpp>
#include "IDOMCount.hpp"
#include <string.h>
#include <stdlib.h>

// ---------------------------------------------------------------------------
//  This is a simple program which invokes the DOMParser to build a DOM
//  tree for the specified input file. It then walks the tree and counts
//  the number of elements. The element count is then printed.
// ---------------------------------------------------------------------------
static void usage()
{
    cout << "\nUsage:\n"
            "    DOMCount [-v -n] {XML file}\n\n"
            "This program invokes the XML4C DOM parser, builds\n"
            "the DOM tree, and then prints the number of elements\n"
            "found in the input XML file.\n\n"
            "Options:\n"
            "    -v=xxx      Validation scheme [always | never | auto*]\n"
            "    -n          Enable namespace processing. Defaults to off.\n\n"
            "    -s          Enable schema processing. Defaults to off.\n\n"
            "  * = Default if not provided explicitly\n\n"
         << endl;
}

// ---------------------------------------------------------------------------
//
//  Recursively Count up the total number of child Elements under the specified Node.
//
// ---------------------------------------------------------------------------
static int countChildElements(IDOM_Node *n)
{
    IDOM_Node *child;
    int count = 0;
    for (child = n->getFirstChild(); child != 0; child=child->getNextSibling())
    {
        if (n->getNodeType() == IDOM_Node::ELEMENT_NODE)
        {
            count++;
            count += countChildElements(child);
        }
    }
    return count;
}

// ---------------------------------------------------------------------------
//
//   main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
    // Initialize the XML4C system
    try
    {
        XMLPlatformUtils::Initialize();
    }

    catch (const XMLException& toCatch)
    {
         cerr << "Error during initialization! :\n"
              << StrX(toCatch.getMessage()) << endl;
         return 1;
    }

    // Check command line and extract arguments.
    if (argC < 2)
    {
        usage();
        return 1;
    }

    const char*               xmlFile = 0;
    IDOMParser::ValSchemes    valScheme = IDOMParser::Val_Auto;
    bool                      doNamespaces    = false;
    bool                      doSchema        = false;

    // See if non validating dom parser configuration is requested.
    if ((argC == 2) && !strcmp(argV[1], "-?"))
    {
        usage();
        return 2;
    }

    int argInd;
    for (argInd = 1; argInd < argC; argInd++)
    {
        // Break out on first non-dash parameter
        if (argV[argInd][0] != '-')
            break;

        if (!strncmp(argV[argInd], "-v=", 3)
        ||  !strncmp(argV[argInd], "-V=", 3))
        {
            const char* const parm = &argV[argInd][3];

            if (!strcmp(parm, "never"))
                valScheme = IDOMParser::Val_Never;
            else if (!strcmp(parm, "auto"))
                valScheme = IDOMParser::Val_Auto;
            else if (!strcmp(parm, "always"))
                valScheme = IDOMParser::Val_Always;
            else
            {
                cerr << "Unknown -v= value: " << parm << endl;
                return 2;
            }
        }
         else if (!strcmp(argV[argInd], "-n")
              ||  !strcmp(argV[argInd], "-N"))
        {
            doNamespaces = true;
        }
         else if (!strcmp(argV[argInd], "-s")
              ||  !strcmp(argV[argInd], "-S"))
        {
            doSchema = true;
        }
         else
        {
            cerr << "Unknown option '" << argV[argInd]
                 << "', ignoring it\n" << endl;
        }
    }

    //
    //  There should be only one and only one parameter left, and that
    //  should be the file name.
    //
    if (argInd != argC - 1)
    {
        usage();
        return 1;
    }
    xmlFile = argV[argInd];

    // Instantiate the DOM parser.
    IDOMParser parser;
    parser.setValidationScheme(valScheme);
    parser.setDoNamespaces(doNamespaces);
    parser.setDoSchema(doSchema);

    // And create our error handler and install it
    DOMCountErrorHandler errorHandler;
    parser.setErrorHandler(&errorHandler);

    //
    //  Get the starting time and kick off the parse of the indicated
    //  file. Catch any exceptions that might propogate out of it.
    //
    unsigned long duration;
    try
    {
        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
        parser.parse(xmlFile);
        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
        duration = endMillis - startMillis;
    }

    catch (const XMLException& toCatch)
    {
        cerr << "\nError during parsing: '" << xmlFile << "'\n"
             << "Exception message is:  \n"
             << StrX(toCatch.getMessage()) << "\n" << endl;
        return -1;
    }
    catch (const IDOM_DOMException& toCatch)
    {
        cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n"
             << "DOMException code is:  \n"
             << toCatch.code << "\n" << endl;
        XMLPlatformUtils::Terminate();
        return 4;
    }
    catch (...)
    {
       cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";
        XMLPlatformUtils::Terminate();
        return 4;
    }

    //
    //  Extract the DOM tree, get the list of all the elements and report the
    //  length as the count of elements.
    //
    if (errorHandler.getSawErrors())
    {
        cout << "\nErrors occured, no output available\n" << endl;
    }
     else
    {
        IDOM_Document *doc = parser.getDocument();
        //unsigned int elementCount = doc.getElementsByTagName("*").getLength();
        unsigned int elementCount = countChildElements(doc);

        // Print out the stats that we collected and time taken.
        cout << xmlFile << ": " << duration << " ms ("
             << elementCount << " elems)." << endl;
    }

    // And call the termination method
    XMLPlatformUtils::Terminate();

    return 0;
}

DOMCountErrorHandler::DOMCountErrorHandler() :

    fSawErrors(false)
{
}

DOMCountErrorHandler::~DOMCountErrorHandler()
{
}

// ---------------------------------------------------------------------------
//  DOMCountHandlers: Overrides of the SAX ErrorHandler interface
// ---------------------------------------------------------------------------
void DOMCountErrorHandler::error(const SAXParseException& e)
{
    fSawErrors = true;
    cerr << "\nError at file " << StrX(e.getSystemId())
         << ", line " << e.getLineNumber()
         << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << endl;
}

void DOMCountErrorHandler::fatalError(const SAXParseException& e)
{
    fSawErrors = true;
    cerr << "\nFatal Error at file " << StrX(e.getSystemId())
         << ", line " << e.getLineNumber()
         << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << endl;
}

void DOMCountErrorHandler::warning(const SAXParseException& e)
{
    cerr << "\nWarning at file " << StrX(e.getSystemId())
         << ", line " << e.getLineNumber()
         << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << endl;
}

void DOMCountErrorHandler::resetErrors()
{
}
<commit_msg>IDOM: Incorrect element count.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <sax/SAXException.hpp>
#include <sax/SAXParseException.hpp>
#include <parsers/IDOMParser.hpp>
#include <idom/IDOM_DOMException.hpp>
#include <idom/IDOM_Document.hpp>
#include "IDOMCount.hpp"
#include <string.h>
#include <stdlib.h>

// ---------------------------------------------------------------------------
//  This is a simple program which invokes the DOMParser to build a DOM
//  tree for the specified input file. It then walks the tree and counts
//  the number of elements. The element count is then printed.
// ---------------------------------------------------------------------------
static void usage()
{
    cout << "\nUsage:\n"
            "    DOMCount [-v -n] {XML file}\n\n"
            "This program invokes the XML4C DOM parser, builds\n"
            "the DOM tree, and then prints the number of elements\n"
            "found in the input XML file.\n\n"
            "Options:\n"
            "    -v=xxx      Validation scheme [always | never | auto*]\n"
            "    -n          Enable namespace processing. Defaults to off.\n\n"
            "    -s          Enable schema processing. Defaults to off.\n\n"
            "  * = Default if not provided explicitly\n\n"
         << endl;
}

// ---------------------------------------------------------------------------
//
//  Recursively Count up the total number of child Elements under the specified Node.
//
// ---------------------------------------------------------------------------
static int countChildElements(IDOM_Node *n)
{
    IDOM_Node *child;
    int count = 0;
    if (n->getNodeType() == IDOM_Node::ELEMENT_NODE)
    {
        count++;
        for (child = n->getFirstChild(); child != 0; child=child->getNextSibling())
        {
            if (child->getNodeType() == IDOM_Node::ELEMENT_NODE)
            {
                count += countChildElements(child);
            }
        }
    }
    return count;
}

// ---------------------------------------------------------------------------
//
//   main
//
// ---------------------------------------------------------------------------
int main(int argC, char* argV[])
{
    // Initialize the XML4C system
    try
    {
        XMLPlatformUtils::Initialize();
    }

    catch (const XMLException& toCatch)
    {
         cerr << "Error during initialization! :\n"
              << StrX(toCatch.getMessage()) << endl;
         return 1;
    }

    // Check command line and extract arguments.
    if (argC < 2)
    {
        usage();
        return 1;
    }

    const char*               xmlFile = 0;
    IDOMParser::ValSchemes    valScheme = IDOMParser::Val_Auto;
    bool                      doNamespaces    = false;
    bool                      doSchema        = false;

    // See if non validating dom parser configuration is requested.
    if ((argC == 2) && !strcmp(argV[1], "-?"))
    {
        usage();
        return 2;
    }

    int argInd;
    for (argInd = 1; argInd < argC; argInd++)
    {
        // Break out on first non-dash parameter
        if (argV[argInd][0] != '-')
            break;

        if (!strncmp(argV[argInd], "-v=", 3)
        ||  !strncmp(argV[argInd], "-V=", 3))
        {
            const char* const parm = &argV[argInd][3];

            if (!strcmp(parm, "never"))
                valScheme = IDOMParser::Val_Never;
            else if (!strcmp(parm, "auto"))
                valScheme = IDOMParser::Val_Auto;
            else if (!strcmp(parm, "always"))
                valScheme = IDOMParser::Val_Always;
            else
            {
                cerr << "Unknown -v= value: " << parm << endl;
                return 2;
            }
        }
         else if (!strcmp(argV[argInd], "-n")
              ||  !strcmp(argV[argInd], "-N"))
        {
            doNamespaces = true;
        }
         else if (!strcmp(argV[argInd], "-s")
              ||  !strcmp(argV[argInd], "-S"))
        {
            doSchema = true;
        }
         else
        {
            cerr << "Unknown option '" << argV[argInd]
                 << "', ignoring it\n" << endl;
        }
    }

    //
    //  There should be only one and only one parameter left, and that
    //  should be the file name.
    //
    if (argInd != argC - 1)
    {
        usage();
        return 1;
    }
    xmlFile = argV[argInd];

    // Instantiate the DOM parser.
    IDOMParser parser;
    parser.setValidationScheme(valScheme);
    parser.setDoNamespaces(doNamespaces);
    parser.setDoSchema(doSchema);

    // And create our error handler and install it
    DOMCountErrorHandler errorHandler;
    parser.setErrorHandler(&errorHandler);

    //
    //  Get the starting time and kick off the parse of the indicated
    //  file. Catch any exceptions that might propogate out of it.
    //
    unsigned long duration;
    try
    {
        const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
        parser.parse(xmlFile);
        const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
        duration = endMillis - startMillis;
    }

    catch (const XMLException& toCatch)
    {
        cerr << "\nError during parsing: '" << xmlFile << "'\n"
             << "Exception message is:  \n"
             << StrX(toCatch.getMessage()) << "\n" << endl;
        return -1;
    }
    catch (const IDOM_DOMException& toCatch)
    {
        cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n"
             << "DOMException code is:  \n"
             << toCatch.code << "\n" << endl;
        XMLPlatformUtils::Terminate();
        return 4;
    }
    catch (...)
    {
       cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";
        XMLPlatformUtils::Terminate();
        return 4;
    }

    //
    //  Extract the DOM tree, get the list of all the elements and report the
    //  length as the count of elements.
    //
    if (errorHandler.getSawErrors())
    {
        cout << "\nErrors occured, no output available\n" << endl;
    }
     else
    {
        IDOM_Document *doc = parser.getDocument();
        //unsigned int elementCount = doc.getElementsByTagName("*").getLength();
        unsigned int elementCount = countChildElements((IDOM_Node*)doc->getDocumentElement());

        // Print out the stats that we collected and time taken.
        cout << xmlFile << ": " << duration << " ms ("
             << elementCount << " elems)." << endl;
    }

    // And call the termination method
    XMLPlatformUtils::Terminate();

    return 0;
}

DOMCountErrorHandler::DOMCountErrorHandler() :

    fSawErrors(false)
{
}

DOMCountErrorHandler::~DOMCountErrorHandler()
{
}

// ---------------------------------------------------------------------------
//  DOMCountHandlers: Overrides of the SAX ErrorHandler interface
// ---------------------------------------------------------------------------
void DOMCountErrorHandler::error(const SAXParseException& e)
{
    fSawErrors = true;
    cerr << "\nError at file " << StrX(e.getSystemId())
         << ", line " << e.getLineNumber()
         << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << endl;
}

void DOMCountErrorHandler::fatalError(const SAXParseException& e)
{
    fSawErrors = true;
    cerr << "\nFatal Error at file " << StrX(e.getSystemId())
         << ", line " << e.getLineNumber()
         << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << endl;
}

void DOMCountErrorHandler::warning(const SAXParseException& e)
{
    cerr << "\nWarning at file " << StrX(e.getSystemId())
         << ", line " << e.getLineNumber()
         << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << endl;
}

void DOMCountErrorHandler::resetErrors()
{
}
<|endoftext|>


<commit_before>#pragma once
#include <memory>
#include <random>
#include <stdexcept>      // std::invalid_argument

#include "argtype.hpp"
#include "json.hpp"

namespace nervana {
    class decoded_media;
    class params;
    class json_config_parser;
}

typedef std::shared_ptr<nervana::decoded_media>        media_ptr;
typedef std::shared_ptr<nervana::json_config_parser>   config_ptr;
typedef std::shared_ptr<nervana::params>               param_ptr;

enum class MediaType {
    UNKNOWN = -1,
    IMAGE = 0,
    VIDEO = 1,
    AUDIO = 2,
    TEXT = 3,
    TARGET = 4,
};

/*  ABSTRACT INTERFACES */
class nervana::decoded_media {
public:
    virtual ~decoded_media() {}
    virtual MediaType get_type() = 0;
};

/*  ABSTRACT INTERFACES */
class nervana::params {
public:
    virtual ~params() {}
};

class nervana::json_config_parser {
public:
    template<typename T> void parse_dist(T& value, const std::string key, const nlohmann::json &js)
    {
        auto val = js.find(key);
        if (val != js.end()) {
            auto params = val->get<std::vector<typename T::result_type>>();
            set_dist_params(value, params);
        }
    }

    template<typename T, typename S> inline void set_dist_params(T& dist, S& params)
    {
        dist = T{params[0], params[1]};
    }

    // Specialization for a bernoulli coin flipping random var
    inline void set_dist_params(std::bernoulli_distribution& dist, std::vector<bool>& params)
    {
        dist = std::bernoulli_distribution{params[0] ? 0.5 : 0.0};
    }

    template<typename T> void parse_value(
                                    T& value,
                                    const std::string key,
                                    const nlohmann::json &js,
                                    bool required=false )
    {
        auto val = js.find(key);
        if (val != js.end()) {
            value = val->get<T>();
        } else if (required) {
            throw std::invalid_argument("Required Argument: " + key + " not set");
        }
    }

    template<typename T> void parse_req(T& value, const std::string key, const nlohmann::json &js)
    {
        parse_value(value, key, js, true);
    }

    template<typename T> void parse_opt(T& value, const std::string key, const nlohmann::json &js)
    {
        parse_value(value, key, js, false);
    }
};
<commit_msg>Add rawmedia type<commit_after>#pragma once
#include <memory>
#include <random>
#include <stdexcept>      // std::invalid_argument

#include "argtype.hpp"
#include "json.hpp"

namespace nervana {
    class decoded_media;
    class params;
    class json_config_parser;
}

typedef std::shared_ptr<nervana::decoded_media>        media_ptr;
typedef std::shared_ptr<nervana::json_config_parser>   config_ptr;
typedef std::shared_ptr<nervana::params>               param_ptr;

enum class MediaType {
    UNKNOWN = -1,
    IMAGE = 0,
    VIDEO = 1,
    AUDIO = 2,
    TEXT = 3,
    TARGET = 4,
    RAW = 5,
};

/*  ABSTRACT INTERFACES */
class nervana::decoded_media {
public:
    virtual ~decoded_media() {}
    virtual MediaType get_type() = 0;
};

/*  ABSTRACT INTERFACES */
class nervana::params {
public:
    virtual ~params() {}
};

class nervana::json_config_parser {
public:
    template<typename T> void parse_dist(T& value, const std::string key, const nlohmann::json &js)
    {
        auto val = js.find(key);
        if (val != js.end()) {
            auto params = val->get<std::vector<typename T::result_type>>();
            set_dist_params(value, params);
        }
    }

    template<typename T, typename S> inline void set_dist_params(T& dist, S& params)
    {
        dist = T{params[0], params[1]};
    }

    // Specialization for a bernoulli coin flipping random var
    inline void set_dist_params(std::bernoulli_distribution& dist, std::vector<bool>& params)
    {
        dist = std::bernoulli_distribution{params[0] ? 0.5 : 0.0};
    }

    template<typename T> void parse_value(
                                    T& value,
                                    const std::string key,
                                    const nlohmann::json &js,
                                    bool required=false )
    {
        auto val = js.find(key);
        if (val != js.end()) {
            value = val->get<T>();
        } else if (required) {
            throw std::invalid_argument("Required Argument: " + key + " not set");
        }
    }

    template<typename T> void parse_req(T& value, const std::string key, const nlohmann::json &js)
    {
        parse_value(value, key, js, true);
    }

    template<typename T> void parse_opt(T& value, const std::string key, const nlohmann::json &js)
    {
        parse_value(value, key, js, false);
    }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2020-2022 F4PGA Authors
 *
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 */

#include "UhdmAst.h"
#include "frontends/ast/ast.h"
#include "kernel/yosys.h"
#include "uhdmcommonfrontend.h"

#if defined(_MSC_VER)
#include <direct.h>
#include <process.h>
#else
#include <sys/param.h>
#include <unistd.h>
#endif

#include "Surelog/ErrorReporting/Report.h"
#include "Surelog/surelog.h"

namespace UHDM
{
extern void visit_object(vpiHandle obj_h, int indent, const char *relation, std::set<const BaseClass *> *visited, std::ostream &out,
                         bool shallowVisit = false);
}

YOSYS_NAMESPACE_BEGIN

std::vector<vpiHandle> executeCompilation(SURELOG::SymbolTable *symbolTable, SURELOG::ErrorContainer *errors, SURELOG::CommandLineParser *clp,
                                          SURELOG::scompiler *compiler)
{
    bool success = true;
    bool noFatalErrors = true;
    unsigned int codedReturn = 0;
    clp->setWriteUhdm(false);
    errors->printMessages(clp->muteStdout());
    std::vector<vpiHandle> the_design;
    if (success && (!clp->help())) {
        compiler = SURELOG::start_compiler(clp);
        if (!compiler)
            codedReturn |= 1;
        the_design.push_back(SURELOG::get_uhdm_design(compiler));
    }
    SURELOG::ErrorContainer::Stats stats;
    if (!clp->help()) {
        stats = errors->getErrorStats();
        if (stats.nbFatal)
            codedReturn |= 1;
        if (stats.nbSyntax)
            codedReturn |= 2;
    }
    bool noFErrors = true;
    if (!clp->help())
        noFErrors = errors->printStats(stats, clp->muteStdout());
    if (noFErrors == false) {
        noFatalErrors = false;
    }
    if ((!noFatalErrors) || (!success) || (errors->getErrorStats().nbError))
        codedReturn |= 1;
    if (codedReturn) {
        log_error("Error when parsing design. Aborting!\n");
    }
    return the_design;
}

struct UhdmSurelogAstFrontend : public UhdmCommonFrontend {
    UhdmSurelogAstFrontend(std::string name, std::string short_help) : UhdmCommonFrontend(name, short_help) {}
    UhdmSurelogAstFrontend() : UhdmCommonFrontend("verilog_with_uhdm", "generate/read UHDM file") {}
    void help() override
    {
        //   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
        log("\n");
        log("    read_verilog_with_uhdm [options] [filenames]\n");
        log("\n");
        log("Read SystemVerilog files using Surelog into the current design\n");
        log("\n");
        this->print_read_options();
    }
    AST::AstNode *parse(std::string filename) override
    {
        std::vector<const char *> cstrings;
        cstrings.reserve(this->args.size());
        for (size_t i = 0; i < this->args.size(); ++i)
            cstrings.push_back(const_cast<char *>(this->args[i].c_str()));

        SURELOG::SymbolTable *symbolTable = new SURELOG::SymbolTable();
        SURELOG::ErrorContainer *errors = new SURELOG::ErrorContainer(symbolTable);
        SURELOG::CommandLineParser *clp = new SURELOG::CommandLineParser(errors, symbolTable, false, false);
        bool success = clp->parseCommandLine(cstrings.size(), &cstrings[0]);
        if (!success) {
            log_error("Error parsing Surelog arguments!\n");
        }
        // Force -parse flag settings even if it wasn't specified
        clp->setwritePpOutput(true);
        clp->setParse(true);
        clp->setCompile(true);
        clp->setElaborate(true);

        SURELOG::scompiler *compiler = nullptr;
        const std::vector<vpiHandle> uhdm_design = executeCompilation(symbolTable, errors, clp, compiler);
        if (this->shared.debug_flag || !this->report_directory.empty()) {
            for (auto design : uhdm_design) {
                std::stringstream strstr;
                UHDM::visit_object(design, 1, "", &this->shared.report.unhandled, this->shared.debug_flag ? std::cout : strstr);
            }
        }

        SURELOG::shutdown_compiler(compiler);
        delete clp;
        delete symbolTable;
        delete errors;
        // on parse_only mode, don't try to load design
        // into yosys
        if (this->shared.parse_only)
            return nullptr;

        UhdmAst uhdm_ast(this->shared);
        AST::AstNode *current_ast = uhdm_ast.visit_designs(uhdm_design);
        if (!this->report_directory.empty()) {
            this->shared.report.write(this->report_directory);
        }

        return current_ast;
    }
    void call_log_header(RTLIL::Design *design) override { log_header(design, "Executing Verilog with UHDM frontend.\n"); }
} UhdmSurelogAstFrontend;

struct UhdmSystemVerilogFrontend : public UhdmSurelogAstFrontend {
    UhdmSystemVerilogFrontend() : UhdmSurelogAstFrontend("systemverilog", "read SystemVerilog files") {}
    void help() override
    {
        //   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
        log("\n");
        log("    read_systemverilog [options] [filenames]\n");
        log("\n");
        log("Read SystemVerilog files using Surelog into the current design\n");
        log("\n");
        this->print_read_options();
    }
} UhdmSystemVerilogFrontend;

YOSYS_NAMESPACE_END
<commit_msg>Use fullSVMode in Surelog<commit_after>/*
 * Copyright 2020-2022 F4PGA Authors
 *
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 */

#include "UhdmAst.h"
#include "frontends/ast/ast.h"
#include "kernel/yosys.h"
#include "uhdmcommonfrontend.h"

#if defined(_MSC_VER)
#include <direct.h>
#include <process.h>
#else
#include <sys/param.h>
#include <unistd.h>
#endif

#include "Surelog/ErrorReporting/Report.h"
#include "Surelog/surelog.h"

namespace UHDM
{
extern void visit_object(vpiHandle obj_h, int indent, const char *relation, std::set<const BaseClass *> *visited, std::ostream &out,
                         bool shallowVisit = false);
}

YOSYS_NAMESPACE_BEGIN

std::vector<vpiHandle> executeCompilation(SURELOG::SymbolTable *symbolTable, SURELOG::ErrorContainer *errors, SURELOG::CommandLineParser *clp,
                                          SURELOG::scompiler *compiler)
{
    bool success = true;
    bool noFatalErrors = true;
    unsigned int codedReturn = 0;
    clp->setWriteUhdm(false);
    errors->printMessages(clp->muteStdout());
    std::vector<vpiHandle> the_design;
    if (success && (!clp->help())) {
        compiler = SURELOG::start_compiler(clp);
        if (!compiler)
            codedReturn |= 1;
        the_design.push_back(SURELOG::get_uhdm_design(compiler));
    }
    SURELOG::ErrorContainer::Stats stats;
    if (!clp->help()) {
        stats = errors->getErrorStats();
        if (stats.nbFatal)
            codedReturn |= 1;
        if (stats.nbSyntax)
            codedReturn |= 2;
    }
    bool noFErrors = true;
    if (!clp->help())
        noFErrors = errors->printStats(stats, clp->muteStdout());
    if (noFErrors == false) {
        noFatalErrors = false;
    }
    if ((!noFatalErrors) || (!success) || (errors->getErrorStats().nbError))
        codedReturn |= 1;
    if (codedReturn) {
        log_error("Error when parsing design. Aborting!\n");
    }
    return the_design;
}

struct UhdmSurelogAstFrontend : public UhdmCommonFrontend {
    UhdmSurelogAstFrontend(std::string name, std::string short_help) : UhdmCommonFrontend(name, short_help) {}
    UhdmSurelogAstFrontend() : UhdmCommonFrontend("verilog_with_uhdm", "generate/read UHDM file") {}
    void help() override
    {
        //   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
        log("\n");
        log("    read_verilog_with_uhdm [options] [filenames]\n");
        log("\n");
        log("Read SystemVerilog files using Surelog into the current design\n");
        log("\n");
        this->print_read_options();
    }
    AST::AstNode *parse(std::string filename) override
    {
        std::vector<const char *> cstrings;
        cstrings.reserve(this->args.size());
        for (size_t i = 0; i < this->args.size(); ++i)
            cstrings.push_back(const_cast<char *>(this->args[i].c_str()));

        SURELOG::SymbolTable *symbolTable = new SURELOG::SymbolTable();
        SURELOG::ErrorContainer *errors = new SURELOG::ErrorContainer(symbolTable);
        SURELOG::CommandLineParser *clp = new SURELOG::CommandLineParser(errors, symbolTable, false, false);
        bool success = clp->parseCommandLine(cstrings.size(), &cstrings[0]);
        if (!success) {
            log_error("Error parsing Surelog arguments!\n");
        }
        // Force -parse flag settings even if it wasn't specified
        clp->setwritePpOutput(true);
        clp->setParse(true);
        clp->setCompile(true);
        clp->setElaborate(true);
        clp->fullSVMode(true);

        SURELOG::scompiler *compiler = nullptr;
        const std::vector<vpiHandle> uhdm_design = executeCompilation(symbolTable, errors, clp, compiler);
        if (this->shared.debug_flag || !this->report_directory.empty()) {
            for (auto design : uhdm_design) {
                std::stringstream strstr;
                UHDM::visit_object(design, 1, "", &this->shared.report.unhandled, this->shared.debug_flag ? std::cout : strstr);
            }
        }

        SURELOG::shutdown_compiler(compiler);
        delete clp;
        delete symbolTable;
        delete errors;
        // on parse_only mode, don't try to load design
        // into yosys
        if (this->shared.parse_only)
            return nullptr;

        UhdmAst uhdm_ast(this->shared);
        AST::AstNode *current_ast = uhdm_ast.visit_designs(uhdm_design);
        if (!this->report_directory.empty()) {
            this->shared.report.write(this->report_directory);
        }

        return current_ast;
    }
    void call_log_header(RTLIL::Design *design) override { log_header(design, "Executing Verilog with UHDM frontend.\n"); }
} UhdmSurelogAstFrontend;

struct UhdmSystemVerilogFrontend : public UhdmSurelogAstFrontend {
    UhdmSystemVerilogFrontend() : UhdmSurelogAstFrontend("systemverilog", "read SystemVerilog files") {}
    void help() override
    {
        //   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
        log("\n");
        log("    read_systemverilog [options] [filenames]\n");
        log("\n");
        log("Read SystemVerilog files using Surelog into the current design\n");
        log("\n");
        this->print_read_options();
    }
} UhdmSystemVerilogFrontend;

YOSYS_NAMESPACE_END
<|endoftext|>


<commit_before>#include "stdafx.h"

using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;

//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("openalprnet")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("openalprnet")];
[assembly:AssemblyCopyrightAttribute("Copyright (c)  2015")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];

//
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:

[assembly: AssemblyVersionAttribute("2.1.0")]
[assembly: AssemblyFileVersionAttribute("2.1.0")]
[assembly: AssemblyInformationalVersionAttribute("2.1.0")]

[assembly:ComVisible(false)];

[assembly:CLSCompliantAttribute(true)];

[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
<commit_msg>Fix visual studio deprecation warning.<commit_after>#include "stdafx.h"

using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;

//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("openalprnet")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("openalprnet")];
[assembly:AssemblyCopyrightAttribute("Copyright (c)  2015")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];

//
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:

[assembly: AssemblyVersionAttribute("2.1.0")]
[assembly: AssemblyFileVersionAttribute("2.1.0")]
[assembly: AssemblyInformationalVersionAttribute("2.1.0")]

[assembly:ComVisible(false)];

[assembly:CLSCompliantAttribute(true)];
<|endoftext|>


<commit_before>#include "core/token_list.h"
namespace token_list{
    inline std::string to_string(const type t){
        switch(t)
        {
            case type::PAR    :   return "paranthese";
            case type::MAT    :   return "matrix";
            case type::OPER   :   return "operator";
            case type::FUNC   :   return "function";
            case type::STR    :   return "string";
            case type::VAL    :   return "value" ;
            case type::VAR    :   return "variable";
            default: return "";
        }

    }
    item::item(const type t,const size_t w,const size_t i,const size_t j) :
        t(t),start(i),end(j),prev(0),is_closing(false),weight(w) {}

    item::item(const type t,const size_t w,const size_t i, const size_t j, const size_t prev):
        t(t),start(i),end(j),prev(prev),is_closing(true),weight(w) {}

    item::operator std::string() const {
        if(!prev)
            return "{t: "+to_string(t) +",["+ std::to_string(start) +","+ std::to_string(end) +"],"+std::to_string(weight)+"}";
        else
            return "{t: "+to_string(t) +",["+ std::to_string(start) +","+ std::to_string(end) +"],"+std::to_string(weight)+",p="+ std::to_string(prev) +"}";
    }
}
<commit_msg>Remove usage of std::to_string<commit_after>#include "core/token_list.h"
#include <sstream>
namespace token_list{

    inline std::string to_string(const type t){
        switch(t)
        {
            case type::PAR    :   return "paranthese";
            case type::MAT    :   return "matrix";
            case type::OPER   :   return "operator";
            case type::FUNC   :   return "function";
            case type::STR    :   return "string";
            case type::VAL    :   return "value" ;
            case type::VAR    :   return "variable";
            default: return "";
        }

    }

    item::item(const type t,const size_t w,const size_t i,const size_t j) :
        t(t),start(i),end(j),prev(0),is_closing(false),weight(w) {}

    item::item(const type t,const size_t w,const size_t i, const size_t j, const size_t prev):
        t(t),start(i),end(j),prev(prev),is_closing(true),weight(w) {}

    item::operator std::string() const {
        std::stringstream s;
        if(!prev)
            s << "{t: "<<to_string(t) <<",["<< start <<","<< end <<"],"<<weight<<"}";
        else
            s << "{t: "<<to_string(t) <<",["<< start <<","<< end <<"],"<<weight<<",p="<< prev << "}";
        return s.str();
    }
}
<|endoftext|>


<commit_before>/// Implementation of devices_manager.hpp
///
/// (c) Koheron

#include "devices_manager.hpp"
#include "kserver.hpp"
#include "commands.hpp"

#if KSERVER_HAS_THREADS
#  include <thread>
#endif

namespace kserver {

DeviceManager::DeviceManager(KServer *kserver_)
: device_list(device_num)
,  kserver(kserver_)
#if KSERVER_HAS_DEVMEM
,  dev_mem(kserver_, kserver_->config->addr_limit_down, kserver_->config->addr_limit_up)
#endif
{
    device_list[KSERVER] = static_cast<KDeviceAbstract*>(kserver);
    is_started[KSERVER] = 1;
}

DeviceManager::~DeviceManager()
{
    Reset();
}

int DeviceManager::Init()
{
#if KSERVER_HAS_DEVMEM
    if (dev_mem.open() < 0) {
        kserver->syslog.print(SysLog::CRITICAL,
                              "Can't start DevMem\n");
        return -1;
    }
#endif

    return 0;
}

// X Macro: Start new device
#if KSERVER_HAS_DEVMEM
#define EXPAND_AS_START_DEVICE(num, name, operations ...)                 \
        case num:                                                         \
            device_list[num]                                              \
                = new name (static_cast<KServer*>(device_list[KSERVER]),  \
                            dev_mem);                                     \
            break;
#else
#define EXPAND_AS_START_DEVICE(num, name, operations ...)                 \
        case num:                                                         \
            device_list[num]                                              \
                = new name (static_cast<KServer*>(device_list[KSERVER])); \
            break;
#endif

int DeviceManager::StartDev(device_t dev)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    assert(dev < device_num);

    if (is_started[dev])
        return 0;

    if (dev == NO_DEVICE) {
        is_started[dev] = 1;
        return 0;
    }

    if (dev == KSERVER)
        if (!is_started[dev]) {
            kserver->syslog.print(SysLog::CRITICAL,
                                  "KServer must always be started !\n");
            return -1;
        }

    switch (dev) {
        // Automatic generation with X macro
        DEVICES_TABLE(EXPAND_AS_START_DEVICE)

      default:
        kserver->syslog.print(SysLog::CRITICAL, "Unknown device\n");
        return -1;
    }

    assert(device_list.at(dev) != NULL);

    if (IsFailed(dev)) {
        kserver->syslog.print(SysLog::CRITICAL, "Failed to start %s\n",
                              GET_DEVICE_NAME(dev).c_str() );
        return -1;
    }

    is_started[dev] = 1;

    return 0;
}

// X Macro: Execute device
#define EXPAND_AS_EXECUTE_DEVICE(num, name, operations ...)         \
        case num: {                                                 \
            KDevice<name, num>                                      \
                *dev = static_cast<KDevice<name, num> *>(dev_abs);  \
            error = dev->execute(cmd);                              \
            break;                                                  \
        }

int DeviceManager::Execute(const Command& cmd)
{
    if (!is_started[cmd.device])
        if (StartDev(cmd.device) < 0)
            return -1;

    if (cmd.device == 0)
        return 0;

    assert(cmd.device < device_num);
    KDeviceAbstract *dev_abs = device_list[cmd.device];

    int error = 0;

    switch (dev_abs->kind) {
      case NO_DEVICE:
        return 0;
        break;
      case KSERVER: {
        KDevice<KServer, KSERVER>
           *dev = static_cast<KDevice<KServer, KSERVER> *>(dev_abs);
        error = dev->execute(cmd);
        break;
      }

      DEVICES_TABLE(EXPAND_AS_EXECUTE_DEVICE) // X-Macro

      case device_num:
      default:
        kserver->syslog.print(SysLog::CRITICAL, "Execute: Unknown device\n");
        return -1;
    }

    return error;
}

bool DeviceManager::IsStarted(device_t dev) const
{
    assert(dev < device_num);
    return is_started[(unsigned int) (dev)];
}

void DeviceManager::SetDevStarted(device_t dev)
{
    assert(dev < device_num);
    is_started[(unsigned int) (dev)] = 1;
}

bool DeviceManager::IsFailed(device_t dev)
{
    // NO_DEVICE never fail
    if (dev == NO_DEVICE)
        return 0;

    assert(dev < device_num);
    assert(device_list.at(dev) != 0);

    return device_list.at(dev)->is_failed();
}

// X Macro: Stop device
#define EXPAND_AS_STOP_DEVICE(num, name, operations ...)       \
        case num: {                                            \
            if (is_started[num]) {                             \
                delete static_cast< name *>(device_list[num]); \
                is_started[num] = 0;                           \
            }                                                  \
            break;                                             \
        }

void DeviceManager::StopDev(device_t dev)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    assert(dev < device_num);

    // A direct call to delete as:
    // delete device_list[dev];
    // doesn't call the specific destructor of each class
    // since device_list contains pointers of KDeviceAbstract.
    // Therefore, we cast to the appropriate KDevice before
    // deleting:
    // delete ( dev_name *) device_list[dev];
    switch (dev) {
      // Automatic generation with X macro
      DEVICES_TABLE(EXPAND_AS_STOP_DEVICE)

      default:
        kserver->syslog.print(SysLog::CRITICAL, "Unknown device\n");
    }
}

void DeviceManager::Reset(void)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    // KServer is never reseted
    for (unsigned int i=2; i<device_num; i++)
        StopDev((device_t)i);
}

int DeviceManager::StartAll(void)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    int ret = 0;

    // Maybe not the most efficient implementation
    // But not a speed critical function
    for (unsigned int i=0; i<device_num; i++)
        if (StartDev((device_t)i) < 0)
            ret = -1;

    return ret;
}

KS_device_status DeviceManager::GetStatus(device_t dev)
{
    // NO_DEVICE and KSERVER are always on
    // and never fail
    if (dev==0 || dev==1)
        return DEV_ON;

    assert(dev < device_num);

    if (!is_started[dev])
        return DEV_OFF;

    if (IsFailed(dev))
        return DEV_FAIL;
    else
        return DEV_ON;
}

} // namespace kserver
<commit_msg>Remove memory limits (#125)<commit_after>/// Implementation of devices_manager.hpp
///
/// (c) Koheron

#include "devices_manager.hpp"
#include "kserver.hpp"
#include "commands.hpp"

#if KSERVER_HAS_THREADS
#  include <thread>
#endif

namespace kserver {

DeviceManager::DeviceManager(KServer *kserver_)
: device_list(device_num)
,  kserver(kserver_)
#if KSERVER_HAS_DEVMEM
,  dev_mem(kserver_)
#endif
{
    device_list[KSERVER] = static_cast<KDeviceAbstract*>(kserver);
    is_started[KSERVER] = 1;
}

DeviceManager::~DeviceManager()
{
    Reset();
}

int DeviceManager::Init()
{
#if KSERVER_HAS_DEVMEM
    if (dev_mem.open() < 0) {
        kserver->syslog.print(SysLog::CRITICAL,
                              "Can't start DevMem\n");
        return -1;
    }
#endif

    return 0;
}

// X Macro: Start new device
#if KSERVER_HAS_DEVMEM
#define EXPAND_AS_START_DEVICE(num, name, operations ...)                 \
        case num:                                                         \
            device_list[num]                                              \
                = new name (static_cast<KServer*>(device_list[KSERVER]),  \
                            dev_mem);                                     \
            break;
#else
#define EXPAND_AS_START_DEVICE(num, name, operations ...)                 \
        case num:                                                         \
            device_list[num]                                              \
                = new name (static_cast<KServer*>(device_list[KSERVER])); \
            break;
#endif

int DeviceManager::StartDev(device_t dev)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    assert(dev < device_num);

    if (is_started[dev])
        return 0;

    if (dev == NO_DEVICE) {
        is_started[dev] = 1;
        return 0;
    }

    if (dev == KSERVER)
        if (!is_started[dev]) {
            kserver->syslog.print(SysLog::CRITICAL,
                                  "KServer must always be started !\n");
            return -1;
        }

    switch (dev) {
        // Automatic generation with X macro
        DEVICES_TABLE(EXPAND_AS_START_DEVICE)

      default:
        kserver->syslog.print(SysLog::CRITICAL, "Unknown device\n");
        return -1;
    }

    assert(device_list.at(dev) != NULL);

    if (IsFailed(dev)) {
        kserver->syslog.print(SysLog::CRITICAL, "Failed to start %s\n",
                              GET_DEVICE_NAME(dev).c_str() );
        return -1;
    }

    is_started[dev] = 1;

    return 0;
}

// X Macro: Execute device
#define EXPAND_AS_EXECUTE_DEVICE(num, name, operations ...)         \
        case num: {                                                 \
            KDevice<name, num>                                      \
                *dev = static_cast<KDevice<name, num> *>(dev_abs);  \
            error = dev->execute(cmd);                              \
            break;                                                  \
        }

int DeviceManager::Execute(const Command& cmd)
{
    if (!is_started[cmd.device])
        if (StartDev(cmd.device) < 0)
            return -1;

    if (cmd.device == 0)
        return 0;

    assert(cmd.device < device_num);
    KDeviceAbstract *dev_abs = device_list[cmd.device];

    int error = 0;

    switch (dev_abs->kind) {
      case NO_DEVICE:
        return 0;
        break;
      case KSERVER: {
        KDevice<KServer, KSERVER>
           *dev = static_cast<KDevice<KServer, KSERVER> *>(dev_abs);
        error = dev->execute(cmd);
        break;
      }

      DEVICES_TABLE(EXPAND_AS_EXECUTE_DEVICE) // X-Macro

      case device_num:
      default:
        kserver->syslog.print(SysLog::CRITICAL, "Execute: Unknown device\n");
        return -1;
    }

    return error;
}

bool DeviceManager::IsStarted(device_t dev) const
{
    assert(dev < device_num);
    return is_started[(unsigned int) (dev)];
}

void DeviceManager::SetDevStarted(device_t dev)
{
    assert(dev < device_num);
    is_started[(unsigned int) (dev)] = 1;
}

bool DeviceManager::IsFailed(device_t dev)
{
    // NO_DEVICE never fail
    if (dev == NO_DEVICE)
        return 0;

    assert(dev < device_num);
    assert(device_list.at(dev) != 0);

    return device_list.at(dev)->is_failed();
}

// X Macro: Stop device
#define EXPAND_AS_STOP_DEVICE(num, name, operations ...)       \
        case num: {                                            \
            if (is_started[num]) {                             \
                delete static_cast< name *>(device_list[num]); \
                is_started[num] = 0;                           \
            }                                                  \
            break;                                             \
        }

void DeviceManager::StopDev(device_t dev)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    assert(dev < device_num);

    // A direct call to delete as:
    // delete device_list[dev];
    // doesn't call the specific destructor of each class
    // since device_list contains pointers of KDeviceAbstract.
    // Therefore, we cast to the appropriate KDevice before
    // deleting:
    // delete ( dev_name *) device_list[dev];
    switch (dev) {
      // Automatic generation with X macro
      DEVICES_TABLE(EXPAND_AS_STOP_DEVICE)

      default:
        kserver->syslog.print(SysLog::CRITICAL, "Unknown device\n");
    }
}

void DeviceManager::Reset(void)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    // KServer is never reseted
    for (unsigned int i=2; i<device_num; i++)
        StopDev((device_t)i);
}

int DeviceManager::StartAll(void)
{
#if KSERVER_HAS_THREADS
    std::lock_guard<std::mutex> lock(mutex);
#endif

    int ret = 0;

    // Maybe not the most efficient implementation
    // But not a speed critical function
    for (unsigned int i=0; i<device_num; i++)
        if (StartDev((device_t)i) < 0)
            ret = -1;

    return ret;
}

KS_device_status DeviceManager::GetStatus(device_t dev)
{
    // NO_DEVICE and KSERVER are always on
    // and never fail
    if (dev==0 || dev==1)
        return DEV_ON;

    assert(dev < device_num);

    if (!is_started[dev])
        return DEV_OFF;

    if (IsFailed(dev))
        return DEV_FAIL;
    else
        return DEV_ON;
}

} // namespace kserver
<|endoftext|>