File: history.c

package info (click to toggle)
fence-virt 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 772 kB
  • sloc: ansic: 10,257; cpp: 382; makefile: 272; sh: 214; lex: 113; yacc: 105
file content (124 lines) | stat: -rw-r--r-- 2,009 bytes parent folder | download
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "config.h"

#include <stdio.h>
#include <malloc.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <list.h>
#include <time.h>

#include "history.h"

history_info_t *
history_init(history_compare_fn func, time_t expiration, size_t element_size)
{
	history_info_t *hist;

	errno = EINVAL;
	if (!func || !expiration || !element_size)
		return NULL;

	hist = malloc(sizeof(*hist));
	if (!hist)
		return NULL;
	memset(hist, 0, sizeof(*hist));

	hist->timeout = expiration;
	hist->element_size = element_size;
	hist->compare_func = func;

	return hist;
}


/*
 * Purge our history when the entries time out.
 *
 * Returns 1 if a matching history node was found, or 0
 * if not. 
 */
int
history_check(history_info_t *hinfo, void *stuff)
{
	history_node *entry = NULL;
	time_t now;
	int x;

	if (!hinfo)
		return 0; /* XXX */

	if (!hinfo->hist)
		return 0;

	now = time(NULL);

loop_again:
	list_for((&hinfo->hist), entry, x) {
		if (entry->when < (now - hinfo->timeout)) {
			list_remove((&hinfo->hist), entry);
			free(entry->data);
			free(entry);
			goto loop_again;
		}

		if (hinfo->compare_func(entry->data, stuff)) {
			return 1;
		}
	}
	return 0;
}


int
history_record(history_info_t *hinfo, void *data)
{
	history_node *entry = NULL;

	errno = EINVAL;
	if (!data || !hinfo)
		return -1;

	if (history_check(hinfo, data) == 1) {
		errno = EEXIST;
		return -1;
	}

	entry = malloc(sizeof(*entry));
	if (!entry) {
		return -1;
	}
	memset(entry, 0, sizeof(*entry));

	entry->data = malloc(hinfo->element_size);
	if (!entry->data) {
		free(entry);
		errno = ENOMEM;
		return -1;
	}

	memcpy(entry->data, data, hinfo->element_size);
	entry->when = time(NULL);
	list_insert((&hinfo->hist), entry);
	return 0;
}


int
history_wipe(history_info_t *hinfo)
{
	history_node *entry = NULL;

	if (!hinfo)
		return -1;

	while (hinfo->hist) {
		entry = hinfo->hist;
		list_remove((&hinfo->hist), entry);
		free(entry->data);
		free(entry);
	}

	/* User must free(hinfo); */
	return 0;
}