예제 #1
0
void MainWindow::str2Copy()
{
    strCopy(2);
}
예제 #2
0
파일: strops.c 프로젝트: hemmecke/aldor
String
strCopyIf(CString s)
{
	return s ? strCopy(s) : (String) s;
}
예제 #3
0
파일: gf_implicit.c 프로젝트: dokterp/aldor
local Foam
gen1ImplicitExport(Syme syme, FoamTag repTag)
{
	TForm		tf, tfret;
	AInt		retfmt, index;
	Foam		foam, clos;
	FoamTag		retType;
	AbSyn		params, oldex, id;
	FoamList	pars;
	Length		i, gfTag;
	GenFoamState	saved;
	Hash		hash;


	/* Paranoia */
	assert(syme);


	/* Get the type of this syme */
	tf = symeType(syme);
	assert (tfIsMap(tf));


	/* Name of the export */
	gen0ProgName = strCopy(symeString(syme));


	/* Type hash code */
	hash = tfHash(tf);


	/* Is this something we know about? */
	for (i = gfTag = 0;(i < GFI_LIMIT) && !gfTag; i++)
	{
		struct gf_impl_info *e = &gfImplicitInfoTable[i];

		if (e->type != hash) continue;
		if (!strEqual(e->name, gen0ProgName)) continue;
		gfTag = i + 1;
	}


	/* Did we recognise it? */
	if (!gfTag)
	{
		bug("[%s] %s#%ld not recognised\n",
			"gen1ImplicitExport", gen0ProgName, hash);
		return (Foam)NULL;
	}
	else
		gfTag--;


	/* Note the function signature */
	tfret   = tfMapRet(tf);
	retType = gen0Type(tfret, &retfmt);


	/* Fake up a bit of absyn */
	id = abNewId(sposNone, symIntern(gen0ProgName));
	abSetDefineIdx(id, symeDefnNum(syme));


	/* Not sure if we need this ... */
	oldex = gen0ProgPushExporter(id);


	/* Deal with const number */
	/* gen0AddConst(symeConstNum(syme), gen0NumProgs); */
	genSetConstNum(syme, abDefineIdx(id), (UShort) gen0NumProgs, true);


	/* Create a closure for the function */
	clos = gen0ProgClosEmpty();
	foam = gen0ProgInitEmpty(gen0ProgName, id);


	/* What format number are we using? */
	index = gen0FormatNum;


	/* Save the current state */
	saved = gen0ProgSaveState(PT_ExFn);


	/*
	 * Deal with special return types. None of these
	 * ought to appear at the moment but there is no
	 * point in creating extra work for the future.
	 */
	if (tfIsMulti(tfret))
		retfmt = gen0MultiFormatNumber(tfret);

	if (tfIsGenerator(tfret))
		foamProgSetGenerator(foam);


	/* Create the parameters for this function */
	params = ab0ImplicitExportArgs(tfMapArg(tf));


	/* Initialise the program state */
	gen0State->type    = tf;
	gen0State->param   = params;
	gen0State->program = foam;


	/* Not sure if we really need this ... see below */
#ifdef PUSH_FORAMTS
	gen0PushFormat(index);
#endif


	/* Create the parameter list */
	pars = gen0ImplicitExportArgs(tfMapArg(tf));


	/* Generate code for the body of this export */
	switch (gfTag)
	{
	   case GFI_PackedArrayNew:
		gen0ImplicitPANew(pars, repTag);
		break;
	   case GFI_PackedArrayGet:
		gen0ImplicitPAGet(pars, repTag);
		break;
	   case GFI_PackedArraySet:
		gen0ImplicitPASet(pars, repTag);
		break;
	   case GFI_PackedRecordSet:
		gen0ImplicitPRSet(pars, repTag);
		break;
	   case GFI_PackedRecordGet:
		gen0ImplicitPRGet(pars, repTag);
		break;
	   case GFI_PackedRepSize:
		gen0ImplicitPRSize(pars, repTag);
		break;
	   default:
		bug("[%s] GFI tag #%d not recognised\n",
			"gen1ImplicitExport", gfTag);
	}


#ifdef PUSH_FORAMTS
	gen0ProgAddFormat(index);
	gen0ProgFiniEmpty(foam, retType, retfmt);
#else
	/*
	 * Finish off the FOAM creation. Note that we want to
	 * use a basic machine type for the return type of this
	 * function so that Fortran can understand the result.
	 * This means we use `rtype' in gen0ProgFiniEmpty()
	 * rather than `retType' which we would do normally.
	 */
 	gen0UseStackedFormat(int0); /* These two lines provide a format */
 	gen0ProgPushFormat(int0);   /* for the lexical argument `op'   */
	gen0ProgFiniEmpty(foam, retType, retfmt);
#endif


	/* Optimisation bits */
	/* foam->foamProg.infoBits = IB_INLINEME; */
	foamOptInfo(foam) = inlInfoNew(NULL, foam, NULL, false);


	/* Compute side-effects of this foam */
	/* gen0ComputeSideEffects(foam); */


	/* Restore the saved state before returning */
	gen0ProgRestoreState(saved);
	return clos;
}
예제 #4
0
파일: tree.cpp 프로젝트: Raimondi/scid
errorT
TreeCache::ReadFile (const char * fname)
{
    // Only read the file if the cache is empty:
    if (NumInUse > 0) { return OK; }
#ifdef WINCE
    /*FILE * */Tcl_Channel fp;
    fileNameT fullname;
    strCopy (fullname, fname);
    strAppend (fullname, TREEFILE_SUFFIX);

    //fp = fopen (fullname, "rb");
    fp = mySilent_Tcl_OpenFileChannel(NULL, fullname, "r", 0666);
    if (fp == NULL) {
        return ERROR_FileOpen;
    }
 my_Tcl_SetChannelOption(NULL, fp, "-encoding", "binary");
 my_Tcl_SetChannelOption(NULL, fp, "-translation", "binary");

    uint magic = readFourBytes (fp);
    if (magic != TREEFILE_MAGIC) {
        //fclose (fp);
        my_Tcl_Close(NULL, fp);

#else
    FILE * fp;
    fileNameT fullname;
    strCopy (fullname, fname);
    strAppend (fullname, TREEFILE_SUFFIX);

    fp = fopen (fullname, "rb");
    if (fp == NULL) {
        return ERROR_FileOpen;
    }

    uint magic = readFourBytes (fp);
    if (magic != TREEFILE_MAGIC) {
        fclose (fp);
#endif
        return ERROR_Corrupt;
    }
    readTwoBytes (fp);  // Scid Version; unused
    uint cacheSize = readFourBytes (fp);
    SetCacheSize (cacheSize);
    NumInUse = readFourBytes (fp);
    LowestTotal = readFourBytes (fp);
    LowestTotalIndex = readFourBytes(fp);

    for (uint count=0; count < NumInUse; count++) {
        cachedTreeT * ctree = &(Cache[count]);
        ctree->toMove = readOneByte (fp);
        for (squareT sq=0; sq < 64; sq++) {
            ctree->board[sq] = readOneByte (fp);
        }

        // Read the moves:
        ctree->tree.moveCount = readFourBytes (fp);
        ctree->tree.totalCount = readFourBytes (fp);

        uint numMoves = ctree->tree.moveCount;
        for (uint i=0; i < numMoves; i++) {
            // Read this move node:

            treeNodeT * tnode = &(ctree->tree.node[i]);
            readSimpleMove (fp, &(tnode->sm));
            readString (fp, tnode->san, 8);
            for (uint res = 0; res < 4; res++) {
                tnode->freq[res] = readFourBytes (fp);
            }
            tnode->total = readFourBytes (fp);
            tnode->score = readFourBytes (fp);
            tnode->ecoCode = readTwoBytes (fp);
            tnode->eloCount = readFourBytes (fp);
            tnode->eloSum = readFourBytes (fp);
            tnode->perfCount = readFourBytes (fp);
            tnode->perfSum = readFourBytes (fp);
            tnode->yearCount = readFourBytes (fp);
            tnode->yearSum = readFourBytes (fp);
        }

        // Read the compressed filter:
        ctree->cfilter = new CompressedFilter;
        ctree->cfilter->ReadFromFile (fp);
    }
#ifdef WINCE
     my_Tcl_Close(NULL, fp);
#else
    fclose (fp);
#endif
    return OK;
}
예제 #5
0
LPWSTR DWFileResumeList::GetListName()
{
	if (!m_dataListName)
		strCopy(m_dataListName, L"ResumeInfo");
	return m_dataListName;
}
예제 #6
0
파일: pgnscid.cpp 프로젝트: Raimondi/scid
int
main (int argc, char * argv[])
{
    setbuf(stdout, NULL);   // Make stdout unbuffered.

    gameNumberT gNumber;

    bool option_ForceReplace = false;
    bool option_PreGameComments = true;

    uint pgnFileSize = 0;
    char *progname = argv[0];
    fileNameT fname;
    fileNameT baseName;
    uint argsleft = argc - 1;
    char ** nextArg = argv + 1;

    // Parse command-line argments:
    while (argsleft > 0  &&  nextArg[0][0] == '-') {
        if (! strCompare (*nextArg, "-f")) {
            option_ForceReplace = true;
        } else if (! strCompare (*nextArg, "-x")) {
            option_PreGameComments = false;
        } else {
            usage (progname);
        }
        argsleft--;
        nextArg++;
    }
    if (argsleft != 1  &&  argsleft != 2) {
        usage (progname);
    }

    char * pgnName = *nextArg;
    MFile pgnFile;

    pgnFileSize = fileSize (pgnName, "");

    // Ensure positive file size counter to avoid division by zero:
    if (pgnFileSize < 1) {
        pgnFileSize = 1;
    }

    // Make baseName from pgnName if baseName is not provided:
    if (argsleft == 1) {
        strCopy (baseName, pgnName);
        // If a gzip file, remove two suffixes, the first being ".gz":
        const char * lastSuffix = strFileSuffix (baseName);
        if (lastSuffix != NULL  &&  strEqual (lastSuffix, GZIP_SUFFIX)) {
            strTrimFileSuffix (baseName);
        }
        // Trim the ".pgn" suffix:
        strTrimFileSuffix (baseName);
    } else {
        strCopy (baseName, nextArg[1]);
    }

    // Check for existing database, avoid overwriting it:
    if (! option_ForceReplace) {
        if (fileSize (baseName, INDEX_SUFFIX) > 0) {
            // Scid index file already exists:
            fprintf (stderr, "%s: database already exists: %s\n", progname,
                     baseName);
            fprintf (stderr, "You can use:  %s -f %s   to overwrite"
                     " the existing database.\n", progname, pgnName);
            exit(1);
        }
    }

    if (pgnFile.Open (pgnName, FMODE_ReadOnly) != OK) {
        fprintf (stderr, "%s: could not open file %s\n", progname, pgnName);
        exit(1);
    }

    // Try opening the log file:
    strCopy (fname, baseName);
    strAppend (fname, ".err");
    FILE * logFile = fopen (fname, "w");
    if (logFile == NULL) {
        fprintf (stderr, "%s: could not open log file: %s\n", progname, fname);
        exit(1);
    }

    printf ("Converting file %s to Scid database %s:\n", pgnName, baseName);
    printf ("Errors/warnings will be written to %s.\n\n", fname);

    scid_Init();

    GFile * gameFile = new GFile;
    if ((gameFile->Create (baseName, FMODE_WriteOnly)) != OK) {
        fprintf (stderr, "%s: could not create the file %s%s\n",
                 progname, baseName, GFILE_SUFFIX);
        fprintf (stderr, "The file may already exist and be read-only, or\n");
        fprintf (stderr, "you may not have permission to create this file.\n");
        exit(1);
    }

    NameBase * nb = new NameBase;
    Index * idx = new Index;
    IndexEntry * ie = new IndexEntry;
    idx->SetFileName (baseName);
    idx->CreateIndexFile (FMODE_WriteOnly);

    Game * game = new Game;
    ProgBar progBar(stdout);
    progBar.Start();

    ByteBuffer *bbuf = new ByteBuffer;
    bbuf->SetBufferSize (BBUF_SIZE); // 32768

    PgnParser pgnParser (&pgnFile);
    pgnParser.SetErrorFile (logFile);
    pgnParser.SetPreGameText (option_PreGameComments);

    // TODO: Add command line option for ignored tags, rather than
    //       just hardcoding PlyCount as the only ignored tag.
    pgnParser.AddIgnoredTag ("PlyCount");

    // Add each game found to the database:
    while (pgnParser.ParseGame(game) != ERROR_NotFound) {
        ie->Init();

        if (idx->AddGame (&gNumber, ie) != OK) {
            fprintf (stderr, "\nLimit of %d games reached!\n", MAX_GAMES);
            exit(1);
        }

        // Add the names to the namebase:
        idNumberT id = 0;

        if (nb->AddName (NAME_PLAYER, game->GetWhiteStr(), &id) != OK) {
            fatalNameError (NAME_PLAYER);
        }
        nb->IncFrequency (NAME_PLAYER, id, 1);
        ie->SetWhite (id);

        if (nb->AddName (NAME_PLAYER, game->GetBlackStr(), &id) != OK) {
            fatalNameError (NAME_PLAYER);
        }
        nb->IncFrequency (NAME_PLAYER, id, 1);
        ie->SetBlack (id);

        if (nb->AddName (NAME_EVENT, game->GetEventStr(), &id) != OK) {
            fatalNameError (NAME_EVENT);
        }
        nb->IncFrequency (NAME_EVENT, id, 1);
        ie->SetEvent (id);

        if (nb->AddName (NAME_SITE, game->GetSiteStr(), &id) != OK) {
            fatalNameError (NAME_SITE);
        }
        nb->IncFrequency (NAME_SITE, id, 1);
        ie->SetSite (id);

        if (nb->AddName (NAME_ROUND, game->GetRoundStr(), &id) != OK) {
            fatalNameError (NAME_ROUND);
        }
        nb->IncFrequency (NAME_ROUND, id, 1);
        ie->SetRound (id);

        bbuf->Empty();
        if (game->Encode (bbuf, ie) != OK) {
            fprintf (stderr, "Fatal error encoding game!\n");
            abort();
        }
        uint offset = 0;
        if (gameFile->AddGame (bbuf, &offset) != OK) {
            fprintf (stderr, "Fatal error writing game file!\n");
            abort();
        }
        ie->SetOffset (offset);
        ie->SetLength (bbuf->GetByteCount());
        idx->WriteEntries (ie, gNumber, 1);

        // Update the progress bar:
        if (! (gNumber % 100)) {
            int bytesSeen = pgnParser.BytesUsed();
            int percentDone = 1 + ((bytesSeen) * 100 / pgnFileSize);
            progBar.Update (percentDone);
        }

    }

    uint t = 0;   // = time(0);
    nb->SetTimeStamp(t);
    nb->SetFileName (baseName);
    if (nb->WriteNameFile() != OK) {
        fprintf (stderr, "Fatal error writing name file!\n");
        exit(1);
    }
    progBar.Finish();

    printf ("\nDatabase `%s': %d games, %d players, %d events, %d sites.\n",
            baseName, idx->GetNumGames(), nb->GetNumNames (NAME_PLAYER),
            nb->GetNumNames (NAME_EVENT), nb->GetNumNames (NAME_SITE));
    fclose (logFile);
    if (pgnParser.ErrorCount() > 0) {
        printf ("There were %u errors or warnings; ", pgnParser.ErrorCount());
        printf ("examine the file \"%s.err\"\n", baseName);
    } else {
        printf ("There were no warnings or errors.\n");
        removeFile (baseName, ".err");
    }
    gameFile->Close();
    idx->CloseIndexFile();

    // If there is a tree cache file for this database, it is out of date:
    removeFile (baseName, TREEFILE_SUFFIX);
#ifdef ASSERTIONS
    printf("%d asserts were tested\n", numAsserts);
#endif
    return 0;
}
예제 #7
0
    void runTest ()
    {
        beginTestCase ("public/private");

        // Construct a seed.
        RippleAddress   naSeed;

        expect (naSeed.setSeedGeneric ("masterpassphrase"));
        expect (naSeed.humanSeed () == "snoPBrXtMeMyMHUVTgbuqAfg1SUTb", naSeed.humanSeed ());

        // Create node public/private key pair
        RippleAddress   naNodePublic    = RippleAddress::createNodePublic (naSeed);
        RippleAddress   naNodePrivate   = RippleAddress::createNodePrivate (naSeed);

        expect (naNodePublic.humanNodePublic () == "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9", naNodePublic.humanNodePublic ());
        expect (naNodePrivate.humanNodePrivate () == "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe", naNodePrivate.humanNodePrivate ());

        // Check node signing.
        Blob vucTextSrc = strCopy ("Hello, nurse!");
        uint256 uHash   = Serializer::getSHA512Half (vucTextSrc);
        Blob vucTextSig;

        naNodePrivate.signNodePrivate (uHash, vucTextSig);
        expect (naNodePublic.verifyNodePublic (uHash, vucTextSig, ECDSA::strict), "Verify failed.");

        // Construct a public generator from the seed.
        RippleAddress   naGenerator     = RippleAddress::createGeneratorPublic (naSeed);

        expect (naGenerator.humanGenerator () == "fhuJKrhSDzV2SkjLn9qbwm5AaRmrxDPfFsHDCP6yfDZWcxDFz4mt", naGenerator.humanGenerator ());

        // Create account #0 public/private key pair.
        RippleAddress   naAccountPublic0    = RippleAddress::createAccountPublic (naGenerator, 0);
        RippleAddress   naAccountPrivate0   = RippleAddress::createAccountPrivate (naGenerator, naSeed, 0);

        expect (naAccountPublic0.humanAccountID () == "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", naAccountPublic0.humanAccountID ());
        expect (naAccountPublic0.humanAccountPublic () == "aBQG8RQAzjs1eTKFEAQXr2gS4utcDiEC9wmi7pfUPTi27VCahwgw", naAccountPublic0.humanAccountPublic ());
        expect (naAccountPrivate0.humanAccountPrivate () == "p9JfM6HHi64m6mvB6v5k7G2b1cXzGmYiCNJf6GHPKvFTWdeRVjh", naAccountPrivate0.humanAccountPrivate ());

        // Create account #1 public/private key pair.
        RippleAddress   naAccountPublic1    = RippleAddress::createAccountPublic (naGenerator, 1);
        RippleAddress   naAccountPrivate1   = RippleAddress::createAccountPrivate (naGenerator, naSeed, 1);

        expect (naAccountPublic1.humanAccountID () == "r4bYF7SLUMD7QgSLLpgJx38WJSY12ViRjP", naAccountPublic1.humanAccountID ());
        expect (naAccountPublic1.humanAccountPublic () == "aBPXpTfuLy1Bhk3HnGTTAqnovpKWQ23NpFMNkAF6F1Atg5vDyPrw", naAccountPublic1.humanAccountPublic ());
        expect (naAccountPrivate1.humanAccountPrivate () == "p9JEm822LMrzJii1k7TvdphfENTp6G5jr253Xa5rkzUWVr8ogQt", naAccountPrivate1.humanAccountPrivate ());

        // Check account signing.
        expect (naAccountPrivate0.accountPrivateSign (uHash, vucTextSig), "Signing failed.");
        expect (naAccountPublic0.accountPublicVerify (uHash, vucTextSig, ECDSA::strict), "Verify failed.");
        expect (!naAccountPublic1.accountPublicVerify (uHash, vucTextSig, ECDSA::not_strict), "Anti-verify failed.");
        expect (!naAccountPublic1.accountPublicVerify (uHash, vucTextSig, ECDSA::strict), "Anti-verify failed.");

        expect (naAccountPrivate1.accountPrivateSign (uHash, vucTextSig), "Signing failed.");
        expect (naAccountPublic1.accountPublicVerify (uHash, vucTextSig, ECDSA::strict), "Verify failed.");
        expect (!naAccountPublic0.accountPublicVerify (uHash, vucTextSig, ECDSA::not_strict), "Anti-verify failed.");
        expect (!naAccountPublic0.accountPublicVerify (uHash, vucTextSig, ECDSA::strict), "Anti-verify failed.");

        // Check account encryption.
        Blob vucTextCipher
            = naAccountPrivate0.accountPrivateEncrypt (naAccountPublic1, vucTextSrc);
        Blob vucTextRecovered
            = naAccountPrivate1.accountPrivateDecrypt (naAccountPublic0, vucTextCipher);

        expect (vucTextSrc == vucTextRecovered, "Encrypt-decrypt failed.");
    }
예제 #8
0
// DrvDeviceCapabilities function returns requested information
// about a printer's capabilities.
//
// NOTE:
//   WE NEED TO TAKE INTO ACCOUNT DIFFERENCE BETWEEN OUR CAPS, TARGET CAPS
DWORD DrvDeviceCapabilities(
                            HANDLE    hPrinter,
                            PWSTR     pDeviceName,
                            WORD      iDevCap,
                            VOID      *pvOutput,
                            PDEVMODE  pDevMode
	                        )
{
    //DEBUGMESSAGE(("DrvDeviceCapabilities"));

	DWORD dwRetValue = GDI_ERROR;
    WORD *pwOutput = (WORD*)pvOutput;
    POINTS *pptsdwRet = ((POINTS *)&dwRetValue);

    switch (iDevCap)
    {
    case DC_PAPERNAMES:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PAPERNAMES"));
    case DC_MEDIAREADY:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_MEDIAREADY"));
        if (pvOutput) {
            TCHAR str[] = TEXT("None (the printer is virtual!)");
            // each paper name is 64 chars max
            strCopy((LPTSTR)pvOutput, str, strBufferSize(str));
        }
        return 1;

    case DC_PAPERS:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PAPERS"));
        if (pvOutput)
            *pwOutput = DMPAPER_A4;     // A4 is 210x297 mm
        return 1;

    case DC_PAPERSIZE:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PAPERSIZE"));
        if (pvOutput) {
            POINT *arr = (POINT*)pvOutput;
            arr[0].x = A4_WIDTH_MM*10;
            arr[0].y = A4_HEIGHT_MM*10;
        }
        return 1;

    case DC_BINNAMES:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_BINNAMES"));
        if (pvOutput)
            // each bin name is 24 chars max
            strCopy((LPTSTR)pvOutput, TEXT("Bin"), 3*sizeof(TCHAR));
        return 1;

    case DC_BINS:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_BINS"));
        if (pvOutput)
            *pwOutput = DMBIN_ONLYONE;
        return 1;

    case DC_COPIES:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_COPIES"));
        return 1;

    case DC_STAPLE:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_STAPLE"));
        return 0;   // not supported
    case DC_COLLATE:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_COLLATE"));
        return 0;   // not supported
    case DC_DUPLEX:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_DUPLEX"));
        return 0;   // not supported

    case DC_ENUMRESOLUTIONS:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_ENUMRESOLUTIONS"));
        if (pvOutput) {
            LONG *arr = (LONG*)pvOutput;
            arr[0] = emfDRIVER_WIDTH_DPI;
            arr[1] = emfDRIVER_HEIGHT_DPI;
        }
        return 1;

        // info about our driver's devmode

    case DC_DRIVER:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_DRIVER"));
        return emfDRIVER_REAL_VERSION;
    case DC_EXTRA:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_EXTRA"));
        return extdmSizeofPrivate();
    case DC_SIZE:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_SIZE"));
        return sizeof(DEVMODEW);    // size of only public members
    case DC_VERSION:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_VERSION"));
        return DM_SPECVERSION;
    case DC_FIELDS:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_FIELDS"));
        return extdmDEFAULT_FIELDS;
    case DC_FILEDEPENDENCIES:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_FILEDEPENDENCIES"));
        return 0;

    case DC_MAXEXTENT:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_MAXEXTENT"));
        pptsdwRet->x = A4_WIDTH_MM*10;
        pptsdwRet->y = A4_HEIGHT_MM*10;
        return dwRetValue;

    case DC_MINEXTENT:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_MINEXTENT"));
        // min is 1 mm
        pptsdwRet->x = 10;
        pptsdwRet->y = 10;
        return dwRetValue;

    case DC_ORIENTATION:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_ORIENTATION"));
        return 90;


    case DC_TRUETYPE:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_TRUETYPE"));
        return DCTT_BITMAP;//|DCTT_SUBDEV|DCTT_DOWNLOAD;

    case DC_PERSONALITY:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PERSONALITY"));
        if (pvOutput)
            // each printer desc lang name is 32 chars max
            strCopy((LPTSTR)pvOutput, TEXT("EMF"), 3*sizeof(TCHAR));
        return 1;

    case DC_COLORDEVICE:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_COLORDEVICE"));
        return 1;

    //case DC_SPL_MEDIAREADY:

    case DC_NUP:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_NUP"));
        return 1;

    case DC_PRINTERMEM:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PRINTERMEM"));
        return 4096;        // simulate 4MB of internal mem

        // 60 pages per minute: we're fast :)
    case DC_PRINTRATE:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PRINTRATE"));
    case DC_PRINTRATEPPM:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PRINTRATEPPM"));
        return 60;
    case DC_PRINTRATEUNIT:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_PRINTRATEUNIT"));
        return PRINTRATEUNIT_PPM;

    case DC_BINADJUST:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_BINADJUST"));
        // should be not used for WinXP/2000 but I've tested
        // that MS Word calls WinXP drivers with this code too!
        return DCBA_FACEUPNONE;

    case DC_EMF_COMPLIANT:
        DEBUGMESSAGE(("DrvDeviceCapabilities - DC_EMF_COMPLIANT"));
        // should be not used for WinXP/2000 but just to be sure...
        return 1;

        // other win98 only codes:
    //case DC_DATATYPE_PRODUCED:
    //case DC_MANUFACTURER:
    //case DC_MODEL:

    default:
        DEBUGMESSAGE(("Unexpected device capability required: %d", iDevCap));
        return GDI_ERROR;
    }

	return dwRetValue;
}
예제 #9
0
    void run()
    {
        // Construct a seed.
        RippleAddress naSeed;

        expect (naSeed.setSeedGeneric ("masterpassphrase"));
        expect (naSeed.humanSeed () == "snoPBrXtMeMyMHUVTgbuqAfg1SUTb", naSeed.humanSeed ());

        // Create node public/private key pair
        RippleAddress naNodePublic    = RippleAddress::createNodePublic (naSeed);
        RippleAddress naNodePrivate   = RippleAddress::createNodePrivate (naSeed);

        expect (naNodePublic.humanNodePublic () == "n94a1u4jAz288pZLtw6yFWVbi89YamiC6JBXPVUj5zmExe5fTVg9", naNodePublic.humanNodePublic ());
        expect (naNodePrivate.humanNodePrivate () == "pnen77YEeUd4fFKG7iycBWcwKpTaeFRkW2WFostaATy1DSupwXe", naNodePrivate.humanNodePrivate ());

        // Check node signing.
        Blob vucTextSrc = strCopy ("Hello, nurse!");
        uint256 uHash   = sha512Half(makeSlice(vucTextSrc));
        Blob vucTextSig;

        naNodePrivate.signNodePrivate (uHash, vucTextSig);
        expect (naNodePublic.verifyNodePublic (uHash, vucTextSig, ECDSA::strict), "Verify failed.");

        // Construct a public generator from the seed.
        RippleAddress   generator     = RippleAddress::createGeneratorPublic (naSeed);

        expect (generator.humanGenerator () == "fhuJKrhSDzV2SkjLn9qbwm5AaRmrxDPfFsHDCP6yfDZWcxDFz4mt", generator.humanGenerator ());

        // Create ed25519 account public/private key pair.
        KeyPair keys = generateKeysFromSeed (KeyType::ed25519, naSeed);
        expectEquals (keys.publicKey.humanAccountPublic(), "aKGheSBjmCsKJVuLNKRAKpZXT6wpk2FCuEZAXJupXgdAxX5THCqR");

        // Check ed25519 account signing.
        vucTextSig = keys.secretKey.accountPrivateSign (vucTextSrc);

        expect (!vucTextSig.empty(), "ed25519 signing failed.");
        expect (keys.publicKey.accountPublicVerify (vucTextSrc, vucTextSig, ECDSA()), "ed25519 verify failed.");

        // Create account #0 public/private key pair.
        RippleAddress   naAccountPublic0    = RippleAddress::createAccountPublic (generator, 0);
        RippleAddress   naAccountPrivate0   = RippleAddress::createAccountPrivate (generator, naSeed, 0);

        expect (toBase58(calcAccountID(naAccountPublic0)) == "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh");
        expect (naAccountPublic0.humanAccountPublic () == "aBQG8RQAzjs1eTKFEAQXr2gS4utcDiEC9wmi7pfUPTi27VCahwgw", naAccountPublic0.humanAccountPublic ());

        // Create account #1 public/private key pair.
        RippleAddress   naAccountPublic1    = RippleAddress::createAccountPublic (generator, 1);
        RippleAddress   naAccountPrivate1   = RippleAddress::createAccountPrivate (generator, naSeed, 1);

        expect (toBase58(calcAccountID(naAccountPublic1)) == "r4bYF7SLUMD7QgSLLpgJx38WJSY12ViRjP");
        expect (naAccountPublic1.humanAccountPublic () == "aBPXpTfuLy1Bhk3HnGTTAqnovpKWQ23NpFMNkAF6F1Atg5vDyPrw", naAccountPublic1.humanAccountPublic ());

        // Check account signing.
        vucTextSig = naAccountPrivate0.accountPrivateSign (vucTextSrc);

        expect (!vucTextSig.empty(), "Signing failed.");
        expect (naAccountPublic0.accountPublicVerify (vucTextSrc, vucTextSig, ECDSA::strict), "Verify failed.");
        expect (!naAccountPublic1.accountPublicVerify (vucTextSrc, vucTextSig, ECDSA::not_strict), "Anti-verify failed.");
        expect (!naAccountPublic1.accountPublicVerify (vucTextSrc, vucTextSig, ECDSA::strict), "Anti-verify failed.");

        vucTextSig = naAccountPrivate1.accountPrivateSign (vucTextSrc);

        expect (!vucTextSig.empty(), "Signing failed.");
        expect (naAccountPublic1.accountPublicVerify (vucTextSrc, vucTextSig, ECDSA::strict), "Verify failed.");
        expect (!naAccountPublic0.accountPublicVerify (vucTextSrc, vucTextSig, ECDSA::not_strict), "Anti-verify failed.");
        expect (!naAccountPublic0.accountPublicVerify (vucTextSrc, vucTextSig, ECDSA::strict), "Anti-verify failed.");

        // Check account encryption.
        Blob vucTextCipher
            = naAccountPrivate0.accountPrivateEncrypt (naAccountPublic1, vucTextSrc);
        Blob vucTextRecovered
            = naAccountPrivate1.accountPrivateDecrypt (naAccountPublic0, vucTextCipher);

        expect (vucTextSrc == vucTextRecovered, "Encrypt-decrypt failed.");

        {
            RippleAddress nSeed;
            uint128 seed1, seed2;
            seed1.SetHex ("71ED064155FFADFA38782C5E0158CB26");
            nSeed.setSeed (seed1);
            expect (nSeed.humanSeed() == "shHM53KPZ87Gwdqarm1bAmPeXg8Tn",
                "Incorrect human seed");
            expect (nSeed.humanSeed1751() == "MAD BODY ACE MINT OKAY HUB WHAT DATA SACK FLAT DANA MATH",
                "Incorrect 1751 seed");
        }
    }
예제 #10
0
ERROR recursive_interpret(FUNCTION_PTR function, STACK_PTR stack)
{
	
// 	fprintf(stderr,"Zavolana funkce: %d\n",function);
	LIST_NODE_PTR instr_node = function->instructions.begin;
	ERROR err = E_OK;
	
	// ----- Priprava promenych ------
	INSTRUCTION_PTR instruction = NULL;
	int str_from,str_to,tmp_count;
	STRING tmp_string;
	
	STACK_PTR tmp_stack;
	tmp_stack = gcMalloc(sizeof(struct STACK));
	stackInit(tmp_stack);
	
	// NULL SYMBOL
	ITEMPTR null_item;
	null_item = gcMalloc(sizeof(struct ITEM));
	null_item->type = TYPE_NULL;
	
	SYMBOL* null_symbol;
	null_symbol = gcMalloc(sizeof(struct SYMBOL));
	null_symbol->type = TYPE_NULL;
	null_symbol->items = null_item;
	
	// TMP SYMBOL
	ITEMPTR tmp_item;
	
	SYMBOL* tmp_symbol;
	
    SYMBOL* op1 = NULL;
    SYMBOL* op2 = NULL;
    SYMBOL* op3 = NULL;
	
	FUNCTION_PTR tmp_function = NULL;
	
	while(instr_node != NULL && err == E_OK)
	{
		instruction = instr_node->value;
		
		tmp_item = gcMalloc(sizeof(struct ITEM));
		tmp_symbol = gcMalloc(sizeof(struct SYMBOL));
		tmp_symbol->items = tmp_item;
	
		op1 = (SYMBOL*) instruction->operand1;
		op2 = (SYMBOL*) instruction->operand2;
		op3 = (SYMBOL*) instruction->destionation;
		
		fprintf(stderr,"while interpret : %d (%s)\n",instruction->type, debugInstruction(instruction->type));
		
		switch(instruction->type)
		{
			case INSTRUCTION_NOP:
			break;
			
			case INSTRUCTION_MOV:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				
				data_copy(op2, op1);
				op1->filgy = true;
			break;
			
			case INSTRUCTION_LOAD_NULL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'O')) != E_OK)
					return err;
				if ((err = op_check(op3,'O')) != E_OK)
					return err;
				
				data_copy(null_symbol,op1);
				data_copy(null_symbol,op2);
				data_copy(null_symbol,op3);
				op1->filgy = true;
				op2->filgy = true;
				op3->filgy = true;
			break;
			
			case INSTRUCTION_ADDITION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt + op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valInt + op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble + op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble + op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_INT)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));;
					sprintf(new_char_string, "%d", op3->items->value.valInt);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));
					sprintf(new_char_string, "%lf", op3->items->value.valDouble);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_SUBSTRACTION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt - op3->items->value.valInt;
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valInt - op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble - op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble - op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_MULTIPLICATION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt * op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = ((double)op2->items->value.valInt) * op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble * ((double)op3->items->value.valInt);
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble * op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_DIVISION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					if(op3->items->value.valInt == 0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt / op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					if(op3->items->value.valDouble == 0.0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valInt / op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					if(op3->items->value.valInt == 0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble / op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					if(op3->items->value.valDouble == 0.0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble / op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_LESS:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt < op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble < op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used < op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GREATER:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt > op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble > op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used > op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_LESS_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt <= op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble <= op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used <= op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GREATER_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt >= op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble >= op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used >= op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt == op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble == op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used == op3->items->value.valString.used;
				}
				else
					tmp_symbol->items->value.valBool = false;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_NOT_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt != op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble != op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used != op3->items->value.valString.used;
					if(!tmp_symbol->items->value.valBool)
					{
						tmp_symbol->items->value.valBool = !strCompare(op2->items->value.valString, op3->items->value.valString.data);
					}
				}
				else
					tmp_symbol->items->value.valBool = false;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_PUSH:
// 				printf("ahoj %d\n",op1->filgy);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				
				stackPush(stack,op1);
			break;
			
			case INSTRUCTION_POP:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				
				if(tmp_symbol == NULL){
					tmp_symbol = gcMalloc(sizeof(SYMBOL));
					tmp_symbol->items = gcMalloc(sizeof(ITEM));
					
					tmp_symbol->items->type = TYPE_NULL;
					tmp_symbol->filgy = true;
					
				}
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
			break;
			
			case INSTRUCTION_CALL:
				if(op1 == NULL)
					return E_COMPILATOR;
				
				tmp_function = function;
				function = (FUNCTION_PTR)op1;
				
				err=recursive_interpret(function,stack);
				if (err != E_OK)
					return err;
				
				function = tmp_function;
			break;
			
			case INSTRUCTION_RETURN:
				return err;
			break;
			
			case INSTRUCTION_JUMP:
				if(op3 == NULL)
					return E_COMPILATOR;
				
				instr_node = function->instructions.begin;
				while(instr_node != (LIST_NODE_PTR)op3)
				{
					if(instr_node->next == NULL)
					{
						fprintf(stderr,"NENALEZENO!!!\n");
						fprintf(stderr,"NENALEZENO!!!\n");
						fprintf(stderr,"NENALEZENO!!!\n");
						break;
					}
					instr_node = instr_node->next;
				}
				continue;
			break;
			
			case INSTRUCTION_IF_JUMP:	
// 				if ((err = op_check(op2,'I')) != E_OK)
// 					return err;
				if(op3 == NULL)
					return E_COMPILATOR;
				
				if(op2->items->type == TYPE_BOOL)
				{
					if(!op2->items->value.valBool)
					{
						instr_node = function->instructions.begin;
						while(instr_node != (LIST_NODE_PTR)op3)
						{
							if(instr_node->next == NULL)
								break;
							instr_node = instr_node->next;
						}
						continue;						
					}
				}
// 				if(op2->items->type == TYPE_DIGIT_INT)
// 				{
// 					printf("AHOJ\n");
// 					if(!op2->items->value.valInt)
// 					{
// 						instr_node = function->instructions.begin;
// 						while(instr_node != (LIST_NODE_PTR)op3)
// 						{
// 							if(instr_node->next == NULL)
// 								break;
// 							instr_node = instr_node->next;
// 						}
// 						continue;						
// 					}
// 				}
			break;
			
			case INSTRUCTION_LABEL:
				
			break;
			
			case INSTRUCTION_BOOLVAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				tmp_symbol->items = boolval(*tmp_symbol->items);
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_DOUBLEVAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				tmp_symbol->items = doubleval(*tmp_symbol->items);
				if(tmp_symbol->items == NULL)
					return E_SEMANTIC_DOUBLEVAL;
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_INTVAL:	
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				op1 = stackPop(stack);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				
				tmp_symbol->items = intval(*op1->items);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_STRVAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				tmp_symbol->items = strval(*tmp_symbol->items);
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GET_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_string = get_string();
				
				tmp_symbol->items->type = TYPE_STRING;
				strInit(&tmp_symbol->items->value.valString);
				strCopy(&tmp_string, &tmp_symbol->items->value.valString);
				
				data_copy(tmp_symbol, op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_CONCATE:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->type = TYPE_STRING;
					strInit(&tmp_symbol->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_INT)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));
					sprintf(new_char_string, "%d", op3->items->value.valInt);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));
					sprintf(new_char_string, "%lf", op3->items->value.valDouble);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_PUT_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if (op2 == NULL)
					return E_COMPILATOR;
				
				// DODELAT VRACENI POCTU VYPSANYCH! DO OP1
				
				tmp_count = *((int*)op2);
				for(int i=0;i<tmp_count;i++)
				{
					tmp_symbol = stackPop(stack);
					if ((err = op_check(tmp_symbol,'I')) != E_OK)
						return err;
					stackPush(tmp_stack,tmp_symbol);
				}
				for(int i=0;i<tmp_count;i++)
				{
					tmp_symbol = stackPop(tmp_stack);
					if(tmp_symbol->items->type == 2)
						printf("%d",tmp_symbol->items->value.valInt);
					else if(tmp_symbol->items->type == 3)
						printf("%lf",tmp_symbol->items->value.valDouble);
					else if(tmp_symbol->items->type == 4)
						printf("%s",tmp_symbol->items->value.valString.data);
				}
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_STRLEN:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if (op2 == NULL)
					return E_COMPILATOR;
				
				tmp_count = *((int*)op2);
				if (tmp_count != 1)
					return E_COMPILATOR;
				
				op1 = stackPop(stack);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				tmp_symbol->items->type = TYPE_DIGIT_INT;
				tmp_symbol->items->value.valInt = my_strlen(op1->items->value.valString);
				
				data_copy(tmp_symbol, op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GET_SUBSTRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if (op2 == NULL)
					return E_COMPILATOR;
				tmp_count = *((int*)op2);
				if (tmp_count != 3)
					return E_COMPILATOR;
				
				// TO
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				str_to = tmp_symbol->items->value.valInt;
				
				// FROM
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				str_from = tmp_symbol->items->value.valInt;
				
				// STRING
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				
				tmp_string = get_substring(tmp_symbol->items->value.valString,str_from,str_to,&err);
				if(err != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_STRING;
				strCopy(&tmp_symbol->items->value.valString,&tmp_string);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_FIND_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				op2 = stackPop(stack);
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				
				op3 = stackPop(stack);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_DIGIT_INT;
				tmp_symbol->items->value.valInt = find_string(op3->items->value.valString, op2->items->value.valString);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_SORT_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				
				sort_string(tmp_symbol->items->value.valString);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			default:
				return E_OK;
			break;
			
		}
		instr_node = instr_node->next;
	}
	return err;
}
예제 #11
0
void MainWindow::str1Copy()
{
    strCopy(1);
}
예제 #12
0
void MainWindow::str4Copy()
{
    strCopy(4);
}
예제 #13
0
void MainWindow::str3Copy()
{
    strCopy(3);
}
예제 #14
0
파일: oid-test.c 프로젝트: agievich/bee2
bool_t oidTest()
{
	octet buf[1024];
	char str[2048];
	char str1[2048];
	size_t count;
	// length octet 0x00
	hexTo(buf, "060000");
	if (oidFromDER(0, buf, 3) != SIZE_MAX)
		return FALSE;
	// length octet 0x80
	hexTo(buf, "068000");
	if (oidFromDER(0, buf, 3) != SIZE_MAX)
		return FALSE;
	// length octet 0xFF
	hexTo(buf, "06FF00");
	if (oidFromDER(0, buf, 3) != SIZE_MAX)
		return FALSE;
	// invalid type
	hexTo(buf, "080100");
	if (oidFromDER(0, buf, 3) != SIZE_MAX)
		return FALSE;
	// illegal padding
	hexTo(buf, "06070180808080807F");
	if (oidFromDER(0, buf, 9) != SIZE_MAX)
		return FALSE;
	hexTo(buf, "06028001");
	if (oidFromDER(0, buf, 4) != SIZE_MAX)
		return FALSE;
	hexTo(buf, "0602807F");
	if (oidFromDER(0, buf, 4) != SIZE_MAX)
		return FALSE;
	// MacOS errors
	hexTo(buf, "06028100");
	if (oidFromDER(str, buf, 4) == SIZE_MAX || !strEq(str, "2.48"))
		return FALSE;
	hexTo(buf, "06028101");
	if (oidFromDER(str, buf, 4) == SIZE_MAX || !strEq(str, "2.49"))
		return FALSE;
	hexTo(buf, "06028837");
	if (oidFromDER(str, buf, 4) == SIZE_MAX || !strEq(str, "2.999"))
		return FALSE;
	// OpenSSL errors
	count = oidToDER(buf, "2.65500");
	if (count == SIZE_MAX || oidFromDER(str, buf, count) == SIZE_MAX ||
		!strEq(str, "2.65500"))
		return FALSE;
	// overflow
	hexTo(buf, "060981B1D1AF85ECA8804F");
	if (oidFromDER(0, buf, 11) != SIZE_MAX)
		return FALSE;
	if (oidIsValid("2.5.4.4294967299"))
		return FALSE;
	// belt-hash
	count = oidToDER(buf, "1.2.112.0.2.0.34.101.31.81");
	if (count != 11 || !hexEq(buf, "06092A7000020022651F51"))
		return FALSE;
	if (oidFromDER(str, buf, count - 1) != SIZE_MAX)
		return FALSE;
	if (oidFromDER(0, buf, count + 1) != SIZE_MAX)
		return FALSE;
	// длинная длина
	strCopy(str1, "1.2.3456.78910.11121314.15161718.19202122.23242526."
		"27282930.31323334.35363738.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18."
		"19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42."
		"43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66."
		"19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42."
		"43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66."
		"19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42."
		"43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66");
	count = oidToDER(buf, str1);
	oidFromDER(str, buf, count);
	if (!strEq(str, str1))
		return FALSE;
	str1[strLen(str1)] = '.';
	strCopy(str1 + strLen(str) + 1, str);
	count = oidToDER(buf, str1);
	oidFromDER(str, buf, count);
	if (!strEq(str, str1))
		return FALSE;
	// все нормально
	return TRUE;
}
예제 #15
0
SYMBOL_PTR stInsertStaticValue(FUNCTION_PTR function, STRING id, enum_RetVal retval, SYMBOL_PTR* symbol){
		
 	fprintf(stderr, "|| Static val in %s : %s\n", id.data, debugRetval(retval));
	
	bool wasEmpty = false;
	
	if(!(*symbol)){
		*symbol = gcMalloc(sizeof(SYMBOL));
		wasEmpty = true;
	}
	
	if(wasEmpty || !(*symbol)->items)
		(*symbol)->items = gcMalloc(sizeof(ITEM));
	//strCopy(&id, &(*symbol)->id); //mozno ne?
	
	
	switch(retval){
		case TTYPE_NULL:
			(*symbol)->items->type = TYPE_NULL;
			(*symbol)->filgy = true;
			break;
		case TTYPE_TRUE:
			(*symbol)->items->type = TYPE_BOOL;
			(*symbol)->items->value.valBool = true;
			(*symbol)->filgy = true;
			break;
		case TTYPE_FALSE:
			(*symbol)->items->type = TYPE_BOOL;
			(*symbol)->items->value.valBool = false;
			(*symbol)->filgy = true;
			break;
		case TTYPE_STRING:
			(*symbol)->items->type = TYPE_STRING;
			strCopy(&id, &((*symbol)->items->value.valString));
			(*symbol)->filgy = true;
			break;
		case TTYPE_NUMBER:
			(*symbol)->items->type = TYPE_DIGIT_INT;
		
			sscanf(id.data, "%d", &((*symbol)->items->value.valInt));
			(*symbol)->filgy = true;
			break;
		case TTYPE_DEC_NUMBER:
			(*symbol)->items->type = TYPE_DIGIT_DOUBLE;
			
			sscanf(id.data, "%lf", &((*symbol)->items->value.valDouble));
			(*symbol)->filgy = true;
			break;
		case TTYPE_VARIABLE:
			(*symbol)->items->type = TYPE_CALLABLE;
			(*symbol)->filgy = true;
			break;
		default:
			(*symbol)->items->type = TYPE_OTHER;
			break;
	}
	
	listInsertEnd(&function->staticValues, (*symbol));

	return (*symbol);
}
예제 #16
0
파일: include.c 프로젝트: pdo/aldor
local SrcLineList
inclFile(String fname, Bool reincluding, Bool top, long *pnlines)
{
	Scope("inclFile");

	SrcLineList     sll;
	Hash            fhash;
	FileName        fn;
	FileState	o_fileState; 
	IfState		fluid(ifState);
	String		curdir;

	o_fileState 	     = fileState;     /* no fluid(struct) */
	ifState              = NoIf;
	fileState.lineNumber = 0;

	fn = inclFind(fname, fileState.curDir);

	if (fn != 0) {
		fileState.curDir   = strCopy(fnameDir(fn));
		fileState.curFile  = strCopy(fnameUnparseStatic(fn));
		fileState.curFname = fn;
	}
	curdir = fileState.curDir;

	if (fn == 0) {
		fileState = o_fileState;
		if (top) {
			comsgFatal(NULL, ALDOR_F_CantOpen, fname);
			NotReached(sll = 0);
		}
		else
			sll = inclError(ALDOR_F_CantOpen, fname);
	} 
	else {
		fhash = fileHash(fn);
		fname = strCopy (fnameUnparseStatic(fn));

		if (!reincluding && listMemq(Hash)(includedFileCodes, fhash)) {
			sll = listNil(SrcLine);
		}
		else if (listMemq(Hash)(fileState.fileCodes, fhash)) {
			String s = inclActiveFileChain
				(fileState.fileNames, "->");
			fileState = o_fileState;
			sll = inclError(ALDOR_E_InclInfinite, s);
			strFree(s);
		}
		else {
			includedFileCodes   =
			   listCons(Hash)  (fhash,includedFileCodes);
			fileState.fileCodes =
			   listCons(Hash)  (fhash,fileState.fileCodes);
			fileState.fileNames =
			   listCons(String)(fname,fileState.fileNames);
			fileState.infile    = fileRdOpen(fn);

			sll = inclFileContents();

			listFreeCons(Hash)  (fileState.fileCodes);
			listFreeCons(String)(fileState.fileNames);
			fclose(fileState.infile);
		}
		fnameFree(fn);
		strFree(curdir);
				 /*!! curFile is used in src lines */
		strFree(fname);
	}
	if (pnlines) *pnlines = fileState.lineNumber;
	fileState = o_fileState;
	Return(sll);
}
예제 #17
0
파일: strlib.cpp 프로젝트: vohac/genex
void vstring::strReflowLine (char * & target, strSizeType width, int align)
{
   strSizeType n = strLength (target);
   char * indent = 0x0000;              // Zwischenspeicher fuer einrueckungspaces oder fuer ganze Zeile
   strSizeType i;                       // Schleifenzaehler und universalvariable
   strSizeType numberOfSpaces;          // Anzahl der Spaces, die die Zeile zunaechst besitzt (Blocksatz)
   if (n < width)                       // ist die Zeile ueberhaupt auszurichten, oder ohnehin schon zu lang
   {
      switch (align)
      {
      case 0 :                          // Center
         i = (width - n) / 2;           // Anzahl der Leerzeichen ist die Haelte des aufzufuellenden Teils (abgerundet)
         if (i > 0)
         {
            strAlloc (indent, i);
            indent[i] = 0;
            while (i > 0)               // String mit leerzeichen erstellen
            {
               i--;
               indent[i] = ' ';
            }
            strCopy (target, indent, target);  // und den einrueckungsstring vorne drankopieren
         }
         break;
      case 1 :                          // Links
         break;                         // in diesem falle muss gar nichts gemacht werden
      case 2 :                          // Rechts
         i = width - n;                 // Anzahl der Leerzeichen, die aufgefuellt werden muessen
         strAlloc (indent, i);
         indent[i] = 0;
         while (i > 0)                  // String erstellen
         {
            i--;
            indent[i] = ' ';
         }
         strCopy (target, indent, target);  // und den einrueckungsstring vorne drankopieren
         break;
      case 3 :                          // Blocksatz
         numberOfSpaces = 0;
         for (i = 0; i < n; i++)        // Erst mal zaehlen, wieviele spaces der string bislang hat
         {
            if (target[i] == ' ')
            {
               numberOfSpaces++;
            }
         }
         if (numberOfSpaces > 0)        // gibt es leerzeichen, die ausgeweitet werden koennten? Ansonsten passiert gar nichts
         {
            strAlloc (indent, width);   // erstellen einen Leeren String, der das gesamt ergebnis aufnimmt
            indent[width] = 0;          // setze schonmal das null-terminierungsbyte
            strSizeType spaces = numberOfSpaces + (width - n);  // Soviele spaces muessen insgesamt untergebracht werden
            strSizeType j, k;           // Schleifenvariablen
            i = 0;
            j = 0;
            while (i < n)
            {
               if (target[i] == ' ')
               {
                  for (k = spaces / numberOfSpaces; k > 0; k--)  // wir haben ein leerzeichen entdeckt, und schreiben jetzt die ausgeweiteten leerzeichen in den Zielstring
                  {
                     indent[j] = ' ';   // schreibe leerzeichen in zielstring
                     j++;
                  }
                  spaces -= spaces / numberOfSpaces;  // notiere, dass die eben geschriebenen Leerzeichen 'verbraucht' sind
                  numberOfSpaces--;     // und dass jetzt ebenfalls ein leerzeichen des quellstring bereits abgearbeitet ist
               }
               else
               {
                  indent[j] = target[i];  // alle anderen Zeichen werden einfach kopiert
                  j++;
               }
               i++;                     // nun das naechste Zeichen des Quellstrings bearbeiten
            }
            strCopy (target, indent);   // kopiere jetzt den gesamte temporaeren String in das eigentliche Ziel
         }
         break;
      }
   }
   strFree (indent);
}
예제 #18
0
파일: Utils.cpp 프로젝트: Maria143/uipf
/*
strToEat	string, which has to be converted
*/
std::string toLower(const std::string& strToEat){

       std::string strCopy (strToEat);
       std::transform(strCopy.begin(), strCopy.end(), strCopy.begin(), ::tolower);
       return strCopy;
}
예제 #19
0
파일: cmdline.c 프로젝트: nilqed/aldor
/*
 * Subsume options in response file into argument vector.
 * Only the slots 'argi0..*pargc-1 are treated as arguments.
 */
Bool
cmdSubsumeResponseFiles(int argi0, int *pargc, String **pargv)
{
	int 	nresps = 0, i;
	String 	*argv;
	String 	envopts;

	assert(*pargc >= 1);

	/* Copy the original args into a new r/w vector.
	 * The extra slot is potentially used in handling AXIOMXLARGS.
	 */
	argv = (String *) stoAlloc(OB_Other, (*pargc+1) * sizeof(String *));
	for (i = 0; i < *pargc; i++)
		argv[i] = strCopy((*pargv)[i]);
	*pargv  = argv;
 
	/* Check for ALDORARGS/AXIOMXLARGS environment variable. */
	envopts = osGetEnv("ALDORARGS");
	if (!envopts) envopts = osGetEnv("AXIOMXLARGS");
	if (envopts) {
		envopts = strCopy(envopts);
		for (i = *pargc - 1; i >= argi0; i--)
			(*pargv)[i+1] = (*pargv)[i];
		(*pargv)[argi0] = strCopy("-aFake");
		(*pargc)++;
		cmdOneResponse(pargc, pargv, envopts, argi0, argi0+1);
		nresps++;
		strFree(envopts);
	}

	while (cmdHasOption('a', NULL, *pargc, *pargv)) {
		String	 fileName = 0, fileText;
		FileName fn;
		int	 opt = 0, nextArg, startArg, j;
 
		for (nextArg = argi0, j = 0; ; ) {
			startArg = nextArg;
			opt = cmdGetOption(*pargc,*pargv,
					   &nextArg,&j,&fileName);

			/* Have response file option by itself. */
			if (optIs(opt, 'a'))
				break;
 
			/* Next option is response file option. Must be last */
			else if (j > 0 && optIs((*pargv)[startArg][j], 'a')) {
				int oldStartArg = startArg, oldJ = j;
				startArg = nextArg;
				opt = cmdGetOption(*pargc,*pargv,
						   &nextArg,&j,&fileName);
				(*pargv)[oldStartArg][oldJ] = '\0';
				++startArg;
				break;
			}
		}
 
		if (! fileName || ! fileName[0])
			/* Can't use cmdUseError here - no msg db! */
			comsgFatal(NULL,ALDOR_F_CmdBadOption,"-a",cmdName);
 
		fn = fnameParse(fileName);
		if (! fileIsReadable(fn))
			comsgFatal(NULL, ALDOR_F_CantOpen, fileName);
 
		/* We now have an existing response file */
		fileText = fileContentsString(fn);
		cmdOneResponse(pargc, pargv, fileText, startArg, nextArg);
		fileFreeContentsString(fileText);

		nresps++;
	}
 
	return nresps > 0;
}
예제 #20
0
/*
 * Executes SQL statement zSql on zDatabase, using parameters zArgs and file name substitutions zFileArgs
 * Result data is loaded onto pData, and pRowCnt and pColCnt will indicate number of loaded rows and
 * number of columns in the row. Total number of items in pData will be nRowCnt * nColCnt
 */
