Factor out serialization of streams and add tests.