varint-unit.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. * http://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 "common/test.h"
  19. #include "rpc/varint.h"
  20. #include <errno.h>
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <unistd.h>
  25. static int varint32_round_trip_test(int val)
  26. {
  27. int size;
  28. int32_t oval = 0;
  29. int32_t off = 0;
  30. uint8_t buf[16] = { 0 };
  31. const size_t buf_len = sizeof(buf)/sizeof(buf[0]);
  32. size = varint32_size(val);
  33. EXPECT_INT_ZERO(varint32_encode(val, buf, buf_len, &off));
  34. EXPECT_INT_EQ(size, off);
  35. off = 0;
  36. EXPECT_INT_ZERO(varint32_decode(&oval, buf, buf_len, &off));
  37. EXPECT_INT_EQ(size, off);
  38. EXPECT_INT_EQ(val, oval);
  39. return 0;
  40. }
  41. static int be32_round_trip_test(int val)
  42. {
  43. int32_t oval;
  44. uint8_t buf[sizeof(int32_t)] = { 0 };
  45. be32_encode(val, buf);
  46. oval = be32_decode(buf);
  47. EXPECT_INT_EQ(val, oval);
  48. return 0;
  49. }
  50. static int round_trip_test(int var)
  51. {
  52. EXPECT_INT_ZERO(varint32_round_trip_test(var));
  53. EXPECT_INT_ZERO(be32_round_trip_test(var));
  54. return 0;
  55. }
  56. int main()
  57. {
  58. round_trip_test(0);
  59. round_trip_test(123);
  60. round_trip_test(6578);
  61. round_trip_test(0x7fffffff);
  62. round_trip_test(-15);
  63. round_trip_test(-1);
  64. return EXIT_SUCCESS;
  65. }
  66. // vim: ts=4:sw=4:tw=79:et