Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added children and array item iteration #123

Merged
merged 1 commit into from
Jan 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()