Flutter Impeller
allocation_unittests.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <cstring>
6 #include <limits>
7 
8 #include "flutter/testing/testing.h"
10 
11 namespace impeller {
12 namespace testing {
13 
14 TEST(AllocationTest, ReserveNPOTPotentialOverflow) {
15  std::vector<uint8_t> data(64, 0xff);
16 
17  auto allocate_and_write = [&](uint64_t size) {
18  Allocation allocation;
19 
20  // Allocate a buffer with the size rounded up to the next power of two.
21  if (!allocation.Truncate(Bytes{size})) {
22  // Not enough memory available.
23  return;
24  }
25 
26  // If the allocation succeeded, then check that writes are safe.
27  memcpy(allocation.GetBuffer(), data.data(), data.size());
28  EXPECT_EQ(memcmp(allocation.GetBuffer(), data.data(), data.size()), 0);
29  };
30 
31  // Try allocations with sizes around the maximum 32-bit value.
32  allocate_and_write((1ULL << 32) + 1);
33  allocate_and_write((1ULL << 32) - 1);
34 
35  // Test that an allocation size that is out of range fails immediately.
36  Allocation max_allocation;
37  EXPECT_FALSE(
38  max_allocation.Truncate(Bytes{std::numeric_limits<uint64_t>::max()}));
39 }
40 
41 TEST(AllocationTest, NextPowerOfTwoSize) {
42  EXPECT_EQ(*Allocation::NextPowerOfTwoSize((1ULL << 32) - 1), 1ULL << 32);
43  EXPECT_EQ(*Allocation::NextPowerOfTwoSize((1ULL << 32) + 1), 1ULL << 33);
44  EXPECT_EQ(*Allocation::NextPowerOfTwoSize(1ULL << 63), 1ULL << 63);
45  EXPECT_EQ(Allocation::NextPowerOfTwoSize((1ULL << 63) + 1).status().code(),
46  absl::StatusCode::kInvalidArgument);
47  EXPECT_EQ(Allocation::NextPowerOfTwoSize(std::numeric_limits<uint64_t>::max())
48  .status()
49  .code(),
50  absl::StatusCode::kInvalidArgument);
51 }
52 
53 } // namespace testing
54 } // namespace impeller
Describes an allocation on the heap.
Definition: allocation.h:23
uint8_t * GetBuffer() const
Gets the pointer to the start of the allocation.
Definition: allocation.cc:20
static absl::StatusOr< uint64_t > NextPowerOfTwoSize(uint64_t x)
Gets the next power of two size.
Definition: allocation.cc:42
bool Truncate(Bytes length, bool npot=true)
Resize the underlying allocation to at least given number of bytes.
Definition: allocation.cc:32
TEST(AllocationSizeTest, CanCreateTypedAllocations)