/* -*- 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 #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; static int messageq_last_free; void messageq_init(void) { int i; messageq_index = 0; messageq_serial = 0; messageq_last_free = 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) { int i; i = messageq_index; while (messageq[i].recipient != recipient && i != (messageq_index -1)) { i = (i < MAX_MESSAGES -1) ? i +1 : 0; } /* * We found the message for our recipient. We'll now set the recipient field to 0 since the recipient * should know the message was for him, he asked for it. This is needed to prefent the above loop * to find the same message again, since the message will stay alive in the system until its expired. */ messageq[i].recipient = MESSAGE_NONE; return &messageq[i]; } 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; }