Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HashTableNT: add update method #28

Merged
merged 1 commit into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/borghash/HashTableNT.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
HashTableNT: wrapper around HashTable, providing namedtuple values and serialization.
"""
from __future__ import annotations

from collections.abc import Mapping
from typing import BinaryIO, Iterator, Any

from collections import namedtuple
Expand Down Expand Up @@ -111,6 +113,23 @@ cdef class HashTableNT:
else:
return self._to_namedtuple_value(binary_value)

def update(self, other=(), /, **kwds):
"""Like dict.update, but other can also be a HashTableNT instance."""
if isinstance(other, HashTableNT):
for key, value in other.items():
self[key] = value
elif isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value

def k_to_idx(self, key: bytes) -> int:
return self.inner.k_to_idx(key)

Expand Down
15 changes: 15 additions & 0 deletions tests/hashtablent_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
key1, value1 = b"a" * 32, value_type(11, 12, 13)
key2, value2 = b"b" * 32, value_type(21, 22, 23)
key3, value3 = b"c" * 32, value_type(31, 32, 33)
key4, value4 = b"d" * 32, value_type(41, 42, 43)


@pytest.fixture
Expand Down Expand Up @@ -91,6 +92,20 @@ def test_pop(ntht12):
assert ntht12.pop(key3, None) is None


def test_update_kvpairs(ntht12):
ntht12.update([(key3, value3), (key4, value4)])
assert ntht12[key3] == value3
assert ntht12[key4] == value4


def test_update_ntht(ntht12, ntht):
ntht[key3] = value3
ntht[key4] = value4
ntht12.update(ntht)
assert ntht12[key3] == value3
assert ntht12[key4] == value4


def test_ntht_stress(ntht):
# this also triggers some hashtable resizing
keys = set()
Expand Down