]> git.tuebingen.mpg.de Git - osl.git/blob - hash.h
6d6cb8f3911f40e65f2037f57fd90420c69d8120
[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 *result);
18 void sha3_hash(const char *data, unsigned long len, unsigned char *result);
19
20 static inline void hash_function(uint8_t table_version, const char *data,
21                 unsigned long len, unsigned char *result)
22 {
23         if (table_version == 1)
24                 return sha1_hash(data, len, result);
25         if (table_version == 2)
26                 return sha3_hash(data, len, result);
27         assert(0);
28 }
29
30 /**
31  * Compare two hashes.
32  *
33  * \param h1 Pointer to the first hash value.
34  * \param h2 Pointer to the second hash value.
35  *
36  * \return 1, -1, or zero, depending on whether \a h1 is greater than,
37  * less than or equal to h2, respectively.
38  */
39 _static_inline_ int hash_compare(HASH_TYPE *h1, HASH_TYPE *h2)
40 {
41         int i;
42
43         for (i = 0; i < HASH_SIZE; i++) {
44                 if (h1[i] < h2[i])
45                         return -1;
46                 if (h1[i] > h2[i])
47                         return 1;
48         }
49         return 0;
50 }
51
52 /**
53  * Convert a hash value to ascii format.
54  *
55  * \param hash the hash value.
56  * \param asc Result pointer.
57  *
58  * \a asc must point to an area of at least 2 * \p HASH_SIZE + 1 bytes which
59  * will be filled by the function with the ascii representation of the hash
60  * value given by \a hash, and a terminating \p NULL byte.
61  */
62 _static_inline_ void hash_to_asc(HASH_TYPE *hash, char *asc)
63 {
64         int i;
65         const char hexchar[] = "0123456789abcdef";
66
67         for (i = 0; i < HASH_SIZE; i++) {
68                 asc[2 * i] = hexchar[hash[i] >> 4];
69                 asc[2 * i + 1] = hexchar[hash[i] & 0xf];
70         }
71         asc[2 * HASH_SIZE] = '\0';
72 }