networking · advanced · ~40 min

fd_set–style bit tracker for multiplexed I/O

Bit-packed sets; bitwise add/remove with mask.

Challenge

Implement a fixed-capacity FD bitmap:

typedef struct fdset fdset_t;
fdset_t *fdset_create(int max_fd);   /* tracks FDs 0..max_fd inclusive */
void     fdset_add(fdset_t *s, int fd);
void     fdset_remove(fdset_t *s, int fd);
int      fdset_contains(fdset_t *s, int fd);
int      fdset_count(fdset_t *s);
void     fdset_destroy(fdset_t *s);

Use 32 FDs per uint32_t. fd_set_add on an out-of-range fd is a no-op.

Why this matters

select(2) uses an fd_set — a bitmap of file descriptor numbers. Implementing it teaches bitmap math and why epoll superseded select for high-FD-count servers.

Input format

max_fd >= 0; fd is int.

Output format

See API.

Constraints

Use (max_fd / 32) + 1 words. No loops in add/remove/contains (just bit math).

Starter code

typedef struct fdset fdset_t;
fdset_t *fdset_create(int max_fd);
void     fdset_add(fdset_t *s, int fd);
void     fdset_remove(fdset_t *s, int fd);
int      fdset_contains(fdset_t *s, int fd);
int      fdset_count(fdset_t *s);
void     fdset_destroy(fdset_t *s);

Common mistakes

Indexing past the bitmap on a large fd; using a signed type so the high bit shifts wrong; double-counting in count via a manual popcount with mismatched mask.

Edge cases to handle

add same fd twice — still counted once. remove of absent fd — no-op.

Complexity

O(1) add/remove/contains. O(words) count.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.