]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/hgfs/hash.c
merge
[plan9front.git] / sys / src / cmd / hgfs / hash.c
1 #include <u.h>
2 #include <libc.h>
3 #include <thread.h>
4 #include "dat.h"
5 #include "fns.h"
6
7 #include <mp.h>
8 #include <libsec.h>
9
10 int
11 Hfmt(Fmt *f)
12 {
13         uchar *p, *e;
14         for(p = va_arg(f->args, uchar*), e = p + HASHSZ; p != e; p++)
15                 if(fmtprint(f, "%.2x", *p) < 0)
16                         return -1;
17         return 0;
18 }
19
20 int
21 fhash(int fd, uchar p1[], uchar p2[], uchar h[])
22 {
23         DigestState *ds;
24         uchar buf[BUFSZ];
25         int n;
26
27         ds = nil;
28         memset(h, 0, HASHSZ);
29         if(memcmp(p1, p2, HASHSZ) > 0){
30                 ds = sha1(p2, HASHSZ, nil, ds);
31                 sha1(p1, HASHSZ, nil, ds);
32         } else {
33                 ds = sha1(p1, HASHSZ, nil, ds);
34                 sha1(p2, HASHSZ, nil, ds);
35         }
36         while((n = read(fd, buf, BUFSZ)) > 0)
37                 sha1(buf, n, nil, ds);
38         sha1(buf, 0, h, ds);
39
40         return 0;
41 }
42
43 int
44 hex2hash(char *s, uchar *h)
45 {
46         uchar *b;
47         int n;
48
49         b = h;
50         memset(h, 0, HASHSZ);
51         n = HASHSZ*2;
52         while(*s && n > 0){
53                 if(*s >= '0' && *s <= '9')
54                         *h |= *s - '0';
55                 else if(*s >= 'a' && *s <= 'f')
56                         *h |= 10 + *s - 'a';
57                 else if(*s >= 'A' && *s <= 'F')
58                         *h |= 10 + *s - 'A';
59                 else
60                         break;
61                 if(n-- & 1)
62                         h++;
63                 else
64                         *h <<= 4;
65                 s++;
66         }
67         return h - b;
68 }
69
70 uvlong
71 hash2qid(uchar *h)
72 {
73         uvlong v;
74         int i;
75
76         v = 0;
77         for(i=0; i<8; i++)
78                 v |= (uvlong)h[i]<<(56-8*i);
79         return v;
80 }