The open source OpenXR runtime
1/** @file
2 @brief Header providing C++-enhanced versions of the various string
3 functions that work on fixed-length buffers, inspired by
4 https://randomascii.wordpress.com/2013/04/03/stop-using-strncpy-already/
5
6 @date 2015
7
8 This header is maintained as a part of 'util-headers' - you can always
9 find the latest version online at https://github.com/rpavlik/util-headers
10
11 This GUID can help identify the project: d1dbc94e-e863-49cf-bc08-ab4d9f486613
12
13 This copy of the header is from the revision that Git calls
14 1a8444782d15cb9458052e3d8251c4f5b8e808d5
15
16 Commit date: "2022-03-11 12:11:32 -0600"
17
18 @author
19 Sensics, Inc.
20 <http://sensics.com/osvr>
21*/
22
23// Copyright 2015, Sensics, Inc.
24// Copyright 2022, Collabora, Ltd.
25//
26// SPDX-License-Identifier: BSL-1.0
27//
28// Distributed under the Boost Software License, Version 1.0.
29// (See accompanying file LICENSE_1_0.txt or copy at
30// http://www.boost.org/LICENSE_1_0.txt)
31
32#ifndef INCLUDED_FixedLengthStringFunctions_h_GUID_34010E53_D3F3_42BD_FB36_6D00EA79C3A9
33#define INCLUDED_FixedLengthStringFunctions_h_GUID_34010E53_D3F3_42BD_FB36_6D00EA79C3A9
34
35// Internal Includes
36// - none
37
38// Library/third-party includes
39// - none
40
41// Standard includes
42#include <stddef.h>
43#include <stdexcept>
44#include <string.h>
45
46#ifdef _MSC_VER
47#define UTILHEADERS_STR_MSRUNTIME
48#else
49#include <limits.h>
50#ifndef _WIN32
51#include <sys/types.h>
52#endif
53#if defined(__KLIBC__) || defined(__BIONIC__) || \
54 (!defined(__GLIBC__) && defined(_BSD_SOURCE))
55// strlcpy providers:
56// klibc
57// bionic
58// musl if _GNU_SOURCE or _BSD_SOURCE defined (_BSD_SOURCE defined by default) -
59// but not glibc!
60#define UTILHEADERS_STR_STRLCPY
61#elif defined(__DARWIN_C_LEVEL) && defined(__DARWIN_C_FULL) && \
62 (__DARWIN_C_LEVEL >= __DARWIN_C_FULL)
63// Also provided in cases on Darwin
64#define UTILHEADERS_STR_STRLCPY
65#endif
66#endif
67
68namespace util {
69/// @brief Copy a string into a char array, guaranteed to null-terminate and not
70/// overrun. Does not correctly handle UTF-8 (may truncate in the middle of a
71/// codepoint).
72template <size_t N> inline void strcpy_safe(char (&dest)[N], const char *src) {
73#if defined(UTILHEADERS_STR_STRLCPY)
74 strlcpy(dest, src, N);
75#elif defined(UTILHEADERS_STR_MSRUNTIME)
76 strncpy_s(dest, src, _TRUNCATE);
77#else
78 strncpy(dest, src, N);
79 dest[N - 1] = '\0';
80#endif
81}
82} // namespace util
83
84#endif // INCLUDED_FixedLengthStringFunctions_h_GUID_34010E53_D3F3_42BD_FB36_6D00EA79C3A9