Skip to content

Commit

Permalink
Refactor node_cast_value to use large if/elif instead of dict lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
jaseg committed Dec 25, 2017
1 parent 0927072 commit 62add95
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions mpv.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,18 +196,31 @@ def node_value(self, decoder=identity_decoder):

@staticmethod
def node_cast_value(v, fmt=MpvFormat.NODE, decoder=identity_decoder):
return {
MpvFormat.NONE: lambda v: None,
MpvFormat.STRING: lambda v: decoder(v.string),
MpvFormat.OSD_STRING: lambda v: v.string.decode('utf-8'),
MpvFormat.FLAG: lambda v: bool(v.flag),
MpvFormat.INT64: lambda v: v.int64,
MpvFormat.DOUBLE: lambda v: v.double,
MpvFormat.NODE: lambda v: v.node.contents.node_value(decoder) if v.node else None,
MpvFormat.NODE_ARRAY: lambda v: v.list.contents.array_value(decoder) if v.list else None,
MpvFormat.NODE_MAP: lambda v: v.map.contents.dict_value(decoder) if v.map else None,
MpvFormat.BYTE_ARRAY: lambda v: v.byte_array.contents.bytes_value() if v.byte_array else None,
}[fmt](v)
if fmt == MpvFormat.NONE:
return None
elif fmt == MpvFormat.STRING:
return decoder(v.string)
elif fmt == MpvFormat.OSD_STRING:
return v.string.decode('utf-8')
elif fmt == MpvFormat.FLAG:
return bool(v.flag)
elif fmt == MpvFormat.INT64:
return v.int64
elif fmt == MpvFormat.DOUBLE:
return v.double
else:
if not v.node: # Check for null pointer
return None
if fmt == MpvFormat.NODE:
return v.node.contents.node_value(decoder)
elif fmt == MpvFormat.NODE_ARRAY:
return v.list.contents.array_value(decoder)
elif fmt == MpvFormat.NODE_MAP:
return v.map.contents.dict_value(decoder)
elif fmt == MpvFormat.BYTE_ARRAY:
return v.byte_array.contents.bytes_value()
else:
raise TypeError('Unknown MPV node format {}. Please submit a bug report.'.format(fmt))

class MpvNodeUnion(Union):
_fields_ = [('string', c_char_p),
Expand Down

0 comments on commit 62add95

Please # to comment.