C string buffer library

Overview

FROZEN - Better project at Stricks

block

Buf

Experimental string buffer library.

Why ?

Because C strings are painful, unsafe and slow.

Say you're making a forum engine,
where a page is a fixed-size buffer that you fill with posts.

How would you safely build a page without truncating posts ?

The hard way

char page[PAGE_SZ];

// Keep track !
size_t page_len = 0;

while(1) {

    char* user = db_col("user");
    char* text = db_col("text");

    // Big enough ?
    #define POST_SZ 100

    // Better malloc and realloc ?
    char post[POST_SZ];  

    // May be truncated !
    snprintf (post, POST_SZ, "<div>%s<p>%s</p></div>", user, text);

    // Typing "strlen()" 100 times a day..
    const size_t post_len = strlen(post);

    // Check if it fits !
    // What about terminating null ? Will it fit ?
    if (page_len + post_len < PAGE_SZ) {    
        // Not sure..
        strncat (page, post, PAGE_SZ-page_len); 
        // ..about all this.
        page_len += post_len;
    } else {
        break;
    } 
}

The Buf way

Buf page = buf_new(PAGE_SZ);

while(1) {

    char* user = db_col("user");
    char* text = db_col("text");

    if (!buf_append (page, "<div>%s<p>%s</p></div>", user, text)) {
        break;
    }
}

Principle

The Buf type is an opaque pointer to a struct.
This struct ends with a flexible array :

struct Buf_s *Buf;

struct Buf_s {
    uint32_t cap;  // capacity
    uint32_t len;  // current length
    unsigned char data[];  // null-terminated string
}

Making *Buf a contiguous chunk of memory.
And you still get your good old C-string through the buf_data() accessor.

schema

Quick sample

The example folder implements the 'forum'.
It reads rows from a mock db, and renders them to a page of limited size.
When the next post won't fit, we flush the page and start anew.

make && cd example && ./forum

API

buf_new

Buf buf_new (const size_t cap);

Allocate a fresh Buf of capacity cap.
To release, simply free(buf);

buf_append

int buf_append (Buf buf, const char* fmt, ...);

Append a formatted c-string to buf.
If new data would exceed capacity, buf stays unmodified.
Returns: change in length, or zero on failure.

buf_write

int buf_write (Buf buf, const char* fmt, ...);

Write a formatted c-string at start of buf.
If new data would exceed capacity, buf stays unmodified.
Returns: new length, or zero on failure.

buf_dup

Buf buf_dup (const Buf buf);

Make a clone.

buf_resize

bool buf_resize (Buf* pbuf, const size_t newcap);

Change capacity.
If lowered below length, data will be truncated.

buf_reset

void buf_reset (Buf buf);

Set data length to zero.

Accessors

Capacity
size_t buf_cap (const Buf buf);

Current length
size_t buf_len (const Buf buf);

Data string
const char* buf_data (const Buf buf);

Usage

// app.c

#include <stdio.h>
#include "buf.h"

int main() {

    char name[] = "Bob";
    Buf msg = buf_new(100);

    buf_append (msg, "Hello! ");
    buf_append (msg, "My name is %s", name);

    puts (buf_data(msg));

    //-> Hello! My name is Bob

    return 0;
}

gcc app.c buf.o -o app

Build & unit-test

make && make check

TODO

  • utf8 ?
  • Add methods like split() ?
  • Make separate FlexBuf lib with auto-resize ?
You might also like...
ENet reliable UDP networking library

Please visit the ENet homepage at http://enet.bespin.org for installation and usage instructions. If you obtained this package from github, the quick

A modern C++ network library for developing high performance network services in TCP/UDP/HTTP protocols.
A modern C++ network library for developing high performance network services in TCP/UDP/HTTP protocols.

evpp Introduction 中文说明 evpp is a modern C++ network library for developing high performance network services using TCP/UDP/HTTP protocols. evpp provid

C++ library for creating an embedded Rest HTTP server (and more)

The libhttpserver reference manual Tl;dr libhttpserver is a C++ library for building high performance RESTful web servers. libhttpserver is built upon

The Apache Kafka C/C++ library

