blob: a471d5450af6cf3662d621bd3c1b85657dc438f3 [file] [log] [blame]
Yann Collet71eafdd2016-02-12 02:31:57 +01001/*
2 dibio - I/O API for dictionary builder
3 Copyright (C) Yann Collet 2016
4
5 GPL v2 License
6
7 This program 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.
11
12 This program 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.
16
17 You should have received a copy of the GNU General Public License along
18 with this program; if not, write to the Free Software Foundation, Inc.,
19 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 You can contact the author at :
22 - zstd homepage : http://www.zstd.net/
23*/
24
25/*-**************************************
26* Compiler Options
27****************************************/
28/* Disable some Visual warning messages */
29#ifdef _MSC_VER
30# define _CRT_SECURE_NO_WARNINGS /* fopen */
31# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
32#endif
33
34/* Unix Large Files support (>4GB) */
35#define _FILE_OFFSET_BITS 64
36#if (defined(__sun__) && (!defined(__LP64__))) /* Sun Solaris 32-bits requires specific definitions */
37# define _LARGEFILE_SOURCE
38#elif ! defined(__LP64__) /* No point defining Large file for 64 bit */
39# define _LARGEFILE64_SOURCE
40#endif
41
42
43/*-*************************************
44* Includes
45***************************************/
46#include <stdlib.h> /* malloc, free */
47#include <string.h> /* memset */
48#include <stdio.h> /* fprintf, fopen, ftello64 */
49#include <sys/types.h> /* stat64 */
50#include <sys/stat.h> /* stat64 */
51#include <time.h> /* clock */
52
53#include "mem.h" /* read */
54#include "error_private.h"
55#include "dictBuilder_static.h"
56
57/*-*************************************
58* Compiler specifics
59***************************************/
60#if !defined(S_ISREG)
61# define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
62#endif
63
64
65/*-*************************************
66* Constants
67***************************************/
68#define KB *(1 <<10)
69#define MB *(1 <<20)
70#define GB *(1U<<30)
71
72#define DICTLISTSIZE 10000
73#define MEMMULT 11
74static const size_t maxMemory = (sizeof(size_t) == 4) ? (2 GB - 64 MB) : ((size_t)(512 MB) << sizeof(size_t));
75
76#define NOISELENGTH 32
77#define PRIME1 2654435761U
78#define PRIME2 2246822519U
79
80
81/*-*************************************
82* Console display
83***************************************/
84#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
85#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
86static unsigned g_displayLevel = 0; /* 0 : no display; 1: errors; 2: default; 4: full information */
87void DiB_setNotificationLevel(unsigned l) { g_displayLevel=l; ZDICT_setNotificationLevel(l); }
88
89void DiB_printHex(U32 dlevel, const void* ptr, size_t length)
90{
91 const BYTE* const b = (const BYTE*)ptr;
92 size_t u;
93 for (u=0; u<length; u++) {
94 BYTE c = b[u];
95 if (c<32 || c>126) c = '.'; /* non-printable char */
96 DISPLAYLEVEL(dlevel, "%c", c);
97 }
98}
99
100
101/*-*************************************
102* Exceptions
103***************************************/
104#ifndef DEBUG
105# define DEBUG 0
106#endif
107#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
108#define EXM_THROW(error, ...) \
109{ \
110 DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
111 DISPLAYLEVEL(1, "Error %i : ", error); \
112 DISPLAYLEVEL(1, __VA_ARGS__); \
113 DISPLAYLEVEL(1, "\n"); \
114 exit(error); \
115}
116
117
118/* ********************************************************
119* Helper functions
120**********************************************************/
121unsigned DiB_isError(size_t errorCode) { return ERR_isError(errorCode); }
122
123const char* DiB_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
124
125
126/* ********************************************************
127* File related operations
128**********************************************************/
129static unsigned long long DiB_getFileSize(const char* infilename)
130{
131 int r;
132#if defined(_MSC_VER)
133 struct _stat64 statbuf;
134 r = _stat64(infilename, &statbuf);
135#else
136 struct stat statbuf;
137 r = stat(infilename, &statbuf);
138#endif
139 if (r || !S_ISREG(statbuf.st_mode)) return 0; /* No good... */
140 return (unsigned long long)statbuf.st_size;
141}
142
143
144static unsigned long long DiB_getTotalFileSize(const char** fileNamesTable, unsigned nbFiles)
145{
146 unsigned long long total = 0;
147 unsigned n;
148 for (n=0; n<nbFiles; n++)
149 total += DiB_getFileSize(fileNamesTable[n]);
150 return total;
151}
152
153
154static void DiB_loadFiles(void* buffer, size_t bufferSize,
155 size_t* fileSizes,
156 const char** fileNamesTable, unsigned nbFiles)
157{
158 char* buff = (char*)buffer;
159 size_t pos = 0;
160 unsigned n;
161
162 for (n=0; n<nbFiles; n++) {
163 size_t readSize;
164 unsigned long long fileSize = DiB_getFileSize(fileNamesTable[n]);
165 FILE* f = fopen(fileNamesTable[n], "rb");
166 if (f==NULL) EXM_THROW(10, "impossible to open file %s", fileNamesTable[n]);
167 DISPLAYLEVEL(2, "Loading %s... \r", fileNamesTable[n]);
168 if (fileSize > bufferSize-pos) fileSize = 0; /* stop there, not enough memory to load all files */
169 readSize = fread(buff+pos, 1, (size_t)fileSize, f);
170 if (readSize != (size_t)fileSize) EXM_THROW(11, "could not read %s", fileNamesTable[n]);
171 pos += readSize;
172 fileSizes[n] = (size_t)fileSize;
173 fclose(f);
174 }
175}
176
177
178/*-********************************************************
179* Dictionary training functions
180**********************************************************/
181static size_t DiB_findMaxMem(unsigned long long requiredMem)
182{
183 size_t step = 8 MB;
184 void* testmem = NULL;
185
186 requiredMem = (((requiredMem >> 23) + 1) << 23);
187 requiredMem += 2 * step;
188 if (requiredMem > maxMemory) requiredMem = maxMemory;
189
190 while (!testmem) {
191 requiredMem -= step;
192 testmem = malloc((size_t)requiredMem);
193 }
194
195 free(testmem);
196 return (size_t)(requiredMem - step);
197}
198
199
200static void DiB_fillNoise(void* buffer, size_t length)
201{
202 unsigned acc = PRIME1;
203 size_t p=0;;
204
205 for (p=0; p<length; p++) {
206 acc *= PRIME2;
207 ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
208 }
209}
210
211
212static void DiB_saveDict(const char* dictFileName,
213 const void* buff, size_t buffSize)
214{
215 FILE* f;
216 size_t n;
217
218 f = fopen(dictFileName, "wb");
219 if (f==NULL) EXM_THROW(3, "cannot open %s ", dictFileName);
220
221 n = fwrite(buff, 1, buffSize, f);
222 if (n!=buffSize) EXM_THROW(4, "%s : write error", dictFileName)
223
224 n = (size_t)fclose(f);
225 if (n!=0) EXM_THROW(5, "%s : flush error", dictFileName)
226}
227
228
229int DiB_trainFromFiles(const char* dictFileName, unsigned maxDictSize,
230 const char** fileNamesTable, unsigned nbFiles,
231 ZDICT_params_t params)
232{
233 void* srcBuffer;
234 size_t benchedSize;
235 size_t* fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t));
236 unsigned long long totalSizeToLoad = DiB_getTotalFileSize(fileNamesTable, nbFiles);
237 void* dictBuffer = malloc(maxDictSize);
238 size_t dictSize;
239 int result = 0;
240
241 /* init */
242 benchedSize = DiB_findMaxMem(totalSizeToLoad * MEMMULT) / MEMMULT;
243 if ((unsigned long long)benchedSize > totalSizeToLoad) benchedSize = (size_t)totalSizeToLoad;
244 if (benchedSize < totalSizeToLoad)
245 DISPLAYLEVEL(1, "Not enough memory; training on %u MB only...\n", (unsigned)(benchedSize >> 20));
246
247 /* Memory allocation & restrictions */
248 srcBuffer = malloc(benchedSize+NOISELENGTH); /* + noise */
249 if ((!fileSizes) || (!srcBuffer) || (!dictBuffer)) EXM_THROW(12, "not enough memory for DiB_trainFiles"); /* should not happen */
250
251 /* Load input buffer */
252 DiB_loadFiles(srcBuffer, benchedSize, fileSizes, fileNamesTable, nbFiles);
253 DiB_fillNoise((char*)srcBuffer + benchedSize, NOISELENGTH); /* guard band, for end of buffer condition */
254
255 /* call buffer version */
256 dictSize = ZDICT_trainFromBuffer_unsafe(dictBuffer, maxDictSize,
257 srcBuffer, fileSizes, nbFiles,
258 params);
259 if (ZDICT_isError(dictSize)) {
260 DISPLAYLEVEL(1, "dictionary training failed : %s", ZDICT_getErrorName(dictSize)); /* should not happen */
261 result = 1;
262 goto _cleanup;
263 }
264
265 /* save dict */
266 DISPLAYLEVEL(2, "Save dictionary of size %u into file %s \n", (U32)dictSize, dictFileName);
267 DiB_saveDict(dictFileName, dictBuffer, dictSize);
268
269 /* clean up */
270_cleanup:
271 free(srcBuffer);
272 free(dictBuffer);
273 free(fileSizes);
274 return result;
275}