Midas C++ API - utility functions
This page describes small utility functions in the midas library: safe string copying (mstrlcpy.h) and CRC-32C checksums (crc32c.h). Both headers are installed in $MIDASSYS/include, and the functions are in the midas library, so any program linked with midas can use them.
Safe string copying
#include "mstrlcpy.h"
size_t mstrlcpy(char *dst, const char *src, size_t size);
size_t mstrlcat(char *dst, const char *src, size_t size);
Versions of strcpy() and strcat() that can't write past the end of dst. They work like the BSD functions strlcpy() and strlcat(), which midas used to provide and which are no longer available.
| Function | Description |
|---|---|
mstrlcpy() |
Copies src to dst, where size is the size of dst in bytes. At most size - 1 characters are copied, and dst always ends with a NUL (unless size is 0). Returns the length of src. |
mstrlcat() |
Adds src to the end of the string in dst. Unlike strncat(), size is the full size of dst, not the space left in it. dst always ends with a NUL (unless size is no more than the length of the string already in dst). Returns the length of src plus the length of the string that was in dst (or size, if that's smaller). |
If the return value is size or more, the result was cut short to fit in dst:
char name[32];
if (mstrlcpy(name, long_name, sizeof(name)) >= sizeof(name))
cm_msg(MERROR, "my_function", "Name \"%s\" is too long", long_name);
CRC-32C checksums
#include "crc32c.h"
uint32_t crc32c(uint32_t crc, const void *buf, size_t len);
uint32_t crc32c_sw(uint32_t crc, const void *buf, size_t len);
uint32_t crc32c_hw(uint32_t crc, const void *buf, size_t len);
Compute the CRC-32C (Castagnoli) checksum of len bytes at buf. Start with crc set to 0. To checksum data that comes in pieces, pass the result for the previous pieces as crc:
uint32_t crc = 0;
crc = crc32c(crc, part1, size1);
crc = crc32c(crc, part2, size2); // now the checksum of part1 followed by part2
| Function | Description |
|---|---|
crc32c() |
Uses the processor's CRC-32C instruction if it has one (SSE 4.2 on x86-64, or the CRC extension on ARM64), and otherwise crc32c_sw(). Use this one. |
crc32c_sw() |
Always uses the software version, which is about 15 times slower than the hardware instruction. |
crc32c_hw() |
Always uses the hardware instruction. Calls abort() if midas was built without it, so only use it if you know the processor supports it. |
The crc32c_sum test program prints the checksum of its standard input.