summaryrefslogtreecommitdiff
path: root/channel.c
blob: cab461291d174faa6b073f88e0a0c855d16ec0d0 (plain)
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
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#include "channel.h"

struct channel_t *channels;
int channel_count;

void channel_init() {
	channels = NULL;
	channel_count = 0;
}

struct channel_t *channel_add(const char *name) {
	channels = realloc(channels, ++channel_count * sizeof(struct regexset_t));
	if(!channels) {
		char *error = strerror(errno);
		fprintf(stderr, "Could not (re)allocate memory for channels: %s\n", error);
		return NULL;
	}
	struct channel_t *channel = &channels[channel_count-1];
	channel->name = strdup(name);
	channel->file_count = 0;
	channel->files = NULL;
	return channel;
}

int channel_set_file_count(struct channel_t *channel, int count) {
	channel->files = malloc(count * sizeof(struct channel_file_t));
	if(!channel->files) {
		char *error = strerror(errno);
		fprintf(stderr, "Could not allocate memory for channel files (%s): %s\n", channel->name, error);
		return 0;
	}
	channel->file_count = count;
	return 1;
}

int channel_set_file(struct channel_t *channel, int index, const char *path, int rs_index) {
	struct channel_file_t *file;
	/* Make sure index is in range. */
	if(!(index < channel->file_count))
		return 0;
	file = &channel->files[index];
	file->path = strdup(path);
	file->rs = rs_get(rs_index);
	/* Fail if we don't get a regex set. */
	if(!file->rs)
		return 0;
	return 1;
}

void channel_free() {
	for(int i = 0; i < channel_count; i++) {
		free(channels[i].name);
		/* Free all file path strings. */
		for(int j = 0; j < channels[i].file_count; j++) {
			free(channels[i].files[j].path);
		}
		/* 'files' is a dynamically allocated array, must be freed. */
		free(channels[i].files);
	}
	free(channels);
	channels = NULL;
}