pushfoo / eightdad

A Chip-8 interpreter in python that may include other tools in the future
BSD 2-Clause "Simplified" License
0 stars 0 forks source link

Try replacing property abuse with field-clamping descriptors #66

Open pushfoo opened 4 years ago

pushfoo commented 4 years ago

This should apply to the instruction decoder and maybe a few fields on the VM. For the instruction decoder, there might be a subclass of clamped that uses a mask as a constructor argument when initializing the descriptor. A more complicated implementation might be able to use a bit-mask as the only argument and infer the min and max from there, if also given a negatives allowed or minimum argument.

Maybe something like the following?

class Instruction:
    x : int = MaskedField(mask=0x0F00, signed=False)

    def __init__(self, **kwargs):

The result should be shorter and cleaner code than the current property and clamping decorators used.

pushfoo commented 4 years ago

The MaskedField would take a bitmask argument, and signed argument probably isn't needed for chip-8. The constructor would shift the mask right until it's aligned at zero and store:

  1. the length of the field / the maximum valid value of the field
  2. how far it needs to be shifted right to be applied

When setting a field value, anything that would exceed the maximum raises a ValueError. When reading, some clever logic yet to be written could handle extracting the raw bytes as needed. Decode could happen on demand rather than setting a local property for now. Eventually, this could be replaced with some sort of update-time aware optimization but that might be excessive for chip-8.