<commit_before>#include "Halide.h"

#include <utility>
// #include <cstdio>

using namespace Halide;

struct Complex {
  Expr real, imag;
  Complex(Tuple t) : real(t[0]), imag(t[1]) {}
  Complex(Expr r, Expr i) : real(r), imag(i) {}
  Complex(FuncRefExpr t) : Complex(Tuple(t)) {}
  Complex(FuncRefVar t) : Complex(Tuple(t)) {}
  operator Tuple() const {
    return{ real, imag };
  }
  Complex operator+(const Complex &other) const {
    return{ real + other.real, imag + other.imag };
  }
  Complex operator*(const Complex &other) const {
    return{ real * other.real - imag * other.imag,
      real * other.imag + imag * other.real };
  }
};

// "Optimization".
inline void updif(const Expr & cond, FuncRefExpr fref, const Complex &cplx) {
  Complex added = Complex(fref) + cplx;
  fref = Complex(
             select(cond, added.real, Complex(fref).real)
           , select(cond, added.imag, Complex(fref).imag)
           );
}

#define P(a) a(#a)
#define IP(a,b,c) a(b,c,#a)

int main(/* int argc, char **argv */) {
  int over = 8;

  Param<double>
      P(scale)
    , P(wstep)
    ;
  Param<int>
      P(num_of_baselines)
    // , P(max_supp_here)
    , P(ts_ch)
    , P(grid_pitch)
    , P(grid_size)
    ;
  ImageParam IP(supports, type_of<int>(), 1);
  ImageParam IP(gcf_supps, type_of<int>(), 1);
  ImageParam IP(uvwf, type_of<double>(), 3);
  ImageParam IP(vis, type_of<double>(), 3);
  ImageParam IP(gcfoff, type_of<int>(), 1);

  // We don't make additional complex dimension ATM
  // because we will need all 4 available dimensions
  // to address GCF if we stick to one-GCF-layer-per-baseline
  // approach.
  // Interleaved.
  ImageParam
      IP(gcfr, type_of<double>(), 1)
    , IP(gcfi, type_of<double>(), 1)
    ;
  Func
      P(uvs)
    , P(uv)
    , P(w)
    , P(overc)
    ;

  Var P(t), P(uvdim), P(bl);
  uvs(uvdim,t,bl) = uvwf(uvdim,t,bl) * scale;
  overc(uvdim,t,bl) = cast(Int(16), over * (uvs(uvdim,t,bl) - floor(uvs(uvdim,t,bl))));
  uv(uvdim,t,bl) = cast(Int(16), uvs(uvdim,t,bl) + cast(Int(16), grid_size / 2 - supports(bl) / 2));
  w(t,bl) = cast(Int(16), uvwf(2,t,bl) / wstep);

  // If we compute_root them.
  // uvs.bound(uvdim, 0, 2);
  // overc.bound(uvdim, 0, 2);
  // uv.bound(uvdim, 0, 2);

  // UV-Grid - initially 0
  Func P(uvg); Var P(x), P(y);
  uvg(x, y) = Complex(cast<double>(0.0f), cast<double>(0.0f));

  // Grid visibilities. This is a reduction over:
  // 0. All baselines
  // 1. All visibilities
  // 2. All GCF coordinates (X,Y)
  // Provisional limit only to experiment with things
  #define TMP_LIM 256
  RDom red(
      0, num_of_baselines
    , 0, TMP_LIM
    , 0, ts_ch
    , 0, TMP_LIM
    );

  RVar
      rbl   = red.x
    , rgcfx = red.y
    , rvis  = red.z
    , rgcfy = red.w
    ;

  Param<int> P(gcf_data_size);
  // No layer correction yet
  Expr off = clamp (gcfoff(w(rvis,rbl)) + overc(0,rvis,rbl) * gcf_supps(w(rvis,rbl)) + overc(1,rvis,rbl), 0, gcf_data_size-1);
  // Do the complex arithmetic to update the grid
  Complex visC(
      vis(0,rvis,rbl)
    , vis(1,rvis,rbl)
    );
  Complex gcfC(
      gcfr(off)
    , gcfi(off)
    );
  updif(rgcfx < supports(rbl) && rgcfy < supports(rbl)
    , uvg(
      clamp(uv(0,rvis,rbl) + rgcfx, 0, grid_pitch - 1)
    , clamp(uv(1,rvis,rbl) + rgcfy, 0, grid_size - 1))
    , visC * gcfC
    );

  uvg.bound(x, 0, grid_size);
  uvg.bound(y, 0, grid_pitch);

  // Temp. disable. It wants constants only.
  // uvg.vectorize(x);

  Func P(uvgsh_full);
  Var P(gu), P(gv);
  uvg.compute_root();
  uvgsh_full(gu, gv) = uvg(gu, gv);
  uvgsh_full.output_buffers()[0].set_stride(0, Expr());
  uvgsh_full.output_buffers()[1].set_stride(0, Expr());

  std::vector<Halide::Argument> compile_args = {
       scale
     , wstep
     , num_of_baselines
     , supports
     , ts_ch
     , grid_pitch
     , grid_size
     , gcf_supps
     , uvwf
     , vis
     , gcf_data_size
     , gcfoff
     , gcfr, gcfi
     };
  // uvg.compile_to_lowered_stmt("uvg.html", compile_args, HTML);
  uvgsh_full.compile_to_lowered_stmt("uvg_full.html", compile_args, HTML);

  Target target(
      // Target::Windows
      Target::Linux
    , Target::X86, 64
    , { Target::SSE41
      , Target::AVX
      }
    );
  uvgsh_full.compile_to_file("uvgsh_full", compile_args, target);
}
<commit_msg>Cleanup and reorganize.<commit_after>#include "Halide.h"

#include <utility>
#include <vector>

using namespace Halide;

struct Complex {
  Expr real, imag;
  Complex(Tuple t) : real(t[0]), imag(t[1]) {}
  Complex(Expr r, Expr i) : real(r), imag(i) {}
  Complex(FuncRefExpr t) : Complex(Tuple(t)) {}
  operator Tuple() const {
    return{ real, imag };
  }
  Complex operator+(const Complex &other) const {
    return{ real + other.real, imag + other.imag };
  }
  Complex operator*(const Complex &other) const {
    return{ real * other.real - imag * other.imag,
      real * other.imag + imag * other.real };
  }
};

inline Complex select(Expr condition, Complex true_value, Complex false_value) {
  return Complex(
      select(condition, true_value.real, false_value.real)
    , select(condition, true_value.imag, false_value.imag)
    );
}

inline Func flushAndContinue(const char * new_name, Func & f) {
  Func ret(new_name);
  f.compute_root();
  ret(f.args()) = f(f.args());
  return ret;
}

#define P(a) a(#a)
#define IP(a,b,c) a(b,c,#a)

int main(/* int argc, char **argv */) {
  int over = 8;

  Param<double>
      P(scale)
    , P(wstep)
    ;
  Param<int>
      P(num_of_baselines)
    // , P(max_supp_here)
    , P(ts_ch)
    , P(grid_pitch)
    , P(grid_size)
    ;
  ImageParam IP(supports, type_of<int>(), 1);
  ImageParam IP(gcf_supps, type_of<int>(), 1);
  ImageParam IP(uvwf, type_of<double>(), 3);
  ImageParam IP(vis, type_of<double>(), 3);
  ImageParam IP(gcfoff, type_of<int>(), 1);

  // We don't make additional complex dimension ATM
  // because we will need all 4 available dimensions
  // to address GCF if we stick to one-GCF-layer-per-baseline
  // approach.
  // Interleaved.
  ImageParam
      IP(gcfr, type_of<double>(), 1)
    , IP(gcfi, type_of<double>(), 1)
    ;
  Func
      P(uvs)
    , P(uv)
    , P(w)
    , P(overc)
    ;

  Var P(t), P(uvdim), P(bl);
  uvs(uvdim, t, bl) = uvwf(uvdim, t, bl) * scale;
  overc(uvdim, t, bl) = cast(Int(16), over * (uvs(uvdim, t, bl) - floor(uvs(uvdim, t, bl))));
  uv(uvdim, t, bl) = cast(Int(16), uvs(uvdim, t, bl) + cast(Int(16), grid_size / 2 - supports(bl) / 2));
  w(t, bl) = cast(Int(16), uvwf(2, t, bl) / wstep);

  // If we compute_root them.
  // uvs.bound(uvdim, 0, 2);
  // overc.bound(uvdim, 0, 2);
  // uv.bound(uvdim, 0, 2);

  // UV-Grid - initially 0
  Func P(uvg); Var P(x), P(y);
  uvg(x, y) = Complex(cast<double>(0.0f), cast<double>(0.0f));

  // Grid visibilities. This is a reduction over:
  // 0. All baselines
  // 1. All visibilities
  // 2. All GCF coordinates (X,Y)
  // Provisional limit only to experiment with things
#define TMP_LIM 256
  RDom red(
      0, num_of_baselines
    , 0, TMP_LIM
    , 0, ts_ch
    , 0, TMP_LIM
    );

  RVar
      rbl   = red.x
    , rgcfx = red.y
    , rvis  = red.z
    , rgcfy = red.w
    ;

  Param<int> P(gcf_data_size);
  // No layer correction yet
  Expr off = clamp(gcfoff(w(rvis, rbl)) + overc(0, rvis, rbl) * gcf_supps(w(rvis, rbl)) + overc(1, rvis, rbl), 0, gcf_data_size - 1);
  // Do the complex arithmetic to update the grid
  Complex visC(
      vis(0, rvis, rbl)
    , vis(1, rvis, rbl)
    );
  Complex gcfC(
      gcfr(off)
    , gcfi(off)
    );

  FuncRefExpr uvRef = uvg(
      clamp(uv(0, rvis, rbl) + rgcfx, 0, grid_pitch - 1)
    , clamp(uv(1, rvis, rbl) + rgcfy, 0, grid_size - 1)
    );

  // Convolve
  uvRef = select(rgcfx < supports(rbl) && rgcfy < supports(rbl), Complex(uvRef) + visC * gcfC, uvRef);

  uvg.bound(x, 0, grid_size);
  uvg.bound(y, 0, grid_pitch);

  // Temp. disable. It wants constants only.
  // uvg.vectorize(x);

  Func uvgsh_full = flushAndContinue("uvgsh_full", uvg);
  uvgsh_full.output_buffers()[0].set_stride(0, Expr());
  uvgsh_full.output_buffers()[1].set_stride(0, Expr());

  std::vector<Halide::Argument> compile_args = {
      scale
    , wstep
    , num_of_baselines
    , supports
    , ts_ch
    , grid_pitch
    , grid_size
    , gcf_supps
    , uvwf
    , vis
    , gcf_data_size
    , gcfoff
    , gcfr, gcfi
    };
  // uvg.compile_to_lowered_stmt("uvg.html", compile_args, HTML);
  uvgsh_full.compile_to_lowered_stmt("uvg_full.html", compile_args, HTML);

  Target target(
      // Target::Windows
      Target::Linux
    , Target::X86, 64
    , { Target::SSE41
      , Target::AVX
      }
    );
  uvgsh_full.compile_to_file("uvgsh_full", compile_args, target);
}
<|endoftext|>


<commit_before>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTypeface.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "Sk1DPathEffect.h"
#include "SkCornerPathEffect.h"
#include "SkPathMeasure.h"
#include "SkRandom.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkDither.h"

static const struct {
    const char* fName;
    SkTypeface::Style   fStyle;
} gFaces[] = {
    { NULL, SkTypeface::kNormal },
    { NULL, SkTypeface::kBold },
    { "serif", SkTypeface::kNormal },
    { "serif", SkTypeface::kBold },
    { "serif", SkTypeface::kItalic },
    { "serif", SkTypeface::kBoldItalic },
    { "monospace", SkTypeface::kNormal }
};

