Beispiel #1
0
	CacheEntry MemcachedCache::value(const QString& key) const
	{
		QReadLocker lock(&m_lock);

		const QByteArray rawKey(fullKey(key));

		char* rawData;
		size_t rawDataLength;
		uint32_t flags;
		memcached_return rt;

		rawData = memcached_get(
			m_memcached,
			rawKey.constData(),
			rawKey.length(),
			&rawDataLength,
			&flags,
			&rt
		);

		if(rt != MEMCACHED_SUCCESS && rt != MEMCACHED_NOTFOUND)
		{
			qFatal("Memcached error: %s", memcached_strerror(m_memcached, rt));
		}

		Q_ASSERT(rawDataLength >= sizeof(quint64) || !rawData);
		if(rawDataLength < sizeof(quint64) || !rawData)
		{
			return CacheEntry();
		}
		
		const quint64 timeStamp = qFromLittleEndian(*reinterpret_cast<quint64*>(rawData));
		const QByteArray data(rawData + sizeof(quint64), rawDataLength - sizeof(quint64));
		return CacheEntry(QDateTime::fromTime_t(timeStamp), data);
	}
Beispiel #2
0
Trail* Course::GetTrailForceRegenCache( StepsType st, CourseDifficulty cd ) const
{
	// Construct a new Trail, add it to the cache, then return it.
	CacheData &cache = m_TrailCache[ CacheEntry(st, cd) ];
	Trail &trail = cache.trail;
	trail.Init();
	if( !GetTrailSorted(st, cd, trail) )
	{
		// This course difficulty doesn't exist.
		cache.null = true;
		return NULL;
	}

	// If we have cached RadarValues for this trail, insert them.
	{
		RadarCache_t::const_iterator it = m_RadarCache.find( CacheEntry( st, cd ) );
		if( it != m_RadarCache.end() )
		{
			const RadarValues &rv = it->second;
			trail.SetRadarValues(rv);
		}
	}

	cache.null = false;
	return &cache.trail;
}
Beispiel #3
0
void Cache::load(const Common::String &name, Common::SeekableReadStream &stream) {
	// First check if the entry already exists
	if (_resources.contains(name))
		return;

	int32 signature = stream.readUint32BE();
	stream.seek(0);

	// Allocate a new cache entry
	_resources[name] = CacheEntry();
	CacheEntry &cacheEntry = _resources[name];

	// Check whether the file is compressed
	if (signature == MKTAG('L', 'Z', 'V', 26)) {
		// It's compressed, so decompress the file and store it's data in the cache entry
		Common::SeekableReadStream *decompressed = _vm->_res->decompress(stream);
		cacheEntry.resize(decompressed->size());
		decompressed->read(&cacheEntry[0], decompressed->size());

		delete decompressed;
	} else {
		// It's not, so read the raw data of the file into the cache entry
		cacheEntry.resize(stream.size());
		stream.read(&cacheEntry[0], stream.size());
	}
}
Beispiel #4
0
/* This is called by many simple functions, like Course::GetTotalSeconds, and may
 * be called on all songs to sort.  It can take time to execute, so we cache the
 * results.  Returned pointers remain valid for the lifetime of the Course.  If the
 * course difficulty doesn't exist, NULL is returned. */
