00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #ifndef TESSERACT_CCUTIL_HELPERS_H_
00026 #define TESSERACT_CCUTIL_HELPERS_H_
00027
00028 #include <stdio.h>
00029 #include <string.h>
00030
00031
00032 inline void chomp_string(char *str) {
00033 int last_index = strlen(str) - 1;
00034 if (str[last_index] == '\n') {
00035 str[last_index] = '\0';
00036 }
00037 }
00038
00039
00040 inline void SkipNewline(FILE *file) {
00041 if (fgetc(file) != '\n') fseek(file, -1, SEEK_CUR);
00042 }
00043
00044
00045 inline int sort_floats(const void *arg1, const void *arg2) {
00046 float diff = *((float *) arg1) - *((float *) arg2);
00047 if (diff > 0) {
00048 return 1;
00049 } else if (diff < 0) {
00050 return -1;
00051 } else {
00052 return 0;
00053 }
00054 }
00055
00056
00057 inline int RoundUp(int n, int block_size) {
00058 return block_size * ((n + block_size - 1) / block_size);
00059 }
00060
00061
00062 template<typename T>
00063 inline T ClipToRange(const T& x, const T& lower_bound, const T& upper_bound) {
00064 if (x < lower_bound)
00065 return lower_bound;
00066 if (x > upper_bound)
00067 return upper_bound;
00068 return x;
00069 }
00070
00071
00072 template<typename T1, typename T2>
00073 inline void UpdateRange(const T1& x, T2* lower_bound, T2* upper_bound) {
00074 if (x < *lower_bound)
00075 *lower_bound = x;
00076 if (x > *upper_bound)
00077 *upper_bound = x;
00078 }
00079
00080
00081 template<typename T1, typename T2>
00082 inline void UpdateRange(const T1& x_lo, const T1& x_hi,
00083 T2* lower_bound, T2* upper_bound) {
00084 if (x_lo < *lower_bound)
00085 *lower_bound = x_lo;
00086 if (x_hi > *upper_bound)
00087 *upper_bound = x_hi;
00088 }
00089
00090
00091
00092
00093 inline int Modulo(int a, int b) {
00094 return (a % b + b) % b;
00095 }
00096
00097
00098
00099
00100
00101
00102
00103 inline int DivRounded(int a, int b) {
00104 return a >= 0 ? (a + b / 2) / b : (a - b / 2) / b;
00105 }
00106
00107
00108 inline void ReverseN(void* ptr, int num_bytes) {
00109 char *cptr = reinterpret_cast<char *>(ptr);
00110 int halfsize = num_bytes / 2;
00111 for (int i = 0; i < halfsize; ++i) {
00112 char tmp = cptr[i];
00113 cptr[i] = cptr[num_bytes - 1 - i];
00114 cptr[num_bytes - 1 - i] = tmp;
00115 }
00116 }
00117
00118
00119 inline void Reverse16(void *ptr) {
00120 ReverseN(ptr, 2);
00121 }
00122
00123
00124 inline void Reverse32(void *ptr) {
00125 ReverseN(ptr, 4);
00126 }
00127
00128
00129 inline void Reverse64(void* ptr) {
00130 ReverseN(ptr, 8);
00131 }
00132
00133
00134 #endif // TESSERACT_CCUTIL_HELPERS_H_