tlx
hash_sdbm.hpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/string/hash_sdbm.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_SDBM_HEADER
12 #define TLX_STRING_HASH_SDBM_HEADER
13 
14 #include <string>
15 
16 namespace tlx {
17 
18 //! \addtogroup tlx_string
19 //! \{
20 
21 /*!
22  * Simple, fast, but "insecure" string hash method by sdbm database from
23  * http://www.cse.yorku.ca/~oz/hash.html
24  */
25 static inline
26 uint32_t hash_sdbm(const unsigned char* str) {
27  uint32_t hash = 0;
28  unsigned char c;
29  while ((c = *str++) != 0) {
30  hash = c + (hash << 6) + (hash << 16) - hash;
31  }
32  return hash;
33 }
34 
35 /*!
36  * Simple, fast, but "insecure" string hash method by sdbm database from
37  * http://www.cse.yorku.ca/~oz/hash.html
38  */
39 static inline
40 uint32_t hash_sdbm(const char* str) {
41  return hash_sdbm(reinterpret_cast<const unsigned char*>(str));
42 }
43 
44 /*!
45  * Simple, fast, but "insecure" string hash method by sdbm database from
46  * http://www.cse.yorku.ca/~oz/hash.html
47  */
48 static inline
49 uint32_t hash_sdbm(const unsigned char* str, size_t size) {
50  uint32_t hash = 0;
51  while (size-- > 0) {
52  hash = static_cast<unsigned char>(*str++)
53  + (hash << 6) + (hash << 16) - hash;
54  }
55  return hash;
56 }
57 
58 /*!
59  * Simple, fast, but "insecure" string hash method by sdbm database from
60  * http://www.cse.yorku.ca/~oz/hash.html
61  */
62 static inline
63 uint32_t hash_sdbm(const char* str, size_t size) {
64  return hash_sdbm(reinterpret_cast<const unsigned char*>(str), size);
65 }
66 
67 /*!
68  * Simple, fast, but "insecure" string hash method by sdbm database from
69  * http://www.cse.yorku.ca/~oz/hash.html
70  */
71 static inline
72 uint32_t hash_sdbm(const std::string& str) {
73  return hash_sdbm(str.data(), str.size());
74 }
75 
76 //! \}
77 
78 } // namespace tlx
79 
80 #endif // !TLX_STRING_HASH_SDBM_HEADER
81 
82 /******************************************************************************/
static uint32_t hash_sdbm(const unsigned char *str)
Simple, fast, but "insecure" string hash method by sdbm database from http://www.cse.yorku.ca/~oz/hash.html.
Definition: hash_sdbm.hpp:26