serialize.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. * Helper functions which serialize and deserialize integers
  7. * into bytes in big endian.
  8. */
  9. #pragma once
  10. namespace ROCKSDB_NAMESPACE {
  11. namespace cassandra {
  12. namespace {
  13. const int64_t kCharMask = 0xFFLL;
  14. const int32_t kBitsPerByte = 8;
  15. }
  16. template<typename T>
  17. void Serialize(T val, std::string* dest);
  18. template<typename T>
  19. T Deserialize(const char* src, std::size_t offset=0);
  20. // Specializations
  21. template<>
  22. inline void Serialize<int8_t>(int8_t t, std::string* dest) {
  23. dest->append(1, static_cast<char>(t & kCharMask));
  24. }
  25. template<>
  26. inline void Serialize<int32_t>(int32_t t, std::string* dest) {
  27. for (unsigned long i = 0; i < sizeof(int32_t); i++) {
  28. dest->append(1, static_cast<char>(
  29. (t >> (sizeof(int32_t) - 1 - i) * kBitsPerByte) & kCharMask));
  30. }
  31. }
  32. template<>
  33. inline void Serialize<int64_t>(int64_t t, std::string* dest) {
  34. for (unsigned long i = 0; i < sizeof(int64_t); i++) {
  35. dest->append(
  36. 1, static_cast<char>(
  37. (t >> (sizeof(int64_t) - 1 - i) * kBitsPerByte) & kCharMask));
  38. }
  39. }
  40. template<>
  41. inline int8_t Deserialize<int8_t>(const char* src, std::size_t offset) {
  42. return static_cast<int8_t>(src[offset]);
  43. }
  44. template<>
  45. inline int32_t Deserialize<int32_t>(const char* src, std::size_t offset) {
  46. int32_t result = 0;
  47. for (unsigned long i = 0; i < sizeof(int32_t); i++) {
  48. result |= static_cast<int32_t>(static_cast<unsigned char>(src[offset + i]))
  49. << ((sizeof(int32_t) - 1 - i) * kBitsPerByte);
  50. }
  51. return result;
  52. }
  53. template<>
  54. inline int64_t Deserialize<int64_t>(const char* src, std::size_t offset) {
  55. int64_t result = 0;
  56. for (unsigned long i = 0; i < sizeof(int64_t); i++) {
  57. result |= static_cast<int64_t>(static_cast<unsigned char>(src[offset + i]))
  58. << ((sizeof(int64_t) - 1 - i) * kBitsPerByte);
  59. }
  60. return result;
  61. }
  62. } // namepsace cassandrda
  63. } // namespace ROCKSDB_NAMESPACE