-
Notifications
You must be signed in to change notification settings - Fork 0
/
var_print.c
156 lines (131 loc) · 2.41 KB
/
var_print.c
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#include <stdio.h>
#include <stdint.h>
#include "log.h"
#include "str.h"
#include "octstr.h"
#include "mpl.h"
#include "variable.h"
#include "var_print.h"
#define BUF_SZ 1024
int
str_append_int(str_t *dst, struct variable *src)
{
mpl_int *tmp;
//FIXME: fixed bufsz?
char buf[BUF_SZ];
int ret;
tmp = var_cast_to_bignum(src);
ret = mpl_to_str(tmp, buf, 10, BUF_SZ);
if (ret != MPL_OK) {
DEBUG(LOG_DEFAULT, "mpl_to_str convertion error\n");
return -1;
}
str_append(dst, buf);
return 0;
}
int
str_append_hex(str_t *dst, struct variable *src)
{
octstr_t *tmp;
char buf[5];
unsigned char *s;
int i, n;
tmp = var_cast_to_octstr(src);
n = octstr_len(tmp);
s = octstr_ptr(tmp);
for (i = 0; i < n; i++) {
snprintf(buf, sizeof(buf), "\\x%2.2X", s[i]);
str_append(dst, buf);
}
return 0;
}
int
str_append_s(str_t *dst, struct variable *src)
{
str_t *tmp;
tmp = var_cast_to_str(src);
str_append_str(dst, tmp);
return 0;
}
int
var_str_print_formatted(struct variable *dst, struct variable *fmt, struct variable **args, int nargs)
{
str_t *str;
str_t *d;
char *s;
d = var_str_ptr(dst);
str_reset(d);
str = var_cast_to_str(fmt);
s = str_ptr(str);
for (; *s != '\0'; s++) {
if (*s == '\\') {
s++;
switch (*s) {
case 't':
str_putc(d, '\t');
break;
case 'n':
str_putc(d, '\n');
break;
case 'r':
str_putc(d, '\r');
break;
default:
str_putc(d, *s);
break;
}
} else if (*s == '%') {
if (nargs <= 0) {
DEBUG(LOG_VERBOSE, "to few arguments");
str_putc(d, *s);
continue;
}
s++;
switch(*s) {
case 'd':
str_append_int(d, *args);
break;
case 'x':
str_append_hex(d, *args);
break;
case 's':
str_append_s(d, *args);
break;
case '%':
str_putc(d, '%');
break;
default:
DEBUG(LOG_DEFAULT, "unknown qualifier\n");
str_putc(d, *s);
break;
}
args++;
nargs--;
} else {
str_putc(d, *s);
}
}
if (nargs != 0)
DEBUG(LOG_DEFAULT, "to many arguments\n");
var_force_type(dst, VAR_STRING);
return 0;
}
int
var_print_formatted(struct variable *fmt, struct variable **args, int nargs)
{
struct variable var;
int n;
var_init(&var);
n = var_str_print_formatted(&var, fmt, args, nargs);
if (n == 0) {
str_t *str;
char *s;
str = var_str_ptr(&var);
s = str_ptr(str);
printf("%s", s);
} else {
DEBUG(LOG_DEFAULT, "print formatted err\n");
}
var_clear(&var);
return n;
}