UNIXworkcode

1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. 3 * 4 * Copyright 2021 Mike Becker, Olaf Wintermann All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions are met: 8 * 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 20 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 * POSSIBILITY OF SUCH DAMAGE. 27 */ 28 29 /** 30 * @file buffer.h 31 * 32 * @brief Advanced buffer implementation. 33 * 34 * Instances of CxBuffer can be used to read from or to write to like one 35 * would do with a stream. 36 * 37 * Some features for convenient use of the buffer 38 * can be enabled. See the documentation of the macro constants for more 39 * information. 40 * 41 * @author Mike Becker 42 * @author Olaf Wintermann 43 * @copyright 2-Clause BSD License 44 */ 45 46 #ifndef UCX_BUFFER_H 47 #define UCX_BUFFER_H 48 49 #include "common.h" 50 #include "allocator.h" 51 52 #ifdef __cplusplus 53 extern "C" { 54 #endif 55 56 /** 57 * No buffer features enabled (all flags cleared). 58 */ 59 #define CX_BUFFER_DEFAULT 0x00 60 61 /** 62 * If this flag is enabled, the buffer will automatically free its contents when destroyed. 63 * 64 * Do NOT set this flag together with #CX_BUFFER_COPY_ON_WRITE. It will be automatically 65 * set when the copy-on-write operation is performed. 66 */ 67 #define CX_BUFFER_FREE_CONTENTS 0x01 68 69 /** 70 * If this flag is enabled, the buffer will automatically extend its capacity. 71 */ 72 #define CX_BUFFER_AUTO_EXTEND 0x02 73 74 /** 75 * If this flag is enabled, the buffer will allocate new memory when written to. 76 * 77 * The current contents of the buffer will be copied to the new memory, and the flag 78 * will be cleared while the #CX_BUFFER_FREE_CONTENTS flag will be set automatically. 79 */ 80 #define CX_BUFFER_COPY_ON_WRITE 0x04 81 82 /** 83 * If this flag is enabled, the buffer will copy its contents to a new memory area on reallocation. 84 * 85 * After performing the copy, the flag is automatically cleared. 86 * This flag has no effect on buffers which do not have #CX_BUFFER_AUTO_EXTEND set, which is why 87 * buffers automatically admit the auto-extend flag when initialized with copy-on-extend enabled. 88 */ 89 #define CX_BUFFER_COPY_ON_EXTEND 0x08 90 91 /** 92 * Function pointer for cxBufferWrite that is compatible with cx_write_func. 93 * @see cx_write_func 94 */ 95 #define cxBufferWriteFunc ((cx_write_func) cxBufferWrite) 96 /** 97 * Function pointer for cxBufferRead that is compatible with cx_read_func. 98 * @see cx_read_func 99 */ 100 #define cxBufferReadFunc ((cx_read_func) cxBufferRead) 101 102 103 /** Structure for the UCX buffer data. */ 104 struct cx_buffer_s { 105 /** A pointer to the buffer contents. */ 106 union { 107 /** 108 * Data is interpreted as text. 109 */ 110 char *space; 111 /** 112 * Data is interpreted as binary. 113 */ 114 unsigned char *bytes; 115 }; 116 /** The allocator to use for automatic memory management. */ 117 const CxAllocator *allocator; 118 /** Current position of the buffer. */ 119 size_t pos; 120 /** Current capacity (i.e. maximum size) of the buffer. */ 121 size_t capacity; 122 /** Maximum capacity that this buffer may grow to. */ 123 size_t max_capacity; 124 /** Current size of the buffer content. */ 125 size_t size; 126 /** 127 * Flag register for buffer features. 128 * @see #CX_BUFFER_DEFAULT 129 * @see #CX_BUFFER_FREE_CONTENTS 130 * @see #CX_BUFFER_AUTO_EXTEND 131 * @see #CX_BUFFER_COPY_ON_WRITE 132 */ 133 int flags; 134 }; 135 136 /** 137 * UCX buffer. 138 */ 139 typedef struct cx_buffer_s CxBuffer; 140 141 /** 142 * Initializes a fresh buffer. 143 * 144 * You may also provide a read-only @p space, in which case 145 * you will need to cast the pointer, and you should set the 146 * #CX_BUFFER_COPY_ON_WRITE flag. 147 * 148 * You need to set the size manually after initialization if 149 * you provide @p space which already contains data. 150 * 151 * When you specify stack memory as @p space and decide to use 152 * the auto-extension feature, you @em must use the 153 * #CX_BUFFER_COPY_ON_EXTEND flag, instead of the 154 * #CX_BUFFER_AUTO_EXTEND flag. 155 * 156 * @note You may provide @c NULL as the argument for @p space. 157 * Then this function will allocate the space and enforce 158 * the #CX_BUFFER_FREE_CONTENTS flag. In that case, specifying 159 * copy-on-write should be avoided, because the allocated 160 * space will be leaking after the copy-on-write operation. 161 * 162 * @param buffer the buffer to initialize 163 * @param space pointer to the memory area, or @c NULL to allocate 164 * new memory 165 * @param capacity the capacity of the buffer 166 * @param allocator the allocator this buffer shall use for automatic 167 * memory management 168 * (if @c NULL, the cxDefaultAllocator will be used) 169 * @param flags buffer features (see cx_buffer_s.flags) 170 * @return zero on success, non-zero if a required allocation failed 171 */ 172 cx_attr_nonnull_arg(1) 173 CX_EXPORT int cxBufferInit(CxBuffer *buffer, void *space, size_t capacity, 174 const CxAllocator *allocator, int flags); 175 176 /** 177 * Destroys the buffer contents. 178 * 179 * Has no effect if the #CX_BUFFER_FREE_CONTENTS feature is not enabled. 180 * If you want to free the memory of the entire buffer, use cxBufferFree(). 181 * 182 * @param buffer the buffer which contents shall be destroyed 183 * @see cxBufferInit() 184 */ 185 cx_attr_nonnull 186 CX_EXPORT void cxBufferDestroy(CxBuffer *buffer); 187 188 /** 189 * Deallocates the buffer. 190 * 191 * If the #CX_BUFFER_FREE_CONTENTS feature is enabled, this function also destroys 192 * the contents. If you @em only want to destroy the contents, use cxBufferDestroy(). 193 * 194 * @param buffer the buffer to deallocate 195 * @see cxBufferCreate() 196 */ 197 CX_EXPORT void cxBufferFree(CxBuffer *buffer); 198 199 /** 200 * Allocates and initializes a fresh buffer. 201 * 202 * You may also provide a read-only @p space, in which case 203 * you will need to cast the pointer, and you should set the 204 * #CX_BUFFER_COPY_ON_WRITE flag. 205 * When you specify stack memory as @p space and decide to use 206 * the auto-extension feature, you @em must use the 207 * #CX_BUFFER_COPY_ON_EXTEND flag, instead of the 208 * #CX_BUFFER_AUTO_EXTEND flag. 209 * 210 * @note You may provide @c NULL as the argument for @p space. 211 * Then this function will allocate the space and enforce 212 * the #CX_BUFFER_FREE_CONTENTS flag. 213 * 214 * @param space pointer to the memory area, or @c NULL to allocate 215 * new memory 216 * @param capacity the capacity of the buffer 217 * @param allocator the allocator to use for allocating the structure and the automatic 218 * memory management within the buffer 219 * (if @c NULL, the cxDefaultAllocator will be used) 220 * @param flags buffer features (see cx_buffer_s.flags) 221 * @return a pointer to the buffer on success, @c NULL if a required allocation failed 222 */ 223 cx_attr_malloc cx_attr_dealloc(cxBufferFree, 1) cx_attr_nodiscard 224 CX_EXPORT CxBuffer *cxBufferCreate(void *space, size_t capacity, 225 const CxAllocator *allocator, int flags); 226 227 /** 228 * Shifts the contents of the buffer by the given offset. 229 * 230 * If the offset is positive, the contents are shifted to the right. 231 * If auto extension is enabled, the buffer grows, if necessary. 232 * In case the auto extension fails, this function returns a non-zero value and 233 * no contents are changed. 234 * When the auto extension is disabled, the contents that do not fit into the 235 * buffer are discarded. 236 * 237 * If the offset is negative, the contents are shifted to the left where the 238 * first @p shift bytes are discarded. 239 * The new size of the buffer is the old size minus the absolute shift value. 240 * If this value is larger than the buffer size, the buffer is emptied (but 241 * not cleared, see the security note below). 242 * 243 * The buffer position gets shifted alongside the content but is kept 244 * within the boundaries of the buffer. 245 * 246 * @note For situations where @c off_t is not large enough, there are specialized cxBufferShiftLeft() and 247 * cxBufferShiftRight() functions using a @c size_t as the parameter type. 248 * 249 * @attention 250 * Security Note: The shifting operation does @em not erase the previously occupied memory cells. 251 * But you can do that manually by calling 252 * <code>memset(buffer->bytes, 0, shift)</code> for a right shift or 253 * <code>memset(buffer->bytes + buffer->size, 0, buffer->capacity - buffer->size)</code> 254 * for a left shift. 255 * 256 * @param buffer the buffer 257 * @param shift the shift offset (negative means left shift) 258 * @retval zero success 259 * @retval non-zero if a required auto-extension or copy-on-write fails 260 * @see cxBufferShiftLeft() 261 * @see cxBufferShiftRight() 262 */ 263 cx_attr_nonnull 264 CX_EXPORT int cxBufferShift(CxBuffer *buffer, off_t shift); 265 266 /** 267 * Shifts the buffer to the right. 268 * See cxBufferShift() for details. 269 * 270 * @param buffer the buffer 271 * @param shift the shift offset 272 * @retval zero success 273 * @retval non-zero if a required auto-extension or copy-on-write fails 274 * @see cxBufferShift() 275 */ 276 cx_attr_nonnull 277 CX_EXPORT int cxBufferShiftRight(CxBuffer *buffer, size_t shift); 278 279 /** 280 * Shifts the buffer to the left. 281 * See cxBufferShift() for details. 282 * 283 * @param buffer the buffer 284 * @param shift the positive shift offset 285 * @retval zero success 286 * @retval non-zero if the buffer uses copy-on-write and the allocation fails 287 * @see cxBufferShift() 288 */ 289 cx_attr_nonnull 290 CX_EXPORT int cxBufferShiftLeft(CxBuffer *buffer, size_t shift); 291 292 293 /** 294 * Moves the position of the buffer. 295 * 296 * The new position is relative to the @p whence argument. 297 * 298 * @li @c SEEK_SET marks the start of the buffer. 299 * @li @c SEEK_CUR marks the current position. 300 * @li @c SEEK_END marks the end of the buffer. 301 * 302 * With an offset of zero, this function sets the buffer position to zero 303 * (@c SEEK_SET), the buffer size (@c SEEK_END) or leaves the buffer position 304 * unchanged (@c SEEK_CUR). 305 * 306 * @param buffer the buffer 307 * @param offset position offset relative to @p whence 308 * @param whence one of @c SEEK_SET, @c SEEK_CUR or @c SEEK_END 309 * @retval zero success 310 * @retval non-zero if the position is invalid 311 * 312 */ 313 cx_attr_nonnull 314 CX_EXPORT int cxBufferSeek(CxBuffer *buffer, off_t offset, int whence); 315 316 /** 317 * Discards items from the end of the buffer. 318 * 319 * When the current position points to a byte that gets discarded, 320 * the position is set to the buffer size. 321 * 322 * @param buffer the buffer 323 * @param size the size of one item 324 * @param nitems the number of items to discard 325 * @return the actual number of discarded items 326 */ 327 cx_attr_nonnull 328 CX_EXPORT size_t cxBufferPop(CxBuffer *buffer, size_t size, size_t nitems); 329 330 /** 331 * Clears the buffer by resetting the position and deleting the data. 332 * 333 * The data is deleted by zeroing it with a call to memset(). 334 * If you do not need that, you can use the faster cxBufferReset(). 335 * 336 * @note If the #CX_BUFFER_COPY_ON_WRITE flag is set, this function 337 * will not erase the data and behave exactly as cxBufferReset(). 338 * 339 * @param buffer the buffer to be cleared 340 * @see cxBufferReset() 341 */ 342 cx_attr_nonnull 343 CX_EXPORT void cxBufferClear(CxBuffer *buffer); 344 345 /** 346 * Resets the buffer by resetting the position and size to zero. 347 * 348 * The data in the buffer is not deleted. If you need a safe 349 * reset of the buffer, use cxBufferClear(). 350 * 351 * @param buffer the buffer to be cleared 352 * @see cxBufferClear() 353 */ 354 cx_attr_nonnull 355 CX_EXPORT void cxBufferReset(CxBuffer *buffer); 356 357 /** 358 * Tests, if the buffer position has exceeded the buffer size. 359 * 360 * @param buffer the buffer to test 361 * @retval true if the current buffer position has exceeded the last 362 * byte of the buffer's contents 363 * @retval false otherwise 364 */ 365 cx_attr_nonnull cx_attr_nodiscard 366 CX_EXPORT bool cxBufferEof(const CxBuffer *buffer); 367 368 /** 369 * Ensures that the buffer has the required capacity. 370 * 371 * If the current capacity is not sufficient, the buffer will be extended. 372 * If the current capacity is larger, the buffer is shrunk and superfluous 373 * content is discarded. 374 * 375 * This function will reserve no more bytes than requested, in contrast to 376 * cxBufferMinimumCapacity(), which may reserve more bytes to improve the 377 * number of future necessary reallocations. 378 * 379 * @param buffer the buffer 380 * @param capacity the required capacity for this buffer 381 * @retval zero on success 382 * @retval non-zero on allocation failure 383 * @see cxBufferShrink() 384 * @see cxBufferMinimumCapacity() 385 */ 386 cx_attr_nonnull 387 CX_EXPORT int cxBufferReserve(CxBuffer *buffer, size_t capacity); 388 389 /** 390 * Limits the buffer's capacity. 391 * 392 * If the current capacity is already larger, this function fails and returns 393 * non-zero. 394 * 395 * The capacity limit will affect auto-extension features, as well as future 396 * calls to cxBufferMinimumCapacity() and cxBufferReserve(). 397 * 398 * @param buffer the buffer 399 * @param capacity the maximum allowed capacity for this buffer 400 * @retval zero the limit is applied 401 * @retval non-zero the new limit is smaller than the current capacity 402 * @see cxBufferReserve() 403 * @see cxBufferMinimumCapacity() 404 */ 405 cx_attr_nonnull 406 CX_EXPORT int cxBufferMaximumCapacity(CxBuffer *buffer, size_t capacity); 407 408 /** 409 * Ensures that the buffer has a minimum capacity. 410 * 411 * If the current capacity is not sufficient, the buffer will be generously 412 * extended. 413 * 414 * The new capacity will be a power of two until the system's page size is reached. 415 * Then, the new capacity will be a multiple of the page size. 416 * 417 * @param buffer the buffer 418 * @param capacity the minimum required capacity for this buffer 419 * @retval zero the capacity was already sufficient or successfully increased 420 * @retval non-zero on allocation failure 421 * @see cxBufferMaximumCapacity() 422 * @see cxBufferReserve() 423 * @see cxBufferShrink() 424 */ 425 cx_attr_nonnull 426 CX_EXPORT int cxBufferMinimumCapacity(CxBuffer *buffer, size_t capacity); 427 428 /** 429 * Shrinks the capacity of the buffer to fit its current size. 430 * 431 * If @p reserve is larger than zero, the buffer is shrunk to its size plus 432 * the number of reserved bytes. 433 * 434 * If the current capacity is not larger than the size plus the reserved bytes, 435 * nothing happens. 436 * 437 * If the #CX_BUFFER_COPY_ON_WRITE or #CX_BUFFER_COPY_ON_EXTEND flag is set, 438 * this function does nothing. 439 * 440 * @param buffer the buffer 441 * @param reserve the number of bytes that shall remain reserved 442 * @see cxBufferReserve() 443 * @see cxBufferMinimumCapacity() 444 */ 445 cx_attr_nonnull 446 CX_EXPORT void cxBufferShrink(CxBuffer *buffer, size_t reserve); 447 448 /** 449 * Writes data to a CxBuffer. 450 * 451 * If auto-extension is enabled, the buffer's capacity is automatically 452 * increased when it is not large enough to hold all data. 453 * By default, the capacity grows indefinitely, unless limited with 454 * cxBufferMaximumCapacity(). 455 * When auto-extension fails, this function writes no data and returns zero. 456 * 457 * The position of the buffer is moved alongside the written data. 458 * 459 * @note The signature is compatible with the fwrite() family of functions. 460 * 461 * @param ptr a pointer to the memory area containing the bytes to be written 462 * @param size the length of one element 463 * @param nitems the element count 464 * @param buffer the CxBuffer to write to 465 * @return the total count of elements written 466 * @see cxBufferAppend() 467 * @see cxBufferRead() 468 */ 469 cx_attr_nonnull 470 CX_EXPORT size_t cxBufferWrite(const void *ptr, size_t size, 471 size_t nitems, CxBuffer *buffer); 472 473 /** 474 * Appends data to a CxBuffer. 475 * 476 * The data is always appended to current data within the buffer, 477 * regardless of the current position. 478 * This is especially useful when the buffer is primarily meant for reading 479 * while additional data is added to the buffer occasionally. 480 * Consequently, the position of the buffer is unchanged after this operation. 481 * 482 * @note The signature is compatible with the fwrite() family of functions. 483 * 484 * @param ptr a pointer to the memory area containing the bytes to be written 485 * @param size the length of one element 486 * @param nitems the element count 487 * @param buffer the CxBuffer to write to 488 * @return the total count of elements written 489 * @see cxBufferWrite() 490 * @see cxBufferRead() 491 */ 492 cx_attr_nonnull 493 CX_EXPORT size_t cxBufferAppend(const void *ptr, size_t size, 494 size_t nitems, CxBuffer *buffer); 495 496 /** 497 * Reads data from a CxBuffer. 498 * 499 * The position of the buffer is increased by the number of bytes read. 500 * 501 * @note The signature is compatible with the fread() family of functions. 502 * 503 * @param ptr a pointer to the memory area where to store the read data 504 * @param size the length of one element 505 * @param nitems the element count 506 * @param buffer the CxBuffer to read from 507 * @return the total number of elements read 508 * @see cxBufferWrite() 509 * @see cxBufferAppend() 510 */ 511 cx_attr_nonnull 512 CX_EXPORT size_t cxBufferRead(void *ptr, size_t size, 513 size_t nitems, CxBuffer *buffer); 514 515 /** 516 * Writes a character to a buffer. 517 * 518 * The least significant byte of the argument is written to the buffer. If the 519 * end of the buffer is reached and #CX_BUFFER_AUTO_EXTEND feature is enabled, 520 * the buffer capacity is extended, unless a limit set by 521 * cxBufferMaximumCapacity() is reached. 522 * If the feature is disabled or the buffer extension fails, @c EOF is returned. 523 * 524 * On successful writing, the position of the buffer is increased. 525 * 526 * If you just want to write a null-terminator at the current position, you 527 * should use cxBufferTerminate() instead. 528 * 529 * @param buffer the buffer to write to 530 * @param c the character to write 531 * @return the byte that has been written or @c EOF when the end of the 532 * stream is reached, and automatic extension is not enabled or not possible 533 * @see cxBufferTerminate() 534 */ 535 cx_attr_nonnull 536 CX_EXPORT int cxBufferPut(CxBuffer *buffer, int c); 537 538 /** 539 * Writes a terminating zero to a buffer at the current position. 540 * 541 * If successful, sets the size to the current position and advances 542 * the position by one. 543 * 544 * The purpose of this function is to have the written data ready to be used as 545 * a C string with the buffer's size being the length of that string. 546 * 547 * @param buffer the buffer to write to 548 * @return zero, if the terminator could be written, non-zero otherwise 549 */ 550 cx_attr_nonnull 551 CX_EXPORT int cxBufferTerminate(CxBuffer *buffer); 552 553 /** 554 * Writes a string to a buffer. 555 * 556 * This is a convenience function for <code>cxBufferWrite(str, 1, strlen(str), buffer)</code>. 557 * 558 * @param buffer the buffer 559 * @param str the zero-terminated string 560 * @return the number of bytes written 561 */ 562 cx_attr_nonnull cx_attr_cstr_arg(2) 563 CX_EXPORT size_t cxBufferPutString(CxBuffer *buffer, const char *str); 564 565 /** 566 * Gets a character from a buffer. 567 * 568 * The current position of the buffer is increased after a successful read. 569 * 570 * @param buffer the buffer to read from 571 * @return the character or @c EOF, if the end of the buffer is reached 572 */ 573 cx_attr_nonnull 574 CX_EXPORT int cxBufferGet(CxBuffer *buffer); 575 576 #ifdef __cplusplus 577 } 578 #endif 579 580 #endif // UCX_BUFFER_H 581