112 lines
2.0 KiB
C
112 lines
2.0 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include "tree.h"
|
|
|
|
struct descriptor {
|
|
int fd;
|
|
SPLAY_ENTRY(descriptor) entry;
|
|
};
|
|
|
|
int descriptor_cmp(struct descriptor *a, struct descriptor *b);
|
|
|
|
SPLAY_HEAD(descriptors, descriptor);
|
|
SPLAY_PROTOTYPE(descriptors, descriptor, entry, descriptor_cmp);
|
|
SPLAY_GENERATE(descriptors, descriptor, entry, descriptor_cmp);
|
|
|
|
struct descriptors entries;
|
|
|
|
int descriptor_cmp(struct descriptor *a, struct descriptor *b)
|
|
{
|
|
if (a->fd < b->fd)
|
|
return -1;
|
|
if (a->fd > b->fd)
|
|
return 1;
|
|
|
|
return 0;
|
|
}
|
|
|
|
void add(int fd)
|
|
{
|
|
struct descriptor *des = malloc(sizeof *des);
|
|
des->fd = fd;
|
|
SPLAY_INSERT(descriptors, &entries, des);
|
|
}
|
|
|
|
|
|
void find(int fd)
|
|
{
|
|
struct descriptor des;
|
|
struct descriptor *found;
|
|
|
|
des.fd = fd;
|
|
found = SPLAY_FIND(descriptors, &entries, &des);
|
|
|
|
if (found == NULL)
|
|
printf("Not found fd %d\n", fd);
|
|
else
|
|
printf("Found fd %d (%d)\n", found->fd, fd);
|
|
}
|
|
|
|
void rem(int fd)
|
|
{
|
|
struct descriptor des;
|
|
|
|
des.fd = fd;
|
|
SPLAY_REMOVE(descriptors, &entries, &des);
|
|
}
|
|
|
|
void iter(void){
|
|
struct descriptor *bd;
|
|
SPLAY_FOREACH(bd, descriptors, &entries) {
|
|
printf("foreach fd %d\n", bd->fd);
|
|
}
|
|
}
|
|
|
|
void rem_iter(void){
|
|
struct descriptor *bd;
|
|
|
|
while (!SPLAY_EMPTY(&entries)) {
|
|
bd = SPLAY_ROOT(&entries);
|
|
SPLAY_REMOVE(descriptors, &entries, bd);
|
|
printf("removed fd %d\n", bd->fd);
|
|
free(bd);
|
|
}
|
|
}
|
|
|
|
void fd_min_max(void)
|
|
{
|
|
struct descriptor *min_des, *max_des;
|
|
|
|
min_des = SPLAY_MIN(descriptors, &entries);
|
|
max_des = SPLAY_MAX(descriptors, &entries);
|
|
|
|
if (min_des && max_des)
|
|
printf("min fd = %d max fd = %d\n", min_des->fd, max_des->fd);
|
|
|
|
}
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
SPLAY_INIT(&entries);
|
|
add(3);
|
|
add(4);
|
|
add(5);
|
|
add(11);
|
|
add(64);
|
|
add(9);
|
|
add(12);
|
|
|
|
find(11);
|
|
find(13);
|
|
|
|
rem(11);
|
|
find(11);
|
|
fd_min_max();
|
|
iter();
|
|
rem_iter();
|
|
fd_min_max();
|
|
|
|
|
|
return 0;
|
|
}
|