00001
00002
00003
00004
00005
00006
00007
00008
00009
00010 #ifndef GRID_CLEINT_BYTE_UTILS_HPP_INCLUDED
00011 #define GRID_CLEINT_BYTE_UTILS_HPP_INCLUDED
00012
00013 #include <vector>
00014 #include <set>
00015 #include <cassert>
00016 #include <cstdint>
00017 #include <cstddef>
00018 #include <cstring>
00019
00024 namespace GridClientByteUtils {
00025
00026 using std::size_t;
00027
00029 enum ByteOrder { BIG_ENDIAN_ORDER = 1, LITTLE_ENDIAN_ORDER = 2 };
00030
00039 template <class T> void bytesToValue(const int8_t* buf, size_t nBytes, T& res, const ByteOrder& order =
00040 BIG_ENDIAN_ORDER) {
00041 assert(buf != NULL);
00042 assert(order == BIG_ENDIAN_ORDER || order == LITTLE_ENDIAN_ORDER);
00043
00044 size_t bytesCnt = sizeof(T) / sizeof(int8_t);
00045
00046 assert(nBytes >= bytesCnt);
00047
00048 res = 0;
00049
00050 for (size_t i = 0; i < bytesCnt; i++) {
00051 int shift = (order == BIG_ENDIAN_ORDER ? bytesCnt - i - 1 : i) << 3;
00052
00053 res |= (0xffL & buf[i]) << shift;
00054 }
00055 }
00056
00064 template <class T> void valueToBytes(const T& val, std::vector<int8_t>& bytes, const ByteOrder& order =
00065 BIG_ENDIAN_ORDER) {
00066 assert(order == BIG_ENDIAN_ORDER || order == LITTLE_ENDIAN_ORDER);
00067
00068 bytes.clear();
00069
00070 size_t bytesCnt = sizeof(T) / sizeof(int8_t);
00071
00072 for (size_t i = 0; i < bytesCnt; i++) {
00073 int shift = (order == BIG_ENDIAN_ORDER ? bytesCnt - i - 1 : i) << 3;
00074
00075 bytes.push_back((int8_t)((val >> shift) & 0xff));
00076 }
00077 }
00078
00087 template <class T> void valueToBytes(const T& val, int8_t* buf, size_t nBytes, const ByteOrder& order =
00088 BIG_ENDIAN_ORDER) {
00089 assert(buf != NULL);
00090 assert(order == BIG_ENDIAN_ORDER || order == LITTLE_ENDIAN_ORDER);
00091
00092 size_t bytesCnt = sizeof(T) / sizeof(int8_t);
00093
00094 assert(nBytes >= bytesCnt);
00095
00096 for (size_t i = 0; i < bytesCnt; i++) {
00097 int shift = (order == BIG_ENDIAN_ORDER ? bytesCnt - i - 1 : i) << 3;
00098
00099 buf[i] = ((int8_t)((val >> shift) & 0xff));
00100 }
00101 }
00102
00111 template <class IT, class T> T bitwiseOr(IT first, IT last, T initVal) {
00112 T ret = initVal;
00113
00114 for (IT i = first; i != last; i++)
00115 ret |= *i;
00116
00117 return ret;
00118 }
00119 }
00120 #endif