diff options
| author | Alejandro Colomar <alx@nginx.com> | 2022-10-25 18:42:52 +0200 |
|---|---|---|
| committer | Alejandro Colomar <alx@nginx.com> | 2022-11-16 13:09:18 +0100 |
| commit | a0c0126b3b616fb2a0cf252c51300455f7899ba3 (patch) | |
| tree | b12f379ba94a9358f83f474e40b50573c810e75d /src/nxt_string.c | |
| parent | 270f45d5c737d0f62978bdfec1803677d0f3e6c1 (diff) | |
| download | unit-a0c0126b3b616fb2a0cf252c51300455f7899ba3.tar.gz unit-a0c0126b3b616fb2a0cf252c51300455f7899ba3.tar.bz2 | |
Added nxt_ustr2str() to make C strings from fixed-width buffers.
This function makes it easy to transform a fixed-width buffer
(which is how we represent strings in Unit most of the time) into
a proper C string (NUL-terminated). We need to do this when
interfacing libraries or the kernel, where most APIs expect
NUL-terminated strings.
The implementation is similar to strncpy_s(3), but avoids the
unnecessary runtime checks. It's better to wrap the function in a
macro and do as many static_assert(3)s as one considers necessary;
in fact, if in the future C allows backwards VLA syntax, static
analysis could be better than those static_assert(3)s.
We use char for NUL-terminated strings, and u_char for the
*u*nterminated strings.
The documentation for the function:
/*
* SYNOPSIS
* void ustr2str(char dst[restrict .n+1],
* const u_char src[restrict .n],
* size_t n);
*
* ARGUMENTS
* dst Pointer to the first byte of the destination buffer.
* src Pointer to the first byte of the source string.
* n Size of 'src'.
*
* DESCRIPTION
* Copy a string from the fixed-width source string, which may be
* not-NUL-terminated, into a NUL-terminated string in the
* destination buffer.
*
* CAVEATS
* If the destination buffer is not wider than the source buffer
* at least by 1 byte, the behavior is undefined.
*
* Use of this function normally indicates a problem in the design
* of the strings, since normally it's better to guarantee that all
* strings are properly terminated. The main use for this function
* is to interface with some standard buffers, such as those
* defined in utmp(7), which for historical reasons are not
* guaranteed to be terminated.
*
* EXAMPLES
* u_char src[10] = "0123456789"; // not NUL-terminated
* char dst[sizeof(src) + 1];
*
* static_assert(lengthof(src) < lengthof(dst))
* ustr2str(dst, src, lengthof(src));
*
* SEE ALSO
* nxt_sts2str(3), strlcpy(3), strscpy(9)
*/
Cc: Andrew Clayton <a.clayton@nginx.com>
Signed-off-by: Alejandro Colomar <alx@nginx.com>
Diffstat (limited to 'src/nxt_string.c')
| -rw-r--r-- | src/nxt_string.c | 4 |
1 files changed, 4 insertions, 0 deletions
diff --git a/src/nxt_string.c b/src/nxt_string.c index 1ca595a1..39f472e9 100644 --- a/src/nxt_string.c +++ b/src/nxt_string.c @@ -7,6 +7,10 @@ #include <nxt_main.h> +extern inline void nxt_ustr2str(char *restrict dst, const u_char *restrict src, + size_t length); + + nxt_str_t * nxt_str_alloc(nxt_mp_t *mp, size_t length) { |
