xref: /haiku/headers/private/shared/HashString.h (revision 1deede7388b04dbeec5af85cae7164735ea9e70d)
1 /*
2  * Copyright 2004-2007, Ingo Weinhold, bonefish@users.sf.net. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  */
5 #ifndef HASH_STRING_H
6 #define HASH_STRING_H
7 
8 #include <SupportDefs.h>
9 
10 // string_hash
11 //
12 // from the Dragon Book: a slightly modified hashpjw()
13 static inline
14 uint32
15 string_hash(const char *name)
16 {
17 	uint32 h = 0;
18 	if (name) {
19 		for (; *name; name++) {
20 			uint32 g = h & 0xf0000000;
21 			if (g)
22 				h ^= g >> 24;
23 			h = (h << 4) + *name;
24 		}
25 	}
26 	return h;
27 }
28 
29 #ifdef __cplusplus
30 
31 namespace BPrivate {
32 
33 // HashString
34 class HashString {
35 public:
36 	HashString();
37 	HashString(const HashString &string);
38 	HashString(const char *string, int32 length = -1);
39 	~HashString();
40 
41 	bool SetTo(const char *string, int32 maxLength = -1);
42 	void Unset();
43 
44 	void Truncate(int32 newLength);
45 
46 	const char *GetString() const;
47 	int32 GetLength() const	{ return fLength; }
48 
49 	uint32 GetHashCode() const	{ return string_hash(GetString()); }
50 
51 	HashString &operator=(const HashString &string);
52 	bool operator==(const HashString &string) const;
53 	bool operator!=(const HashString &string) const { return !(*this == string); }
54 
55 private:
56 	bool _SetTo(const char *string, int32 length);
57 
58 private:
59 	int32	fLength;
60 	char	*fString;
61 };
62 
63 }	// namespace BPrivate
64 
65 using BPrivate::HashString;
66 
67 #endif	// __cplusplus
68 
69 #endif	// HASH_STRING_H
70