summaryrefslogtreecommitdiffstats
path: root/include/c/str/cpy/stp/stpe/ustr2stpe.h
blob: 87c2065cf91fd6dffa787f7cae7d381d1b095fb8 (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
// Copyright 2023 Alejandro Colomar <alx@kernel.org>
// SPDX-License-Identifier:  LGPL-3.0-or-later WITH LGPL-3.0-linking-exception


#ifndef INCLUDE_C_STR_CPY_STP_STPE_USTR2STPE_H_
#define INCLUDE_C_STR_CPY_STP_STPE_USTR2STPE_H_


#include <stdbool.h>
#include <stddef.h>
#include <sys/param.h>

#include <c/branch/likely.h>
#include <c/branch/unreachable.h>
#include <c/mem/cpy/mempcpy.h>
#include <c/qual/nullable/nullable.h>
#include <c/str/len/strlen.h>


#pragma clang assume_nonnull begin
inline char *c_nullable c_ustr2stpe(char *c_nullable dst, char *end,
    const char *restrict src, size_t slen);


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

	if (dst == end)
		return end;
	if (c_unlikely(dst == NULL))  // Allow chaining with stpeprintf().
		return NULL;
	c_impossible(dst > end);

	dsize = end - dst;
	trunc = (slen > dsize - 1);
	dlen = MIN(slen, dsize - 1);
	dst[dlen] = '\0';

	return c_mempcpy(dst, src, dlen) + trunc;
}
#pragma clang assume_nonnull end


#endif  // Header guard