static const int gFaceCount = SK_ARRAY_COUNT(gFaces);

class FontScalerTestView : public SampleView {
    SkTypeface* fFaces[gFaceCount];

public:
	FontScalerTestView() {
        for (int i = 0; i < gFaceCount; i++) {
            fFaces[i] = SkTypeface::CreateFromName(gFaces[i].fName,
                                                   gFaces[i].fStyle);
        }
        this->setBGColor(0xFFDDDDDD);
    }

    virtual ~FontScalerTestView() {
        for (int i = 0; i < gFaceCount; i++) {
            SkSafeUnref(fFaces[i]);
        }
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "FontScaler Test");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        SkPaint paint;

        // test handling of obscene cubic values (currently broken)
        if (false) {
            SkPoint pts[4];
            pts[0].set(1.61061274e+09f, 6291456);
            pts[1].set(-7.18397061e+15f, -1.53091184e+13f);
            pts[2].set(-1.30077315e+16f, -2.77196141e+13f);
            pts[3].set(-1.30077315e+16f, -2.77196162e+13f);

            SkPath path;
            path.moveTo(pts[0]);
            path.cubicTo(pts[1], pts[2], pts[3]);
            canvas->drawPath(path, paint);
        }

        canvas->translate(200, 20);
        canvas->rotate(30);

        paint.setAntiAlias(true);
        paint.setLCDRenderText(true);
        SkSafeUnref(paint.setTypeface(SkTypeface::CreateFromName("Times Roman", SkTypeface::kNormal)));

//        const char* text = "abcdefghijklmnopqrstuvwxyz";
        const char* text = "HnHnHnHnHnHnHnHnH";
        size_t textLen = strlen(text);

        SkScalar x = SkIntToScalar(10);
        SkScalar y = SkIntToScalar(20);

        {
            SkPaint p;
            p.setColor(SK_ColorRED);
            SkRect r;
            r.set(0, 0, x, y*20);
            canvas->drawRect(r, p);
        }

        int index = 0;
        for (int ps = 9; ps <= 24; ps++) {
            textLen = strlen(text);
            paint.setTextSize(SkIntToScalar(ps));
            canvas->drawText(text, textLen, x, y, paint);
            y += paint.getFontMetrics(NULL);
            index += 1;
        }
    }

private:
    typedef SkView INHERITED;
};

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

static SkView* MyFactory() { return new FontScalerTestView; }
static SkViewRegister reg(MyFactory);

<commit_msg>add more angles, and test lineartext<commit_after>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTypeface.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "Sk1DPathEffect.h"
#include "SkCornerPathEffect.h"
#include "SkPathMeasure.h"
#include "SkRandom.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkDither.h"

static const struct {
    const char* fName;
    SkTypeface::Style   fStyle;
} gFaces[] = {
    { NULL, SkTypeface::kNormal },
    { NULL, SkTypeface::kBold },
    { "serif", SkTypeface::kNormal },
    { "serif", SkTypeface::kBold },
    { "serif", SkTypeface::kItalic },
    { "serif", SkTypeface::kBoldItalic },
    { "monospace", SkTypeface::kNormal }
};

static const int gFaceCount = SK_ARRAY_COUNT(gFaces);

class FontScalerTestView : public SampleView {
    SkTypeface* fFaces[gFaceCount];

public:
	FontScalerTestView() {
        for (int i = 0; i < gFaceCount; i++) {
            fFaces[i] = SkTypeface::CreateFromName(gFaces[i].fName,
                                                   gFaces[i].fStyle);
        }
        this->setBGColor(0xFFDDDDDD);
    }

    virtual ~FontScalerTestView() {
        for (int i = 0; i < gFaceCount; i++) {
            SkSafeUnref(fFaces[i]);
        }
    }

protected:
    // overrides from SkEventSink
    virtual bool onQuery(SkEvent* evt) {
        if (SampleCode::TitleQ(*evt)) {
            SampleCode::TitleR(evt, "FontScaler Test");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    static void rotate_about(SkCanvas* canvas, SkScalar degrees, SkScalar px, SkScalar py) {
        canvas->translate(px, py);
        canvas->rotate(degrees);
        canvas->translate(-px, -py);
    }

    virtual void onDrawContent(SkCanvas* canvas) {
        SkPaint paint;

        // test handling of obscene cubic values (currently broken)
        if (false) {
            SkPoint pts[4];
            pts[0].set(1.61061274e+09f, 6291456);
            pts[1].set(-7.18397061e+15f, -1.53091184e+13f);
            pts[2].set(-1.30077315e+16f, -2.77196141e+13f);
            pts[3].set(-1.30077315e+16f, -2.77196162e+13f);

            SkPath path;
            path.moveTo(pts[0]);
            path.cubicTo(pts[1], pts[2], pts[3]);
            canvas->drawPath(path, paint);
        }

        paint.setAntiAlias(true);
        paint.setLCDRenderText(true);
        SkSafeUnref(paint.setTypeface(SkTypeface::CreateFromName("Times Roman", SkTypeface::kNormal)));

//        const char* text = "abcdefghijklmnopqrstuvwxyz";
        const char* text = "HnHnHnHnHnHnHnH";
        const size_t textLen = strlen(text);

        for (int j = 0; j < 2; ++j) {
            for (int i = 0; i < 6; ++i) {
                SkScalar x = SkIntToScalar(10);
                SkScalar y = SkIntToScalar(20);

                SkAutoCanvasRestore acr(canvas, true);
                canvas->translate(50 + i * 230, 20);
                rotate_about(canvas, i * 7, x, y * 10);

                {
                    SkPaint p;
                    p.setAntiAlias(true);
                    SkRect r;
                    r.set(x-3, 15, x-1, 280);
                    canvas->drawRect(r, p);
                }

                int index = 0;
                for (int ps = 9; ps <= 24; ps++) {
                    paint.setTextSize(SkIntToScalar(ps));
                    canvas->drawText(text, textLen, x, y, paint);
                    y += paint.getFontMetrics(NULL);
                    index += 1;
                }
            }
            canvas->translate(0, 400);
            paint.setLinearText(true);
        }
    }

private:
    typedef SkView INHERITED;
};

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

static SkView* MyFactory() { return new FontScalerTestView; }
static SkViewRegister reg(MyFactory);

<|endoftext|>


<commit_before>#define PUT(x) std::cout << #x "=" << (x) << std::endl
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <time.h>
#include <mcl/fp.hpp>
#include <mcl/fp_tower.hpp>

typedef mcl::FpT<mcl::FpTag, 256> Fp;
typedef mcl::Fp2T<Fp> Fp2;
typedef mcl::FpDblT<Fp> FpDbl;

void testFp2()
{
	puts(__FUNCTION__);
	const int xi_c = 9;
	Fp2::init(xi_c);
	Fp2 x, y, z;
	x.a = 1;
	x.b = 2;
	y.a = 3;
	y.b = 4;
	/*
		x = 1 + 2u
		y = 3 + 4u
	*/
	Fp2::add(z, x, y);
	CYBOZU_TEST_EQUAL(z, Fp2(4, 6));
	Fp2::sub(z, x, y);
	CYBOZU_TEST_EQUAL(z, Fp2(-2, -2));
	Fp2::mul(z, x, y);
	/*
		(1 + 2u)(3 + 4u) = (3 - 8) + (4 + 6)u = -5 + 10u
	*/
	CYBOZU_TEST_EQUAL(z, Fp2(-5, 10));
	Fp2::neg(z, z);
	CYBOZU_TEST_EQUAL(z, Fp2(5, -10));
	/*
		xi = 9 + u
		(1 - 2u)(9 + u) = (9 + 2) + (1 - 18)u = 11 - 17u
	*/
	z = Fp2(1, -2);
	Fp2::mul_xi(z, z);
	CYBOZU_TEST_EQUAL(z, Fp2(11, -17));
	z = x * x;
	Fp2::sqr(y, x);
	CYBOZU_TEST_EQUAL(z, y);
	x.a = -123456789;
	x.b = 464652165165;
	y = x * x;
	Fp2::sqr(x, x);
	CYBOZU_TEST_EQUAL(x, y);
	{
		std::ostringstream oss;
		oss << x;
		std::istringstream iss(oss.str());
		Fp2 w;
		iss >> w;
		CYBOZU_TEST_EQUAL(x, w);
	}
	y = x;
	Fp2::inv(y, x);
	y *= x;
	CYBOZU_TEST_EQUAL(y, 1);
}

void testFpDbl()
{
	puts(__FUNCTION__);
	{
		std::string pstr;
		Fp::getModulo(pstr);
		mpz_class mp(pstr);
		mp <<= Fp::getUnitSize() * mcl::fp::UnitBitSize;
		mpz_class mp1 = mp - 1;
		mcl::Gmp::getStr(pstr, mp1);
		const char *tbl[] = {
			"0", "1", "123456", "123456789012345668909", pstr.c_str(),
		};
		for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
			mpz_class mx(tbl[i]), my;
			FpDbl x;
			x.setMpz(mx);
			x.getMpz(my);
			CYBOZU_TEST_EQUAL(mx, my);
			for (size_t j = 0; j < CYBOZU_NUM_OF_ARRAY(tbl); j++) {
				FpDbl y, z;
				mpz_class mz, mo;
				my = tbl[j];
				y.setMpz(my);
				FpDbl::add(z, x, y);
				mcl::Gmp::addMod(mo, mx, my, mp);
				z.getMpz(mz);
				CYBOZU_TEST_EQUAL(mz, mo);
				mcl::Gmp::subMod(mo, mx, my, mp);
				FpDbl::sub(z, x, y);
				z.getMpz(mz);
				CYBOZU_TEST_EQUAL(mz, mo);
			}
		}
	}
}

void test(const char *p, mcl::fp::Mode mode)
{
	Fp::setModulo(p, 0, mode);
	testFp2();
	if (Fp::getBitSize() <= 256) {
		testFpDbl();
	}
}
#if 0
void benchFp2()
{
	Fp2 x, y;
	x.a.set("4");
	x.b.set("464652165165");
	y = x * x;
	CYBOZU_BENCH("Fp2::add     ", Fp2::add, x, x, y);
	CYBOZU_BENCH("Fp2::addNC   ", Fp2::addNC, x, x, y);
	CYBOZU_BENCH("Fp2::sub     ", Fp2::sub, x, x, y);
	CYBOZU_BENCH("Fp2::neg     ", Fp2::neg, x, x);
	CYBOZU_BENCH("Fp2::mul     ", Fp2::mul, x, x, y);
	CYBOZU_BENCH("Fp2::inverse ", x.inverse);
	CYBOZU_BENCH("Fp2::square  ", Fp2::square, x, x);
	CYBOZU_BENCH("Fp2::mul_xi  ", Fp2::mul_xi, x, x);
	CYBOZU_BENCH("Fp2::mul_Fp_0", Fp2::mul_Fp_0, x, x, Param::half);
	CYBOZU_BENCH("Fp2::mul_Fp_1", Fp2::mul_Fp_1, x, Param::half);
	CYBOZU_BENCH("Fp2::divBy2  ", Fp2::divBy2, x, x);
	CYBOZU_BENCH("Fp2::divBy4  ", Fp2::divBy4, x, x);
}
#endif

CYBOZU_TEST_AUTO(test)
{
	const char *tbl[] = {
		// N = 3
		"0x000000000000000100000000000000000000000000000033", // min prime
		"0x00000000fffffffffffffffffffffffffffffffeffffac73",
		"0x0000000100000000000000000001b8fa16dfab9aca16b6b3",
		"0x000000010000000000000000000000000000000000000007",
		"0x30000000000000000000000000000000000000000000002b",
		"0x70000000000000000000000000000000000000000000001f",
		"0x800000000000000000000000000000000000000000000005",
		"0xfffffffffffffffffffffffffffffffffffffffeffffee37",
		"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d",
		"0xffffffffffffffffffffffffffffffffffffffffffffff13", // max prime

		// N = 4
		"0x0000000000000001000000000000000000000000000000000000000000000085", // min prime
		"0x2523648240000001ba344d80000000086121000000000013a700000000000013",
		"0x7523648240000001ba344d80000000086121000000000013a700000000000017",
		"0x800000000000000000000000000000000000000000000000000000000000005f",
		"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff43", // max prime
	};
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		const char *p = tbl[i];
		printf("prime=%s\n", p);
		test(tbl[i], mcl::fp::FP_GMP);
#ifdef MCL_USE_LLVM
		test(tbl[i], mcl::fp::FP_LLVM);
		test(tbl[i], mcl::fp::FP_LLVM_MONT);
#endif
#ifdef MCL_USE_XBYAK
		test(tbl[i], mcl::fp::FP_XBYAK);
#endif
	}
}

