diff --git a/elftools/common/utils.py b/elftools/common/utils.py index d8acefab..4e80e188 100644 --- a/elftools/common/utils.py +++ b/elftools/common/utils.py @@ -12,6 +12,14 @@ from ..construct import ConstructError +def merge_dicts(*dicts): + "Given any number of dicts, merges them into a new one.""" + result = {} + for d in dicts: + result.update(d) + return result + + def bytelist2string(bytelist): """ Convert a list of byte values (e.g. [0x10 0x20 0x00]) to a bytes object (e.g. b'\x10\x20\x00'). diff --git a/test/test_utils.py b/test/test_utils.py index 86b1da13..23669e73 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -8,7 +8,7 @@ from random import randint from elftools.common.py3compat import int2byte, BytesIO -from elftools.common.utils import (parse_cstring_from_stream, +from elftools.common.utils import (parse_cstring_from_stream, merge_dicts, preserve_stream_pos) @@ -54,5 +54,15 @@ def test_basic(self): self.assertEqual(sio.tell(), 5) +class Test_merge_dicts(unittest.TestCase): + def test_basic(self): + md = merge_dicts({10: 20, 20: 30}, {30: 40, 50: 60}) + self.assertEqual(md, {10: 20, 20: 30, 30: 40, 50: 60}) + + def test_keys_resolve(self): + md = merge_dicts({10: 20, 20: 30}, {20: 40, 50: 60}) + self.assertEqual(md, {10: 20, 20: 40, 50: 60}) + + if __name__ == '__main__': unittest.main()