Пример #1
0
    int get(int key) {
        auto got = cache_map.find(key);
        if (got == cache_map.end())
            return -1;

        cache_list.splice(cache_list.begin(), cache_list, got->second);
        
        return got->second->second;
    }
Пример #2
0
    void set(int key, int value) {
        auto got = cache_map.find(key);
        if (got != cache_map.end()) {
            cache_list.erase(got->second);
            cache_map.erase(got);
        }

        cache_list.push_front(make_pair(key, value));
        cache_map.insert(make_pair(key, cache_list.begin()));
        clean();
    }
void cache_display()
{
  HTTP_header* http_hdr;
  HTTP_pointer* ptr;
  CACHE_LIST::iterator N;//use a standard iterator variable to move through the cache

  string LR_key, last;
  time_t last_accessed;
  cout<<endl;
  cout<<"_____________________Files Cache____________________________"<<endl;
  N= cache.begin();
  while(N != cache.end())
  {
    LR_key = N->first;//first element in cache
    ptr = N->second;//pointer to the next

    http_hdr = ptr->getHeader();
    last_accessed = http_hdr->get_last_accessed();
    last = UTC_convert(last_accessed);

    cout<<"page: "<<LR_key<<", was last accessed at: "<<last<<endl;
    N++;
  }
}
void update_cache(string url, HTTP_pointer* entity,int status)
{
  if(status == 0)
  {
  	//first check if cache has empty places
  	double MTD=INT_MIN;//minimum access time
  	time_t currentTime = time_current();
  	if(cache.size() < MAX)
  	{
    		//just insert it and return
    		cout<<"Current size of cache: "<<cache.size()<<endl;
    		entity = set_Time(entity);
    		cache.insert(make_pair(url, entity));
    		return;
  	}

  //now if cache is full, find the entry with the oldest access time
  //
  	int i=0;

  	CACHE_LIST::iterator Least_recent_key;
  	CACHE_LIST::iterator N = cache.begin();
  	time_t last;
	for(; N != cache.end(); N++)
  	{
  		HTTP_pointer* en = N->second;
    		last = en->getHeader()->get_last_accessed();
    		double timediff = difftime(currentTime, last);
    		if(timediff > MTD)
    		{
      			MTD = timediff;//find the minima
      			Least_recent_key = N;
    		}
    		i++;
  	}

  //now we have the least recently used key in index leastRecent
  	cout<<"The least recently used(LRU) page is "<<Least_recent_key->first<<", hence this entry will be deleted in the cache"<<endl;
  	cache.erase(Least_recent_key);
  	cache.insert(make_pair(url, entity));
   }
 else
 {

 //method to replace existing entries in cache

  	string key;
	CACHE_LIST::iterator N = cache.begin();

	for(; N != cache.end(); N++)
	{
		key = N->first;
		if(key == url)
		{
			cout<<"Entry found for page "<<key<<", this will be replaced with the new page now"<<endl;
			cache.erase(key);
			entity = set_Time(entity);
			cache.insert(make_pair(url, entity));
			break;
		}
	}
 }
}