<commit_msg>test of FpDBl::addNC, subNC<commit_after>#define PUT(x) std::cout << #x "=" << (x) << std::endl
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <time.h>
#include <mcl/fp.hpp>
#include <mcl/fp_tower.hpp>

typedef mcl::FpT<mcl::FpTag, 256> Fp;
typedef mcl::Fp2T<Fp> Fp2;
typedef mcl::FpDblT<Fp> FpDbl;

void testFp2()
{
	puts(__FUNCTION__);
	const int xi_c = 9;
	Fp2::init(xi_c);
	Fp2 x, y, z;
	x.a = 1;
	x.b = 2;
	y.a = 3;
	y.b = 4;
	/*
		x = 1 + 2u
		y = 3 + 4u
	*/
	Fp2::add(z, x, y);
	CYBOZU_TEST_EQUAL(z, Fp2(4, 6));
	Fp2::sub(z, x, y);
	CYBOZU_TEST_EQUAL(z, Fp2(-2, -2));
	Fp2::mul(z, x, y);
	/*
		(1 + 2u)(3 + 4u) = (3 - 8) + (4 + 6)u = -5 + 10u
	*/
	CYBOZU_TEST_EQUAL(z, Fp2(-5, 10));
	Fp2::neg(z, z);
	CYBOZU_TEST_EQUAL(z, Fp2(5, -10));
	/*
		xi = 9 + u
		(1 - 2u)(9 + u) = (9 + 2) + (1 - 18)u = 11 - 17u
	*/
	z = Fp2(1, -2);
	Fp2::mul_xi(z, z);
	CYBOZU_TEST_EQUAL(z, Fp2(11, -17));
	z = x * x;
	Fp2::sqr(y, x);
	CYBOZU_TEST_EQUAL(z, y);
	x.a = -123456789;
	x.b = 464652165165;
	y = x * x;
	Fp2::sqr(x, x);
	CYBOZU_TEST_EQUAL(x, y);
	{
		std::ostringstream oss;
		oss << x;
		std::istringstream iss(oss.str());
		Fp2 w;
		iss >> w;
		CYBOZU_TEST_EQUAL(x, w);
	}
	y = x;
	Fp2::inv(y, x);
	y *= x;
	CYBOZU_TEST_EQUAL(y, 1);
}

void testFpDbl()
{
	puts(__FUNCTION__);
	{
		std::string pstr;
		Fp::getModulo(pstr);
		mpz_class mp(pstr);
		mp <<= Fp::getUnitSize() * mcl::fp::UnitBitSize;
		mpz_class mp1 = mp - 1;
		mcl::Gmp::getStr(pstr, mp1);
		const char *tbl[] = {
			"0", "1", "123456", "123456789012345668909", pstr.c_str(),
		};
		for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
			mpz_class mx(tbl[i]), my;
			FpDbl x;
			x.setMpz(mx);
			x.getMpz(my);
			CYBOZU_TEST_EQUAL(mx, my);
			for (size_t j = 0; j < CYBOZU_NUM_OF_ARRAY(tbl); j++) {
				FpDbl y, z;
				mpz_class mz, mo;
				my = tbl[j];
				y.setMpz(my);
				FpDbl::add(z, x, y);
				mcl::Gmp::addMod(mo, mx, my, mp);
				z.getMpz(mz);
				CYBOZU_TEST_EQUAL(mz, mo);
				mcl::Gmp::subMod(mo, mx, my, mp);
				FpDbl::sub(z, x, y);
				z.getMpz(mz);
				CYBOZU_TEST_EQUAL(mz, mo);
				if (!Fp::isFullBit()) {
					FpDbl::addNC(z, x, y);
					mo = mx + my;
					z.getMpz(mz);
					CYBOZU_TEST_EQUAL(mz, mo);
					if (mx >= my) {
						FpDbl::subNC(z, x, y);
						mo = mx - my;
						z.getMpz(mz);
						CYBOZU_TEST_EQUAL(mz, mo);
					}
				}
			}
		}
	}
}

void test(const char *p, mcl::fp::Mode mode)
{
	Fp::setModulo(p, 0, mode);
	printf("mode=%s\n", mcl::fp::ModeToStr(mode));
	if (Fp::getBitSize() > 256) {
		printf("not support p=%s\n", p);
		return;
	}
	testFp2();
	testFpDbl();
}
#if 0
void benchFp2()
{
	Fp2 x, y;
	x.a.set("4");
	x.b.set("464652165165");
	y = x * x;
	CYBOZU_BENCH("Fp2::add     ", Fp2::add, x, x, y);
	CYBOZU_BENCH("Fp2::addNC   ", Fp2::addNC, x, x, y);
	CYBOZU_BENCH("Fp2::sub     ", Fp2::sub, x, x, y);
	CYBOZU_BENCH("Fp2::neg     ", Fp2::neg, x, x);
	CYBOZU_BENCH("Fp2::mul     ", Fp2::mul, x, x, y);
	CYBOZU_BENCH("Fp2::inverse ", x.inverse);
	CYBOZU_BENCH("Fp2::square  ", Fp2::square, x, x);
	CYBOZU_BENCH("Fp2::mul_xi  ", Fp2::mul_xi, x, x);
	CYBOZU_BENCH("Fp2::mul_Fp_0", Fp2::mul_Fp_0, x, x, Param::half);
	CYBOZU_BENCH("Fp2::mul_Fp_1", Fp2::mul_Fp_1, x, Param::half);
	CYBOZU_BENCH("Fp2::divBy2  ", Fp2::divBy2, x, x);
	CYBOZU_BENCH("Fp2::divBy4  ", Fp2::divBy4, x, x);
}
#endif

CYBOZU_TEST_AUTO(test)
{
	const char *tbl[] = {
		// N = 3
		"0x000000000000000100000000000000000000000000000033", // min prime
		"0x00000000fffffffffffffffffffffffffffffffeffffac73",
		"0x0000000100000000000000000001b8fa16dfab9aca16b6b3",
		"0x000000010000000000000000000000000000000000000007",
		"0x30000000000000000000000000000000000000000000002b",
		"0x70000000000000000000000000000000000000000000001f",
		"0x800000000000000000000000000000000000000000000005",
		"0xfffffffffffffffffffffffffffffffffffffffeffffee37",
		"0xfffffffffffffffffffffffe26f2fc170f69466a74defd8d",
		"0xffffffffffffffffffffffffffffffffffffffffffffff13", // max prime

		// N = 4
		"0x0000000000000001000000000000000000000000000000000000000000000085", // min prime
		"0x2523648240000001ba344d80000000086121000000000013a700000000000013",
		"0x7523648240000001ba344d80000000086121000000000013a700000000000017",
		"0x800000000000000000000000000000000000000000000000000000000000005f",
		"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff43", // max prime
	};
	for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) {
		const char *p = tbl[i];
		printf("prime=%s\n", p);
		test(tbl[i], mcl::fp::FP_GMP);
#ifdef MCL_USE_LLVM
		test(tbl[i], mcl::fp::FP_LLVM);
		test(tbl[i], mcl::fp::FP_LLVM_MONT);
#endif
#ifdef MCL_USE_XBYAK
		test(tbl[i], mcl::fp::FP_XBYAK);
#endif
	}
}

<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/content_converter.h"

#include <string>
#include <vector>

#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/web_contents_permission_helper.h"
#include "atom/common/native_mate_converters/blink_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/ui_base_types_converter.h"
#include "brave/browser/api/navigation_controller.h"
#include "brave/browser/api/navigation_handle.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "native_mate/dictionary.h"

namespace {

void ExecuteCommand(content::WebContents* web_contents,
                    int action,
                    const content::CustomContextMenuContext& context) {
  web_contents->ExecuteCustomContextMenuCommand(action, context);
}

// Forward declaration for nested recursive call.
v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu);

v8::Local<v8::Value> MenuItemToV8(
    v8::Isolate* isolate,
    content::WebContents* web_contents,
    const content::CustomContextMenuContext& context,
    const content::MenuItem& item) {
  mate::Dictionary v8_item = mate::Dictionary::CreateEmpty(isolate);
  switch (item.type) {
    case content::MenuItem::CHECKABLE_OPTION:
    case content::MenuItem::GROUP:
      v8_item.Set("checked", item.checked);
    case content::MenuItem::OPTION:
    case content::MenuItem::SUBMENU:
      v8_item.Set("label", item.label);
      v8_item.Set("enabled", item.enabled);
    default:
      v8_item.Set("type", item.type);
  }
  if (item.type == content::MenuItem::SUBMENU)
    v8_item.Set("submenu",
                MenuToV8(isolate, web_contents, context, item.submenu));
  else if (item.action > 0)
    v8_item.Set("click",
                base::Bind(ExecuteCommand, web_contents, item.action, context));
  return v8_item.GetHandle();
}

v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu) {
  std::vector<v8::Local<v8::Value>> v8_menu;
  for (const auto& menu_item : menu)
    v8_menu.push_back(MenuItemToV8(isolate, web_contents, context, menu_item));
  return mate::ConvertToV8(isolate, v8_menu);
}

}  // namespace

