Skip to content

Commit

Permalink
init with given items: be more flexible
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasWaldmann committed Oct 26, 2024
1 parent 29d91f0 commit 92739a0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
27 changes: 18 additions & 9 deletions borghash.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ HashTable: low-level ht mapping fully random bytes keys to bytes values.
HashTableNT: wrapper around HashTable, providing namedtuple values and serialization.
"""
from typing import Tuple

from libc.stdlib cimport malloc, free, realloc
from libc.string cimport memcpy, memset, memcmp
from libc.stdint cimport uint8_t, uint32_t

from typing import Tuple
from collections import namedtuple
from collections.abc import Mapping
import json
import struct

Expand All @@ -32,6 +32,20 @@ cdef uint32_t RESERVED = 0xFFFFFF00 # all >= this is reserved

_NoDefault = object()

def _fill(this, other):
if other is None:
return
if isinstance(other, Mapping):
for key in other:
this[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
this[key] = other[key]
else:
for key, value in other:
this[key] = value


cdef class HashTable:
def __init__(self, items=None, *,
key_size: int = 0, value_size: int = 0, capacity: int = MIN_CAPACITY,
Expand Down Expand Up @@ -76,10 +90,7 @@ cdef class HashTable:
self.stats_linear = 0 # how many steps the linear search inside _lookup_index needed
self.stats_resize_table = 0
self.stats_resize_kv = 0
# initialize?
if items is not None:
for key, value in items:
self[key] = value
_fill(self, items)

def __del__(self):
free(self.table)
Expand Down Expand Up @@ -336,9 +347,7 @@ cdef class HashTableNT:
self.value_size = struct.calcsize(self.value_format)
self.value_type = value_type
self.inner = HashTable(key_size=self.key_size, value_size=self.value_size, capacity=capacity)
if items is not None:
for key, value in items:
self[key] = value
_fill(self, items)

def clear(self):
self.inner.clear()
Expand Down
4 changes: 4 additions & 0 deletions tests/hashtable_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ def test_init():
ht = HashTable(items, key_size=32, value_size=4)
assert ht[key1] == value1
assert ht[key2] == value2
items = dict(items)
ht = HashTable(items, key_size=32, value_size=4)
assert ht[key1] == value1
assert ht[key2] == value2



Expand Down

0 comments on commit 92739a0

Please sign in to comment.