Utils.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2017-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 <type_traits>
  18. #include <folly/io/Cursor.h>
  19. #include <folly/io/IOBuf.h>
  20. #include <folly/lang/Bits.h>
  21. /**
  22. * Helper functions for compression codecs.
  23. */
  24. namespace folly {
  25. namespace io {
  26. namespace compression {
  27. namespace detail {
  28. /**
  29. * Reads sizeof(T) bytes, and returns false if not enough bytes are available.
  30. * Returns true if the first n bytes are equal to prefix when interpreted as
  31. * a little endian T.
  32. */
  33. template <typename T>
  34. typename std::enable_if<std::is_unsigned<T>::value, bool>::type
  35. dataStartsWithLE(const IOBuf* data, T prefix, uint64_t n = sizeof(T)) {
  36. DCHECK_GT(n, 0);
  37. DCHECK_LE(n, sizeof(T));
  38. T value;
  39. Cursor cursor{data};
  40. if (!cursor.tryReadLE(value)) {
  41. return false;
  42. }
  43. const T mask = n == sizeof(T) ? T(-1) : (T(1) << (8 * n)) - 1;
  44. return prefix == (value & mask);
  45. }
  46. template <typename T>
  47. typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type
  48. prefixToStringLE(T prefix, uint64_t n = sizeof(T)) {
  49. DCHECK_GT(n, 0);
  50. DCHECK_LE(n, sizeof(T));
  51. prefix = Endian::little(prefix);
  52. std::string result;
  53. result.resize(n);
  54. memcpy(&result[0], &prefix, n);
  55. return result;
  56. }
  57. } // namespace detail
  58. } // namespace compression
  59. } // namespace io
  60. } // namespace folly