Ejemplo n.º 1
0
        int64_t LCMSerializerVisitor::calculateHash(int64_t v, const string &s) {
            v = calculateHash(v, s.length());

            string::const_iterator it = s.begin();
            while (it != s.end()) {
                const char c = (*it++);
                v = calculateHash(v, c);
            }

            return v;
        }
Ejemplo n.º 2
0
IntegerGroupParams
deriveIntegerGroupFromOrder(Bignum &groupOrder)
{
	IntegerGroupParams result;

	// Set the order to "groupOrder"
	result.groupOrder = groupOrder;

	// Try possible values for "modulus" of the form "groupOrder * 2 * i" where
	// "p" is prime and i is a counter starting at 1.
	for (uint32_t i = 1; i < NUM_SCHNORRGEN_ATTEMPTS; i++) {
		// Set modulus equal to "groupOrder * 2 * i"
		result.modulus = (result.groupOrder * Bignum(i*2)) + Bignum(1);

		// Test the result for primality
		// TODO: This is a probabilistic routine and thus not the right choice
		if (result.modulus.isPrime(256)) {

			// Success.
			//
			// Calculate the generators "g", "h" using the process described in
			// NIST FIPS 186-3, Appendix A.2.3. This algorithm takes ("p", "q",
			// "domain_parameter_seed", "index"). We use "index" value 1
			// to generate "g" and "index" value 2 to generate "h".
			uint256 seed = calculateSeed(groupOrder, "", 128, "");
			uint256 pSeed = calculateHash(seed);
			uint256 qSeed = calculateHash(pSeed);
			result.g(calculateGroupGenerator(Bignum(0), seed, pSeed, qSeed, result.modulus, result.groupOrder, 1));
			result.h(calculateGroupGenerator(Bignum(0), seed, pSeed, qSeed, result.modulus, result.groupOrder, 2));

			// Perform some basic tests to make sure we have good parameters
			if (!(result.modulus.isPrime()) ||                          // modulus is prime
			        !(result.groupOrder.isPrime()) ||                       // order is prime
			        !((result.g().pow_mod(result.groupOrder, result.modulus)).isOne()) || // g^order mod modulus = 1
			        !((result.h().pow_mod(result.groupOrder, result.modulus)).isOne()) || // h^order mod modulus = 1
			        ((result.g().pow_mod(Bignum(100), result.modulus)).isOne()) ||        // g^100 mod modulus != 1
			        ((result.h().pow_mod(Bignum(100), result.modulus)).isOne()) ||        // h^100 mod modulus != 1
			        result.g() == result.h() ||                                 // g != h
			        result.g().isOne()) {                                       // g != 1
				// If any of the above tests fail, throw an exception
				throw ZerocoinException("Group parameters are not valid");
			}

			return result;
		}
	}

	// If we reached this point group generation has failed. Throw an exception.
	throw ZerocoinException("Too many attempts to generate Schnorr group.");
}
Ejemplo n.º 3
0
//static
CoverArt CoverArtUtils::guessCoverArt(TrackPointer pTrack) {
    CoverArt art;
    art.info.source = CoverInfo::GUESSED;

    if (pTrack.isNull()) {
        return art;
    }

    const QFileInfo fileInfo(pTrack->getFileInfo());
    art.image = extractEmbeddedCover(fileInfo, pTrack->getSecurityToken());
    if (!art.image.isNull()) {
        // TODO() here we my introduce a duplicate hash code
        art.info.hash = calculateHash(art.image);
        art.info.coverLocation = QString();
        art.info.type = CoverInfo::METADATA;
        qDebug() << "CoverArtUtils::guessCoverArt found metadata art" << art;
        return art;
    }

    QLinkedList<QFileInfo> possibleCovers = findPossibleCoversInFolder(
            fileInfo.absolutePath());
    art = selectCoverArtForTrack(pTrack.data(), possibleCovers);
    if (art.info.type == CoverInfo::FILE) {
        qDebug() << "CoverArtUtils::guessCoverArt found file art" << art;
    } else {
        qDebug() << "CoverArtUtils::guessCoverArt didn't find art" << art;
    }
    return art;
}
Ejemplo n.º 4
0
QByteArray QInstaller::calculateHash(const QString &path, QCryptographicHash::Algorithm algo)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly))
        return QByteArray();
    return calculateHash(&file, algo);
}
Ejemplo n.º 5
0
bool DSIGReference::checkHash() {

	// Determine the hash value of the element and check if matches that stored in the
	// DigestValue part of the element

	// First set up for input

	XMLByte calculatedHashVal[CRYPTO_MAX_HASH_SIZE];		// The hash that we determined
	XMLByte readHashVal[CRYPTO_MAX_HASH_SIZE];			// The hash in the element

	unsigned int calculatedHashSize, i;

	if ((calculatedHashSize = calculateHash(calculatedHashVal, CRYPTO_MAX_HASH_SIZE)) == 0)
		return false;

	if (readHash(readHashVal, CRYPTO_MAX_HASH_SIZE) != calculatedHashSize)
		return false;

	for (i = 0; i < calculatedHashSize; ++i) {
		if (calculatedHashVal[i] != readHashVal[i])
			return false;

	}

	// Got through with flying colours!
	return true;

}
Ejemplo n.º 6
0
Definition::Definition(QVariantMap initialValues) {
    QStringList keys = QStringList() << "key" << "value" << "usage" << "notes"
                                     << "type" << "dictionaryHash" << "wordHash" << "sex";
    getValuesOf(&initialValues, keys);

    calculateHash();
}
Ejemplo n.º 7
0
Expression InitCompletion::getExpression(const QString &text, Scope &sc, bool showAllResults)
{
    Tree::parent = this;

    long cache_value = calculateHash(text);

    /* automatic cache mode */
    /* we save a hash value for all included files from the current file
    in the tags file, if it matches the hash of the current buffer, nothing
    has changed, and reuse the existing tags file */

    bool build_cache = true;
    QFile fCache(tagsFilePath);
    if(fCache.open(QIODevice::ReadOnly))
    {
        QString pattern = "!_TAG_CACHE\t" + QString::number(cache_value) + NEW_LINE;
        for (int i=0; i<10; i++)
            if (fCache.readLine() == pattern)
                build_cache = false;

        fCache.close();
    }
    if (build_cache)
        buildTagsFile(cache_value, text);

    /* We create a file with the parsed text */
    QFile f(parsedFilePath);
    f.open(QIODevice::WriteOnly | QIODevice::Text);
    f.write (text.toLocal8Bit());
    f.close();

    /* real parsing starts here */
    Parse parse(ctagsCmdPath, tagsFilePath, parsedFilePath, smallTagsFilePath);
    return parse.parseExpression(text, &sc, showAllResults);
}
Ejemplo n.º 8
0
OnlineLookup::OnlineLookup(QVariantMap initialValues){
    QStringList keys;
    keys << "name" << "url" << "sourceLanguage" << "index";
    getValuesOf(&initialValues, keys);

    calculateHash();
}
Ejemplo n.º 9
0
void images_duplicate_at(Image* image, uint32_t type, int index, int offset) {
	if(image == NULL)
		return;

	uint32_t totalLen = sizeof(Img2Header) + image->padded;
	uint8_t* buffer = (uint8_t*) malloc(totalLen);

	nor_read(buffer, image->offset, totalLen);
	Img2Header* header = (Img2Header*) buffer;
	header->imageType = type;

	if(index >= 0)
		header->index = index;

	calculateDataHash(buffer + sizeof(Img2Header), image->padded, header->dataHash);

	uint32_t checksum = 0;
	crc32(&checksum, buffer, 0x64);
	header->header_checksum = checksum;

	calculateHash(header, header->hash);

	nor_write(buffer, offset, totalLen);

	free(buffer);

	images_release();
	images_setup();
}
Ejemplo n.º 10
0
    static int findBestHashMultiplier (const StringArray& strings)
    {
        StringArray allStrings;

        for (int i = strings.size(); --i >= 0;)
            allStrings.addTokens (strings[i], "|", "");

        int v = 31;

        for (;;)
        {
            SortedSet <int> hashes;
            bool collision = false;
            for (int i = allStrings.size(); --i >= 0;)
            {
                const int hash = calculateHash (allStrings[i], v);
                if (hashes.contains (hash))
                {
                    collision = true;
                    break;
                }

                hashes.add (hash);
            }

            if (! collision)
                break;

            v += 2;
        }

        return v;
    }
