glusterfs

Форк
0
1301 строка · 41.5 Кб
1
/*
2
*  xxhsum - Command line interface for xxhash algorithms
3
*  Copyright (C) Yann Collet 2012-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
*  - xxHash homepage : http://www.xxhash.com
23
*  - xxHash source repository : https://github.com/Cyan4973/xxHash
24
*/
25

26
/* xxhsum :
27
 * Provides hash value of a file content, or a list of files, or stdin
28
 * Display convention is Big Endian, for both 32 and 64 bits algorithms
29
 */
30

31
#ifndef XXHASH_C_2097394837
32
#define XXHASH_C_2097394837
33

34
/* ************************************
35
 *  Compiler Options
36
 **************************************/
37
/* MS Visual */
38
#if defined(_MSC_VER) || defined(_WIN32)
39
#  define _CRT_SECURE_NO_WARNINGS   /* removes visual warnings */
40
#endif
41

42
/* Under Linux at least, pull in the *64 commands */
43
#ifndef _LARGEFILE64_SOURCE
44
#  define _LARGEFILE64_SOURCE
45
#endif
46

47

48
/* ************************************
49
 *  Includes
50
 **************************************/
51
#include <stdlib.h>     /* malloc, calloc, free, exit */
52
#include <stdio.h>      /* fprintf, fopen, ftello64, fread, stdin, stdout, _fileno (when present) */
53
#include <string.h>     /* strcmp */
54
#include <sys/types.h>  /* stat, stat64, _stat64 */
55
#include <sys/stat.h>   /* stat, stat64, _stat64 */
56
#include <time.h>       /* clock_t, clock, CLOCKS_PER_SEC */
57
#include <assert.h>     /* assert */
58

59
#define XXH_STATIC_LINKING_ONLY   /* *_state_t */
60
#include "xxhash.h"
61

62

63
/* ************************************
64
 *  OS-Specific Includes
65
 **************************************/
66
#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)
67
#  include <fcntl.h>    /* _O_BINARY */
68
#  include <io.h>       /* _setmode, _isatty */
69
#  define SET_BINARY_MODE(file) _setmode(_fileno(file), _O_BINARY)
70
#  define IS_CONSOLE(stdStream) _isatty(_fileno(stdStream))
71
#else
72
#  include <unistd.h>   /* isatty, STDIN_FILENO */
73
#  define SET_BINARY_MODE(file)
74
#  define IS_CONSOLE(stdStream) isatty(STDIN_FILENO)
75
#endif
76

77
#if !defined(S_ISREG)
78
#  define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
79
#endif
80

81

82
/* ************************************
83
*  Basic Types
84
**************************************/
85
#ifndef MEM_MODULE
86
# define MEM_MODULE
87
# if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
88
#   include <stdint.h>
89
    typedef uint8_t  BYTE;
90
    typedef uint16_t U16;
91
    typedef uint32_t U32;
92
    typedef  int32_t S32;
93
    typedef uint64_t U64;
94
#  else
95
    typedef unsigned char      BYTE;
96
    typedef unsigned short     U16;
97
    typedef unsigned int       U32;
98
    typedef   signed int       S32;
99
    typedef unsigned long long U64;
100
#  endif
101
#endif
102

103
static unsigned BMK_isLittleEndian(void)
104
{
105
    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental  */
106
    return one.c[0];
107
}
108

109

110
/* *************************************
111
 *  Constants
112
 ***************************************/
113
#define LIB_VERSION XXH_VERSION_MAJOR.XXH_VERSION_MINOR.XXH_VERSION_RELEASE
114
#define QUOTE(str) #str
115
#define EXPAND_AND_QUOTE(str) QUOTE(str)
116
#define PROGRAM_VERSION EXPAND_AND_QUOTE(LIB_VERSION)
117
static const int g_nbBits = (int)(sizeof(void*)*8);
118
static const char g_lename[] = "little endian";
119
static const char g_bename[] = "big endian";
120
#define ENDIAN_NAME (BMK_isLittleEndian() ? g_lename : g_bename)
121
static const char author[] = "Yann Collet";
122
#define WELCOME_MESSAGE(exename) "%s %s (%i-bits %s), by %s \n", \
123
                    exename, PROGRAM_VERSION, g_nbBits, ENDIAN_NAME, author
124

125
#define KB *( 1<<10)
126
#define MB *( 1<<20)
127
#define GB *(1U<<30)
128

129
static size_t XXH_DEFAULT_SAMPLE_SIZE = 100 KB;
130
#define NBLOOPS    3                              /* Default number of benchmark iterations */
131
#define TIMELOOP_S 1
132
#define TIMELOOP  (TIMELOOP_S * CLOCKS_PER_SEC)   /* Minimum timing per iteration */
133
#define XXHSUM32_DEFAULT_SEED 0                   /* Default seed for algo_xxh32 */
134
#define XXHSUM64_DEFAULT_SEED 0                   /* Default seed for algo_xxh64 */
135

136
#define MAX_MEM    (2 GB - 64 MB)
137

138
static const char stdinName[] = "-";
139
typedef enum { algo_xxh32, algo_xxh64 } algoType;
140
static const algoType g_defaultAlgo = algo_xxh64;    /* required within main() & usage() */
141

142
/* <16 hex char> <SPC> <SPC> <filename> <'\0'>
143
 * '4096' is typical Linux PATH_MAX configuration. */
144
#define DEFAULT_LINE_LENGTH (sizeof(XXH64_hash_t) * 2 + 2 + 4096 + 1)
145

146
/* Maximum acceptable line length. */
147
#define MAX_LINE_LENGTH (32 KB)
148

149

150
/* ************************************
151
 *  Display macros
152
 **************************************/
153
#define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
154
#define DISPLAYRESULT(...)   fprintf(stdout, __VA_ARGS__)
155
#define DISPLAYLEVEL(l, ...) do { if (g_displayLevel>=l) DISPLAY(__VA_ARGS__); } while (0)
156
static int g_displayLevel = 2;
157

158

159
/* ************************************
160
 *  Local variables
161
 **************************************/
162
static U32 g_nbIterations = NBLOOPS;
163

164

165
/* ************************************
166
 *  Benchmark Functions
167
 **************************************/
168
static clock_t BMK_clockSpan( clock_t start )
169
{
170
    return clock() - start;   /* works even if overflow; Typical max span ~ 30 mn */
171
}
172

173