namespace mate {

// static
v8::Local<v8::Value> Converter<content::MenuItem::Type>::ToV8(
    v8::Isolate* isolate, const content::MenuItem::Type& val) {
  switch (val) {
    case content::MenuItem::CHECKABLE_OPTION:
      return StringToV8(isolate, "checkbox");
    case content::MenuItem::GROUP:
      return StringToV8(isolate, "radio");
    case content::MenuItem::SEPARATOR:
      return StringToV8(isolate, "separator");
    case content::MenuItem::SUBMENU:
      return StringToV8(isolate, "submenu");
    case content::MenuItem::OPTION:
    default:
      return StringToV8(isolate, "normal");
  }
}

// static
v8::Local<v8::Value> Converter<ContextMenuParamsWithWebContents>::ToV8(
    v8::Isolate* isolate, const ContextMenuParamsWithWebContents& val) {
  const auto& params = val.first;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("x", params.x);
  dict.Set("y", params.y);
  dict.Set("linkURL", params.link_url);
  dict.Set("linkText", params.link_text);
  dict.Set("pageURL", params.page_url);
  dict.Set("frameURL", params.frame_url);
  dict.Set("srcURL", params.src_url);
  dict.Set("mediaType", params.media_type);
  dict.Set("mediaFlags", MediaFlagsToV8(isolate, params.media_flags));
  bool has_image_contents =
    (params.media_type == blink::WebContextMenuData::MediaTypeImage) &&
    params.has_image_contents;
  dict.Set("hasImageContents", has_image_contents);
  dict.Set("isEditable", params.is_editable);
  dict.Set("editFlags", EditFlagsToV8(isolate, params.edit_flags));
  dict.Set("selectionText", params.selection_text);
  dict.Set("titleText", params.title_text);
  dict.Set("misspelledWord", params.misspelled_word);
  dict.Set("frameCharset", params.frame_charset);
  dict.Set("inputFieldType", params.input_field_type);
  dict.Set("menuSourceType",  params.source_type);

  if (params.custom_context.request_id || params.custom_context.is_pepper_menu)
    dict.Set("menu", MenuToV8(isolate, val.second, params.custom_context,
                              params.custom_items));
  return mate::ConvertToV8(isolate, dict);
}

// static
bool Converter<blink::mojom::PermissionStatus>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    blink::mojom::PermissionStatus* out) {
  bool result;
  if (!ConvertFromV8(isolate, val, &result))
    return false;

  if (result)
    *out = blink::mojom::PermissionStatus::GRANTED;
  else
    *out = blink::mojom::PermissionStatus::DENIED;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::PermissionType>::ToV8(
    v8::Isolate* isolate, const content::PermissionType& val) {
  using PermissionType = atom::WebContentsPermissionHelper::PermissionType;
  switch (val) {
    case content::PermissionType::MIDI_SYSEX:
      return StringToV8(isolate, "midiSysex");
    case content::PermissionType::PUSH_MESSAGING:
      return StringToV8(isolate, "pushMessaging");
    case content::PermissionType::NOTIFICATIONS:
      return StringToV8(isolate, "notifications");
    case content::PermissionType::GEOLOCATION:
      return StringToV8(isolate, "geolocation");
    case content::PermissionType::AUDIO_CAPTURE:
    case content::PermissionType::VIDEO_CAPTURE:
      return StringToV8(isolate, "media");
    case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER:
      return StringToV8(isolate, "mediaKeySystem");
    case content::PermissionType::MIDI:
      return StringToV8(isolate, "midi");
    default:
      break;
  }

  if (val == (content::PermissionType)(PermissionType::POINTER_LOCK))
    return StringToV8(isolate, "pointerLock");
  else if (val == (content::PermissionType)(PermissionType::FULLSCREEN))
    return StringToV8(isolate, "fullscreen");
  else if (val == (content::PermissionType)(PermissionType::OPEN_EXTERNAL))
    return StringToV8(isolate, "openExternal");
  else if (val == (content::PermissionType)
      (PermissionType::PROTOCOL_REGISTRATION))
    return StringToV8(isolate, "protocolRegistration");

  return StringToV8(isolate, "unknown");
}

// static
bool Converter<content::StopFindAction>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::StopFindAction* out) {
  std::string action;
  if (!ConvertFromV8(isolate, val, &action))
    return false;

  if (action == "clearSelection")
    *out = content::STOP_FIND_ACTION_CLEAR_SELECTION;
  else if (action == "keepSelection")
    *out = content::STOP_FIND_ACTION_KEEP_SELECTION;
  else if (action == "activateSelection")
    *out = content::STOP_FIND_ACTION_ACTIVATE_SELECTION;
  else
    return false;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::WebContents*>::ToV8(
    v8::Isolate* isolate, content::WebContents* val) {
  if (!val)
    return v8::Null(isolate);
  return atom::api::WebContents::CreateFrom(isolate, val).ToV8();
}

// static
bool Converter<content::WebContents*>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::WebContents** out) {
  atom::api::WebContents* web_contents = nullptr;
  if (!ConvertFromV8(isolate, val, &web_contents) || !web_contents)
    return false;

  *out = web_contents->web_contents();
  return true;
}

// static
v8::Local<v8::Value> Converter<content::NavigationHandle*>::ToV8(
    v8::Isolate* isolate, content::NavigationHandle* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationHandle::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::NavigationEntry*>::ToV8(
    v8::Isolate* isolate, content::NavigationEntry* val) {
  if (!val)
    return v8::Null(isolate);

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("uniqueId", val->GetUniqueID());
  dict.Set("pageType", val->GetPageType());
  dict.Set("url", val->GetURL());
  dict.Set("referrer", val->GetReferrer().url);
  dict.Set("virtualURL", val->GetVirtualURL());
  dict.Set("title", val->GetTitle());
  dict.Set("display_title", val->GetTitleForDisplay());
  dict.Set("viewSourceMode", val->IsViewSourceMode());
  dict.Set("transitionType", val->GetTransitionType());
  dict.Set("hasPostData", val->GetHasPostData());
  // GetFavicon
  // GetSSL
  dict.Set("originalRequestURL", val->GetOriginalRequestURL());
  dict.Set("isOverridingUserAgent", val->GetIsOverridingUserAgent());
  dict.Set("timestamp", val->GetTimestamp().ToDoubleT());
  dict.Set("httpStatusCode", val->GetHttpStatusCode());
  dict.Set("isRestored", val->IsRestored());
  dict.Set("extraHeaders",  val->GetExtraHeaders());

  return mate::ConvertToV8(isolate, dict);
}

// static
v8::Local<v8::Value> Converter<content::NavigationController*>::ToV8(
    v8::Isolate* isolate, content::NavigationController* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationController::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::ReloadType>::ToV8(
    v8::Isolate* isolate, const content::ReloadType& val) {
  switch (val) {
    case content::ReloadType::NONE:
      return StringToV8(isolate, "none");
    case content::ReloadType::NORMAL:
      return StringToV8(isolate, "normal");
    case content::ReloadType::BYPASSING_CACHE:
      return StringToV8(isolate, "bypassingCache");
    case content::ReloadType::ORIGINAL_REQUEST_URL:
      return StringToV8(isolate, "originalRequestUrl");
    case content::ReloadType::DISABLE_LOFI_MODE:
      return StringToV8(isolate, "disableLofiMode");
    default:
      break;
  }

  return StringToV8(isolate, "unknown");
}

// static
v8::Local<v8::Value> Converter<content::PageType>::ToV8(
    v8::Isolate* isolate, const content::PageType& val) {
  switch (val) {
    case content::PageType::PAGE_TYPE_NORMAL:
      return StringToV8(isolate, "normal");
    case content::PageType::PAGE_TYPE_ERROR:
      return StringToV8(isolate, "error");
    case content::PageType::PAGE_TYPE_INTERSTITIAL:
      return StringToV8(isolate, "interstitial");
    default:
      return StringToV8(isolate, "unknown");
  }
}

// static
v8::Local<v8::Value> Converter<content::RestoreType>::ToV8(
    v8::Isolate* isolate, const content::RestoreType& val) {
  switch (val) {
    case content::RestoreType::LAST_SESSION_EXITED_CLEANLY:
      return StringToV8(isolate, "lastSessionExitedCleanly");
    case content::RestoreType::LAST_SESSION_CRASHED:
      return StringToV8(isolate, "lastSessionCrashed");
    case content::RestoreType::CURRENT_SESSION:
      return StringToV8(isolate, "currentSession");
    default:
      return StringToV8(isolate, "none");
  }
}

// static
v8::Local<v8::Value> Converter<ui::PageTransition>::ToV8(
    v8::Isolate* isolate, const ui::PageTransition& val) {
  if (val & ui::PageTransition::PAGE_TRANSITION_LINK)
    return StringToV8(isolate, "link");
  if (val & ui::PageTransition::PAGE_TRANSITION_TYPED)
    return StringToV8(isolate, "typed");
  if (val & ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK)
    return StringToV8(isolate, "auto_bookmark");
  if (val & ui::PageTransition::PAGE_TRANSITION_AUTO_SUBFRAME)
    return StringToV8(isolate, "auto_subframe");
  if (val & ui::PageTransition::PAGE_TRANSITION_MANUAL_SUBFRAME)
    return StringToV8(isolate, "manual_subframe");
  if (val & ui::PageTransition::PAGE_TRANSITION_GENERATED)
    return StringToV8(isolate, "generated");
  if (val & ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL)
    return StringToV8(isolate, "auto_toplevel");
  if (val & ui::PageTransition::PAGE_TRANSITION_FORM_SUBMIT)
    return StringToV8(isolate, "form_submit");
  if (val & ui::PageTransition::PAGE_TRANSITION_RELOAD)
    return StringToV8(isolate, "reload");
  if (val & ui::PageTransition::PAGE_TRANSITION_KEYWORD)
    return StringToV8(isolate, "keyword");
  if (val & ui::PageTransition::PAGE_TRANSITION_KEYWORD_GENERATED)
    return StringToV8(isolate, "keyword_generated");

  return StringToV8(isolate, "unknown");
}

}  // namespace mate
<commit_msg>fix page transition type auditors @bbondy<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/content_converter.h"

#include <string>
#include <vector>

#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/web_contents_permission_helper.h"
#include "atom/common/native_mate_converters/blink_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/ui_base_types_converter.h"
#include "brave/browser/api/navigation_controller.h"
#include "brave/browser/api/navigation_handle.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "native_mate/dictionary.h"

namespace {

void ExecuteCommand(content::WebContents* web_contents,
                    int action,
                    const content::CustomContextMenuContext& context) {
  web_contents->ExecuteCustomContextMenuCommand(action, context);
}

// Forward declaration for nested recursive call.
v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu);

v8::Local<v8::Value> MenuItemToV8(
    v8::Isolate* isolate,
    content::WebContents* web_contents,
    const content::CustomContextMenuContext& context,
    const content::MenuItem& item) {
  mate::Dictionary v8_item = mate::Dictionary::CreateEmpty(isolate);
  switch (item.type) {
    case content::MenuItem::CHECKABLE_OPTION:
    case content::MenuItem::GROUP:
      v8_item.Set("checked", item.checked);
    case content::MenuItem::OPTION:
    case content::MenuItem::SUBMENU:
      v8_item.Set("label", item.label);
      v8_item.Set("enabled", item.enabled);
    default:
      v8_item.Set("type", item.type);
  }
  if (item.type == content::MenuItem::SUBMENU)
    v8_item.Set("submenu",
                MenuToV8(isolate, web_contents, context, item.submenu));
  else if (item.action > 0)
    v8_item.Set("click",
                base::Bind(ExecuteCommand, web_contents, item.action, context));
  return v8_item.GetHandle();
}

v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu) {
  std::vector<v8::Local<v8::Value>> v8_menu;
  for (const auto& menu_item : menu)
    v8_menu.push_back(MenuItemToV8(isolate, web_contents, context, menu_item));
  return mate::ConvertToV8(isolate, v8_menu);
}

}  // namespace

