]> git.saurik.com Git - apple/icu.git/blob - icuSources/common/servnotf.cpp
ICU-64232.0.1.tar.gz
[apple/icu.git] / icuSources / common / servnotf.cpp
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /**
4 *******************************************************************************
5 * Copyright (C) 2001-2012, International Business Machines Corporation and *
6 * others. All Rights Reserved. *
7 *******************************************************************************
8 */
9
10 #include "unicode/utypes.h"
11
12 #if !UCONFIG_NO_SERVICE
13
14 #include "servnotf.h"
15 #ifdef NOTIFIER_DEBUG
16 #include <stdio.h>
17 #endif
18
19 U_NAMESPACE_BEGIN
20
21 EventListener::~EventListener() {}
22 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(EventListener)
23
24 static UMutex *notifyLock() {
25 static UMutex *m = STATIC_NEW(UMutex);
26 return m;
27 }
28
29 ICUNotifier::ICUNotifier(void)
30 : listeners(NULL)
31 {
32 }
33
34 ICUNotifier::~ICUNotifier(void) {
35 {
36 Mutex lmx(notifyLock());
37 delete listeners;
38 listeners = NULL;
39 }
40 }
41
42
43 void
44 ICUNotifier::addListener(const EventListener* l, UErrorCode& status)
45 {
46 if (U_SUCCESS(status)) {
47 if (l == NULL) {
48 status = U_ILLEGAL_ARGUMENT_ERROR;
49 return;
50 }
51
52 if (acceptsListener(*l)) {
53 Mutex lmx(notifyLock());
54 if (listeners == NULL) {
55 listeners = new UVector(5, status);
56 } else {
57 for (int i = 0, e = listeners->size(); i < e; ++i) {
58 const EventListener* el = (const EventListener*)(listeners->elementAt(i));
59 if (l == el) {
60 return;
61 }
62 }
63 }
64
65 listeners->addElement((void*)l, status); // cast away const
66 }
67 #ifdef NOTIFIER_DEBUG
68 else {
69 fprintf(stderr, "Listener invalid for this notifier.");
70 exit(1);
71 }
72 #endif
73 }
74 }
75
76 void
77 ICUNotifier::removeListener(const EventListener *l, UErrorCode& status)
78 {
79 if (U_SUCCESS(status)) {
80 if (l == NULL) {
81 status = U_ILLEGAL_ARGUMENT_ERROR;
82 return;
83 }
84
85 {
86 Mutex lmx(notifyLock());
87 if (listeners != NULL) {
88 // identity equality check
89 for (int i = 0, e = listeners->size(); i < e; ++i) {
90 const EventListener* el = (const EventListener*)listeners->elementAt(i);
91 if (l == el) {
92 listeners->removeElementAt(i);
93 if (listeners->size() == 0) {
94 delete listeners;
95 listeners = NULL;
96 }
97 return;
98 }
99 }
100 }
101 }
102 }
103 }
104
105 void
106 ICUNotifier::notifyChanged(void)
107 {
108 if (listeners != NULL) {
109 Mutex lmx(notifyLock());
110 if (listeners != NULL) {
111 for (int i = 0, e = listeners->size(); i < e; ++i) {
112 EventListener* el = (EventListener*)listeners->elementAt(i);
113 notifyListener(*el);
114 }
115 }
116 }
117 }
118
119 U_NAMESPACE_END
120
121 /* UCONFIG_NO_SERVICE */
122 #endif
123