AceCommon  1.6.0
Arduino library for low-level common functions and features with no external dependencies
djb2.h
Go to the documentation of this file.
1 /*
2 MIT License
3 
4 Copyright (c) 2020 Brian T. Park
5 
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12 
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15 
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23 */
24 
32 #ifndef ACE_COMMON_HASH_DJB2_H
33 #define ACE_COMMON_HASH_DJB2_H
34 
35 #include <stdint.h> // uint32_t
36 #include "../fstrings/FlashString.h"
37 class __FlashStringHelper;
38 
39 namespace ace_common {
40 
51 template <typename T>
52 uint32_t hashDjb2Template(T s) {
53  uint32_t hash = 5381;
54  uint8_t c;
55 
56  while ((c = *s++)) {
57  hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
58  }
59 
60  return hash;
61 }
62 
69 inline uint32_t hashDjb2(const char* s) { return hashDjb2Template(s); }
70 
77 inline uint32_t hashDjb2(const __FlashStringHelper* fs) {
78  return hashDjb2Template<FlashString>(FlashString(fs));
79 }
80 
81 } // ace_common
82 
83 #endif
A thin wrapper around a (const __FlashStringHelper*) so that it acts exactly like a (const char*) wit...
Definition: FlashString.h:49
uint32_t hashDjb2Template(T s)
Implement the djb2 hash algorithm as described in https://stackoverflow.com/questions/7666509 and htt...
Definition: djb2.h:52
uint32_t hashDjb2(const char *s)
Type checked version of hashDjb2Template(T s) for a regular c-string (const uint8_t*) terminated by N...
Definition: djb2.h:69