summaryrefslogtreecommitdiff
path: root/assorted/pack.c
blob: 9eec65e2f1a4e54d1578465ad02830c0ddf469b1 (plain)
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
/*
 *	libHX/assorted/pack.c
 *	Copyright Jan Engelhardt, 1999-2005
 *
 *	This file is part of libHX. libHX is free software; you can
 *	redistribute it and/or modify it under the terms of the GNU Lesser
 *	General Public License as published by the Free Software Foundation;
 *	either version 2.1 or (at your option) any later version.
 */
#include <sys/types.h>
#include <stdarg.h>
#include <stdint.h>
#include <string.h>

size_t HX_pack(char *buf, size_t buflen, const char *fmt, ...)
{
	char *obp = buf;
	int run = 1;
	va_list ap;
	va_start(ap, fmt);

	while (run && *fmt != '\0') {
		switch (*fmt++) {
		case 'A': /* string with up to 255 chars */
		case 'a': {
			const char *src = va_arg(ap, const char *);
			size_t slen = strlen(src) & 0xFF;
			if (buflen < slen + 1) {
				run = 0;
				break;
			}
			*buf++ = slen;
			memcpy(buf, src, slen);
			buf    += slen;
			buflen -= slen + 1;
			break;
		}
		case 'C': /* unsigned char */
		case 'c':
			if (buflen-- < 1) {
				run = 0;
				break;
			}
			/*
			 * Minimum object's size being pushed on the stack is 2
			 * bytes since short int is promoted to int when passed
			 * thru va_arg and stays uncasted. (FIXME)
			 */
			*buf++ = va_arg(ap, unsigned int);
			break;
		case 'H': /* unsigned short */
		case 'h':
			if (buflen < sizeof(uint16_t)) {
				run = 0;
				break;
			}
			*((uint16_t *)buf) = va_arg(ap, uint16_t);
			buf    += sizeof(uint16_t);
			buflen -= sizeof(uint16_t);
			break;
		case 'L': /* unsigned long */
		case 'l':
			if (buflen < sizeof(uint32_t)) {
				run = 0;
				break;
			}
			*((uint32_t *)buf) = va_arg(ap, uint32_t);
			buf    += sizeof(uint32_t);
			buflen -= sizeof(uint32_t);
			break;
		case 'S': /* string with up to 65535 chars */
		case 's': {
			const char *src = va_arg(ap, const char *);
			size_t slen = strlen(src) & 0xFFFF;
			if (buflen < slen + 2) {
				run = 0;
				break;
			}
			*((unsigned short *)buf) = slen;
			memcpy(buf += 2, src, slen);
			buf    += slen;
			buflen -= slen + 2;
			break;
		}
		case 'V': /* fixed size string */
		case 'v': {
			void *src = va_arg(ap, void *);
			size_t slen = va_arg(ap, size_t);
			if (buflen < slen) {
				run = 0;
				break;
			}
			memcpy(buf, src, slen);
			buf    += slen;
			buflen -= slen;
			break;
		}
		} /* switch */
	}

	va_end(ap);
	return buf - obp;
}