-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathsafe_snprintf.cpp
More file actions
74 lines (58 loc) · 1.58 KB
/
Copy pathsafe_snprintf.cpp
File metadata and controls
74 lines (58 loc) · 1.58 KB
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
//
// JK_Botti - be more human!
//
// safe_snprintf.cpp
//
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include "safe_snprintf.h"
#include "compiler.h"
// Acts very much like safevoid_snprintf(dst, dst_size, "%s", src)
// if src is null "(null)" is written
// returns dst
char* safe_strcopy(char* dst, size_t dst_size, const char *src)
{
if (unlikely(!dst_size))
return dst;
if (unlikely(!src))
src = "(null)";
#ifdef HAVE_MEMCCPY
// memccpy copies until '\0' found or dst_size-1 bytes copied,
// returns NULL if '\0' was not found within the limit
if (!memccpy(dst, src, '\0', dst_size - 1))
dst[dst_size - 1] = '\0';
#else
{
size_t i;
for (i = 0; likely(i < dst_size - 1) && likely(src[i] != '\0'); i++)
dst[i] = src[i];
dst[i] = '\0';
}
#endif
return dst;
}
void safevoid_vsnprintf(char* s, size_t n, const char *format, va_list ap)
{
int res;
if (unlikely(!s) || unlikely(!n))
return;
// If the format string is empty, nothing to do.
if (unlikely(!format) || unlikely(!*format))
{
s[0] = 0;
return;
}
res = vsnprintf(s, n, format, ap);
// w32api returns -1 on too long write, glibc returns number of bytes it could have written if there were enough space
// w32api doesn't write null at all, some buggy glibc don't either
if (unlikely(res < 0) || unlikely((size_t)res >= n))
s[n-1] = 0;
}
void safevoid_snprintf(char* s, size_t n, const char* format, ...)
{
va_list ap;
va_start(ap, format);
safevoid_vsnprintf(s, n, format, ap);
va_end(ap);
}