Skip to content

Commit

Permalink
Merge pull request #123 from d0c-s4vage/feature/119-child_iteration_v…
Browse files Browse the repository at this point in the history
…ia_iter

Added children and array item iteration
  • Loading branch information
d0c-s4vage authored Jan 22, 2020
2 parents 5b90492 + 21c786e commit 56eaea9
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
10 changes: 10 additions & 0 deletions pfp/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,11 @@ def _pfp__show(self, level=0, include_offset=False):
)
res.append("{}}}".format(" " * level))
return "\n".join(res)

def __iter__(self):
"""Iterate over this struct's children
"""
return self._pfp__children.__iter__()


@inherit_hash
Expand Down Expand Up @@ -2324,6 +2329,11 @@ def __len__(self):
else:
return len(self.items)

def __iter__(self):
"""Iterate over all items in this array
"""
return self.items.__iter__()


# http://www.sweetscape.com/010editor/manual/ArraysStrings.htm
@inherit_hash
Expand Down
26 changes: 26 additions & 0 deletions tests/test_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,32 @@ def test_array_overwrite_fetch(self):
struct.array = [0xFFFF]
self.assertEqual(struct.array[0], 0xFFFF)

def test_array_iter(self):
"""Test array item iteration.
"""
dom = self._test_parse_build(
"ABCDEFGHI",
"""
typedef struct {
char first;
char second;
char third;
} three_bytes;
three_bytes three_three_bytes[3];
""",
)
items = [x for x in dom.three_three_bytes]
self.assertEqual(items[0].first, 0x41)
self.assertEqual(items[0].second, 0x42)
self.assertEqual(items[0].third, 0x43)
self.assertEqual(items[1].first, 0x44)
self.assertEqual(items[1].second, 0x45)
self.assertEqual(items[1].third, 0x46)
self.assertEqual(items[2].first, 0x47)
self.assertEqual(items[2].second, 0x48)
self.assertEqual(items[2].third, 0x49)


if __name__ == "__main__":
unittest.main()
20 changes: 20 additions & 0 deletions tests/test_struct_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,26 @@ def test_implicit_array_dot_notation_for_last(self):
stdout="3",
)

def test_struct_iter(self):
"""Test struct children iteration.
"""
dom = self._test_parse_build(
"ABC",
"""
typedef struct {
char first;
char second;
char third;
} three_bytes;
three_bytes bytes;
""",
)
chars = [x for x in dom.bytes]
self.assertEquals(chars[0], 0x41)
self.assertEquals(chars[1], 0x42)
self.assertEquals(chars[2], 0x43)


if __name__ == "__main__":
unittest.main()

0 comments on commit 56eaea9

Please sign in to comment.