diff -r 33d229634809 -r f4789572c9d6 docs/src/modules.md --- a/docs/src/modules.md Mon Nov 13 15:54:17 2017 +0100 +++ b/docs/src/modules.md Mon Nov 20 16:10:23 2017 +0100 @@ -13,6 +13,16 @@ via `#include `. Required modules are included automatically. +
+ +----------------------- ---------------------- ---------------------------- ------------------------- +[Allocator](#allocator) [AVL Tree](#avl) [Buffer](#buffer) [List](#list) +[Logging](#logging) [Map](#map) [Memory Pool](#mempool) [Properties](#properties) +[Stack](#stack) [String](#string) [Testing](#test) [Utilities](#utils) +----------------------- ---------------------- ---------------------------- ------------------------- + +
+ ## Allocator @@ -151,6 +161,77 @@ The `sstr_t` type of this module always carries the string and its length to reduce the risk of buffer overflows dramatically. +### Initialization + +There are several ways to create an `sstr_t`: + +```C +/* (1) sstr() uses strlen() internally, hence cstr MUST be zero-terminated */ +sstr_t a = sstr(cstr); + +/* (2) cstr does not need to be zero-terminated, if length is specified */ +sstr_t b = sstrn(cstr, len); + +/* (3) S() macro creates sstr_t from a string using sizeof() and using sstrn(). + This version is especially useful for function arguments */ +sstr_t c = S("hello"); + +/* (4) ST() macro creates sstr_t struct literal using sizeof() */ +sstr_t d = ST("hello"); +``` + +You should not use the `S()` or `ST()` macro with string of unknown origin, +since the `sizeof()` call might not coincide with the string length in those +cases. If you know what you are doing, it can save you some performance, +because you do not need the `strlen()` call. + +### Finding the position of a substring + +The `sstrstr()` function gives you a new `sstr_t` object starting with the +requested substring. Thus determining the position comes down to a simple +subtraction. + +```C +sstr_t haystack = ST("Here we go!"); +sstr_t needle = ST("we"); +sstr_t result = sstrstr(haystack, needle); +if (result.ptr) + printf("Found at position %zd.\n", haystack.length-result.length); +else + printf("Not found.\n"); +``` + +### Spliting a string by a delimiter + +The `sstrsplit()` function (and its allocator based version `sstrsplit_a()`) is +very powerful and might look a bit nasty at a first glance. But it is indeed +very simple to use. It is even more convenient in combination with a memory +pool. + +```C +sstr_t test = ST("here::are::some::strings"); +sstr_t delim = ST("::"); + +ssize_t count = 0; /* no limit */ +UcxMempool* pool = ucx_mempool_new_default(); + +sstr_t* result = sstrsplit_a(pool->allocator, test, delim, &count); +for (ssize_t i = 0 ; i < count ; i++) { + /* don't forget to specify the length via the %*s format specifier */ + printf("%*s\n", result[i].length, result[i].ptr); +} + +ucx_mempool_destroy(pool); +``` +The output is: + + here + are + some + strings + +The memory pool ensures, that all strings are freed. + ## Testing