Fix endianess problems
[hex-a-hop.git] / packfile.h
blob50838b939579496dcd198ca0eb670ee70877d81f
1 /*
2 Copyright (C) 2005-2007 Tom Beaumont
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include <stdint.h>
20 #include <SDL/SDL_endian.h>
22 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
23 #define SWAP16(X) (X)
24 #define SWAP32(X) (X)
25 #else
26 #define SWAP16(X) SDL_Swap16(X)
27 #define SWAP32(X) SDL_Swap32(X)
28 #endif
30 struct PackFile1
32 class Entry {
33 int32_t len;
34 public:
35 char name[1];
37 Entry* GetNext()
39 return (Entry*)((char*)name + len);
42 void* Data()
44 char* pos = name;
45 while (*pos!=0)
46 pos++;
47 return pos+1;
50 int DataLen()
52 return len - strlen(name) - 1;
56 int numfiles;
57 Entry** e;
58 void* data;
60 PackFile1() : e(0), data(0), numfiles(0)
63 Entry* Find(const char* name)
65 if (numfiles==0) return 0;
66 int a=0, b=numfiles;
67 while (b>a)
69 const int mid = (a+b)>>1;
70 int diff = strcmp(name, e[mid]->name);
71 if (diff==0)
72 return e[mid];
73 else if (diff < 0)
74 b=mid;
75 else
76 a=mid+1;
78 return 0;
81 void Read(FILE* f)
83 if (numfiles || e || data)
84 FATAL("Calling Packfile1::Read when already initialised.");
86 int32_t size;
87 fseek(f, -(int)sizeof(size), SEEK_END);
88 int end_offset = ftell(f);
89 fread(&size, sizeof(size), 1, f);
90 size = SWAP32(size);
91 fseek(f, end_offset - size, SEEK_SET);
93 data = malloc(size);
94 char* data_end = (char*)data + size;
95 fread(data, 1, size, f);
97 numfiles=0;
98 Entry* i = (Entry*)data;
99 while ((void*)i < data_end)
101 numfiles++;
102 int32_t *data_length = (int32_t*)i;
103 *data_length = SWAP32(*data_length);
104 i = i->GetNext();
107 e = new Entry* [numfiles]; // CHECKME: where to delete?
109 i = (Entry*)data;
110 for (int j=0; j<numfiles; j++, i = i->GetNext())
111 e[j] = i;
114 ~PackFile1()
116 free(data);