tlx
Loading...
Searching...
No Matches
hash_djb2.hpp
Go to the documentation of this file.
1/*******************************************************************************
2 * tlx/string/hash_djb2.hpp
3 *
4 * Part of tlx - http://panthema.net/tlx
5 *
6 * Copyright (C) 2019 Timo Bingmann <tb@panthema.net>
7 *
8 * All rights reserved. Published under the Boost Software License, Version 1.0
9 ******************************************************************************/
10
11#ifndef TLX_STRING_HASH_DJB2_HEADER
12#define TLX_STRING_HASH_DJB2_HEADER
13
14#include <cstdint>
15#include <string>
16
17namespace tlx {
18
19//! \addtogroup tlx_string
20//! \{
21
22/*!
23 * Simple, fast, but "insecure" string hash method by Dan Bernstein from
24 * http://www.cse.yorku.ca/~oz/hash.html
25 */
26static inline
27uint32_t hash_djb2(const unsigned char* str) {
28 uint32_t hash = 5381;
29 unsigned char c;
30 while ((c = *str++) != 0) {
31 // hash * 33 + c
32 hash = ((hash << 5) + hash) + c;
33 }
34 return hash;
35}
36
37/*!
38 * Simple, fast, but "insecure" string hash method by Dan Bernstein from
39 * http://www.cse.yorku.ca/~oz/hash.html
40 */
41static inline
42uint32_t hash_djb2(const char* str) {
43 return hash_djb2(reinterpret_cast<const unsigned char*>(str));
44}
45
46/*!
47 * Simple, fast, but "insecure" string hash method by Dan Bernstein from
48 * http://www.cse.yorku.ca/~oz/hash.html
49 */
50static inline
51uint32_t hash_djb2(const unsigned char* str, size_t size) {
52 uint32_t hash = 5381;
53 while (size-- > 0) {
54 // hash * 33 + c
55 hash = ((hash << 5) + hash) + static_cast<unsigned char>(*str++);
56 }
57 return hash;
58}
59
60/*!
61 * Simple, fast, but "insecure" string hash method by Dan Bernstein from
62 * http://www.cse.yorku.ca/~oz/hash.html
63 */
64static inline
65uint32_t hash_djb2(const char* str, size_t size) {
66 return hash_djb2(reinterpret_cast<const unsigned char*>(str), size);
67}
68
69/*!
70 * Simple, fast, but "insecure" string hash method by Dan Bernstein from
71 * http://www.cse.yorku.ca/~oz/hash.html
72 */
73static inline
74uint32_t hash_djb2(const std::string& str) {
75 return hash_djb2(str.data(), str.size());
76}
77
78//! \}
79
80} // namespace tlx
81
82#endif // !TLX_STRING_HASH_DJB2_HEADER
83
84/******************************************************************************/
static uint32_t hash_djb2(const unsigned char *str)
Simple, fast, but "insecure" string hash method by Dan Bernstein from http://www.cse....
Definition: hash_djb2.hpp:27