librdkafka - the Apache Kafka C/C++ client library Copyright (c) 2012-2020, Magnus Edenhill. https://github.com/edenhill/librdkafka librdkafka is a C

canonical libwebsockets.org networking library
canonical libwebsockets.org networking library

Libwebsockets Libwebsockets is a simple-to-use, MIT-license, pure C library providing client and server for http/1, http/2, websockets, MQTT and other

Event-driven network library for multi-threaded Linux server in C++11

Muduo is a multithreaded C++ network library based on the reactor pattern. http://github.com/chenshuo/muduo Copyright (c) 2010, Shuo Chen. All righ

nghttp2 - HTTP/2 C Library and tools

nghttp2 - HTTP/2 C Library This is an implementation of the Hypertext Transfer Protocol version 2 in C. The framing layer of HTTP/2 is implemented as

C library to create simple HTTP servers and Web Applications.

Onion http server library Travis status Coverity status Onion is a C library to create simple HTTP servers and Web Applications. master the developmen

Single C file TLS 1.2/1.3 implementation, using tomcrypt as crypto library

TLSe Single C file TLS 1.3, 1.2, 1.1 and 1.0(without the weak ciphers) implementation, using libtomcrypt as crypto library. It also supports DTLS 1.2

Owner
Francois Alcover
Studied Computer Science at Paris VI.
Francois Alcover
Minimalistic pipeline buffer

Synopsis pipebuf is as a low‐overhead buffer for command pipelines. Usage pipebuf reads from standard input and writes to standard output, buffering t

Mikael 1 Sep 9, 2022
ipcbuf - test/report the size of an IPC kernel buffer

ipcbuf - test/report the size of an IPC kernel buffer Different forms of IPC utilize different in-kernel buffers, depending on a variety of possibly s

Jan Schaumann 6 Sep 7, 2022
Mongoose Embedded Web Server Library - a multi-protocol embedded networking library with TCP/UDP, HTTP, WebSocket, MQTT built-in protocols, async DNS resolver, and non-blocking API.

Mongoose - Embedded Web Server / Embedded Networking Library Mongoose is a networking library for C/C++. It implements event-driven non-blocking APIs

Cesanta Software 9k Jan 1, 2023
C Hypertext Library - A library for writing web applications in C

CHL C Hypertext Library - A library for writing web applications in C #include <chl/chl.h> int main() { chl_set_default_headers(); chl_print_header

null 271 Nov 14, 2022
The C++ Network Library Project -- cross-platform, standards compliant networking library.

C++ Network Library Modern C++ network programming libraries. Join us on Slack: http://slack.cpp-netlib.org/ Subscribe to the mailing list: https://gr

C++ Network Library 1.9k Dec 27, 2022
C++ peer to peer library, built on the top of boost

Breep What is Breep? Breep is a c++ bridged peer to peer library. What does that mean? It means that even though the network is constructed as a peer

Lucas Lazare 110 Nov 24, 2022
Cross-platform, efficient, customizable, and robust asynchronous HTTP/WebSocket server C++14 library with the right balance between performance and ease of use

What Is RESTinio? RESTinio is a header-only C++14 library that gives you an embedded HTTP/Websocket server. It is based on standalone version of ASIO

Stiffstream 924 Jan 6, 2023
A C library for asynchronous DNS requests

c-ares This is c-ares, an asynchronous resolver library. It is intended for applications which need to perform DNS queries without blocking, or need t

c-ares 1.5k Jan 3, 2023
A C++ header-only HTTP/HTTPS server and client library

cpp-httplib A C++11 single-file header-only cross platform HTTP/HTTPS library. It's extremely easy to setup. Just include the httplib.h file in your c

null 8.3k Dec 31, 2022
Ultra fast and low latency asynchronous socket server & client C++ library with support TCP, SSL, UDP, HTTP, HTTPS, WebSocket protocols and 10K connections problem solution

CppServer Ultra fast and low latency asynchronous socket server & client C++ library with support TCP, SSL, UDP, HTTP, HTTPS, WebSocket protocols and

Ivan Shynkarenka 958 Jan 3, 2023