2 * Copyright 2020-2021 Niklas Ekström
5 #include <proto/exec.h>
9 struct List active_sockets;
11 struct Socket *send_queue_head = NULL;
12 struct Socket *send_queue_tail = NULL;
14 static UBYTE next_stream_id = 1;
16 extern void NewList(struct List *l);
20 NewList(&active_sockets);
23 struct Socket *find_socket(void *sig_task, ULONG socket)
25 for (struct Node *node = active_sockets.lh_Head; node->ln_Succ != NULL; node = node->ln_Succ)
27 struct Socket *s = (struct Socket *)node;
28 if (s->sig_task == sig_task && s->socket == socket)
34 struct Socket *find_socket_by_stream_id(UBYTE stream_id)
36 for (struct Node *node = active_sockets.lh_Head; node->ln_Succ != NULL; node = node->ln_Succ)
38 struct Socket *s = (struct Socket *)node;
39 if (s->stream_id == stream_id)
45 static UBYTE allocate_stream_id()
47 // Bug: If all stream ids are allocated then this loop won't terminate.
51 UBYTE stream_id = next_stream_id;
53 if (find_socket_by_stream_id(stream_id) == NULL)
58 static void free_stream_id(UBYTE stream_id)
60 // Currently do nothing.
61 // Could speed up allocate_stream_id using a bitmap?
64 struct Socket *create_socket(struct Task *task, ULONG id)
66 struct Socket *s = (struct Socket *)AllocMem(sizeof(struct Socket), MEMF_CLEAR);
69 s->stream_id = allocate_stream_id();
70 AddTail(&active_sockets, (struct Node *)s);
74 void delete_socket(struct Socket *s)
76 Remove((struct Node *)s);
77 free_stream_id(s->stream_id);
78 FreeMem(s, sizeof(struct Socket));
81 void add_to_send_queue(struct Socket *s, UWORD required_length)
83 s->send_queue_required_length = required_length;
84 s->next_in_send_queue = NULL;
86 if (send_queue_head == NULL)
89 send_queue_tail->next_in_send_queue = s;
92 s->flags |= SOCKET_IN_SEND_QUEUE;
95 void remove_from_send_queue(struct Socket *s)
97 if (s->flags & SOCKET_IN_SEND_QUEUE)
99 if (send_queue_head == s)
101 send_queue_head = s->next_in_send_queue;
102 if (send_queue_head == NULL)
103 send_queue_tail = NULL;
107 struct Socket *curr = send_queue_head;
108 while (curr->next_in_send_queue != s)
109 curr = curr->next_in_send_queue;
111 curr->next_in_send_queue = s->next_in_send_queue;
112 if (send_queue_tail == s)
113 send_queue_tail = curr;
116 s->next_in_send_queue = NULL;
117 s->flags &= ~SOCKET_IN_SEND_QUEUE;