174
static size_t BMK_findMaxMem(U64 requiredMem)
175
{
176
    size_t const step = 64 MB;
177
    void* testmem = NULL;
178

179
    requiredMem = (((requiredMem >> 26) + 1) << 26);
180
    requiredMem += 2*step;
181
    if (requiredMem > MAX_MEM) requiredMem = MAX_MEM;
182

183
    while (!testmem) {
184
        if (requiredMem > step) requiredMem -= step;
185
        else requiredMem >>= 1;
186
        testmem = malloc ((size_t)requiredMem);
187
    }
188
    free (testmem);
189

190
    /* keep some space available */
191
    if (requiredMem > step) requiredMem -= step;
192
    else requiredMem >>= 1;
193

194
    return (size_t)requiredMem;
195
}
196

197

198
static U64 BMK_GetFileSize(const char* infilename)
199
{
200
    int r;
201
#if defined(_MSC_VER)
202
    struct _stat64 statbuf;
203
    r = _stat64(infilename, &statbuf);
204
#else
205
    struct stat statbuf;
206
    r = stat(infilename, &statbuf);
207
#endif
208
    if (r || !S_ISREG(statbuf.st_mode)) return 0;   /* No good... */
209
    return (U64)statbuf.st_size;
210
}
211

212
typedef U32 (*hashFunction)(const void* buffer, size_t bufferSize, U32 seed);
213

214
static U32 localXXH32(const void* buffer, size_t bufferSize, U32 seed) { return XXH32(buffer, bufferSize, seed); }
215

216
static U32 localXXH64(const void* buffer, size_t bufferSize, U32 seed) { return (U32)XXH64(buffer, bufferSize, seed); }
217

218
static void BMK_benchHash(hashFunction h, const char* hName, const void* buffer, size_t bufferSize)
219
{
220
    U32 nbh_perIteration = ((300 MB) / (bufferSize+1)) + 1;  /* first loop conservatively aims for 300 MB/s */
221
    U32 iterationNb;
222
    double fastestH = 100000000.;
223

224
    DISPLAYLEVEL(2, "\r%70s\r", "");       /* Clean display line */
225
    if (g_nbIterations<1) g_nbIterations=1;
226
    for (iterationNb = 1; iterationNb <= g_nbIterations; iterationNb++) {
227
        U32 r=0;
228
        clock_t cStart;
229

230
        DISPLAYLEVEL(2, "%1i-%-17.17s : %10u ->\r", iterationNb, hName, (U32)bufferSize);
231
        cStart = clock();
232
        while (clock() == cStart);   /* starts clock() at its exact beginning */
233
        cStart = clock();
234

235
        {   U32 i;
236
            for (i=0; i<nbh_perIteration; i++)
237
                r += h(buffer, bufferSize, i);
238
        }
239
        if (r==0) DISPLAYLEVEL(3,".\r");  /* do something with r to avoid compiler "optimizing" away hash function */
240
        {   double const timeS = ((double)BMK_clockSpan(cStart) / CLOCKS_PER_SEC) / nbh_perIteration;
241
            if (timeS < fastestH) fastestH = timeS;
242
            DISPLAYLEVEL(2, "%1i-%-17.17s : %10u -> %8.0f it/s (%7.1f MB/s) \r",
243
                    iterationNb, hName, (U32)bufferSize,
244
                    (double)1 / fastestH,
245
                    ((double)bufferSize / (1<<20)) / fastestH );
246
        }
247
        assert(fastestH > 1./2000000000);  /* avoid U32 overflow */
248
        nbh_perIteration = (U32)(1 / fastestH) + 1;  /* adjust nbh_perIteration to last roughtly one second */
249
    }
250
    DISPLAYLEVEL(1, "%-19.19s : %10u -> %8.0f it/s (%7.1f MB/s) \n", hName, (U32)bufferSize,
251
        (double)1 / fastestH,
252
        ((double)bufferSize / (1<<20)) / fastestH);
253
    if (g_displayLevel<1)
254
        DISPLAYLEVEL(0, "%u, ", (U32)((double)1 / fastestH));
255
}
256

257

258
/* BMK_benchMem():
259
 * specificTest : 0 == run all tests, 1+ run only specific test
260
 * buffer : is supposed 8-bytes aligned (if malloc'ed, it should be)
261
 * the real allocated size of buffer is supposed to be >= (bufferSize+3).
262
 * @return : 0 on success, 1 if error (invalid mode selected) */
263
static int BMK_benchMem(const void* buffer, size_t bufferSize, U32 specificTest)
264
{
265
    assert((((size_t)buffer) & 8) == 0);  /* ensure alignment */
266

267
    /* XXH32 bench */
268
    if ((specificTest==0) | (specificTest==1))
269
        BMK_benchHash(localXXH32, "XXH32", buffer, bufferSize);
270

271
    /* Bench XXH32 on Unaligned input */
272
    if ((specificTest==0) | (specificTest==2))
273
        BMK_benchHash(localXXH32, "XXH32 unaligned", ((const char*)buffer)+1, bufferSize);
274

275
    /* Bench XXH64 */
276
    if ((specificTest==0) | (specificTest==3))
277
        BMK_benchHash(localXXH64, "XXH64", buffer, bufferSize);
278

279
    /* Bench XXH64 on Unaligned input */
280
    if ((specificTest==0) | (specificTest==4))
281
        BMK_benchHash(localXXH64, "XXH64 unaligned", ((const char*)buffer)+3, bufferSize);
282

283
    if (specificTest > 4) {
284
        DISPLAY("benchmark mode invalid \n");
285
        return 1;
286
    }
287
    return 0;
288
}
289

290

291
static size_t BMK_selectBenchedSize(const char* fileName)
292
{   U64 const inFileSize = BMK_GetFileSize(fileName);
293
    size_t benchedSize = (size_t) BMK_findMaxMem(inFileSize);
294
    if ((U64)benchedSize > inFileSize) benchedSize = (size_t)inFileSize;
295
    if (benchedSize < inFileSize) {
296
        DISPLAY("Not enough memory for '%s' full size; testing %i MB only...\n", fileName, (int)(benchedSize>>20));
297
    }
298
    return benchedSize;
299
}
300

301

