コード例 #1
0
ファイル: swipl-ld.c プロジェクト: ddgold/design_patterns
void
linkBaseExecutable()
{ char *cout = out;

#if !defined(HOST_OS_WINDOWS)			/* bit of a hack ... */
  if ( embed_shared )
  { linkSharedObject();
    return;
  }
#endif

#if defined(HOST_TOOLCHAIN_MSC)
{ char tmp[MAXPATHLEN];
  sprintf(tmp, "/out:%s", cout);
  prependArgList(&ldoptions, tmp);
}
  concatArgList(&ldoptions, "", &ofiles);	/* object files */
  exportlibdirs();
  if ( !nolibswipl )
  { appendArgList(&ldoptions, pllib);		/* -lswipl */
    addOptionString(pllibs);
  }
  concatArgList(&ldoptions, "", &libs);		/* libraries */
  concatArgList(&ldoptions, "", &lastlibs);	/* libraries */
#else /* !defined(HOST_TOOLCHAIN_MSC) */
  prependArgList(&ldoptions, cout);
  prependArgList(&ldoptions, "-o");		/* -o ctmp */
  concatArgList(&ldoptions, "", &ofiles);	/* object files */
  concatArgList(&ldoptions, "-L", &libdirs);    /* library directories */
  if ( !nolibswipl )
  { appendArgList(&ldoptions, pllib);		/* -lswipl */
    addOptionString(pllibs);
  }
  concatArgList(&ldoptions, "", &libs);		/* libraries */
  concatArgList(&ldoptions, "", &lastlibs);	/* libraries */
#endif /* !defined(HOST_TOOLCHAIN_MSC) */

  if ( !nostate )
  {
#if defined(HOST_TOOLCHAIN_MSC)
    if ( !embed_shared )
    { char buf[MAXPATHLEN];
      appendArgList(&tmpfiles, replaceExtension(cout, "exp", buf));
      appendArgList(&tmpfiles, replaceExtension(cout, "lib", buf));
    }
#endif
  }

  callprog(ld, &ldoptions);
}
コード例 #2
0
ファイル: mainwindow.cpp プロジェクト: xoreos/phaethon
void MainWindow::exportBMUMP3() {
	if (!_currentItem)
		return;

	assert(_currentItem->getFileType() == Aurora::kFileTypeBMU);

	QString fileName = QFileDialog::getSaveFileName(this,
		tr("Save MP3 file"),
		replaceExtension(_currentItem->getName(), Aurora::kFileTypeMP3),
		tr("MP3 file (*.mp3)"));

	if (fileName.isEmpty())
		return;

	_status.push(constructStatus("Exporting", _currentItem->getName(), fileName));
	BOOST_SCOPE_EXIT((&_status)) {
		_status.pop();
	} BOOST_SCOPE_EXIT_END

	try {
		std::unique_ptr<Common::SeekableReadStream> res(_currentItem->getResourceData());

		Common::WriteFile file(fileName.toStdString());

		exportBMUMP3Impl(*res, file);
		file.flush();

	} catch (Common::Exception &e) {
		Common::printException(e, "WARNING: ");
		return;
	}
}
コード例 #3
0
ファイル: mainwindow.cpp プロジェクト: xoreos/phaethon
void MainWindow::exportWAV() {
	if (!_currentItem)
		return;

	assert(_currentItem->getResourceType() == Aurora::kResourceSound);

	QString fileName = QFileDialog::getSaveFileName(this,
		tr("Save PCM WAV file"),
		replaceExtension(_currentItem->getName(), Aurora::kFileTypeWAV),
		tr("WAV file (*.wav)"));

	if (fileName.isEmpty())
		return;

	_status.push(constructStatus("Exporting", _currentItem->getName(), fileName));
	BOOST_SCOPE_EXIT((&_status)) {
		_status.pop();
	} BOOST_SCOPE_EXIT_END

	try {
		std::unique_ptr<Sound::AudioStream> sound(_currentItem->getAudioStream());

		Common::WriteFile file(fileName.toStdString());

		exportWAVImpl(sound.get(), file);
		file.flush();

	} catch (Common::Exception &e) {
		Common::printException(e, "WARNING: ");
		return;
	}
}
コード例 #4
0
ファイル: mainwindow.cpp プロジェクト: xoreos/phaethon
void MainWindow::exportTGA() {
	if (!_currentItem)
		return;

	assert(_currentItem->getResourceType() == Aurora::kResourceImage);

	QString fileName = QFileDialog::getSaveFileName(this,
		tr("Save TGA file"),
		replaceExtension(_currentItem->getName(), Aurora::kFileTypeTGA),
		tr("TGA file (*.tga)"));

	if (fileName.isEmpty())
		return;

	_status.push(constructStatus("Exporting", _currentItem->getName(), fileName));
	BOOST_SCOPE_EXIT((&_status)) {
		_status.pop();
	} BOOST_SCOPE_EXIT_END

	try {
		std::unique_ptr<Images::Decoder> image(_currentItem->getImage());

		image->dumpTGA(fileName.toStdString());

	} catch (Common::Exception &e) {
		Common::printException(e, "WARNING: ");
	}
}
コード例 #5
0
ファイル: mdx2midi.cpp プロジェクト: fourks/mdxtools
int main(int argc, char **argv) {
	for(int i = 1; i < argc; i++) {
		try {
			MDXMidi m;
			m.open(argv[i], replaceExtension(argv[i], "mid"));
		} catch(exceptionf e) {
			fprintf(stderr, "Error: %s\n", e.what());
		}
	}
	return 0;
}
コード例 #6
0
ファイル: swipl-ld.c プロジェクト: ddgold/design_patterns
void
saveExportLib()
{ char ibuf[MAXPATHLEN];
  char obuf[MAXPATHLEN];
  char *ilib, *olib;

  ilib = replaceExtension(ctmp, "lib", ibuf);
  olib = replaceExtension(out, "lib", obuf);

  if ( verbose )
  { printf("\tren \"%s\" \"%s\"\n", ilib, olib);
  }

  if ( !fake )
  { if ( rename(ilib, olib) != 0 )
    { fprintf(stderr, "Could not rename export lib %s to %s: %s\n",
	      ilib, olib, oserror());
      error(1);
    }
  }
}
コード例 #7
0
ファイル: Rom.cpp プロジェクト: dezgeg/yagb
void Rom::setupSaveRam(char const* name) {
    std::string saveRamFile = replaceExtension(name, "sav");

    saveRamFd = open(saveRamFile.c_str(), O_CREAT | O_RDWR, 0644);
    if (saveRamFd < 0) {
        throw "Can't open save RAM file";
    }
    if (ftruncate(saveRamFd, MAX_SAVE_RAM_SIZE) < 0) {
        throw "Can't resize save RAM file";
    }
    saveRamData = (Byte*)mmap(nullptr, MAX_SAVE_RAM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, saveRamFd, 0);
    if (saveRamData == MAP_FAILED) {
        throw "Can't mmap save RAM file";
    }
}
コード例 #8
0
ファイル: DC_main.cpp プロジェクト: 299299/NagaGame
void resources_process()
{
    StringArray input_file_list;
    scan_dir(input_file_list, g_config->m_inputDir.c_str(), "*", SCAN_FILES, true);

    LOGI("input file num = %d.", input_file_list.size());
    bool shaderIncludedAdded = false;

    for (size_t i=0; i<input_file_list.size(); ++i)
    {
        const std::string& input = input_file_list[i];
        std::string ext = getFileExt(input);
        if(ext == EngineNames::LEVEL)
            continue;
        BaseCompiler* compiler = g_config->create_compiler(ext);
        if(!compiler)
        {
            LOGW("can not find any compiler for this resource %s.", input.c_str());
            continue;
        }
        std::string output = input_to_output(input);
        if(ext == "dds") output =
            replaceExtension(output, EngineNames::TEXTURE);
        compiler->m_input = input;
        compiler->m_output = output;
        if(!compiler->checkProcessing())
        {
            delete compiler;
            continue;
        }
        LOGI("data compile %s --> %s", input.c_str(), output.c_str());
        g_config->m_compilers.push_back(compiler);
    }
    for(size_t i=0; i<g_config->m_compilers.size(); ++i)
    {
        g_config->m_compilers[i]->preProcess();
    }
}
コード例 #9
0
ファイル: simulator.c プロジェクト: alaindomissy/nanoengineer
int
main(int argc, char **argv)
{
    struct part *part;
    int opt, n;
    int dump_part = 0;
    int printStructurePotentialEnergy = 0;
    int needVDW = 1;
    char *printPotential = NULL;
    double printPotentialInitial = -1; // pm
    double printPotentialIncrement = -1; // pm
    double printPotentialLimit = -1; // pm
    char *fileNameTemplate = NULL;
    char *outputFilename = NULL;
	
    reinit_globals();

    if (signal(SIGTERM, &SIGTERMhandler) == SIG_ERR) {
        perror("signal(SIGTERM)");
        exit(1);
    }
    
    CommandLine = assembleCommandLine(argc, argv);
    while ((opt = getopt_long(argc, argv,
			    "hnmEi:f:s:t:xXONI:K:rD:o:q:B:",
			    option_vec, NULL)) != -1) {
	switch(opt) {
	case 'h':
	    usage();
	case OPT_DUMP_PART:
	    dump_part = 1;
	    break;
	case OPT_WRITE_GROMACS_TOPOLOGY:
	    GromacsOutputBaseName = optarg;
	    break;
	case OPT_PATH_TO_CPP:
	    PathToCpp = optarg;
	    break;
	case OPT_SYSTEM_PARAMETERS:
	    SystemParametersFileName = optarg;
	    break;
        case OPT_PRINT_POTENTIAL:
            printPotential = optarg;
	    break;
        case OPT_INITIAL:
	    printPotentialInitial = atof(optarg);
	    break;
        case OPT_INCREMENT:
	    printPotentialIncrement = atof(optarg);
	    break;
        case OPT_LIMIT:
	    printPotentialLimit = atof(optarg);
	    break;
        case OPT_DIRECT_EVALUATE:
            DirectEvaluate = 1;
	    break;
        case OPT_INTERPOLATE:
            DirectEvaluate = 0;
	    break;
        case OPT_SIMPLE_MOVIE_FORCE_SCALE:
            SimpleMovieForceScale = atof(optarg);
            break;
        case OPT_MIN_THRESH_CUT_RMS:
            MinimizeThresholdCutoverRMS = atof(optarg);
            break;
        case OPT_MIN_THRESH_CUT_MAX:
            MinimizeThresholdCutoverMax = atof(optarg);
            break;
        case OPT_MIN_THRESH_END_RMS:
            MinimizeThresholdEndRMS = atof(optarg);
            break;
        case OPT_MIN_THRESH_END_MAX:
            MinimizeThresholdEndMax = atof(optarg);
            break;
        case OPT_VDW_CUTOFF_RADIUS:
            VanDerWaalsCutoffRadius = atof(optarg);
            break;
        case OPT_VDW_CUTOFF_FACTOR:
            VanDerWaalsCutoffFactor = atof(optarg);
            break;
        case OPT_ENABLE_ELECTROSTATIC:
            EnableElectrostatic = atoi(optarg);
            break;
        case OPT_TIME_REVERSAL:
            TimeReversal = 1;
            break;
        case OPT_THERMOSTAT_GAMMA:
            ThermostatGamma = atof(optarg);
            break;
        case OPT_PRINT_ENERGIES:
            PrintPotentialEnergy = 1;
            break;
        case OPT_NEIGHBOR_SEARCHING:
            NeighborSearching = atoi(optarg);
            break;
	case 'n':
	    // ignored
	    break;
	case 'm':
	    ToMinimize=1;
	    break;
	case 'E':
	    printStructurePotentialEnergy=1;
	    break;
	case 'i':
	    IterPerFrame = atoi(optarg);
	    break;
	case 'f':
	    NumFrames = atoi(optarg);
	    break;
	case 's':
	    Dt = atof(optarg);
	    break;
	case 't':
	    Temperature = atof(optarg);
	    break;
	case 'x':
	    DumpAsText = 1;
	    break;
	case 'X':
	    DumpIntermediateText = 1;
	    break;
	case 'O':
	    OutputFormat = 1;
	    break;
	case 'N':
	    OutputFormat = 2;
	    break;
	case OPT_OUTPUT_FORMAT_3:
	    OutputFormat = 3;
	    break;
	case 'I':
	    IDKey = optarg;
	    break;
	case 'K':
	    KeyRecordInterval = atoi(optarg);
	    break;
	case 'r':
	    PrintFrameNums = 1;
	    break;
	case 'D':
	    n = atoi(optarg);
	    if (n < 32 && n >= 0) {
		debug_flags |= 1 << n;
	    }
	    break;
	case 'o':
	    outputFilename = optarg;
	    break;
	case 'q':
	    TraceFileName = optarg;
	    break;
	case 'B':
	    BaseFileName = optarg;
	    break;
        case ':':
        case '?':
	default:
	    usage();
	    exit(1);
	}
    }
    if (optind + 1 == argc) {   // (optind < argc) if not paranoid
	fileNameTemplate = argv[optind];
    }

    if (DEBUG(D_PRINT_BEND_STRETCH)) { // -D8
        initializeBondTable();
        printBendStretch();
        exit(0);
    }

    if (DumpAsText) {
        OutputFormat = 0;
    }

    if (!fileNameTemplate) {
        usage();
    }
    InputFileName = replaceExtension(fileNameTemplate, "mmp");

    if (BaseFileName != NULL) {
        int i1;
        int i2;
        struct xyz *basePositions;
        struct xyz *initialPositions;
        
        basePositions = readXYZ(BaseFileName, &i1);
        if (basePositions == NULL) {
            fprintf(stderr, "could not read base positions file from -B<filename>\n");
            exit(1);
        }
        initialPositions = readXYZ(InputFileName, &i2);
        if (initialPositions == NULL) {
            fprintf(stderr, "could not read comparison positions file\n");
            exit(1);
        }
        if (i1 != i2) {
            fprintf(stderr, "structures to compare must have same number of atoms\n");
            exit(1);
        }
        exit(doStructureCompare(i1, basePositions, initialPositions,
                                NumFrames, 1e-8, 1e-4, 1.0+1e-4));
    }

    if (outputFilename) {
        OutputFileName = copy_string(outputFilename);
    } else {
        char *extension;
        
        switch (OutputFormat) {
        case 0:
            extension = "xyz";
            break;
        case 1:
        case 2:
        default:
            extension = "dpb";
            break;
        case 3:
            extension = "gro";
            break;
        }
        
        OutputFileName = replaceExtension(fileNameTemplate, extension);
    }

    if (TraceFileName) {
        TraceFile = fopen(TraceFileName, "w");
        if (TraceFile == NULL) {
            perror(TraceFileName);
            exit(1);
        }
    } else {
        TraceFile = fdopen(1, "w");
        if (TraceFile == NULL) {
            perror("fdopen stdout as TraceFile");
            exit(1);
        }
    }
    traceFileVersion(); // call this before any other writes to trace file.
    // tell where and how the simulator was built. We never build the
    // standalone simulator with distutils.
    fprintf(TraceFile, "%s", tracePrefix);

    initializeBondTable();

    if (IterPerFrame <= 0) IterPerFrame = 1;

    if (printPotential) {
        printPotentialAndGradientFunctions(printPotential,
                                           printPotentialInitial,
                                           printPotentialIncrement,
                                           printPotentialLimit);
        exit(0);
    }
    
    part = readMMP(InputFileName);
    if (EXCEPTION) {
        exit(1);
    }
    if (GromacsOutputBaseName != NULL) {
        needVDW = 0;
    }
    initializePart(part, needVDW);
    createPatterns();
    matchPartToAllPatterns(part);
    
    if (printStructurePotentialEnergy) {
        struct xyz *force = (struct xyz *)allocate(sizeof(struct xyz) * part->num_atoms);
        double potentialEnergy = calculatePotential(part, part->positions);
        calculateGradient(part, part->positions, force);
        printf("%e %e %e %e (Potential energy in aJ, gradient of atom 1)\n", potentialEnergy, force[1].x, force[1].y, force[1].z);
        exit(0);
    }
    
    if (dump_part) {
        //
        // this segment is convenient to run valgrind on to test the
        // part and bond table destructors.  By the time we reach the
        // exit() there should be no malloc'd blocks remaining.
        //
        // valgrind -v --leak-check=full --leak-resolution=high --show-reachable=yes simulator --dump-part part.mmp
        //
        printPart(stdout, part);
        destroyPart(part);
        part = NULL;
        destroyBondTable();
        fclose(TraceFile);
        destroyAccumulator(CommandLine);
        free(InputFileName);
        free(OutputFileName);
        exit(0);
    }

    if (GromacsOutputBaseName != NULL) {
        printGromacsToplogy(GromacsOutputBaseName, part);
        destroyPart(part);
        part = NULL;
        destroyBondTable();
        fclose(TraceFile);
        destroyAccumulator(CommandLine);
        free(InputFileName);
        free(OutputFileName);
        done("");
        exit(0);
    }

    constrainGlobals();
    traceHeader(part);

    if  (ToMinimize) {
	NumFrames = max(NumFrames,(int)sqrt((double)part->num_atoms));
	Temperature = 0.0;
    } else {
        traceJigHeader(part);
    }

    OutputFile = fopen(OutputFileName, DumpAsText ? "w" : "wb");
    if (OutputFile == NULL) {
        perror(OutputFileName);
        exit(1);
    }
    writeOutputHeader(OutputFile, part);

    if  (ToMinimize) {
	minimizeStructure(part);
	exit(0);
    }
    else {
        dynamicsMovie(part);
    }

    done("");
    return 0;
}
コード例 #10
0
std::string PECOFFLinkingContext::getPDBFilePath() const {
  assert(_debug);
  if (!_pdbFilePath.empty())
    return _pdbFilePath;
  return replaceExtension(outputPath(), ".pdb");
}
コード例 #11
0
std::string PECOFFLinkingContext::getOutputImportLibraryPath() const {
  if (!_implib.empty())
    return _implib;
  return replaceExtension(outputPath(), ".lib");
}
コード例 #12
0
ファイル: swipl-ld.c プロジェクト: ddgold/design_patterns
static void
fillDefaultOptions()
{ char tmp[1024];
  char *defcxx = PROG_CXX;

  defaultProgram(&cc,  PROG_CC);
  if ( streq(cc, "gcc") )			/* TBD: MINGW */
    defcxx = "g++";
  defaultProgram(&cxx, defcxx);

  if ( !ld )				/* not specified */
  { ld = (shared ? SO_LD : PROG_LD);

    if ( cppfiles.size > 0 && streq(ld, cc) )
      ld = cxx;
  }

#if defined(HOST_TOOLCHAIN_MSC)
  if ( strcmp(LIB_PL_DEBUG,pllib) == 0 )
    ensureOption(&coptions, "/MDd");
  else ensureOption(&coptions, "/MD");
  ensureOption(&coptions, "/D__WINDOWS__");
  ensureOption(&coptions, "/nologo");
  ensureOption(&ldoptions, "/nologo");
#endif

  tmpPath(&ctmp,   "ctmp-");
  tmpPath(&pltmp,  "pltmp-");
#if defined(__CYGWIN__)
/* Compile generates .exe files on Cygwin */
  replaceExtension(ctmp, "exe", tmp);
  free(ctmp);
  ctmp = strdup(tmp);
#endif
#if defined(HOST_OS_WINDOWS)
/* Saved states have the .exe extension under Windows */
  replaceExtension(pltmp, "exe", tmp);
  free(pltmp);
  pltmp = strdup(tmp);
#endif
  if ( shared && !out && !nolink )
  { fprintf(stderr, "%s: \"-o out\" required for linking shared object\n", plld);
    exit(1);
  }
#if defined(HOST_OS_WINDOWS)
  if ( out && !nolink )
  { replaceExtension(out, shared || embed_shared ? "dll" : "exe", tmp);
    out = strdup(tmp);
  }
#endif
  defaultPath(&out, PROG_OUT);

  defaultProgram(&plgoal,     "version");
  defaultProgram(&pltoplevel, "prolog");
  defaultProgram(&plinitfile, "none");
  defaultProgram(&plsysinit,  "none");

#ifdef __WINDOWS__
  sprintf(tmp, "%s/lib", plbase);
#else
  sprintf(tmp, "%s/lib/%s", plbase, plarch);
#endif
  prependArgList(&libdirs, tmp);
  sprintf(tmp, "%s/include", plbase);
  prependArgList(&includedirs, tmp);
}
コード例 #13
0
ファイル: swipl-ld.c プロジェクト: ddgold/design_patterns
void
linkSharedObject()
{ char soname[MAXPATHLEN];
  char *soout;

  if ( !soext )
    soext = SO_EXT;

  if ( file_name_extension(out) )
  { soout = out;
  } else
  { soout = replaceExtension(out, soext, soname);
  }

#if defined(HOST_TOOLCHAIN_MSC)
  prependArgList(&ldoptions, "/dll");
{ char tmp[MAXPATHLEN];
  sprintf(tmp, "/out:%s", soout);
  prependArgList(&ldoptions, tmp);
}
  concatArgList(&ldoptions, "", &ofiles);	/* object files */
  exportlibdirs();
  if ( !nolibswipl )
  { appendArgList(&ldoptions, pllib);		/* swipl.lib */
    addOptionString(pllibs);
  }
  concatArgList(&ldoptions, "", &libs);		/* libraries */
  concatArgList(&ldoptions, "", &lastlibs);	/* libraries */
#else /* !defined(HOST_TOOLCHAIN_MSC) */
#ifdef __CYGWIN__
  prependArgList(&ldoptions, SO_LDFLAGS);
  prependArgList(&ldoptions, soout);
  prependArgList(&ldoptions, "-o");		/* -o ctmp */
  concatArgList(&ldoptions, "", &ofiles);	/* object files */
  if ( !nolibswipl )
  { appendArgList(&ldoptions, pllib);		/* -lswipl */
    addOptionString(pllibs);
  }
  concatArgList(&ldoptions, "-L", &libdirs);    /* library directories */
  concatArgList(&ldoptions, "", &libs);		/* libraries */
  concatArgList(&ldoptions, "", &lastlibs);	/* libraries */
#else /*__CYGWIN__*/
#ifdef SO_FORMAT_LDFLAGS			/* must specify output too */
  { char tmp[MAXPATHLEN];
    tmp[0] = UNQUOTED;
    sprintf(&tmp[1], SO_FORMAT_LDFLAGS);
    prependArgList(&ldoptions, tmp);
  }
#else
  prependArgList(&ldoptions, SO_LDFLAGS);
  prependArgList(&ldoptions, soout);
  prependArgList(&ldoptions, "-o");		/* -o ctmp */
#endif /*SO_FORMAT_LDFLAGS*/
  concatArgList(&ldoptions, "", &ofiles);	/* object files */
  concatArgList(&ldoptions, "-L", &libdirs);    /* library directories */
  concatArgList(&ldoptions, "", &libs);		/* libraries */
#ifdef O_SHARED_KERNEL
  if ( !nolibswipl )
#endif
  { appendArgList(&ldoptions, pllib);		/* -lswipl */
  }
  concatArgList(&ldoptions, "", &lastlibs);	/* libraries */
#ifdef __BEOS__
  appendArgList(&ldoptions, plexe);		/* last is executable */
#endif
#endif /*__CYGWIN__*/
#endif /* !defined(HOST_TOOLCHAIN_MSC) */

  callprog(ld, &ldoptions);
}
コード例 #14
0
ファイル: search.cpp プロジェクト: UIKit0/qgrep
unsigned int searchProject(Output* output_, const char* file, const char* string, unsigned int options, unsigned int limit, const char* include, const char* exclude)
{
	SearchOutput output(output_, options, limit);
	std::unique_ptr<Regex> regex(createRegex(string, getRegexOptions(options)));
	std::unique_ptr<Regex> includeRe(include ? createRegex(include, RO_IGNORECASE) : 0);
	std::unique_ptr<Regex> excludeRe(exclude ? createRegex(exclude, RO_IGNORECASE) : 0);
	NgramRegex ngregex((options & SO_BRUTEFORCE) ? nullptr : regex.get());
	
	std::string dataPath = replaceExtension(file, ".qgd");
	FileStream in(dataPath.c_str(), "rb");
	if (!in)
	{
		output_->error("Error reading data file %s\n", dataPath.c_str());
		return 0;
	}
	
	DataFileHeader header;
	if (!read(in, header) || memcmp(header.magic, kDataFileHeaderMagic, strlen(kDataFileHeaderMagic)) != 0)
	{
		output_->error("Error reading data file %s: malformed header\n", dataPath.c_str());
		return 0;
	}

	{
		unsigned int chunkIndex = 0;

		// Assume 50% compression ratio (it's usually much better)
		BlockPool chunkPool(kChunkSize * 3 / 2);

		std::vector<unsigned char> index;
		DataChunkHeader chunk;

		WorkQueue queue(WorkQueue::getIdealWorkerCount(), kMaxQueuedChunkData);

		while (!output.isLimitReached() && read(in, chunk))
		{
			if (ngregex.empty() || chunk.indexSize == 0)
			{
				in.skip(chunk.indexSize);
			}
			else
			{
				try
				{
					index.resize(chunk.indexSize);
				}
				catch (const std::bad_alloc&)
				{
					output_->error("Error reading data file %s: malformed chunk\n", dataPath.c_str());
					return 0;
				}

				if (chunk.indexSize && !read(in, &index[0], chunk.indexSize))
				{
					output_->error("Error reading data file %s: malformed chunk\n", dataPath.c_str());
					return 0;
				}

				if (!ngregex.match(index, chunk.indexHashIterations))
				{
					in.skip(chunk.compressedSize);
					continue;
				}
			}

			std::shared_ptr<char> data = chunkPool.allocate(chunk.compressedSize + chunk.uncompressedSize, std::nothrow);

			if (!data || !read(in, data.get(), chunk.compressedSize))
			{
				output_->error("Error reading data file %s: malformed chunk\n", dataPath.c_str());
				return 0;
			}

			queue.push([=, &regex, &output, &includeRe, &excludeRe]() {
				char* compressed = data.get();
				char* uncompressed = data.get() + chunk.compressedSize;

				decompress(uncompressed, chunk.uncompressedSize, compressed, chunk.compressedSize);
				processChunk(regex.get(), &output, chunkIndex, uncompressed, chunk.fileCount, includeRe.get(), excludeRe.get());
			}, chunk.compressedSize + chunk.uncompressedSize);

			chunkIndex++;
		}
	}

	return output.output.getLineCount();
}
コード例 #15
0
ファイル: update.cpp プロジェクト: zeux/qgrep
bool updateProject(Output* output, const char* path)
{
	auto start = std::chrono::high_resolution_clock::now();

    output->print("Updating %s:\n", path);

	std::unique_ptr<ProjectGroup> group = parseProject(output, path);
	if (!group)
		return false;

	removeFile(replaceExtension(path, ".qgc").c_str());

	output->print("Scanning project...\r");

	std::vector<FileInfo> files = getProjectGroupFiles(output, group.get());

	output->print("Building file table...\r");

	if (!buildFiles(output, path, files))
		return false;
	
	std::string targetPath = replaceExtension(path, ".qgd");
	std::string tempPath = targetPath + "_";

	UpdateStatistics stats = {};
	unsigned int totalChunks = 0;

	{
		BuildContext* builder = buildStart(output, tempPath.c_str(), files.size());
		if (!builder)
			return false;

		UpdateFileIterator fileit = {files, 0};

		// update contents using existing database (if any)
		if (!processFile(output, builder, fileit, stats, targetPath.c_str()))
		{
			buildFinish(builder);
			return false;
		}

		// update all unprocessed files
		while (fileit)
		{
			buildAppendFile(builder, fileit->path.c_str(), fileit->timeStamp, fileit->fileSize);
			++fileit;
			stats.filesAdded++;
		}

		totalChunks = buildFinish(builder);
	}

	output->print("\n");

	auto time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start);

	printStatistics(output, stats, totalChunks, time.count() / 1e3);
	
	if (!renameFile(tempPath.c_str(), targetPath.c_str()))
	{
		output->error("Error saving data file %s\n", targetPath.c_str());
		return false;
	}

	return true;
}