Fix a number of bugs, and add unit tests

Bugs:
- incorrect result when buffer was expanded more than once;
- memory leak on einval and eilseq returns;
- if input was >64KB, only first (n % 64K) bytes were processed, the rest being silently ignored;
- NULs handled in a way which makes little sense with Erlang.