blob: 91518bab669d31712970d1e9eb62b64c1aa6375d [file] [log] [blame]
Doug Zongker9270a202012-01-09 15:16:13 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include "utils.h"
17#include <stdarg.h>
18#include <stdio.h>
19#include <string.h>
20
21char*
22buff_addc (char* buff, char* buffEnd, int c)
23{
24 int avail = buffEnd - buff;
25
26 if (avail <= 0) /* already in overflow mode */
27 return buff;
28
29 if (avail == 1) { /* overflowing, the last byte is reserved for zero */
30 buff[0] = 0;
31 return buff + 1;
32 }
33
34 buff[0] = (char) c; /* add char and terminating zero */
35 buff[1] = 0;
36 return buff + 1;
37}
38
39char*
40buff_adds (char* buff, char* buffEnd, const char* s)
41{
42 int slen = strlen(s);
43
44 return buff_addb(buff, buffEnd, s, slen);
45}
46
47char*
48buff_addb (char* buff, char* buffEnd, const void* data, int len)
49{
50 int avail = (buffEnd - buff);
51
52 if (avail <= 0 || len <= 0) /* already overflowing */
53 return buff;
54
55 if (len > avail)
56 len = avail;
57
58 memcpy(buff, data, len);
59
60 buff += len;
61
62 /* ensure there is a terminating zero */
63 if (buff >= buffEnd) { /* overflow */
64 buff[-1] = 0;
65 } else
66 buff[0] = 0;
67
68 return buff;
69}
70
71char*
72buff_add (char* buff, char* buffEnd, const char* format, ... )
73{
74 int avail;
75
76 avail = (buffEnd - buff);
77
78 if (avail > 0) {
79 va_list args;
80 int nn;
81
82 va_start(args, format);
83 nn = vsnprintf( buff, avail, format, args);
84 va_end(args);
85
86 if (nn < 0) {
87 /* some C libraries return -1 in case of overflow,
88 * but they will also do that if the format spec is
89 * invalid. We assume ADB is not buggy enough to
90 * trigger that last case. */
91 nn = avail;
92 }
93 else if (nn > avail) {
94 nn = avail;
95 }
96
97 buff += nn;
98
99 /* ensure that there is a terminating zero */
100 if (buff >= buffEnd)
101 buff[-1] = 0;
102 else
103 buff[0] = 0;
104 }
105 return buff;
106}