]> git.tuebingen.mpg.de Git - osl.git/blob - hash.h
08153383218a36bdd664508b920e2725153656b4
[osl.git] / hash.h
1 /*
2  * Copyright (C) 2007-2009 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file hash.h Inline functions for hash values. */
8
9 #include "portable_io.h"
10
11 /** hash arrays are always unsigned char. */
12 #define HASH_TYPE unsigned char
13
14 /** Size of the hash value in bytes. */
15 #define HASH_SIZE 20
16
17 void sha1_hash(const char *data, unsigned long len, unsigned char *sha1);
18
19 static inline void hash_function(uint8_t table_version, const char *data,
20                 unsigned long len, unsigned char *result)
21 {
22         assert(table_version == 1);
23         sha1_hash(data, len, result);
24 }
25
26 /**
27  * Compare two hashes.
28  *
29  * \param h1 Pointer to the first hash value.
30  * \param h2 Pointer to the second hash value.
31  *
32  * \return 1, -1, or zero, depending on whether \a h1 is greater than,
33  * less than or equal to h2, respectively.
34  */
35 _static_inline_ int hash_compare(HASH_TYPE *h1, HASH_TYPE *h2)
36 {
37         int i;
38
39         for (i = 0; i < HASH_SIZE; i++) {
40                 if (h1[i] < h2[i])
41                         return -1;
42                 if (h1[i] > h2[i])
43                         return 1;
44         }
45         return 0;
46 }
47
48 /**
49  * Convert a hash value to ascii format.
50  *
51  * \param hash the hash value.
52  * \param asc Result pointer.
53  *
54  * \a asc must point to an area of at least 2 * \p HASH_SIZE + 1 bytes which
55  * will be filled by the function with the ascii representation of the hash
56  * value given by \a hash, and a terminating \p NULL byte.
57  */
58 _static_inline_ void hash_to_asc(HASH_TYPE *hash, char *asc)
59 {
60         int i;
61         const char hexchar[] = "0123456789abcdef";
62
63         for (i = 0; i < HASH_SIZE; i++) {
64                 asc[2 * i] = hexchar[hash[i] >> 4];
65                 asc[2 * i + 1] = hexchar[hash[i] & 0xf];
66         }
67         asc[2 * HASH_SIZE] = '\0';
68 }