1 // Copyright 2019 Google LLC.
2 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3
4 #include "include/private/base/SkContainers.h"
5
6 #include "include/private/base/SkAlign.h"
7 #include "include/private/base/SkAssert.h"
8 #include "include/private/base/SkMalloc.h"
9 #include "include/private/base/SkTo.h"
10
11 #include <algorithm>
12 #include <cstddef>
13
14 namespace {
15 // Return at least as many bytes to keep malloc aligned.
16 constexpr size_t kMinBytes = alignof(max_align_t);
17
complete_size(void * ptr,size_t size)18 SkSpan<std::byte> complete_size(void* ptr, size_t size) {
19 if (ptr == nullptr) {
20 return {};
21 }
22
23 return {static_cast<std::byte*>(ptr), sk_malloc_size(ptr, size)};
24 }
25 } // namespace
26
allocate(int capacity,double growthFactor)27 SkSpan<std::byte> SkContainerAllocator::allocate(int capacity, double growthFactor) {
28 SkASSERT(capacity >= 0);
29 SkASSERT(growthFactor >= 1.0);
30 SkASSERT_RELEASE(capacity <= fMaxCapacity);
31
32 if (growthFactor > 1.0 && capacity > 0) {
33 capacity = this->growthFactorCapacity(capacity, growthFactor);
34 }
35
36 return sk_allocate_throw(capacity * fSizeOfT);
37 }
38
roundUpCapacity(int64_t capacity) const39 size_t SkContainerAllocator::roundUpCapacity(int64_t capacity) const {
40 SkASSERT(capacity >= 0);
41
42 // If round will not go above fMaxCapacity return rounded capacity.
43 if (capacity < fMaxCapacity - kCapacityMultiple) {
44 return SkAlignTo(capacity, kCapacityMultiple);
45 }
46
47 return SkToSizeT(fMaxCapacity);
48 }
49
growthFactorCapacity(int capacity,double growthFactor) const50 size_t SkContainerAllocator::growthFactorCapacity(int capacity, double growthFactor) const {
51 SkASSERT(capacity >= 0);
52 SkASSERT(growthFactor >= 1.0);
53 // Multiply by the growthFactor. Remember this must be done in 64-bit ints and not
54 // size_t because size_t changes.
55 const int64_t capacityGrowth = static_cast<int64_t>(capacity * growthFactor);
56
57 // Notice that for small values of capacity, rounding up will provide most of the growth.
58 return this->roundUpCapacity(capacityGrowth);
59 }
60
61
sk_allocate_canfail(size_t size)62 SkSpan<std::byte> sk_allocate_canfail(size_t size) {
63 // Make sure to ask for at least the minimum number of bytes.
64 const size_t adjustedSize = std::max(size, kMinBytes);
65 void* ptr = sk_malloc_canfail(adjustedSize);
66 return complete_size(ptr, adjustedSize);
67 }
68
sk_allocate_throw(size_t size)69 SkSpan<std::byte> sk_allocate_throw(size_t size) {
70 if (size == 0) {
71 return {};
72 }
73 // Make sure to ask for at least the minimum number of bytes.
74 const size_t adjustedSize = std::max(size, kMinBytes);
75 void* ptr = sk_malloc_throw(adjustedSize);
76 return complete_size(ptr, adjustedSize);
77 }
78
sk_report_container_overflow_and_die()79 void sk_report_container_overflow_and_die() {
80 SK_ABORT("Requested capacity is too large.");
81 }
82