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