Skip to content

Instantly share code, notes, and snippets.

@cls
Last active February 16, 2017 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cls/88b167998f2f2ebbb90cab9e28916f17 to your computer and use it in GitHub Desktop.
Save cls/88b167998f2f2ebbb90cab9e28916f17 to your computer and use it in GitHub Desktop.
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