summaryrefslogtreecommitdiffstats
path: root/pcp/pcpaddcommon.c
blob: d19f4d8daa009faa03a24f42fcb8686f2b88417e (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
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
/*
** Copyright 2001 Double Precision, Inc.  See COPYING for
** distribution information.
*/


#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include "pcp.h"

static int compar_times(const void *a, const void *b)
{
	const struct PCP_event_time *aa=*(const struct PCP_event_time **)a;
	const struct PCP_event_time *bb=*(const struct PCP_event_time **)b;

	return (aa->start < bb->start ? -1:
		aa->start > bb->start ? 1:
		aa->end < bb->end ? -1:
		aa->end > bb->end ? 1:0);
}

const struct PCP_event_time **
pcp_add_sort_times(const struct PCP_event_time *t,
		   unsigned n)
{
	const struct PCP_event_time **ptr;
	unsigned i;

	if (n == 0)
	{
		errno=EINVAL;
		return (NULL);
	}

	ptr=malloc(n*sizeof(const struct PCP_event_time *));
	if (!ptr)
		return (NULL);

	for (i=0; i<n; i++)
		ptr[i]=t+i;

	if (n)
		qsort(ptr, n, sizeof(*ptr),
		      compar_times);

	for (i=0; i<n; i++)
	{
		if (ptr[i]->start > ptr[i]->end)
		{
			free(ptr);
			errno=EINVAL;
			return (NULL);
		}

		if (i > 0 && ptr[i-1]->end > ptr[i]->start)
		{
			free(ptr);
			errno=EINVAL;
			return (NULL);
		}
	}

	return (ptr);
}

int pcp_read_saveevent(struct PCP_save_event *ae,
		       char *buf, int bufsize)
{
	int n;

	if (ae->write_event_func)
		return ( ((*ae->write_event_func)
			  (buf, bufsize, ae->write_event_func_misc_ptr)));

	if (!ae->write_event_buf && ae->write_event_fd >= 0)
		return ( read(ae->write_event_fd, buf, bufsize));

	if (ae->write_event_buf == 0)
	{
		errno=EIO;
		return (-1);
	}

	for (n=0; n<bufsize && *ae->write_event_buf; n++)
		buf[n]= *ae->write_event_buf++;

	return (n);
}