302
static int BMK_benchFiles(const char** fileNamesTable, int nbFiles, U32 specificTest)
303
{
304
    int result = 0;
305
    int fileIdx;
306

307
    for (fileIdx=0; fileIdx<nbFiles; fileIdx++) {
308
        const char* const inFileName = fileNamesTable[fileIdx];
309
        FILE* const inFile = fopen( inFileName, "rb" );
310
        size_t const benchedSize = BMK_selectBenchedSize(inFileName);
311
        char* const buffer = (char*)calloc(benchedSize+16+3, 1);
312
        void* const alignedBuffer = (buffer+15) - (((size_t)(buffer+15)) & 0xF);  /* align on next 16 bytes */
313

314
        /* Checks */
315
        if ((inFile==NULL) || (inFileName==NULL)) {
316
            DISPLAY("Pb opening %s\n", inFileName);
317
            free(buffer);
318
            return 11;
319
        }
320
        if(!buffer) {
321
            DISPLAY("\nError: not enough memory!\n");
322
            fclose(inFile);
323
            return 12;
324
        }
325

326
        /* Fill input buffer */
327
        DISPLAYLEVEL(1, "\rLoading %s...        \n", inFileName);
328
        {   size_t const readSize = fread(alignedBuffer, 1, benchedSize, inFile);
329
            fclose(inFile);
330
            if(readSize != benchedSize) {
331
                DISPLAY("\nError: problem reading file '%s' !!    \n", inFileName);
332
                free(buffer);
333
                return 13;
334
        }   }
335

336
        /* bench */
337
        result |= BMK_benchMem(alignedBuffer, benchedSize, specificTest);
338

339
        free(buffer);
340
    }
341

342
    return result;
343
}
344

345

346

347
static int BMK_benchInternal(size_t keySize, int specificTest)
348
{
349
    void* const buffer = calloc(keySize+16+3, 1);
350
    void* const alignedBuffer = ((char*)buffer+15) - (((size_t)((char*)buffer+15)) & 0xF);  /* align on next 16 bytes */
351
    if(!buffer) {
352
        DISPLAY("\nError: not enough memory!\n");
353
        return 12;
354
    }
355

356
    /* bench */
357
    DISPLAYLEVEL(1, "Sample of ");
358
    if (keySize > 10 KB) {
359
        DISPLAYLEVEL(1, "%u KB", (U32)(keySize >> 10));
360
    } else {
361
        DISPLAYLEVEL(1, "%u bytes", (U32)keySize);
362
    }
363
    DISPLAYLEVEL(1, "...        \n");
364

365
    {   int const result = BMK_benchMem(alignedBuffer, keySize, specificTest);
366
        free(buffer);
367
        return result;
368
    }
369
}
370

371

372
static void BMK_checkResult(U32 r1, U32 r2)
373
{
374
    static int nbTests = 1;
375
    if (r1==r2) {
376
        DISPLAYLEVEL(3, "\rTest%3i : %08X == %08X   ok   ", nbTests, r1, r2);
377
    } else {
378
        DISPLAY("\rERROR : Test%3i : %08X <> %08X   !!!!!   \n", nbTests, r1, r2);
379
        exit(1);
380
    }
381
    nbTests++;
382
}
383

384

385
static void BMK_checkResult64(U64 r1, U64 r2)
386
{
387
    static int nbTests = 1;
388
    if (r1!=r2) {
389
        DISPLAY("\rERROR : Test%3i : 64-bit values non equals   !!!!!   \n", nbTests);
390
        DISPLAY("\r %08X%08X != %08X%08X \n", (U32)(r1>>32), (U32)r1, (U32)(r2>>32), (U32)r2);
391
        exit(1);
392
    }
393
    nbTests++;
394
}
395

396

397
static void BMK_testSequence64(void* sentence, size_t len, U64 seed, U64 Nresult)
398
{
399
    XXH64_state_t state;
400
    U64 Dresult;
401
    size_t pos;
402

403
    Dresult = XXH64(sentence, len, seed);
404
    BMK_checkResult64(Dresult, Nresult);
405

406
    XXH64_reset(&state, seed);
407
    XXH64_update(&state, sentence, len);
408
    Dresult = XXH64_digest(&state);
409
    BMK_checkResult64(Dresult, Nresult);
410

411
    XXH64_reset(&state, seed);
412
    for (pos=0; pos<len; pos++)
413
        XXH64_update(&state, ((char*)sentence)+pos, 1);
414
    Dresult = XXH64_digest(&state);
415
    BMK_checkResult64(Dresult, Nresult);
416
}
417

418

419
static void BMK_testSequence(const void* sequence, size_t len, U32 seed, U32 Nresult)
420
{
421
    XXH32_state_t state;
422
    U32 Dresult;
423
    size_t pos;
424

425
    Dresult = XXH32(sequence, len, seed);
426
    BMK_checkResult(Dresult, Nresult);
427

428
    XXH32_reset(&state, seed);
429
    XXH32_update(&state, sequence, len);
430
    Dresult = XXH32_digest(&state);
431
    BMK_checkResult(Dresult, Nresult);
432

433
    XXH32_reset(&state, seed);
434
    for (pos=0; pos<len; pos++)
435
        XXH32_update(&state, ((const char*)sequence)+pos, 1);
436
    Dresult = XXH32_digest(&state);
437
    BMK_checkResult(Dresult, Nresult);
438
}
439

440

441
#define SANITY_BUFFER_SIZE 101
442
static void BMK_sanityCheck(void)
443
{
444
    static const U32 prime = 2654435761U;
445
    BYTE sanityBuffer[SANITY_BUFFER_SIZE];
446
    U32 byteGen = prime;
447

448
    int i;
449
    for (i=0; i<SANITY_BUFFER_SIZE; i++) {
450
        sanityBuffer[i] = (BYTE)(byteGen>>24);
451
        byteGen *= byteGen;
452
    }
453

454
    BMK_testSequence(NULL,          0, 0,     0x02CC5D05);
455
    BMK_testSequence(NULL,          0, prime, 0x36B78AE7);
456
    BMK_testSequence(sanityBuffer,  1, 0,     0xB85CBEE5);
457
    BMK_testSequence(sanityBuffer,  1, prime, 0xD5845D64);
458
    BMK_testSequence(sanityBuffer, 14, 0,     0xE5AA0AB4);
459
    BMK_testSequence(sanityBuffer, 14, prime, 0x4481951D);
460
    BMK_testSequence(sanityBuffer, SANITY_BUFFER_SIZE, 0,     0x1F1AA412);
461
    BMK_testSequence(sanityBuffer, SANITY_BUFFER_SIZE, prime, 0x498EC8E2);
462

463
    BMK_testSequence64(NULL        ,  0, 0,     0xEF46DB3751D8E999ULL);
464
    BMK_testSequence64(NULL        ,  0, prime, 0xAC75FDA2929B17EFULL);
465
    BMK_testSequence64(sanityBuffer,  1, 0,     0x4FCE394CC88952D8ULL);
466
    BMK_testSequence64(sanityBuffer,  1, prime, 0x739840CB819FA723ULL);
467
    BMK_testSequence64(sanityBuffer, 14, 0,     0xCFFA8DB881BC3A3DULL);
468
    BMK_testSequence64(sanityBuffer, 14, prime, 0x5B9611585EFCC9CBULL);
469
    BMK_testSequence64(sanityBuffer, SANITY_BUFFER_SIZE, 0,     0x0EAB543384F878ADULL);
470
    BMK_testSequence64(sanityBuffer, SANITY_BUFFER_SIZE, prime, 0xCAA65939306F1E21ULL);
471

472
    DISPLAYLEVEL(3, "\r%70s\r", "");       /* Clean display line */
473
    DISPLAYLEVEL(3, "Sanity check -- all tests ok\n");
474
}
475

