tag: Reintroduce tag library.
[sliver-openvswitch.git] / lib / tag.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 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
17 #include <config.h>
18 #include "tag.h"
19 #include <limits.h>
20
21 #define N_TAG_BITS (CHAR_BIT * sizeof(tag_type))
22 BUILD_ASSERT_DECL(IS_POW2(N_TAG_BITS));
23
24 #define LOG2_N_TAG_BITS (N_TAG_BITS == 32 ? 5 : N_TAG_BITS == 64 ? 6 : 0)
25 BUILD_ASSERT_DECL(LOG2_N_TAG_BITS > 0);
26
27 /* Returns a tag deterministically generated from 'seed'.
28  *
29  * 'seed' should have data in all of its bits; if it has data only in its
30  * low-order bits then the resulting tags will be poorly distributed.  Use a
31  * hash function such as hash_bytes() to generate 'seed' if necessary. */
32 tag_type
33 tag_create_deterministic(uint32_t seed)
34 {
35     int x = seed & (N_TAG_BITS - 1);
36     int y = (seed >> LOG2_N_TAG_BITS) % (N_TAG_BITS - 1);
37     y += y >= x;
38     return (1u << x) | (1u << y);
39 }