-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathporthelp.c
More file actions
101 lines (83 loc) · 2.39 KB
/
porthelp.c
File metadata and controls
101 lines (83 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* porthelp.c
*
* Created on: Jul 21, 2011
* Author: erich
* Description: Implements some tools that might come in handy when writing a port
*/
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include "porthelp.h"
typedef struct
{
handleType type;
void *pointer;
} HandleListEntry, *PHandleListEntry;
volatile HandleListEntry *HandleList;
int HandleList_max;
int CreateHandleFromPointer(void *p, handleType type)
{
if (HandleList==NULL)
{
//Initialize the handlelist
HandleList_max=4096 / sizeof(HandleListEntry); //allocate around the size of 4KB
HandleList=(PHandleListEntry)malloc(HandleList_max*4096);
memset((void *)HandleList, 0, sizeof(HandleListEntry)*256);
}
//find a empty handle spot, if none are found, relocate (shouldn't happen since ce doesn't open that many handles (of the type provided here), and tends to close them)
int i;
for (i=1; i<HandleList_max; i++) //start from 1, just sacrifice 0
{
if (HandleList[i].type==htEmpty)
{
HandleList[i].pointer=p;
HandleList[i].type=type;
return i;
}
}
//still here so not a single spot was free (wtf?)
i=HandleList_max;
HandleList_max=HandleList_max * 2;
HandleList=(PHandleListEntry)realloc((void *)HandleList, HandleList_max * sizeof(HandleListEntry));
memset((void *)&HandleList[i], 0, i); //zero the new block (i contains the old size which is the appended new size)
HandleList[i].pointer=p;
HandleList[i].type=type;
return i;
}
void *GetPointerFromHandle(int handle)
{
if ((handle>0) && (handle<HandleList_max) && (HandleList[handle].type != htEmpty))
return HandleList[handle].pointer;
else
return NULL;
}
handleType GetHandleType(int handle)
{
if ((handle>0) && (handle<HandleList_max))
return HandleList[handle].type;
else
return htEmpty;
}
void RemoveHandle(int handle)
{
if ((handle>0) && (handle<HandleList_max) && (HandleList[handle].type != htEmpty))
HandleList[handle].type=htEmpty;
}
int SearchHandleList(int type, HANDLESEARCHCALLBACK cb, void *searchdata)
/*
* go through the handle list and call cb(data, searchdata) for each handle of the specified type
* if cb(data,searchdata) returns true then return that handle, else return 0
*/
{
int i;
for (i=1; i<HandleList_max; i++)
{
if (HandleList[i].type==type)
{
if (cb(HandleList[i].pointer, searchdata))
return i;
}
}
return 0;
}