| 1 | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ |
| 2 | /* If you are missing that file, acquire a complete release at teeworlds.com. */ |
| 3 | |
| 4 | #ifndef BASE_MEM_H |
| 5 | #define BASE_MEM_H |
| 6 | |
| 7 | #include <cstdint> |
| 8 | #include <cstring> |
| 9 | #include <type_traits> |
| 10 | |
| 11 | /** |
| 12 | * Memory management utilities. |
| 13 | * |
| 14 | * @defgroup Memory Memory |
| 15 | */ |
| 16 | |
| 17 | /** |
| 18 | * Copies a memory block. |
| 19 | * |
| 20 | * @ingroup Memory |
| 21 | * |
| 22 | * @param dest Destination. |
| 23 | * @param source Source to copy. |
| 24 | * @param size Size of the block to copy. |
| 25 | * |
| 26 | * @remark This functions DOES NOT handle cases where the source and destination overlap. |
| 27 | * |
| 28 | * @see mem_move |
| 29 | */ |
| 30 | void mem_copy(void *dest, const void *source, size_t size); |
| 31 | |
| 32 | /** |
| 33 | * Copies a memory block. |
| 34 | * |
| 35 | * @ingroup Memory |
| 36 | * |
| 37 | * @param dest Destination. |
| 38 | * @param source Source to copy. |
| 39 | * @param size Size of the block to copy. |
| 40 | * |
| 41 | * @remark This functions handles the cases where the source and destination overlap. |
| 42 | * |
| 43 | * @see mem_copy |
| 44 | */ |
| 45 | void mem_move(void *dest, const void *source, size_t size); |
| 46 | |
| 47 | /** |
| 48 | * Sets a complete memory block to 0. |
| 49 | * |
| 50 | * @ingroup Memory |
| 51 | * |
| 52 | * @param block Pointer to the block to zero out. |
| 53 | * @param size Size of the block. |
| 54 | */ |
| 55 | template<typename T> |
| 56 | inline void mem_zero(T *block, size_t size) |
| 57 | { |
| 58 | static_assert((std::is_trivially_constructible<T>::value && std::is_trivially_destructible<T>::value) || std::is_fundamental<T>::value); |
| 59 | memset(block, 0, size); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Compares two blocks of memory of the same size, lexicographically. |
| 64 | * |
| 65 | * @ingroup Memory |
| 66 | * |
| 67 | * @param a First block of data. |
| 68 | * @param b Second block of data. |
| 69 | * @param size Size of the data to compare. |
| 70 | * |
| 71 | * @return `< 0` if block `a` is less than block `b`. |
| 72 | * @return `0` if block `a` is equal to block `b`. |
| 73 | * @return `> 0` if block `a` is greater than block `b`. |
| 74 | */ |
| 75 | int mem_comp(const void *a, const void *b, size_t size); |
| 76 | |
| 77 | /** |
| 78 | * Checks whether a block of memory contains null bytes. |
| 79 | * |
| 80 | * @ingroup Memory |
| 81 | * |
| 82 | * @param block Pointer to the block to check for nulls. |
| 83 | * @param size Size of the block. |
| 84 | * |
| 85 | * @return `true` if the block has a null byte, `false` otherwise. |
| 86 | */ |
| 87 | bool mem_has_null(const void *block, size_t size); |
| 88 | |
| 89 | #endif |
| 90 | |