# HG changeset patch
# User Mike Becker <universe@uap-core.de>
# Date 1651414333 -7200
# Node ID 3700ac4bd9a3a342365e3216c8ffed3b11e4f0e4
# Parent  2e73456e5f84f9a9e3008c2acd3ca102e125c209
#184 #170 first basic flush test

diff -r 2e73456e5f84 -r 3700ac4bd9a3 src/cx/buffer.h
--- a/src/cx/buffer.h	Sun May 01 13:14:31 2022 +0200
+++ b/src/cx/buffer.h	Sun May 01 16:12:13 2022 +0200
@@ -117,12 +117,7 @@
      * The write function used for flushing.
      * If NULL, the flushed content gets discarded.
      */
-    size_t (*flush_func)(
-            void const *,
-            size_t,
-            size_t,
-            void *
-    );
+    cx_write_func flush_func;
 
     /**
      * The target for \c flush_func.
diff -r 2e73456e5f84 -r 3700ac4bd9a3 src/cx/common.h
--- a/src/cx/common.h	Sun May 01 13:14:31 2022 +0200
+++ b/src/cx/common.h	Sun May 01 16:12:13 2022 +0200
@@ -93,6 +93,16 @@
 #include <stddef.h>
 #include <stdbool.h>
 
+/**
+ * Function pointer compatible with fwrite-like functions.
+ */
+typedef size_t (*cx_write_func)(
+        void const *,
+        size_t,
+        size_t,
+        void *
+);
+
 #ifdef _WIN32
 #if !(defined __ssize_t_defined || defined _SSIZE_T_)
 #include <BaseTsd.h>
diff -r 2e73456e5f84 -r 3700ac4bd9a3 test/test_buffer.cpp
--- a/test/test_buffer.cpp	Sun May 01 13:14:31 2022 +0200
+++ b/test/test_buffer.cpp	Sun May 01 16:12:13 2022 +0200
@@ -293,9 +293,10 @@
 
 class BufferWrite : public ::testing::Test {
 protected:
-    CxBuffer buf{};
+    CxBuffer buf{}, target{};
 
     void SetUp() override {
+        cxBufferInit(&target, nullptr, 16, cxDefaultAllocator, CX_BUFFER_AUTO_EXTEND);
         cxBufferInit(&buf, nullptr, 16, cxDefaultAllocator, CX_BUFFER_DEFAULT);
         buf.capacity = 8; // artificially reduce capacity to check OOB writes
         memset(buf.space, 0, 16);
@@ -305,6 +306,13 @@
 
     void TearDown() override {
         cxBufferDestroy(&buf);
+        cxBufferDestroy(&target);
+    }
+
+    void enableFlushing() {
+        buf.flush_target = &target;
+        buf.flush_func = reinterpret_cast<cx_write_func>(cxBufferWrite);
+        buf.flush_blkmax = 1;
     }
 };
 
@@ -507,3 +515,23 @@
     EXPECT_EQ(buf.pos, 7);
     EXPECT_EQ(memcmp(buf.space, "preXXX\0t", 8), 0);
 }
+
+TEST_F(BufferWrite, FlushAtCapacity) {
+    enableFlushing();
+    ASSERT_EQ(buf.capacity, 8);
+    ASSERT_EQ(buf.pos, 4);
+    size_t written = cxBufferWrite("foo", 1, 3, &buf);
+    EXPECT_EQ(written, 3);
+    ASSERT_EQ(buf.pos, 7);
+    ASSERT_EQ(buf.size, 7);
+    ASSERT_EQ(target.pos, 0);
+    ASSERT_EQ(target.size, 0);
+    written = cxBufferWrite("hello", 1, 5, &buf);
+    EXPECT_EQ(written, 5);
+    EXPECT_EQ(buf.pos, 0);
+    EXPECT_EQ(buf.size, 0);
+    EXPECT_EQ(buf.capacity, 8);
+    EXPECT_EQ(target.pos, 12);
+    ASSERT_EQ(target.size, 12);
+    EXPECT_EQ(memcmp(target.space, "prepfoohello", 12), 0);
+}