Skip to content

Instantly share code, notes, and snippets.

@cls cls/repack.py
Last active Feb 16, 2017

Embed
What would you like to do?
Repacking structs to minimise bit wastage
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
You can’t perform that action at this time.