static int
_runSql(char *zDatabase, char *zSrcSql, char *zArgs, char *zFileArgs, Array_t *pData, int *pColCnt,
        char *zEntryFilePath,
        char *zSubstFileNames)
{
    int result;

    sqlite3 *pDB = NULL;
    sqlite3_stmt *pStmt = NULL;
    sqlite3_stmt *pArgsStmt = NULL;
    Array_t sqlArgs;
    char *zError = NULL;
    char *zFullFilePath = NULL;
    sqlite3_stmt *pSubstStmt = NULL;
    char *zFileContent = NULL;
    char *zSchemaSql = NULL;

    char *zSql = strCopy(zSrcSql, -1);

    /*
    * Only first 16 substitute parameters will be processed. This is related to the fact that in C there
    * is no non-hacking way to dynamically build variadic arguments. So, to support list of values we just
    * limit maximum number of substitute strings to reasonably high number (16)
    */
    const char *zz[16];
    memset(&zz, 0, sizeof(zz));

    Array_init(&sqlArgs, sizeof(SqlArg_t), (void *) _freeSqlArg);

    *pColCnt = 0;

    //    Array_init(pData, sizeof(sqlite3_value *), (void *) _freeSqliteValue);

    /*
    * Open database (use :memory: if not defined)
    */
    if (zDatabase == NULL || strlen(zDatabase) == 0)
    {
        zDatabase = ":memory:";
    }
    CHECK_CALL(sqlite3_open_v2(zDatabase, &pDB,
                               SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_SHAREDCACHE,
                               NULL));

    CHECK_CALL(sqlite3_enable_load_extension(pDB, 1));

    // load extension library
    CHECK_CALL(sqlite3_load_extension(pDB, "../../bin/libFlexilite", NULL, &zError));

    // load and run db schema
    CHECK_CALL(file_load_utf8("../../sql/dbschema.sql", &zSchemaSql));
    CHECK_CALL(sqlite3_exec(pDB, (const char *) zSchemaSql, NULL, NULL, &zError));

    /*
     * Substitute strings
     */
    if (!STR_EMPTY(zSubstFileNames))
    {
        CHECK_STMT_PREPARE(pDB, "select key, value from json_each(:1);", &pSubstStmt);
        CHECK_CALL(sqlite3_bind_text(pSubstStmt, 1, zSubstFileNames, -1, NULL));
        int nSubst = 0;
        while ((result = sqlite3_step(pSubstStmt)) == SQLITE_ROW)
        {
            if (nSubst >= 16)
            {
                result = SQLITE_ERROR;
                zError = "Number of substitute strings must not exceed 16";
                goto ONERROR;
            }
            sqlite3_free(zFullFilePath);
            zFullFilePath = NULL;

            Path_join(&zFullFilePath, zEntryFilePath, (char *) sqlite3_column_text(pSubstStmt, 1));

            CHECK_CALL(file_load_utf8(zFullFilePath, &zFileContent));

            zz[nSubst++] = zFileContent;
            zFileContent = NULL; // Memory will be freed by zz
        }
        if (result != SQLITE_DONE)
            goto ONERROR;

        char *zTemp = zSql;
        zSql = sqlite3_mprintf(zTemp, zz[0], zz[1], zz[2], zz[3], zz[4], zz[5], zz[6], zz[7], zz[8],
                               zz[9], zz[10], zz[11], zz[12], zz[13], zz[14], zz[15]);
        sqlite3_free(zTemp);
    }

    // TODO use flexi('init')

    CHECK_STMT_PREPARE(pDB, zSql, &pStmt);

    // Check if we have arguments JSON. Prepare arguments
    if (!STR_EMPTY(zArgs))
    {
        CHECK_STMT_PREPARE(pDB, "select value, type from json_each(:1);", &pArgsStmt);
        CHECK_CALL(sqlite3_bind_text(pArgsStmt, 1, zArgs, -1, NULL));
        int nArgCnt = 0;
        while ((result = sqlite3_step(pArgsStmt)) == SQLITE_ROW)
        {
            SqlArg_t item;
            memset(&item, 0, sizeof(item));
            item.pValue = sqlite3_value_dup(sqlite3_column_value(pArgsStmt, 0));
            Array_setNth(&sqlArgs, sqlArgs.iCnt, &item);
            nArgCnt++;
        }

        if (result != SQLITE_DONE)
            goto ONERROR;

        /*
         * Process file args
         */
        CHECK_CALL(sqlite3_reset(pArgsStmt));
        CHECK_CALL(sqlite3_bind_text(pArgsStmt, 1, zFileArgs, -1, NULL));
        while ((result = sqlite3_step(pArgsStmt)) == SQLITE_ROW)
        {
            int argNo = sqlite3_column_int(pArgsStmt, 0);
            if (argNo >= 1 && argNo <= nArgCnt)
            {
                sqlite3_free(zFullFilePath);
                zFullFilePath = NULL;

                SqlArg_t *arg = Array_getNth(&sqlArgs, (u32) argNo - 1);
                Path_join(&zFullFilePath, zEntryFilePath, (char *) sqlite3_value_text(arg->pValue));

                CHECK_CALL(file_load_utf8(zFullFilePath, &arg->zText));
            }
        }

        if (result != SQLITE_DONE)
            goto ONERROR;

        Array_each(&sqlArgs, (void *) _bindSqlArg, pStmt);
    }

    while ((result = sqlite3_step(pStmt)) == SQLITE_ROW)
    {
        if (*pColCnt == 0)
            *pColCnt = sqlite3_column_count(pStmt);
        int iCol;
        for (iCol = 0; iCol < *pColCnt; iCol++)
        {
            sqlite3_value *pVal = sqlite3_value_dup(sqlite3_column_value(pStmt, iCol));
            Array_setNth(pData, pData->iCnt, &pVal);
        }
    }

    if (result != SQLITE_DONE)
        goto ONERROR;
    result = SQLITE_OK;
    goto EXIT;

    ONERROR:
    Array_clear(pData);
    if (pDB && zError == NULL)
    {
        zError = (char *) sqlite3_errmsg(pDB);
    }
    if (zError != NULL)
        printf("Error: %s\n", zError);

    EXIT:

    sqlite3_free(zSchemaSql);
    sqlite3_finalize(pStmt);
    sqlite3_finalize(pArgsStmt);
    sqlite3_finalize(pSubstStmt);
    if (pDB != NULL)
    {
        result = sqlite3_close(pDB);
        if (result != SQLITE_OK)
        {
            printf("DB Close Error %d. %s\n", result, sqlite3_errmsg(pDB));
        }
    }
    Array_clear(&sqlArgs);
    sqlite3_free(zFullFilePath);
    sqlite3_free(zSql);

    for (int i = 0; i < ARRAY_LEN(zz); i++)
        sqlite3_free((void *) zz[i]);

    if (zFileContent != NULL)
        sqlite3_free(zFileContent);

    return result;
}
예제 #21
0
파일: buffer.c 프로젝트: nilqed/aldor
String
bufGetString(Buffer buf)
{
	String	s = strCopy(bufGets(buf));
	return strnFrAscii(s, strLength(s) + 1);
}
// means "We got some data from an inbound ledger"
void InboundLedgers::gotLedgerData (Job&, uint256 hash,
        boost::shared_ptr<protocol::TMLedgerData> packet_ptr, boost::weak_ptr<Peer> wPeer)
{
    protocol::TMLedgerData& packet = *packet_ptr;
    Peer::pointer peer = wPeer.lock ();

    WriteLog (lsTRACE, InboundLedger) << "Got data (" << packet.nodes ().size () << ") for acquiring ledger: " << hash;

    InboundLedger::pointer ledger = find (hash);

    if (!ledger)
    {
        WriteLog (lsTRACE, InboundLedger) << "Got data for ledger we're not acquiring";

        if (peer)
            peer->applyLoadCharge (LT_InvalidRequest);

        return;
    }

    ledger->noAwaitData ();

    if (!peer)
        return;

    if (packet.type () == protocol::liBASE)
    {
        if (packet.nodes_size () < 1)
        {
            WriteLog (lsWARNING, InboundLedger) << "Got empty base data";
            peer->applyLoadCharge (LT_InvalidRequest);
            return;
        }

        if (!ledger->takeBase (packet.nodes (0).nodedata ()))
        {
            WriteLog (lsWARNING, InboundLedger) << "Got invalid base data";
            peer->applyLoadCharge (LT_InvalidRequest);
            return;
        }

        SHAMapAddNode san = SHAMapAddNode::useful ();

        if ((packet.nodes ().size () > 1) && !ledger->takeAsRootNode (strCopy (packet.nodes (1).nodedata ()), san))
        {
            WriteLog (lsWARNING, InboundLedger) << "Included ASbase invalid";
        }

        if ((packet.nodes ().size () > 2) && !ledger->takeTxRootNode (strCopy (packet.nodes (2).nodedata ()), san))
        {
            WriteLog (lsWARNING, InboundLedger) << "Included TXbase invalid";
        }

        if (!san.isInvalid ())
        {
            ledger->progress ();
            ledger->trigger (peer);
        }
        else
            WriteLog (lsDEBUG, InboundLedger) << "Peer sends invalid base data";

        return;
    }

    if ((packet.type () == protocol::liTX_NODE) || (packet.type () == protocol::liAS_NODE))
    {
        std::list<SHAMapNode> nodeIDs;
        std::list< Blob > nodeData;

        if (packet.nodes ().size () <= 0)
        {
            WriteLog (lsINFO, InboundLedger) << "Got response with no nodes";
            peer->applyLoadCharge (LT_InvalidRequest);
            return;
        }

        for (int i = 0; i < packet.nodes ().size (); ++i)
        {
            const protocol::TMLedgerNode& node = packet.nodes (i);

            if (!node.has_nodeid () || !node.has_nodedata ())
            {
                WriteLog (lsWARNING, InboundLedger) << "Got bad node";
                peer->applyLoadCharge (LT_InvalidRequest);
                return;
            }

            nodeIDs.push_back (SHAMapNode (node.nodeid ().data (), node.nodeid ().size ()));
            nodeData.push_back (Blob (node.nodedata ().begin (), node.nodedata ().end ()));
        }

        SHAMapAddNode ret;

        if (packet.type () == protocol::liTX_NODE)
            ledger->takeTxNode (nodeIDs, nodeData, ret);
        else
            ledger->takeAsNode (nodeIDs, nodeData, ret);

        if (!ret.isInvalid ())
        {
            ledger->progress ();
            ledger->trigger (peer);
        }
        else
            WriteLog (lsDEBUG, InboundLedger) << "Peer sends invalid node data";

        return;
    }

    WriteLog (lsWARNING, InboundLedger) << "Not sure what ledger data we got";
    peer->applyLoadCharge (LT_InvalidRequest);
}
예제 #23
0
BOOL ParseLine::SetErrorMessage(LPCWSTR message, long position)
{
	strCopy(m_strErrorMessage, message);
	m_nErrorPosition = position;
	return FALSE;
}
예제 #24
0
파일: tree.cpp 프로젝트: Raimondi/scid
errorT
TreeCache::WriteFile (const char * fname)
{
#ifdef WINCE
    /*FILE **/Tcl_Channel  fp;
    fileNameT fullname;
    strCopy (fullname, fname);
    strAppend (fullname, TREEFILE_SUFFIX);

//    fp = fopen (fullname, "wb");
    fp = my_Tcl_OpenFileChannel(NULL, fullname, "w", 0666);
    if (fp == NULL) { return ERROR_FileOpen; }
 my_Tcl_SetChannelOption(NULL, fp, "-encoding", "binary");
 my_Tcl_SetChannelOption(NULL, fp, "-translation", "binary");

#else
    FILE * fp;
    fileNameT fullname;
    strCopy (fullname, fname);
    strAppend (fullname, TREEFILE_SUFFIX);

    fp = fopen (fullname, "wb");
    if (fp == NULL) { return ERROR_FileOpen; }
#endif
    writeFourBytes (fp, TREEFILE_MAGIC);
    writeTwoBytes (fp, SCID_VERSION);
    writeFourBytes (fp, CacheSize);
    writeFourBytes (fp, NumInUse);
    writeFourBytes (fp, LowestTotal);
    writeFourBytes (fp, LowestTotalIndex);

    for (uint count = 0; count < NumInUse; count++) {
        // Write this cached position:
        cachedTreeT * ctree = &(Cache[count]);
        writeOneByte (fp, ctree->toMove);
        for (squareT sq=0; sq < 64; sq++) {
            writeOneByte (fp, ctree->board[sq]);
        }
        // Write the moves:
        writeFourBytes (fp, ctree->tree.moveCount);
        writeFourBytes (fp, ctree->tree.totalCount);
        uint numMoves = ctree->tree.moveCount;
        for (uint i=0; i < numMoves; i++) {
            // Write this move node:
            treeNodeT * tnode = &(ctree->tree.node[i]);
            writeSimpleMove (fp, &(tnode->sm));
            writeString (fp, tnode->san, 8);
            for (uint res = 0; res < 4; res++) {
                writeFourBytes (fp, tnode->freq[res]);
            }
            writeFourBytes (fp, tnode->total);
            writeFourBytes (fp, tnode->score);
            writeTwoBytes (fp, tnode->ecoCode);
            writeFourBytes (fp, tnode->eloCount);
            writeFourBytes (fp, tnode->eloSum);
            writeFourBytes (fp, tnode->perfCount);
            writeFourBytes (fp, tnode->perfSum);
            writeFourBytes (fp, tnode->yearCount);
            writeFourBytes (fp, tnode->yearSum);
        }
        // Write the compressed filter:
        ctree->cfilter->WriteToFile (fp);
    }
#ifdef WINCE
    my_Tcl_Close(NULL, fp);
#else
    fclose (fp);
#endif
    return OK;
}
예제 #25
0
BOOL ParseLine::ParseFunction(LPWSTR &strCurr, BOOL bRHS)
{
	BOOL bResult = FALSE;

	skipWhitespaces(strCurr);

	LPWSTR startOfFunction = strCurr;

	LPWSTR endOfToken = findEndOfTokenName(strCurr);
	if (endOfToken == strCurr)
		return SetErrorMessage(L"Invalid character found", strCurr-m_strLine);

	if (bRHS)
		strCopy(RHS.FunctionName, strCurr, endOfToken - strCurr);
	else
		strCopy(LHS.FunctionName, strCurr, endOfToken - strCurr);

	strCurr = endOfToken;
	skipWhitespaces(strCurr);

	if (strCurr[0] == '(')
	{
		strCurr++;
		skipWhitespaces(strCurr);
		if (strCurr[0] != ')')
		{
			strCurr--;
			do
			{
				strCurr++;
				skipWhitespaces(strCurr);
				
				if (strCurr[0] == '"')
				{
					strCurr++;
					LPWSTR nextChr = strCurr;
					do
					{
						if (nextChr[0] == '\\')
						{
							if (nextChr[1] == '\0')
								return SetErrorMessage(L"Line continuation by using a backslash is not supported.", strCurr-m_strLine);
							nextChr += 2;
						}
						nextChr = wcspbrk(nextChr, L"\\\"");
						if (nextChr == NULL)
							return SetErrorMessage(L"Cannot find end of string", strCurr-m_strLine);
					} while (nextChr[0] != '"');

					if (bRHS)
						AddParameter(RHS, strCurr, nextChr - strCurr);
					else
						AddParameter(LHS, strCurr, nextChr - strCurr);

					strCurr = nextChr+1;
				}
				else
				{
					LPWSTR nextChr = wcspbrk(strCurr, L",)");
					if (nextChr == NULL)
						return SetErrorMessage(L"Cannot find next ',' or ')' in function", strCurr-m_strLine);

					for (nextChr-- ; ((nextChr > strCurr) && (isWhitespace(nextChr[0]))) ; nextChr--);
					if (nextChr >= strCurr)
						nextChr++;

					if (nextChr <= strCurr)
						return SetErrorMessage(L"Missing parameter", strCurr-m_strLine);

					if (bRHS)
						AddParameter(RHS, strCurr, nextChr - strCurr);
					else
						AddParameter(LHS, strCurr, nextChr - strCurr);

					strCurr = nextChr;
				}
				skipWhitespaces(strCurr);
			}
			while (strCurr[0] == ',');
		}

		if (strCurr[0] == '\0')
			return SetErrorMessage(L"End of line found. Expecting ',' or ')'", strCurr-m_strLine);
		if (strCurr[0] != ')')
			return SetErrorMessage(L"Invalid character found. Expecting ',' or ')'", strCurr-m_strLine);

		strCurr++;
		bResult = TRUE;
	}

	if (bRHS)
		strCopy(RHS.Function, startOfFunction, strCurr-startOfFunction);
	else
		strCopy(LHS.Function, startOfFunction, strCurr-startOfFunction);

	skipWhitespaces(strCurr);

	if (strCurr[0] == '=')
	{
		if (bRHS)
			return SetErrorMessage(L"Cannot assign twice. Unexpected '=' found", strCurr-m_strLine);

		m_bHasRHS = TRUE;

		strCurr++;
		LPWSTR endOfFunction = strCurr;
		return ParseFunction(endOfFunction, TRUE);
	}

	if (strCurr[0] == '\0')
		return TRUE;
	else if (strCurr[0] == '#')
		return TRUE;
	else
		return SetErrorMessage(L"Invalid character found. Expecting '=' or '('", strCurr-m_strLine);
}
예제 #26
0
파일: Des.cpp 프로젝트: starqiu/Ciper
/*
 *DES加密
 *输入:plainText 16位明文(16进制), key 16位密钥(16进制)
 *输出:result 加密后的结果 16位密文(16进制)
 */