476

477
/* ********************************************************
478
*  File Hashing
479
**********************************************************/
480

481
static void BMK_display_LittleEndian(const void* ptr, size_t length)
482
{
483
    const BYTE* p = (const BYTE*)ptr;
484
    size_t idx;
485
    for (idx=length-1; idx<length; idx--)    /* intentional underflow to negative to detect end */
486
        DISPLAYRESULT("%02x", p[idx]);
487
}
488

489
static void BMK_display_BigEndian(const void* ptr, size_t length)
490
{
491
    const BYTE* p = (const BYTE*)ptr;
492
    size_t idx;
493
    for (idx=0; idx<length; idx++)
494
        DISPLAYRESULT("%02x", p[idx]);
495
}
496

497
static void BMK_hashStream(void* xxhHashValue, const algoType hashType, FILE* inFile, void* buffer, size_t blockSize)
498
{
499
    XXH64_state_t state64;
500
    XXH32_state_t state32;
501
    size_t readSize;
502

503
    /* Init */
504
    XXH32_reset(&state32, XXHSUM32_DEFAULT_SEED);
505
    XXH64_reset(&state64, XXHSUM64_DEFAULT_SEED);
506

507
    /* Load file & update hash */
508
    readSize = 1;
509
    while (readSize) {
510
        readSize = fread(buffer, 1, blockSize, inFile);
511
        switch(hashType)
512
        {
513
        case algo_xxh32:
514
            XXH32_update(&state32, buffer, readSize);
515
            break;
516
        case algo_xxh64:
517
            XXH64_update(&state64, buffer, readSize);
518
            break;
519
        default:
520
            break;
521
        }
522
    }
523

524
    switch(hashType)
525
    {
526
    case algo_xxh32:
527
        {   U32 const h32 = XXH32_digest(&state32);
528
            memcpy(xxhHashValue, &h32, sizeof(h32));
529
            break;
530
        }
531
    case algo_xxh64:
532
        {   U64 const h64 = XXH64_digest(&state64);
533
            memcpy(xxhHashValue, &h64, sizeof(h64));
534
            break;
535
        }
536
    default:
537
            break;
538
    }
539
}
540

541

542
typedef enum { big_endian, little_endian} endianess;
543

544
static int BMK_hash(const char* fileName,
545
                    const algoType hashType,
546
                    const endianess displayEndianess)
547
{
548
    FILE*  inFile;
549
    size_t const blockSize = 64 KB;
550
    void*  buffer;
551
    U32    h32 = 0;
552
    U64    h64 = 0;
553

554
    /* Check file existence */
555
    if (fileName == stdinName) {
556
        inFile = stdin;
557
        SET_BINARY_MODE(stdin);
558
    }
559
    else
560
        inFile = fopen( fileName, "rb" );
561
    if (inFile==NULL) {
562
        DISPLAY( "Pb opening %s\n", fileName);
563
        return 1;
564
    }
565

566
    /* Memory allocation & restrictions */
567
    buffer = malloc(blockSize);
568
    if(!buffer) {
569
        DISPLAY("\nError: not enough memory!\n");
570
        fclose(inFile);
571
        return 1;
572
    }
573

574
    /* loading notification */
575
    {   const size_t fileNameSize = strlen(fileName);
576
        const char* const fileNameEnd = fileName + fileNameSize;
577
        const int maxInfoFilenameSize = (int)(fileNameSize > 30 ? 30 : fileNameSize);
578
        int infoFilenameSize = 1;
579
        while ((infoFilenameSize < maxInfoFilenameSize)
580
            && (fileNameEnd[-1-infoFilenameSize] != '/')
581
            && (fileNameEnd[-1-infoFilenameSize] != '\\') )
582
              infoFilenameSize++;
583
        DISPLAY("\rLoading %s...  \r", fileNameEnd - infoFilenameSize);
584

585
        /* Load file & update hash */
586
        switch(hashType)
587
        {
588
        case algo_xxh32:
589
            BMK_hashStream(&h32, algo_xxh32, inFile, buffer, blockSize);
590
            break;
591
        case algo_xxh64:
592
            BMK_hashStream(&h64, algo_xxh64, inFile, buffer, blockSize);
593
            break;
594
        default:
595
            break;
596
        }
597

598
        fclose(inFile);
599
        free(buffer);
600
        DISPLAY("%s             \r", fileNameEnd - infoFilenameSize);  /* erase line */
601
    }
602

603
    /* display Hash */
604
    switch(hashType)
605
    {
606
    case algo_xxh32:
607
        {   XXH32_canonical_t hcbe32;
608
            XXH32_canonicalFromHash(&hcbe32, h32);
609
            displayEndianess==big_endian ?
610
                BMK_display_BigEndian(&hcbe32, sizeof(hcbe32)) : BMK_display_LittleEndian(&hcbe32, sizeof(hcbe32));
611
            DISPLAYRESULT("  %s\n", fileName);
612
            break;
613
        }
614
    case algo_xxh64:
615
        {   XXH64_canonical_t hcbe64;
616
            XXH64_canonicalFromHash(&hcbe64, h64);
617
            displayEndianess==big_endian ?
618
                BMK_display_BigEndian(&hcbe64, sizeof(hcbe64)) : BMK_display_LittleEndian(&hcbe64, sizeof(hcbe64));
619
            DISPLAYRESULT("  %s\n", fileName);
620
            break;
621
        }
622
    default:
623
            break;
624
    }
625

626
    return 0;
627
}
628

629

630
static int BMK_hashFiles(const char** fnList, int fnTotal,
631
                         algoType hashType, endianess displayEndianess)
632
{
633
    int fnNb;
634
    int result = 0;
635

636
    if (fnTotal==0)
637
        return BMK_hash(stdinName, hashType, displayEndianess);
638

639
    for (fnNb=0; fnNb<fnTotal; fnNb++)
640
        result += BMK_hash(fnList[fnNb], hashType, displayEndianess);
641
    DISPLAY("\r%70s\r", "");
642
    return result;
643
}
644

