fd/fmt: Add buffered formatting to fd

This makes it possible to trivially write formatted data to a file
descriptor with built-in buffering to reduce the number of syscalls.

Change-Id: Ib66c062b65e2a611f13be570c2ed5fe5eb208fb7
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/src/fd/fmt.cpp b/src/fd/fmt.cpp
new file mode 100644
index 0000000..fc6392d
--- /dev/null
+++ b/src/fd/fmt.cpp
@@ -0,0 +1,36 @@
+#include <stdplus/fd/fmt.hpp>
+#include <stdplus/fd/ops.hpp>
+
+namespace stdplus
+{
+namespace fd
+{
+
+FormatBuffer::FormatBuffer(stdplus::Fd& fd, size_t max) : fd(fd), max(max)
+{
+}
+
+FormatBuffer::~FormatBuffer() noexcept(false)
+{
+    flush();
+}
+
+void FormatBuffer::flush()
+{
+    if (buf.size() > 0)
+    {
+        stdplus::fd::write(fd, buf);
+        buf.clear();
+    }
+}
+
+void FormatBuffer::writeIfNeeded()
+{
+    if (buf.size() >= max)
+    {
+        flush();
+    }
+}
+
+} // namespace fd
+} // namespace stdplus
diff --git a/src/meson.build b/src/meson.build
index 4364395..e491878 100644
--- a/src/meson.build
+++ b/src/meson.build
@@ -36,6 +36,7 @@
   stdplus_srcs += [
     'fd/create.cpp',
     'fd/dupable.cpp',
+    'fd/fmt.cpp',
     'fd/impl.cpp',
     'fd/line.cpp',
     'fd/managed.cpp',