2 functions taken from samba4 for quick prototyping of ctdb. These are
3 not intended to remain part of ctdb
7 #include "system/time.h"
8 #include "system/filesys.h"
14 struct timeval timeval_zero(void)
23 return True if a timeval is zero
25 bool timeval_is_zero(const struct timeval *tv)
27 return tv->tv_sec == 0 && tv->tv_usec == 0;
31 return a timeval for the current time
33 struct timeval timeval_current(void)
36 gettimeofday(&tv, NULL);
41 return a timeval struct with the given elements
43 struct timeval timeval_set(uint32_t secs, uint32_t usecs)
51 int timeval_compare(const struct timeval *tv1, const struct timeval *tv2)
53 if (tv1->tv_sec > tv2->tv_sec) return 1;
54 if (tv1->tv_sec < tv2->tv_sec) return -1;
55 if (tv1->tv_usec > tv2->tv_usec) return 1;
56 if (tv1->tv_usec < tv2->tv_usec) return -1;
60 struct timeval timeval_until(const struct timeval *tv1,
61 const struct timeval *tv2)
64 if (timeval_compare(tv1, tv2) >= 0) {
65 return timeval_zero();
67 t.tv_sec = tv2->tv_sec - tv1->tv_sec;
68 if (tv1->tv_usec > tv2->tv_usec) {
70 t.tv_usec = 1000000 - (tv1->tv_usec - tv2->tv_usec);
72 t.tv_usec = tv2->tv_usec - tv1->tv_usec;
77 _PUBLIC_ struct timeval timeval_add(const struct timeval *tv,
78 uint32_t secs, uint32_t usecs)
80 struct timeval tv2 = *tv;
81 const unsigned int million = 1000000;
84 tv2.tv_sec += tv2.tv_usec / million;
85 tv2.tv_usec = tv2.tv_usec % million;
90 _PUBLIC_ struct timeval timeval_current_ofs(uint32_t secs, uint32_t usecs)
92 struct timeval tv = timeval_current();
93 return timeval_add(&tv, secs, usecs);
96 _PUBLIC_ char *fd_load(int fd, size_t *size, TALLOC_CTX *mem_ctx)
101 if (fstat(fd, &sbuf) != 0) return NULL;
103 p = (char *)talloc_size(mem_ctx, sbuf.st_size+1);
106 if (read(fd, p, sbuf.st_size) != sbuf.st_size) {
112 if (size) *size = sbuf.st_size;
118 _PUBLIC_ char *file_load(const char *fname, size_t *size, TALLOC_CTX *mem_ctx)
123 if (!fname || !*fname) return NULL;
125 fd = open(fname,O_RDONLY);
126 if (fd == -1) return NULL;
128 p = fd_load(fd, size, mem_ctx);
137 parse a buffer into lines
138 'p' will be freed on error, and otherwise will be made a child of the returned array
140 static char **file_lines_parse(char *p, size_t size, int *numlines, TALLOC_CTX *mem_ctx)
147 for (s = p, i=0; s < p+size; s++) {
148 if (s[0] == '\n') i++;
151 ret = talloc_array(mem_ctx, char *, i+2);
157 talloc_steal(ret, p);
159 memset(ret, 0, sizeof(ret[0])*(i+2));
160 if (numlines) *numlines = i;
163 for (s = p, i=0; s < p+size; s++) {
169 if (s[0] == '\r') s[0] = 0;
177 load a file into memory and return an array of pointers to lines in the file
178 must be freed with talloc_free().
180 _PUBLIC_ char **file_lines_load(const char *fname, int *numlines, TALLOC_CTX *mem_ctx)
185 p = file_load(fname, &size, mem_ctx);
188 return file_lines_parse(p, size, numlines, mem_ctx);