xref: /haiku/src/tests/kits/app/bmessenger/Helpers.h (revision 52a380120846174213ccce9c4aab0dda17c72083)
1 //------------------------------------------------------------------------------
2 //	Helpers.h
3 //
4 //------------------------------------------------------------------------------
5 
6 #ifndef HELPERS_H
7 #define HELPERS_H
8 
9 // Standard Includes -----------------------------------------------------------
10 
11 // System Includes -------------------------------------------------------------
12 #include <Looper.h>
13 
14 // Project Includes ------------------------------------------------------------
15 
16 // Local Includes --------------------------------------------------------------
17 
18 // Local Defines ---------------------------------------------------------------
19 
20 // Globals ---------------------------------------------------------------------
21 
22 
23 // helper class: quits a BLooper on destruction
24 class LooperQuitter {
25 public:
26 	inline LooperQuitter(BLooper *looper) : fLooper(looper) {}
27 	inline ~LooperQuitter() { fLooper->Lock(); fLooper->Quit(); }
28 
29 private:
30 	BLooper	*fLooper;
31 };
32 
33 // helper class: deletes an object on destruction
34 template<typename T>
35 class AutoDeleter {
36 public:
37 	inline AutoDeleter(T *object, bool array = false)
38 		: fObject(object), fArray(array) {}
39 	inline ~AutoDeleter()
40 	{
41 		if (fArray)
42 			delete[] fObject;
43 		else
44 			delete fObject;
45 	}
46 
47 protected:
48 	T		*fObject;
49 	bool	fArray;
50 };
51 
52 // helper class: deletes an BHandler on destruction
53 class HandlerDeleter : AutoDeleter<BHandler> {
54 public:
55 	inline HandlerDeleter(BHandler *handler)
56 		: AutoDeleter<BHandler>(handler) {}
57 	inline ~HandlerDeleter()
58 	{
59 		if (fObject) {
60 			if (BLooper *looper = fObject->Looper()) {
61 				looper->Lock();
62 				looper->RemoveHandler(fObject);
63 				looper->Unlock();
64 			}
65 		}
66 	}
67 };
68 
69 // helper function: return the this team's ID
70 static inline
71 team_id
72 get_this_team()
73 {
74 	thread_info info;
75 	get_thread_info(find_thread(NULL), &info);
76 	return info.team;
77 }
78 
79 #endif	// HELPERS_H
80