libgit2/libgit2 — pull request #2036 by ethomson (2014-01-08 18:37:08+00:00)
Title: Handle git_buf's from users more liberally

When accepting `git_buf`s as user input (in `git_blob_filtered_content`), we state that we accept a `git_buf` that has a `ptr` value of `NULL`, but we in fact do not.

From [`buffer.h`](https://github.com/libgit2/libgit2/blob/development/include/git2/buffer.h#L37-L39):

> `ptr` points to the start of the allocated memory. If it is NULL, then the `git_buf` is considered empty and libgit2 will feel free to overwrite it with new data.

Thus, consumers tend to create a `git_buf` where all members are `0`. See for example `git_buf` creation in [LibGit2Sharp](https://github.com/libgit2/libgit2sharp/blob/vNext/LibGit2Sharp/Core/Proxy.cs#L107) and in [jagged](https://github.com/ethomson/jagged/blob/master/src/main/native/libjagged/object.c#L184).

However the `git_buf` family of functions were written thinking that `git_buf`s would be initialized with `GIT_BUF_INIT` or `git_buf_init`, namely that the `ptr` would always be null-terminated (set to `git_buf__initbuf`), even when `asize` was 0. Indeed, this is documented in [`buffer.c`](https://github.com/libgit2/libgit2/blob/development/src/buffer.c#L13-L15):

> Used as default value for git_buf->ptr so that people can always assume ptr is non-NULL and zero terminated even for new git_bufs.

For example [`git_buf_shorten`](https://github.com/libgit2/libgit2/blob/development/src/buffer.c#L287) will always null-terminate. On `git_buf`s provided from LibGit2Sharp or jagged, this will obviously try to dereference a null pointer.

This basically brings this function in line with the documentation (we accept `NULL`, converting that internally to a `git_buf__initbuf`). Obviously we could make more aggressive changes here - we could ensure that users always create `git_buf`s with some sort of `init` method, or we could drop the assumption that `git_buf`s are always null terminated, but those both seem unnecessary and this seems to me like a good middle ground.