tesseract 5.2.0
Loading...
Searching...
No Matches
helpers.h
Go to the documentation of this file.
1/******************************************************************************
2 *
3 * File: helpers.h
4 * Description: General utility functions
5 * Author: Daria Antonova
6 *
7 * (c) Copyright 2009, Google Inc.
8 ** Licensed under the Apache License, Version 2.0 (the "License");
9 ** you may not use this file except in compliance with the License.
10 ** You may obtain a copy of the License at
11 ** http://www.apache.org/licenses/LICENSE-2.0
12 ** Unless required by applicable law or agreed to in writing, software
13 ** distributed under the License is distributed on an "AS IS" BASIS,
14 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 ** See the License for the specific language governing permissions and
16 ** limitations under the License.
17 *
18 *****************************************************************************/
19
20#ifndef TESSERACT_CCUTIL_HELPERS_H_
21#define TESSERACT_CCUTIL_HELPERS_H_
22
23#include <cassert>
24#include <climits> // for INT_MIN, INT_MAX
25#include <cmath> // std::isfinite
26#include <cstdio>
27#include <cstring>
28#include <algorithm> // for std::find
29#include <functional>
30#include <random>
31#include <string>
32#include <vector>
33
34namespace tesseract {
35
36template <class T>
37inline bool contains(const std::vector<T> &data, const T &value) {
38 return std::find(data.begin(), data.end(), value) != data.end();
39}
40
41inline const std::vector<std::string> split(const std::string &s, char c) {
42 std::string buff;
43 std::vector<std::string> v;
44 for (auto n : s) {
45 if (n != c) {
46 buff += n;
47 } else if (n == c && !buff.empty()) {
48 v.push_back(buff);
49 buff.clear();
50 }
51 }
52 if (!buff.empty()) {
53 v.push_back(buff);
54 }
55 return v;
56}
57
58// A simple linear congruential random number generator.
59class TRand {
60public:
61 // Sets the seed to the given value.
62 void set_seed(uint64_t seed) {
63 e.seed(seed);
64 }
65 // Sets the seed using a hash of a string.
66 void set_seed(const std::string &str) {
67 std::hash<std::string> hasher;
68 set_seed(static_cast<uint64_t>(hasher(str)));
69 }
70
71 // Returns an integer in the range 0 to INT32_MAX.
72 int32_t IntRand() {
73 return e();
74 }
75 // Returns a floating point value in the range [-range, range].
76 double SignedRand(double range) {
77 return range * 2.0 * IntRand() / INT32_MAX - range;
78 }
79 // Returns a floating point value in the range [0, range].
80 double UnsignedRand(double range) {
81 return range * IntRand() / INT32_MAX;
82 }
83
84private:
85 std::minstd_rand e;
86};
87
88// Remove newline (if any) at the end of the string.
89inline void chomp_string(char *str) {
90 int last_index = static_cast<int>(strlen(str)) - 1;
91 while (last_index >= 0 && (str[last_index] == '\n' || str[last_index] == '\r')) {
92 str[last_index--] = '\0';
93 }
94}
95
96// return the smallest multiple of block_size greater than or equal to n.
97inline int RoundUp(int n, int block_size) {
98 return block_size * ((n + block_size - 1) / block_size);
99}
100
101// Clip a numeric value to the interval [lower_bound, upper_bound].
102template <typename T>
103inline T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound) {
104 if (x < lower_bound) {
105 return lower_bound;
106 }
107 if (x > upper_bound) {
108 return upper_bound;
109 }
110 return x;
111}
112
113// Extend the range [lower_bound, upper_bound] to include x.
114template <typename T1, typename T2>
115inline void UpdateRange(const T1 &x, T2 *lower_bound, T2 *upper_bound) {
116 if (x < *lower_bound) {
117 *lower_bound = x;
118 }
119 if (x > *upper_bound) {
120 *upper_bound = x;
121 }
122}
123
124// Decrease lower_bound to be <= x_lo AND increase upper_bound to be >= x_hi.
125template <typename T1, typename T2>
126inline void UpdateRange(const T1 &x_lo, const T1 &x_hi, T2 *lower_bound, T2 *upper_bound) {
127 if (x_lo < *lower_bound) {
128 *lower_bound = x_lo;
129 }
130 if (x_hi > *upper_bound) {
131 *upper_bound = x_hi;
132 }
133}
134
135// Intersect the range [*lower2, *upper2] with the range [lower1, upper1],
136// putting the result back in [*lower2, *upper2].
137// If non-intersecting ranges are given, we end up with *lower2 > *upper2.
138template <typename T>
139inline void IntersectRange(const T &lower1, const T &upper1, T *lower2, T *upper2) {
140 if (lower1 > *lower2) {
141 *lower2 = lower1;
142 }
143 if (upper1 < *upper2) {
144 *upper2 = upper1;
145 }
146}
147
148// Proper modulo arithmetic operator. Returns a mod b that works for -ve a.
149// For any integer a and positive b, returns r : 0<=r<b and a=n*b + r for
150// some integer n.
151inline int Modulo(int a, int b) {
152 return (a % b + b) % b;
153}
154
155// Integer division operator with rounding that works for negative input.
156// Returns a divided by b, rounded to the nearest integer, without double
157// counting at 0. With simple rounding 1/3 = 0, 0/3 = 0 -1/3 = 0, -2/3 = 0,
158// -3/3 = 0 and -4/3 = -1.
159// I want 1/3 = 0, 0/3 = 0, -1/3 = 0, -2/3 = -1, -3/3 = -1 and -4/3 = -1.
160inline int DivRounded(int a, int b) {
161 if (b < 0) {
162 return -DivRounded(a, -b);
163 }
164 return a >= 0 ? (a + b / 2) / b : (a - b / 2) / b;
165}
166
167// Return a double cast to int with rounding.
168inline int IntCastRounded(double x) {
169 assert(std::isfinite(x));
170 assert(x < INT_MAX);
171 assert(x > INT_MIN);
172 return x >= 0.0 ? static_cast<int>(x + 0.5) : -static_cast<int>(-x + 0.5);
173}
174
175// Return a float cast to int with rounding.
176inline int IntCastRounded(float x) {
177 assert(std::isfinite(x));
178 return x >= 0.0F ? static_cast<int>(x + 0.5F) : -static_cast<int>(-x + 0.5F);
179}
180
181// Reverse the order of bytes in a n byte quantity for big/little-endian switch.
182inline void ReverseN(void *ptr, int num_bytes) {
183 assert(num_bytes == 1 || num_bytes == 2 || num_bytes == 4 || num_bytes == 8);
184 char *cptr = static_cast<char *>(ptr);
185 int halfsize = num_bytes / 2;
186 for (int i = 0; i < halfsize; ++i) {
187 char tmp = cptr[i];
188 cptr[i] = cptr[num_bytes - 1 - i];
189 cptr[num_bytes - 1 - i] = tmp;
190 }
191}
192
193// Reverse the order of bytes in a 32 bit quantity for big/little-endian switch.
194inline void Reverse32(void *ptr) {
195 ReverseN(ptr, 4);
196}
197
198// Reads a vector of simple types from the given file. Assumes that bitwise
199// read/write will work with ReverseN according to sizeof(T).
200// Returns false in case of error.
201// If swap is true, assumes a big/little-endian swap is needed.
202template <typename T>
203bool DeSerialize(bool swap, FILE *fp, std::vector<T> &data) {
204 uint32_t size;
205 if (fread(&size, sizeof(size), 1, fp) != 1) {
206 return false;
207 }
208 if (swap) {
209 Reverse32(&size);
210 }
211 // Arbitrarily limit the number of elements to protect against bad data.
212 assert(size <= UINT16_MAX);
213 if (size > UINT16_MAX) {
214 return false;
215 }
216 // TODO: optimize.
217 data.resize(size);
218 if (size > 0) {
219 if (fread(&data[0], sizeof(T), size, fp) != size) {
220 return false;
221 }
222 if (swap) {
223 for (uint32_t i = 0; i < size; ++i) {
224 ReverseN(&data[i], sizeof(T));
225 }
226 }
227 }
228 return true;
229}
230
231// Writes a vector of simple types to the given file. Assumes that bitwise
232// read/write of T will work. Returns false in case of error.
233template <typename T>
234bool Serialize(FILE *fp, const std::vector<T> &data) {
235 uint32_t size = data.size();
236 if (fwrite(&size, sizeof(size), 1, fp) != 1) {
237 return false;
238 } else if constexpr (std::is_class<T>::value) {
239 // Serialize a tesseract class.
240 for (auto &item : data) {
241 if (!item.Serialize(fp)) {
242 return false;
243 }
244 }
245 } else if (size > 0) {
246 if (fwrite(&data[0], sizeof(T), size, fp) != size) {
247 return false;
248 }
249 }
250 return true;
251}
252
253} // namespace tesseract
254
255#endif // TESSERACT_CCUTIL_HELPERS_H_
@ T1
Definition: rune.c:27
@ T2
Definition: rune.c:29
void ReverseN(void *ptr, int num_bytes)
Definition: helpers.h:182
int IntCastRounded(double x)
Definition: helpers.h:168
int DivRounded(int a, int b)
Definition: helpers.h:160
bool DeSerialize(bool swap, FILE *fp, std::vector< T > &data)
Definition: helpers.h:203
void chomp_string(char *str)
Definition: helpers.h:89
bool Serialize(FILE *fp, const std::vector< T > &data)
Definition: helpers.h:234
int RoundUp(int n, int block_size)
Definition: helpers.h:97
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:103
void IntersectRange(const T &lower1, const T &upper1, T *lower2, T *upper2)
Definition: helpers.h:139
void UpdateRange(const T1 &x, T2 *lower_bound, T2 *upper_bound)
Definition: helpers.h:115
void Reverse32(void *ptr)
Definition: helpers.h:194
const std::vector< std::string > split(const std::string &s, char c)
Definition: helpers.h:41
bool contains(const std::vector< T > &data, const T &value)
Definition: helpers.h:37
int Modulo(int a, int b)
Definition: helpers.h:151
void set_seed(const std::string &str)
Definition: helpers.h:66
double SignedRand(double range)
Definition: helpers.h:76
int32_t IntRand()
Definition: helpers.h:72
double UnsignedRand(double range)
Definition: helpers.h:80
void set_seed(uint64_t seed)
Definition: helpers.h:62