645

646
typedef enum {
647
    GetLine_ok,
648
    GetLine_eof,
649
    GetLine_exceedMaxLineLength,
650
    GetLine_outOfMemory,
651
} GetLineResult;
652

653
typedef enum {
654
    CanonicalFromString_ok,
655
    CanonicalFromString_invalidFormat,
656
} CanonicalFromStringResult;
657

658
typedef enum {
659
    ParseLine_ok,
660
    ParseLine_invalidFormat,
661
} ParseLineResult;
662

663
typedef enum {
664
    LineStatus_hashOk,
665
    LineStatus_hashFailed,
666
    LineStatus_failedToOpen,
667
} LineStatus;
668

669
typedef union {
670
    XXH32_canonical_t xxh32;
671
    XXH64_canonical_t xxh64;
672
} Canonical;
673

674
typedef struct {
675
    Canonical   canonical;
676
    const char* filename;
677
    int         xxhBits;    /* canonical type : 32:xxh32, 64:xxh64 */
678
} ParsedLine;
679

680
typedef struct {
681
    unsigned long   nProperlyFormattedLines;
682
    unsigned long   nImproperlyFormattedLines;
683
    unsigned long   nMismatchedChecksums;
684
    unsigned long   nOpenOrReadFailures;
685
    unsigned long   nMixedFormatLines;
686
    int             xxhBits;
687
    int             quit;
688
} ParseFileReport;
689

690
typedef struct {
691
    const char*     inFileName;
692
    FILE*           inFile;
693
    int             lineMax;
694
    char*           lineBuf;
695
    size_t          blockSize;
696
    char*           blockBuf;
697
    int             strictMode;
698
    int             statusOnly;
699
    int             warn;
700
    int             quiet;
701
    ParseFileReport report;
702
} ParseFileArg;
703

704

705
/*  Read line from stream.
706
    Returns GetLine_ok, if it reads line successfully.
707
    Returns GetLine_eof, if stream reaches EOF.
708
    Returns GetLine_exceedMaxLineLength, if line length is longer than MAX_LINE_LENGTH.
709
    Returns GetLine_outOfMemory, if line buffer memory allocation failed.
710
 */
711
static GetLineResult getLine(char** lineBuf, int* lineMax, FILE* inFile)
712
{
713
    GetLineResult result = GetLine_ok;
714
    int len = 0;
715

716
    if ((*lineBuf == NULL) || (*lineMax<1)) {
717
        free(*lineBuf);  /* in case it's != NULL */
718
        *lineMax = 0;
719
        *lineBuf = (char*)malloc(DEFAULT_LINE_LENGTH);
720
        if(*lineBuf == NULL) return GetLine_outOfMemory;
721
        *lineMax = DEFAULT_LINE_LENGTH;
722
    }
723

724
    for (;;) {
725
        const int c = fgetc(inFile);
726
        if (c == EOF) {
727
            /* If we meet EOF before first character, returns GetLine_eof,
728
             * otherwise GetLine_ok.
729
             */
730
            if (len == 0) result = GetLine_eof;
731
            break;
732
        }
733

734
        /* Make enough space for len+1 (for final NUL) bytes. */
735
        if (len+1 >= *lineMax) {
736
            char* newLineBuf = NULL;
737
            int newBufSize = *lineMax;
738

739
            newBufSize += (newBufSize/2) + 1; /* x 1.5 */
740
            if (newBufSize > MAX_LINE_LENGTH) newBufSize = MAX_LINE_LENGTH;
741
            if (len+1 >= newBufSize) return GetLine_exceedMaxLineLength;
742

743
            newLineBuf = (char*) realloc(*lineBuf, newBufSize);
744
            if (newLineBuf == NULL) return GetLine_outOfMemory;
745

746
            *lineBuf = newLineBuf;
747
            *lineMax = newBufSize;
748
        }
749

750
        if (c == '\n') break;
751
        (*lineBuf)[len++] = (char) c;
752
    }
753

754
    (*lineBuf)[len] = '\0';
755
    return result;
756
}
757

758

759
/*  Converts one hexadecimal character to integer.
760
 *  Returns -1, if given character is not hexadecimal.
761
 */
762
static int charToHex(char c)
763
{
764
    int result = -1;
765
    if (c >= '0' && c <= '9') {
766
        result = (int) (c - '0');
767
    } else if (c >= 'A' && c <= 'F') {
768
        result = (int) (c - 'A') + 0x0a;
769
    } else if (c >= 'a' && c <= 'f') {
770
        result = (int) (c - 'a') + 0x0a;
771
    }
772
    return result;
773
}
774

775

776
/*  Converts XXH32 canonical hexadecimal string hashStr to big endian unsigned char array dst.
777
 *  Returns CANONICAL_FROM_STRING_INVALID_FORMAT, if hashStr is not well formatted.
778
 *  Returns CANONICAL_FROM_STRING_OK, if hashStr is parsed successfully.
779
 */
780
static CanonicalFromStringResult canonicalFromString(unsigned char* dst,
781
                                                     size_t dstSize,
782
                                                     const char* hashStr)
783
{
784
    size_t i;
785
    for (i = 0; i < dstSize; ++i) {
786
        int h0, h1;
787

788
        h0 = charToHex(hashStr[i*2 + 0]);
789
        if (h0 < 0) return CanonicalFromString_invalidFormat;
790

791
        h1 = charToHex(hashStr[i*2 + 1]);
792
        if (h1 < 0) return CanonicalFromString_invalidFormat;
793

794
        dst[i] = (unsigned char) ((h0 << 4) | h1);
795
    }
796
    return CanonicalFromString_ok;
797
}
798

799

800
/*  Parse single line of xxHash checksum file.
801
 *  Returns PARSE_LINE_ERROR_INVALID_FORMAT, if line is not well formatted.
802
 *  Returns PARSE_LINE_OK if line is parsed successfully.
803
 *  And members of parseLine will be filled by parsed values.
804
 *
805
 *  - line must be ended with '\0'.
806
 *  - Since parsedLine.filename will point within given argument `line`,
807
 *    users must keep `line`s content during they are using parsedLine.
808
 *
809
 *  Given xxHash checksum line should have the following format:
810
 *
811
 *      <8 or 16 hexadecimal char> <space> <space> <filename...> <'\0'>
812
 */
