1/*
2 * Copyright 2009-2013, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
4 */
5
6
7#include <package/hpkg/Strings.h>
8
9
10namespace BPackageKit {
11
12namespace BHPKG {
13
14namespace BPrivate {
15
16
17// from the Dragon Book: a slightly modified hashpjw()
18uint32
19hash_string(const char* string)
20{
21	if (string == NULL)
22		return 0;
23
24	uint32 h = 0;
25
26	for (; *string; string++) {
27		uint32 g = h & 0xf0000000;
28		if (g)
29			h ^= g >> 24;
30		h = (h << 4) + *string;
31	}
32
33	return h;
34}
35
36
37StringCache::StringCache()
38{
39}
40
41
42StringCache::~StringCache()
43{
44	CachedString* cachedString = Clear(true);
45	while (cachedString != NULL) {
46		CachedString* next = cachedString->next;
47		delete cachedString;
48		cachedString = next;
49	}
50}
51
52
53CachedString*
54StringCache::Get(const char* value)
55{
56	CachedString* string = Lookup(value);
57	if (string != NULL) {
58		string->usageCount++;
59		return string;
60	}
61
62	string = new CachedString;
63	if (!string->Init(value)) {
64		delete string;
65		throw std::bad_alloc();
66	}
67
68	Insert(string);
69	return string;
70}
71
72
73void
74StringCache::Put(CachedString* string)
75{
76	if (string != NULL) {
77		if (--string->usageCount == 0) {
78			Remove(string);
79			delete string;
80		}
81	}
82}
83
84
85}	// namespace BPrivate
86
87}	// namespace BHPKG
88
89}	// namespace BPackageKit
90