Last active
February 16, 2017 17:42
-
-
Save cls/88b167998f2f2ebbb90cab9e28916f17 to your computer and use it in GitHub Desktop.
Repacking structs to minimise bit wastage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from queue import PriorityQueue | |
| class Field: | |
| def __init__(self, size, align): | |
| self.size = size | |
| self.align = align | |
| class Struct: | |
| def __init__(self, fields): | |
| size = 0 | |
| waste = 0 | |
| align = 1 | |
| for field in fields: | |
| size += field.size | |
| while size % field.align != 0: | |
| size += 1 | |
| waste += 1 | |
| if field.align > align: | |
| align = field.align | |
| while size % align != 0: | |
| size += 1 | |
| self.fields = fields | |
| self.size = size | |
| self.waste = waste | |
| def __lt__(self, other): | |
| return self.waste < other.waste | |
| def repack(fields): | |
| fields = set(fields) | |
| queue = PriorityQueue() | |
| queue.put(Struct([])) | |
| while True: | |
| struct = queue.get() | |
| remaining = fields - set(struct.fields) | |
| if not remaining: | |
| return struct | |
| for field in remaining: | |
| queue.put(Struct(struct.fields + [field])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment