interval_tree_serializer.py
ofrak.service.serialization.serializers.interval_tree_serializer
IntervalTreeSerializer (SerializerInterface)
Serialize and deserialize third-party object IntervalTree
into PJSONType
.
Implementation: an IntervalTree
is a binary lookup tree of intervals, each interval being
an Interval
object representing a 3-tuple (begin, end, data).
As IntervalTree
provides a from_tuples
constructor, and has an all_intervals
attribute,
we can simply serialize it as its list of intervals (themselves serialized as tuples).
obj_to_pjson(self, obj, _type_hint)
Serialize the object to PJSON. Note that the generic self._service.to_pjson
can be used here.
Source code in ofrak/service/serialization/serializers/interval_tree_serializer.py
def obj_to_pjson(self, obj: IntervalTree, _type_hint: Any) -> PJSONType:
return self._service.to_pjson(
[(interval.begin, interval.end, interval.data) for interval in obj.all_intervals],
Iterable[IntervalTreeTupleType],
)
pjson_to_obj(self, pjson_obj, type_hint)
Deserialize PJSON into the object. Note that the generic self._service.from_pjson
can be used here.
Source code in ofrak/service/serialization/serializers/interval_tree_serializer.py
def pjson_to_obj(self, pjson_obj: PJSONType, type_hint: Any) -> IntervalTree:
return IntervalTree.from_tuples(
self._service.from_pjson(pjson_obj, Iterable[IntervalTreeTupleType])
)