Refactor BufferOutputStream.

- Rewrite BufferOutputStream to handle 0 sized buffers and to get rid
  of an unnecessary loop.
- Add tests to verify overflow corner cases.
- Implement async_safe_format_buffer to call async_safe_format_buffer_va_list
  instead of duplicate the code.

Test: Ran new unit tests, booted on angler.
Change-Id: I7fb13e209f5b7443d212f55aab4b05ff2e0e8219
diff --git a/tests/async_safe_test.cpp b/tests/async_safe_test.cpp
index 3d6fcaa..e71ba7a 100644
--- a/tests/async_safe_test.cpp
+++ b/tests/async_safe_test.cpp
@@ -181,8 +181,20 @@
   char buf[BUFSIZ];
   ASSERT_EQ(11, async_safe_format_buffer(buf, sizeof(buf), "hello %s", "world"));
   EXPECT_STREQ("hello world", buf);
+
   ASSERT_EQ(11, async_safe_format_buffer(buf, 8, "hello %s", "world"));
   EXPECT_STREQ("hello w", buf);
+
+  ASSERT_EQ(11, async_safe_format_buffer(buf, 6, "hello %s", "world"));
+  EXPECT_STREQ("hello", buf);
+
+  ASSERT_EQ(4, async_safe_format_buffer(nullptr, 0, "xxxx"));
+
+  ASSERT_EQ(4, async_safe_format_buffer(buf, 1, "xxxx"));
+  EXPECT_STREQ("", buf);
+
+  ASSERT_EQ(4, async_safe_format_buffer(buf, 2, "xxxx"));
+  EXPECT_STREQ("x", buf);
 #else // __BIONIC__
   GTEST_LOG_(INFO) << "This test does nothing.\n";
 #endif // __BIONIC__