コード例 #1
0
ファイル: lzhamtest.cpp プロジェクト: raedwulf/liblzham
static bool compare_files(const char *pFilename1, const char* pFilename2)
{
   FILE* pFile1 = open_file_with_retries(pFilename1, "rb");
   if (!pFile1)
   {
      print_error("Failed opening file: %s\n", pFilename1);
      return false;
   }

   FILE* pFile2 = open_file_with_retries(pFilename2, "rb");
   if (!pFile2)
   {
      print_error("Failed opening file: %s\n", pFilename2);
      fclose(pFile1);
      return false;
   }

   fseek(pFile1, 0, SEEK_END);
   int64 fileSize1 = _ftelli64(pFile1);
   fseek(pFile1, 0, SEEK_SET);

   fseek(pFile2, 0, SEEK_END);
   int64 fileSize2 = _ftelli64(pFile2);
   fseek(pFile2, 0, SEEK_SET);

   if (fileSize1 != fileSize2)
   {
      print_error("Files to compare are not the same size: %I64i vs. %I64i.\n", fileSize1, fileSize2);
      fclose(pFile1);
      fclose(pFile2);
      return false;
   }

   const uint cBufSize = 1024 * 1024;
   std::vector<uint8> buf1(cBufSize);
   std::vector<uint8> buf2(cBufSize);

   int64 bytes_remaining = fileSize1;
   while (bytes_remaining)
   {
      const uint bytes_to_read = static_cast<uint>(my_min(cBufSize, bytes_remaining));

      if (fread(&buf1.front(), bytes_to_read, 1, pFile1) != 1)
      {
         print_error("Failed reading from file: %s\n", pFilename1);
         fclose(pFile1);
         fclose(pFile2);
         return false;
      }

      if (fread(&buf2.front(), bytes_to_read, 1, pFile2) != 1)
      {
         print_error("Failed reading from file: %s\n", pFilename2);
         fclose(pFile1);
         fclose(pFile2);
         return false;
      }

      if (memcmp(&buf1.front(), &buf2.front(), bytes_to_read) != 0)
      {
         print_error("File data comparison failed!\n");
         fclose(pFile1);
         fclose(pFile2);
         return false;
      }

      bytes_remaining -= bytes_to_read;
   }

   fclose(pFile1);
   fclose(pFile2);
   return true;
}
コード例 #2
0
ファイル: main.cpp プロジェクト: pombreda/main
	void Process()
	{
		PathListIt it = paths.begin();
		while (it != paths.end()) {
			getFolderContent(*it);
			++it;
		}
		logInfo(L"Files to process:\t%8llu\n", data.size());

		logDebug(L"");
		std::sort(data.begin(), data.end(), CompareBySizeAndTime);
		std::pair<FilesListIt, FilesListIt> bounds;
		FilesListIt srch = data.begin();
		while (srch != data.end()) {
			logCounter(L"Files left:\t%8llu", std::distance(srch, data.end()));
			bounds = std::equal_range(srch, data.end(), *srch, CompareBySize);
			if (std::distance(bounds.first, bounds.second) == 1) {
				++Statistics::getInstance()->filesFoundUnique;
				data.erase(bounds.first);
			} else {
				while (srch != bounds.second) {
					FilesListIt it = srch;
					++it;
					shared_ptr<File>& f1 = *srch;
					while (it != bounds.second) {
						shared_ptr<File>& f2 = *it;
						AutoUTF buf1(f1->path());
						AutoUTF buf2(f2->path());
						{
							ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN);
							logDebug(L"Comparing files [size = %I64u]:\n", f1->size());
						}
						logDebug(L"  %s\n", buf1.c_str());
						logDebug(L"  %s\n", buf2.c_str());
						++Statistics::getInstance()->fileCompares;
						f1->refresh();
						f2->refresh();
						if (AttrMustMatch && f1->attr() != f2->attr()) {
							{
								ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
								logDebug(L"  Attributes of files do not match, skipping\n");
							}
							Statistics::getInstance()->fileMetaDataMismatch++;
							++it;
							break;
						}
						if (TimeMustMatch && f1->mtime() != f2->mtime()) {
							{
								ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
								logDebug(L"  Modification timestamps of files do not match, skipping\n");
							}
							Statistics::getInstance()->fileMetaDataMismatch++;
							++it;
							break;
						}
						if (!isSameVolume(*f1, *f2)) {
							{
								ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
								logDebug(L"  Files ignored - on different volumes\n");
							}
							++Statistics::getInstance()->filesOnDifferentVolumes;
							++it;
							break;
						}
						if (f1 == f2) {
							++Statistics::getInstance()->fileAlreadyLinked;
							{
								ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_GREEN);
								logDebug(L"  Files ignored - already linked\n");
							}
							++it;
							break;
						}
						if (f1->size() > FirstBlock) {
							if (!f1->LoadHashMini()) {
								break;
							}
							if (!f2->LoadHashMini()) {
								it = data.erase(it);
								continue;
							}
						} else {
							if (!f1->LoadHashFull()) {
								break;
							}
							if (!f2->LoadHashFull()) {
								it = data.erase(it);
								continue;
							}
						}
						if (isIdentical(*f1, *f2)) {
							++Statistics::getInstance()->fileContentSame;
							if (logLevel == LOG_VERBOSE) {
								{
									ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_BLUE | FOREGROUND_GREEN);
									logVerbose(L"Comparing files [size = %I64u]:\n", f1->size());
								}
								logVerbose(L"  %s\n", buf1.c_str());
								logVerbose(L"  %s\n", buf2.c_str());
							}
							{
								ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
								logVerbose(L"  Files are equal, hard link possible\n");
							}
							if (hardlink) {
								f1->hardlink(*f2);
							}
							Statistics::getInstance()->FreeSpaceIncrease += f1->size();
							it = data.erase(it);
						} else {
							{
								ConsoleColor col(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
								logDebug(L"  Files differ in content (hash)\n");
							}
							Statistics::getInstance()->hashComparesHit1++;
							++it;
						}
					}
					srch = data.erase(srch);
				}
			}
			srch = bounds.second;
		}
		logCounter(L"                              ");
	}