Ejemplo n.º 11
0
    void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
                              const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
    {
        jassert (strings.size() == codeToExecute.size());
        const String indent (String::repeatedString (" ", indentLevel));
        const int hashMultiplier = findBestHashMultiplier (strings);

        out << indent << "int hash = 0;" << newLine
            << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
            << indent << "    while (*" << utf8PointerVariable << " != 0)" << newLine
            << indent << "        hash = " << hashMultiplier << " * hash + *" << utf8PointerVariable << "++;" << newLine
            << newLine
            << indent << "switch (hash)" << newLine
            << indent << "{" << newLine;

        for (int i = 0; i < strings.size(); ++i)
        {
            StringArray matchingStrings;
            matchingStrings.addTokens (strings[i], "|", "");

            for (int j = 0; j < matchingStrings.size(); ++j)
            {
                out << indent << "    case 0x" << hexString8Digits (calculateHash (matchingStrings[j], hashMultiplier)) << ":";

                if (j < matchingStrings.size() - 1)
                    out << newLine;
            }

            out << "  " << codeToExecute[i] << newLine;
        }

        out << indent << "    default: break;" << newLine
            << indent << "}" << newLine << newLine;
    }
Ejemplo n.º 12
0
    static unsigned int findBestHashMultiplier (const StringArray& strings)
    {
        unsigned int v = 31;

        for (;;)
        {
            SortedSet <unsigned int> hashes;
            bool collision = false;
            for (int i = strings.size(); --i >= 0;)
            {
                const unsigned int hash = calculateHash (strings[i], v);
                if (hashes.contains (hash))
                {
                    collision = true;
                    break;
                }

                hashes.add (hash);
            }

            if (! collision)
                break;

            v += 2;
        }

        return v;
    }
