import source from 1.3.40
[external/swig.git] / CCache / hash.c
1 /*
2    Copyright (C) Andrew Tridgell 2002
3    
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.
8    
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.
13    
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., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18 /*
19   simple front-end functions to mdfour code
20 */
21
22 #include "ccache.h"
23
24 static struct mdfour md;
25
26 void hash_buffer(const char *s, int len)
27 {
28         mdfour_update(&md, (unsigned char *)s, len);
29 }
30
31 void hash_start(void)
32 {
33         mdfour_begin(&md);
34 }
35
36 void hash_string(const char *s)
37 {
38         hash_buffer(s, strlen(s));
39 }
40
41 void hash_int(int x)
42 {
43         hash_buffer((char *)&x, sizeof(x));
44 }
45
46 /* add contents of a file to the hash */
47 void hash_file(const char *fname)
48 {
49         char buf[1024];
50         int fd, n;
51
52         fd = open(fname, O_RDONLY|O_BINARY);
53         if (fd == -1) {
54                 cc_log("Failed to open %s\n", fname);
55                 fatal("hash_file");
56         }
57
58         while ((n = read(fd, buf, sizeof(buf))) > 0) {
59                 hash_buffer(buf, n);
60         }
61         close(fd);
62 }
63
64 /* return the hash result as a static string */
65 char *hash_result(void)
66 {
67         unsigned char sum[16];
68         static char ret[53];
69         int i;
70
71         hash_buffer(NULL, 0);
72         mdfour_result(&md, sum);
73         
74         for (i=0;i<16;i++) {
75                 sprintf(&ret[i*2], "%02x", (unsigned)sum[i]);
76         }
77         sprintf(&ret[i*2], "-%u", (unsigned)md.totalN);
78
79         return ret;
80 }