docs/src/modules.md

Wed, 07 Aug 2019 21:14:58 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 07 Aug 2019 21:14:58 +0200
branch
feature/array
changeset 345
6089eb30a51a
parent 340
8acf182f6424
child 359
9f86bc73f96b
permissions
-rw-r--r--

ucx_array_sort() uses qsort_r(), if available

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

mercurial