dynamic_memory.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
  3. */
  4. #include <gtest/gtest.h>
  5. #include <uavcan/dynamic_memory.hpp>
  6. TEST(DynamicMemory, Basic)
  7. {
  8. uavcan::PoolAllocator<128, 32> pool32;
  9. EXPECT_EQ(4, pool32.getNumFreeBlocks());
  10. EXPECT_EQ(0, pool32.getPeakNumUsedBlocks());
  11. const void* ptr1 = pool32.allocate(16);
  12. ASSERT_TRUE(ptr1);
  13. EXPECT_EQ(1, pool32.getNumUsedBlocks());
  14. EXPECT_FALSE(pool32.allocate(120));
  15. EXPECT_EQ(1, pool32.getNumUsedBlocks());
  16. pool32.deallocate(ptr1);
  17. EXPECT_EQ(0, pool32.getNumUsedBlocks());
  18. EXPECT_EQ(1, pool32.getPeakNumUsedBlocks());
  19. }
  20. TEST(DynamicMemory, OutOfMemory)
  21. {
  22. uavcan::PoolAllocator<64, 32> pool32;
  23. EXPECT_EQ(2, pool32.getNumFreeBlocks());
  24. EXPECT_EQ(0, pool32.getNumUsedBlocks());
  25. EXPECT_EQ(0, pool32.getPeakNumUsedBlocks());
  26. const void* ptr1 = pool32.allocate(32);
  27. ASSERT_TRUE(ptr1);
  28. EXPECT_EQ(1, pool32.getNumUsedBlocks());
  29. EXPECT_EQ(1, pool32.getPeakNumUsedBlocks());
  30. const void* ptr2 = pool32.allocate(32);
  31. ASSERT_TRUE(ptr2);
  32. EXPECT_EQ(2, pool32.getNumUsedBlocks());
  33. EXPECT_EQ(2, pool32.getPeakNumUsedBlocks());
  34. ASSERT_FALSE(pool32.allocate(32)); // No free blocks left --> UAVCAN_NULLPTR
  35. EXPECT_EQ(2, pool32.getNumUsedBlocks());
  36. EXPECT_EQ(0, pool32.getNumFreeBlocks());
  37. EXPECT_EQ(2, pool32.getPeakNumUsedBlocks());
  38. }
  39. TEST(DynamicMemory, LimitedPoolAllocator)
  40. {
  41. uavcan::PoolAllocator<128, 32> pool32;
  42. uavcan::LimitedPoolAllocator lim(pool32, 2);
  43. EXPECT_EQ(2, lim.getBlockCapacity());
  44. EXPECT_EQ(0, pool32.getPeakNumUsedBlocks());
  45. const void* ptr1 = lim.allocate(1);
  46. const void* ptr2 = lim.allocate(1);
  47. const void* ptr3 = lim.allocate(1);
  48. EXPECT_TRUE(ptr1);
  49. EXPECT_TRUE(ptr2);
  50. EXPECT_FALSE(ptr3);
  51. lim.deallocate(ptr2);
  52. const void* ptr4 = lim.allocate(1);
  53. lim.deallocate(ptr1);
  54. const void* ptr5 = lim.allocate(1);
  55. const void* ptr6 = lim.allocate(1);
  56. EXPECT_TRUE(ptr4);
  57. EXPECT_TRUE(ptr5);
  58. EXPECT_FALSE(ptr6);
  59. EXPECT_EQ(2, pool32.getPeakNumUsedBlocks());
  60. }