-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_fmt.cpp
More file actions
77 lines (60 loc) · 1.19 KB
/
string_fmt.cpp
File metadata and controls
77 lines (60 loc) · 1.19 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
75
76
77
/*
* Copyright (c) 2015, Wing Eng
* All rights reserved.
*/
#include <alloca.h>
#include <stdarg.h>
#include <assert.h>
#include "string_fmt.h"
void string_fmt_c::
vformat (const char *fmt, va_list ap)
{
int buf_sz = 256;
while (1) {
char *buf = (char *) alloca(buf_sz);
va_list apc;
va_copy(apc, ap);
int n = vsnprintf(buf, buf_sz, fmt, apc);
if (n > -1 && n < buf_sz) {
*this = buf;
return;
}
if (n > -1) // Needed size returned
buf_sz = n + 1; // For null char
else {
assert(0);
}
}
}
void string_fmt_c::
format (const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vformat(fmt, ap);
va_end(ap);
}
void string_fmt_c::
append (const char *fmt, ...)
{
string_fmt_c tmp;
va_list ap;
va_start(ap, fmt);
tmp.vformat(fmt, ap);
*this += tmp;
}
#ifdef _TEST
#define TEST(x) if (!(x)) assert(0)
int
main ()
{
string_fmt_c s, s1;
s = "abc";
s1.format("this '%s' is %d\n", "thing", 99);
TEST(s1 == "this 'thing' is 99\n");
s1.append("some %d", 55);
TEST(s1 == "this 'thing' is 99\nsome 55");
printf("all test passed\n");
return 0;
}
#endif