]> git.proxmox.com Git - ceph.git/blob - ceph/src/rocksdb/utilities/cassandra/serialize.h
update source to Ceph Pacific 16.2.2
[ceph.git] / ceph / src / rocksdb / utilities / cassandra / serialize.h
1 // Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
2 // This source code is licensed under both the GPLv2 (found in the
3 // COPYING file in the root directory) and Apache 2.0 License
4 // (found in the LICENSE.Apache file in the root directory).
5
6 /**
7 * Helper functions which serialize and deserialize integers
8 * into bytes in big endian.
9 */
10
11 #pragma once
12
13 namespace ROCKSDB_NAMESPACE {
14 namespace cassandra {
15 namespace {
16 const int64_t kCharMask = 0xFFLL;
17 const int32_t kBitsPerByte = 8;
18 }
19
20 template<typename T>
21 void Serialize(T val, std::string* dest);
22
23 template<typename T>
24 T Deserialize(const char* src, std::size_t offset=0);
25
26 // Specializations
27 template<>
28 inline void Serialize<int8_t>(int8_t t, std::string* dest) {
29 dest->append(1, static_cast<char>(t & kCharMask));
30 }
31
32 template<>
33 inline void Serialize<int32_t>(int32_t t, std::string* dest) {
34 for (unsigned long i = 0; i < sizeof(int32_t); i++) {
35 dest->append(1, static_cast<char>(
36 (t >> (sizeof(int32_t) - 1 - i) * kBitsPerByte) & kCharMask));
37 }
38 }
39
40 template<>
41 inline void Serialize<int64_t>(int64_t t, std::string* dest) {
42 for (unsigned long i = 0; i < sizeof(int64_t); i++) {
43 dest->append(
44 1, static_cast<char>(
45 (t >> (sizeof(int64_t) - 1 - i) * kBitsPerByte) & kCharMask));
46 }
47 }
48
49 template<>
50 inline int8_t Deserialize<int8_t>(const char* src, std::size_t offset) {
51 return static_cast<int8_t>(src[offset]);
52 }
53
54 template<>
55 inline int32_t Deserialize<int32_t>(const char* src, std::size_t offset) {
56 int32_t result = 0;
57 for (unsigned long i = 0; i < sizeof(int32_t); i++) {
58 result |= static_cast<int32_t>(static_cast<unsigned char>(src[offset + i]))
59 << ((sizeof(int32_t) - 1 - i) * kBitsPerByte);
60 }
61 return result;
62 }
63
64 template<>
65 inline int64_t Deserialize<int64_t>(const char* src, std::size_t offset) {
66 int64_t result = 0;
67 for (unsigned long i = 0; i < sizeof(int64_t); i++) {
68 result |= static_cast<int64_t>(static_cast<unsigned char>(src[offset + i]))
69 << ((sizeof(int64_t) - 1 - i) * kBitsPerByte);
70 }
71 return result;
72 }
73
74 } // namepsace cassandrda
75 } // namespace ROCKSDB_NAMESPACE