Fumofumotris/source/io/input.c

70 lines
1.6 KiB
C
Raw Normal View History

#include "input.h"
2024-03-25 05:34:59 +00:00
#include <pthread.h>
2024-04-16 22:14:53 +00:00
#include "platform.h"
2024-03-25 05:34:59 +00:00
2024-04-19 06:38:45 +00:00
struct InputRecord *buf_get(struct InputBuffer *buf, size_t i) {
return buf->recs + (buf->start + i) % IO_BUF_SIZE;
}
size_t max_size(size_t a, size_t b) {
return a > b ? a : b;
2024-04-16 22:14:53 +00:00
}
2024-04-19 06:38:45 +00:00
void InputBufferTransfer(struct InputBuffer *dest, struct InputBuffer *src)
2024-04-16 22:14:53 +00:00
{
2024-04-19 06:38:45 +00:00
size_t copy_amt = IO_BUF_SIZE - max_size(dest->len, src->len);
2024-04-16 22:14:53 +00:00
2024-04-19 06:38:45 +00:00
for (size_t i = 0; i < copy_amt; i++)
*buf_get(dest, dest->len + i) = *buf_get(src, i);
2024-04-16 22:14:53 +00:00
2024-04-19 06:38:45 +00:00
if (copy_amt < src->len)
src->start += copy_amt;
2024-04-16 22:14:53 +00:00
2024-04-19 06:38:45 +00:00
src->len -= copy_amt;
dest->len += copy_amt;
2024-04-16 22:14:53 +00:00
}
2024-04-19 06:38:45 +00:00
void InputBufferAdd(struct InputBuffer *buf, struct InputRecord *rec)
2024-04-16 22:14:53 +00:00
{
2024-04-19 06:38:45 +00:00
*buf_get(buf, buf->len++) = *rec;
2024-04-16 22:14:53 +00:00
}
struct input_args {
struct InputBuffer *buf;
pthread_mutex_t *mutex;
};
2024-04-19 06:38:45 +00:00
void *input_thread_loop(struct input_args *args)
2024-04-16 22:14:53 +00:00
{
2024-04-18 05:04:44 +00:00
struct InputBuffer *buf = args->buf;
pthread_mutex_t *mutex = args->mutex;
free(args);
2024-04-16 22:14:53 +00:00
struct InputBuffer tmp_buf = { .len = 0, .start = 0 };
2024-04-01 22:39:21 +00:00
while (true) {
2024-04-16 22:14:53 +00:00
if (!PlatformReadInput(&tmp_buf))
2024-04-10 20:05:56 +00:00
return false;
2024-04-18 05:04:44 +00:00
pthread_mutex_lock(mutex);
2024-04-15 19:29:51 +00:00
{
2024-04-18 05:04:44 +00:00
InputBufferTransfer(&tmp_buf, buf);
2024-04-01 22:39:21 +00:00
}
2024-04-18 05:04:44 +00:00
pthread_mutex_unlock(mutex);
2024-04-01 22:39:21 +00:00
}
2024-03-25 05:34:59 +00:00
return nullptr;
}
2024-04-19 06:38:45 +00:00
bool CreateInputThread(struct InputBuffer *buf, pthread_mutex_t *mutex)
2024-03-25 05:34:59 +00:00
{
2024-04-18 05:04:44 +00:00
struct input_args *args = malloc(sizeof(struct input_args));
*args = (struct input_args) {
2024-04-16 22:14:53 +00:00
.buf = buf,
.mutex = mutex,
};
2024-04-18 05:04:44 +00:00
pthread_t thread;
2024-04-19 06:38:45 +00:00
return pthread_create(&thread, nullptr, input_thread_loop, args) == 0;
2024-03-25 05:34:59 +00:00
}