namespace mate {

// static
v8::Local<v8::Value> Converter<content::MenuItem::Type>::ToV8(
    v8::Isolate* isolate, const content::MenuItem::Type& val) {
  switch (val) {
    case content::MenuItem::CHECKABLE_OPTION:
      return StringToV8(isolate, "checkbox");
    case content::MenuItem::GROUP:
      return StringToV8(isolate, "radio");
    case content::MenuItem::SEPARATOR:
      return StringToV8(isolate, "separator");
    case content::MenuItem::SUBMENU:
      return StringToV8(isolate, "submenu");
    case content::MenuItem::OPTION:
    default:
      return StringToV8(isolate, "normal");
  }
}

// static
v8::Local<v8::Value> Converter<ContextMenuParamsWithWebContents>::ToV8(
    v8::Isolate* isolate, const ContextMenuParamsWithWebContents& val) {
  const auto& params = val.first;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("x", params.x);
  dict.Set("y", params.y);
  dict.Set("linkURL", params.link_url);
  dict.Set("linkText", params.link_text);
  dict.Set("pageURL", params.page_url);
  dict.Set("frameURL", params.frame_url);
  dict.Set("srcURL", params.src_url);
  dict.Set("mediaType", params.media_type);
  dict.Set("mediaFlags", MediaFlagsToV8(isolate, params.media_flags));
  bool has_image_contents =
    (params.media_type == blink::WebContextMenuData::MediaTypeImage) &&
    params.has_image_contents;
  dict.Set("hasImageContents", has_image_contents);
  dict.Set("isEditable", params.is_editable);
  dict.Set("editFlags", EditFlagsToV8(isolate, params.edit_flags));
  dict.Set("selectionText", params.selection_text);
  dict.Set("titleText", params.title_text);
  dict.Set("misspelledWord", params.misspelled_word);
  dict.Set("frameCharset", params.frame_charset);
  dict.Set("inputFieldType", params.input_field_type);
  dict.Set("menuSourceType",  params.source_type);

  if (params.custom_context.request_id || params.custom_context.is_pepper_menu)
    dict.Set("menu", MenuToV8(isolate, val.second, params.custom_context,
                              params.custom_items));
  return mate::ConvertToV8(isolate, dict);
}

// static
bool Converter<blink::mojom::PermissionStatus>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    blink::mojom::PermissionStatus* out) {
  bool result;
  if (!ConvertFromV8(isolate, val, &result))
    return false;

  if (result)
    *out = blink::mojom::PermissionStatus::GRANTED;
  else
    *out = blink::mojom::PermissionStatus::DENIED;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::PermissionType>::ToV8(
    v8::Isolate* isolate, const content::PermissionType& val) {
  using PermissionType = atom::WebContentsPermissionHelper::PermissionType;
  switch (val) {
    case content::PermissionType::MIDI_SYSEX:
      return StringToV8(isolate, "midiSysex");
    case content::PermissionType::PUSH_MESSAGING:
      return StringToV8(isolate, "pushMessaging");
    case content::PermissionType::NOTIFICATIONS:
      return StringToV8(isolate, "notifications");
    case content::PermissionType::GEOLOCATION:
      return StringToV8(isolate, "geolocation");
    case content::PermissionType::AUDIO_CAPTURE:
    case content::PermissionType::VIDEO_CAPTURE:
      return StringToV8(isolate, "media");
    case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER:
      return StringToV8(isolate, "mediaKeySystem");
    case content::PermissionType::MIDI:
      return StringToV8(isolate, "midi");
    default:
      break;
  }

  if (val == (content::PermissionType)(PermissionType::POINTER_LOCK))
    return StringToV8(isolate, "pointerLock");
  else if (val == (content::PermissionType)(PermissionType::FULLSCREEN))
    return StringToV8(isolate, "fullscreen");
  else if (val == (content::PermissionType)(PermissionType::OPEN_EXTERNAL))
    return StringToV8(isolate, "openExternal");
  else if (val == (content::PermissionType)
      (PermissionType::PROTOCOL_REGISTRATION))
    return StringToV8(isolate, "protocolRegistration");

  return StringToV8(isolate, "unknown");
}

// static
bool Converter<content::StopFindAction>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::StopFindAction* out) {
  std::string action;
  if (!ConvertFromV8(isolate, val, &action))
    return false;

  if (action == "clearSelection")
    *out = content::STOP_FIND_ACTION_CLEAR_SELECTION;
  else if (action == "keepSelection")
    *out = content::STOP_FIND_ACTION_KEEP_SELECTION;
  else if (action == "activateSelection")
    *out = content::STOP_FIND_ACTION_ACTIVATE_SELECTION;
  else
    return false;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::WebContents*>::ToV8(
    v8::Isolate* isolate, content::WebContents* val) {
  if (!val)
    return v8::Null(isolate);
  return atom::api::WebContents::CreateFrom(isolate, val).ToV8();
}

// static
bool Converter<content::WebContents*>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::WebContents** out) {
  atom::api::WebContents* web_contents = nullptr;
  if (!ConvertFromV8(isolate, val, &web_contents) || !web_contents)
    return false;

  *out = web_contents->web_contents();
  return true;
}

// static
v8::Local<v8::Value> Converter<content::NavigationHandle*>::ToV8(
    v8::Isolate* isolate, content::NavigationHandle* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationHandle::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::NavigationEntry*>::ToV8(
    v8::Isolate* isolate, content::NavigationEntry* val) {
  if (!val)
    return v8::Null(isolate);

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("uniqueId", val->GetUniqueID());
  dict.Set("pageType", val->GetPageType());
  dict.Set("url", val->GetURL());
  dict.Set("referrer", val->GetReferrer().url);
  dict.Set("virtualURL", val->GetVirtualURL());
  dict.Set("title", val->GetTitle());
  dict.Set("displayTitle", val->GetTitleForDisplay());
  dict.Set("viewSourceMode", val->IsViewSourceMode());
  dict.Set("transitionType", val->GetTransitionType());
  dict.Set("hasPostData", val->GetHasPostData());
  // GetFavicon
  // GetSSL
  dict.Set("originalRequestURL", val->GetOriginalRequestURL());
  dict.Set("isOverridingUserAgent", val->GetIsOverridingUserAgent());
  dict.Set("timestamp", val->GetTimestamp().ToDoubleT());
  dict.Set("httpStatusCode", val->GetHttpStatusCode());
  dict.Set("isRestored", val->IsRestored());
  dict.Set("extraHeaders",  val->GetExtraHeaders());

  return mate::ConvertToV8(isolate, dict);
}

// static
v8::Local<v8::Value> Converter<content::NavigationController*>::ToV8(
    v8::Isolate* isolate, content::NavigationController* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationController::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::ReloadType>::ToV8(
    v8::Isolate* isolate, const content::ReloadType& val) {
  switch (val) {
    case content::ReloadType::NONE:
      return StringToV8(isolate, "none");
    case content::ReloadType::NORMAL:
      return StringToV8(isolate, "normal");
    case content::ReloadType::BYPASSING_CACHE:
      return StringToV8(isolate, "bypassingCache");
    case content::ReloadType::ORIGINAL_REQUEST_URL:
      return StringToV8(isolate, "originalRequestUrl");
    case content::ReloadType::DISABLE_LOFI_MODE:
      return StringToV8(isolate, "disableLofiMode");
    default:
      break;
  }

  return StringToV8(isolate, "unknown");
}

// static
v8::Local<v8::Value> Converter<content::PageType>::ToV8(
    v8::Isolate* isolate, const content::PageType& val) {
  switch (val) {
    case content::PageType::PAGE_TYPE_NORMAL:
      return StringToV8(isolate, "normal");
    case content::PageType::PAGE_TYPE_ERROR:
      return StringToV8(isolate, "error");
    case content::PageType::PAGE_TYPE_INTERSTITIAL:
      return StringToV8(isolate, "interstitial");
    default:
      return StringToV8(isolate, "unknown");
  }
}

// static
v8::Local<v8::Value> Converter<content::RestoreType>::ToV8(
    v8::Isolate* isolate, const content::RestoreType& val) {
  switch (val) {
    case content::RestoreType::LAST_SESSION_EXITED_CLEANLY:
      return StringToV8(isolate, "lastSessionExitedCleanly");
    case content::RestoreType::LAST_SESSION_CRASHED:
      return StringToV8(isolate, "lastSessionCrashed");
    case content::RestoreType::CURRENT_SESSION:
      return StringToV8(isolate, "currentSession");
    default:
      return StringToV8(isolate, "none");
  }
}

// static
v8::Local<v8::Value> Converter<ui::PageTransition>::ToV8(
    v8::Isolate* isolate, const ui::PageTransition& val) {
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_LINK))
    return StringToV8(isolate, "link");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_TYPED))
    return StringToV8(isolate, "typed");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK))
    return StringToV8(isolate, "autoBookmark");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_SUBFRAME))
    return StringToV8(isolate, "autoSubframe");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_MANUAL_SUBFRAME))
    return StringToV8(isolate, "manualSubframe");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_GENERATED))
    return StringToV8(isolate, "generated");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL))
    return StringToV8(isolate, "autoToplevel");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_FORM_SUBMIT))
    return StringToV8(isolate, "formSubmit");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_RELOAD))
    return StringToV8(isolate, "reload");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_KEYWORD))
    return StringToV8(isolate, "keyword");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_KEYWORD_GENERATED))
    return StringToV8(isolate, "keywordGenerated");

  return StringToV8(isolate, "unknown");
}

}  // namespace mate
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include "napiconfig.h"
#include "NeXusFile.hpp"

using std::cout;
using std::endl;
using std::string;
using std::vector;

int main(int argc, char** argv)
{
  NXaccess create_code = NXACC_CREATE;
#ifdef HDF5
  create_code = NXACC_CREATE5;
#elif HDF4
  create_code = NXACC_CREATE4;
#elif NXXML
  create_code = NXACC_CREATEXML;
#endif
  create_code = NXACC_CREATEXML; // TODO remove this line
  NeXus::File file("napi_cpp.nxs", create_code);
  // create group
  file.makeGroup("entry", "NXentry");
  // group attributes
  file.putAttr("hugo", "namenlos");
  file.putAttr("cucumber", "passion");
  // put string
  file.writeData("ch_data", "NeXus_data");

  // 2d array
  vector<int> array_dims;
  array_dims.push_back(5);
  array_dims.push_back(4);
  char c1_array[5][4] = {{'a', 'b', 'c' ,'d'}, {'e', 'f', 'g' ,'h'},
                         {'i', 'j', 'k', 'l'}, {'m', 'n', 'o', 'p'},
                         {'q', 'r', 's' , 't'}};
  file.makeData("c1_data", NeXus::CHAR, array_dims);
  file.putData(c1_array);
  file.closeData();

  // 1d uint8 array
  vector<uint8_t> i1_array;
  for (size_t i = 0; i < 4; i++) {
    i1_array.push_back(i+1);
  }
  file.writeData("i1_data", i1_array);

  // 1d int16 array
  vector<int16_t> i2_array;
  for (size_t i = 0; i < 4; i++) {
    i2_array.push_back(1000*(i+1));
  }
  file.writeData("i2_data", i2_array);

  // 1d int32 data
  vector<int32_t> i4_array;
  for (size_t i = 0; i < 4; i++) {
    i4_array.push_back(1000000*(i+1));
  }
  file.writeData("i4_data", i4_array);

  // 2d float data
  vector<float> r4_array;
  for (size_t i = 0; i < 5*4; i++) {
    r4_array.push_back(static_cast<float>(i));
  }
  file.writeData("r4_data", r4_array, array_dims);

  // 2d double data - slab test
  vector<double> r8_array;
  for (size_t i = 0; i < 5*4; i++) {
    r8_array.push_back(static_cast<double>(i));
  }
  file.makeData("r8_data", NeXus::FLOAT64, array_dims);
  vector<int> slab_start;
  slab_start.push_back(4);
  slab_start.push_back(0);
  vector<int> slab_size;
  slab_size.push_back(1);
  slab_size.push_back(4);
  file.putSlab(&(r8_array[16]), slab_start, slab_size);
  slab_start[0] = 0;
  slab_start[1] = 0;
  slab_size[0]=4;
  slab_size[1]=4;
  file.putSlab(&(r8_array[0]), slab_start, slab_size);

  // add some attributes
  file.putAttr("ch_attribute", "NeXus");
  file.putAttr("i4_attribute", 42);
  file.putAttr("r4_attribute", 3.14159265);

  // set up for creating a link
  NXlink link = file.getDataID();
  file.closeData();

  // int64 tests - TODO this does not put anything into the file
#ifdef HAVE_LONG_LONG_INT
  vector<int64_t> grossezahl;
  grossezahl.push_back(12);
  grossezahl.push_back(555555555555LL);
  grossezahl.push_back(23);
  grossezahl.push_back(777777777777LL);
  file.writeData("grosszahl", grossezahl);
#endif

  // create a new group inside this one
  file.makeGroup("data", "NXdata");

  // create a link
  file.makeLink(link);

  return 0;
}

