Setting tag sliver-openvswitch-2.2.90-1
[sliver-openvswitch.git] / lib / hash.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <config.h>
17 #include "hash.h"
18 #include <string.h>
19 #include "unaligned.h"
20
21 /* Returns the hash of 'a', 'b', and 'c'. */
22 uint32_t
23 hash_3words(uint32_t a, uint32_t b, uint32_t c)
24 {
25     return mhash_finish(mhash_add(mhash_add(mhash_add(a, 0), b), c), 12);
26 }
27
28 /* Returns the hash of the 'n' bytes at 'p', starting from 'basis'. */
29 uint32_t
30 hash_bytes(const void *p_, size_t n, uint32_t basis)
31 {
32     const uint32_t *p = p_;
33     size_t orig_n = n;
34     uint32_t hash;
35
36     hash = basis;
37     while (n >= 4) {
38         hash = mhash_add(hash, get_unaligned_u32(p));
39         n -= 4;
40         p += 1;
41     }
42
43     if (n) {
44         uint32_t tmp = 0;
45
46         memcpy(&tmp, p, n);
47         hash = mhash_add__(hash, tmp);
48     }
49
50     return mhash_finish(hash, orig_n);
51 }
52
53 /* Returns the hash of the 'n' 32-bit words at 'p', starting from 'basis'.
54  * 'p' must be properly aligned. */
55 uint32_t
56 hash_words(const uint32_t p[], size_t n_words, uint32_t basis)
57 {
58     uint32_t hash;
59     size_t i;
60
61     hash = basis;
62     for (i = 0; i < n_words; i++) {
63         hash = mhash_add(hash, p[i]);
64     }
65     return mhash_finish(hash, n_words * 4);
66 }
67
68 uint32_t
69 hash_double(double x, uint32_t basis)
70 {
71     uint32_t value[2];
72     BUILD_ASSERT_DECL(sizeof x == sizeof value);
73
74     memcpy(value, &x, sizeof value);
75     return hash_3words(value[0], value[1], basis);
76 }