Apache Singa
A General Distributed Deep Learning Library
integer.h
1 /************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements. See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership. The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License. You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied. See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 #ifndef INTEGER_H_
23 #define INTEGER_H_
24 
25 #include <cstdint>
26 
27 namespace singa{
28 static bool isNetworkOrder() {
29  int test = 1;
30  return (1 != *(uint8_t*)&test);
31 }
32 
33 template <typename T>
34 static inline T byteSwap(const T& v) {
35  int size = sizeof(v);
36  T ret;
37  uint8_t *dest = reinterpret_cast<uint8_t *>(&ret);
38  uint8_t *src = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&v));
39  for (int i = 0; i < size; ++i) {
40  dest[i] = src[size - i - 1];
41  }
42  return ret;
43 }
44 
45 template <typename T>
46 static inline T hton(const T& v)
47 {
48  return isNetworkOrder() ? v : byteSwap(v);
49 }
50 
51 template <typename T>
52 static inline T ntoh(const T& v)
53 {
54  return hton(v);
55 }
56 
57 static inline int appendInteger(char* buf) {return 0;}
58 static inline int readInteger(char* buf) {return 0;}
59 
60 template<typename Type, typename... Types>
61 static int appendInteger(char* buf, Type value, Types... values) {
62  *(Type*)buf = hton(value);
63  return sizeof(Type) + appendInteger(buf + sizeof(Type), values...);
64 }
65 
66 template<typename Type, typename... Types>
67 static int readInteger(char* buf, Type& value, Types&... values) {
68  value = ntoh(*(Type*)buf);
69  return sizeof(Type) + readInteger(buf + sizeof(Type), values...);
70 }
71 
72 }
73 #endif
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements...
Definition: common.h:48