2 Copyright (C) 2003, 2010 - Wolfire Games
3 Copyright (C) 2010-2016 - Lugaru contributors (see AUTHORS file)
5 This file is part of Lugaru.
7 Lugaru is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 Lugaru is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Lugaru. If not, see <http://www.gnu.org/licenses/>.
26 struct BinIOUnpackContext {
31 static void BinIOUnpack(void *context, int type, int byte_order, int count)
33 struct BinIOUnpackContext *ctx = (struct BinIOUnpackContext*)context;
39 case BinIO_TYPE_IGNORE_BYTE:
40 ctx->data += 1 * count;
43 BinIOConvert1(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
44 ctx->data += 1 * count;
46 case BinIO_TYPE_INT16:
47 BinIOConvert2(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
48 ctx->data += 2 * count;
50 case BinIO_TYPE_INT32:
51 BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
52 ctx->data += 4 * count;
54 case BinIO_TYPE_INT64:
55 BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
56 ctx->data += 8 * count;
58 case BinIO_TYPE_FLOAT32:
59 BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
60 ctx->data += 4 * count;
62 case BinIO_TYPE_FLOAT64:
63 BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
64 ctx->data += 8 * count;
69 void unpackf(const char *format, ...)
72 va_start(args, format);
73 vfunpackf(stdin, format, args);
77 void sunpackf(const void *buffer, const char *format, ...)
80 va_start(args, format);
81 vsunpackf(buffer, format, args);
85 void funpackf(FILE *file, const char *format, ...)
88 va_start(args, format);
89 vfunpackf(file, format, args);
93 void vsunpackf(const void *buffer, const char *format, va_list args)
95 struct BinIOFormatCursor cursor;
96 struct BinIOUnpackContext context;
98 BinIOInitFormatCursor(&cursor, format);
100 context.data = (const unsigned char*)buffer;
101 va_copy(context.args, args);
103 while (BinIONextChar(&context, &cursor, BinIOUnpack)) {}
105 va_end(context.args);
108 void vfunpackf(FILE *file, const char *format, va_list args)
110 size_t n_bytes = BinIOFormatByteCount(format);
111 void* buffer = malloc(n_bytes);
112 fread(buffer, n_bytes, 1, file);
114 vsunpackf(buffer, format, args);