Trail* Course::GetTrail( StepsType st, CourseDifficulty cd ) const
{
	ASSERT( cd != Difficulty_Invalid );

	// Check to see if the Trail cache is out of date
	if( m_iTrailCacheSeed != GAMESTATE->m_iStageSeed )
	{
		RegenerateNonFixedTrails();
		m_iTrailCacheSeed = GAMESTATE->m_iStageSeed;
	}

	// Look in the Trail cache
	{
		TrailCache_t::iterator it = m_TrailCache.find( CacheEntry(st, cd) );
		if( it != m_TrailCache.end() )
		{
			CacheData &cache = it->second;
			if( cache.null )
				return NULL;
			return &cache.trail;
		}
	}

	return GetTrailForceRegenCache( st, cd );
}
bool FrameManager::getTransform(const std::string& frame, ros::Time time, Ogre::Vector3& position, Ogre::Quaternion& orientation)
{
  boost::mutex::scoped_lock lock(cache_mutex_);

  position = Ogre::Vector3(9999999, 9999999, 9999999);
  orientation = Ogre::Quaternion::IDENTITY;

  if (fixed_frame_.empty())
  {
    return false;
  }

  M_Cache::iterator it = cache_.find(CacheKey(frame, time));
  if (it != cache_.end())
  {
    position = it->second.position;
    orientation = it->second.orientation;
    return true;
  }

  geometry_msgs::Pose pose;
  pose.orientation.w = 1.0f;

  if (!transform(frame, time, pose, position, orientation))
  {
    return false;
  }

  cache_.insert(std::make_pair(CacheKey(frame, time), CacheEntry(position, orientation)));

  return true;
}
RunLengthPredictor::RunLengthPredictor(size_t table_size,
                                       size_t pattern_size,
                                       size_t confidence_threshold)
    : cache(table_size, CacheEntry(pattern_size)),
      pattern(pattern_size),
      confidence_threshold(confidence_threshold)
{

}
void Cache::init() {
    Cache::_size = 0;
    // adding messages with errors
    _cache[HTTP_NOT_IMPLEMENTED] = CacheEntry();
    _cache[HTTP_NOT_IMPLEMENTED].add_data("HTTP/1.0 501 Not Implemented\r\n\r\n<html><head><title>501</title></head><body><h1>501 Not Implemented</h1><hr>Proxy</body></html>");
    _cache[HTTP_NOT_IMPLEMENTED].cached();

    _cache[HTTP_BAD_REQUEST] = CacheEntry();
    _cache[HTTP_BAD_REQUEST].add_data("HTTP/1.0 400 Bad Request\r\n\r\n<html><head><title>400</title></head><body><h1>400 Bad Request</h1><hr>Proxy</body></html>");
    _cache[HTTP_BAD_REQUEST].cached();

    _cache[HTTP_INTERNAL_ERROR] = CacheEntry();
    _cache[HTTP_INTERNAL_ERROR].add_data("HTTP/1.0 500 Internal Error\r\n\r\n<html><head><title>500</title></head><body><h1>500 Internal Error</h1><hr>Proxy</body></html>");
    _cache[HTTP_INTERNAL_ERROR].cached();

    _cache[HTTP_SERVICE_UNAVAILABLE] = CacheEntry();
    _cache[HTTP_SERVICE_UNAVAILABLE].add_data("HTTP/1.0 503 Service Unavailable\r\n\r\n<html><head><title>503</title></head><body><h1>503 Service Unavailable</h1><hr>Proxy</body></html>");
    _cache[HTTP_SERVICE_UNAVAILABLE].cached();
}
Beispiel #8
0
void BlockCache::put(nodeid_t id, const mempage &mem)
{
    m_cache.insert(CacheEntry(id, mem));
    m_size += mem.size();

    while (m_size > m_maxSize && !m_cache.empty())
    {
        m_size -= m_cache.get<1>().front().block.size();
        m_cache.get<1>().pop_front();
    }
}
Beispiel #9
0
 //--------------------------------------------------------------------------//
 //--------------------------------------------------------------------------//
 Font::CacheEntry* Font::cache(const String &msg){
   m_cache.push_back( CacheEntry() );
   CacheEntry &ce=m_cache.back();
   ce.hash         =gen_hash( (const byte*)&m_position, sizeof(m_position) );
   ce.hash         =gen_hash(msg, ce.hash);
   ce.lastUsed     =m_counter;
   ce.vertCount    =msg.length()*4;
   ce.verts        =new Vertex[ce.vertCount];
   m_cacheUpdated  =false;
   return &ce;
 }
