Section BasicCombinators.
Variables A B : Type.
Variable sA : Serializer A.
Variable sB : Serializer B.
Definition option_serialize (x : option A) : IOStreamWriter.t :=
match x with
| Some a => IOStreamWriter.append (fun _ => serialize true)
(fun _ => serialize a)
| None => serialize false
end.
Definition option_deserialize : ByteListReader.t (option A) :=
b <- deserialize ;;
match b with
| true => Some <$> deserialize
| false => ByteListReader.ret None
end.
Proof using.
intros.
unfold option_serialize, option_deserialize.
destruct a;
repeat (cheerios_crush; simpl).
Qed.
Global Instance option_Serializer : Serializer (option A).
Definition pair_serialize (x : A * B) : IOStreamWriter.t :=
let (a, b) := x in IOStreamWriter.append (fun _ => serialize a)
(fun _ => serialize b).
Definition pair_deserialize : ByteListReader.t (A * B) :=
a <- deserialize ;;
b <- deserialize ;;
ByteListReader.ret (a, b).
Proof using.
intros.
unfold pair_serialize, pair_deserialize.
destruct a.
cheerios_crush.
Qed.
Global Instance pair_Serializer : Serializer (A * B).
Definition sum_serialize (x : A + B) : IOStreamWriter.t :=
match x with
| inl a => IOStreamWriter.append (fun _ => serialize true)
(fun _ => serialize a)
| inr b => IOStreamWriter.append (fun _ => serialize false)
(fun _ => serialize b)
end.
Definition sum_deserialize : ByteListReader.t (A + B) :=
b <- deserialize ;;
match b with
| true => inl <$> deserialize
| false => inr <$> deserialize
end.
Proof using.
unfold sum_serialize, sum_deserialize.
destruct a; cheerios_crush.
Qed.
Global Instance sum_Serializer : Serializer (A + B).
Fixpoint list_serialize_rec (l : list A) : IOStreamWriter.t :=
match l with
| [] => IOStreamWriter.empty
| a :: l' => IOStreamWriter.append (fun _ => serialize a)
(fun _ => list_serialize_rec l')
end.
Definition list_serialize (l : list A) : IOStreamWriter.t :=
IOStreamWriter.append (fun _ => serialize (length l))
(fun _ => list_serialize_rec l).
Fixpoint list_deserialize_rec (n : nat) : ByteListReader.t (list A) :=
match n with
| 0 => ByteListReader.ret []
| S n' => cons <$> deserialize <*> list_deserialize_rec n'
end.
Definition list_deserialize : ByteListReader.t (list A) :=
deserialize >>= list_deserialize_rec.
Proof using.
intros.
unfold list_serialize_rec.
cheerios_crush. simpl.
induction l.
- simpl. cheerios_crush.
- simpl.
rewrite sequence_rewrite.
rewrite ByteListReader.bind_unwrap.
rewrite ByteListReader.map_unwrap.
rewrite IOStreamWriter.append_unwrap.
rewrite app_ass.
rewrite serialize_deserialize_id.
rewrite ByteListReader.bind_unwrap.
rewrite IHl.
cheerios_crush.
Qed.
Proof using.
intros.
induction l.
- simpl. cheerios_crush.
rewrite app_nil_r.
reflexivity.
- simpl.
cheerios_crush.
rewrite IHl.
reflexivity.
Qed.

Lemma list_serialize_deserialize_id :
serialize_deserialize_id_spec list_serialize list_deserialize.