serialize.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #include <cstdint>
  11. #include <string>
  12. #include "rocksdb/rocksdb_namespace.h"
  13. namespace ROCKSDB_NAMESPACE {
  14. namespace cassandra {
  15. namespace {
  16. const int64_t kCharMask = 0xFFLL;
  17. const int32_t kBitsPerByte = 8;
  18. } // namespace
  19. template <typename T>
  20. void Serialize(T val, std::string* dest);
  21. template <typename T>
  22. T Deserialize(const char* src, std::size_t offset = 0);
  23. // Specializations
  24. template <>
  25. inline void Serialize<int8_t>(int8_t t, std::string* dest) {
  26. dest->append(1, static_cast<char>(t & kCharMask));
  27. }
  28. template <>
  29. inline void Serialize<int32_t>(int32_t t, std::string* dest) {
  30. for (unsigned long i = 0; i < sizeof(int32_t); i++) {
  31. dest->append(
  32. 1, static_cast<char>((t >> (sizeof(int32_t) - 1 - i) * kBitsPerByte) &
  33. kCharMask));
  34. }
  35. }
  36. template <>
  37. inline void Serialize<int64_t>(int64_t t, std::string* dest) {
  38. for (unsigned long i = 0; i < sizeof(int64_t); i++) {
  39. dest->append(
  40. 1, static_cast<char>((t >> (sizeof(int64_t) - 1 - i) * kBitsPerByte) &
  41. kCharMask));
  42. }
  43. }
  44. template <>
  45. inline int8_t Deserialize<int8_t>(const char* src, std::size_t offset) {
  46. return static_cast<int8_t>(src[offset]);
  47. }
  48. template <>
  49. inline int32_t Deserialize<int32_t>(const char* src, std::size_t offset) {
  50. int32_t result = 0;
  51. for (unsigned long i = 0; i < sizeof(int32_t); i++) {
  52. result |= static_cast<int32_t>(static_cast<unsigned char>(src[offset + i]))
  53. << ((sizeof(int32_t) - 1 - i) * kBitsPerByte);
  54. }
  55. return result;
  56. }
  57. template <>
  58. inline int64_t Deserialize<int64_t>(const char* src, std::size_t offset) {
  59. int64_t result = 0;
  60. for (unsigned long i = 0; i < sizeof(int64_t); i++) {
  61. result |= static_cast<int64_t>(static_cast<unsigned char>(src[offset + i]))
  62. << ((sizeof(int64_t) - 1 - i) * kBitsPerByte);
  63. }
  64. return result;
  65. }
  66. } // namespace cassandra
  67. } // namespace ROCKSDB_NAMESPACE