/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 2; tab-width: 2 -*- */ /* * message_queue.c * Copyright (C) Oliver 2008 * * main.c is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * main.c is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #ifdef G_OS_WIN32 #define WIN32_LEAN_AND_MEAN 1 #include #else #define FALSE 0 #define TRUE !FALSE #endif #include #include #include #include "message_queue.h" #define MAX_MESSAGES MESSAGE_WINDOW_SIZE struct messageq_s messageq[MAX_MESSAGES]; static int messageq_index, messageq_serial; void messageq_init(void) { int i; messageq_index = 0; messageq_serial = 0; for( i = 0; i < MAX_MESSAGES; i++) { messageq[i].sender = 0; messageq[i].recipient = 0; messageq[i].payload = NULL; messageq[i].payload_size = 0; } } static void msgcpy(struct messageq_s *dest, const struct messageq_s *src) { dest->sender = src->sender; dest->recipient = src->recipient; dest->payload = (void *)malloc(src->payload_size); memcpy(dest->payload, src->payload, src->payload_size); dest->payload_size = src->payload_size; } static void msgfree(int index) { messageq[index].sender = 0; messageq[index].recipient = 0; free(messageq[index].payload); messageq[index].payload_size = 0; } struct messageq_s *messageq_get(int recipient) { struct messageq_s *return_value; int i, message_found; message_found = FALSE; i = messageq_index; do { i = (i < MAX_MESSAGES -1) ? i +1 : 0; if (messageq[i].recipient & recipient) { message_found++; //printf("message[%d].recp = %d (messageq_index= %d)\n", i, messageq[i].recipient, messageq_index); //printf("Message found! %d\n", message_found); } } while ((i != (messageq_index)) && (!message_found)); /* * We found the message for our recipient. We'll now substract the recipient field since the recipient * should not look at this field. This is needed to so that multi-recipients can still read messages, and * to make sure the loop above is able to end. Since the message will stay alive in the system until its expired, * anybody (in that is a recepient) can still read it. */ if (message_found) { messageq[i].recipient -= recipient; return_value = &messageq[i]; } else { return_value = NULL; } return return_value; } void messageq_send(struct messageq_s *message) { /* Before sending the message, we clean out old cruft. We do this here * since we will be overwriting the contens of the message here anyway. */ msgfree(messageq_index); msgcpy(&messageq[messageq_index], message); messageq_index = ++messageq_serial %MAX_MESSAGES; }