Ejemplo n.º 13
0
//static
CoverInfo CoverArtUtils::guessCoverInfo(const Track& track) {
    CoverInfo coverInfo;

    coverInfo.trackLocation = track.getLocation();
    coverInfo.source = CoverInfo::GUESSED;

    const QFileInfo fileInfo(track.getFileInfo());
    QImage image = extractEmbeddedCover(fileInfo, track.getSecurityToken());
    if (!image.isNull()) {
        // TODO() here we my introduce a duplicate hash code
        coverInfo.hash = calculateHash(image);
        coverInfo.coverLocation = QString();
        coverInfo.type = CoverInfo::METADATA;
        qDebug() << "CoverArtUtils::guessCover found metadata art" << coverInfo;
        return coverInfo;
    }

    QLinkedList<QFileInfo> possibleCovers = findPossibleCoversInFolder(
            fileInfo.absolutePath());
    coverInfo = selectCoverArtForTrack(track, possibleCovers);
    if (coverInfo.type == CoverInfo::FILE) {
        qDebug() << "CoverArtUtils::guessCover found file art" << coverInfo;
    } else {
        qDebug() << "CoverArtUtils::guessCover didn't find art" << coverInfo;
    }
    return coverInfo;
}
Ejemplo n.º 14
0
void images_write(Image* image, void* data, unsigned int length, int encrypt) {
	bufferPrintf("images_write(%x, %x, %x)\r\n", image, data, length);
	if(image == NULL)
		return;

	mtd_t *dev = images_device();
	if(!dev)
		return;

	mtd_prepare(dev);

	uint32_t padded = length;
	if((length & 0xF) != 0) {
		padded = (padded & ~0xF) + 0x10;
	}

	if(image->next != NULL && (image->offset + sizeof(Img2Header) + padded) >= image->next->offset) {
		bufferPrintf("**ABORTED** requested length greater than available space.\r\n");
		return;
	}

	uint32_t totalLen = sizeof(Img2Header) + padded;
	uint8_t* writeBuffer = (uint8_t*) malloc(totalLen);

	mtd_read(dev, writeBuffer, image->offset, sizeof(Img2Header));

	memcpy(writeBuffer + sizeof(Img2Header), data, length);

	if(encrypt)
		aes_838_encrypt(writeBuffer + sizeof(Img2Header), padded, NULL);

	Img2Header* header = (Img2Header*) writeBuffer;
	header->dataLen = length;
	header->dataLenPadded = padded;

	calculateDataHash(writeBuffer + sizeof(Img2Header), padded, header->dataHash);

	uint32_t checksum = 0;
	crc32(&checksum, writeBuffer, 0x64);
	header->header_checksum = checksum;

	calculateHash(header, header->hash);

	bufferPrintf("mtd_write(0x%p, %x, %x, %x)\r\n", dev, writeBuffer, image->offset, totalLen);

	mtd_write(dev, writeBuffer, image->offset, totalLen);

	bufferPrintf("mtd_write(0x%p, %x, %x, %x) done\r\n", dev, writeBuffer, image->offset, totalLen);

	free(writeBuffer);

	mtd_finish(dev);

	images_release();
	images_setup();

}
Ejemplo n.º 15
0
Word::Word(QVariantMap initialValues){
    //key is automatically generated here, only "name" and "dictionaryHash" are expected
    initialValues["name"] = Utils::makeName((initialValues["name"]).toString());
    initialValues["key"] = Utils::makeKey((initialValues["name"]).toString());

    QStringList keys = QStringList() << "name" << "key" << "dictionaryHash" ;
    getValuesOf(&initialValues, keys);

    calculateHash();
}
Ejemplo n.º 16
0
void MangoExact::loadQuery (Scanner &scanner)
{
   MoleculeAutoLoader loader(scanner);

   _context.setLoaderSettings(loader);
   loader.loadMolecule(_query);
   Molecule::checkForConsistency(_query);

   _initQuery(_query);

   calculateHash(_query, _query_hash);
}
Ejemplo n.º 17
0
void ServiceMgr::registerSystem(Systems::AbstractSystem *sys) {
    p_systems.push_back(sys);

    int id = calculateHash(sys->getName()) % p_lookupSize;
    if (p_lookup[id] == nullptr) {
        p_lookup[id] = new LookupEntry(sys->getName(), p_systems.size() - 1);
    } else {
        LookupEntry *entry = new LookupEntry(sys->getName(), p_systems.size() - 1);
        entry->next = p_lookup[id];
        p_lookup[id] = entry;
    }
}
Ejemplo n.º 18
0
bool OpenAddressingTable::insert(uint64_t table, uint64_t key, void* data, void** actualData /* = nullptr */) {
    checkDataKey(table, key);
    checkDataPtr(data);

    auto hash = calculateHash(table, key);
    for (auto pos = hash; pos < (hash + mCapacity); ++pos) {
        auto& entry = mBuckets[pos % mCapacity];
        auto ptr = entry.ptr.load();

        // Check if pointer is already acquired (i.e. not a deletion and not free) - Skip bucket if it is
        // There is no need to check if the insertion will conflict as this will be resolved at a later time.
        if ((ptr != (crossbow::to_underlying(EntryMarker::DELETED))
                && (ptr != crossbow::to_underlying(EntryMarker::FREE)))) {
            continue;
        }

        // Try to claim this bucket by setting the pointer to inserting
        // If this fails somebody else claimed the bucket in the mean time
        auto insertPtr = (reinterpret_cast<uintptr_t>(data) | crossbow::to_underlying(EntryMarker::INSERTING));
        if (!entry.ptr.compare_exchange_strong(ptr, insertPtr)) {
            continue;
        }

        // Write the key and table information
        // Table has to be written last as it is read last by readers to detect if key was written correctly
        entry.keyId.store(key);
        entry.tableId.store(table);

        // Check if another insert conflicts with ours
        // If this fails somebody else is inserting or has already inserted the same key, set pointer to invalid and
        // free bucket.
        if (hasInsertConflict(hash, pos, table, key, actualData)) {
            entry.ptr.store(crossbow::to_underlying(EntryMarker::INVALID));
            deleteEntry(entry);
            return false;
        }

        // Try to set the pointer from null or deleted to our data pointer
        // If this fails somebody else set the element to invalid and the bucket has to be released
        if (!entry.ptr.compare_exchange_strong(insertPtr, reinterpret_cast<uintptr_t>(data))) {
            deleteEntry(entry);

            if (actualData) *actualData = nullptr;
            return false;
        }

        return true;
    }

    LOG_ERROR("Hash table is full");
    return false;
}
Ejemplo n.º 19
0
int ServiceMgr::getSystemID(const std::string *name) {
    LookupEntry *entry = p_lookup[calculateHash(name) % p_lookupSize];

    if (entry == nullptr)
        return -1;

    while (entry->next != nullptr) {
        if (entry->name->compare(name->c_str()) != 0)
            entry = entry->next;
    }

    return entry->sys;
}
Ejemplo n.º 20
0
  void SText::trim() {
    const std::string& pWhitespace = " \t";
    const size_t beginStr = m_text.find_first_not_of(pWhitespace);

    if (beginStr == std::string::npos) return;

    const size_t endStr = m_text.find_last_not_of(pWhitespace);
    const size_t range = endStr - beginStr + 1;

    m_text = m_text.substr(beginStr, range);

    calculateHash();
  }