/*
  int unlimited_dims[1] = {NX_UNLIMITED};
  int chunk_size[2]={5,4};
  int slab_start[2], slab_size[2];
  char name[64], char_class[64], char_buffer[128];
  char group_name[64], class_name[64];
  char c1_array[5][4] = {{'a', 'b', 'c' ,'d'}, {'e', 'f', 'g' ,'h'},
     {'i', 'j', 'k', 'l'}, {'m', 'n', 'o', 'p'}, {'q', 'r', 's' , 't'}};
  NXhandle fileid;
  NXlink glink, dlink, blink;
  int comp_array[100][20];
  int dims[2];
  int cdims[2];
  int nx_creation_code;
  char nxFile[80];
  char filename[256];
*/
<commit_msg>Added compressed data test. Refs #116.<commit_after>#include <iostream>
#include <string>
#include <vector>
#include "napiconfig.h"
#include "NeXusFile.hpp"

using std::cout;
using std::endl;
using std::string;
using std::vector;

int main(int argc, char** argv)
{
  NXaccess create_code = NXACC_CREATE;
#ifdef HDF5
  create_code = NXACC_CREATE5;
#elif HDF4
  create_code = NXACC_CREATE4;
#elif NXXML
  create_code = NXACC_CREATEXML;
#endif
  create_code = NXACC_CREATEXML; // TODO remove this line
  NeXus::File file("napi_cpp.nxs", create_code);
  // create group
  file.makeGroup("entry", "NXentry");
  // group attributes
  file.putAttr("hugo", "namenlos");
  file.putAttr("cucumber", "passion");
  // put string
  file.writeData("ch_data", "NeXus_data");

  // 2d array
  vector<int> array_dims;
  array_dims.push_back(5);
  array_dims.push_back(4);
  char c1_array[5][4] = {{'a', 'b', 'c' ,'d'}, {'e', 'f', 'g' ,'h'},
                         {'i', 'j', 'k', 'l'}, {'m', 'n', 'o', 'p'},
                         {'q', 'r', 's' , 't'}};
  file.makeData("c1_data", NeXus::CHAR, array_dims);
  file.putData(c1_array);
  file.closeData();

  // 1d uint8 array
  vector<uint8_t> i1_array;
  for (size_t i = 0; i < 4; i++) {
    i1_array.push_back(i+1);
  }
  file.writeData("i1_data", i1_array);

  // 1d int16 array
  vector<int16_t> i2_array;
  for (size_t i = 0; i < 4; i++) {
    i2_array.push_back(1000*(i+1));
  }
  file.writeData("i2_data", i2_array);

  // 1d int32 data
  vector<int32_t> i4_array;
  for (size_t i = 0; i < 4; i++) {
    i4_array.push_back(1000000*(i+1));
  }
  file.writeData("i4_data", i4_array);

  // 2d float data
  vector<float> r4_array;
  for (size_t i = 0; i < 5*4; i++) {
    r4_array.push_back(static_cast<float>(i));
  }
  file.writeData("r4_data", r4_array, array_dims);

  // 2d double data - slab test
  vector<double> r8_array;
  for (size_t i = 0; i < 5*4; i++) {
    r8_array.push_back(static_cast<double>(i));
  }
  file.makeData("r8_data", NeXus::FLOAT64, array_dims);
  vector<int> slab_start;
  slab_start.push_back(4);
  slab_start.push_back(0);
  vector<int> slab_size;
  slab_size.push_back(1);
  slab_size.push_back(4);
  file.putSlab(&(r8_array[16]), slab_start, slab_size);
  slab_start[0] = 0;
  slab_start[1] = 0;
  slab_size[0]=4;
  slab_size[1]=4;
  file.putSlab(&(r8_array[0]), slab_start, slab_size);

  // add some attributes
  file.putAttr("ch_attribute", "NeXus");
  file.putAttr("i4_attribute", 42);
  file.putAttr("r4_attribute", 3.14159265);

  // set up for creating a link
  NXlink link = file.getDataID();
  file.closeData();

  // int64 tests - TODO this does not put anything into the file
#ifdef HAVE_LONG_LONG_INT
  vector<int64_t> grossezahl;
  grossezahl.push_back(12);
  grossezahl.push_back(555555555555LL);
  grossezahl.push_back(23);
  grossezahl.push_back(777777777777LL);
  file.writeData("grosszahl", grossezahl);
#endif

  // create a new group inside this one
  file.makeGroup("data", "NXdata");

  // create a link
  file.makeLink(link);

  // compressed data
  array_dims[0] = 100;
  array_dims[1] = 20;
  vector<int> comp_array;
  for (int i = 0; i < array_dims[0]; i++) {
    for (int j = 0; j < array_dims[1]; j++) {
      comp_array.push_back(i);
    }
  }
  vector<int> cdims;
  cdims.push_back(20);
  cdims.push_back(20);
  file.writeCompData("comp_data", comp_array, array_dims, NeXus::LZW, cdims);

  return 0;
}

/*
  int unlimited_dims[1] = {NX_UNLIMITED};
  int chunk_size[2]={5,4};
  int slab_start[2], slab_size[2];
  char name[64], char_class[64], char_buffer[128];
  char group_name[64], class_name[64];
  char c1_array[5][4] = {{'a', 'b', 'c' ,'d'}, {'e', 'f', 'g' ,'h'},
     {'i', 'j', 'k', 'l'}, {'m', 'n', 'o', 'p'}, {'q', 'r', 's' , 't'}};
  NXhandle fileid;
  NXlink glink, dlink, blink;
  int comp_array[100][20];
  int dims[2];
  int cdims[2];
  int nx_creation_code;
  char nxFile[80];
  char filename[256];
*/
<|endoftext|>


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

#include "webrtc/base/gunit.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/base/socket_unittest.h"
#include "webrtc/base/thread.h"
#include "webrtc/base/macsocketserver.h"

