static void TestAllocation() {
  static const int kNum = 100;
  void* ptr[kNum];
  for (int size = 8; size <= 65536; size*=2) {
    for (int i = 0; i < kNum; i++) {
      ptr[i] = malloc(size);
    }
    for (int i = 0; i < kNum; i++) {
      free(ptr[i]);
    }
  }
}

// Routine that does a bunch of MarkThreadIdle() calls in sequence
// without any intervening allocations
static void MultipleIdleCalls() {
  for (int i = 0; i < 4; i++) {
    MallocExtension::instance()->MarkThreadIdle();
  }
}

// Routine that does a bunch of MarkThreadIdle() calls in sequence
// with intervening allocations
static void MultipleIdleNonIdlePhases() {
  for (int i = 0; i < 4; i++) {
    TestAllocation();
    MallocExtension::instance()->MarkThreadIdle();
  }
}

// Get current thread cache usage
static size_t GetTotalThreadCacheSize() {
  size_t result;
  CHECK(MallocExtension::instance()->GetNumericProperty(
            "tcmalloc.current_total_thread_cache_bytes",
            &result));
  return result;
}

// Check that MarkThreadIdle() actually reduces the amount
// of per-thread memory.
static void TestIdleUsage() {
  const size_t original = GetTotalThreadCacheSize();

  TestAllocation();
  const size_t post_allocation = GetTotalThreadCacheSize();
  CHECK_GT(post_allocation, original);

  MallocExtension::instance()->MarkThreadIdle();
  const size_t post_idle = GetTotalThreadCacheSize();
  CHECK_LE(post_idle, original);

  // Log after testing because logging can allocate heap memory.
  VLOG(0, "Original usage: %" PRIuS "\n", original);
  VLOG(0, "Post allocation: %" PRIuS "\n", post_allocation);
  VLOG(0, "Post idle: %" PRIuS "\n", post_idle);
}

int main(int argc, char** argv) {
  RunThread(&TestIdleUsage);
  RunThread(&TestAllocation);
  RunThread(&MultipleIdleCalls);
  RunThread(&MultipleIdleNonIdlePhases);

  printf("PASS\n");
  return 0;
}
