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