It seems like you're getting the encoded length first, and then doing the actual encoding. Would it make sense to first encode into a byte array, then get its length, and then write them to `out`?