docs/src/modules.md

Mon, 14 May 2018 18:25:20 +0200

author
Mike Becker <universe@uap-core.de>
date
Mon, 14 May 2018 18:25:20 +0200
changeset 314
5d28dc8f0765
parent 310
b09677d72413
child 321
9af21a50b516
permissions
-rw-r--r--

renames int and longint distance and compare functions according to the new scheme

universe@264 1 ---
universe@264 2 title: Modules
universe@264 3 ---
universe@259 4
universe@259 5 UCX provides several modules for data structures and algorithms.
universe@259 6 You may choose to use specific modules by inclueding the corresponding header
universe@259 7 file.
universe@259 8 Please note, that some modules make use of other UCX modules.
universe@259 9 For instance, the [Allocator](#allocator) module is used by many other modules
universe@259 10 to allow flexible memory allocation.
universe@259 11 By default the header files are placed into an `ucx` directory within your
universe@282 12 systems include directory. In this case you can use a module by including it
universe@259 13 via `#include <ucx/MODULENAME.h>`.
universe@259 14 Required modules are included automatically.
universe@259 15
universe@267 16 <div id="modules" align="center">
universe@267 17
universe@280 18 ----------------------- ---------------------- ---------------------------- -------------------------
universe@280 19 [Allocator](#allocator) [AVL&nbsp;Tree](#avl-tree) [Buffer](#buffer) [List](#list)
universe@280 20 [Logging](#logging) [Map](#map) [Memory&nbsp;Pool](#memory-pool) [Properties](#properties)
universe@280 21 [Stack](#stack) [String](#string) [Testing](#testing) [Utilities](#utilities)
universe@280 22 ----------------------- ---------------------- ---------------------------- -------------------------
universe@267 23
universe@267 24 </div>
universe@267 25
universe@259 26 ## Allocator
universe@259 27
universe@259 28 *Header file:* [allocator.h](api/allocator_8h.html)
universe@259 29 *Required modules:* None.
universe@259 30
universe@259 31 A UCX allocator consists of a pointer to the memory area / pool and four
universe@259 32 function pointers to memory management functions operating on this memory
universe@259 33 area / pool. These functions shall behave equivalent to the standard libc
universe@259 34 functions `malloc`, `calloc`, `realloc` and `free`.
universe@259 35
universe@259 36 The signature of the memory management functions is based on the signature
universe@259 37 of the respective libc function but each of them takes the pointer to the
universe@259 38 memory area / pool as first argument.
universe@259 39
universe@259 40 As the pointer to the memory area / pool can be arbitrarily chosen, any data
universe@259 41 can be provided to the memory management functions. One example is the
universe@280 42 [UCX Memory Pool](#memory-pool).
universe@259 43
universe@259 44 ## AVL Tree
universe@259 45
universe@259 46 *Header file:* [avl.h](api/avl_8h.html)
universe@259 47 *Required modules:* [Allocator](#allocator)
universe@259 48
universe@259 49 This binary search tree implementation allows average O(1) insertion and
universe@259 50 removal of elements (excluding binary search time).
universe@259 51 All common binary tree operations are implemented. Furthermore, this module
universe@259 52 provides search functions via lower and upper bounds.
universe@259 53
universe@287 54 ### Filtering items with a time window
universe@287 55
universe@287 56 Suppose you have a list of items which contain a `time_t` value and your task
universe@287 57 is to find all items within a time window `[t_start, t_end]`.
universe@287 58 With AVL Trees this is easy:
universe@287 59 ```C
universe@287 60 /* ---------------------
universe@287 61 * Somewhere in a header
universe@287 62 */
universe@287 63 typedef struct {
universe@287 64 time_t ts;
universe@294 65 /* other important data */
universe@287 66 } MyObject;
universe@287 67
universe@287 68 /* -----------
universe@287 69 * Source code
universe@287 70 */
universe@287 71
universe@314 72 UcxAVLTree* tree = ucx_avl_new(ucx_cmp_longint);
universe@294 73 /* ... populate tree with objects, use '& MyObject.ts' as key ... */
universe@287 74
universe@287 75
universe@294 76 /* Now find every item, with 30 <= ts <= 70 */
universe@287 77 time_t ts_start = 30;
universe@287 78 time_t ts_end = 70;
universe@287 79
universe@287 80 printf("Values in range:\n");
universe@287 81 for (
universe@287 82 UcxAVLNode* node = ucx_avl_find_node(
universe@287 83 tree, (intptr_t) &ts_start,
universe@314 84 ucx_dist_longint, UCX_AVL_FIND_LOWER_BOUNDED);
universe@287 85 node && (*(time_t*)node->key) <= ts_end;
universe@287 86 node = ucx_avl_succ(node)
universe@287 87 ) {
universe@287 88 printf(" ts: %ld\n", ((MyObject*)node->value)->ts);
universe@287 89 }
universe@287 90
universe@287 91 ucx_avl_free_content(tree, free);
universe@287 92 ucx_avl_free(tree);
universe@287 93 ```
universe@287 94
universe@259 95 ## Buffer
universe@259 96
universe@259 97 *Header file:* [buffer.h](api/buffer_8h.html)
universe@259 98 *Required modules:* None.
universe@259 99
universe@259 100 Instances of this buffer implementation can be used to read from or to write to
universe@259 101 memory like you would do with a stream. This allows the use of
universe@282 102 `ucx_stream_copy()` from the [Utilities](#utilities) module to copy contents
universe@282 103 from one buffer to another or from file or network streams to the buffer and
universe@259 104 vice-versa.
universe@259 105
universe@259 106 More features for convenient use of the buffer can be enabled, like automatic
universe@259 107 memory management and automatic resizing of the buffer space.
universe@259 108 See the documentation of the macro constants in the header file for more
universe@259 109 information.
universe@259 110
universe@290 111 ### Add line numbers to a file
universe@290 112
universe@290 113 When reading a file line by line, you have three options: first, you could limit
universe@290 114 the maximum supported line length.
universe@290 115 Second, you allocate a god buffer large
universe@290 116 enough for the most lines a text file could have.
universe@290 117 And third, undoubtedly the best option, you start with a small buffer, which
universe@290 118 adjusts on demand.
universe@290 119 An `UcxBuffer` can be created to do just that for you.
universe@290 120 Just pass the `UCX_BUFFER_AUTOEXTEND` option to the initialization function.
universe@290 121 Here is a full working program, which adds line numbers to a file.
universe@290 122 ```C
universe@290 123 #include <stdio.h>
universe@290 124 #include <ucx/buffer.h>
universe@290 125 #include <ucx/utils.h>
universe@290 126
universe@290 127 int main(int argc, char** argv) {
universe@290 128
universe@290 129 if (argc != 2) {
universe@290 130 fprintf(stderr, "Usage: %s <file>\n", argv[0]);
universe@290 131 return 1;
universe@290 132 }
universe@290 133
universe@290 134 FILE* input = fopen(argv[1], "r");
universe@290 135 if (!input) {
universe@290 136 perror("Canno read input");
universe@290 137 return 1;
universe@290 138 }
universe@290 139
universe@290 140 const size_t chunksize = 256;
universe@290 141
universe@290 142 UcxBuffer* linebuf =
universe@290 143 ucx_buffer_new(
universe@294 144 NULL, /* the buffer should manage the memory area for us */
universe@294 145 2*chunksize, /* initial size should be twice the chunk size */
universe@294 146 UCX_BUFFER_AUTOEXTEND); /* the buffer will grow when necessary */
universe@290 147
universe@290 148 size_t lineno = 1;
universe@290 149 do {
universe@294 150 /* read line chunk */
universe@290 151 size_t read = ucx_stream_ncopy(
universe@290 152 input, linebuf, fread, ucx_buffer_write, chunksize);
universe@290 153 if (read == 0) break;
universe@290 154
universe@294 155 /* handle line endings */
universe@290 156 do {
universe@290 157 sstr_t bufstr = ucx_buffer_to_sstr(linebuf);
universe@290 158 sstr_t nl = sstrchr(bufstr, '\n');
universe@290 159 if (nl.length == 0) break;
universe@290 160
universe@290 161 size_t linelen = bufstr.length - nl.length;
universe@290 162 sstr_t linestr = sstrsubsl(bufstr, 0, linelen);
universe@290 163
universe@290 164 printf("%zu: %" PRIsstr "\n", lineno++, SFMT(linestr));
universe@290 165
universe@294 166 /* shift the buffer to the next line */
universe@290 167 ucx_buffer_shift_left(linebuf, linelen+1);
universe@290 168 } while(1);
universe@290 169
universe@290 170 } while(1);
universe@290 171
universe@294 172 /* print the 'noeol' line, if any */
universe@290 173 sstr_t lastline = ucx_buffer_to_sstr(linebuf);
universe@290 174 if (lastline.length > 0) {
universe@290 175 printf("%zu: %" PRIsstr, lineno, SFMT(lastline));
universe@290 176 }
universe@290 177
universe@290 178 fclose(input);
universe@290 179 ucx_buffer_free(linebuf);
universe@290 180
universe@290 181 return 0;
universe@290 182 }
universe@290 183 ```
universe@290 184
universe@259 185 ## List
universe@259 186
universe@259 187 *Header file:* [list.h](api/list_8h.html)
universe@259 188 *Required modules:* [Allocator](#allocator)
universe@259 189
universe@259 190 This module provides the data structure and several functions for a doubly
universe@259 191 linked list. Among the common operations like insert, remove, search and sort,
universe@259 192 we allow convenient iteration via a special `UCX_FOREACH` macro.
universe@259 193
universe@294 194 ### Remove duplicates from an array of strings
universe@294 195
universe@294 196 Assume you are given an array of `sstr_t` and want to create a list of these
universe@294 197 strings without duplicates.
universe@294 198 ```C
universe@294 199 #include <stdio.h>
universe@294 200 #include <ucx/list.h>
universe@294 201 #include <ucx/string.h>
universe@294 202 #include <ucx/utils.h>
universe@294 203
universe@294 204 UcxList* remove_duplicates(sstr_t* array, size_t arrlen) {
universe@294 205 UcxList* list = NULL;
universe@294 206 for (size_t i = 0 ; i < arrlen ; ++i) {
universe@310 207 if (ucx_list_find(list, array+i, ucx_cmp_sstr, NULL) == -1) {
universe@294 208 sstr_t* s = malloc(sizeof(sstr_t));
universe@294 209 *s = sstrdup(array[i]);
universe@294 210 list = ucx_list_append(list, s);
universe@294 211 }
universe@294 212 }
universe@294 213 return list;
universe@294 214 }
universe@294 215
universe@294 216 /* we will need this function to clean up the list contents later */
universe@294 217 void free_sstr(void* ptr) {
universe@294 218 sstr_t* s = ptr;
universe@294 219 free(s->ptr);
universe@294 220 free(s);
universe@294 221 }
universe@294 222
universe@294 223 /* ... */
universe@294 224
universe@294 225 sstr_t* array = /* some array of strings */
universe@294 226 size_t arrlen = /* the length of the array */
universe@294 227
universe@294 228 UcxList* list = remove_duplicates(array,arrlen);
universe@294 229
universe@294 230 /* Iterate over the list and print the elements */
universe@294 231 UCX_FOREACH(elem, list) {
universe@294 232 sstr_t s = *((sstr_t*)elem->data);
universe@294 233 printf("%" PRIsstr "\n", SFMT(s));
universe@294 234 }
universe@294 235
universe@294 236 /* Use our free function to free the duplicated strings. */
universe@294 237 ucx_list_free_content(list, free_sstr);
universe@294 238 ucx_list_free(list);
universe@294 239 ```
universe@294 240
universe@259 241 ## Logging
universe@259 242
universe@259 243 *Header file:* [logging.h](api/logging_8h.html)
universe@259 244 *Required modules:* [Map](#map), [String](#string)
universe@259 245
universe@259 246 The logging module comes with some predefined log levels and allows some more
universe@259 247 customization. You may choose if you want to get timestamps or source file and
universe@259 248 line number logged automatically when outputting a message.
universe@295 249 The following function call initializes a debug logger with all of the above
universe@295 250 information:
universe@295 251 ```C
universe@295 252 log = ucx_logger_new(stdout, UCX_LOGGER_DEBUG,
universe@295 253 UCX_LOGGER_LEVEL | UCX_LOGGER_TIMESTAMP | UCX_LOGGER_SOURCE);
universe@295 254 ```
universe@295 255 Afterwards you can use this logger with the predefined macros
universe@295 256 ```C
universe@295 257 ucx_logger_trace(log, "Verbose output");
universe@295 258 ucx_logger_debug(log, "Debug message");
universe@295 259 ucx_logger_info(log, "Information");
universe@295 260 ucx_logger_warn(log, "Warning");
universe@295 261 ucx_logger_error(log, "Error message");
universe@295 262 ```
universe@295 263 or you use
universe@295 264 ```C
universe@295 265 ucx_logger_log(log, CUSTOM_LEVEL, "Some message")
universe@295 266 ```
universe@295 267 When you use your custom log level, don't forget to register it with
universe@295 268 ```C
universe@295 269 ucx_logger_register_level(log, CUSTOM_LEVEL, "CUSTOM")
universe@295 270 ```
universe@295 271 where the last argument must be a string literal.
universe@259 272
universe@259 273 ## Map
universe@259 274
universe@259 275 *Header file:* [map.h](api/map_8h.html)
universe@259 276 *Required modules:* [Allocator](#allocator), [String](#string)
universe@259 277
universe@259 278 This module provides a hash map implementation using murmur hash 2 and separate
universe@259 279 chaining with linked lists. Similarly to the list module, we provide a
universe@259 280 `UCX_MAP_FOREACH` macro to conveniently iterate through the key/value pairs.
universe@259 281
universe@298 282 ### Parsing command line options
universe@298 283
universe@298 284 Assume you want to parse command line options and record them within a map.
universe@298 285 One way to do this is shown by the following code sample:
universe@298 286 ```C
universe@298 287 UcxMap* options = ucx_map_new(16);
universe@298 288 const char *NOARG = "";
universe@298 289
universe@298 290 char *option = NULL;
universe@298 291 char optchar = 0;
universe@298 292 for(int i=1;i<argc;i++) {
universe@298 293 char *arg = argv[i];
universe@298 294 size_t len = strlen(arg);
universe@298 295 if(len > 1 && arg[0] == '-') {
universe@298 296 for(int c=1;c<len;c++) {
universe@299 297 if(option) {
universe@299 298 fprintf(stderr,
universe@299 299 "Missing argument for option -%c\n", optchar);
universe@299 300 return 1;
universe@299 301 }
universe@298 302 switch(arg[c]) {
universe@298 303 default: {
universe@298 304 fprintf(stderr, "Unknown option -%c\n\n", arg[c]);
universe@298 305 return 1;
universe@298 306 }
universe@298 307 case 'v': {
universe@298 308 ucx_map_cstr_put(options, "verbose", NOARG);
universe@298 309 break;
universe@298 310 }
universe@298 311 case 'o': {
universe@298 312 option = "output";
universe@298 313 optchar = 'o';
universe@298 314 break;
universe@298 315 }
universe@298 316 }
universe@298 317 }
universe@298 318 } else if(option) {
universe@298 319 ucx_map_cstr_put(options, option, arg);
universe@298 320 option = NULL;
universe@298 321 } else {
universe@298 322 /* ... handle argument that is not an option ... */
universe@298 323 }
universe@298 324 }
universe@298 325 if(option) {
universe@298 326 fprintf(stderr,
universe@298 327 "Missing argument for option -%c\n", optchar);
universe@298 328 return 1;
universe@298 329 }
universe@298 330 ```
universe@298 331 With the following loop, you can access the previously recorded options:
universe@298 332 ```C
universe@298 333 UcxMapIterator iter = ucx_map_iterator(options);
universe@298 334 char *arg;
universe@298 335 UCX_MAP_FOREACH(optkey, arg, iter) {
universe@298 336 char* opt = optkey.data;
universe@298 337 if (*arg) {
universe@298 338 printf("%s = %s\n", opt, arg);
universe@298 339 } else {
universe@298 340 printf("%s active\n", opt);
universe@298 341 }
universe@298 342 }
universe@298 343 ```
universe@298 344 Don't forget to call `ucx_map_free()`, when you are done with the map.
universe@298 345
universe@259 346 ## Memory Pool
universe@259 347
universe@259 348 *Header file:* [mempool.h](api/mempool_8h.html)
universe@259 349 *Required modules:* [Allocator](#allocator)
universe@259 350
universe@259 351 Here we have a concrete allocator implementation in the sense of a memory pool.
universe@259 352 This pool allows you to register destructor functions for the allocated memory,
universe@259 353 which are automatically called on the destruction of the pool.
universe@259 354 But you may also register *independent* destructor functions within a pool in
universe@302 355 case some external library allocated memory for you, which should be
universe@259 356 destroyed together with this pool.
universe@259 357
universe@302 358 Many UCX modules support the use of an allocator.
universe@302 359 The [String Module](#string), for instance, provides the `sstrdup_a()` function,
universe@302 360 which uses the specified allocator to allocate the memory for the duplicated
universe@302 361 string.
universe@302 362 This way, you can use a `UcxMempool` to keep track of the memory occupied by
universe@302 363 duplicated strings and cleanup everything with just a single call to
universe@302 364 `ucx_mempool_destroy()`.
universe@302 365
universe@302 366 ### Read CSV data into a structure
universe@302 367
universe@302 368 The following code example shows some of the basic memory pool functions and
universe@302 369 how they can be used with other UCX modules.
universe@302 370 ```C
universe@302 371 #include <stdio.h>
universe@302 372 #include <ucx/mempool.h>
universe@302 373 #include <ucx/list.h>
universe@302 374 #include <ucx/string.h>
universe@302 375 #include <ucx/buffer.h>
universe@302 376 #include <ucx/utils.h>
universe@302 377
universe@302 378 typedef struct {
universe@302 379 sstr_t column_a;
universe@302 380 sstr_t column_b;
universe@302 381 sstr_t column_c;
universe@302 382 } CSVData;
universe@302 383
universe@302 384 int main(int argc, char** argv) {
universe@302 385
universe@302 386 UcxMempool* pool = ucx_mempool_new(128);
universe@302 387
universe@302 388 FILE *f = fopen("test.csv", "r");
universe@302 389 if (!f) {
universe@302 390 perror("Cannot open file");
universe@302 391 return 1;
universe@302 392 }
universe@302 393 /* close the file automatically at pool destruction*/
universe@302 394 ucx_mempool_reg_destr(pool, f, (ucx_destructor) fclose);
universe@302 395
universe@302 396 /* create a buffer and register it at the memory pool for destruction */
universe@302 397 UcxBuffer* content = ucx_buffer_new(NULL, 256, UCX_BUFFER_AUTOEXTEND);
universe@302 398 ucx_mempool_reg_destr(pool, content, (ucx_destructor) ucx_buffer_free);
universe@302 399
universe@302 400 /* read the file and split it by lines first */
universe@302 401 ucx_stream_copy(f, content, fread, ucx_buffer_write);
universe@302 402 sstr_t contentstr = ucx_buffer_to_sstr(content);
universe@302 403 ssize_t lc = 0;
universe@302 404 sstr_t* lines = sstrsplit_a(pool->allocator, contentstr, S("\n"), &lc);
universe@302 405
universe@302 406 /* skip the header and parse the remaining data */
universe@302 407 UcxList* datalist = NULL;
universe@302 408 for (size_t i = 1 ; i < lc ; i++) {
universe@302 409 if (lines[i].length == 0) continue;
universe@302 410 ssize_t fc = 3;
universe@302 411 sstr_t* fields = sstrsplit_a(pool->allocator, lines[i], S(";"), &fc);
universe@302 412 if (fc != 3) {
universe@302 413 fprintf(stderr, "Syntax error in line %zu.\n", i);
universe@302 414 ucx_mempool_destroy(pool);
universe@302 415 return 1;
universe@302 416 }
universe@302 417 CSVData* data = ucx_mempool_malloc(pool, sizeof(CSVData));
universe@302 418 data->column_a = fields[0];
universe@302 419 data->column_b = fields[1];
universe@302 420 data->column_c = fields[2];
universe@302 421 datalist = ucx_list_append_a(pool->allocator, datalist, data);
universe@302 422 }
universe@302 423
universe@302 424 /* control output */
universe@302 425 UCX_FOREACH(elem, datalist) {
universe@302 426 CSVData* data = elem->data;
universe@302 427 printf("Column A: %" PRIsstr " | "
universe@302 428 "Column B: %" PRIsstr " | "
universe@302 429 "Column C: %" PRIsstr "\n",
universe@302 430 SFMT(data->column_a), SFMT(data->column_b), SFMT(data->column_c)
universe@302 431 );
universe@302 432 }
universe@302 433
universe@302 434 /* cleanup everything, no manual free() needed */
universe@302 435 ucx_mempool_destroy(pool);
universe@302 436
universe@302 437 return 0;
universe@302 438 }
universe@302 439 ```
universe@302 440
universe@302 441 ### Overriding the default destructor
universe@302 442
universe@302 443 Sometimes you need to allocate memory with `ucx_mempool_malloc()`, but the
universe@302 444 memory is not supposed to be freed with a simple call to `free()`.
universe@302 445 In this case, you can overwrite the default destructor as follows:
universe@302 446 ```C
universe@302 447 MyObject* obj = ucx_mempool_malloc(pool, sizeof(MyObject));
universe@302 448
universe@302 449 /* some special initialization with own resource management */
universe@302 450 my_object_init(obj);
universe@302 451
universe@302 452 /* register destructor function */
universe@302 453 ucx_mempool_set_destr(obj, (ucx_destructor) my_object_destroy);
universe@302 454 ```
universe@304 455 Be aware, that your destructor function should not free any memory, that is
universe@302 456 also managed by the pool.
universe@302 457 Otherwise you might be risking a double-free.
universe@302 458
universe@259 459 ## Properties
universe@259 460
universe@259 461 *Header file:* [properties.h](api/properties_8h.html)
universe@259 462 *Required modules:* [Map](#map)
universe@259 463
universe@259 464 This module provides load and store function for `*.properties` files.
universe@259 465 The key/value pairs are stored within an UCX Map.
universe@259 466
universe@277 467 ### Example: Loading properties from a file
universe@277 468
universe@277 469 ```C
universe@294 470 /* Open the file as usual */
universe@277 471 FILE* file = fopen("myprops.properties", "r");
universe@277 472 if (!file) {
universe@277 473 // error handling
universe@277 474 return 1;
universe@277 475 }
universe@277 476
universe@294 477 /* Load the properties from the file */
universe@277 478 UcxMap* myprops = ucx_map_new(16);
universe@277 479 if (ucx_properties_load(myprops, file)) {
universe@294 480 /* ... error handling ... */
universe@277 481 fclose(file);
universe@277 482 ucx_map_free(myprops);
universe@277 483 return 1;
universe@277 484 }
universe@277 485
universe@294 486 /* Print out the key/value pairs */
universe@277 487 char* propval;
universe@277 488 UcxMapIterator propiter = ucx_map_iterator(myprops);
universe@277 489 UCX_MAP_FOREACH(key, propval, propiter) {
universe@277 490 printf("%s = %s\n", (char*)key.data, propval);
universe@277 491 }
universe@277 492
universe@294 493 /* Don't forget to free the values before freeing the map */
universe@277 494 ucx_map_free_content(myprops, NULL);
universe@277 495 ucx_map_free(myprops);
universe@277 496 fclose(file);
universe@277 497 ```
universe@295 498
universe@259 499 ## Stack
universe@259 500
universe@259 501 *Header file:* [stack.h](api/stack_8h.html)
universe@259 502 *Required modules:* [Allocator](#allocator)
universe@259 503
universe@259 504 This concrete implementation of an UCX Allocator allows you to grab some amount
universe@259 505 of memory which is then handled as a stack.
universe@259 506 Please note, that the term *stack* only refers to the behavior of this
universe@301 507 allocator. You may still choose to use either stack or heap memory
universe@259 508 for the underlying space.
universe@259 509 A typical use case is an algorithm where you need to allocate and free large
universe@259 510 amounts of memory very frequently.
universe@259 511
universe@301 512 The following code sample shows how to initialize a stack and push and pop
universe@301 513 simple data.
universe@301 514 ```C
universe@301 515 const size_t len = 1024;
universe@301 516 char space[len];
universe@301 517 UcxStack stack;
universe@301 518 ucx_stack_init(&stack, space, len);
universe@301 519
universe@301 520 int i = 42;
universe@301 521 float f = 3.14f;
universe@301 522 const char* str = "Hello!";
universe@301 523 size_t strn = 7;
universe@301 524
universe@301 525 /* push the integer */
universe@301 526 ucx_stack_push(&stack, sizeof(int), &i);
universe@301 527
universe@301 528 /* push the float and rember the address */
universe@301 529 float* remember = ucx_stack_push(&stack, sizeof(float), &f);
universe@301 530
universe@301 531 /* push the string with zero terminator */
universe@301 532 ucx_stack_push(&stack, strn, str);
universe@301 533
universe@301 534 /* if we forget, how big an element was, we can ask the stack */
universe@301 535 printf("Length of string: %zu\n", ucx_stack_topsize(&stack)-1);
universe@301 536
universe@301 537 /* retrieve the string as sstr_t, without zero terminator! */
universe@301 538 sstr_t s;
universe@301 539 s.length = ucx_stack_topsize(&stack)-1;
universe@301 540 s.ptr = malloc(s.length);
universe@301 541 ucx_stack_popn(&stack, s.ptr, s.length);
universe@301 542 printf("%" PRIsstr "\n", SFMT(s));
universe@301 543
universe@301 544 /* print the float directly from the stack and free it */
universe@301 545 printf("Float: %f\n", *remember);
universe@301 546 ucx_stack_free(&stack, remember);
universe@301 547
universe@301 548 /* the last element is the integer */
universe@301 549 int j;
universe@301 550 ucx_stack_pop(&stack, &j);
universe@301 551 printf("Integer: %d\n", j);
universe@301 552 ```
universe@301 553
universe@301 554
universe@301 555
universe@259 556 ## String
universe@259 557
universe@259 558 *Header file:* [string.h](api/string_8h.html)
universe@259 559 *Required modules:* [Allocator](#allocator)
universe@259 560
universe@259 561 This module provides a safe implementation of bounded string.
universe@259 562 Usually C strings do not carry a length. While for zero-terminated strings you
universe@259 563 can easily get the length with `strlen`, this is not generally possible for
universe@259 564 arbitrary strings.
universe@259 565 The `sstr_t` type of this module always carries the string and its length to
universe@259 566 reduce the risk of buffer overflows dramatically.
universe@259 567
universe@267 568 ### Initialization
universe@267 569
universe@267 570 There are several ways to create an `sstr_t`:
universe@267 571
universe@267 572 ```C
universe@267 573 /* (1) sstr() uses strlen() internally, hence cstr MUST be zero-terminated */
universe@267 574 sstr_t a = sstr(cstr);
universe@267 575
universe@267 576 /* (2) cstr does not need to be zero-terminated, if length is specified */
universe@267 577 sstr_t b = sstrn(cstr, len);
universe@267 578
universe@267 579 /* (3) S() macro creates sstr_t from a string using sizeof() and using sstrn().
universe@267 580 This version is especially useful for function arguments */
universe@267 581 sstr_t c = S("hello");
universe@267 582
universe@267 583 /* (4) ST() macro creates sstr_t struct literal using sizeof() */
universe@267 584 sstr_t d = ST("hello");
universe@267 585 ```
universe@267 586
universe@267 587 You should not use the `S()` or `ST()` macro with string of unknown origin,
universe@267 588 since the `sizeof()` call might not coincide with the string length in those
universe@267 589 cases. If you know what you are doing, it can save you some performance,
universe@267 590 because you do not need the `strlen()` call.
universe@267 591
universe@267 592 ### Finding the position of a substring
universe@267 593
universe@267 594 The `sstrstr()` function gives you a new `sstr_t` object starting with the
universe@267 595 requested substring. Thus determining the position comes down to a simple
universe@267 596 subtraction.
universe@267 597
universe@267 598 ```C
universe@267 599 sstr_t haystack = ST("Here we go!");
universe@267 600 sstr_t needle = ST("we");
universe@267 601 sstr_t result = sstrstr(haystack, needle);
universe@267 602 if (result.ptr)
universe@267 603 printf("Found at position %zd.\n", haystack.length-result.length);
universe@267 604 else
universe@267 605 printf("Not found.\n");
universe@267 606 ```
universe@267 607
universe@267 608 ### Spliting a string by a delimiter
universe@267 609
universe@267 610 The `sstrsplit()` function (and its allocator based version `sstrsplit_a()`) is
universe@267 611 very powerful and might look a bit nasty at a first glance. But it is indeed
universe@267 612 very simple to use. It is even more convenient in combination with a memory
universe@267 613 pool.
universe@267 614
universe@267 615 ```C
universe@267 616 sstr_t test = ST("here::are::some::strings");
universe@267 617 sstr_t delim = ST("::");
universe@267 618
universe@267 619 ssize_t count = 0; /* no limit */
universe@267 620 UcxMempool* pool = ucx_mempool_new_default();
universe@267 621
universe@267 622 sstr_t* result = sstrsplit_a(pool->allocator, test, delim, &count);
universe@267 623 for (ssize_t i = 0 ; i < count ; i++) {
universe@267 624 /* don't forget to specify the length via the %*s format specifier */
universe@267 625 printf("%*s\n", result[i].length, result[i].ptr);
universe@267 626 }
universe@267 627
universe@267 628 ucx_mempool_destroy(pool);
universe@267 629 ```
universe@267 630 The output is:
universe@267 631
universe@267 632 here
universe@267 633 are
universe@267 634 some
universe@267 635 strings
universe@267 636
universe@267 637 The memory pool ensures, that all strings are freed.
universe@267 638
universe@259 639 ## Testing
universe@259 640
universe@259 641 *Header file:* [test.h](api/test_8h.html)
universe@259 642 *Required modules:* None.
universe@259 643
universe@259 644 This module provides a testing framework which allows you to execute test cases
universe@259 645 within test suites.
universe@259 646 To avoid code duplication within tests, we also provide the possibility to
universe@259 647 define test subroutines.
universe@259 648
universe@297 649 You should declare test cases and subroutines in a header file per test unit
universe@297 650 and implement them as you would implement normal functions.
universe@297 651 ```C
universe@297 652 /* myunit.h */
universe@297 653 UCX_TEST(function_name);
universe@297 654 UCX_TEST_SUBROUTINE(subroutine_name, paramlist); /* optional */
universe@297 655
universe@297 656
universe@297 657 /* myunit.c */
universe@297 658 UCX_TEST_SUBROUTINE(subroutine_name, paramlist) {
universe@297 659 /* ... reusable tests with UCX_TEST_ASSERT() ... */
universe@297 660 }
universe@297 661
universe@297 662 UCX_TEST(function_name) {
universe@297 663 /* ... resource allocation and other test preparation ... */
universe@297 664
universe@297 665 /* mandatory marker for the start of the tests */
universe@297 666 UCX_TEST_BEGIN
universe@297 667
universe@297 668 /* ... verifications with UCX_TEST_ASSERT() ...
universe@297 669 * (and/or calls with UCX_TEST_CALL_SUBROUTINE())
universe@297 670 */
universe@297 671
universe@297 672 /* mandatory marker for the end of the tests */
universe@297 673 UCX_TEST_END
universe@297 674
universe@297 675 /* ... resource cleanup ...
universe@297 676 * (all code after UCX_TEST_END is always executed)
universe@297 677 */
universe@297 678 }
universe@297 679 ```
universe@297 680 If you want to use the `UCX_TEST_ASSERT()` macro in a function, you are
universe@297 681 *required* to use a `UCX_TEST_SUBROUTINE`.
universe@297 682 Otherwise the testing framework does not know where to jump, when the assertion
universe@297 683 fails.
universe@297 684
universe@297 685 After implementing the tests, you can easily build a test suite and execute it:
universe@297 686 ```C
universe@297 687 UcxTestSuite* suite = ucx_test_suite_new();
universe@297 688 ucx_test_register(suite, testMyTestCase01);
universe@297 689 ucx_test_register(suite, testMyTestCase02);
universe@297 690 /* ... */
universe@297 691 ucx_test_run(suite, stdout); /* stdout, or any other FILE stream */
universe@297 692 ```
universe@297 693
universe@259 694 ## Utilities
universe@259 695
universe@259 696 *Header file:* [utils.h](api/utils_8h.html)
universe@259 697 *Required modules:* [Allocator](#allocator), [String](#string)
universe@259 698
universe@259 699 In this module we provide very general utility function for copy and compare
universe@259 700 operations.
universe@259 701 We also provide several `printf` variants to conveniently print formatted data
universe@259 702 to streams or strings.
universe@259 703
universe@279 704 ### A simple copy program
universe@279 705
universe@279 706 The utilities package provides several stream copy functions.
universe@279 707 One of them has a very simple interface and can, for instance, be used to copy
universe@279 708 whole files in a single call.
universe@279 709 This is a minimal working example:
universe@279 710 ```C
universe@279 711 #include <stdio.h>
universe@279 712 #include <ucx/utils.h>
universe@279 713
universe@279 714 int main(int argc, char** argv) {
universe@279 715
universe@279 716 if (argc != 3) {
universe@279 717 fprintf(stderr, "Use %s <src> <dest>", argv[0]);
universe@279 718 return 1;
universe@279 719 }
universe@279 720
universe@294 721 FILE *srcf = fopen(argv[1], "r"); /* insert error handling on your own */
universe@279 722 FILE *destf = fopen(argv[2], "w");
universe@279 723
universe@279 724 size_t n = ucx_stream_copy(srcf, destf, fread, fwrite);
universe@279 725 printf("%zu bytes copied.\n", n);
universe@279 726
universe@279 727 fclose(srcf);
universe@279 728 fclose(destf);
universe@279 729
universe@279 730
universe@279 731 return 0;
universe@279 732 }
universe@279 733 ```
universe@279 734
universe@281 735 ### Automatic allocation for formatted strings
universe@279 736
universe@281 737 The UCX utility function `ucx_asprintf()` and it's convenient shortcut
universe@281 738 `ucx_sprintf` allow easy formatting of strings, without ever having to worry
universe@281 739 about the required space.
universe@281 740 ```C
universe@281 741 sstr_t mystring = ucx_sprintf("The answer is: %d!", 42);
universe@281 742 ```
universe@281 743 Still, you have to pass `mystring.ptr` to `free()` (or the free function of
universe@281 744 your allocator, if you use `ucx_asprintf`).
universe@281 745 If you don't have all the information ready to build your string, you can even
universe@281 746 use a [UcxBuffer](#buffer) as a target with the utility function
universe@281 747 `ucx_bprintf()`.
universe@281 748 ```C
universe@281 749 UcxBuffer* strbuffer = ucx_buffer_new(NULL, 512, UCX_BUFFER_AUTOEXTEND);
universe@281 750
universe@281 751 for (unsigned int i = 2 ; i < 100 ; i++) {
universe@281 752 ucx_bprintf(strbuffer, "Integer %d is %s\n",
universe@281 753 i, prime(i) ? "prime" : "not prime");
universe@281 754 }
universe@281 755
universe@294 756 /* print the result to stdout */
universe@281 757 printf("%s", (char*)strbuffer->space);
universe@281 758
universe@281 759 ucx_buffer_free(strbuffer);
universe@281 760 ```

mercurial