Path: blob/master/src/hotspot/share/libadt/dict.cpp
40951 views
/*1* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "libadt/dict.hpp"26#include "utilities/powerOfTwo.hpp"2728// Dictionaries - An Abstract Data Type2930// %%%%% includes not needed with AVM framework - Ungar3132#include <assert.h>3334//------------------------------data-----------------------------------------35// String hash tables36#define MAXID 2037static const char shft[MAXID] = {1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6};38// Precomputed table of null character hashes39// xsum[0] = (1 << shft[0]) + 1;40// for(int i = 1; i < MAXID; i++) {41// xsum[i] = (1 << shft[i]) + 1 + xsum[i - 1];42// }43static const short xsum[MAXID] = {3,8,17,34,67,132,261,264,269,278,295,328,393,522,525,530,539,556,589,654};4445//------------------------------bucket---------------------------------------46class bucket : public ResourceObj {47public:48uint _cnt, _max; // Size of bucket49void** _keyvals; // Array of keys and values50};5152//------------------------------Dict-----------------------------------------53// The dictionary is kept has a hash table. The hash table is a even power54// of two, for nice modulo operations. Each bucket in the hash table points55// to a linear list of key-value pairs; each key & value is just a (void *).56// The list starts with a count. A hash lookup finds the list head, then a57// simple linear scan finds the key. If the table gets too full, it's58// doubled in size; the total amount of EXTRA times all hash functions are59// computed for the doubling is no more than the current size - thus the60// doubling in size costs no more than a constant factor in speed.61Dict::Dict(CmpKey initcmp, Hash inithash) : _arena(Thread::current()->resource_area()),62_hash(inithash), _cmp(initcmp) {6364_size = 16; // Size is a power of 265_cnt = 0; // Dictionary is empty66_bin = (bucket*)_arena->Amalloc_4(sizeof(bucket) * _size);67memset((void*)_bin, 0, sizeof(bucket) * _size);68}6970Dict::Dict(CmpKey initcmp, Hash inithash, Arena* arena, int size)71: _arena(arena), _hash(inithash), _cmp(initcmp) {72// Size is a power of 273_size = MAX2(16, round_up_power_of_2(size));7475_cnt = 0; // Dictionary is empty76_bin = (bucket*)_arena->Amalloc_4(sizeof(bucket) * _size);77memset((void*)_bin, 0, sizeof(bucket) * _size);78}7980// Deep copy into arena of choice81Dict::Dict(const Dict &d, Arena* arena)82: _arena(arena), _size(d._size), _cnt(d._cnt), _hash(d._hash), _cmp(d._cmp) {83_bin = (bucket*)_arena->Amalloc_4(sizeof(bucket) * _size);84memcpy((void*)_bin, (void*)d._bin, sizeof(bucket) * _size);85for (uint i = 0; i < _size; i++) {86if (!_bin[i]._keyvals) {87continue;88}89_bin[i]._keyvals = (void**)_arena->Amalloc_4(sizeof(void*) * _bin[i]._max * 2);90memcpy(_bin[i]._keyvals, d._bin[i]._keyvals, _bin[i]._cnt * 2 * sizeof(void*));91}92}9394//------------------------------~Dict------------------------------------------95// Delete an existing dictionary.96Dict::~Dict() { }9798//------------------------------doubhash---------------------------------------99// Double hash table size. If can't do so, just suffer. If can, then run100// thru old hash table, moving things to new table. Note that since hash101// table doubled, exactly 1 new bit is exposed in the mask - so everything102// in the old table ends up on 1 of two lists in the new table; a hi and a103// lo list depending on the value of the bit.104void Dict::doubhash() {105uint oldsize = _size;106_size <<= 1; // Double in size107_bin = (bucket*)_arena->Arealloc(_bin, sizeof(bucket) * oldsize, sizeof(bucket) * _size);108memset((void*)(&_bin[oldsize]), 0, oldsize * sizeof(bucket));109// Rehash things to spread into new table110for (uint i = 0; i < oldsize; i++) { // For complete OLD table do111bucket* b = &_bin[i]; // Handy shortcut for _bin[i]112if (!b->_keyvals) continue; // Skip empties fast113114bucket* nb = &_bin[i+oldsize]; // New bucket shortcut115uint j = b->_max; // Trim new bucket to nearest power of 2116while (j > b->_cnt) { j >>= 1; } // above old bucket _cnt117if (!j) { j = 1; } // Handle zero-sized buckets118nb->_max = j << 1;119// Allocate worst case space for key-value pairs120nb->_keyvals = (void**)_arena->Amalloc_4(sizeof(void* ) * nb->_max * 2);121uint nbcnt = 0;122123for (j = 0; j < b->_cnt;) { // Rehash all keys in this bucket124void* key = b->_keyvals[j + j];125if ((_hash(key) & (_size-1)) != i) { // Moving to hi bucket?126nb->_keyvals[nbcnt + nbcnt] = key;127nb->_keyvals[nbcnt + nbcnt + 1] = b->_keyvals[j + j + 1];128nb->_cnt = nbcnt = nbcnt + 1;129b->_cnt--; // Remove key/value from lo bucket130b->_keyvals[j + j] = b->_keyvals[b->_cnt + b->_cnt];131b->_keyvals[j + j + 1] = b->_keyvals[b->_cnt + b->_cnt + 1];132// Don't increment j, hash compacted element also.133} else {134j++; // Iterate.135}136} // End of for all key-value pairs in bucket137} // End of for all buckets138}139140//------------------------------Insert----------------------------------------141// Insert or replace a key/value pair in the given dictionary. If the142// dictionary is too full, it's size is doubled. The prior value being143// replaced is returned (NULL if this is a 1st insertion of that key). If144// an old value is found, it's swapped with the prior key-value pair on the145// list. This moves a commonly searched-for value towards the list head.146void*Dict::Insert(void* key, void* val, bool replace) {147uint hash = _hash(key); // Get hash key148uint i = hash & (_size - 1); // Get hash key, corrected for size149bucket* b = &_bin[i];150for (uint j = 0; j < b->_cnt; j++) {151if (!_cmp(key, b->_keyvals[j + j])) {152if (!replace) {153return b->_keyvals[j + j + 1];154} else {155void* prior = b->_keyvals[j + j + 1];156b->_keyvals[j + j ] = key;157b->_keyvals[j + j + 1] = val;158return prior;159}160}161}162if (++_cnt > _size) { // Hash table is full163doubhash(); // Grow whole table if too full164i = hash & (_size - 1); // Rehash165b = &_bin[i];166}167if (b->_cnt == b->_max) { // Must grow bucket?168if (!b->_keyvals) {169b->_max = 2; // Initial bucket size170b->_keyvals = (void**)_arena->Amalloc_4(sizeof(void*) * b->_max * 2);171} else {172b->_keyvals = (void**)_arena->Arealloc(b->_keyvals, sizeof(void*) * b->_max * 2, sizeof(void*) * b->_max * 4);173b->_max <<= 1; // Double bucket174}175}176b->_keyvals[b->_cnt + b->_cnt ] = key;177b->_keyvals[b->_cnt + b->_cnt + 1] = val;178b->_cnt++;179return NULL; // Nothing found prior180}181182//------------------------------Delete---------------------------------------183// Find & remove a value from dictionary. Return old value.184void* Dict::Delete(void* key) {185uint i = _hash(key) & (_size - 1); // Get hash key, corrected for size186bucket* b = &_bin[i]; // Handy shortcut187for (uint j = 0; j < b->_cnt; j++) {188if (!_cmp(key, b->_keyvals[j + j])) {189void* prior = b->_keyvals[j + j + 1];190b->_cnt--; // Remove key/value from lo bucket191b->_keyvals[j+j ] = b->_keyvals[b->_cnt + b->_cnt ];192b->_keyvals[j+j+1] = b->_keyvals[b->_cnt + b->_cnt + 1];193_cnt--; // One less thing in table194return prior;195}196}197return NULL;198}199200//------------------------------FindDict-------------------------------------201// Find a key-value pair in the given dictionary. If not found, return NULL.202// If found, move key-value pair towards head of list.203void* Dict::operator [](const void* key) const {204uint i = _hash(key) & (_size - 1); // Get hash key, corrected for size205bucket* b = &_bin[i]; // Handy shortcut206for (uint j = 0; j < b->_cnt; j++) {207if (!_cmp(key, b->_keyvals[j + j])) {208return b->_keyvals[j + j + 1];209}210}211return NULL;212}213214//------------------------------print------------------------------------------215// Handier print routine216void Dict::print() {217DictI i(this); // Moved definition in iterator here because of g++.218tty->print("Dict@" INTPTR_FORMAT "[%d] = {", p2i(this), _cnt);219for (; i.test(); ++i) {220tty->print("(" INTPTR_FORMAT "," INTPTR_FORMAT "),", p2i(i._key), p2i(i._value));221}222tty->print_cr("}");223}224225//------------------------------Hashing Functions----------------------------226// Convert string to hash key. This algorithm implements a universal hash227// function with the multipliers frozen (ok, so it's not universal). The228// multipliers (and allowable characters) are all odd, so the resultant sum229// is odd - guaranteed not divisible by any power of two, so the hash tables230// can be any power of two with good results. Also, I choose multipliers231// that have only 2 bits set (the low is always set to be odd) so232// multiplication requires only shifts and adds. Characters are required to233// be in the range 0-127 (I double & add 1 to force oddness). Keys are234// limited to MAXID characters in length. Experimental evidence on 150K of235// C text shows excellent spreading of values for any size hash table.236int hashstr(const void* t) {237char c, k = 0;238int32_t sum = 0;239const char* s = (const char*)t;240241while (((c = *s++) != '\0') && (k < MAXID-1)) { // Get characters till null or MAXID-1242c = (c << 1) + 1; // Characters are always odd!243sum += c + (c << shft[k++]); // Universal hash function244}245return (int)((sum + xsum[k]) >> 1); // Hash key, un-modulo'd table size246}247248//------------------------------hashptr--------------------------------------249// Slimey cheap hash function; no guaranteed performance. Better than the250// default for pointers, especially on MS-DOS machines.251int hashptr(const void* key) {252return ((intptr_t)key >> 2);253}254255// Slimey cheap hash function; no guaranteed performance.256int hashkey(const void* key) {257return (intptr_t)key;258}259260//------------------------------Key Comparator Functions---------------------261int32_t cmpstr(const void* k1, const void* k2) {262return strcmp((const char*)k1, (const char*)k2);263}264265// Cheap key comparator.266int32_t cmpkey(const void* key1, const void* key2) {267if (key1 == key2) {268return 0;269}270intptr_t delta = (intptr_t)key1 - (intptr_t)key2;271if (delta > 0) {272return 1;273}274return -1;275}276277//=============================================================================278//------------------------------reset------------------------------------------279// Create an iterator and initialize the first variables.280void DictI::reset(const Dict* dict) {281_d = dict;282_i = (uint)-1; // Before the first bin283_j = 0; // Nothing left in the current bin284++(*this); // Step to first real value285}286287//------------------------------next-------------------------------------------288// Find the next key-value pair in the dictionary, or return a NULL key and289// value.290void DictI::operator ++(void) {291if (_j--) { // Still working in current bin?292_key = _d->_bin[_i]._keyvals[_j + _j];293_value = _d->_bin[_i]._keyvals[_j + _j + 1];294return;295}296297while (++_i < _d->_size) { // Else scan for non-zero bucket298_j = _d->_bin[_i]._cnt;299if (!_j) {300continue;301}302_j--;303_key = _d->_bin[_i]._keyvals[_j+_j];304_value = _d->_bin[_i]._keyvals[_j+_j+1];305return;306}307_key = _value = NULL;308}309310311