Tizen 2.1 base
[platform/core/uifw/ise-engine-sunpinyin.git] / src / slm / tslmendian / writer.h
1 // -*- mode: c++ -*-
2 #ifndef WRITER_H
3 #define WRITER_H
4
5 #include <stdio.h>
6 #include <stdint.h>
7 #include <algorithm>
8
9 #ifndef LITTLE_ENDIAN
10 enum {
11     BIG_ENDIAN = 4321,
12     LITTLE_ENDIAN = 1234,
13     UNKNOWN_ENDIAN = 0x0000
14 };
15 #else
16 #define UNKNOWN_ENDIAN (0x0000)
17 #endif
18 int get_host_endian();
19 int parse_endian(const char* arg);
20 const char* endian2str(int endian);
21
22 // change the byte order of given variable
23 template <typename Type>
24 Type change_byte_order(const Type& v){
25     Type t = v;
26     const size_t size = sizeof(v);
27     uint8_t* first = (uint8_t *) (&t);
28     uint8_t* last = first + size - 1;
29     while (first < last) {
30         std::swap(*first++, *last--);
31     }
32     return t;
33 }
34
35 template <typename T>
36 class OtherEndian
37 {
38 public:
39     typedef T TargetType;
40     static TargetType create(const T& from){
41         return from;
42     }
43 };
44
45 #if WORDS_BIGENDIAN
46 #define DEFINE_OTHER_TYPE(__T__) typedef __T__ ## _BE TargetType
47 #else
48 #define DEFINE_OTHER_TYPE(__T__) typedef __T__ ## _LE TargetType
49 #endif
50
51 //
52 // we always defined a reversed layout of big-endian and little-endian
53 // bit-field struct, so such kind of struct need to be reverted if host
54 // arch is different from build arch.
55 //
56 template <typename T>
57 bool revert_write(const T& t, FILE *fp){
58     T reverted = change_byte_order(t);
59     typename OtherEndian<T>::TargetType o =
60         OtherEndian<T>::create(reverted);
61     return fwrite(&o, sizeof(o), 1, fp) == 1;
62 }
63
64 //
65 // if the struct has non-bit-field member(s), TTransUnit, among others,
66 // the order of members is the same as how they are defined.
67 //
68
69 class Writer
70 {
71 public:
72     Writer(FILE *fp, bool doRevert)
73         : m_fp(fp), m_doRevert(doRevert)
74     {}
75
76     template <typename T>
77     bool write(const T& t){
78         if (m_doRevert)
79             return revert_write(t, m_fp);
80         else
81             return fwrite(&t, sizeof(t), 1, m_fp) == 1;
82     }
83
84
85     template <typename T>
86     bool write(const T* t, size_t len){
87         for (unsigned i = 0; i < len; i++) {
88             if (!write(t[i]))
89                 return false;
90         }
91         return true;
92     }
93 private:
94     FILE *m_fp;
95     const bool m_doRevert;
96 };
97
98
99
100 #endif // WRITER_H