зеркало из https://github.com/mozilla/gecko-dev.git
Bug 1479484 - Part 3: Add perfecthash.py with codegen to xpcom/ds/tools, r=froydnj
Summary: This is a streamlined version of perfecthash.py from xpcom/reflect/xptinfo. There are a few major changes here: Instead of providing '(key, value)' pairs to the constructor, callers provide a list of 'entries'. An optional 'key' parameter allows overriding the function used to get an entry's key. The default behaviour is as before, destructuring a (key, value) tuple. Keys can now be anything which supports the 'memoryview' protocol with 1-byte elements, rather than being forced to be a 'bytearray'. This allows passing in types such as bytestrings. A new 'cxx_codegen' method is now exposed which generates a series of fully-contained C++ declarations to perform entry lookups. It is possible to override many parts of this codegen to make it the best fit for your component. PerfectHash remembers the 'key' function, meaning lookup methods automatically verify a valid key was passed in, and return 'None' otherwise. Depends On D2615 Reviewers: froydnj! Tags: #secure-revision Bug #: 1479484 Differential Revision: https://phabricator.services.mozilla.com/D2616
This commit is contained in:
Родитель
b8f77dd95d
Коммит
d36f0538d8
|
@ -0,0 +1,240 @@
|
|||
# perfecthash.py - Helper for generating perfect hash functions
|
||||
#
|
||||
# This Source Code Form is subject to the terms of the Mozilla Public
|
||||
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
"""
|
||||
A perfect hash function (PHF) is a function which maps distinct elements from a
|
||||
source set to a sequence of integers with no collisions.
|
||||
|
||||
PHFs generated by this module use a 32-bit FNV hash to index an intermediate
|
||||
table. The value from that table is then used to run a second 32-bit FNV hash to
|
||||
get a final index.
|
||||
|
||||
The algorithm works by starting with the largest set of conflicts, and testing
|
||||
intermediate table values until no conflicts are generated, allowing efficient
|
||||
index lookup at runtime. (see also: http://stevehanov.ca/blog/index.php?id=119)
|
||||
|
||||
NOTE: This perfect hash generator was designed to be simple, easy to follow, and
|
||||
maintainable, rather than being as optimized as possible, due to the relatively
|
||||
small dataset it was designed for. In the future we may want to optimize further.
|
||||
"""
|
||||
|
||||
from collections import namedtuple
|
||||
import textwrap
|
||||
|
||||
|
||||
class PerfectHash(object):
|
||||
"""PerfectHash objects represent a computed perfect hash function, which
|
||||
can be generated at compile time to provide highly efficient and compact
|
||||
static HashTables.
|
||||
|
||||
Consumers must provide an intermediate table size to store the generated
|
||||
hash function. Larger tables will generate more quickly, while smaller
|
||||
tables will consume less space on disk."""
|
||||
|
||||
# 32-bit FNV offset basis and prime value.
|
||||
FNV_OFFSET_BASIS = 0x811C9DC5
|
||||
FNV_PRIME = 16777619
|
||||
U32_MAX = 0xffffffff
|
||||
|
||||
# Bucket of entries which map into a given intermediate index.
|
||||
Bucket = namedtuple('Bucket', 'index entries')
|
||||
|
||||
def __init__(self, entries, size, validate=True, key=lambda (k, _): k):
|
||||
"""Create a new PerfectHash
|
||||
|
||||
@param entries set of entries to generate a PHF for
|
||||
@param size size of the PHF intermediate table
|
||||
@param validate test the generated hash function after generation
|
||||
@param key function to get 'memoryview'-compatible key for an
|
||||
entry. defaults to extracting the first element of an
|
||||
entry 2-tuple.
|
||||
"""
|
||||
|
||||
assert 0 < len(entries) < self.U32_MAX, "bad # of entries!"
|
||||
self._key = key
|
||||
|
||||
# Allocate the intermediate table and keys.
|
||||
self.table = [0] * size
|
||||
self.entries = [None] * len(entries)
|
||||
|
||||
# A set of Bucket values. Each bucket contains the index into the
|
||||
# intermediate table, and a list of Entries which map into that bucket.
|
||||
buckets = [self.Bucket(idx, []) for idx in range(size)]
|
||||
|
||||
# Determine which input strings map to which buckets in the table.
|
||||
for entry in entries:
|
||||
assert entry is not None, "None entry in entries"
|
||||
assert self.key(entry).itemsize == 1, "non-byte key elements"
|
||||
buckets[self._hash(self.key(entry)) % size].entries.append(entry)
|
||||
|
||||
# Sort the buckets such that the largest one comes first.
|
||||
buckets.sort(key=lambda b: len(b.entries), reverse=True)
|
||||
|
||||
for bucket in buckets:
|
||||
# Once we've reached an empty bucket, we're done.
|
||||
if len(bucket.entries) == 0:
|
||||
break
|
||||
|
||||
# Try values for the basis until we find one with no conflicts.
|
||||
idx = 0
|
||||
basis = 1
|
||||
slots = []
|
||||
while idx < len(bucket.entries):
|
||||
slot = self._hash(self.key(bucket.entries[idx]), basis) % len(self.entries)
|
||||
if self.entries[slot] is not None or slot in slots:
|
||||
# There was a conflict, try the next basis.
|
||||
basis += 1
|
||||
idx = 0
|
||||
del slots[:]
|
||||
assert basis < self.U32_MAX, "table too small"
|
||||
else:
|
||||
slots.append(slot)
|
||||
idx += 1
|
||||
|
||||
assert basis < self.U32_MAX
|
||||
|
||||
# We've found a basis which doesn't conflict
|
||||
self.table[bucket.index] = basis
|
||||
for slot, entry in zip(slots, bucket.entries):
|
||||
self.entries[slot] = entry
|
||||
|
||||
# Validate that looking up each key succeeds
|
||||
if validate:
|
||||
for entry in entries:
|
||||
assert self.get_entry(self.key(entry)), "get_entry(%s)" % repr(entry)
|
||||
|
||||
@classmethod
|
||||
def _hash(cls, key, basis=FNV_OFFSET_BASIS):
|
||||
"""A basic FNV-based hash function. key is the memoryview to hash.
|
||||
32-bit FNV is used for indexing into the first table, and the value
|
||||
stored in that table is used as the offset basis for indexing into the
|
||||
values table."""
|
||||
for byte in memoryview(key):
|
||||
basis ^= ord(byte) # xor-in the byte
|
||||
basis *= cls.FNV_PRIME # Multiply by the FNV prime
|
||||
basis &= cls.U32_MAX # clamp to 32-bits
|
||||
return basis
|
||||
|
||||
def key(self, entry):
|
||||
return memoryview(self._key(entry))
|
||||
|
||||
def get_raw_index(self, key):
|
||||
"""Determine the index in self.entries without validating"""
|
||||
mid = self.table[self._hash(key) % len(self.table)]
|
||||
return self._hash(key, mid) % len(self.entries)
|
||||
|
||||
def get_index(self, key):
|
||||
"""Given a key, determine the index in self.entries"""
|
||||
idx = self.get_raw_index(key)
|
||||
if memoryview(key) != self.key(self.entries[idx]):
|
||||
return None
|
||||
return idx
|
||||
|
||||
def get_entry(self, key):
|
||||
"""Given a key, get the corresponding entry"""
|
||||
idx = self.get_index(key)
|
||||
if idx is None:
|
||||
return None
|
||||
return self.entries[idx]
|
||||
|
||||
@staticmethod
|
||||
def _indent(text, amount=1):
|
||||
return text.replace('\n', '\n' + (' ' * amount))
|
||||
|
||||
def cxx_codegen(self, name, entry_type, lower_entry, entries_name=None,
|
||||
return_type=None, return_entry='return entry;',
|
||||
key_type='const char*', key_bytes='aKey',
|
||||
key_length='strlen(aKey)'):
|
||||
"""Generate complete C++ code for a get_entry-style method.
|
||||
|
||||
@param name Name for the entry getter function.
|
||||
@param entry_type C++ type of each entry in static memory.
|
||||
@param lower_entry Function called with each entry to convert it to a
|
||||
C++ literal of type 'entry_type'.
|
||||
|
||||
# Optional Keyword Parameters:
|
||||
@param entries_name Name for the generated entry table.
|
||||
|
||||
@param return_type C++ return type, default: 'const entry_type&'
|
||||
@param return_entry Override the default behaviour for returning the
|
||||
found entry. 'entry' is a reference to the found
|
||||
entry, and 'aKey' is the lookup key. 'return_entry'
|
||||
can be used for additional checks, e.g. for keys
|
||||
not in the table.
|
||||
|
||||
@param key_type C++ key type, default: 'const char*'
|
||||
@param key_bytes 'const char*' expression to get bytes for 'aKey'
|
||||
@param key_length 'size_t' expression to get length of 'aKey'"""
|
||||
|
||||
if return_type is None:
|
||||
return_type = 'const %s&' % entry_type
|
||||
if entries_name is None:
|
||||
entries_name = 's%sEntries' % name
|
||||
|
||||
# Write out 16 bases per line.
|
||||
bases = ''
|
||||
for idx, base in enumerate(self.table):
|
||||
if idx and idx % 16 == 0:
|
||||
bases += '\n'
|
||||
bases += '%4d,' % base
|
||||
|
||||
# Determine how big of an integer is needed for bases table.
|
||||
max_base = max(self.table)
|
||||
if max_base <= 0xff:
|
||||
basis_type = 'uint8_t'
|
||||
elif max_base <= 0xffff:
|
||||
basis_type = 'uint16_t'
|
||||
else:
|
||||
basis_type = 'uint32_t'
|
||||
|
||||
# Lower each entry to C++ code
|
||||
entries = ',\n'.join(lower_entry(entry) for entry in self.entries)
|
||||
|
||||
return textwrap.dedent("""
|
||||
const %(entry_type)s %(entries_name)s[] = {
|
||||
%(entries)s
|
||||
};
|
||||
|
||||
%(return_type)s
|
||||
%(name)s(%(key_type)s aKey)
|
||||
{
|
||||
const char* bytes = %(key_bytes)s;
|
||||
size_t length = %(key_length)s;
|
||||
auto hash = [&] (uint32_t basis) -> uint32_t {
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
basis = (basis ^ uint8_t(bytes[i])) * %(fnv_prime)d;
|
||||
}
|
||||
return basis;
|
||||
};
|
||||
|
||||
static const %(basis_type)s BASES[] = {
|
||||
%(bases)s
|
||||
};
|
||||
|
||||
%(basis_type)s basis = BASES[hash(%(fnv_basis)d) %% %(nbases)d];
|
||||
auto& entry = %(entries_name)s[hash(basis) %% %(nentries)d];
|
||||
%(return_entry)s
|
||||
}
|
||||
""") % {
|
||||
'name': name,
|
||||
'fnv_basis': self.FNV_OFFSET_BASIS,
|
||||
'fnv_prime': self.FNV_PRIME,
|
||||
|
||||
'entry_type': entry_type,
|
||||
'entries_name': entries_name,
|
||||
'entries': self._indent(entries),
|
||||
'nentries': len(self.entries),
|
||||
'return_entry': self._indent(return_entry),
|
||||
'return_type': return_type,
|
||||
|
||||
'basis_type': basis_type,
|
||||
'bases': self._indent(bases, 2),
|
||||
'nbases': len(self.table),
|
||||
|
||||
'key_type': key_type,
|
||||
'key_bytes': key_bytes,
|
||||
'key_length': key_length,
|
||||
}
|
Загрузка…
Ссылка в новой задаче