util: implement sortdict.insert()
authorMartin von Zweigbergk <martinvonz@google.com>
Mon, 16 Dec 2019 15:58:47 -0800
changeset 43913 68af0228fedc
parent 43912 727cf6acadfe
child 43914 4b3c8df189bc
util: implement sortdict.insert() As flagged by pytype (reported via Matt Harbison, thanks). This was broken by bd0fd3ff9916 (util: rewrite sortdict using Python 2.7's OrderedDict, 2017-05-16). We actually call insert() on namespaces.py:100, but we clearly don't have test coverage of that an no users have reported it AFAIK. Differential Revision: https://phab.mercurial-scm.org/D7680
mercurial/util.py
--- a/mercurial/util.py	Mon Dec 16 23:27:17 2019 -0500
+++ b/mercurial/util.py	Mon Dec 16 15:58:47 2019 -0800
@@ -1253,6 +1253,9 @@
     >>> d2.update([(b'a', 2)])
     >>> list(d2.keys()) # should still be in last-set order
     ['b', 'a']
+    >>> d1.insert(1, b'a.5', 0.5)
+    >>> d1
+    sortdict([('a', 0), ('a.5', 0.5), ('b', 1)])
     '''
 
     def __setitem__(self, key, value):
@@ -1268,6 +1271,14 @@
             for k, v in src:
                 self[k] = v
 
+    def insert(self, position, key, value):
+        for (i, (k, v)) in enumerate(list(self.items())):
+            if i == position:
+                self[key] = value
+            if i >= position:
+                del self[k]
+                self[k] = v
+
 
 class cowdict(cow, dict):
     """copy-on-write dict