docs/src/modules.md

Mon, 30 Dec 2019 09:52:07 +0100

author
Mike Becker <universe@uap-core.de>
date
Mon, 30 Dec 2019 09:52:07 +0100
branch
feature/array
changeset 387
7e0f19fe23ff
parent 359
9f86bc73f96b
child 370
07ac32b385e4
permissions
-rw-r--r--

closes array branch towards ucx 2.1 release

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

mercurial