tesseract  3.05.00
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
genericvector.h
Go to the documentation of this file.
1 // File: genericvector.h
3 // Description: Generic vector class
4 // Author: Daria Antonova
5 // Created: Mon Jun 23 11:26:43 PDT 2008
6 //
7 // (C) Copyright 2007, 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 //
19 //
20 #ifndef TESSERACT_CCUTIL_GENERICVECTOR_H_
21 #define TESSERACT_CCUTIL_GENERICVECTOR_H_
22 
23 #include <assert.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 
27 #include "tesscallback.h"
28 #include "errcode.h"
29 #include "helpers.h"
30 #include "ndminx.h"
31 #include "serialis.h"
32 #include "strngs.h"
33 
34 // Use PointerVector<T> below in preference to GenericVector<T*>, as that
35 // provides automatic deletion of pointers, [De]Serialize that works, and
36 // sort that works.
37 template <typename T>
38 class GenericVector {
39  public:
42  }
43  GenericVector(int size, T init_val) {
44  init(size);
45  init_to_size(size, init_val);
46  }
47 
48  // Copy
49  GenericVector(const GenericVector& other) {
50  this->init(other.size());
51  this->operator+=(other);
52  }
55 
57 
58  // Reserve some memory.
59  void reserve(int size);
60  // Double the size of the internal array.
61  void double_the_size();
62 
63  // Resizes to size and sets all values to t.
64  void init_to_size(int size, T t);
65  // Resizes to size without any initialization.
66  void resize_no_init(int size) {
67  reserve(size);
68  size_used_ = size;
69  }
70 
71  // Return the size used.
72  int size() const {
73  return size_used_;
74  }
75  int size_reserved() const {
76  return size_reserved_;
77  }
78 
79  int length() const {
80  return size_used_;
81  }
82 
83  // Return true if empty.
84  bool empty() const {
85  return size_used_ == 0;
86  }
87 
88  // Return the object from an index.
89  T &get(int index) const;
90  T &back() const;
91  T &operator[](int index) const;
92  // Returns the last object and removes it.
93  T pop_back();
94 
95  // Return the index of the T object.
96  // This method NEEDS a compare_callback to be passed to
97  // set_compare_callback.
98  int get_index(T object) const;
99 
100  // Return true if T is in the array
101  bool contains(T object) const;
102 
103  // Return true if the index is valid
104  T contains_index(int index) const;
105 
106  // Push an element in the end of the array
107  int push_back(T object);
108  void operator+=(T t);
109 
110  // Push an element in the end of the array if the same
111  // element is not already contained in the array.
112  int push_back_new(T object);
113 
114  // Push an element in the front of the array
115  // Note: This function is O(n)
116  int push_front(T object);
117 
118  // Set the value at the given index
119  void set(T t, int index);
120 
121  // Insert t at the given index, push other elements to the right.
122  void insert(T t, int index);
123 
124  // Removes an element at the given index and
125  // shifts the remaining elements to the left.
126  void remove(int index);
127 
128  // Truncates the array to the given size by removing the end.
129  // If the current size is less, the array is not expanded.
130  void truncate(int size) {
131  if (size < size_used_)
132  size_used_ = size;
133  }
134 
135  // Add a callback to be called to delete the elements when the array took
136  // their ownership.
138 
139  // Add a callback to be called to compare the elements when needed (contains,
140  // get_id, ...)
142 
143  // Clear the array, calling the clear callback function if any.
144  // All the owned callbacks are also deleted.
145  // If you don't want the callbacks to be deleted, before calling clear, set
146  // the callback to NULL.
147  void clear();
148 
149  // Delete objects pointed to by data_[i]
150  void delete_data_pointers();
151 
152  // This method clears the current object, then, does a shallow copy of
153  // its argument, and finally invalidates its argument.
154  // Callbacks are moved to the current object;
155  void move(GenericVector<T>* from);
156 
157  // Read/Write the array to a file. This does _NOT_ read/write the callbacks.
158  // The callback given must be permanent since they will be called more than
159  // once. The given callback will be deleted at the end.
160  // If the callbacks are NULL, then the data is simply read/written using
161  // fread (and swapping)/fwrite.
162  // Returns false on error or if the callback returns false.
163  // DEPRECATED. Use [De]Serialize[Classes] instead.
164  bool write(FILE* f, TessResultCallback2<bool, FILE*, T const &>* cb) const;
165  bool read(FILE* f, TessResultCallback3<bool, FILE*, T*, bool>* cb, bool swap);
166  // Writes a vector of simple types to the given file. Assumes that bitwise
167  // read/write of T will work. Returns false in case of error.
168  // TODO(rays) Change all callers to use TFile and remove deprecated methods.
169  bool Serialize(FILE* fp) const;
170  bool Serialize(tesseract::TFile* fp) const;
171  // Reads a vector of simple types from the given file. Assumes that bitwise
172  // read/write will work with ReverseN according to sizeof(T).
173  // Returns false in case of error.
174  // If swap is true, assumes a big/little-endian swap is needed.
175  bool DeSerialize(bool swap, FILE* fp);
176  bool DeSerialize(bool swap, tesseract::TFile* fp);
177  // Skips the deserialization of the vector.
178  static bool SkipDeSerialize(bool swap, tesseract::TFile* fp);
179  // Writes a vector of classes to the given file. Assumes the existence of
180  // bool T::Serialize(FILE* fp) const that returns false in case of error.
181  // Returns false in case of error.
182  bool SerializeClasses(FILE* fp) const;
183  bool SerializeClasses(tesseract::TFile* fp) const;
184  // Reads a vector of classes from the given file. Assumes the existence of
185  // bool T::Deserialize(bool swap, FILE* fp) that returns false in case of
186  // error. Also needs T::T() and T::T(constT&), as init_to_size is used in
187  // this function. Returns false in case of error.
188  // If swap is true, assumes a big/little-endian swap is needed.
189  bool DeSerializeClasses(bool swap, FILE* fp);
190  bool DeSerializeClasses(bool swap, tesseract::TFile* fp);
191  // Calls SkipDeSerialize on the elements of the vector.
192  static bool SkipDeSerializeClasses(bool swap, tesseract::TFile* fp);
193 
194  // Allocates a new array of double the current_size, copies over the
195  // information from data to the new location, deletes data and returns
196  // the pointed to the new larger array.
197  // This function uses memcpy to copy the data, instead of invoking
198  // operator=() for each element like double_the_size() does.
199  static T *double_the_size_memcpy(int current_size, T *data) {
200  T *data_new = new T[current_size * 2];
201  memcpy(data_new, data, sizeof(T) * current_size);
202  delete[] data;
203  return data_new;
204  }
205 
206  // Reverses the elements of the vector.
207  void reverse() {
208  for (int i = 0; i < size_used_ / 2; ++i)
209  Swap(&data_[i], &data_[size_used_ - 1 - i]);
210  }
211 
212  // Sorts the members of this vector using the less than comparator (cmp_lt),
213  // which compares the values. Useful for GenericVectors to primitive types.
214  // Will not work so great for pointers (unless you just want to sort some
215  // pointers). You need to provide a specialization to sort_cmp to use
216  // your type.
217  void sort();
218 
219  // Sort the array into the order defined by the qsort function comparator.
220  // The comparator function is as defined by qsort, ie. it receives pointers
221  // to two Ts and returns negative if the first element is to appear earlier
222  // in the result and positive if it is to appear later, with 0 for equal.
223  void sort(int (*comparator)(const void*, const void*)) {
224  qsort(data_, size_used_, sizeof(*data_), comparator);
225  }
226 
227  // Searches the array (assuming sorted in ascending order, using sort()) for
228  // an element equal to target and returns true if it is present.
229  // Use binary_search to get the index of target, or its nearest candidate.
230  bool bool_binary_search(const T& target) const {
231  int index = binary_search(target);
232  if (index >= size_used_)
233  return false;
234  return data_[index] == target;
235  }
236  // Searches the array (assuming sorted in ascending order, using sort()) for
237  // an element equal to target and returns the index of the best candidate.
238  // The return value is conceptually the largest index i such that
239  // data_[i] <= target or 0 if target < the whole vector.
240  // NOTE that this function uses operator> so really the return value is
241  // the largest index i such that data_[i] > target is false.
242  int binary_search(const T& target) const {
243  int bottom = 0;
244  int top = size_used_;
245  while (top - bottom > 1) {
246  int middle = (bottom + top) / 2;
247  if (data_[middle] > target)
248  top = middle;
249  else
250  bottom = middle;
251  }
252  return bottom;
253  }
254 
255  // Compact the vector by deleting elements using operator!= on basic types.
256  // The vector must be sorted.
257  void compact_sorted() {
258  if (size_used_ == 0)
259  return;
260 
261  // First element is in no matter what, hence the i = 1.
262  int last_write = 0;
263  for (int i = 1; i < size_used_; ++i) {
264  // Finds next unique item and writes it.
265  if (data_[last_write] != data_[i])
266  data_[++last_write] = data_[i];
267  }
268  // last_write is the index of a valid data cell, so add 1.
269  size_used_ = last_write + 1;
270  }
271 
272  // Compact the vector by deleting elements for which delete_cb returns
273  // true. delete_cb is a permanent callback and will be deleted.
275  int new_size = 0;
276  int old_index = 0;
277  // Until the callback returns true, the elements stay the same.
278  while (old_index < size_used_ && !delete_cb->Run(old_index++))
279  ++new_size;
280  // Now just copy anything else that gets false from delete_cb.
281  for (; old_index < size_used_; ++old_index) {
282  if (!delete_cb->Run(old_index)) {
283  data_[new_size++] = data_[old_index];
284  }
285  }
286  size_used_ = new_size;
287  delete delete_cb;
288  }
289 
290  T dot_product(const GenericVector<T>& other) const {
291  T result = static_cast<T>(0);
292  for (int i = MIN(size_used_, other.size_used_) - 1; i >= 0; --i)
293  result += data_[i] * other.data_[i];
294  return result;
295  }
296 
297  // Returns the index of what would be the target_index_th item in the array
298  // if the members were sorted, without actually sorting. Members are
299  // shuffled around, but it takes O(n) time.
300  // NOTE: uses operator< and operator== on the members.
301  int choose_nth_item(int target_index) {
302  // Make sure target_index is legal.
303  if (target_index < 0)
304  target_index = 0; // ensure legal
305  else if (target_index >= size_used_)
306  target_index = size_used_ - 1;
307  unsigned int seed = 1;
308  return choose_nth_item(target_index, 0, size_used_, &seed);
309  }
310 
311  // Swaps the elements with the given indices.
312  void swap(int index1, int index2) {
313  if (index1 != index2) {
314  T tmp = data_[index1];
315  data_[index1] = data_[index2];
316  data_[index2] = tmp;
317  }
318  }
319  // Returns true if all elements of *this are within the given range.
320  // Only uses operator<
321  bool WithinBounds(const T& rangemin, const T& rangemax) const {
322  for (int i = 0; i < size_used_; ++i) {
323  if (data_[i] < rangemin || rangemax < data_[i])
324  return false;
325  }
326  return true;
327  }
328 
329  protected:
330  // Internal recursive version of choose_nth_item.
331  int choose_nth_item(int target_index, int start, int end, unsigned int* seed);
332 
333  // Init the object, allocating size memory.
334  void init(int size);
335 
336  // We are assuming that the object generally placed in thie
337  // vector are small enough that for efficiency it makes sense
338  // to start with a larger initial size.
339  static const int kDefaultVectorSize = 4;
342  T* data_;
344  // Mutable because Run method is not const
346 };
347 
348 namespace tesseract {
349 
350 // Function to read a GenericVector<char> from a whole file.
351 // Returns false on failure.
352 typedef bool (*FileReader)(const STRING& filename, GenericVector<char>* data);
353 // Function to write a GenericVector<char> to a whole file.
354 // Returns false on failure.
355 typedef bool (*FileWriter)(const GenericVector<char>& data,
356  const STRING& filename);
357 // The default FileReader loads the whole file into the vector of char,
358 // returning false on error.
359 inline bool LoadDataFromFile(const STRING& filename,
360  GenericVector<char>* data) {
361  FILE* fp = fopen(filename.string(), "rb");
362  if (fp == NULL) return false;
363  fseek(fp, 0, SEEK_END);
364  size_t size = ftell(fp);
365  fseek(fp, 0, SEEK_SET);
366  // Pad with a 0, just in case we treat the result as a string.
367  data->init_to_size(static_cast<int>(size) + 1, 0);
368  bool result = fread(&(*data)[0], 1, size, fp) == size;
369  fclose(fp);
370  return result;
371 }
372 // The default FileWriter writes the vector of char to the filename file,
373 // returning false on error.
374 inline bool SaveDataToFile(const GenericVector<char>& data,
375  const STRING& filename) {
376  FILE* fp = fopen(filename.string(), "wb");
377  if (fp == NULL) return false;
378  bool result =
379  static_cast<int>(fwrite(&data[0], 1, data.size(), fp)) == data.size();
380  fclose(fp);
381  return result;
382 }
383 
384 template <typename T>
385 bool cmp_eq(T const & t1, T const & t2) {
386  return t1 == t2;
387 }
388 
389 // Used by sort()
390 // return < 0 if t1 < t2
391 // return 0 if t1 == t2
392 // return > 0 if t1 > t2
393 template <typename T>
394 int sort_cmp(const void* t1, const void* t2) {
395  const T* a = static_cast<const T *> (t1);
396  const T* b = static_cast<const T *> (t2);
397  if (*a < *b) {
398  return -1;
399  } else if (*b < *a) {
400  return 1;
401  } else {
402  return 0;
403  }
404 }
405 
406 // Used by PointerVector::sort()
407 // return < 0 if t1 < t2
408 // return 0 if t1 == t2
409 // return > 0 if t1 > t2
410 template <typename T>
411 int sort_ptr_cmp(const void* t1, const void* t2) {
412  const T* a = *reinterpret_cast<T * const *>(t1);
413  const T* b = *reinterpret_cast<T * const *>(t2);
414  if (*a < *b) {
415  return -1;
416  } else if (*b < *a) {
417  return 1;
418  } else {
419  return 0;
420  }
421 }
422 
423 // Subclass for a vector of pointers. Use in preference to GenericVector<T*>
424 // as it provides automatic deletion and correct serialization, with the
425 // corollary that all copy operations are deep copies of the pointed-to objects.
426 template<typename T>
427 class PointerVector : public GenericVector<T*> {
428  public:
430  explicit PointerVector(int size) : GenericVector<T*>(size) { }
432  // Clear must be called here, even though it is called again by the base,
433  // as the base will call the wrong clear.
434  clear();
435  }
436  // Copy must be deep, as the pointers will be automatically deleted on
437  // destruction.
438  PointerVector(const PointerVector& other) : GenericVector<T*>(other) {
439  this->init(other.size());
440  this->operator+=(other);
441  }
443  this->reserve(this->size_used_ + other.size_used_);
444  for (int i = 0; i < other.size(); ++i) {
445  this->push_back(new T(*other.data_[i]));
446  }
447  return *this;
448  }
449 
451  if (&other != this) {
452  this->truncate(0);
453  this->operator+=(other);
454  }
455  return *this;
456  }
457 
458  // Removes an element at the given index and
459  // shifts the remaining elements to the left.
460  void remove(int index) {
461  delete GenericVector<T*>::data_[index];
463  }
464 
465  // Truncates the array to the given size by removing the end.
466  // If the current size is less, the array is not expanded.
467  void truncate(int size) {
468  for (int i = size; i < GenericVector<T*>::size_used_; ++i)
469  delete GenericVector<T*>::data_[i];
471  }
472 
473  // Compact the vector by deleting elements for which delete_cb returns
474  // true. delete_cb is a permanent callback and will be deleted.
476  int new_size = 0;
477  int old_index = 0;
478  // Until the callback returns true, the elements stay the same.
479  while (old_index < GenericVector<T*>::size_used_ &&
480  !delete_cb->Run(GenericVector<T*>::data_[old_index++]))
481  ++new_size;
482  // Now just copy anything else that gets false from delete_cb.
483  for (; old_index < GenericVector<T*>::size_used_; ++old_index) {
484  if (!delete_cb->Run(GenericVector<T*>::data_[old_index])) {
485  GenericVector<T*>::data_[new_size++] =
486  GenericVector<T*>::data_[old_index];
487  } else {
488  delete GenericVector<T*>::data_[old_index];
489  }
490  }
492  delete delete_cb;
493  }
494 
495  // Clear the array, calling the clear callback function if any.
496  // All the owned callbacks are also deleted.
497  // If you don't want the callbacks to be deleted, before calling clear, set
498  // the callback to NULL.
499  void clear() {
502  }
503 
504  // Writes a vector of (pointers to) classes to the given file. Assumes the
505  // existence of bool T::Serialize(FILE*) const that returns false in case of
506  // error. There is no Serialize for simple types, as you would have a
507  // normal GenericVector of those.
508  // Returns false in case of error.
509  bool Serialize(FILE* fp) const {
511  if (fwrite(&used, sizeof(used), 1, fp) != 1) return false;
512  for (int i = 0; i < used; ++i) {
513  inT8 non_null = GenericVector<T*>::data_[i] != NULL;
514  if (fwrite(&non_null, sizeof(non_null), 1, fp) != 1) return false;
515  if (non_null && !GenericVector<T*>::data_[i]->Serialize(fp)) return false;
516  }
517  return true;
518  }
519  bool Serialize(TFile* fp) const {
521  if (fp->FWrite(&used, sizeof(used), 1) != 1) return false;
522  for (int i = 0; i < used; ++i) {
523  inT8 non_null = GenericVector<T*>::data_[i] != NULL;
524  if (fp->FWrite(&non_null, sizeof(non_null), 1) != 1) return false;
525  if (non_null && !GenericVector<T*>::data_[i]->Serialize(fp)) return false;
526  }
527  return true;
528  }
529  // Reads a vector of (pointers to) classes to the given file. Assumes the
530  // existence of bool T::DeSerialize(bool, Tfile*) const that returns false in
531  // case of error. There is no Serialize for simple types, as you would have a
532  // normal GenericVector of those.
533  // If swap is true, assumes a big/little-endian swap is needed.
534  // Also needs T::T(), as new T is used in this function.
535  // Returns false in case of error.
536  bool DeSerialize(bool swap, FILE* fp) {
537  inT32 reserved;
538  if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
539  if (swap) Reverse32(&reserved);
540  GenericVector<T*>::reserve(reserved);
541  truncate(0);
542  for (int i = 0; i < reserved; ++i) {
543  inT8 non_null;
544  if (fread(&non_null, sizeof(non_null), 1, fp) != 1) return false;
545  T* item = NULL;
546  if (non_null) {
547  item = new T;
548  if (!item->DeSerialize(swap, fp)) {
549  delete item;
550  return false;
551  }
552  this->push_back(item);
553  } else {
554  // Null elements should keep their place in the vector.
555  this->push_back(NULL);
556  }
557  }
558  return true;
559  }
560  bool DeSerialize(bool swap, TFile* fp) {
561  inT32 reserved;
562  if (!DeSerializeSize(swap, fp, &reserved)) return false;
563  GenericVector<T*>::reserve(reserved);
564  truncate(0);
565  for (int i = 0; i < reserved; ++i) {
566  if (!DeSerializeElement(swap, fp)) return false;
567  }
568  return true;
569  }
570  // Enables deserialization of a selection of elements. Note that in order to
571  // retain the integrity of the stream, the caller must call some combination
572  // of DeSerializeElement and DeSerializeSkip of the exact number returned in
573  // *size, assuming a true return.
574  static bool DeSerializeSize(bool swap, TFile* fp, inT32* size) {
575  if (fp->FRead(size, sizeof(*size), 1) != 1) return false;
576  if (swap) Reverse32(size);
577  return true;
578  }
579  // Reads and appends to the vector the next element of the serialization.
580  bool DeSerializeElement(bool swap, TFile* fp) {
581  inT8 non_null;
582  if (fp->FRead(&non_null, sizeof(non_null), 1) != 1) return false;
583  T* item = NULL;
584  if (non_null) {
585  item = new T;
586  if (!item->DeSerialize(swap, fp)) {
587  delete item;
588  return false;
589  }
590  this->push_back(item);
591  } else {
592  // Null elements should keep their place in the vector.
593  this->push_back(NULL);
594  }
595  return true;
596  }
597  // Skips the next element of the serialization.
598  static bool DeSerializeSkip(bool swap, TFile* fp) {
599  inT8 non_null;
600  if (fp->FRead(&non_null, sizeof(non_null), 1) != 1) return false;
601  if (non_null) {
602  if (!T::SkipDeSerialize(swap, fp)) return false;
603  }
604  return true;
605  }
606 
607  // Sorts the items pointed to by the members of this vector using
608  // t::operator<().
609  void sort() { this->GenericVector<T*>::sort(&sort_ptr_cmp<T>); }
610 };
611 
612 } // namespace tesseract
613 
614 // A useful vector that uses operator== to do comparisons.
615 template <typename T>
616 class GenericVectorEqEq : public GenericVector<T> {
617  public:
620  NewPermanentTessCallback(tesseract::cmp_eq<T>));
621  }
624  NewPermanentTessCallback(tesseract::cmp_eq<T>));
625  }
626 };
627 
628 template <typename T>
629 void GenericVector<T>::init(int size) {
630  size_used_ = 0;
631  size_reserved_ = 0;
632  data_ = 0;
633  clear_cb_ = 0;
634  compare_cb_ = 0;
635  reserve(size);
636 }
637 
638 template <typename T>
640  clear();
641 }
642 
643 // Reserve some memory. If the internal array contains elements, they are
644 // copied.
645 template <typename T>
647  if (size_reserved_ >= size || size <= 0)
648  return;
649  T* new_array = new T[size];
650  for (int i = 0; i < size_used_; ++i)
651  new_array[i] = data_[i];
652  if (data_ != NULL) delete[] data_;
653  data_ = new_array;
654  size_reserved_ = size;
655 }
656 
657 template <typename T>
659  if (size_reserved_ == 0) {
660  reserve(kDefaultVectorSize);
661  }
662  else {
663  reserve(2 * size_reserved_);
664  }
665 }
666 
667 // Resizes to size and sets all values to t.
668 template <typename T>
669 void GenericVector<T>::init_to_size(int size, T t) {
670  reserve(size);
671  size_used_ = size;
672  for (int i = 0; i < size; ++i)
673  data_[i] = t;
674 }
675 
676 
677 // Return the object from an index.
678 template <typename T>
679 T &GenericVector<T>::get(int index) const {
680  ASSERT_HOST(index >= 0 && index < size_used_);
681  return data_[index];
682 }
683 
684 template <typename T>
685 T &GenericVector<T>::operator[](int index) const {
686  assert(index >= 0 && index < size_used_);
687  return data_[index];
688 }
689 
690 template <typename T>
692  ASSERT_HOST(size_used_ > 0);
693  return data_[size_used_ - 1];
694 }
695 // Returns the last object and removes it.
696 template <typename T>
698  ASSERT_HOST(size_used_ > 0);
699  return data_[--size_used_];
700 }
701 
702 // Return the object from an index.
703 template <typename T>
704 void GenericVector<T>::set(T t, int index) {
705  ASSERT_HOST(index >= 0 && index < size_used_);
706  data_[index] = t;
707 }
708 
709 // Shifts the rest of the elements to the right to make
710 // space for the new elements and inserts the given element
711 // at the specified index.
712 template <typename T>
713 void GenericVector<T>::insert(T t, int index) {
714  ASSERT_HOST(index >= 0 && index <= size_used_);
715  if (size_reserved_ == size_used_)
716  double_the_size();
717  for (int i = size_used_; i > index; --i) {
718  data_[i] = data_[i-1];
719  }
720  data_[index] = t;
721  size_used_++;
722 }
723 
724 // Removes an element at the given index and
725 // shifts the remaining elements to the left.
726 template <typename T>
727 void GenericVector<T>::remove(int index) {
728  ASSERT_HOST(index >= 0 && index < size_used_);
729  for (int i = index; i < size_used_ - 1; ++i) {
730  data_[i] = data_[i+1];
731  }
732  size_used_--;
733 }
734 
735 // Return true if the index is valindex
736 template <typename T>
738  return index >= 0 && index < size_used_;
739 }
740 
741 // Return the index of the T object.
742 template <typename T>
743 int GenericVector<T>::get_index(T object) const {
744  for (int i = 0; i < size_used_; ++i) {
745  ASSERT_HOST(compare_cb_ != NULL);
746  if (compare_cb_->Run(object, data_[i]))
747  return i;
748  }
749  return -1;
750 }
751 
752 // Return true if T is in the array
753 template <typename T>
754 bool GenericVector<T>::contains(T object) const {
755  return get_index(object) != -1;
756 }
757 
758 // Add an element in the array
759 template <typename T>
761  int index = 0;
762  if (size_used_ == size_reserved_)
763  double_the_size();
764  index = size_used_++;
765  data_[index] = object;
766  return index;
767 }
768 
769 template <typename T>
771  int index = get_index(object);
772  if (index >= 0)
773  return index;
774  return push_back(object);
775 }
776 
777 // Add an element in the array (front)
778 template <typename T>
780  if (size_used_ == size_reserved_)
781  double_the_size();
782  for (int i = size_used_; i > 0; --i)
783  data_[i] = data_[i-1];
784  data_[0] = object;
785  ++size_used_;
786  return 0;
787 }
788 
789 template <typename T>
791  push_back(t);
792 }
793 
794 template <typename T>
796  this->reserve(size_used_ + other.size_used_);
797  for (int i = 0; i < other.size(); ++i) {
798  this->operator+=(other.data_[i]);
799  }
800  return *this;
801 }
802 
803 template <typename T>
805  if (&other != this) {
806  this->truncate(0);
807  this->operator+=(other);
808  }
809  return *this;
810 }
811 
812 // Add a callback to be called to delete the elements when the array took
813 // their ownership.
814 template <typename T>
816  clear_cb_ = cb;
817 }
818 
819 // Add a callback to be called to delete the elements when the array took
820 // their ownership.
821 template <typename T>
824  compare_cb_ = cb;
825 }
826 
827 // Clear the array, calling the callback function if any.
828 template <typename T>
830  if (size_reserved_ > 0) {
831  if (clear_cb_ != NULL)
832  for (int i = 0; i < size_used_; ++i)
833  clear_cb_->Run(data_[i]);
834  delete[] data_;
835  data_ = NULL;
836  size_used_ = 0;
837  size_reserved_ = 0;
838  }
839  if (clear_cb_ != NULL) {
840  delete clear_cb_;
841  clear_cb_ = NULL;
842  }
843  if (compare_cb_ != NULL) {
844  delete compare_cb_;
845  compare_cb_ = NULL;
846  }
847 }
848 
849 template <typename T>
851  for (int i = 0; i < size_used_; ++i)
852  if (data_[i]) {
853  delete data_[i];
854  }
855 }
856 
857 
858 template <typename T>
860  FILE* f, TessResultCallback2<bool, FILE*, T const &>* cb) const {
861  if (fwrite(&size_reserved_, sizeof(size_reserved_), 1, f) != 1) return false;
862  if (fwrite(&size_used_, sizeof(size_used_), 1, f) != 1) return false;
863  if (cb != NULL) {
864  for (int i = 0; i < size_used_; ++i) {
865  if (!cb->Run(f, data_[i])) {
866  delete cb;
867  return false;
868  }
869  }
870  delete cb;
871  } else {
872  if (fwrite(data_, sizeof(T), size_used_, f) != size_used_) return false;
873  }
874  return true;
875 }
876 
877 template <typename T>
880  bool swap) {
881  inT32 reserved;
882  if (fread(&reserved, sizeof(reserved), 1, f) != 1) return false;
883  if (swap) Reverse32(&reserved);
884  reserve(reserved);
885  if (fread(&size_used_, sizeof(size_used_), 1, f) != 1) return false;
886  if (swap) Reverse32(&size_used_);
887  if (cb != NULL) {
888  for (int i = 0; i < size_used_; ++i) {
889  if (!cb->Run(f, data_ + i, swap)) {
890  delete cb;
891  return false;
892  }
893  }
894  delete cb;
895  } else {
896  if (fread(data_, sizeof(T), size_used_, f) != size_used_) return false;
897  if (swap) {
898  for (int i = 0; i < size_used_; ++i)
899  ReverseN(&data_[i], sizeof(T));
900  }
901  }
902  return true;
903 }
904 
905 // Writes a vector of simple types to the given file. Assumes that bitwise
906 // read/write of T will work. Returns false in case of error.
907 template <typename T>
908 bool GenericVector<T>::Serialize(FILE* fp) const {
909  if (fwrite(&size_used_, sizeof(size_used_), 1, fp) != 1) return false;
910  if (fwrite(data_, sizeof(*data_), size_used_, fp) != size_used_) return false;
911  return true;
912 }
913 template <typename T>
915  if (fp->FWrite(&size_used_, sizeof(size_used_), 1) != 1) return false;
916  if (fp->FWrite(data_, sizeof(*data_), size_used_) != size_used_) return false;
917  return true;
918 }
919 
920 // Reads a vector of simple types from the given file. Assumes that bitwise
921 // read/write will work with ReverseN according to sizeof(T).
922 // Returns false in case of error.
923 // If swap is true, assumes a big/little-endian swap is needed.
924 template <typename T>
925 bool GenericVector<T>::DeSerialize(bool swap, FILE* fp) {
926  inT32 reserved;
927  if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
928  if (swap) Reverse32(&reserved);
929  reserve(reserved);
930  size_used_ = reserved;
931  if (fread(data_, sizeof(T), size_used_, fp) != size_used_) return false;
932  if (swap) {
933  for (int i = 0; i < size_used_; ++i)
934  ReverseN(&data_[i], sizeof(data_[i]));
935  }
936  return true;
937 }
938 template <typename T>
940  inT32 reserved;
941  if (fp->FRead(&reserved, sizeof(reserved), 1) != 1) return false;
942  if (swap) Reverse32(&reserved);
943  reserve(reserved);
944  size_used_ = reserved;
945  if (fp->FRead(data_, sizeof(T), size_used_) != size_used_) return false;
946  if (swap) {
947  for (int i = 0; i < size_used_; ++i)
948  ReverseN(&data_[i], sizeof(data_[i]));
949  }
950  return true;
951 }
952 template <typename T>
954  inT32 reserved;
955  if (fp->FRead(&reserved, sizeof(reserved), 1) != 1) return false;
956  if (swap) Reverse32(&reserved);
957  return fp->FRead(NULL, sizeof(T), reserved) == reserved;
958 }
959 
960 // Writes a vector of classes to the given file. Assumes the existence of
961 // bool T::Serialize(FILE* fp) const that returns false in case of error.
962 // Returns false in case of error.
963 template <typename T>
965  if (fwrite(&size_used_, sizeof(size_used_), 1, fp) != 1) return false;
966  for (int i = 0; i < size_used_; ++i) {
967  if (!data_[i].Serialize(fp)) return false;
968  }
969  return true;
970 }
971 template <typename T>
973  if (fp->FWrite(&size_used_, sizeof(size_used_), 1) != 1) return false;
974  for (int i = 0; i < size_used_; ++i) {
975  if (!data_[i].Serialize(fp)) return false;
976  }
977  return true;
978 }
979 
980 // Reads a vector of classes from the given file. Assumes the existence of
981 // bool T::Deserialize(bool swap, FILE* fp) that returns false in case of
982 // error. Also needs T::T() and T::T(constT&), as init_to_size is used in
983 // this function. Returns false in case of error.
984 // If swap is true, assumes a big/little-endian swap is needed.
985 template <typename T>
986 bool GenericVector<T>::DeSerializeClasses(bool swap, FILE* fp) {
987  uinT32 reserved;
988  if (fread(&reserved, sizeof(reserved), 1, fp) != 1) return false;
989  if (swap) Reverse32(&reserved);
990  T empty;
991  init_to_size(reserved, empty);
992  for (int i = 0; i < reserved; ++i) {
993  if (!data_[i].DeSerialize(swap, fp)) return false;
994  }
995  return true;
996 }
997 template <typename T>
999  uinT32 reserved;
1000  if (fp->FRead(&reserved, sizeof(reserved), 1) != 1) return false;
1001  if (swap) Reverse32(&reserved);
1002  T empty;
1003  init_to_size(reserved, empty);
1004  for (int i = 0; i < reserved; ++i) {
1005  if (!data_[i].DeSerialize(swap, fp)) return false;
1006  }
1007  return true;
1008 }
1009 template <typename T>
1011  uinT32 reserved;
1012  if (fp->FRead(&reserved, sizeof(reserved), 1) != 1) return false;
1013  if (swap) Reverse32(&reserved);
1014  for (int i = 0; i < reserved; ++i) {
1015  if (!T::SkipDeSerialize(swap, fp)) return false;
1016  }
1017  return true;
1018 }
1019 
1020 // This method clear the current object, then, does a shallow copy of
1021 // its argument, and finally invalidates its argument.
1022 template <typename T>
1024  this->clear();
1025  this->data_ = from->data_;
1026  this->size_reserved_ = from->size_reserved_;
1027  this->size_used_ = from->size_used_;
1028  this->compare_cb_ = from->compare_cb_;
1029  this->clear_cb_ = from->clear_cb_;
1030  from->data_ = NULL;
1031  from->clear_cb_ = NULL;
1032  from->compare_cb_ = NULL;
1033  from->size_used_ = 0;
1034  from->size_reserved_ = 0;
1035 }
1036 
1037 template <typename T>
1039  sort(&tesseract::sort_cmp<T>);
1040 }
1041 
1042 // Internal recursive version of choose_nth_item.
1043 // The algorithm used comes from "Algorithms" by Sedgewick:
1044 // http://books.google.com/books/about/Algorithms.html?id=idUdqdDXqnAC
1045 // The principle is to choose a random pivot, and move everything less than
1046 // the pivot to its left, and everything greater than the pivot to the end
1047 // of the array, then recurse on the part that contains the desired index, or
1048 // just return the answer if it is in the equal section in the middle.
1049 // The random pivot guarantees average linear time for the same reason that
1050 // n times vector::push_back takes linear time on average.
1051 // target_index, start and and end are all indices into the full array.
1052 // Seed is a seed for rand_r for thread safety purposes. Its value is
1053 // unimportant as the random numbers do not affect the result except
1054 // between equal answers.
1055 template <typename T>
1056 int GenericVector<T>::choose_nth_item(int target_index, int start, int end,
1057  unsigned int* seed) {
1058  // Number of elements to process.
1059  int num_elements = end - start;
1060  // Trivial cases.
1061  if (num_elements <= 1)
1062  return start;
1063  if (num_elements == 2) {
1064  if (data_[start] < data_[start + 1]) {
1065  return target_index > start ? start + 1 : start;
1066  } else {
1067  return target_index > start ? start : start + 1;
1068  }
1069  }
1070  // Place the pivot at start.
1071  #ifndef rand_r // _MSC_VER, ANDROID
1072  srand(*seed);
1073  #define rand_r(seed) rand()
1074  #endif // _MSC_VER
1075  int pivot = rand_r(seed) % num_elements + start;
1076  swap(pivot, start);
1077  // The invariant condition here is that items [start, next_lesser) are less
1078  // than the pivot (which is at index next_lesser) and items
1079  // [prev_greater, end) are greater than the pivot, with items
1080  // [next_lesser, prev_greater) being equal to the pivot.
1081  int next_lesser = start;
1082  int prev_greater = end;
1083  for (int next_sample = start + 1; next_sample < prev_greater;) {
1084  if (data_[next_sample] < data_[next_lesser]) {
1085  swap(next_lesser++, next_sample++);
1086  } else if (data_[next_sample] == data_[next_lesser]) {
1087  ++next_sample;
1088  } else {
1089  swap(--prev_greater, next_sample);
1090  }
1091  }
1092  // Now the invariant is set up, we recurse on just the section that contains
1093  // the desired index.
1094  if (target_index < next_lesser)
1095  return choose_nth_item(target_index, start, next_lesser, seed);
1096  else if (target_index < prev_greater)
1097  return next_lesser; // In equal bracket.
1098  else
1099  return choose_nth_item(target_index, prev_greater, end, seed);
1100 }
1101 
1102 
1103 #endif // TESSERACT_CCUTIL_GENERICVECTOR_H_
bool SaveDataToFile(const GenericVector< char > &data, const STRING &filename)
void Reverse32(void *ptr)
Definition: helpers.h:193
bool DeSerialize(bool swap, TFile *fp)
bool DeSerializeElement(bool swap, TFile *fp)
inT32 size_reserved_
void set_compare_callback(TessResultCallback2< bool, T const &, T const & > *cb)
virtual R Run(A1, A2, A3)=0
int sort_cmp(const void *t1, const void *t2)
SIGNED char inT8
Definition: host.h:98
bool SerializeClasses(FILE *fp) const
int FWrite(const void *buffer, int size, int count)
Definition: serialis.cpp:131
Definition: strngs.h:44
void double_the_size()
bool contains(T object) const
void resize_no_init(int size)
Definition: genericvector.h:66
inT32 choose_nth_item(inT32 index, float *array, inT32 count)
Definition: statistc.cpp:641
unsigned int uinT32
Definition: host.h:103
void swap(int index1, int index2)
T & back() const
void init_to_size(int size, T t)
void sort(int(*comparator)(const void *, const void *))
int inT32
Definition: host.h:102
bool cmp_eq(T const &t1, T const &t2)
static bool SkipDeSerialize(bool swap, tesseract::TFile *fp)
void reserve(int size)
T contains_index(int index) const
bool empty() const
Definition: genericvector.h:84
void init(int size)
int get_index(T object) const
bool LoadDataFromFile(const STRING &filename, GenericVector< char > *data)
int sort_ptr_cmp(const void *t1, const void *t2)
GenericVector(const GenericVector &other)
Definition: genericvector.h:49
void truncate(int size)
bool DeSerialize(bool swap, FILE *fp)
bool write(FILE *f, TessResultCallback2< bool, FILE *, T const & > *cb) const
int push_back_new(T object)
void compact(TessResultCallback1< bool, const T * > *delete_cb)
bool(* FileReader)(const STRING &filename, GenericVector< char > *data)
T & get(int index) const
GenericVector< T > & operator+=(const GenericVector &other)
bool WithinBounds(const T &rangemin, const T &rangemax) const
int size() const
Definition: genericvector.h:72
bool(* FileWriter)(const GenericVector< char > &data, const STRING &filename)
bool Serialize(FILE *fp) const
PointerVector< T > & operator+=(const PointerVector &other)
PointerVector(const PointerVector &other)
virtual R Run(A1, A2)=0
void move(GenericVector< T > *from)
TessResultCallback2< bool, T const &, T const & > * compare_cb_
int choose_nth_item(int target_index)
int push_front(T object)
void set(T t, int index)
#define MIN(x, y)
Definition: ndminx.h:28
TessCallback1< T > * clear_cb_
virtual R Run(A1)=0
T dot_product(const GenericVector< T > &other) const
void delete_data_pointers()
ICOORD & operator+=(ICOORD &op1, const ICOORD &op2)
Definition: ipoints.h:86
static bool DeSerializeSize(bool swap, TFile *fp, inT32 *size)
static T * double_the_size_memcpy(int current_size, T *data)
void remove(int index)
int size_reserved() const
Definition: genericvector.h:75
void Swap(T *p1, T *p2)
Definition: helpers.h:90
bool bool_binary_search(const T &target) const
bool Serialize(FILE *fp) const
int FRead(void *buffer, int size, int count)
Definition: serialis.cpp:91
void ReverseN(void *ptr, int num_bytes)
Definition: helpers.h:177
static bool DeSerializeSkip(bool swap, TFile *fp)
T & operator[](int index) const
int push_back(T object)
bool DeSerialize(bool swap, FILE *fp)
static bool SkipDeSerializeClasses(bool swap, tesseract::TFile *fp)
bool DeSerializeClasses(bool swap, FILE *fp)
void insert(T t, int index)
void compact_sorted()
void compact(TessResultCallback1< bool, int > *delete_cb)
GenericVector(int size, T init_val)
Definition: genericvector.h:43
#define ASSERT_HOST(x)
Definition: errcode.h:84
static const int kDefaultVectorSize
void set_clear_callback(TessCallback1< T > *cb)
const char * string() const
Definition: strngs.cpp:201
bool read(FILE *f, TessResultCallback3< bool, FILE *, T *, bool > *cb, bool swap)
PointerVector< T > & operator=(const PointerVector &other)
int length() const
Definition: genericvector.h:79
bool Serialize(TFile *fp) const
GenericVectorEqEq(int size)
GenericVector< T > & operator=(const GenericVector &other)
#define rand_r(seed)
_ConstTessMemberResultCallback_0_0< false, R, T1 >::base * NewPermanentTessCallback(const T1 *obj, R(T2::*member)() const)
Definition: tesscallback.h:116
int binary_search(const T &target) const