Skip to content

Commit 9294927

Browse files
Merge pull request #28 from borgbackup/update-method
HashTableNT: add update method
2 parents 37c708a + b34032f commit 9294927

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/borghash/HashTableNT.pyx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
HashTableNT: wrapper around HashTable, providing namedtuple values and serialization.
33
"""
44
from __future__ import annotations
5+
6+
from collections.abc import Mapping
57
from typing import BinaryIO, Iterator, Any
68

79
from collections import namedtuple
@@ -111,6 +113,23 @@ cdef class HashTableNT:
111113
else:
112114
return self._to_namedtuple_value(binary_value)
113115

116+
def update(self, other=(), /, **kwds):
117+
"""Like dict.update, but other can also be a HashTableNT instance."""
118+
if isinstance(other, HashTableNT):
119+
for key, value in other.items():
120+
self[key] = value
121+
elif isinstance(other, Mapping):
122+
for key in other:
123+
self[key] = other[key]
124+
elif hasattr(other, "keys"):
125+
for key in other.keys():
126+
self[key] = other[key]
127+
else:
128+
for key, value in other:
129+
self[key] = value
130+
for key, value in kwds.items():
131+
self[key] = value
132+
114133
def k_to_idx(self, key: bytes) -> int:
115134
return self.inner.k_to_idx(key)
116135

tests/hashtablent_test.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
key1, value1 = b"a" * 32, value_type(11, 12, 13)
1515
key2, value2 = b"b" * 32, value_type(21, 22, 23)
1616
key3, value3 = b"c" * 32, value_type(31, 32, 33)
17+
key4, value4 = b"d" * 32, value_type(41, 42, 43)
1718

1819

1920
@pytest.fixture
@@ -91,6 +92,20 @@ def test_pop(ntht12):
9192
assert ntht12.pop(key3, None) is None
9293

9394

95+
def test_update_kvpairs(ntht12):
96+
ntht12.update([(key3, value3), (key4, value4)])
97+
assert ntht12[key3] == value3
98+
assert ntht12[key4] == value4
99+
100+
101+
def test_update_ntht(ntht12, ntht):
102+
ntht[key3] = value3
103+
ntht[key4] = value4
104+
ntht12.update(ntht)
105+
assert ntht12[key3] == value3
106+
assert ntht12[key4] == value4
107+
108+
94109
def test_ntht_stress(ntht):
95110
# this also triggers some hashtable resizing
96111
keys = set()

0 commit comments

Comments
 (0)