Skip to content

Commit 523d3fd

Browse files
authored
Merge pull request #15 from gboulay/dict-update
Add update() to LRU
2 parents 220b787 + b9c8989 commit 523d3fd

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

lru.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,28 @@ get_key(Node *node)
332332
return node->key;
333333
}
334334

335+
static PyObject *
336+
LRU_update(LRU *self, PyObject *args, PyObject *kwargs)
337+
{
338+
PyObject *key, *value;
339+
PyObject *arg = NULL;
340+
Py_ssize_t pos = 0;
341+
342+
if ((PyArg_ParseTuple(args, "|O", &arg))) {
343+
if (arg && PyDict_Check(arg)) {
344+
while (PyDict_Next(arg, &pos, &key, &value))
345+
lru_ass_sub(self, key, value);
346+
}
347+
}
348+
349+
if (kwargs != NULL && PyDict_Check(kwargs)) {
350+
while (PyDict_Next(kwargs, &pos, &key, &value))
351+
lru_ass_sub(self, key, value);
352+
}
353+
354+
Py_RETURN_NONE;
355+
}
356+
335357
static PyObject *
336358
LRU_peek_first_item(LRU *self)
337359
{
@@ -483,6 +505,8 @@ static PyMethodDef LRU_methods[] = {
483505
PyDoc_STR("L.peek_first_item() -> returns the MRU item (key,value) without changing key order")},
484506
{"peek_last_item", (PyCFunction)LRU_peek_last_item, METH_NOARGS,
485507
PyDoc_STR("L.peek_last_item() -> returns the LRU item (key,value) without changing key order")},
508+
{"update", (PyCFunction)LRU_update, METH_VARARGS | METH_KEYWORDS,
509+
PyDoc_STR("L.update() -> update value for key in LRU")},
486510
{NULL, NULL},
487511
};
488512

test/test_lru.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,24 @@ def test_access(self):
106106
self.assertEqual(l[i], str(i))
107107
self.assertEqual(l.get(i,None), str(i))
108108

109+
110+
def test_update(self):
111+
l = LRU(2)
112+
l['a'] = 1
113+
self.assertEqual(l['a'], 1)
114+
l.update(a=2)
115+
self.assertEqual(l['a'], 2)
116+
l['b'] = 2
117+
self.assertEqual(l['b'], 2)
118+
l.update(b=3)
119+
self.assertEqual(l['a'], 2)
120+
self.assertEqual(l['b'], 3)
121+
l.update({'a':1, 'b':2})
122+
self.assertEqual(l['a'], 1)
123+
self.assertEqual(l['b'], 2)
124+
l.update()
125+
126+
109127
def test_peek_first_item(self):
110128
l = LRU(2)
111129
self.assertEqual(None, l.peek_first_item())

0 commit comments

Comments
 (0)