Minor syntactical changes for readability.
[xuni.git] / src / utility.c
blob593aae61e32d61fcb8a29a664289afd219e971fb
1 /*! \file utility.c
3 */
5 #include <stdlib.h>
6 #include <string.h>
8 #include "utility.h"
10 func_point_t string_to_function(const struct string_function_t *data,
11 size_t n, const char *find) {
13 size_t mid = (size_t)-1, first = 0, last = n - 1;
14 int compare;
16 if(!find) return 0;
18 while(first <= last && last != (size_t)-1) {
19 mid = (first + last) / 2;
21 compare = strcmp(find, data[mid].str);
23 if(compare < 0) {
24 last = mid - 1;
26 else if(compare > 0) {
27 first = mid + 1;
29 else {
30 return data[mid].data;
34 return 0;
37 size_t string_to_index(const struct string_index_t *str, size_t n,
38 const char *find) {
40 size_t mid = (size_t)-1, first = 0, last = n - 1;
41 int compare;
43 if(!find) return (size_t)-1;
45 while(first <= last && last != (size_t)-1) {
46 mid = (first + last) / 2;
48 compare = strcmp(find, str[mid].str);
50 if(compare < 0) {
51 last = mid - 1;
53 else if(compare > 0) {
54 first = mid + 1;
56 else {
57 return str[mid].index;
61 return (size_t)-1;
64 double degrees_to_radians(double angle) {
65 return angle * CONSTANT_PI / 180.0;
68 double radians_to_degrees(double angle) {
69 return angle * 180.0 / CONSTANT_PI;
72 /*! Finds the position in which \a find is located in the array \a data, or,
73 if it is not present, the "closest" place. The closest place is the
74 position of the last element that is smaller than \a find. It is used as
75 the place to insert the element \a find.
77 Useful for binary insertion sorts.
79 \param data The array of elements to search for \a find for.
80 \param n The number of elements in \a data.
81 \param find The memory block to search for.
82 \param pos Set to the actual or closest position of \a data within the
83 memory structure.
84 \param compare The function to call to compare two elements in \a data.
85 Must return a negative number, 0, or a positive number based on the
86 parameters, just like \c strcmp().
87 \return True if \a find is actually present in \a data, false otherwise.
88 Note that if \a find is not present, \a pos will still be set.
90 int binary_insertion_sort(void *data, size_t n, void *find, size_t *pos,
91 int (*compare)(void *data, size_t n, void *find)) {
93 size_t mid = (size_t)-1, first = 0, last = n - 1;
94 int c = -1;
96 *pos = 0;
98 if(!n) return 0;
100 while(first <= last && last != (size_t)-1) {
101 mid = (first + last) / 2;
103 c = (*compare)(data, mid, find);
105 if(c < 0) {
106 last = mid - 1;
108 else if(c > 0) {
109 first = mid + 1;
111 else {
112 *pos = mid;
113 return 1;
117 if(c < 0) {
118 *pos = mid;
120 else {
121 *pos = mid + 1;
124 return 0;
127 int set_bit(int original, int bit, int set) {
128 if(set) {
129 original |= bit;
131 else {
132 original &= ~bit;
135 return original;
138 void set_bit_p(int *original, int bit, int set) {
139 *original = set_bit(*original, bit, set);