source: tags/arb-6.0/TEMPLATES/ChecksumCollector.h

Last change on this file was 8467, checked in by westram, 12 years ago
  • helper class to calculate checksums for complex custom data structures
File size: 2.3 KB
Line 
1// ============================================================= //
2//                                                               //
3//   File      : ChecksumCollector.h                             //
4//   Purpose   :                                                 //
5//                                                               //
6//   Coded by Ralf Westram (coder@reallysoft.de) in March 2012   //
7//   Institute of Microbiology (Technical University Munich)     //
8//   http://www.arb-home.de/                                     //
9//                                                               //
10// ============================================================= //
11
12#ifndef CHECKSUMCOLLECTOR_H
13#define CHECKSUMCOLLECTOR_H
14
15#ifndef _GLIBCXX_VECTOR
16#include <vector>
17#endif
18#ifndef ARBDBT_H
19#include <arbdbt.h>
20#endif
21
22
23class ChecksumCollector {
24    // helper class to calculate checksums for complex custom data structures
25    //
26    // Derive from this class,
27    // traverse your structure in ctor and
28    // collect() all data members.
29
30    std::vector<unsigned char> data;
31
32protected:
33   
34    void collect_byte(unsigned char c) { data.push_back(c); }
35    void collect_mem(void *v, int len) {
36        const unsigned char *c = (const unsigned char *)v;
37        for (int p = 0; p<len; ++p) {
38            collect_byte(c[p]);
39        }
40    }
41   
42    void collect(unsigned char c) { collect_byte(c); }
43    void collect(char c) { collect_byte(c); }
44    void collect(bool b) { collect_byte(b); }
45
46    void collect(const float& f) { collect_mem((unsigned char *)&f, sizeof(f)); }
47    void collect(const double& d) { collect_mem((unsigned char *)&d, sizeof(d)); }
48
49    void collect(const char *s) {
50        if (s) {
51            for (int p = 0; s[p]; ++p) collect_byte(s[p]);
52            collect_byte(0);
53        }
54        else {
55            collect_byte(0);
56            collect_byte(0);
57        }
58    }
59
60public:
61    ChecksumCollector() {}
62    ~ChecksumCollector() {}
63
64    uint32_t checksum() const {
65        size_t         size   = data.size();
66        unsigned char *buffer = (unsigned char *)malloc(size);
67        for (size_t s = 0; s<size; ++s) buffer[s] = data[s];
68        uint32_t cs = GB_checksum((char*)buffer, size, false, NULL);
69        free(buffer);
70        return cs;
71    }
72};
73
74
75#else
76#error ChecksumCollector.h included twice
77#endif // CHECKSUMCOLLECTOR_H
Note: See TracBrowser for help on using the repository browser.