コード例 #3
0
ファイル: DFAContentModel.cpp プロジェクト: brock7/TianLong
void DFAContentModel::checkUniqueParticleAttribution (SchemaGrammar*    const pGrammar,
                                                      GrammarResolver*  const pGrammarResolver,
                                                      XMLStringPool*    const pStringPool,
                                                      XMLValidator*     const pValidator,
                                                      unsigned int*     const pContentSpecOrgURI,
                                                      const XMLCh*            pComplexTypeName /*= 0*/)
{

    SubstitutionGroupComparator comparator(pGrammarResolver, pStringPool);

    unsigned int i, j, k;

    // Rename the URI back
    for (i = 0; i < fElemMapSize; i++) {

        unsigned int orgURIIndex = fElemMap[i]->getURI();

        if ((orgURIIndex != XMLContentModel::gEOCFakeId) &&
            (orgURIIndex != XMLContentModel::gEpsilonFakeId) &&
            (orgURIIndex != XMLElementDecl::fgInvalidElemId) &&
            (orgURIIndex != XMLElementDecl::fgPCDataElemId)) {
            fElemMap[i]->setURI(pContentSpecOrgURI[orgURIIndex]);
        }
    }

    // Unique Particle Attribution
    // store the conflict results between any two elements in fElemMap
    // XMLContentModel::gInvalidTrans: not compared; 0: no conflict; 1: conflict
    unsigned int** fConflictTable = (unsigned int**) fMemoryManager->allocate
    (
        fElemMapSize * sizeof(unsigned int*)
    ); //new unsigned int*[fElemMapSize];

    // initialize the conflict table
    for (j = 0; j < fElemMapSize; j++) {
        fConflictTable[j] = (unsigned int*) fMemoryManager->allocate
        (
            fElemMapSize * sizeof(unsigned int)
        ); //new unsigned int[fElemMapSize];
        for (k = j+1; k < fElemMapSize; k++)
            fConflictTable[j][k] = XMLContentModel::gInvalidTrans;
    }

    // for each state, check whether it has overlap transitions
    for (i = 0; i < fTransTableSize; i++) {
        for (j = 0; j < fElemMapSize; j++) {
            for (k = j+1; k < fElemMapSize; k++) {
                if (fTransTable[i][j] != XMLContentModel::gInvalidTrans &&
                    fTransTable[i][k] != XMLContentModel::gInvalidTrans &&
                    fConflictTable[j][k] == XMLContentModel::gInvalidTrans) {

                    // If this is text in a Schema mixed content model, skip it.
                    if ( fIsMixed &&
                         (( fElemMap[j]->getURI() == XMLElementDecl::fgPCDataElemId) ||
                          ( fElemMap[k]->getURI() == XMLElementDecl::fgPCDataElemId)))
                        continue;

                    if (XercesElementWildcard::conflict(pGrammar,
                                                        fElemMapType[j],
                                                        fElemMap[j],
                                                        fElemMapType[k],
                                                        fElemMap[k],
                                                        &comparator)) {
                       fConflictTable[j][k] = 1;

                       XMLBuffer buf1(1023, fMemoryManager);
                       if (((fElemMapType[j] & 0x0f) == ContentSpecNode::Any) ||
                           ((fElemMapType[j] & 0x0f) == ContentSpecNode::Any_NS))
                           buf1.set(SchemaSymbols::fgATTVAL_TWOPOUNDANY);
                       else if ((fElemMapType[j] & 0x0f) == ContentSpecNode::Any_Other)
                           buf1.set(SchemaSymbols::fgATTVAL_TWOPOUNDOTHER);
                       else
                           buf1.set(fElemMap[j]->getRawName());

                       XMLBuffer buf2(1023, fMemoryManager);
                       if (((fElemMapType[k] & 0x0f) == ContentSpecNode::Any) ||
                           ((fElemMapType[k] & 0x0f) == ContentSpecNode::Any_NS))
                           buf2.set(SchemaSymbols::fgATTVAL_TWOPOUNDANY);
                       else if ((fElemMapType[k] & 0x0f) == ContentSpecNode::Any_Other)
                           buf2.set(SchemaSymbols::fgATTVAL_TWOPOUNDOTHER);
                       else
                           buf2.set(fElemMap[k]->getRawName());

                       pValidator->emitError(XMLValid::UniqueParticleAttributionFail,
                                             pComplexTypeName,
                                             buf1.getRawBuffer(),
                                             buf2.getRawBuffer());
                    }
                    else
                       fConflictTable[j][k] = 0;
                }
            }
        }
    }

    for (i = 0; i < fElemMapSize; i++)
        fMemoryManager->deallocate(fConflictTable[i]); //delete [] fConflictTable[i];
    fMemoryManager->deallocate(fConflictTable); //delete [] fConflictTable;
}
コード例 #4
0
ファイル: CharBuffer_test.cpp プロジェクト: scgg/server-model
static bool test()
{
    typedef CCharBuffer<Char> __Buffer;
    Char str[100] = {'a','b', 'c', 'd', 'e', 'f', 'g'};
    //ctor
    __Buffer buf1;
    __Buffer buf2(__CharP"abcdefg");
    const __Buffer buf3(str, sizeof str, 7);
    __Buffer buf4 = __CharP"abcdefg";
    if(buf1 == buf2)
        return false;
    if(buf2 != buf3)
        return false;
    if(buf3 != buf4)
        return false;
    if(buf2 != buf4)
        return false;
    if(!buf1.empty())
        return false;
    if(7 != buf2.size() || 7 != buf2.capacity())
        return false;
    if(sizeof str != buf3.capacity())
        return false;
    if(7 != buf4.capacity())
        return false;
    if(7 != buf4.length())
        return false;
    //assign
    buf1.assign(buf3);
    if(buf1 != buf3)
        return false;
    if(sizeof str != buf1.capacity())
        return false;
    buf2.assign(str, sizeof str, 7);
    if(buf2 != buf3)
        return false;
    if(sizeof str != buf2.capacity())
        return false;
    //copy
    Char str2[8] = {};
    if(7 != buf2.copy(str2, 7))
        return false;
    if(0 != strcmp((const char *)str, (const char *)str2))
        return false;
    //get_allocator
    typename __Buffer::allocator_type a = buf1.get_allocator();
    //begin, end
    typename __Buffer::value_type ch = 'A';
    typedef typename __Buffer::iterator __Iter;
    typedef typename __Buffer::const_iterator __CIter;
    for(__Iter i = buf1.begin();i != buf1.end();++i)
        *i = ch++;
    ch = 'A';
    for(__CIter i = buf3.begin();i != buf3.end();++i)
        if(*i != ch++)
            return false;
    //rbegin, rend
    typedef typename __Buffer::reverse_iterator __RIter;
    typedef typename __Buffer::const_reverse_iterator __CRIter;
    ch = 'A';
    for(__RIter i = buf1.rbegin();i != buf1.rend();++i)
        *i = ch++;
    ch = 'A';
    for(__CRIter i = buf3.rbegin();i != buf3.rend();++i)
        if(*i != ch++)
            return false;
    //operator []
    ch = 'A';
    for(size_t i = 0;i < buf1.size();++i)
        buf1[i] = ch++;
    ch = 'A';
    for(size_t i = 0;i < buf3.size();++i)
        if(buf3[i] != ch++)
            return false;
    //back
    buf1.back() = 'x';
    if(buf3.back() != 'x')
        return false;
    //at
    ch = 'A';
    for(size_t i = 0;i < buf1.size();++i)
        buf1.at(i) = ch++;
    ch = 'A';
    for(size_t i = 0;i < buf3.size();++i)
        if(buf3.at(i) != ch++)
            return false;
    //clear, empty
    if(buf2.empty())
        return false;
    buf2.clear();
    if(!buf2.empty())
        return false;
    //resize
    buf2.resize(7);
    if(7 != buf2.size())
        return false;
    //push_back
    buf2.clear();
    if(buf2 == buf4)
        return false;
    ch = 'a';
    for(int i = 0;i < 7;++i)
        buf2.push_back(ch + i);
    if(buf2 != buf4)
        return false;
    //swap
    buf2.swap(buf4);
    if(str == &buf2[0])
        return false;
    if(str != &buf4[0])
        return false;
    swap(buf4, buf2);
    if(str == &buf4[0])
        return false;
    if(str != &buf2[0])
        return false;
    //append
    buf1.clear();
    for(size_t i = 0;i < 10;++i)
        buf1.append(10, 'd');
    if(100 != buf1.size())
        return false;
    for(size_t i = 0;i < buf1.size();++i)
        if(buf1[i] != 'd')
            return false;
    buf1.clear();
    for(size_t i = 0;i < 20;++i)
        buf1.append(__CharP"ssdeb");
    if(100 != buf1.size())
        return false;
    for(size_t i = 0;i < buf1.size();i += 5)
        if(0 != memcmp(&buf1[i], "ssdeb", 5))
            return false;
    buf4.assign(__CharP"gadfdengb");
    buf1.clear();
    for(size_t i = 0;i < 20;++i)
        buf1.append(buf4, 4, 5);
    if(100 != buf1.size())
        return false;
    for(size_t i = 0;i < buf1.size();i += 5)
        if(0 != memcmp(&buf1[i], "dengb", 5))
            return false;
    buf4.resize(5);
    buf1.clear();
    for(size_t i = 0;i < 20;++i)
        buf1.append(buf4);
    if(100 != buf1.size())
        return false;
    for(size_t i = 0;i < buf1.size();i += 5)
        if(0 != memcmp(&buf1[i], "gadfd", 5))
            return false;
    //operator +=
    buf1.clear();
    for(size_t i = 0;i < 20;++i)
        buf1 += __CharP"sgdeb";
    if(100 != buf1.size())
        return false;
    for(size_t i = 0;i < buf1.size();i += 5)
        if(0 != memcmp(&buf1[i], "sgdeb", 5))
            return false;
    buf4.assign(__CharP"f90rg");
    buf1.clear();
    for(size_t i = 0;i < 20;++i)
        buf1 += buf4;
    if(100 != buf1.size())
        return false;
    for(size_t i = 0;i < buf1.size();i += 5)
        if(0 != memcmp(&buf1[i], "f90rg", 5))
            return false;
    buf1.clear();
    for(int i = 0;i < 100;++i)
        buf1 += 12 + i;
    if(100 != buf1.size())
        return false;
    for(size_t i = 0;i < buf1.size();++i)
        if(buf1[i] != 12 + int(i)){
            cerr<<"buf1["<<i<<"]="<<int(buf1[i])<<" is not "<<(12 + int(i))<<endl;
            return false;
        }
    //insert
    buf4.assign(__CharP"3e4r5");
    buf1.clear();
    buf1 += buf4;
    if(5 != buf1.size())
        return false;
    for(int i = 0;i < 19;++i)
        buf1.insert(i * 5 + 3, 5, 'a');
    if(100 != buf1.size()){
        cerr<<"1: buf1.size()="<<buf1.size()<<" is not 100\n";
        return false;
    }
    if(0 != memcmp(&buf1[0], &buf4[0], 3)){
        cerr<<"1: buf1[0]="<<&buf1[0]<<", buf4[0]="<<&buf4[0]<<endl;
        return false;
    }
    for(int i = 3;i < 98;++i)
        if('a' != buf1[i])
            return false;
    if(0 != memcmp(&buf1[98], &buf4[3], 2))
        return false;
    buf1.clear();
    buf1 += buf4;
    for(int i = 0;i < 19;++i)
        buf1.insert(i * 5 + 3, __CharP"3g89a", 5);
    if(100 != buf1.size()){
        cerr<<"2: buf1.size()="<<buf1.size()<<" is not 100\n";
        return false;
    }
    if(0 != memcmp(&buf1[0], &buf4[0], 3)){
        cerr<<"2: buf1[0]="<<&buf1[0]<<", buf4[0]="<<&buf4[0]<<endl;
        return false;
    }
    for(int i = 0;i < 19;++i)
        if(0 != memcmp("3g89a", &buf1[i * 5 + 3], 5))
            return false;
    if(0 != memcmp(&buf1[98], &buf4[3], 2))
        return false;
    buf1.clear();
    buf1 += buf4;
    for(int i = 0;i < 19;++i)
        buf1.insert(i * 5 + 3, __CharP"3g89a");
    if(100 != buf1.size()){
        cerr<<"3: buf1.size()="<<buf1.size()<<" is not 100\n";
        return false;
    }
    if(0 != memcmp(&buf1[0], &buf4[0], 3)){
        cerr<<"3: buf1[0]="<<&buf1[0]<<", buf4[0]="<<&buf4[0]<<endl;
        return false;
    }
    for(int i = 0;i < 19;++i)
        if(0 != memcmp("3g89a", &buf1[i * 5 + 3], 5))
            return false;
    if(0 != memcmp(&buf1[98], &buf4[3], 2))
        return false;
    buf4.assign(__CharP"23e32t2g22");
    buf1.clear();
    buf1.append(buf4, 0, 5);
    for(int i = 0;i < 19;++i)
        buf1.insert(i * 5 + 3, buf4, 4, 5);
    if(100 != buf1.size()){
        cerr<<"4: buf1.size()="<<buf1.size()<<" is not 100\n";
        return false;
    }
    if(0 != memcmp(&buf1[0], &buf4[0], 3)){
        cerr<<"4: buf1[0]="<<&buf1[0]<<", buf4[0]="<<&buf4[0]<<endl;
        return false;
    }
    for(int i = 0;i < 19;++i)
        if(0 != memcmp(&buf4[4], &buf1[i * 5 + 3], 5))
            return false;
    if(0 != memcmp(&buf1[98], &buf4[3], 2))
        return false;
    buf4.resize(5);
    buf1.clear();
    buf1.append(buf4);
    for(int i = 0;i < 19;++i)
        buf1.insert(i * 5 + 3, buf4);
    if(100 != buf1.size()){
        cerr<<"5: buf1.size()="<<buf1.size()<<" is not 100\n";
        return false;
    }
    if(0 != memcmp(&buf1[0], &buf4[0], 3)){
        cerr<<"5: buf1[0]="<<&buf1[0]<<", buf4[0]="<<&buf4[0]<<endl;
        return false;
    }
    for(int i = 0;i < 19;++i)
        if(0 != memcmp(&buf4[0], &buf1[i * 5 + 3], 5))
            return false;
    if(0 != memcmp(&buf1[98], &buf4[3], 2))
        return false;
    buf1.clear();
    buf1.append(buf4);
    for(int i = 0;i < 95;++i){
        __Iter p = buf1.insert(buf1.begin() + i + 3, 12 + i);
        if(*p != 12 + i)
            return false;
    }
    if(100 != buf1.size()){
        cerr<<"6: buf1.size()="<<buf1.size()<<" is not 100\n";
        return false;
    }
    if(0 != memcmp(&buf1[0], &buf4[0], 3)){
        cerr<<"6: buf1[0]="<<&buf1[0]<<", buf4[0]="<<&buf4[0]<<endl;
        return false;
    }
    for(int i = 0;i < 95;++i)
        if(12 + i != buf1[i + 3])
            return false;
    if(0 != memcmp(&buf1[98], &buf4[3], 2))
        return false;
    //replace
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, 3, '0');
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, 5, '1');
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 5, 3, 'a');
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, __CharP"000", 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, __CharP"11111", 5);
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 5, __CharP"aaa", 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, __CharP"000");
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, __CharP"11111");
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 5, __CharP"aaa");
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"00011111aaa");
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, buf4, 0, 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 3, buf4, 3, 5);
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(4, 5, buf4, 8, 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"000");
    buf1.replace(4, 3, buf4);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"11111");
    buf1.replace(4, 3, buf4);
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"aaa");
    buf1.replace(4, 5, buf4);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;

    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, 3, '0');
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, 5, '1');
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 9, 3, 'a');
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, __CharP"000", 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, __CharP"11111", 5);
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 9, __CharP"aaa", 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, __CharP"000");
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, __CharP"11111");
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 9, __CharP"aaa");
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"00011111aaa");
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, buf4, 0, 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, buf4, 3, 5);
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf1.replace(buf1.begin() + 4, buf1.begin() + 9, buf4, 8, 3);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"000");
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, buf4);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123000789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"11111");
    buf1.replace(buf1.begin() + 4, buf1.begin() + 7, buf4);
    if(12 != buf1.size())
        return false;
    if(0 != memcmp("012311111789", &buf1[0], buf1.size()))
        return false;
    buf4.assign(__CharP"aaa");
    buf1.replace(buf1.begin() + 4, buf1.begin() + 9, buf4);
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123aaa789", &buf1[0], buf1.size()))
        return false;
    //erase
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    __Iter p = buf1.erase(buf1.begin() + 1, buf1.end() - 2);
    if(*p != '8')
        return false;
    if(3 != buf1.size())
        return false;
    if(0 != memcmp("089", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    p = buf1.erase(buf1.begin() + 5);
    if(*p != '6')
        return false;
    if(9 != buf1.size())
        return false;
    if(0 != memcmp("012346789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.erase(3, 4);
    if(6 != buf1.size())
        return false;
    if(0 != memcmp("012789", &buf1[0], buf1.size()))
        return false;
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf1.erase(6);
    if(6 != buf1.size()){
        cerr<<"buf1.size()="<<buf1.size()<<" is not 6\n";
        return false;
    }
    return true;
    if(0 != memcmp("012345", &buf1[0], buf1.size()))
        return false;
    //substr
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(0 != memcmp("0123456789", &buf1[0], buf1.size()))
        return false;
    buf4 = buf1.substr(2, 7);
    if(7 != buf4.size())
        return false;
    if(0 != memcmp("2345678", &buf4[0], buf4.size()))
        return false;
    //compare
    buf1.clear();
    buf1 += __CharP"0123456789";
    if(10 != buf1.size())
        return false;
    if(buf1.compare(2, 5, __CharP"256444", 5))
        return false;
    if(!buf1.compare(2, 5, __CharP"23456444", 5))
        return false;
    if(buf1.compare(2, 5, __CharP"256444"))
        return false;
    if(!buf1.compare(2, 5, __CharP"23456"))
        return false;
    if(buf1.compare(__CharP"23425"))
        return false;
    if(!buf1.compare(__CharP"0123456"))
        return false;
    buf4.assign(__CharP"238623456444");
    if(buf1.compare(2, 6, buf4, 4, 8))
        return false;
    if(!buf1.compare(2, 5, buf4, 4, 8))
        return false;
    buf4.assign(__CharP"2345626234");
    if(buf1.compare(2, 6, buf4))
        return false;
    if(!buf1.compare(2, 5, buf4))
        return false;
    buf4.assign(__CharP"2623424");
    if(buf1.compare(buf4))
        return false;
    if(buf1 == buf4)
        return false;
    buf4.assign(__CharP"0123456789");
    if(!buf1.compare(buf4))
        return false;
    if(buf1 != buf4)
        return false;
    //operators ==, !=, <, <=, >, >=
    buf4.assign(__CharP"0123455789ag");
    if((buf1 == buf4))
        return false;
    if(!(buf1 != buf4))
        return false;
    if((buf1 < buf4))
        return false;
    if((buf1 <= buf4))
        return false;
    if(!(buf1 > buf4))
        return false;
    if(!(buf1 >= buf4))
        return false;
    buf4.assign(__CharP"012345678");
    if((buf1 == buf4))
        return false;
    if(!(buf1 != buf4))
        return false;
    if((buf1 < buf4))
        return false;
    if((buf1 <= buf4))
        return false;
    if(!(buf1 > buf4))
        return false;
    if(!(buf1 >= buf4))
        return false;
    buf4.assign(__CharP"0123456789");
    if(!(buf1 == buf4))
        return false;
    if((buf1 != buf4))
        return false;
    if((buf1 < buf4))
        return false;
    if(!(buf1 <= buf4))
        return false;
    if((buf1 > buf4))
        return false;
    if(!(buf1 >= buf4))
        return false;
    buf4.assign(__CharP"012345688");
    if((buf1 == buf4))
        return false;
    if(!(buf1 != buf4))
        return false;
    if(!(buf1 < buf4))
        return false;
    if(!(buf1 <= buf4))
        return false;
    if((buf1 > buf4))
        return false;
    if((buf1 >= buf4))
        return false;
    buf4.assign(__CharP"01234567890");
    if((buf1 == buf4))
        return false;
    if(!(buf1 != buf4))
        return false;
    if(!(buf1 < buf4))
        return false;
    if(!(buf1 <= buf4))
        return false;
    if((buf1 > buf4))
        return false;
    if((buf1 >= buf4))
        return false;

    const Char * cstr = __CharP"0123455789ag";
    if((buf1 == cstr))
        return false;
    if(!(buf1 != cstr))
        return false;
    if((buf1 < cstr))
        return false;
    if((buf1 <= cstr))
        return false;
    if(!(buf1 > cstr))
        return false;
    if(!(buf1 >= cstr))
        return false;
    cstr = __CharP"012345678";
    if((buf1 == cstr))
        return false;
    if(!(buf1 != cstr))
        return false;
    if((buf1 < cstr))
        return false;
    if((buf1 <= cstr))
        return false;
    if(!(buf1 > cstr))
        return false;
    if(!(buf1 >= cstr))
        return false;
    cstr = __CharP"0123456789";
    if(!(buf1 == cstr))
        return false;
    if((buf1 != cstr))
        return false;
    if((buf1 < cstr))
        return false;
    if(!(buf1 <= cstr))
        return false;
    if((buf1 > cstr))
        return false;
    if(!(buf1 >= cstr))
        return false;
    cstr = __CharP"012345688";
    if((buf1 == cstr))
        return false;
    if(!(buf1 != cstr))
        return false;
    if(!(buf1 < cstr))
        return false;
    if(!(buf1 <= cstr))
        return false;
    if((buf1 > cstr))
        return false;
    if((buf1 >= cstr))
        return false;
    cstr = __CharP"01234567890";
    if((buf1 == cstr))
        return false;
    if(!(buf1 != cstr))
        return false;
    if(!(buf1 < cstr))
        return false;
    if(!(buf1 <= cstr))
        return false;
    if((buf1 > cstr))
        return false;
    if((buf1 >= cstr))
        return false;

    cstr = __CharP"0123455789";
    buf4.assign(__CharP"0123455789ag");
    if((cstr == buf4))
        return false;
    if(!(cstr != buf4))
        return false;
    if((cstr < buf4))
        return false;
    if((cstr <= buf4))
        return false;
    if(!(cstr > buf4))
        return false;
    if(!(cstr >= buf4))
        return false;
    buf4.assign(__CharP"012345678");
    if((cstr == buf4))
        return false;
    if(!(cstr != buf4))
        return false;
    if((cstr < buf4))
        return false;
    if((cstr <= buf4))
        return false;
    if(!(cstr > buf4))
        return false;
    if(!(cstr >= buf4))
        return false;
    buf4.assign(__CharP"0123456789");
    if(!(cstr == buf4))
        return false;
    if((cstr != buf4))
        return false;
    if((cstr < buf4))
        return false;
    if(!(cstr <= buf4))
        return false;
    if((cstr > buf4))
        return false;
    if(!(cstr >= buf4))
        return false;
    buf4.assign(__CharP"012345688");
    if((cstr == buf4))
        return false;
    if(!(cstr != buf4))
        return false;
    if(!(cstr < buf4))
        return false;
    if(!(cstr <= buf4))
        return false;
    if((cstr > buf4))
        return false;
    if((cstr >= buf4))
        return false;
    buf4.assign(__CharP"01234567890");
    if((cstr == buf4))
        return false;
    if(!(cstr != buf4))
        return false;
    if(!(cstr < buf4))
        return false;
    if(!(cstr <= buf4))
        return false;
    if((cstr > buf4))
        return false;
    if((cstr >= buf4))
        return false;

    return true;
}
コード例 #5
0
ファイル: testFileSystem.cpp プロジェクト: JT-a/USD
PXR_NAMESPACE_USING_DIRECTIVE

ARCH_PRAGMA_DEPRECATED_POSIX_NAME

int main()
{
    std::string firstName = ArchMakeTmpFileName("archFS");
    FILE *firstFile;

    char const * const testContent = "text in a file";

    // Open a file, check that its length is 0, write to it, close it, and then
    // check that its length is now the number of characters written.
    ARCH_AXIOM((firstFile = ArchOpenFile(firstName.c_str(), "wb")) != NULL);
    fflush(firstFile);
    ARCH_AXIOM(ArchGetFileLength(firstName.c_str()) == 0);
    fputs(testContent, firstFile);
    fclose(firstFile);
    ARCH_AXIOM(ArchGetFileLength(firstName.c_str()) == strlen(testContent));

    // Map the file and assert the bytes are what we expect they are.
    ARCH_AXIOM((firstFile = ArchOpenFile(firstName.c_str(), "rb")) != NULL);
    ArchConstFileMapping cfm = ArchMapFileReadOnly(firstFile);
    fclose(firstFile);
    ARCH_AXIOM(cfm);
    ARCH_AXIOM(memcmp(testContent, cfm.get(), strlen(testContent)) == 0);
    cfm.reset();

    // Try again with a mutable mapping.
    ARCH_AXIOM((firstFile = ArchOpenFile(firstName.c_str(), "rb")) != NULL);
    ArchMutableFileMapping mfm = ArchMapFileReadWrite(firstFile);
    fclose(firstFile);
    ARCH_AXIOM(mfm);
    ARCH_AXIOM(memcmp(testContent, mfm.get(), strlen(testContent)) == 0);
    // Check that we can successfully mutate.
    mfm.get()[0] = 'T'; mfm.get()[2] = 's';
    ARCH_AXIOM(memcmp("Test", mfm.get(), strlen("Test")) == 0);
    mfm.reset();
    ArchUnlinkFile(firstName.c_str());

    // Test ArchPWrite and ArchPRead.
    int64_t len = strlen(testContent);
    ARCH_AXIOM((firstFile = ArchOpenFile(firstName.c_str(), "w+b")) != NULL);
    ARCH_AXIOM(ArchPWrite(firstFile, testContent, len, 0) == len);
    std::unique_ptr<char[]> buf(new char[len]);
    ARCH_AXIOM(ArchPRead(firstFile, buf.get(), len, 0) == len);
    ARCH_AXIOM(memcmp(testContent, buf.get(), len) == 0);
    char const * const newText = "overwritten in a file";
    ARCH_AXIOM(ArchPWrite(firstFile, newText, strlen(newText),
                      5/*index of 'in a file'*/) == strlen(newText));
    std::unique_ptr<char[]> buf2(new char[strlen("written in a")]);
    ARCH_AXIOM(ArchPRead(firstFile, buf2.get(), strlen("written in a"),
                     9/*index of 'written in a'*/) == strlen("written in a"));
    ARCH_AXIOM(memcmp("written in a", buf2.get(), strlen("written in a")) == 0);

    // create and remove a tmp subdir
    std::string retpath;
    retpath = ArchMakeTmpSubdir(ArchGetTmpDir(), "myprefix");
    ARCH_AXIOM (retpath != "");
    ArchRmDir(retpath.c_str());
    return 0;
}
コード例 #6
0
ファイル: CarbonTestMessages.cpp プロジェクト: zmyer/mcrouter
void ManyFields::deserialize(carbon::CarbonProtocolReader& reader) {
  reader.readStructBegin();
  while (true) {
    const auto pr = reader.readFieldHeader();
    const auto fieldType = pr.first;
    const auto fieldId = pr.second;

    if (fieldType == carbon::FieldType::Stop) {
      break;
    }

    switch (fieldId) {
      case 1: {
        reader.readField(buf1(), fieldType);
        break;
      }
      case 2: {
        reader.readField(buf2(), fieldType);
        break;
      }
      case 3: {
        reader.readField(buf3(), fieldType);
        break;
      }
      case 4: {
        reader.readField(buf4(), fieldType);
        break;
      }
      case 5: {
        reader.readField(buf5(), fieldType);
        break;
      }
      case 6: {
        reader.readField(buf6(), fieldType);
        break;
      }
      case 7: {
        reader.readField(buf7(), fieldType);
        break;
      }
      case 8: {
        reader.readField(buf8(), fieldType);
        break;
      }
      case 9: {
        reader.readField(buf9(), fieldType);
        break;
      }
      case 10: {
        reader.readField(buf10(), fieldType);
        break;
      }
      case 11: {
        reader.readField(buf11(), fieldType);
        break;
      }
      case 12: {
        reader.readField(buf12(), fieldType);
        break;
      }
      case 13: {
        reader.readField(buf13(), fieldType);
        break;
      }
      case 14: {
        reader.readField(buf14(), fieldType);
        break;
      }
      case 15: {
        reader.readField(buf15(), fieldType);
        break;
      }
      case 16: {
        reader.readField(buf16(), fieldType);
        break;
      }
      case 17: {
        reader.readField(buf17(), fieldType);
        break;
      }
      case 18: {
        reader.readField(buf18(), fieldType);
        break;
      }
      case 19: {
        reader.readField(buf19(), fieldType);
        break;
      }
      case 20: {
        reader.readField(buf20(), fieldType);
        break;
      }
      case 21: {
        reader.readField(buf21(), fieldType);
        break;
      }
      case 22: {
        reader.readField(buf22(), fieldType);
        break;
      }
      case 23: {
        reader.readField(buf23(), fieldType);
        break;
      }
      case 24: {
        reader.readField(buf24(), fieldType);
        break;
      }
      case 25: {
        reader.readField(buf25(), fieldType);
        break;
      }
      case 26: {
        reader.readField(buf26(), fieldType);
        break;
      }
      case 27: {
        reader.readField(buf27(), fieldType);
        break;
      }
      case 28: {
        reader.readField(buf28(), fieldType);
        break;
      }
      case 29: {
        reader.readField(buf29(), fieldType);
        break;
      }
      case 30: {
        reader.readField(buf30(), fieldType);
        break;
      }
      case 31: {
        reader.readField(buf31(), fieldType);
        break;
      }
      case 32: {
        reader.readField(buf32(), fieldType);
        break;
      }
      case 33: {
        reader.readField(buf33(), fieldType);
        break;
      }
      case 34: {
        reader.readField(buf34(), fieldType);
        break;
      }
      case 35: {
        reader.readField(buf35(), fieldType);
        break;
      }
      case 36: {
        reader.readField(buf36(), fieldType);
        break;
      }
      case 37: {
        reader.readField(buf37(), fieldType);
        break;
      }
      case 38: {
        reader.readField(buf38(), fieldType);
        break;
      }
      case 39: {
        reader.readField(buf39(), fieldType);
        break;
      }
      case 40: {
        reader.readField(buf40(), fieldType);
        break;
      }
      default: {
        reader.skip(fieldType);
        break;
      }
    }
  }
  reader.readStructEnd();
}
コード例 #7
0
ファイル: conv.cpp プロジェクト: preda/playground
int main(int argc, char **argv) {
  time();

  if (argc < 2) {
    printf("Usage: %s <exp> to Lucas-Lehmer test 2^exp - 1 \n", argv[0]);
    exit(1);
  }
  
  int exp = atoi(argv[1]);
  int words = SIZE / 2;
  int bitsPerWord = exp / words + 1;        // 'exp' being prime, 'words' does not divide it.
  if (bitsPerWord < 2) { bitsPerWord = 2; } // Min 2 bits/word.
  int wordsUsed = exp / bitsPerWord + 1;
  
  printf("Lucas-Lehmer test for 2^%d - 1. %d words, %d bits/word, %d words used\n",
         exp, words, bitsPerWord, wordsUsed);
  
  Context c;
  Queue queue(c);
  Program program;
  time("OpenCL init");
  
  program.compileCL2(c, "conv.cl");
  
  K(program, dif2);
  K(program, dif4);
  K(program, dif8);
  
  K(program, dit2);
  K(program, dit4);
  K(program, dit8);
  K(program, dit8d);
  

  // K(program, sq2k);
  K(program, mul);
  
  time("Kernels compilation");

  /*
  Buf bitsBuf(c, CL_MEM_READ_WRITE, sizeof(int) * words, 0);
  int data = 0;
  clEnqueueFillBuffer(queue.queue, bitsBuf.buf, &data, sizeof(data), 0, words, 0, 0, 0);
  data = 4; // LL seed
  queue.writeBlocking(bitsBuf, &data, sizeof(data));
  */

  int *data = new int[SIZE];
  
  srandom(0);
  for (int i = 0; i < SIZE; ++i) { data[i] = (random() & 0xffffff) - (1 << 23); }
  time("random");
  
  Buf buf1(c, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * SIZE, data);
  Buf buf2(c, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int) * SIZE, data);
  Buf bufTmp(c, CL_MEM_READ_WRITE, sizeof(int) * SIZE, 0);
  time("alloc gpu buffers");

  mul.setArgs(buf1);
  queue.run(mul, 256, 8 * 1024 * 1024 / 4);
  queue.finish();
  time("sq2k ini");

  for (int i = 0; i < 1000; ++i) {
    mul.setArgs(buf1);
    queue.run(mul, 256, 8 * 1024 * 1024 / 4);
  }
  queue.finish();
  time("sq2k");

  exit(0);
  
  for (int round = 3; round >= 0; round -= 2) {
    dif8.setArgs(round, buf1, bufTmp);
    queue.run(dif8, GS, SIZE / 32);
    dif8.setArgs(round - 1, bufTmp, buf1);
    queue.run(dif8, GS, SIZE / 32);
  }
  
  std::unique_ptr<long[]> tmpLong1(new long[SIZE]);
  {
    std::unique_ptr<int[]> tmp1(new int[SIZE]);
    queue.readBlocking(&buf1, 0, sizeof(int) * SIZE, tmp1.get());
    for (int i = 0; i < SIZE; ++i) {
      tmpLong1[i] = tmp1[i];
    }
  }
  Buf bufLong1(c, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(long) * SIZE, tmpLong1.get());
  Buf bufLongTmp(c, CL_MEM_READ_WRITE, sizeof(long) * SIZE, 0);

  for (int round = 0; round < 4; round += 2) {
    dit8.setArgs(round, bufLong1, bufLongTmp);
    queue.run(dit8, GS, SIZE / 32);
    dit8.setArgs(round + 1, bufLongTmp, bufLong1);
    queue.run(dit8, GS, SIZE / 32);
  }

  queue.readBlocking(&bufLong1, 0, sizeof(long) * SIZE, tmpLong1.get());
  int err = 0;
  for (int i = 0; i < SIZE; ++i) {
    if (data[i] != tmpLong1[i]) {
      printf("%d %d %ld\n", i, data[i], tmpLong1[i]);
      if (++err >= 10) { exit(1); }
    }
  }  
  time("OK FFT radix8 round-trip");
      
  for (int i = 0; i < 100; ++i) {
    for (int round = 11; round > 0; round -= 2) {
      dif2.setArgs(round, buf2, bufTmp);
      queue.run(dif2, GS, words);
      dif2.setArgs(round - 1, bufTmp, buf2);
      queue.run(dif2, GS, words);
    }
  }
  queue.finish();
  time("perf DIF2");
  
  for (int i = 0; i < 100; ++i) {
    for (int round = 5; round > 0; round -= 2) {
      dif4.setArgs(round, buf1, bufTmp);
      queue.run(dif4, GS, (words * 2) / 8);
      dif4.setArgs(round - 1, bufTmp, buf1);
      queue.run(dif4, GS, (words * 2) / 8);
    }
  }
  queue.finish();
  time("perf DIF4");

  for (int i = 0; i < 100; ++i) {
    for (int round = 3; round > 0; round -= 2) {
      dif8.setArgs(round, buf1, bufTmp);
      queue.run(dif8, GS, SIZE / 32);
      dif8.setArgs(round - 1, bufTmp, buf1);
      queue.run(dif8, GS, SIZE / 32);
    }
  }
  queue.finish();
  time("perf DIF8");

  for (int i = 0; i < 100; ++i) {
    for (int round = 0; round < 12; round += 2) {
      dit2.setArgs(round, bufLong1, bufLongTmp);
      queue.run(dit2, GS, SIZE / 2);
      dit2.setArgs(round + 1, bufLongTmp, bufLong1);
      queue.run(dit2, GS, SIZE / 2);
    }
  }
  queue.finish();
  time("perf DIT2");

  for (int i = 0; i < 100; ++i) {
    for (int round = 0; round < 6; round += 2) {
      dit4.setArgs(round, bufLong1, bufLongTmp);
      queue.run(dit4, GS, SIZE / 8);
      dit4.setArgs(round + 1, bufLongTmp, bufLong1);
      queue.run(dit4, GS, SIZE / 8);
    }
  }
  queue.finish();
  time("perf DIT4");

  for (int i = 0; i < 100; ++i) {
    for (int round = 0; round < 4; round += 2) {
      dit8.setArgs(round, bufLong1, bufLongTmp);
      queue.run(dit8, GS, SIZE / 32);
      dit8.setArgs(round + 1, bufLongTmp, bufLong1);
      queue.run(dit8, GS, SIZE / 32);
    }
  }
  queue.finish();
  time("perf DIT8");

  for (int i = 0; i < 100; ++i) {
    for (int round = 0; round < 4; round += 2) {
      dit8d.setArgs(round, bufLong1, bufLongTmp);
      queue.run(dit8d, GS, SIZE / 32);
      dit8d.setArgs(round + 1, bufLongTmp, bufLong1);
      queue.run(dit8d, GS, SIZE / 32);
    }
  }
  queue.finish();
  time("perf DIT8d");
  

  /*
  sq4k.setArgs(buf1, buf2);
  for (int i = 0; i < 1000; ++i) {
    queue.run(sq4k, GS, words * GS / (64 * 64));
  }
  queue.finish();
  time("sq4k");
  */

  
  /*
  // Initial DIF round on zero-padded input.
  difIniZeropad.setArgs(bitsBuf, buf2);

  for (int i = 0; i < 100; ++i) {
  queue.run(difIniZeropad, GS, SIZE / 4);

  dif2.setArgs(10, buf2, buf1);
  queue.run(dif2, GS, SIZE / 2);
  
  for (int i = 0; i < 5; ++i) {
    dif2.setArgs(9 - i * 2, buf1, buf2);
    queue.run(dif2, GS, SIZE / 2);
    dif2.setArgs(8 - i * 2, buf2, buf1);
    queue.run(dif2, GS, SIZE / 2);
  }
  }
  queue.finish();
  time("dif1");
  */

  
  //difIniZeropadShifted.setArgs(bitsBuf, buf2);
  
  /*
  for (int i = 0; i < 5; ++i) {
    dit2.setArgs(i * 2, bigBuf, tmpBuf);
    queue.run(dit2, GS, SIZE / 2);
    dit2.setArgs(i * 2 + 1, tmpBuf, bigBuf);
    queue.run(dit2, GS, SIZE / 2);
  }
  queue.finish();
  time("dit2");
  
  queue.readBlocking(bigBuf, 0, sizeof(int) * SIZE, big2);
  time("read from gpu");
  */

  /*
  int err = 0;
  for (int i = 0; i < SIZE; ++i) {
    if (big1[i] != big2[i]) {
      printf("%d %d %d\n", i, big1[i], big2[i]);
      ++err;
      if (err > 10) { break; }
    }
  }
  if (!err) {
    printf("OK\n");
  }
  */
}
コード例 #8
0
ファイル: main.cpp プロジェクト: sampeto/doukutsunetto
DWORD ServerHandler()
{

    bool running = true;

    // Socket handler
    SOCKET socketHnd;
    // Winsock data
    WSADATA wsaData;

    // Check for error
    if (WSAStartup(WSCK_V2, &wsaData))
    {
        errorFlags &= ERR_STARTUP;
        running = false;
    }

    // We want version 2
    if (wsaData.wVersion != WSCK_V2)
    {
        errorFlags &= ERR_WRONGVERSION;
        running = false;
    }

    // For TCP...
    SOCKADDR_IN sckAddr;
    sckAddr.sin_family = AF_INET;
    sckAddr.sin_port = htons(9009);	// Port 9009, will probably change to load from a config file later
    sckAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen from connections from ANY computer

    // Create the socket
    socketHnd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (socketHnd == INVALID_SOCKET)
    {
        errorFlags &= ERR_SOCKETERR;
        running = false;
    }

    if (bind(socketHnd, (LPSOCKADDR)&sckAddr, sizeof(sckAddr)) == SOCKET_ERROR)
    {
        errorFlags &= ERR_BINDERR;
        running = false;
    }

    if (running && errorFlags == 0)
    {
        MessageBoxA(NULL, "Server initialized, close this window to begin listening!", "Info", MB_ICONINFORMATION);
        // Listen with one backlog max
        listen(socketHnd, 1);
    }

    // player X and Y, 4 bytes at 0049E654 and 0049E658
    DWORD *playerX;
    DWORD *playerY;

    DWORD *playerMapID;

    PACKETHEADER PID;
    while (running)
    {
        playerX = (DWORD*)0x0049E654;
        playerY = (DWORD*)0x0049E658;

        playerMapID = (DWORD*)0x004A57F0;

        // Ctrl + F12 unloads the DLL
        if (GetKeyState(VK_CONTROL) && GetKeyState(VK_F12))
            running = false;

        // If polled to exit then stop running
        if (poll_exit)
            running = false;

        /*=========================================
        /* Data sending
        /*=========================================*/
        Buffer buf(13);	// 13 bytes in length
        buf.WriteByte(ID_LOC);
        buf.WriteInt((int)&playerX);
        buf.WriteInt((int)&playerY);
        buf.WriteInt((int)&playerMapID);

        send(socketHnd, (char*)buf.GetBytes(), buf.GetLength(), 0);
        //buf.Clear();

        Buffer buf2(80);
        // Pass the old buffer pointer
        recv(socketHnd, (char*)buf2.GetBytes(), sizeof(buf2.GetBytes())-1, 0);

        // Sleep to allow execution of other threads (and limit actions to about 30 FPS)
        Sleep(34);
    }

    //MessageBoxA(NULL, "test", "test", NULL);

    WSACleanup();

    //if (errorFlags > 0)
    //{
    //	char errMsg[1024];
    //	strcpy(errMsg, "There were error(s):\n");

    //	if (errorFlags & ERR_STARTUP)
    //		strcat(errMsg, "An error occurred while WinSock was initializing\n");
    //	if (errorFlags & ERR_WRONGVERSION)
    //		strcat(errMsg, "WinSock initialized the wrong version\n");
    //	if (errorFlags & ERR_SOCKETERR)
    //		strcat(errMsg, "Socket creation failed\n");
    //	if (errorFlags & ERR_BINDERR)
    //		strcat(errMsg, "Socket bind failed\n");
    //
    //	MessageBoxA(NULL, errMsg, "Error", MB_ICONERROR);
    //}

    return 0;
}
コード例 #9
0
ファイル: Schemes.cpp プロジェクト: ALPHAMARIOX/pn
void Scheme::Load(CScintilla& sc, bool allSettings, LPCTSTR filename)
{
	CFile cfile;
	SchemeHdrRec hdr;
	MsgRec Msg;
	TextRec Txt;
	PropRec Prp;
	char Next2;

	memset(&m_CommentSpec, 0, sizeof(CommentSpecRec));

	if( filename )
	{
		SetFileName(filename);
	}

	if( cfile.Open(m_SchemeFile) )
	{
		// Check the file is OK and read the header.
		if(!InitialLoad(cfile, hdr))
		{
			UNEXPECTED(_T("Tried to load invalid binary scheme file at run-time"));
			cfile.Close();
			return;
		}

		// Set the defaults - these may be changed by the load.
		SetupScintilla(sc, allSettings);

		std::vector<char> buf;

		while (cfile.GetPosition() < cfile.GetLength())
		{
			cfile.Read(&Next2, sizeof(char));
			switch(Next2)
			{
				case nrMsgRec:
					cfile.Read(&Msg, sizeof(MsgRec));
					sc.SPerform(Msg.MsgNum, Msg.wParam, Msg.lParam);
					break;
				case nrTextRec:
					{
						cfile.Read(&Txt, sizeof(TextRec));
						buf.resize(Txt.TextLength + 1);
						cfile.Read(&buf[0], Txt.TextLength*sizeof(char));
						buf[Txt.TextLength] = '\0';
						switch(Txt.TextType)
						{
							case ttFontName : 
								sc.SPerform(SCI_STYLESETFONT, Txt.wParam, (long)&buf[0]);
								break;
							case ttKeywords : 
								sc.SetKeyWords(Txt.wParam, &buf[0]);
								break;
							case ttLexerLanguage : 
								{
									sc.SPerform(SCI_SETLEXERLANGUAGE, 0, (long)&buf[0]);
									m_Lexer = &buf[0];
								}
								break;
							case ttWordChars :
								{
									sc.SPerform(SCI_SETWORDCHARS, 0, (long)&buf[0]);
								}
								break;
						}
					}
					break;
				case nrPropRec:
				{
					cfile.Read(&Prp, sizeof(PropRec));
					buf.resize(Prp.NameLength + 1);
					cfile.Read(&buf[0], Prp.NameLength * sizeof(char));
					buf[Prp.NameLength] = '\0';

					std::vector<char> buf2(Prp.ValueLength + 1);
					cfile.Read(&buf2[0], Prp.ValueLength * sizeof(char));
					buf2[Prp.ValueLength] = '\0';
					sc.SPerform(SCI_SETPROPERTY, (long)&buf[0], (long)&buf2[0]);
				}
				break;
				case nrCommentRec:
				{
					// skip here...
					cfile.Read(&m_CommentSpec, sizeof(CommentSpecRec));
				}
				break;
			}
		}

		cfile.Close();

		if((hdr.Flags & fldEnabled) && OPTIONS->GetCached(Options::OFoldingEnabled))
		{
			///@todo obviously these details need to come from settings somewhere...
			sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold", (LPARAM)"1");
			sc.SPerform(SCI_SETMARGINTYPEN, 2, SC_MARGIN_SYMBOL);
			sc.SPerform(SCI_SETMARGINMASKN, 2, SC_MASK_FOLDERS);
			sc.SPerform(SCI_SETMARGINSENSITIVEN, 2, true);
			sc.SPerform(SCI_SETMARGINWIDTHN, 2, 14);
			sc.SPerform(SCI_SETFOLDFLAGS, 16, 0);
			sc.SetFoldingMargins(efsVSNet);

			sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.compact", (LPARAM)((hdr.Flags & fldCompact) ? "1" : "0"));
			
			if(hdr.Flags & fldComments)
				sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.comment", (LPARAM)"1");

			if(hdr.Flags & fldPreProc)
				sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.preprocessor", (LPARAM)"1");

			if(hdr.Flags & fldElse) 
				sc.SPerform(SCI_SETPROPERTY, (WPARAM)"fold.at.else", (LPARAM)"1");
		}

		if(hdr.Flags & schOverrideTabs)
		{
			if(hdr.Flags & schUseTabs)
				sc.SPerform(SCI_SETUSETABS, 1, 0);
			else
				sc.SPerform(SCI_SETUSETABS, 0, 0);
		}

		if(hdr.Flags & schOverrideTabSize)
		{
			sc.SPerform(SCI_SETTABWIDTH, hdr.TabWidth, 0);
		}

	}
	else
	{
		// Show an error or something...
	}
}
コード例 #10
0
// Based on routines in gdb/remote.c
int
CeCosTestDownloadFilter::put_binary (unsigned char* buf, int len,
                                     unsigned long dl_address,
                                     int packet_size,
                                     CeCosSerial& serial)
{
    int i;
    unsigned char csum;
    Buffer buf2(packet_size);
    unsigned char ch;
    int tcount = 0;
    unsigned char *p, *p2, *plen;

    while (len > 0) {
        /* Subtract header overhead from MAX payload size:
           $M<memaddr>,<len>:#nn */
        int max_buf_size =
            buf2.Size()
            - ( 2 + hexnumlen(dl_address) + 1 + hexnumlen(buf2.Size()) + 4);

        /* Copy the packet into buffer BUF2, encapsulating it
           and giving it a checksum.  */
        int todo = MIN (len, max_buf_size);

        p = (unsigned char*) buf2.Data();
        *p++ = '$';

        // Add X header.
        *p++ = 'X';
        p += hexnumstr(p, dl_address);
        *p++ = ',';
        plen = p;			/* remember where len field goes */
        p += hexnumstr(p, todo);
        *p++ = ':';

        int escaped = 0;
        for (i = 0;
                (i < todo) && (i + escaped) < (max_buf_size - 2);
                i++)
        {
            switch (buf[i] & 0xff)
            {
            case '$':
            case '#':
            case 0x7d:
                /* These must be escaped */
                escaped++;
                *p++ = 0x7d;
                *p++ = (unsigned char) ((buf[i] & 0xff) ^ 0x20);
                break;
            default:
                *p++ = (unsigned char) (buf[i] & 0xff);
                break;
            }
        }

        if (i < todo)
        {
            /* Escape chars have filled up the buffer prematurely,
               and we have actually sent fewer bytes than planned.
               Fix-up the length field of the packet.  */

            /* FIXME: will fail if new len is a shorter string than
               old len.  */

            plen += hexnumstr (plen, i);
            *plen++ = ':';
        }

        // Calculate checksum
        p2 = (unsigned char*)buf2.Data();
        p2++; // skip $
        csum = 0;
        while (p2 < p)
            csum = (unsigned char)(csum + *p2++);
        *p++ = '#';
        *p++ = (unsigned char) tohex ((csum >> 4) & 0xf);
        *p++ = (unsigned char) tohex (csum & 0xf);

        /* Send it over and over until we get a positive ack.  */

        int resend = 1;
        const unsigned char* write_ptr = (const unsigned char*) buf2.Data();
        int write_len = (int)p-(int)buf2.Data();
        while (resend)
        {
            unsigned int __written;

            Trace("Sending bytes for %p-%p\n", dl_address, dl_address+i);
            TargetWrite(serial, write_ptr, write_len);

            /* read until either a timeout occurs (-2) or '+' is read */
            for(;;)
            {
                unsigned int __read;
                serial.Read(&ch, 1, __read);

                if (0 == __read) {
                    tcount ++;
                    if (tcount > 3) {
                        Trace("Timeout in putpkt_binary\n");
                        return 0;
                    }
                    break;		/* Retransmit buffer */
                }

                switch (ch)
                {
                case '+':
                    // Now expect OK packet from target
                    unsigned char ok_msg[6];// $OK#9a
                    serial.Read(ok_msg, 6, __read);

                    // Reply with ACK
                    serial.Write((void*)"+", 1, __written);

                    // And process next packet.
                    resend = 0;
                    break;

                case '-':
                    // Bad packet CRC. Retransmit.
                    Trace ("Bad CRC\n");
                    break;

                default:
                    Trace("Got junk..%02x\n", ch);
                    continue;           // keep reading
                }
                break;		/* Here to retransmit */
            }
        }

        len -= i;
        dl_address += i;
        buf += i;
    }

    return 1;
}
コード例 #11
0
ファイル: ArrayTest.cpp プロジェクト: AndreCAndersen/nupic
void nta::ArrayTest::testArrayCreation()
{
  boost::scoped_ptr<ArrayBase> arrayP;

  TestCaseIterator testCase;
  
  for(testCase = testCases_.begin(); testCase != testCases_.end(); testCase++)
  {
    char *buf = (char *) -1;
    
    if(testCase->second.testUsesInvalidParameters)
    {
      bool caughtException = false;

      try
      {
        arrayP.reset(new ArrayBase(testCase->second.dataType));
      }
      catch(nta::Exception)
      {
        caughtException = true;
      }

      TEST2("Test case: " +
              testCase->first +
              " - Should throw an exception on trying to create an invalid "
              "ArrayBase",
            caughtException);
    }
    else
    {
      arrayP.reset(new ArrayBase(testCase->second.dataType));
      buf = (char *) arrayP->getBuffer();
      TEST2("Test case: " +
              testCase->first +
              " - When not passed a size, a newly created ArrayBase should "
              "have a NULL buffer",
            buf == NULL);
      TESTEQUAL2("Test case: " +
                  testCase->first +
                  " - When not passed a size, a newly created ArrayBase should "
                  "have a count equal to zero",
                (size_t) 0, 
                arrayP->getCount());

      boost::scoped_array<char> buf2(new char[testCase->second.dataTypeSize *
                                              testCase->second.allocationSize]);
                                              
      arrayP.reset(new ArrayBase(testCase->second.dataType,
                             buf2.get(),
                             testCase->second.allocationSize));
      
      buf = (char *) arrayP->getBuffer();
      TEST2("Test case: " +
              testCase->first +
              " - Preallocating a buffer for a newly created ArrayBase should "
              "use the provided buffer",
            buf == buf2.get());
      TESTEQUAL2("Test case: " +
                  testCase->first +
                  " - Preallocating a buffer should have a count equal to our "
                  "allocation size",
                (size_t) testCase->second.allocationSize,
                arrayP->getCount());
    }    
  }
}
コード例 #12
0
ファイル: json.cpp プロジェクト: 1514louluo/acl
int main()
{
#if 1
	const char* sss =
		"[{\"DataKey1\": \"BindRule\", \"DataValue\": {\"waittime\": \"7\"}, \"null_key\": \"null\"},\r\n"
		"{\"DataKey2\": \"BindRule\", \"DataValue\": {\"waittime\": \"7\"}, \"null_key\": \"null\"},\r\n"
		"{\"member\": [25, 26, 27, 28, 29, true, false]},\r\n"
		"{\"max_uint64\": 18446744073709551615},\r\n"
		"[\"string\", true, false, 100, 200, 300, null, null],\r\n"
		"{\"hello world\": true, \"name\": null, \"age\": 25}]\r\n"
		"{\"hello\" : \"world\"} \r\n";
#else
	const char* sss = "{\"name\": \"100\"}";
#endif

	acl::json json;
	const char* ptr = json.update(sss);

	printf("-------------------------------------------------------\r\n");

	printf("%s\r\n", sss);

	printf("-------------------------------------------------------\r\n");

	printf("json finish: %s, left char: %s\r\n",
		json.finish() ? "yes" : "no", ptr);

	printf(">>>to string: %s\r\n", json.to_string().c_str());

	const char* ss =
		"[{\"DataKey1\": \"BindRule\", \"DataValue\": {\"waittime\": \"7\"}, \"null_key\": \"null\"}, "
		"{\"DataKey2\": \"BindRule\", \"DataValue\": {\"waittime\": \"7\"}, \"null_key\": \"null\"}, "
		"{\"member\": [25, 26, 27, 28, 29, true, false]}, "
		"{\"max_uint64\": 18446744073709551615 }, "
		"[\"string\", true, false, 100, 200, 300, null, null], "
		"{\"hello world\": true, \"name\": null, \"age\": 25}]";

	printf("-------------------------------------------------------\r\n");

	acl::string buf1(json.to_string()), buf2(ss);

	buf1.trim_space().trim_line();
	buf2.trim_space().trim_line();

	if (buf1 == buf2)
		printf("All OK\r\n\r\n");
	else
	{
		printf("Error\r\n");
		printf("-------------------------------------------------------\r\n");
		printf("%s\r\n", ss);
		printf("-------------------------------------------------------\r\n");
		printf("%s\r\n", json.to_string().c_str());
		printf("\r\n");
		exit (1);
	}
	

	test_type(json, "hello world");
	test_type(json, "name");
	test_type(json, "age");
	test_type(json, "member");
	test_type(json, "DataKey1");
	test_type(json, "DataValue");
	test_type(json, "null_key");
	test_type(json, "string");
	test_type(json, "waittime");
	test_type(json, "max_uint64");

	test_int64(json, "age");
	test_int64(json, "max_uint64");

#if defined(_WIN32) || defined(_WIN64)
	printf("Enter any key to exit ...");
	fflush(stdout);
	getchar();
#endif
	return 0;
}
コード例 #13
0
ファイル: buffer.hpp プロジェクト: niXman/yas
bool buffer_test(const char* archive_type, const char* io_type) {
    // binary: 4(header) + 4(string length) +21(string)= 29
    // text  : 5(header) +1(space) + 2(string length) + 1(space) +21(string) = 30
    static const char str1[] = "intrusive buffer test";

    yas::intrusive_buffer buf1(str1, sizeof(str1)-1);
    typename archive_traits::oarchive oa1;
    archive_traits::ocreate(oa1, archive_type, io_type);
    oa1 & buf1;

    // binary
    if ( yas::is_binary_archive<typename archive_traits::oarchive_type>::value ) {
        static const unsigned char _res64_le[] = {
            _HEADER_BYTES(),0x43,0x15,0x00,0x00,0x00,0x69,0x6e,0x74,0x72,0x75,0x73
            ,0x69,0x76,0x65,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char _res32_le[] = {
            _HEADER_BYTES(),0x03,0x15,0x00,0x00,0x00,0x69,0x6e,0x74,0x72,0x75,0x73
            ,0x69,0x76,0x65,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char _res64_be[] = {
            _HEADER_BYTES(),0x44,0x00,0x00,0x00,0x15,0x69,0x6e,0x74,0x72,0x75,0x73
            ,0x69,0x76,0x65,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char _res32_be[] = {
            _HEADER_BYTES(),0x03,0x00,0x00,0x00,0x15,0x69,0x6e,0x74,0x72,0x75,0x73
            ,0x69,0x76,0x65,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };

        const unsigned char *res_ptr = (
                                           YAS_PLATFORM_BITS_IS_64()
                                           ? oa1.is_little_endian() ? _res64_le : _res64_be
                                           : oa1.is_little_endian() ? _res32_le : _res32_be
                                       );
        const unsigned int   res_size= (
                                           YAS_PLATFORM_BITS_IS_64()
                                           ? oa1.is_little_endian() ? sizeof(_res64_le) : sizeof(_res64_be)
                                           : oa1.is_little_endian() ? sizeof(_res32_le) : sizeof(_res32_be)
                                       );

        if ( oa1.size() != res_size ) {
            std::cout << "BUFFER intrusive serialization error! [1]" << std::endl;
            return false;
        }
        if ( !oa1.compare(res_ptr, res_size) ) {
            std::cout << "BUFFER intrusive serialization error! [2]" << std::endl;
            return false;
        }
        // text
    } else if ( yas::is_text_archive<typename archive_traits::oarchive_type>::value ) {
        static const unsigned char res64[] = { // "yas49 0221intrusive buffer test"
            _HEADER_BYTES(),0x34,0x39,0x20,0x30,0x32,0x32,0x31,0x69,0x6e,0x74,0x72,0x75,0x73
            ,0x69,0x76,0x65,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char res32[] = { // "yas09 0221intrusive buffer test"
            _HEADER_BYTES(),0x30,0x39,0x20,0x30,0x32,0x32,0x31,0x69,0x6e,0x74,0x72,0x75,0x73
            ,0x69,0x76,0x65,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };

        const unsigned char *res_ptr = (YAS_PLATFORM_BITS_IS_64()) ? res64 : res32;
        const unsigned int  res_size = (YAS_PLATFORM_BITS_IS_64()) ? sizeof(res64) : sizeof(res32);

        if ( oa1.size() != res_size ) {
            std::cout << "BUFFER intrusive serialization error! [3]" << std::endl;
            return false;
        }
        if ( !oa1.compare(res_ptr, res_size) ) {
            std::cout << "BUFFER intrusive serialization error! [4]" << std::endl;
            return false;
        }
        // json
    } else if ( yas::is_json_archive<typename archive_traits::oarchive_type>::value ) {
        std::cout << "BUFFER intrusive serialization error! json is not implemented!" << std::endl;
        return false;
    }

    static const char str2[] = "shared buffer test"; // 18 + 4(header) + 4(size of array) = 26
    yas::shared_buffer buf2(str2, sizeof(str2)-1);
    typename archive_traits::oarchive oa2;
    archive_traits::ocreate(oa2, archive_type, io_type);
    oa2 & buf2;

    if ( yas::is_binary_archive<typename archive_traits::oarchive_type>::value ) {
        static const unsigned char _res64_le[] = {
            _HEADER_BYTES(),0x43,0x12,0x00,0x00,0x00,0x73,0x68,0x61
            ,0x72,0x65,0x64,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char _res32_le[] = {
            _HEADER_BYTES(),0x03,0x12,0x00,0x00,0x00,0x73,0x68,0x61
            ,0x72,0x65,0x64,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char _res64_be[] = {
            _HEADER_BYTES(),0x44,0x00,0x00,0x00,0x12,0x73,0x68,0x61
            ,0x72,0x65,0x64,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char _res32_be[] = {
            _HEADER_BYTES(),0x03,0x00,0x00,0x00,0x12,0x73,0x68,0x61
            ,0x72,0x65,0x64,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };

        const unsigned char *res_ptr = (
                                           YAS_PLATFORM_BITS_IS_64()
                                           ? oa2.is_little_endian() ? _res64_le : _res64_be
                                           : oa2.is_little_endian() ? _res32_le : _res32_be
                                       );
        const unsigned int   res_size= (
                                           YAS_PLATFORM_BITS_IS_64()
                                           ? oa2.is_little_endian() ? sizeof(_res64_le) : sizeof(_res64_be)
                                           : oa2.is_little_endian() ? sizeof(_res32_le) : sizeof(_res32_be)
                                       );

        if ( oa2.size() != res_size ) {
            std::cout << "BUFFER shared serialization error! [5]" << std::endl;
            return false;
        }
        if ( !oa2.compare(res_ptr, res_size) ) {
            std::cout << "BUFFER shared serialization error! [6]" << std::endl;
            return false;
        }
    } else if ( yas::is_text_archive<typename archive_traits::oarchive_type>::value ) {
        static const unsigned char res64[] = { // "yas4A 0218shared buffer test"
            _HEADER_BYTES(),0x34,0x39,0x20,0x30,0x32,0x31,0x38,0x73,0x68
            ,0x61,0x72,0x65,0x64,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };
        static const unsigned char res32[] = { // "yas09 0218shared buffer test"
            _HEADER_BYTES(),0x30,0x39,0x20,0x30,0x32,0x31,0x38,0x73,0x68
            ,0x61,0x72,0x65,0x64,0x20,0x62,0x75,0x66,0x66,0x65,0x72,0x20,0x74,0x65,0x73,0x74
        };

        const unsigned char* res_ptr = (YAS_PLATFORM_BITS_IS_64() ? res64 : res32);
        const unsigned int   res_size= (YAS_PLATFORM_BITS_IS_64() ? sizeof(res64) : sizeof(res32));

        if ( oa2.size() != res_size ) {
            std::cout << "BUFFER shared serialization error! [7]" << std::endl;
            return false;
        }
        if ( !oa2.compare(res_ptr, res_size) ) {
            std::cout << "BUFFER shared serialization error! [8]" << std::endl;
            return false;
        }
        typename archive_traits::iarchive ia1;
        archive_traits::icreate(ia1, oa2, archive_type, io_type);
        yas::shared_buffer buf4;
        ia1 & buf4;
        if ( buf4.size != sizeof(str2)-1 || memcmp(str2, buf4.data.get(), buf4.size) ) {
            std::cout << "BUFFER shared deserialization error! [9]" << std::endl;
            return false;
        }
    }

    return true;
}
コード例 #14
0
ファイル: stri_random.cpp プロジェクト: cran/stringi
/** Generate random permutations of code points in each string
 *
 * @param str character vector
 * @return character vector
 *
 * @version 0.2-1 (Marek Gagolewski, 2014-04-04)
 *
 * @version 0.3-1 (Marek Gagolewski, 2014-11-04)
 *    Issue #112: str_prepare_arg* retvals were not PROTECTed from gc
 *
 * @version 1.2.5 (Marek Gagolewski, 2019-07-23)
 *    #319: Fixed overflow in `stri_rand_shuffle()`.
 */
SEXP stri_rand_shuffle(SEXP str)
{
   PROTECT(str = stri_prepare_arg_string(str, "str"));
   R_len_t n = LENGTH(str);

   GetRNGstate();
   STRI__ERROR_HANDLER_BEGIN(1)
   StriContainerUTF8 str_cont(str, n);

   R_len_t bufsize = 0;
   for (R_len_t i=0; i<n; ++i) {
      if (str_cont.isNA(i)) continue;
      R_len_t ni = str_cont.get(i).length();
      if (ni > bufsize) bufsize = ni;
   }
   std::vector<UChar32> buf1(bufsize); // at most bufsize UChars32 (bufsize/4 min.)
   String8buf buf2(bufsize);

   SEXP ret;
   STRI__PROTECT(ret = Rf_allocVector(STRSXP, n));

   for (R_len_t i=0; i<n; ++i) {

      if (str_cont.isNA(i)) {
         SET_STRING_ELT(ret, i, NA_STRING);
         continue;
      }

      // fill buf1
      UChar32 c = (UChar32)0;
      const char* s = str_cont.get(i).c_str();
      R_len_t sn = str_cont.get(i).length();
      R_len_t j = 0;
      R_len_t k = 0;
      while (c >= 0 && j < sn) {
         U8_NEXT(s, j, sn, c);
         buf1[k++] = (int)c;
      }

      if (c < 0) {
         Rf_warning(MSG__INVALID_UTF8);
         SET_STRING_ELT(ret, i, NA_STRING);
         continue;
      }

      // do shuffle buf1 at pos 0..k-1: (Fisher-Yates shuffle)
      R_len_t cur_n = k;
      for (j=0; j<cur_n-1; ++j) {
         // rand from i to cur_n-1
         R_len_t r = (R_len_t)floor(unif_rand()*(double)(cur_n-j)+(double)j);
         UChar32 tmp = buf1[r];
         buf1[r] = buf1[j];
         buf1[j] = tmp;
      }

      // create string:
      char* buf2data = buf2.data();
      c = (UChar32)0;
      j = 0;
      k = 0;
      UBool err = FALSE;
      while (!err && k < cur_n) {
         c = buf1[k++];
         U8_APPEND((uint8_t*)buf2data, j, bufsize, c, err);
      }

      if (err) throw StriException(MSG__INTERNAL_ERROR);

      SET_STRING_ELT(ret, i, Rf_mkCharLenCE(buf2data, j, CE_UTF8));
   }

   PutRNGstate();
   STRI__UNPROTECT_ALL
   return ret;
   STRI__ERROR_HANDLER_END({
      PutRNGstate();
   })
}
コード例 #15
0
int main() try {
  typedef std::vector<uint8> Buffer;
  Buffer buf(1024);
  Buffer buf2(11024);

  // ----------- init

  char psetid[] = "1234567890123456";
  char test_value[] = "This is a test, This is a";
  char test_value_event[] = "This is a test Event, This is a";
  Strings hlt_names;
  Strings l1_names;

  hlt_names.push_back("a");  hlt_names.push_back("b");
  hlt_names.push_back("c");  hlt_names.push_back("d");
  hlt_names.push_back("e");  hlt_names.push_back("f");
  hlt_names.push_back("g");  hlt_names.push_back("h");
  hlt_names.push_back("i");

  l1_names.push_back("t10");  l1_names.push_back("t11");
  l1_names.push_back("t12");  l1_names.push_back("t13");
  l1_names.push_back("t14");  l1_names.push_back("t15");
  l1_names.push_back("t16");  l1_names.push_back("t17");
  l1_names.push_back("t18");  l1_names.push_back("t19");
  l1_names.push_back("t20");

  char reltag[]="CMSSW_0_8_0_pre7";
  std::string processName = "HLT";
  std::string outputModuleLabel = "HLTOutput";

  uLong crc = crc32(0L, Z_NULL, 0);
  Bytef* crcbuf = (Bytef*) outputModuleLabel.data();
  crc = crc32(crc, crcbuf, outputModuleLabel.length());

  uint32 adler32_chksum = (uint32)cms::Adler32((char*)&test_value[0], sizeof(test_value));
  std::string host_name = "mytestnode.cms";

  InitMsgBuilder init(&buf[0],buf.size(),12,
                      Version((const uint8*)psetid),
                      (const char*)reltag, processName.c_str(),
                      outputModuleLabel.c_str(), crc,
                      hlt_names,hlt_names,l1_names,
                      adler32_chksum, host_name.c_str());

  init.setDataLength(sizeof(test_value));
  std::copy(&test_value[0],&test_value[0]+sizeof(test_value),
            init.dataAddress());

  //Do a dumpInit here if you need to see the event.

  //Start the Streamer file
  std::cout <<"Trying to Write a Streamer file"<< std::endl;
  std::string initfilename = "teststreamfile.dat";
  StreamerOutputFile stream_writer(initfilename);

  std::cout << "Trying to Write Out The Init message into Streamer File: "
      << initfilename << std::endl;
  stream_writer.write(init);

  // ------- event

  std::vector<bool> l1bit(11);
  uint8 hltbits[] = "4567";
  const int hltsize = 9;  /** I am interested in 9 bits only */

  l1bit[0]=true;  l1bit[4]=true;  l1bit[8]=false;  //l1bit[12]=true;
  l1bit[1]=true;  l1bit[5]=false;  l1bit[9]=false;  //l1bit[13]=false;
  l1bit[2]=false;  l1bit[6]=true;  l1bit[10]=true;  //l1bit[14]=false;
  l1bit[3]=false;  l1bit[7]=false;  //l1bit[11]=true;  //l1bit[15]=true;
  //l1bit[16]=false;  l1bit[17]=false;  l1bit[18]=true;  l1bit[19]=true;

  //Lets Build 10 Events and then Write them into Streamer file.

  adler32_chksum = (uint32)cms::Adler32((char*)&test_value_event[0], sizeof(test_value_event));
  //host_name = "mytestnode.cms";

  for (uint32 eventId = 2000; eventId != 2000+NO_OF_EVENTS; ++eventId) {
    EventMsgBuilder emb(&buf2[0],buf2.size(),45,eventId,2,0xdeadbeef,3,
                      l1bit,hltbits,hltsize,adler32_chksum, host_name.c_str());
    emb.setOrigDataSize(78);
    emb.setEventLength(sizeof(test_value_event));
    std::copy(&test_value_event[0],&test_value_event[0]+sizeof(test_value_event),
             emb.eventAddr());

    //Lets write this to our streamer file .
    std::cout<<"Writing Event# : "<<eventId<<" To Streamer file"<< std::endl;
    stream_writer.write(emb);
  }

  //Write the EOF Record Both at the end of Streamer file
  uint32 dummyStatusCode = 1234;
  std::vector<uint32> hltStats;

  hltStats.push_back(32);
  hltStats.push_back(33);
  hltStats.push_back(34);

  stream_writer.writeEOF(dummyStatusCode, hltStats);

  return 0;
} catch(cms::Exception const& e) {
  std::cerr << e.explainSelf() << std::endl;
  return 1;
}
コード例 #16
0
TVerdict CWriteStringStep::doTestStepL()
/**
 * @return - TVerdict code
 * Override of base class pure virtual
 * Our implementation only gets called if the base class doTestStepPreambleL() did
 * not leave. That being the case, the current test result value will be EPass.
 */
	{
	INFO_PRINTF1(_L("This step tests WriteStringToConfig function."));
	SetTestStepResult(EFail);
	
	TPtrC originalValue;
	TBool ret = EFalse;
	
	if(!GetStringFromConfig(ConfigSection(),KTe_RegStepTestSuiteString, originalValue))
		{
		// Leave if there's any error.
		User::Leave(KErrNotFound);
		}

	INFO_PRINTF2(_L("The Original String is %S"), &originalValue); // Block end
	
	RBuf buf;
	buf.Create(originalValue.Length());
	buf.Copy(originalValue);
	
	_LIT(KText,"GoodBye Jason");
	TBufC<16> buf1(KText); 
	TPtrC TheString1(buf1);
	if (WriteStringToConfig(ConfigSection(), KTe_RegStepTestSuiteString, TheString1))
		{
		if (GetStringFromConfig(ConfigSection(), KTe_RegStepTestSuiteString, TheString1) && 0==TheString1.Compare(KText()))
			{
			INFO_PRINTF2(_L("Changed String To %S"),&TheString1); 
			ret = ETrue;
			}
		}
		
	_LIT(KText2,"Hello Jason");
	TBufC<16> buf2(KText2); 
	TPtrC TheString2(buf2);
	
	if (WriteStringToConfig(ConfigSection(), KTe_RegStepTestSuiteString, TheString2))
		{
		if (GetStringFromConfig(ConfigSection(), KTe_RegStepTestSuiteString, TheString2) && 0==TheString2.Compare(KText2()))
			{
			INFO_PRINTF2(_L("Changed String To %S"), &TheString2); 
			}
		}
	else
		{
		ret = EFalse;
		}
	
	if (!WriteStringToConfig(ConfigSection(), KTe_RegStepTestSuiteString, buf))
		{
		ret = EFalse;
		}
	buf.Close();
	
	if (ret)
		{
		SetTestStepResult(EPass);
		}
	
	return TestStepResult();
	}
コード例 #17
0
int main ()
{
  try 
  {
 
    /********** Setup ************/
    saga::session s;
    saga::context c ("opencloud");
    s.add_context  (c) ; 

    /********** Write File************/
    std::cout << std::endl ; 
    std::cout << std::endl ; 
    saga::filesystem::file f (s, "sector://test", saga::filesystem::ReadWrite ) ; 
    std::string towrite ("hello world !\n") ; 
    saga::const_buffer buf ( towrite.c_str(), towrite.length()) ; 
    f.write( buf, towrite.length()) ;  
    std::cout << "Written data: " << towrite ; 


    /********** Read File************/
    saga::mutable_buffer bufread ( towrite.length()) ; 
    f.read( bufread, towrite.length()) ; 
    std::cout << "Data read: " << (char*) bufread.get_data() ;  


    /********* Seek File ************/
    std::cout << "Seek to the end .. " << std::endl ; 
    f.seek( towrite.length(), saga::filesystem::Start ) ; 
    std::string w2 (" clouds!") ; 
    std::cout << "Write some more: " << w2 << std::endl ; 
    saga::const_buffer buf2( w2.c_str(), w2.length()) ; 
    f.write( buf2, w2.length()) ; 

    /********* Read new data ************/
    f.seek( 0, saga::filesystem::Start ) ; 
    saga::mutable_buffer bufread2( towrite.length() + w2.length() + 1 ) ; 
    f.read( bufread2, towrite.length() + w2.length() + 1 ) ; 
    std::cout << "Data read after seek and write: " << (char*) bufread2.get_data() << std::endl ; 

    f.close() ; 

    
    /********* Directory ***************/

    /*Create directories 
     */
    std::cout << std::endl ; 
    std::cout << "Create directory my_dir..." << std::endl ; 
    std::cout << "Create directory my_dir/another_dir..." << std::endl ; 
    saga::url dir ("sector://my_dir") ;
    saga::url dir2 ("sector://my_dir/another_dir") ;
    saga::filesystem::directory d( s, dir ) ; 
    saga::filesystem::directory d2( s, dir2 ) ; 

    /* Change working directory
     */
    std::cout << "Changing cwd to  my_dir/another_dir..." << std::endl ; 
    d.change_dir("another_dir") ; 
    std::cout << "Creating my_dir/another_dir/nested_dir ... " << std::endl ; 
    d.make_dir("nested_dir") ; 

    /* Populate Directories
     */
    std::cout << "Populate files in nested_dir ... " << std::endl ; 
    saga::filesystem::file f2 (s, "my_dir/another_dir/nested_dir/file1", saga::filesystem::ReadWrite ) ; 
    saga::filesystem::file f3 (s, "my_dir/another_dir/nested_dir/file2", saga::filesystem::ReadWrite ) ; 
    saga::filesystem::file f4 (s, "my_dir/another_dir/nested_dir/file3", saga::filesystem::ReadWrite ) ; 
    saga::filesystem::file f5 (s, "/makeme/file3", saga::filesystem::ReadWrite ) ; 
    f2.close() ; 
    f3.close() ; 
    f4.close() ; 
    f5.close() ; 

    /* List directory
     */
    d.change_dir("nested_dir") ; 
    std::vector <saga::url> listing = d.list() ; 
    std::cout << "List nested_dir ..." << std::endl ; 
    for ( std::vector<saga::url>::iterator i = listing.begin(); i != listing.end(); ++ i) 
    {
       std::cout << i->get_string() << std::endl ;  
    }

    /* Copy Files */
    d.copy( "file1", "sector:///" )  ; 

    return 0 ; 
   
  }
  catch ( const saga::exception & e )
  {
    std::cerr << e.what ();
  }
}