A simple fan daemon for OpenPOWER systems
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

96 lines
2.5 KiB

/**
* Copyright 2019 Shawn Anastasio
*
* This file is part of op-fan-daemon.
*
* op-fan-daemon is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* op-fan-daemon is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with op-fan-daemon. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Various utility functions
*/
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include "util.h"
#define vec_template(T) \
bool vec_ ## T ## _init(struct vec_ ## T *v, size_t initial_size, void (*destructor)(T)) { \
if (initial_size < 10) \
initial_size = 10; \
\
v->data = calloc(initial_size, sizeof(T)); \
if (!(v->data)) \
return false; \
\
v->size = initial_size; \
v->count = 0; \
v->destructor = destructor; \
return true; \
}; \
\
void vec_ ## T ## _push_back(struct vec_ ## T *v, T element) { \
if (v->size == v->count) { \
/* double array size */ \
size_t new_size = v->size * 2; \
void *new_data = realloc(v->data, new_size * sizeof(T)); \
assert(new_data); \
v->data = new_data; \
v->size = new_size; \
} \
/* insert element into array */ \
v->data[v->count++] = element; \
} \
\
T vec_ ## T ## _at(struct vec_ ## T *v, size_t i) { \
assert(i < v->count); \
return v->data[i]; \
} \
\
void vec_ ## T ## _remove(struct vec_ ## T *v, size_t i) { \
assert(i < v->count); \
\
if (v->destructor) \
v->destructor(v->data[i]); \
\
if (i != (v->count - 1)) \
memmove(v->data + i, v->data + i + 1, sizeof(T) * (v->count - i - 1)); \
v->count -= 1; \
} \
void vec_ ## T ## _destroy(struct vec_ ## T *v) { \
size_t s = v->count; \
while (s-- > 0) { \
vec_ ## T ## _remove(v, s); \
} \
free(v->data); \
} \
bool vec_ ## T ## _contains(struct vec_ ## T *v, T element, T ## _comparator comparator) { \
for (size_t i=0; i<v->count; i++) { \
if (!comparator(v->data[i], element)) \
return true; \
} \
return false; \
}
vec_template(voidp)
vec_template(int)
void close_destructor(int fd) {
close(fd);
}