I can see how getting the size of this buffer exactly correct will not be easy. It's ok if you just use a TrustedByteArrayOutputStream with an estimated size, as this is running client-side so it's not that big a deal (unlike the Filter code).