NetworkManager/shared/nm-utils/nm-hash-utils.c

76 lines
1.9 KiB
C
Raw Normal View History

/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
* (C) Copyright 2017 Red Hat, Inc.
*/
#include "nm-default.h"
#include "nm-hash-utils.h"
#include "nm-shared-utils.h"
#include "nm-random-utils.h"
/*****************************************************************************/
void
nm_hash_init (NMHashState *state, guint static_seed)
{
static volatile guint global_seed = 0;
guint g, s;
nm_assert (state);
/* we xor @seed with a random @global_seed. This is to make the hashing behavior
* less predictable and harder to exploit collisions. */
g = global_seed;
if (G_UNLIKELY (g == 0)) {
nm_utils_random_bytes (&s, sizeof (s));
if (s == 0)
s = 42;
g_atomic_int_compare_and_exchange ((int *) &global_seed, 0, s);
g = global_seed;
nm_assert (g);
}
s = g ^ static_seed;
state->hash = s;
}
guint
nm_hash_str (const char *str)
{
NMHashState h;
nm_hash_init (&h, 1867854211u);
nm_hash_update_str (&h, str);
return nm_hash_complete (&h);
}
guint
nm_str_hash (gconstpointer str)
{
return nm_hash_str (str);
}
guint
nm_direct_hash (gconstpointer ptr)
{
return nm_hash_ptr (ptr);
}