Ejemplo n.º 1
0
	void resize() {
		int new_length = 4;
		while(new_length < elems_) {
			new_length <<= 1;
		}
		HashNode** new_list = new HashNode*[new_length];
		memset(new_list, 0, sizeof(new_list[0]) * new_length);
		int count = 0;

		for(int i=0; i<length_; ++i) {
			HashNode* now = list_[i];
			while(now != NULL) {
				HashNode* next = now->next_hash;
				Slice key = now->key();
				int hash = now->hash;
				HashNode** ptr = &new_list[hash & (new_length - 1)];

				now->next_hash = *ptr;
				*ptr = now;
				now = next;
				count++;
			}
		}
		assert(elems_ == count);
		delete[] list_;
		list_ = new_list;
		length_ = new_length;
	}
Ejemplo n.º 2
0
	HashNode* insert(const Slice& key, int& hit_id, int& rep_id) {
		HashNode* e = reinterpret_cast<HashNode*>(malloc(sizeof(HashNode) - 1 + key.size()));
		e->key_length = key.size();
		e->hash = hash_slice(key);
		memcpy(e->key_data, key.data(), key.size());

		lru_append(e);
		HashNode* old = table_.insert(e);

		if(old != NULL) {
			//命中缓存
			e->cache_id = old->cache_id;

			hit_id = e->cache_id;
			rep_id = -1;

			lru_remove(old);
			lru_release(old);

			//update hit ratio
			hit_cnt++;
		}
		else {
			//没有命中缓存
			hit_id = -1;

			//如果当前的缓存数量超过capacity,把lru_后面的那个缓存单元淘汰掉
			if(table_.size() > capacity_) {
				HashNode* cursor = lru_.next;
				lru_remove(cursor);
				table_.remove(cursor->key(), cursor->hash);

				e->cache_id = cursor->cache_id;
				lru_release(cursor);
			}
			else {
				e->cache_id = last_id++;  //TODO 会无限增长?
			}

			rep_id = e->cache_id;

			//update hit ratio
			set_cnt++;
		}

		return e;
	}