bh_leb128_test.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (C) 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_leb128.h"
  6. #include "gtest/gtest.h"
  7. #include <vector>
  8. #include <type_traits>
  9. template<typename T>
  10. void
  11. run_read_leb_test(std::vector<uint8_t> data,
  12. bh_leb_read_status_t expected_status, T expected_value)
  13. {
  14. size_t offset = 0;
  15. uint64 value;
  16. bh_leb_read_status_t status =
  17. bh_leb_read(data.data(), data.data() + data.size(), sizeof(T) * 8,
  18. std::is_signed<T>::value, &value, &offset);
  19. ASSERT_EQ(expected_status, status);
  20. if (status == BH_LEB_READ_SUCCESS) {
  21. ASSERT_EQ(data.size(), offset);
  22. ASSERT_EQ(expected_value, (T)value);
  23. }
  24. }
  25. TEST(bh_leb128_test_suite, read_leb_u32)
  26. {
  27. run_read_leb_test<uint32>({ 0 }, BH_LEB_READ_SUCCESS,
  28. 0); // min value
  29. run_read_leb_test<uint32>({ 2 }, BH_LEB_READ_SUCCESS,
  30. 2); // single-byte value
  31. run_read_leb_test<uint32>({ 127 }, BH_LEB_READ_SUCCESS,
  32. 127); // max single-byte value
  33. run_read_leb_test<uint32>({ 128, 1 }, BH_LEB_READ_SUCCESS,
  34. 128); // min value with continuation bit
  35. run_read_leb_test<uint32>({ 160, 138, 32 }, BH_LEB_READ_SUCCESS,
  36. 525600); // arbitrary value
  37. run_read_leb_test<uint32>({ 255, 255, 255, 255, 15 }, BH_LEB_READ_SUCCESS,
  38. UINT32_MAX); // max value
  39. run_read_leb_test<uint32>({ 255, 255, 255, 255, 16 }, BH_LEB_READ_OVERFLOW,
  40. UINT32_MAX); // overflow
  41. run_read_leb_test<uint32>({ 255, 255, 255, 255, 128 }, BH_LEB_READ_TOO_LONG,
  42. 0);
  43. run_read_leb_test<uint32>({ 128 }, BH_LEB_READ_UNEXPECTED_END, 0);
  44. }
  45. TEST(bh_leb128_test_suite, read_leb_i64)
  46. {
  47. run_read_leb_test<int64>({ 184, 188, 195, 159, 237, 209, 128, 2 },
  48. BH_LEB_READ_SUCCESS,
  49. 1128712371232312); // arbitrary value
  50. run_read_leb_test<int64>(
  51. { 128, 128, 128, 128, 128, 128, 128, 128, 128, 127 },
  52. BH_LEB_READ_SUCCESS,
  53. (uint64)INT64_MIN); // min value
  54. run_read_leb_test<int64>({ 255, 255, 255, 255, 255, 255, 255, 255, 255, 0 },
  55. BH_LEB_READ_SUCCESS,
  56. INT64_MAX); // max value
  57. }