add buffer example

Sun, 06 Apr 2025 13:13:52 +0200

author
Mike Becker <universe@uap-core.de>
date
Sun, 06 Apr 2025 13:13:52 +0200
changeset 1276
91a64ba395f7
parent 1275
0f21abc52241
child 1277
637d4775e79e

add buffer example

this fucking completes issue #451

docs/Writerside/topics/buffer.h.md file | annotate | diff | comparison | revisions
--- a/docs/Writerside/topics/buffer.h.md	Sun Apr 06 12:38:40 2025 +0200
+++ b/docs/Writerside/topics/buffer.h.md	Sun Apr 06 13:13:52 2025 +0200
@@ -15,9 +15,51 @@
 
 ## Example
 
-<warning>
-TODO: add example
-</warning>
+In the following example we use a `CxBuffer`, the `bprintf()` macro from the [UCX printf header](printf.h.md),
+and a [UCX map](map.h.md) to create a simple HTTP GET request.
+
+```C
+#include <cx/buffer.h>
+#include <cx/printf.h>
+#include <cx/map.h>
+
+void send_get_request(
+	void *net_target,
+	cx_write_func net_write,
+	const char *host,
+	const char *path,
+	CxMap *header
+) {
+	// initialize buffer and use stack memory for small requests
+	char stackmem[128];
+	CxBuffer buf;
+	cxBufferInit(
+		&buf, stackmem, sizeof(stackmem),
+		cxDefaultAllocator,
+		CX_BUFFER_COPY_ON_EXTEND // move to heap when request is larger
+	);
+	
+	// basic request data
+	cx_bprintf(&buf, "GET %s HTTP/1.1\r\n", path);
+	cx_bprintf(&buf, "Host: %s\r\n", host);
+	
+	// add headers
+	CxMapIterator iter = cxMapIterator(header);
+	cx_foreach(CxMapEntry*, entry, iter) {
+		cxstring name = cx_strn(entry->key->data, entry->key->len);
+		cx_bprintf(&buf, "%.*s: %s\r\n",
+			(int) name.length, name.ptr, entry->value
+		);
+	}
+	
+	// blank line terminates
+	cxBufferWrite("\r\n", 1, 2, &buf);
+	
+	// write request to the network stream and destroy the buffer
+	net_write(buf.space, 1, buf.size, net_target);
+	cxBufferDestroy(&buf);
+}
+```
 
 ## Create
 

mercurial