Zigzag.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * https://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include "Zigzag.hh"
  19. namespace avro {
  20. // TODO: The following two functions have exactly the same code except for the type.
  21. // They should be implemented as a template.
  22. size_t
  23. encodeInt64(int64_t input, std::array<uint8_t, 10> &output) noexcept {
  24. auto val = encodeZigzag64(input);
  25. // put values in an array of bytes with variable length encoding
  26. const int mask = 0x7F;
  27. auto v = val & mask;
  28. size_t bytesOut = 0;
  29. while (val >>= 7) {
  30. output[bytesOut++] = (v | 0x80);
  31. v = val & mask;
  32. }
  33. output[bytesOut++] = v;
  34. return bytesOut;
  35. }
  36. size_t
  37. encodeInt32(int32_t input, std::array<uint8_t, 5> &output) noexcept {
  38. auto val = encodeZigzag32(input);
  39. // put values in an array of bytes with variable length encoding
  40. const int mask = 0x7F;
  41. auto v = val & mask;
  42. size_t bytesOut = 0;
  43. while (val >>= 7) {
  44. output[bytesOut++] = (v | 0x80);
  45. v = val & mask;
  46. }
  47. output[bytesOut++] = v;
  48. return bytesOut;
  49. }
  50. } // namespace avro