Ejemplo n.º 21
0
void images_from_template(Image* image, uint32_t type, int index, void* dataBuffer, unsigned int len, int encrypt) {
	if(image == NULL)
		return;

	mtd_t *dev = images_device();
	if(!dev)
		return;

	mtd_prepare(dev);

	uint32_t offset = MaxOffset + (SegmentSize - (MaxOffset % SegmentSize));
	uint32_t padded = len;
	if((len & 0xF) != 0) {
		padded = (padded & ~0xF) + 0x10;
	}

	uint32_t totalLen = sizeof(Img2Header) + padded;
	uint8_t* buffer = (uint8_t*) malloc(totalLen);

	mtd_read(dev, buffer, image->offset, sizeof(Img2Header));
	Img2Header* header = (Img2Header*) buffer;
	header->imageType = type;

	if(index >= 0)
		header->index = index;

	header->dataLen = len;
	header->dataLenPadded = padded;

	memcpy(buffer + sizeof(Img2Header), dataBuffer, len);
	if(encrypt)
		aes_838_encrypt(buffer + sizeof(Img2Header), padded, NULL);

	calculateDataHash(buffer + sizeof(Img2Header), image->padded, header->dataHash);

	uint32_t checksum = 0;
	crc32(&checksum, buffer, 0x64);
	header->header_checksum = checksum;

	calculateHash(header, header->hash);

	mtd_write(dev, buffer, offset, totalLen);

	free(buffer);

	mtd_finish(dev);

	images_release();
	images_setup();
}
Ejemplo n.º 22
0
void MangoExact::loadQuery (Scanner &scanner)
{
   MoleculeAutoLoader loader(scanner);

   loader.treat_x_as_pseudoatom = _context.treat_x_as_pseudoatom;
   loader.ignore_closing_bond_direction_mismatch =
           _context.ignore_closing_bond_direction_mismatch;
   loader.loadMolecule(_query);
   Molecule::checkForConsistency(_query);

   _initQuery(_query);

   calculateHash(_query, _query_hash);
}
Ejemplo n.º 23
0
Object* getMatchingObject(HashMap *map,void *key,int flag){
	int hash;
	List *list;
	Object *object;
	Iterator it;
	hash = calculateHash(map,key);
	list = get(map->buckets,hash);
	it = getIterator(list);
	while(it.hasNext(&it)){
		object = it.next(&it);
		if(map->compare(object->key,key))
			return object;
	}
	return NULL;
};
Ejemplo n.º 24
0
int put(HashMap *map,void *key,void *value){
	List *listOfHashObjects;
	Object *objectPrevoiuslyPresent,*object;
	int hash;
	if(map == NULL || key == NULL) return 0;
	objectPrevoiuslyPresent = getMatchingObject(map,key,0);
	if(objectPrevoiuslyPresent){
		objectPrevoiuslyPresent->values = value;
		return 1;
	}
	object = createObject(key,value);
	hash = calculateHash(map,key);
	listOfHashObjects = get(map->buckets,hash);
	insert(listOfHashObjects,object,1);
	rehashIfNeeded(map);
	return 1;
};
FontPlatformData::FontPlatformData(const FontPlatformData& other)
{
	m_font = other.m_font ? wkcFontNewCopyPeer(other.m_font) : 0;
	m_fontState = other.m_fontState;

    m_requestSize = other.m_requestSize;
    m_createdSize = other.m_createdSize;
    m_weight = other.m_weight;
    m_italic = other.m_italic;
    m_scale = other.m_scale;
    m_iscale = other.m_iscale;
    m_canScale = other.m_canScale;
    m_ascent = other.m_ascent;
    m_descent = other.m_descent;
    m_lineSpacing = other.m_lineSpacing;
    m_hashValue = calculateHash();
}
Ejemplo n.º 26
0
int removeHashObject(HashMap *map,void *key){
	List *list;
	Object *object;
	Iterator it;
	int index = 1,hash;
	if(key == NULL || map == NULL) return 0;
	hash = calculateHash(map,key);
	list = get(map->buckets,hash);
	it = getIterator(list);
	while(it.hasNext(&it)){
		object = it.next(&it);
		if(map->compare(object->key,key)){
			remove(list,index);
			return 1;
		}
		index++;
	}
	return 0;
};
Ejemplo n.º 27
0
T OpenAddressingTable::execOnElement(uint64_t table, uint64_t key, T notFound, F fun) const {
    auto hash = calculateHash(table, key);
    auto pos = hash;
    while (pos < (hash + mCapacity)) {
        auto& entry = mBuckets[pos % mCapacity];
        auto ptr = entry.ptr.load();

        // Check if pointer is marked as deleted, inserting or invalid - Skip bucket if it is
        if ((ptr & MARKER_MASK) != crossbow::to_underlying(EntryMarker::FREE)) {
            ++pos;
            continue;
        }

        // Check if this bucket marks the end of the overflow bucket - Return not-found if it is
        if (ptr == crossbow::to_underlying(EntryMarker::FREE)) {
            return notFound;
        }

        auto t = entry.tableId.load();
        auto k = entry.keyId.load();

        // Check if the pointer changed - Reload variables if it has
        // Needed to ensure the loaded ptr, table and key are consistent and were not changed by other threads in the
        // meantime. This does not suffer from the ABA problem as the table requires unique pointers and access through
        // an epoch.
        if (entry.ptr.load() != ptr) {
            continue;
        }

        // Check if bucket belongs to another element, skip bucket if it does
        if (t != table || k != key) {
            ++pos;
            continue;
        }

        // Element found
        return fun(entry, reinterpret_cast<const void*>(ptr));
    }

    LOG_ERROR("Hash table is full");
    return notFound;
}
Ejemplo n.º 28
0
void images_duplicate(Image* image, uint32_t type, int index) {
	if(image == NULL)
		return;

	mtd_t *dev = images_device();
	if(!dev)
		return;

	mtd_prepare(dev);

	uint32_t offset = MaxOffset + (SegmentSize - (MaxOffset % SegmentSize));

	uint32_t totalLen = sizeof(Img2Header) + image->padded;
	uint8_t* buffer = (uint8_t*) malloc(totalLen);

	mtd_read(dev, buffer, image->offset, totalLen);
	Img2Header* header = (Img2Header*) buffer;
	header->imageType = type;

	if(index >= 0)
		header->index = index;

	calculateDataHash(buffer + sizeof(Img2Header), image->padded, header->dataHash);

	uint32_t checksum = 0;
	crc32(&checksum, buffer, 0x64);
	header->header_checksum = checksum;

	calculateHash(header, header->hash);

	mtd_write(dev, buffer, offset, totalLen);

	free(buffer);

	mtd_finish(dev);

	images_release();
	images_setup();
}
Ejemplo n.º 29
0
Bignum
generateIntegerFromSeed(uint32_t numBits, uint256 seed, uint32_t *numIterations)
{
	Bignum      result(0);
	uint32_t    iterations = ceil((double)numBits / (double)HASH_OUTPUT_BITS);

#ifdef ZEROCOIN_DEBUG
	cout << "numBits = " << numBits << endl;
	cout << "iterations = " << iterations << endl;
#endif

	// Loop "iterations" times filling up the value "result" with random bits
	for (uint32_t count = 0; count < iterations; count++) {
		// result += ( H(pseed + count) * 2^{count * p0len} )
		result += Bignum(calculateHash(seed + count)) * Bignum(2).pow(count * HASH_OUTPUT_BITS);
	}

	result = Bignum(2).pow(numBits - 1) + (result % (Bignum(2).pow(numBits - 1)));

	// Return the number of iterations and the result
	*numIterations = iterations;
	return result;
}
Ejemplo n.º 30
0
    void createStringMatcher (OutputStream& out, const String& utf8PointerVariable,
                              const StringArray& strings, const StringArray& codeToExecute, const int indentLevel)
    {
        jassert (strings.size() == codeToExecute.size());
        const String indent (String::repeatedString (" ", indentLevel));
        const unsigned int hashMultiplier = findBestHashMultiplier (strings);

        out << indent << "unsigned int hash = 0;" << newLine
            << indent << "if (" << utf8PointerVariable << " != 0)" << newLine
            << indent << "    while (*" << utf8PointerVariable << " != 0)" << newLine
            << indent << "        hash = " << (int) hashMultiplier << " * hash + (unsigned int) *" << utf8PointerVariable << "++;" << newLine
            << newLine
            << indent << "switch (hash)" << newLine
            << indent << "{" << newLine;

        for (int i = 0; i < strings.size(); ++i)
        {
            out << indent << "    case 0x" << hexString8Digits ((int) calculateHash (strings[i], hashMultiplier))
                << ":  " << codeToExecute[i] << newLine;
        }

        out << indent << "    default: break;" << newLine
            << indent << "}" << newLine << newLine;
    }