GroupVarintDetail.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Copyright 2012-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <stddef.h>
  18. #include <stdint.h>
  19. namespace folly {
  20. template <typename T>
  21. class GroupVarint;
  22. namespace detail {
  23. template <typename T>
  24. struct GroupVarintTraits;
  25. template <>
  26. struct GroupVarintTraits<uint32_t> {
  27. enum : uint32_t {
  28. kGroupSize = 4,
  29. kHeaderSize = 1,
  30. };
  31. };
  32. template <>
  33. struct GroupVarintTraits<uint64_t> {
  34. enum : uint32_t {
  35. kGroupSize = 5,
  36. kHeaderSize = 2,
  37. };
  38. };
  39. template <typename T>
  40. class GroupVarintBase {
  41. protected:
  42. typedef GroupVarintTraits<T> Traits;
  43. enum : uint32_t { kHeaderSize = Traits::kHeaderSize };
  44. public:
  45. typedef T type;
  46. /**
  47. * Number of integers encoded / decoded in one pass.
  48. */
  49. enum : uint32_t { kGroupSize = Traits::kGroupSize };
  50. /**
  51. * Maximum encoded size.
  52. */
  53. enum : uint32_t { kMaxSize = kHeaderSize + sizeof(type) * kGroupSize };
  54. /**
  55. * Maximum size for n values.
  56. */
  57. static size_t maxSize(size_t n) {
  58. // Full groups
  59. size_t total = (n / kGroupSize) * kFullGroupSize;
  60. // Incomplete last group, if any
  61. n %= kGroupSize;
  62. if (n) {
  63. total += kHeaderSize + n * sizeof(type);
  64. }
  65. return total;
  66. }
  67. /**
  68. * Size of n values starting at p.
  69. */
  70. static size_t totalSize(const T* p, size_t n) {
  71. size_t size = 0;
  72. for (; n >= kGroupSize; n -= kGroupSize, p += kGroupSize) {
  73. size += Derived::size(p);
  74. }
  75. if (n) {
  76. size += Derived::partialSize(p, n);
  77. }
  78. return size;
  79. }
  80. private:
  81. typedef GroupVarint<T> Derived;
  82. enum { kFullGroupSize = kHeaderSize + kGroupSize * sizeof(type) };
  83. };
  84. } // namespace detail
  85. } // namespace folly