1/*
2
3"Special" Cache.
4
5Copyright (c) 2003 OpenBeOS.
6
7Author:
8	Michael Pfeiffer
9
10Permission is hereby granted, free of charge, to any person obtaining a copy of
11this software and associated documentation files (the "Software"), to deal in
12the Software without restriction, including without limitation the rights to
13use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
14of the Software, and to permit persons to whom the Software is furnished to do
15so, subject to the following conditions:
16
17The above copyright notice and this permission notice shall be included in all
18copies or substantial portions of the Software.
19
20THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26THE SOFTWARE.
27
28*/
29
30#include "Report.h"
31#include "Cache.h"
32#include <Debug.h>
33
34class CIReference : public CacheItem {
35public:
36	CIReference(CacheItem* item) : fItem(item) {
37		ASSERT(dynamic_cast<CIReference*>(item) == NULL);
38	}
39
40	bool Equals(CIDescription* desc) const {
41		return fItem->Equals(desc);
42	}
43
44	CacheItem* Reference() {
45		return fItem;
46	}
47
48private:
49	CacheItem* fItem;
50};
51
52Cache::Cache()
53	: fPass(0)
54	, fNextID(0)
55{};
56
57void Cache::NextPass() {
58	fPass++;
59	fNextID = 0;
60	// max two passes!
61	ASSERT(fPass == 1);
62}
63
64CacheItem* Cache::Find(CIDescription* desc) {
65	REPORT(kDebug, -1, "Cache::Find() pass = %d next id = %d", fPass, fNextID);
66	int id = fNextID ++;
67	const int32 n = CountItems();
68	CacheItem* item = ItemAt(id);
69
70	// In 2. pass for each item an entry must exists
71	ASSERT(fPass != 1 || item != NULL);
72	if (fPass == 1) return item->Reference();
73
74	// In 1. pass we create an entry for each bitmap
75	for (int32 i = 0; i < n; i ++) {
76		item = ItemAt(i);
77		// skip references
78		if (item != item->Reference()) continue;
79		if (item->Equals(desc)) {
80			// found item in cache, create a reference to it
81			CacheItem* ref = new CIReference(item->Reference());
82			if (ref == NULL) return NULL;
83			fCache.AddItem(ref);
84			return item;
85		}
86	}
87	// item not in cache, create one
88	item = desc->NewItem(id);
89	if (item != NULL) {
90		ASSERT(dynamic_cast<CIReference*>(item) == NULL);
91		fCache.AddItem(item);
92	}
93	return item;
94}
95