813
static ParseLineResult parseLine(ParsedLine* parsedLine, const char* line)
814
{
815
    const char* const firstSpace = strchr(line, ' ');
816
    const char* const secondSpace = firstSpace + 1;
817

818
    parsedLine->filename = NULL;
819
    parsedLine->xxhBits = 0;
820

821
    if (firstSpace == NULL || *secondSpace != ' ') return ParseLine_invalidFormat;
822

823
    switch (firstSpace - line)
824
    {
825
    case 8:
826
        {   XXH32_canonical_t* xxh32c = &parsedLine->canonical.xxh32;
827
            if (canonicalFromString(xxh32c->digest, sizeof(xxh32c->digest), line)
828
                != CanonicalFromString_ok) {
829
                return ParseLine_invalidFormat;
830
            }
831
            parsedLine->xxhBits = 32;
832
            break;
833
        }
834

835
    case 16:
836
        {   XXH64_canonical_t* xxh64c = &parsedLine->canonical.xxh64;
837
            if (canonicalFromString(xxh64c->digest, sizeof(xxh64c->digest), line)
838
                != CanonicalFromString_ok) {
839
                return ParseLine_invalidFormat;
840
            }
841
            parsedLine->xxhBits = 64;
842
            break;
843
        }
844

845
    default:
846
            return ParseLine_invalidFormat;
847
            break;
848
    }
849

850
    parsedLine->filename = secondSpace + 1;
851
    return ParseLine_ok;
852
}
853

854

855
/*!  Parse xxHash checksum file.
856
 */
857
static void parseFile1(ParseFileArg* parseFileArg)
858
{
859
    const char* const inFileName = parseFileArg->inFileName;
860
    ParseFileReport* const report = &parseFileArg->report;
861

862
    unsigned long lineNumber = 0;
863
    memset(report, 0, sizeof(*report));
864

865
    while (!report->quit) {
866
        FILE* fp = NULL;
867
        LineStatus lineStatus = LineStatus_hashFailed;
868
        GetLineResult getLineResult;
869
        ParsedLine parsedLine;
870
        memset(&parsedLine, 0, sizeof(parsedLine));
871

872
        lineNumber++;
873
        if (lineNumber == 0) {
874
            /* This is unlikely happen, but md5sum.c has this
875
             * error check. */
876
            DISPLAY("%s : too many checksum lines\n", inFileName);
877
            report->quit = 1;
878
            break;
879
        }
880

881
        getLineResult = getLine(&parseFileArg->lineBuf, &parseFileArg->lineMax,
882
                                parseFileArg->inFile);
883
        if (getLineResult != GetLine_ok) {
884
            if (getLineResult == GetLine_eof) break;
885

886
            switch (getLineResult)
887
            {
888
            case GetLine_ok:
889
            case GetLine_eof:
890
                /* These cases never happen.  See above getLineResult related "if"s.
891
                   They exist just for make gcc's -Wswitch-enum happy. */
892
                break;
893

894
            default:
895
                DISPLAY("%s : %lu: unknown error\n", inFileName, lineNumber);
896
                break;
897

898
            case GetLine_exceedMaxLineLength:
899
                DISPLAY("%s : %lu: too long line\n", inFileName, lineNumber);
900
                break;
901

902
            case GetLine_outOfMemory:
903
                DISPLAY("%s : %lu: out of memory\n", inFileName, lineNumber);
904
                break;
905
            }
906
            report->quit = 1;
907
            break;
908
        }
909

910
        if (parseLine(&parsedLine, parseFileArg->lineBuf) != ParseLine_ok) {
911
            report->nImproperlyFormattedLines++;
912
            if (parseFileArg->warn) {
913
                DISPLAY("%s : %lu: improperly formatted XXHASH checksum line\n"
914
                    , inFileName, lineNumber);
915
            }
916
            continue;
917
        }
918

919
        if (report->xxhBits != 0 && report->xxhBits != parsedLine.xxhBits) {
920
            /* Don't accept xxh32/xxh64 mixed file */
921
            report->nImproperlyFormattedLines++;
922
            report->nMixedFormatLines++;
923
            if (parseFileArg->warn) {
924
                DISPLAY("%s : %lu: improperly formatted XXHASH checksum line (XXH32/64)\n"
925
                    , inFileName, lineNumber);
926
            }
927
            continue;
928
        }
929

930
        report->nProperlyFormattedLines++;
931
        if (report->xxhBits == 0) {
932
            report->xxhBits = parsedLine.xxhBits;
933
        }
934

935
        fp = fopen(parsedLine.filename, "rb");
936
        if (fp == NULL) {
937
            lineStatus = LineStatus_failedToOpen;
938
        } else {
939
            lineStatus = LineStatus_hashFailed;
940
            switch (parsedLine.xxhBits)
941
            {
942
            case 32:
943
                {   XXH32_hash_t xxh;
944
                    BMK_hashStream(&xxh, algo_xxh32, fp, parseFileArg->blockBuf, parseFileArg->blockSize);
945
                    if (xxh == XXH32_hashFromCanonical(&parsedLine.canonical.xxh32)) {
946
                        lineStatus = LineStatus_hashOk;
947
                }   }
948
                break;
949

950
            case 64:
951
                {   XXH64_hash_t xxh;
952
                    BMK_hashStream(&xxh, algo_xxh64, fp, parseFileArg->blockBuf, parseFileArg->blockSize);
953
                    if (xxh == XXH64_hashFromCanonical(&parsedLine.canonical.xxh64)) {
954
                        lineStatus = LineStatus_hashOk;
955
                }   }
956
                break;
957

958
            default:
959
                break;
960
            }
961
            fclose(fp);
962
        }
963

964
        switch (lineStatus)
965
        {
966
        default:
967
            DISPLAY("%s : unknown error\n", inFileName);
968
            report->quit = 1;
969
            break;
970

971
        case LineStatus_failedToOpen:
972
            report->nOpenOrReadFailures++;
973
            if (!parseFileArg->statusOnly) {
974
                DISPLAYRESULT("%s : %lu: FAILED open or read %s\n"
975
                    , inFileName, lineNumber, parsedLine.filename);
976
            }
977
            break;
978

979
        case LineStatus_hashOk:
980
        case LineStatus_hashFailed:
981
            {   int b = 1;
982
                if (lineStatus == LineStatus_hashOk) {
983
                    /* If --quiet is specified, don't display "OK" */
984
                    if (parseFileArg->quiet) b = 0;
985
                } else {
986
                    report->nMismatchedChecksums++;
987
                }
988

989
                if (b && !parseFileArg->statusOnly) {
990
                    DISPLAYRESULT("%s: %s\n", parsedLine.filename
991
                        , lineStatus == LineStatus_hashOk ? "OK" : "FAILED");
992
            }   }
993
            break;
994
        }
995
    }   /* while (!report->quit) */
996
}
997

