Skip to content

Commit

Permalink
Merge pull request #28 from borgbackup/update-method
Browse files Browse the repository at this point in the history
HashTableNT: add update method
  • Loading branch information
ThomasWaldmann authored Nov 9, 2024
2 parents 37c708a + b34032f commit 9294927
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
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

0 comments on commit 9294927

Please sign in to comment.