summaryrefslogtreecommitdiffstats
path: root/lib/stpecpy.h
blob: e2c2f47932a972a8be61a588341e4e5b077d16e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
 * SPDX-FileCopyrightText:  2022 - 2023, Alejandro Colomar <alx@kernel.org>
 *
 * SPDX-License-Identifier:  BSD-3-Clause
 */


#ifndef SHADOW_INCLUDE_LIB_STPECPY_H_
#define SHADOW_INCLUDE_LIB_STPECPY_H_


#include <config.h>

#if !defined(HAVE_STPECPY)

#include <stdbool.h>
#include <stddef.h>
#include <string.h>

#include "defines.h"


inline char *stpecpy(char *dst, char *end, const char *restrict src);


/*
 * SYNOPSIS
 *	char *_Nullable stpecpy(char *_Nullable dst, char end[0],
 *	                        const char *restrict src);
 *
 * ARGUMENTS
 *	dst	Destination buffer where to copy a string.
 *
 *	end	Pointer to one after the last element of the buffer
 *		pointed to by `dst`.  Usually, it should be calculated
 *		as `dst + NITEMS(dst)`.
 *
 *	src	Source string to be copied into dst.
 *
 * DESCRIPTION
 *	This function copies the string pointed to by src, into a string
 *	at the buffer pointed to by dst.  If the destination buffer,
 *	limited by a pointer to its end --one after its last element--,
 *	isn't large enough to hold the copy, the resulting string is
 *	truncated.
 *
 *	This function can be chained with calls to [v]stpeprintf().
 *
 * RETURN VALUE
 *	dst + strlen(dst)
 *		•  On success, this function returns a pointer to the
 *		   terminating NUL byte.
 *
 *	end
 *		•  If this call truncated the resulting string.
 *		•  If `dst == end` (a previous chained call to these
 *		   functions truncated).
 *	NULL
 *		•  If `dst == NULL` (a previous chained call to
 *		   [v]stpeprintf() failed).
 *
 * ERRORS
 *	This function doesn't set errno.
 */


inline char *
stpecpy(char *dst, char *end, const char *restrict src)
{
	bool    trunc;
	char    *p;
	size_t  dsize, dlen, slen;

	if (dst == end)
		return end;
	if (dst == NULL)
		return NULL;

	dsize = end - dst;
	slen = strnlen(src, dsize);
	trunc = (slen == dsize);
	dlen = slen - trunc;

	p = mempcpy(dst, src, dlen);
	*p = '\0';

	return p + trunc;
}


#endif  // !HAVE_STPECPY
#endif  // include guard