xref: /haiku/src/servers/app/RegionPool.cpp (revision 1d9d47fc72028bb71b5f232a877231e59cfe2438)
1 /*
2  * Copyright (c) 2006, Haiku, Inc.
3  * Distributed under the terms of the MIT license.
4  *
5  * Authors:
6  *		Stephan Aßmus <superstippi@gmx.de>
7  */
8 
9 #include "RegionPool.h"
10 
11 #include <new>
12 #include <stdio.h>
13 
14 #if DEBUG_LEAK
15 #include <debugger.h>
16 #endif
17 
18 #include <Region.h>
19 
20 using std::nothrow;
21 
22 RegionPool::RegionPool()
23 	: fAvailable(4)
24 #if DEBUG_LEAK
25 	  ,fUsed(4)
26 #endif
27 {
28 }
29 
30 
31 RegionPool::~RegionPool()
32 {
33 #if DEBUG_LEAK
34 	if (fUsed.CountItems() > 0)
35 		debugger("RegionPool::~RegionPool() - some regions still in use!");
36 #endif
37 	int32 count = fAvailable.CountItems();
38 	for (int32 i = 0; i < count; i++)
39 		delete (BRegion*)fAvailable.ItemAtFast(i);
40 }
41 
42 
43 BRegion*
44 RegionPool::GetRegion()
45 {
46 	BRegion* region = (BRegion*)fAvailable.RemoveItem(
47 		fAvailable.CountItems() - 1);
48 	if (!region) {
49 		region = new (nothrow) BRegion();
50 		if (!region) {
51 			// whoa
52 			fprintf(stderr, "RegionPool::GetRegion() - "
53 							"no memory!\n");
54 		}
55 	}
56 #if DEBUG_LEAK
57 	fUsed.AddItem(region);
58 #endif
59 	return region;
60 }
61 
62 
63 BRegion*
64 RegionPool::GetRegion(const BRegion& other)
65 {
66 	BRegion* region;
67 	int32 count = fAvailable.CountItems();
68 	if (count > 0) {
69 		region = (BRegion*)fAvailable.RemoveItem(count - 1);
70 		*region = other;
71 	} else {
72 		region = new (nothrow) BRegion(other);
73 		if (!region) {
74 			// whoa
75 			fprintf(stderr, "RegionPool::GetRegion() - "
76 							"no memory!\n");
77 		}
78 	}
79 
80 #if DEBUG_LEAK
81 	fUsed.AddItem(region);
82 #endif
83 	return region;
84 }
85 
86 
87 void
88 RegionPool::Recycle(BRegion* region)
89 {
90 	if (!fAvailable.AddItem(region)) {
91 		// at least don't leak the region...
92 		fprintf(stderr, "RegionPool::Recycle() - "
93 						"no memory!\n");
94 		delete region;
95 	} else {
96 		// prepare for next usage
97 		region->MakeEmpty();
98 	}
99 #if DEBUG_LEAK
100 	fUsed.RemoveItem(region);
101 #endif
102 }
103 
104