Преглед изворни кода

fixed bug: event_subscribe now searches for already existing events first, also removed any cast from a const char * to aa char *

Sebastian пре 6 година
родитељ
комит
d63ea42642
3 измењених фајлова са 27 додато и 23 уклоњено
  1. 1 1
      CoffeeCode/buildno
  2. 25 21
      CoffeeCode/events.cpp
  3. 1 1
      CoffeeCode/events.h

+ 1 - 1
CoffeeCode/buildno

@@ -1 +1 @@
-249
+250

+ 25 - 21
CoffeeCode/events.cpp

@@ -40,7 +40,7 @@ events_t *firstEvent = NULL; /**< The first element in the event list */
  * @return Pointer to event, NULL if not found
  */
 
-events_t * event_find(char *event) {
+events_t * event_find(const char *event) {
 	events_t *tmp = firstEvent;
 
 	while (tmp) {
@@ -100,18 +100,22 @@ void addSubscriber(events_t *event, void (*handler)(event_t *)) {
 
 void event_subscribe(const char *event, void (*handler)(event_t *)) {
 	//TODO change event name to a typedef enum or similar
-	events_t *newEvent = (events_t *) malloc(sizeof(events_t));
-	if (!newEvent)
-		logger_error("Not enough memory\n");
-	newEvent->next = NULL;
-	newEvent->subscribers = NULL;
-	strcpy(newEvent->event, event);
-	addSubscriber(newEvent, handler);
-	events_t *tmp = event_findlast();
-	if (tmp)
-		tmp->next = newEvent;
-	else
-		firstEvent = newEvent;
+
+	events_t * subscribeEvent = event_find(event);
+	if(!subscribeEvent){//create new Event
+		subscribeEvent = (events_t *) malloc(sizeof(events_t));
+		if (!subscribeEvent)
+			logger_error("Not enough memory\n");
+		subscribeEvent->next = NULL;
+		subscribeEvent->subscribers = NULL;
+		strcpy(subscribeEvent->event, event);
+		events_t *tmp = event_findlast();
+		if (tmp)
+			tmp->next = subscribeEvent;
+		else
+			firstEvent = subscribeEvent;
+	}
+	addSubscriber(subscribeEvent, handler);
 	logger(V_HAL, "New subscriber to event \"%s\"\n", event);
 }
 
@@ -144,7 +148,7 @@ void event_trigger(event_t *event) {
 
 void event_trigger(char *event) {
 	event_t e;
-	e.event = event;
+	e.event = (const char *)event;
 	event_trigger(&e);
 }
 
@@ -155,7 +159,7 @@ void event_trigger(char *event) {
 
 void event_trigger(const char *event) {
 	event_t e;
-	e.event = (char*)event;
+	e.event = event;
 	event_trigger(&e);
 }
 
@@ -167,11 +171,7 @@ void event_trigger(const char *event) {
  */
 
 void event_trigger(char *event, void *data, int len) {
-	event_t e;
-	e.event = event;
-	e.data = data;
-	e.len = len;
-	event_trigger(&e);
+	event_trigger((const char *) event, data, len);
 }
 
 /**
@@ -182,6 +182,10 @@ void event_trigger(char *event, void *data, int len) {
  */
 
 void event_trigger(const char *event, void *data, int len) {
-	event_trigger((char *) event, data, len);
+	event_t e;
+	e.event = event;
+	e.data = data;
+	e.len = len;
+	event_trigger(&e);
 }
 

+ 1 - 1
CoffeeCode/events.h

@@ -11,7 +11,7 @@
 #define EVENT_LENGTH	20 /*< Maximum length of an event */
 
 struct event_t {
-	char *event;
+	const char *event;
 	void *data = NULL;
 	int len = 0;
 };