998

999
/*  Parse xxHash checksum file.
1000
 *  Returns 1, if all procedures were succeeded.
1001
 *  Returns 0, if any procedures was failed.
1002
 *
1003
 *  If strictMode != 0, return error code if any line is invalid.
1004
 *  If statusOnly != 0, don't generate any output.
1005
 *  If warn != 0, print a warning message to stderr.
1006
 *  If quiet != 0, suppress "OK" line.
1007
 *
1008
 *  "All procedures are succeeded" means:
1009
 *    - Checksum file contains at least one line and less than SIZE_T_MAX lines.
1010
 *    - All files are properly opened and read.
1011
 *    - All hash values match with its content.
1012
 *    - (strict mode) All lines in checksum file are consistent and well formatted.
1013
 *
1014
 */
1015
static int checkFile(const char* inFileName,
1016
                     const endianess displayEndianess,
1017
                     U32 strictMode,
1018
                     U32 statusOnly,
1019
                     U32 warn,
1020
                     U32 quiet)
1021
{
1022
    int result = 0;
1023
    FILE* inFile = NULL;
1024
    ParseFileArg parseFileArgBody;
1025
    ParseFileArg* const parseFileArg = &parseFileArgBody;
1026
    ParseFileReport* const report = &parseFileArg->report;
1027

1028
    if (displayEndianess != big_endian) {
1029
        /* Don't accept little endian */
1030
        DISPLAY( "Check file mode doesn't support little endian\n" );
1031
        return 0;
1032
    }
1033

1034
    /* note : stdinName is special constant pointer.  It is not a string. */
1035
    if (inFileName == stdinName) {
1036
        /* note : Since we expect text input for xxhash -c mode,
1037
         * Don't set binary mode for stdin */
1038
        inFile = stdin;
1039
    } else {
1040
        inFile = fopen( inFileName, "rt" );
1041
    }
1042

1043
    if (inFile == NULL) {
1044
        DISPLAY( "Pb opening %s\n", inFileName);
1045
        return 0;
1046
    }
1047

1048
    parseFileArg->inFileName    = inFileName;
1049
    parseFileArg->inFile        = inFile;
1050
    parseFileArg->lineMax       = DEFAULT_LINE_LENGTH;
1051
    parseFileArg->lineBuf       = (char*) malloc((size_t) parseFileArg->lineMax);
1052
    parseFileArg->blockSize     = 64 * 1024;
1053
    parseFileArg->blockBuf      = (char*) malloc(parseFileArg->blockSize);
1054
    parseFileArg->strictMode    = strictMode;
1055
    parseFileArg->statusOnly    = statusOnly;
1056
    parseFileArg->warn          = warn;
1057
    parseFileArg->quiet         = quiet;
1058

1059
    parseFile1(parseFileArg);
1060

1061
    free(parseFileArg->blockBuf);
1062
    free(parseFileArg->lineBuf);
1063

1064
    if (inFile != stdin) fclose(inFile);
1065

1066
    /* Show error/warning messages.  All messages are copied from md5sum.c
1067
     */
1068
    if (report->nProperlyFormattedLines == 0) {
1069
        DISPLAY("%s: no properly formatted XXHASH checksum lines found\n", inFileName);
1070
    } else if (!statusOnly) {
1071
        if (report->nImproperlyFormattedLines) {
1072
            DISPLAYRESULT("%lu lines are improperly formatted\n"
1073
                , report->nImproperlyFormattedLines);
1074
        }
1075
        if (report->nOpenOrReadFailures) {
1076
            DISPLAYRESULT("%lu listed files could not be read\n"
1077
                , report->nOpenOrReadFailures);
1078
        }
1079
        if (report->nMismatchedChecksums) {
1080
            DISPLAYRESULT("%lu computed checksums did NOT match\n"
1081
                , report->nMismatchedChecksums);
1082
    }   }
1083

1084
    /* Result (exit) code logic is copied from
1085
     * gnu coreutils/src/md5sum.c digest_check() */
1086
    result =   report->nProperlyFormattedLines != 0
1087
            && report->nMismatchedChecksums == 0
1088
            && report->nOpenOrReadFailures == 0
1089
            && (!strictMode || report->nImproperlyFormattedLines == 0)
1090
            && report->quit == 0;
1091
    return result;
1092
}
1093

1094

1095
static int checkFiles(const char** fnList, int fnTotal,
1096
                      const endianess displayEndianess,
1097
                      U32 strictMode,
1098
                      U32 statusOnly,
1099
                      U32 warn,
1100
                      U32 quiet)
1101
{
1102
    int ok = 1;
1103

1104
    /* Special case for stdinName "-",
1105
     * note: stdinName is not a string.  It's special pointer. */
1106
    if (fnTotal==0) {
1107
        ok &= checkFile(stdinName, displayEndianess, strictMode, statusOnly, warn, quiet);
1108
    } else {
1109
        int fnNb;
1110
        for (fnNb=0; fnNb<fnTotal; fnNb++)
1111
            ok &= checkFile(fnList[fnNb], displayEndianess, strictMode, statusOnly, warn, quiet);
1112
    }
1113
    return ok ? 0 : 1;
1114
}
1115

1116

1117
/* ********************************************************
1118
*  Main
1119
**********************************************************/
1120

1121
static int usage(const char* exename)
1122
{
1123
    DISPLAY( WELCOME_MESSAGE(exename) );
1124
    DISPLAY( "Usage :\n");
1125
    DISPLAY( "      %s [arg] [filenames]\n", exename);
1126
    DISPLAY( "When no filename provided, or - provided : use stdin as input\n");
1127
    DISPLAY( "Arguments :\n");
1128
    DISPLAY( " -H# : hash selection : 0=32bits, 1=64bits (default: %i)\n", (int)g_defaultAlgo);
1129
    DISPLAY( " -c  : read xxHash sums from the [filenames] and check them\n");
1130
    DISPLAY( " -h  : help \n");
1131
    return 0;
1132
}
1133

1134

