03b45e04db71965dd70dfce56eafce6ad83f163e
[paraslash.git] / hash.h
1 /*
2 * Copyright (C) 2007-2008 Andre Noll <maan@systemlinux.org>
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 #include "sha1.h"
15 /** We use openssl's sha1 implementation. */
16 #define hash_function sha1_hash
17
18 /**
19 * Compare two hashes.
20 *
21 * \param h1 Pointer to the first hash value.
22 * \param h2 Pointer to the second hash value.
23 *
24 * \return 1, -1, or zero, depending on whether \a h1 is greater than,
25 * less than or equal to h2, respectively.
26 */
27 _static_inline_ int hash_compare(HASH_TYPE *h1, HASH_TYPE *h2)
28 {
29 int i;
30
31 for (i = 0; i < HASH_SIZE; i++) {
32 if (h1[i] < h2[i])
33 return -1;
34 if (h1[i] > h2[i])
35 return 1;
36 }
37 return 0;
38 }
39
40 /**
41 * Convert a hash value to ascii format.
42 *
43 * \param hash the hash value.
44 * \param asc Result pointer.
45 *
46 * \a asc must point to an area of at least 2 * \p HASH_SIZE + 1 bytes which
47 * will be filled by the function with the ascii representation of the hash
48 * value given by \a hash, and a terminating \p NULL byte.
49 */
50 _static_inline_ void hash_to_asc(HASH_TYPE *hash, char *asc)
51 {
52 int i;
53 const char hexchar[] = "0123456789abcdef";
54
55 for (i = 0; i < HASH_SIZE; i++) {
56 asc[2 * i] = hexchar[hash[i] >> 4];
57 asc[2 * i + 1] = hexchar[hash[i] & 0xf];
58 }
59 asc[2 * HASH_SIZE] = '\0';
60 }