void enDES(char* plainText,char* key,char* result){
	printf("加密数据开始!\n");

	char*  dataL=(char*) malloc(32*sizeof(char));//数据左半部分
	char*  dataR=(char*) malloc(32*sizeof(char));//数据右半部分
	char*  dataL_cp=(char*) malloc(32*sizeof(char));//数据左半部分拷贝
	char*  dataR_cp=(char*) malloc(32*sizeof(char));//数据右半部分拷贝
	char*  data_48=(char*) malloc(48*sizeof(char));//48位中间数据
	char*  data_64=(char*) malloc(64*sizeof(char));//64位初始数据初始置换后数据
	char*  data_64_I=(char*) malloc(64*sizeof(char));//64位初始数据
	//16个48位密钥空间
	char**  keys =(char**) malloc(16*sizeof(char*));
	for(int i=0;i<16;i++){
		*(keys+i) = (char*) malloc(48*sizeof(char));
	}
	//得到16个48位密钥
	gen_key(key,keys);
	//16进制明文转换成2进制
	hex2Binary(plainText,16,data_64_I);
	//初始置换
	init_pmt(data_64_I,data_64);
	strCopy(data_64,dataL,32);
	strCopy(data_64+32,dataR,32);

	//轮变换,循环16轮
	for(int rc=1;rc<=16;rc++){
		//printf("第%d轮数据:",rc);
		//扩展置换E
		pmt_E(dataR,data_48);
		strCopy(dataL,dataL_cp,32);
		strCopy(dataR,dataL,32);
		//异或
		for(int i = 0 ;i < 48;i++){
			data_48[i] = data_48[i]^keys[rc-1][i];
		}
		//S盒置换/选择
		pmt_S(data_48,dataR_cp);
		//P置换
		pmt_P(dataR_cp,dataR);
		//异或
		for(int i = 0 ;i < 32;i++){
			dataR[i] = dataL_cp[i]^dataR[i];
		}
		binary2Hex(dataL,32);//打印左半部分
		printf("  ");
		binary2Hex(dataR,32);//打印右半部分
		printf("\n");
	}

	//32位互换
	strCopy(dataR,data_64_I,32);
	strCopy(dataL,data_64_I+32,32);
	//逆初始置换
	init_pmt_reverse(data_64_I,data_64);
	printf("密文为: ");
	binary2Hex(data_64,result,64);

	free(data_64);
	free(dataL);
	free(dataR);
	free(dataL_cp);
	free(dataR_cp);
	free(data_48);
	free(data_64_I);
	free(keys);
}
예제 #27
0
//common parser method.
//This function takes the file name and get the data as stream.
Hash* parseFileDataStream(const char *fname)
{
    Hash *mp=(Hash *)malloc(sizeof(Hash)*N);
    hashInit(mp);
    int k=0,tempIdx=0,nOctact=0,len=0;
    char temp[4],temp1[4],charcter[4];
    char a[4],b[4],c[4],d[4];
    char ch,prvChar='\0';
    FILE *fptr=fopen(fname, "r");
    if(!fptr){
        perror("falied to open the file..");
        return NULL;
    }
    a[0]=b[0]=c[0]=d[0]='\0';
    while (( fscanf(fptr,"%c",&ch) ) != EOF) {
        if(ch!='.'){
            len++;
            temp[(len-1)%3]=ch;

            if(len<4)
                temp1[len-1]=ch;

            if(len>3)
            {
                tempIdx=(len-1)%3;
            }
        }
        else if(prvChar=='.'&&ch=='.')
        {
            len=0;
            nOctact=0;
        }

        else
        {
            nOctact++;
            temp1[3]='\0';
            if(len<=3)
                tempIdx=0;
            else
                tempIdx=(tempIdx+1)%3;

            int i=tempIdx,j;
            j=0;
            do{

                charcter[j]=temp[i];
                j++;
                if(len>3)
                    i=(i+1)%3;
                else
                    i=(i+1)%len;
            }while(i!=tempIdx);

            if(len>3)
                charcter[3]='\0';
            else
                charcter[len]='\0';
            switch(nOctact)
            {
                case 1:
                    strCopy(a,charcter,0,strlen(charcter)-1);
                    break;
                case 2:
                    strCopy(b,charcter,0,strlen(charcter)-1);
                    break;
                case 3:
                    strCopy(c,charcter,0,strlen(charcter)-1);
                    break;
                case 4:
                    if(len>3)
                        k=3;
                    else
                        k=len;
                    strCopy(d,temp1,0,k-1);
                    generateComb(a,d,b,c,mp);
            }
            if(len>3)
            {
                nOctact=1;
                strCopy(a,charcter,0,strlen(charcter)-1);
            }
            else if(nOctact==4)
            {
                nOctact=3;
                strCopy(a,b,0,strlen(b)-1);
                strCopy(b,c,0,strlen(c)-1);
                strCopy(c,d,0,strlen(d)-1);
            }
            len=0;
        }
        prvChar=ch;
    }

    if(nOctact==3)
    {
        if(len>3)
            k=3;
        else
            k=len;
        strCopy(d,temp1,0,k-1);
        generateComb(a,d,b,c,mp);
    }
    fclose(fptr);
    return mp;
}