1135
static int usage_advanced(const char* exename)
1136
{
1137
    usage(exename);
1138
    DISPLAY( "Advanced :\n");
1139
    DISPLAY( " --little-endian : hash printed using little endian convention (default: big endian)\n");
1140
    DISPLAY( " -V, --version   : display version\n");
1141
    DISPLAY( " -h, --help      : display long help and exit\n");
1142
    DISPLAY( " -b  : benchmark mode \n");
1143
    DISPLAY( " -i# : number of iterations (benchmark mode; default %i)\n", g_nbIterations);
1144
    DISPLAY( "\n");
1145
    DISPLAY( "The following four options are useful only when verifying checksums (-c):\n");
1146
    DISPLAY( "--strict : don't print OK for each successfully verified file\n");
1147
    DISPLAY( "--status : don't output anything, status code shows success\n");
1148
    DISPLAY( "--quiet  : exit non-zero for improperly formatted checksum lines\n");
1149
    DISPLAY( "--warn   : warn about improperly formatted checksum lines\n");
1150
    return 0;
1151
}
1152

1153
static int badusage(const char* exename)
1154
{
1155
    DISPLAY("Wrong parameters\n");
1156
    usage(exename);
1157
    return 1;
1158
}
1159

1160
/*! readU32FromChar() :
1161
   @return : unsigned integer value read from input in `char` format,
1162
             0 is no figure at *stringPtr position.
1163
    Interprets K, KB, KiB, M, MB and MiB suffix.
1164
    Modifies `*stringPtr`, advancing it to position where reading stopped.
1165
    Note : function result can overflow if digit string > MAX_UINT */
1166
static unsigned readU32FromChar(const char** stringPtr)
1167
{
1168
    unsigned result = 0;
1169
    while ((**stringPtr >='0') && (**stringPtr <='9'))
1170
        result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1171
    if ((**stringPtr=='K') || (**stringPtr=='M')) {
1172
        result <<= 10;
1173
        if (**stringPtr=='M') result <<= 10;
1174
        (*stringPtr)++ ;
1175
        if (**stringPtr=='i') (*stringPtr)++;
1176
        if (**stringPtr=='B') (*stringPtr)++;
1177
    }
1178
    return result;
1179
}
1180

1181
int main(int argc, const char** argv)
1182
{
1183
    int i, filenamesStart = 0;
1184
    const char* const exename = argv[0];
1185
    U32 benchmarkMode = 0;
1186
    U32 fileCheckMode = 0;
1187
    U32 strictMode    = 0;
1188
    U32 statusOnly    = 0;
1189
    U32 warn          = 0;
1190
    U32 quiet         = 0;
1191
    U32 specificTest  = 0;
1192
    size_t keySize    = XXH_DEFAULT_SAMPLE_SIZE;
1193
    algoType algo     = g_defaultAlgo;
1194
    endianess displayEndianess = big_endian;
1195

1196
    /* special case : xxh32sum default to 32 bits checksum */
1197
    if (strstr(exename, "xxh32sum") != NULL) algo = algo_xxh32;
1198

1199
    for(i=1; i<argc; i++) {
1200
        const char* argument = argv[i];
1201

1202
        if(!argument) continue;   /* Protection, if argument empty */
1203

1204
        if (!strcmp(argument, "--little-endian")) { displayEndianess = little_endian; continue; }
1205
        if (!strcmp(argument, "--check")) { fileCheckMode = 1; continue; }
1206
        if (!strcmp(argument, "--strict")) { strictMode = 1; continue; }
1207
        if (!strcmp(argument, "--status")) { statusOnly = 1; continue; }
1208
        if (!strcmp(argument, "--quiet")) { quiet = 1; continue; }
1209
        if (!strcmp(argument, "--warn")) { warn = 1; continue; }
1210
        if (!strcmp(argument, "--help")) { return usage_advanced(exename); }
1211
        if (!strcmp(argument, "--version")) { DISPLAY(WELCOME_MESSAGE(exename)); return 0; }
1212

1213
        if (*argument!='-') {
1214
            if (filenamesStart==0) filenamesStart=i;   /* only supports a continuous list of filenames */
1215
            continue;
1216
        }
1217

1218
        /* command selection */
1219
        argument++;   /* note : *argument=='-' */
1220

1221
        while (*argument!=0) {
1222
            switch(*argument)
1223
            {
1224
            /* Display version */
1225
            case 'V':
1226
                DISPLAY(WELCOME_MESSAGE(exename)); return 0;
1227

1228
            /* Display help on usage */
1229
            case 'h':
1230
                return usage_advanced(exename);
1231

1232
            /* select hash algorithm */
1233
            case 'H':
1234
                algo = (algoType)(argument[1] - '0');
1235
                argument+=2;
1236
                break;
1237

1238
            /* File check mode */
1239
            case 'c':
1240
                fileCheckMode=1;
1241
                argument++;
1242
                break;
1243

1244
            /* Warning mode (file check mode only, alias of "--warning") */
1245
            case 'w':
1246
                warn=1;
1247
                argument++;
1248
                break;
1249

1250
            /* Trigger benchmark mode */
1251
            case 'b':
1252
                argument++;
1253
                benchmarkMode = 1;
1254
                specificTest = readU32FromChar(&argument);   /* select one specific test (hidden option) */
1255
                break;
1256

1257
            /* Modify Nb Iterations (benchmark only) */
1258
            case 'i':
1259
                argument++;
1260
                g_nbIterations = readU32FromChar(&argument);
1261
                break;
1262

1263
            /* Modify Block size (benchmark only) */
1264
            case 'B':
1265
                argument++;
1266
                keySize = readU32FromChar(&argument);
1267
                break;
1268

1269
            /* Modify verbosity of benchmark output (hidden option) */
1270
            case 'q':
1271
                argument++;
1272
                g_displayLevel--;
1273
                break;
1274

1275
            default:
1276
                return badusage(exename);
1277
            }
1278
        }
1279
    }   /* for(i=1; i<argc; i++) */
1280

1281
    /* Check benchmark mode */
1282
    if (benchmarkMode) {
1283
        DISPLAYLEVEL(2, WELCOME_MESSAGE(exename) );
1284
        BMK_sanityCheck();
1285
        if (filenamesStart==0) return BMK_benchInternal(keySize, specificTest);
1286
        return BMK_benchFiles(argv+filenamesStart, argc-filenamesStart, specificTest);
1287
    }
1288

1289
    /* Check if input is defined as console; trigger an error in this case */
1290
    if ( (filenamesStart==0) && IS_CONSOLE(stdin) ) return badusage(exename);
1291

1292
    if (filenamesStart==0) filenamesStart = argc;
1293
    if (fileCheckMode) {
1294
        return checkFiles(argv+filenamesStart, argc-filenamesStart,
1295
                          displayEndianess, strictMode, statusOnly, warn, quiet);
1296
    } else {
1297
        return BMK_hashFiles(argv+filenamesStart, argc-filenamesStart, algo, displayEndianess);
1298
    }
1299
}
1300

1301
#endif /* XXHASH_C_2097394837 */
1302

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.