namespace rtc {

class WakeThread : public Thread {
 public:
  WakeThread(SocketServer* ss) : ss_(ss) {
  }
  virtual ~WakeThread() {
    Stop();
  }
  void Run() {
    ss_->WakeUp();
  }
 private:
  SocketServer* ss_;
};

#ifndef CARBON_DEPRECATED

// Test that MacCFSocketServer::Wait works as expected.
TEST(MacCFSocketServerTest, TestWait) {
  MacCFSocketServer server;
  uint32 start = Time();
  server.Wait(1000, true);
  EXPECT_GE(TimeSince(start), 1000);
}

// Test that MacCFSocketServer::Wakeup works as expected.
TEST(MacCFSocketServerTest, TestWakeup) {
  MacCFSocketServer server;
  WakeThread thread(&server);
  uint32 start = Time();
  thread.Start();
  server.Wait(10000, true);
  EXPECT_LT(TimeSince(start), 10000);
}

// Test that MacCarbonSocketServer::Wait works as expected.
TEST(MacCarbonSocketServerTest, TestWait) {
  MacCarbonSocketServer server;
  uint32 start = Time();
  server.Wait(1000, true);
  EXPECT_GE(TimeSince(start), 1000);
}

// Test that MacCarbonSocketServer::Wakeup works as expected.
TEST(MacCarbonSocketServerTest, TestWakeup) {
  MacCarbonSocketServer server;
  WakeThread thread(&server);
  uint32 start = Time();
  thread.Start();
  server.Wait(10000, true);
  EXPECT_LT(TimeSince(start), 10000);
}

// Test that MacCarbonAppSocketServer::Wait works as expected.
TEST(MacCarbonAppSocketServerTest, TestWait) {
  MacCarbonAppSocketServer server;
  uint32 start = Time();
  server.Wait(1000, true);
  EXPECT_GE(TimeSince(start), 1000);
}

// Test that MacCarbonAppSocketServer::Wakeup works as expected.
TEST(MacCarbonAppSocketServerTest, TestWakeup) {
  MacCarbonAppSocketServer server;
  WakeThread thread(&server);
  uint32 start = Time();
  thread.Start();
  server.Wait(10000, true);
  EXPECT_LT(TimeSince(start), 10000);
}

#endif

// Test that MacAsyncSocket passes all the generic Socket tests.
class MacAsyncSocketTest : public SocketTest {
 protected:
  MacAsyncSocketTest()
      : server_(CreateSocketServer()),
        scope_(server_.get()) {}
  // Override for other implementations of MacBaseSocketServer.
  virtual MacBaseSocketServer* CreateSocketServer() {
    return new MacCFSocketServer();
  };
  rtc::scoped_ptr<MacBaseSocketServer> server_;
  SocketServerScope scope_;
};

TEST_F(MacAsyncSocketTest, TestConnectIPv4) {
  SocketTest::TestConnectIPv4();
}

TEST_F(MacAsyncSocketTest, TestConnectIPv6) {
  SocketTest::TestConnectIPv6();
}

TEST_F(MacAsyncSocketTest, TestConnectWithDnsLookupIPv4) {
  SocketTest::TestConnectWithDnsLookupIPv4();
}

TEST_F(MacAsyncSocketTest, TestConnectWithDnsLookupIPv6) {
  SocketTest::TestConnectWithDnsLookupIPv6();
}

// BUG=https://code.google.com/p/webrtc/issues/detail?id=2272
TEST_F(MacAsyncSocketTest, DISABLED_TestConnectFailIPv4) {
  SocketTest::TestConnectFailIPv4();
}

TEST_F(MacAsyncSocketTest, TestConnectFailIPv6) {
  SocketTest::TestConnectFailIPv6();
}

// Reenable once we have mac async dns
TEST_F(MacAsyncSocketTest, DISABLED_TestConnectWithDnsLookupFailIPv4) {
  SocketTest::TestConnectWithDnsLookupFailIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestConnectWithDnsLookupFailIPv6) {
  SocketTest::TestConnectWithDnsLookupFailIPv6();
}

TEST_F(MacAsyncSocketTest, TestConnectWithClosedSocketIPv4) {
  SocketTest::TestConnectWithClosedSocketIPv4();
}

TEST_F(MacAsyncSocketTest, TestConnectWithClosedSocketIPv6) {
  SocketTest::TestConnectWithClosedSocketIPv6();
}

// Flaky at the moment (10% failure rate).  Seems the client doesn't get
// signalled in a timely manner...
TEST_F(MacAsyncSocketTest, DISABLED_TestServerCloseDuringConnectIPv4) {
  SocketTest::TestServerCloseDuringConnectIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestServerCloseDuringConnectIPv6) {
  SocketTest::TestServerCloseDuringConnectIPv6();
}
// Flaky at the moment (0.5% failure rate).  Seems the client doesn't get
// signalled in a timely manner...
TEST_F(MacAsyncSocketTest, TestClientCloseDuringConnectIPv4) {
  SocketTest::TestClientCloseDuringConnectIPv4();
}

TEST_F(MacAsyncSocketTest, TestClientCloseDuringConnectIPv6) {
  SocketTest::TestClientCloseDuringConnectIPv6();
}

TEST_F(MacAsyncSocketTest, TestServerCloseIPv4) {
  SocketTest::TestServerCloseIPv4();
}

TEST_F(MacAsyncSocketTest, TestServerCloseIPv6) {
  SocketTest::TestServerCloseIPv6();
}

TEST_F(MacAsyncSocketTest, TestCloseInClosedCallbackIPv4) {
  SocketTest::TestCloseInClosedCallbackIPv4();
}

TEST_F(MacAsyncSocketTest, TestCloseInClosedCallbackIPv6) {
  SocketTest::TestCloseInClosedCallbackIPv6();
}

TEST_F(MacAsyncSocketTest, TestSocketServerWaitIPv4) {
  SocketTest::TestSocketServerWaitIPv4();
}

TEST_F(MacAsyncSocketTest, TestSocketServerWaitIPv6) {
  SocketTest::TestSocketServerWaitIPv6();
}

TEST_F(MacAsyncSocketTest, TestTcpIPv4) {
  SocketTest::TestTcpIPv4();
}

TEST_F(MacAsyncSocketTest, TestTcpIPv6) {
  SocketTest::TestTcpIPv6();
}

TEST_F(MacAsyncSocketTest, TestSingleFlowControlCallbackIPv4) {
  SocketTest::TestSingleFlowControlCallbackIPv4();
}

TEST_F(MacAsyncSocketTest, TestSingleFlowControlCallbackIPv6) {
  SocketTest::TestSingleFlowControlCallbackIPv6();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestUdpIPv4) {
  SocketTest::TestUdpIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestUdpIPv6) {
  SocketTest::TestUdpIPv6();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestGetSetOptionsIPv4) {
  SocketTest::TestGetSetOptionsIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestGetSetOptionsIPv6) {
  SocketTest::TestGetSetOptionsIPv6();
}

#ifndef CARBON_DEPRECATED
class MacCarbonAppAsyncSocketTest : public MacAsyncSocketTest {
  virtual MacBaseSocketServer* CreateSocketServer() {
    return new MacCarbonAppSocketServer();
  };
};

TEST_F(MacCarbonAppAsyncSocketTest, TestSocketServerWaitIPv4) {
  SocketTest::TestSocketServerWaitIPv4();
}

TEST_F(MacCarbonAppAsyncSocketTest, TestSocketServerWaitIPv6) {
  SocketTest::TestSocketServerWaitIPv6();
}
#endif
}  // namespace rtc
<commit_msg>disable MacAsyncSocketTest::TestConnectFailIPv6<commit_after>/*
 *  Copyright 2009 The WebRTC Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/base/gunit.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/base/socket_unittest.h"
#include "webrtc/base/thread.h"
#include "webrtc/base/macsocketserver.h"

namespace rtc {

class WakeThread : public Thread {
 public:
  WakeThread(SocketServer* ss) : ss_(ss) {
  }
  virtual ~WakeThread() {
    Stop();
  }
  void Run() {
    ss_->WakeUp();
  }
 private:
  SocketServer* ss_;
};

#ifndef CARBON_DEPRECATED

// Test that MacCFSocketServer::Wait works as expected.
TEST(MacCFSocketServerTest, TestWait) {
  MacCFSocketServer server;
  uint32 start = Time();
  server.Wait(1000, true);
  EXPECT_GE(TimeSince(start), 1000);
}

// Test that MacCFSocketServer::Wakeup works as expected.
TEST(MacCFSocketServerTest, TestWakeup) {
  MacCFSocketServer server;
  WakeThread thread(&server);
  uint32 start = Time();
  thread.Start();
  server.Wait(10000, true);
  EXPECT_LT(TimeSince(start), 10000);
}

// Test that MacCarbonSocketServer::Wait works as expected.
TEST(MacCarbonSocketServerTest, TestWait) {
  MacCarbonSocketServer server;
  uint32 start = Time();
  server.Wait(1000, true);
  EXPECT_GE(TimeSince(start), 1000);
}

// Test that MacCarbonSocketServer::Wakeup works as expected.
TEST(MacCarbonSocketServerTest, TestWakeup) {
  MacCarbonSocketServer server;
  WakeThread thread(&server);
  uint32 start = Time();
  thread.Start();
  server.Wait(10000, true);
  EXPECT_LT(TimeSince(start), 10000);
}

// Test that MacCarbonAppSocketServer::Wait works as expected.
TEST(MacCarbonAppSocketServerTest, TestWait) {
  MacCarbonAppSocketServer server;
  uint32 start = Time();
  server.Wait(1000, true);
  EXPECT_GE(TimeSince(start), 1000);
}

// Test that MacCarbonAppSocketServer::Wakeup works as expected.
TEST(MacCarbonAppSocketServerTest, TestWakeup) {
  MacCarbonAppSocketServer server;
  WakeThread thread(&server);
  uint32 start = Time();
  thread.Start();
  server.Wait(10000, true);
  EXPECT_LT(TimeSince(start), 10000);
}

#endif

// Test that MacAsyncSocket passes all the generic Socket tests.
class MacAsyncSocketTest : public SocketTest {
 protected:
  MacAsyncSocketTest()
      : server_(CreateSocketServer()),
        scope_(server_.get()) {}
  // Override for other implementations of MacBaseSocketServer.
  virtual MacBaseSocketServer* CreateSocketServer() {
    return new MacCFSocketServer();
  };
  rtc::scoped_ptr<MacBaseSocketServer> server_;
  SocketServerScope scope_;
};

TEST_F(MacAsyncSocketTest, TestConnectIPv4) {
  SocketTest::TestConnectIPv4();
}

TEST_F(MacAsyncSocketTest, TestConnectIPv6) {
  SocketTest::TestConnectIPv6();
}

TEST_F(MacAsyncSocketTest, TestConnectWithDnsLookupIPv4) {
  SocketTest::TestConnectWithDnsLookupIPv4();
}

TEST_F(MacAsyncSocketTest, TestConnectWithDnsLookupIPv6) {
  SocketTest::TestConnectWithDnsLookupIPv6();
}

// BUG=https://code.google.com/p/webrtc/issues/detail?id=2272
TEST_F(MacAsyncSocketTest, DISABLED_TestConnectFailIPv4) {
  SocketTest::TestConnectFailIPv4();
}

// Flaky. See webrtc:4738.
TEST_F(MacAsyncSocketTest, DISABLED_TestConnectFailIPv6) {
  SocketTest::TestConnectFailIPv6();
}

// Reenable once we have mac async dns
TEST_F(MacAsyncSocketTest, DISABLED_TestConnectWithDnsLookupFailIPv4) {
  SocketTest::TestConnectWithDnsLookupFailIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestConnectWithDnsLookupFailIPv6) {
  SocketTest::TestConnectWithDnsLookupFailIPv6();
}

TEST_F(MacAsyncSocketTest, TestConnectWithClosedSocketIPv4) {
  SocketTest::TestConnectWithClosedSocketIPv4();
}

TEST_F(MacAsyncSocketTest, TestConnectWithClosedSocketIPv6) {
  SocketTest::TestConnectWithClosedSocketIPv6();
}

// Flaky at the moment (10% failure rate).  Seems the client doesn't get
// signalled in a timely manner...
TEST_F(MacAsyncSocketTest, DISABLED_TestServerCloseDuringConnectIPv4) {
  SocketTest::TestServerCloseDuringConnectIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestServerCloseDuringConnectIPv6) {
  SocketTest::TestServerCloseDuringConnectIPv6();
}
// Flaky at the moment (0.5% failure rate).  Seems the client doesn't get
// signalled in a timely manner...
TEST_F(MacAsyncSocketTest, TestClientCloseDuringConnectIPv4) {
  SocketTest::TestClientCloseDuringConnectIPv4();
}

TEST_F(MacAsyncSocketTest, TestClientCloseDuringConnectIPv6) {
  SocketTest::TestClientCloseDuringConnectIPv6();
}

TEST_F(MacAsyncSocketTest, TestServerCloseIPv4) {
  SocketTest::TestServerCloseIPv4();
}

TEST_F(MacAsyncSocketTest, TestServerCloseIPv6) {
  SocketTest::TestServerCloseIPv6();
}

TEST_F(MacAsyncSocketTest, TestCloseInClosedCallbackIPv4) {
  SocketTest::TestCloseInClosedCallbackIPv4();
}

TEST_F(MacAsyncSocketTest, TestCloseInClosedCallbackIPv6) {
  SocketTest::TestCloseInClosedCallbackIPv6();
}

TEST_F(MacAsyncSocketTest, TestSocketServerWaitIPv4) {
  SocketTest::TestSocketServerWaitIPv4();
}

TEST_F(MacAsyncSocketTest, TestSocketServerWaitIPv6) {
  SocketTest::TestSocketServerWaitIPv6();
}

TEST_F(MacAsyncSocketTest, TestTcpIPv4) {
  SocketTest::TestTcpIPv4();
}

TEST_F(MacAsyncSocketTest, TestTcpIPv6) {
  SocketTest::TestTcpIPv6();
}

TEST_F(MacAsyncSocketTest, TestSingleFlowControlCallbackIPv4) {
  SocketTest::TestSingleFlowControlCallbackIPv4();
}

TEST_F(MacAsyncSocketTest, TestSingleFlowControlCallbackIPv6) {
  SocketTest::TestSingleFlowControlCallbackIPv6();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestUdpIPv4) {
  SocketTest::TestUdpIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestUdpIPv6) {
  SocketTest::TestUdpIPv6();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestGetSetOptionsIPv4) {
  SocketTest::TestGetSetOptionsIPv4();
}

TEST_F(MacAsyncSocketTest, DISABLED_TestGetSetOptionsIPv6) {
  SocketTest::TestGetSetOptionsIPv6();
}

#ifndef CARBON_DEPRECATED
class MacCarbonAppAsyncSocketTest : public MacAsyncSocketTest {
  virtual MacBaseSocketServer* CreateSocketServer() {
    return new MacCarbonAppSocketServer();
  };
};

TEST_F(MacCarbonAppAsyncSocketTest, TestSocketServerWaitIPv4) {
  SocketTest::TestSocketServerWaitIPv4();
}

TEST_F(MacCarbonAppAsyncSocketTest, TestSocketServerWaitIPv6) {
  SocketTest::TestSocketServerWaitIPv6();
}
#endif
}  // namespace rtc
<|endoftext|>


<commit_before>//===- OpStats.cpp - Prints stats of operations in module -----------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================

#include "mlir/IR/CFGFunction.h"
#include "mlir/IR/MLFunction.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/Statements.h"
#include "mlir/IR/StmtVisitor.h"
#include "mlir/Pass.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/raw_ostream.h"

using namespace mlir;

namespace {
struct PrintOpStatsPass : public FunctionPass, StmtWalker<PrintOpStatsPass> {
  explicit PrintOpStatsPass(llvm::raw_ostream &os = llvm::errs())
      : FunctionPass(&PrintOpStatsPass::passID), os(os) {}

  // Prints the resultant operation stats post iterating over the module.
  PassResult runOnModule(Module *m) override;

  // Process CFG function considering the instructions in basic blocks.
  PassResult runOnCFGFunction(CFGFunction *function) override;

  // Process ML functions and operation statments in ML functions.
  PassResult runOnMLFunction(MLFunction *function) override;
  void visitOperationStmt(OperationStmt *stmt);

  // Print summary of op stats.
  void printSummary();

  static char passID;

private:
  llvm::StringMap<int64_t> opCount;

  llvm::raw_ostream &os;
};
} // namespace

char PrintOpStatsPass::passID = 0;

PassResult PrintOpStatsPass::runOnModule(Module *m) {
  auto result = FunctionPass::runOnModule(m);
  if (!result)
    printSummary();
  return result;
}

PassResult PrintOpStatsPass::runOnCFGFunction(CFGFunction *function) {
  for (const auto &bb : *function)
    for (const auto &inst : bb)
      ++opCount[inst.getName().getStringRef()];
  return success();
}

void PrintOpStatsPass::visitOperationStmt(OperationStmt *stmt) {
  ++opCount[stmt->getName().getStringRef()];
}

PassResult PrintOpStatsPass::runOnMLFunction(MLFunction *function) {
  walk(function);
  return success();
}

void PrintOpStatsPass::printSummary() {
  os << "Operations encountered:\n";
  os << "-----------------------\n";
  std::vector<StringRef> sorted(opCount.keys().begin(), opCount.keys().end());
  llvm::sort(sorted);

  // Returns the lenght of the dialect prefix of an op.
  auto dialectLen = [](StringRef opName) -> size_t {
    auto dialectEnd = opName.find_last_of('.');
    if (dialectEnd == StringRef::npos)
      return 0;
    // Count the periond too.
    return dialectEnd + 1;
  };

  // Left-align the names (aligning on the dialect) and right-align count below.
  // The alignment is for readability and does not affect CSV/FileCheck parsing.
  size_t maxLenName = 0;
  size_t maxLenNamePrefixLen = 0;
  size_t maxLenDialect = 0;
  int maxLenCount = 0;
  for (const auto &key : sorted) {
    size_t len = key.size();
    size_t prefix = dialectLen(key);
    if (len > maxLenName) {
      maxLenName = len;
      maxLenNamePrefixLen = prefix;
    }
    maxLenDialect = max(maxLenDialect, prefix);
    // This takes advantage of the fact that opCount[key] > 0.
    maxLenCount = max(maxLenCount, (int)log10(opCount[key]) + 1);
  }
  // Adjust the max name length to account for the dialect.
  maxLenName += (maxLenDialect - maxLenNamePrefixLen);

  for (const auto &key : sorted) {
    size_t prefix = maxLenDialect - dialectLen(key);
    os.indent(2 + prefix) << '\'' << key << '\'';
    os.indent(maxLenName - key.size() - prefix) << " ,";
    os.indent(maxLenCount - (int)log10(opCount[key])) << opCount[key] << "\n";
  }
}

static PassRegistration<PrintOpStatsPass>
    pass("print-op-stats", "Print statistics of operations");
<commit_msg>Fix off by one in OpStats.<commit_after>//===- OpStats.cpp - Prints stats of operations in module -----------------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================

#include "mlir/IR/CFGFunction.h"
#include "mlir/IR/MLFunction.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/Statements.h"
#include "mlir/IR/StmtVisitor.h"
#include "mlir/Pass.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/raw_ostream.h"

using namespace mlir;

namespace {
struct PrintOpStatsPass : public FunctionPass, StmtWalker<PrintOpStatsPass> {
  explicit PrintOpStatsPass(llvm::raw_ostream &os = llvm::errs())
      : FunctionPass(&PrintOpStatsPass::passID), os(os) {}

  // Prints the resultant operation stats post iterating over the module.
  PassResult runOnModule(Module *m) override;

  // Process CFG function considering the instructions in basic blocks.
  PassResult runOnCFGFunction(CFGFunction *function) override;

  // Process ML functions and operation statments in ML functions.
  PassResult runOnMLFunction(MLFunction *function) override;
  void visitOperationStmt(OperationStmt *stmt);

  // Print summary of op stats.
  void printSummary();

  static char passID;

private:
  llvm::StringMap<int64_t> opCount;

  llvm::raw_ostream &os;
};
} // namespace

char PrintOpStatsPass::passID = 0;

PassResult PrintOpStatsPass::runOnModule(Module *m) {
  auto result = FunctionPass::runOnModule(m);
  if (!result)
    printSummary();
  return result;
}

PassResult PrintOpStatsPass::runOnCFGFunction(CFGFunction *function) {
  for (const auto &bb : *function)
    for (const auto &inst : bb)
      ++opCount[inst.getName().getStringRef()];
  return success();
}

void PrintOpStatsPass::visitOperationStmt(OperationStmt *stmt) {
  ++opCount[stmt->getName().getStringRef()];
}

PassResult PrintOpStatsPass::runOnMLFunction(MLFunction *function) {
  walk(function);
  return success();
}

void PrintOpStatsPass::printSummary() {
  os << "Operations encountered:\n";
  os << "-----------------------\n";
  std::vector<StringRef> sorted(opCount.keys().begin(), opCount.keys().end());
  llvm::sort(sorted);

  // Returns the lenght of the dialect prefix of an op.
  auto dialectLen = [](StringRef opName) -> size_t {
    auto dialectEnd = opName.find_last_of('.');
    if (dialectEnd == StringRef::npos)
      return 0;
    // Count the period too.
    return dialectEnd + 1;
  };

  // Left-align the names (aligning on the dialect) and right-align count below.
  // The alignment is for readability and does not affect CSV/FileCheck parsing.
  size_t maxLenName = 0;
  size_t maxLenNamePrefixLen = 0;
  size_t maxLenDialect = 0;
  int maxLenCount = 0;
  for (const auto &key : sorted) {
    size_t len = key.size();
    size_t prefix = dialectLen(key);
    if (len > maxLenName) {
      maxLenName = len;
      maxLenNamePrefixLen = prefix;
    }
    maxLenDialect = max(maxLenDialect, prefix);
    // This takes advantage of the fact that opCount[key] > 0.
    maxLenCount = max(maxLenCount, (int)log10(opCount[key]) + 1);
  }
  // Adjust the max name length to account for the dialect.
  maxLenName += (maxLenDialect - maxLenNamePrefixLen);

  for (const auto &key : sorted) {
    size_t prefix = maxLenDialect - dialectLen(key);
    os.indent(2 + prefix) << '\'' << key << '\'';
    // Add one to compensate for the period of the dialect.
    os.indent(maxLenName + 1 - key.size() - prefix) << " ,";
    os.indent(maxLenCount - (int)log10(opCount[key])) << opCount[key] << "\n";
  }
}

static PassRegistration<PrintOpStatsPass>
    pass("print-op-stats", "Print statistics of operations");
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 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) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.1  1999/11/09 01:04:45  twl
 * Initial revision
 *
 * Revision 1.2  1999/11/08 20:45:09  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/XML4CDefs.hpp>
#include <util/PlatformUtils.hpp>
#include <util/Mutexes.hpp>

// ---------------------------------------------------------------------------
//  XMLMutex: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLMutex::XMLMutex() :

    fHandle(0)
{
}

XMLMutex::~XMLMutex()
{
    if (fHandle)
    {
        XMLPlatformUtils::closeMutex(fHandle);
        fHandle = 0;
    }
}

// ---------------------------------------------------------------------------
//  XMLMutex: Lock control methods
// ---------------------------------------------------------------------------
void XMLMutex::lock()
{
    if (!fHandle)
    {
        void* tmpHandle = XMLPlatformUtils::makeMutex();
        if (XMLPlatformUtils::compareAndSwap(&fHandle, tmpHandle, 0) != 0)
            XMLPlatformUtils::closeMutex(tmpHandle);
    }
    XMLPlatformUtils::lockMutex(fHandle);
}

void XMLMutex::unlock()
{
    XMLPlatformUtils::unlockMutex(fHandle);
}

// ---------------------------------------------------------------------------
//  XMLMutexLock: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLMutexLock::XMLMutexLock(XMLMutex* const toLock) :

    fToLock(toLock)
{
    fToLock->lock();
}

XMLMutexLock::~XMLMutexLock()
{
    fToLock->unlock();
}
<commit_msg>Got rid of attempts to fancy/schmanzy lazy eval mutex implementation and just force anyone who needs a global/static mutex to lazy eval that themselves.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 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) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.2  1999/12/02 19:42:35  roddey
 * Got rid of attempts to fancy/schmanzy lazy eval mutex implementation and just
 * force anyone who needs a global/static mutex to lazy eval that themselves.
 *
 * Revision 1.1.1.1  1999/11/09 01:04:45  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:09  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <util/XML4CDefs.hpp>
#include <util/PlatformUtils.hpp>
#include <util/Mutexes.hpp>

// ---------------------------------------------------------------------------
//  XMLMutex: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLMutex::XMLMutex() :

    fHandle(0)
{
    // Ask the per-platform driver to make us a mutex
    fHandle = XMLPlatformUtils::makeMutex();
}

XMLMutex::~XMLMutex()
{
    if (fHandle)
    {
        XMLPlatformUtils::closeMutex(fHandle);
        fHandle = 0;
    }
}

// ---------------------------------------------------------------------------
//  XMLMutex: Lock control methods
// ---------------------------------------------------------------------------
void XMLMutex::lock()
{
    XMLPlatformUtils::lockMutex(fHandle);
}

void XMLMutex::unlock()
{
    XMLPlatformUtils::unlockMutex(fHandle);
}

// ---------------------------------------------------------------------------
//  XMLMutexLock: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLMutexLock::XMLMutexLock(XMLMutex* const toLock) :

    fToLock(toLock)
{
    fToLock->lock();
}

XMLMutexLock::~XMLMutexLock()
{
    fToLock->unlock();
}
<|endoftext|>


<commit_before>// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

#include "examples/anim_util.h"
#include "imageio/imageio_util.h"
#include "webp/demux.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  // WebPAnimDecoderGetInfo() is too late to check the canvas size as
  // WebPAnimDecoderNew() will handle the allocations.
  WebPBitstreamFeatures features;
  if (WebPGetFeatures(data, size, &features) == VP8_STATUS_OK) {
    if (!ImgIoUtilCheckSizeArgumentsOverflow(features.width * 4,
                                             features.height)) {
      return 0;
    }
  }

  // decode everything as an animation
  WebPData webp_data = { data, size };
  WebPAnimDecoder* const dec = WebPAnimDecoderNew(&webp_data, NULL);
  if (dec == NULL) return 0;

  WebPAnimInfo info;
  if (!WebPAnimDecoderGetInfo(dec, &info)) return 0;
  if (!ImgIoUtilCheckSizeArgumentsOverflow(info.canvas_width * 4,
                                           info.canvas_height)) {
    return 0;
  }

  while (WebPAnimDecoderHasMoreFrames(dec)) {
    uint8_t* buf;
    int timestamp;
    if (!WebPAnimDecoderGetNext(dec, &buf, &timestamp)) break;
  }
  WebPAnimDecoderDelete(dec);
  return 0;
}
<commit_msg>animdecoder_fuzzer: fix memory leak<commit_after>// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

#include "examples/anim_util.h"
#include "imageio/imageio_util.h"
#include "webp/demux.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  // WebPAnimDecoderGetInfo() is too late to check the canvas size as
  // WebPAnimDecoderNew() will handle the allocations.
  WebPBitstreamFeatures features;
  if (WebPGetFeatures(data, size, &features) == VP8_STATUS_OK) {
    if (!ImgIoUtilCheckSizeArgumentsOverflow(features.width * 4,
                                             features.height)) {
      return 0;
    }
  }

  // decode everything as an animation
  WebPData webp_data = { data, size };
  WebPAnimDecoder* const dec = WebPAnimDecoderNew(&webp_data, NULL);
  if (dec == NULL) return 0;

  WebPAnimInfo info;
  if (!WebPAnimDecoderGetInfo(dec, &info)) goto End;
  if (!ImgIoUtilCheckSizeArgumentsOverflow(info.canvas_width * 4,
                                           info.canvas_height)) {
    goto End;
  }

  while (WebPAnimDecoderHasMoreFrames(dec)) {
    uint8_t* buf;
    int timestamp;
    if (!WebPAnimDecoderGetNext(dec, &buf, &timestamp)) break;
  }
 End:
  WebPAnimDecoderDelete(dec);
  return 0;
}
<|endoftext|>