2 Copyright (C) 2003, 2010 - Wolfire Games
4 This file is part of Lugaru.
6 Lugaru is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 Lugaru is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Lugaru. If not, see <http://www.gnu.org/licenses/>.
25 struct BinIOUnpackContext {
30 static void BinIOUnpack(void *context, int type, int byte_order, int count)
32 struct BinIOUnpackContext *ctx = (struct BinIOUnpackContext*)context;
38 case BinIO_TYPE_IGNORE_BYTE:
39 ctx->data += 1 * count;
42 BinIOConvert1(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
43 ctx->data += 1 * count;
45 case BinIO_TYPE_INT16:
46 BinIOConvert2(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
47 ctx->data += 2 * count;
49 case BinIO_TYPE_INT32:
50 BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
51 ctx->data += 4 * count;
53 case BinIO_TYPE_INT64:
54 BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
55 ctx->data += 8 * count;
57 case BinIO_TYPE_FLOAT32:
58 BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
59 ctx->data += 4 * count;
61 case BinIO_TYPE_FLOAT64:
62 BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count);
63 ctx->data += 8 * count;
68 void unpackf(const char *format, ...)
71 va_start(args, format);
72 vfunpackf(stdin, format, args);
76 void sunpackf(const void *buffer, const char *format, ...)
79 va_start(args, format);
80 vsunpackf(buffer, format, args);
84 void funpackf(FILE *file, const char *format, ...)
87 va_start(args, format);
88 vfunpackf(file, format, args);
92 void vsunpackf(const void *buffer, const char *format, va_list args)
94 struct BinIOFormatCursor cursor;
95 struct BinIOUnpackContext context;
97 BinIOInitFormatCursor(&cursor, format);
99 context.data = (const unsigned char*)buffer;
100 va_copy(context.args, args);
102 while (BinIONextChar(&context, &cursor, BinIOUnpack)) {}
104 va_end(context.args);
107 void vfunpackf(FILE *file, const char *format, va_list args)
109 size_t n_bytes = BinIOFormatByteCount(format);
110 void* buffer = malloc(n_bytes);
111 fread(buffer, n_bytes, 1, file);
113 vsunpackf(buffer, format, args);