// returns the resource ID being stored, for callsite convenience
uint32_t ResourceIdCache::store(const android::String16& package,
        const android::String16& type,
        const android::String16& name,
        bool onlyPublic,
        uint32_t resId) {
    if (mIdMap.size() < MAX_CACHE_ENTRIES) {
        const String16 hashedName = makeHashableName(package, type, name, onlyPublic);
        const uint32_t hashcode = hash(hashedName);
        mIdMap[hashcode] = CacheEntry(hashedName, resId);
    }
    return resId;
}
Beispiel #11
0
void Settings::makeSettingsCache(const QString &groupPath, GroupPathCache &groupPathCache, ConfigOptionGroup *group)
{
	ConfigOption *option;

	for (ConfigOptionGroup::size_type i = 0, size = group->size(); i < size; ++i)
		if ((option = group->at(i))->type() == ConfigOption::Value)
		{
			Q_ASSERT_X(!m_cache.contains(static_cast<ConfigOptionValue*>(option)->id()), "Settings::makeSettingsCache", "Settings can not have same id");
			m_cache[static_cast<ConfigOptionValue*>(option)->id()] = CacheEntry(static_cast<ConfigOptionValue*>(option), groupPath);
		}
		else
			makeSettingsCache(QString(groupPath).append(QChar(L'.')).append(option->title()), groupPathCache, static_cast<ConfigOptionGroup*>(option));
}
Beispiel #12
0
BOOL
StoreManager::SmiDisplayCacheInformation(
    _In_ ULONG64 CacheManager,
    _In_ ULONG CacheIndex
)
/*++

Routine Description:

    Description.

Arguments:

    CacheManager -
    CacheIndex - 

Return Value:

    BOOLEAN.

--*/
{
    WCHAR UniqueId[256 + 1] = { 0 };

    ExtRemoteUnTyped CacheRef(CacheManager, "nt!_SMC_CACHE_REF");
    ULONG64 CachePtr = CacheRef.ArrayElement(CacheIndex).Field("Cache").GetPtr();
    if (CachePtr == 0) return FALSE;

    if (!IsValid(CachePtr)) return FALSE;

    ExtRemoteUnTyped CacheEntry(CachePtr, "nt!_SMC_CACHE");

    g_Ext->Dml("<col fg=\"changed\">Cache @ 0x%I64X</col>\n", CachePtr);

    ULONG64 CacheFileSize = CacheEntry.Field("CacheParams.CacheFileSize").GetUlong64();
    ULONG64 FileHandle = CacheEntry.Field("FileInfo.FileHandle").GetPtr();
    ULONG64 FileObject = CacheEntry.Field("FileInfo.FileObject").GetPtr();

    g_Ext->Dml("    CacheIndex: %d# Store Manager cache file size = %I64d bytes (%d Mb) (%d Gb)\n",
        CacheIndex,
        CacheFileSize,
        CacheFileSize / (1024 * 1024),
        CacheFileSize / (1024 * 1024 * 1024));
    g_Ext->Dml("    Handle: <link cmd=\"!handle 0x%I64X\">0x%I64X</link>\n"
               "    FileObject: <link cmd=\"!fileobj 0x%I64X\">0x%I64X</link> (<link cmd=\"dt nt!_FILE_OBJECT 0x%I64X -b\">more</link>)\n",
               FileHandle, FileHandle,
               FileObject, FileObject, FileObject);
    g_Ext->Dml("    ID: %ws\n\n", CacheEntry.Field("UniqueId").GetString(UniqueId, _countof(UniqueId)));

    return TRUE;
}
Beispiel #13
0
CXAudio2::IntCacheIterator CXAudio2::_PreCacheResource(int ID)
{
	// File already in cache
	IntCacheIterator i = resourceCache.find(ID);

	if (i != resourceCache.end())
		return i;

	// Load WAV (PCM, ADPCM, xWMA).  OGG not supported via resources.

	// Wave file reading class; from the SDK samples
	CWaveFile wav;

	hr = wav.Open(MAKEINTRESOURCE(ID), 0, WAVEFILE_READ, true);

	if (FAILED(hr)) throw CXAudio2Error(hr, "Failed to load file from disk.  Check the filename exists and that the file is of a supported format.");

	DWORD size = wav.GetSize();
	BYTE* pBuffer = new BYTE[size];

	// Read WAV data
	hr = wav.Read(pBuffer, size, &size);

	if (FAILED(hr)) {
		delete[] pBuffer;
		throw CXAudio2Error(hr, "Failed to read WAV data.  Check the WAV file encoding is supported.");
	}

	// Make a cache entry of the WAV data now
	// Avoid invocation of CacheEntry copy constructor which copies pBuffer's memory
	//fileCache[filename] = CacheEntry(pwfx, pBuffer, size);
	resourceCache[ID] = CacheEntry(this);
	i = resourceCache.find(ID);
	CacheEntry& ce = i->second;

	// xWMA
	if (wav.m_bIsXWMA) {

		ce.SetWma((GENERICWAVEFILE*)wav.GetFormat(), pBuffer, size, wav.m_nPacketCount, wav.m_aDecodedPacketCumulativeBytes);	
	}
	// PCM or ADPCM
	else {
		// Cache entry now has reference count 1 and responsibility for deleting pBuffer
		ce.Set((GENERICWAVEFILE*)wav.GetFormat(), pBuffer, size);
	}
	ce.refCount = 0;	// Just precached, nothing referencing yet
	totalCacheSize += size;

	return i;
}
TimeProofService::TimeProof TimeProofService::getProof(LogicalTime time, const Key& key) {
    stdx::lock_guard<stdx::mutex> lk(_cacheMutex);
    auto timeCeil = LogicalTime(Timestamp(time.asTimestamp().asULL() | kRangeMask));
    if (_cache && _cache->hasProof(timeCeil, key)) {
        return _cache->_proof;
    }

    auto unsignedTimeArray = timeCeil.toUnsignedArray();
    // update cache
    _cache =
        CacheEntry(SHA1Block::computeHmac(
                       key.data(), key.size(), unsignedTimeArray.data(), unsignedTimeArray.size()),
                   timeCeil,
                   key);
    return _cache->_proof;
}
Beispiel #15
0
bool SharedCache::LoadDir(string eveDir)
{
	bool loadedDir = false;
	bool loadedIndex = false;
	string cacheDir;

	CRegKey rk;
	LONG lRet = rk.Open(HKEY_CURRENT_USER, "SOFTWARE\\CCP\\EVEONLINE");
	if (lRet == 0)
	{
		ULONG readLen = 256;
		TCHAR path[256];
		lRet = rk.QueryStringValue("CACHEFOLDER", path, &readLen);
		rk.Close();
		
		cacheDir = path;
		loadedDir = (lRet == 0);
	}

	if (loadedDir)
	{
		ifstream in(eveDir + "\\resfileindex.txt");
		if (in.good())
		{
			string line;
			CacheEntry file;
			char filename[255], cachename[255];
			int filesize = 0;
			while (!in.eof())
			{
				getline(in, line, '\n');
				sscanf(line.c_str(), "%255[^','],%255[^','],%*[^','],%d", filename, cachename, &filesize);
				
				file = CacheEntry();
				file.filename = filename;
				file.cachename = cacheDir + "ResFiles\\" + cachename;
				file.fileSize = filesize;
				index.push_back(file);
				line.clear();
			}
			loadedIndex = true;
		}
		in.close();
	}

	return loadedDir && loadedIndex;
}
void Cache::request(BrokenUpHTTPRequest request, ClientListener *client_listener) {
    Logger::debug("Cache::request(%s)", request.url.c_str());

    std::string key = request.url;
    Retranslator *retranslator;

    _cache_mutex.lock();

    // if such entry is already present
    if (_cache.find(key) != _cache.end()) {
        CacheEntry &ce = _cache[key];
        // if CacheEntry is CACHED append CacheEntry's buffer
        // to client buffer and setting finished flag;
        if (ce.get_state() == CacheEntry::CACHED) {
            Logger::info("Cache HIT %s", key.c_str());
            client_listener->add_data(ce.data());
            _cache_mutex.unlock();
            client_listener->finished();
            return;

            // if it's CACHING we can add that client to
            // list of clients
        } else if (ce.get_state() == CacheEntry::CACHING) {
            Logger::info("Cache CACHING %s", key.c_str());
            retranslator = _retranslators[key];
            retranslator->add_client(client_listener);
            
            // that is meant to never happen
        } else {
            assert(false);
        }

        // if there's no such entry we should create one
    } else {
        Logger::info("Cache NEW %s", key.c_str());
        _cache[key] = CacheEntry();
        retranslator = new Retranslator(request, _cache[key], client_listener);
        retranslator->start_download();
        _retranslators[key] = retranslator;
    }

    client_listener->set_retranslator(retranslator);
    _cache_mutex.unlock();
}
Beispiel #17
0
bool TextureCache::load(QImage &img, Alg::MapTreeNode *node) {
	QMutexLocker lock(&imageCacheMutex);

	ImageCache::iterator it;
	QString id = _mapTree->getID(node);
	it = _images.find(id);
	if ( it == _images.end() ) {
		if ( !_mapTree->load(img, node) )
			return false;

		if ( img.format() != QImage::Format_RGB32 &&
		     img.format() != QImage::Format_ARGB32 )
			img = img.convertToFormat(QImage::Format_ARGB32);

		_images[id] = CacheEntry(img, 1);
	}
	else {
		img = it.value().first;
		++it.value().second;
	}

	/*
	for ( int i = 0; i < 5; ++i ) {
		for ( int j = 0; j < w; ++j ) {
			data[i*w + j] = qRgb(255,0,0);
			data[(h-1-i)*w + j] = qRgb(255,0,0);
		}
		for ( int j = 0; j < h; ++j ) {
			data[j*w + i] = qRgb(255,0,0);
			data[j*w + w-1-i] = qRgb(255,0,0);
		}
	}
	*/

	return true;
}
Beispiel #18
0
CXAudio2::StringCacheIterator CXAudio2::_PreCacheFile(std::string filename)
{
	// File already in cache
	StringCacheIterator i = fileCache.find(filename);

	if (i != fileCache.end())
		return i;

	// Check for OGG file
	std::string ext = filename;
	ext.erase(0, ext.length() - 4);

	// Load OGG file
	if (_stricmp(ext.c_str(), ".ogg") == 0 || _stricmp(ext.c_str(), ".oga") == 0) {
#ifdef XAUDIO2_OGGVORBIS
		FILE* f = fopen(filename.c_str(), "rb");

		if (f == NULL)
			throw CXAudio2Error(E_FAIL, std::string("Error loading file '") + filename + "'.  Check the file exists and is valid.");

		OggVorbis_File oggFile;
		ov_open(f, &oggFile, NULL, 0);	// Takes control of f; no need to call fclose()
		vorbis_info* pInfo = ov_info(&oggFile, -1);

		int endian = 0;             // 0 for Little-Endian, 1 for Big-Endian
		int bytesRead = 0;
		int bitStream;

		// Read the file data
		vector<char> oggData;
		char readbuffer[XAUDIO2_OGGVORBIS_BUFFERSIZE];

		do {
			// Read up to a buffer's worth of decoded sound data
			bytesRead = ov_read(&oggFile, readbuffer, XAUDIO2_OGGVORBIS_BUFFERSIZE, endian, 2, 1, &bitStream);

			// Append to end of buffer
		   oggData.insert(oggData.end(), readbuffer, readbuffer + bytesRead);
		}
		while (bytesRead > 0);

		// Fill out a WAVEFORMATEX for the decompressed OGG
		WAVEFORMATEX wfx;
		memset(&wfx, 0, sizeof(WAVEFORMATEX));
		wfx.cbSize = sizeof(WAVEFORMATEX);
		wfx.nChannels = pInfo->channels;
		wfx.nSamplesPerSec = pInfo->rate;
		wfx.wBitsPerSample = 16;		// OGG is always 16 bit
		wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nChannels * 2;
		wfx.nBlockAlign = 2 * wfx.nChannels;
		wfx.wFormatTag = WAVE_FORMAT_PCM;

		ov_clear(&oggFile);

		// Copy the vector which is local scope and will deallocate: the cache takes responsibility for deleting
		BYTE* pBuffer = new BYTE[oggData.size()];
		memcpy(pBuffer, &(oggData.front()), oggData.size());

		// Make a cache entry of the WAV data now
		// Avoid invocation of CacheEntry copy constructor which copies pBuffer's memory
		//fileCache[filename] = CacheEntry(pwfx, pBuffer, size);
		fileCache[filename] = CacheEntry(this);
		i = fileCache.find(filename);
		CacheEntry& ce = i->second;
		ce.Set((GENERICWAVEFILE*)&wfx, pBuffer, oggData.size());
		ce.refCount = 0;	// Just precached, nothing referencing yet
		ce.isOgg = true;
		totalCacheSize += oggData.size();

		return i;
#else
		// Not built with OGG Vorbis support; throw an error
		throw CXAudio2Error(E_FAIL, "OGG Vorbis is not supported by this version of XAudio2.");
#endif
	}
	else {
		// Load WAV (PCM, ADPCM, xWMA)

		// Wave file reading class; from the SDK samples
		CWaveFile wav;

		// Dumb function definition needs an LPSTR, not an LPCSTR
		TCHAR* fileNameStr = new TCHAR[filename.size() + 1];
		memcpy(fileNameStr, filename.c_str(), filename.size() + 1);	// copy null terminator in
		hr = wav.Open(fileNameStr, 0, WAVEFILE_READ);
		delete[] fileNameStr;

		if (FAILED(hr)) throw CXAudio2Error(hr, "Failed to load file from disk.  Check the filename exists and that the file is of a supported format.");

		DWORD size = wav.GetSize();
		BYTE* pBuffer = new BYTE[size];

		// Read WAV data
		hr = wav.Read(pBuffer, size, &size);

		if (FAILED(hr)) {
			delete[] pBuffer;
			throw CXAudio2Error(hr, "Failed to read WAV data.  Check the WAV file encoding is supported.");
		}

		// Make a cache entry of the WAV data now
		// Avoid invocation of CacheEntry copy constructor which copies pBuffer's memory
		//fileCache[filename] = CacheEntry(pwfx, pBuffer, size);
		fileCache[filename] = CacheEntry(this);
		i = fileCache.find(filename);
		CacheEntry& ce = i->second;

		// xWMA
		if (wav.m_bIsXWMA) {

			ce.SetWma((GENERICWAVEFILE*)wav.GetFormat(), pBuffer, size, wav.m_nPacketCount, wav.m_aDecodedPacketCumulativeBytes);	
		}
		// PCM or ADPCM
		else {
			// Cache entry now has reference count 1 and responsibility for deleting pBuffer
			ce.Set((GENERICWAVEFILE*)wav.GetFormat(), pBuffer, size);
		}
		ce.refCount = 0;	// Just precached, nothing referencing yet
		totalCacheSize += size;

		return i;
	}
}