t: add basic tests for our SHA-1 implementation
[git.git] / t / helper / test-sha1.c
blob1ba0675c75f0d2dab281d054b577272cd45c39f9
1 #include "test-tool.h"
2 #include "cache.h"
4 int cmd__sha1(int ac, const char **av)
6 git_SHA_CTX ctx;
7 unsigned char sha1[20];
8 unsigned bufsz = 8192;
9 int binary = 0;
10 char *buffer;
12 if (ac == 2) {
13 if (!strcmp(av[1], "-b"))
14 binary = 1;
15 else
16 bufsz = strtoul(av[1], NULL, 10) * 1024 * 1024;
19 if (!bufsz)
20 bufsz = 8192;
22 while ((buffer = malloc(bufsz)) == NULL) {
23 fprintf(stderr, "bufsz %u is too big, halving...\n", bufsz);
24 bufsz /= 2;
25 if (bufsz < 1024)
26 die("OOPS");
29 git_SHA1_Init(&ctx);
31 while (1) {
32 ssize_t sz, this_sz;
33 char *cp = buffer;
34 unsigned room = bufsz;
35 this_sz = 0;
36 while (room) {
37 sz = xread(0, cp, room);
38 if (sz == 0)
39 break;
40 if (sz < 0)
41 die_errno("test-sha1");
42 this_sz += sz;
43 cp += sz;
44 room -= sz;
46 if (this_sz == 0)
47 break;
48 git_SHA1_Update(&ctx, buffer, this_sz);
50 git_SHA1_Final(sha1, &ctx);
52 if (binary)
53 fwrite(sha1, 1, 20, stdout);
54 else
55 puts(sha1_to_hex(sha1));
56 exit(0);