Passed
Push — master ( d0ebb7...0d8755 )
by Rudi
03:39
created

SquaredCapacity::increaseCapacity()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 9
cp 0
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
namespace Ds\Traits;
3
4
/**
5
 * Common to structures that require a capacity which is a power of two.
6
 */
7
trait SquaredCapacity
8
{
9
    use Capacity;
10
11
    /**
12
     * Rounds an integer to the next power of two if not already a power of two.
13
     *
14
     * @param int $capacity
15
     *
16
     * @return int
17
     */
18
    private function square(int $capacity): int
19
    {
20
        return pow(2, ceil(log($capacity, 2)));
21
    }
22
23
    /**
24
     * Ensures that enough memory is allocated for a specified capacity. This
25
     * potentially reduces the number of reallocations as the size increases.
26
     *
27
     * @param int $capacity The number of values for which capacity should be
28
     *                      allocated. Capacity will stay the same if this value
29
     *                      is less than or equal to the current capacity.
30
     */
31
    public function allocate(int $capacity)
32
    {
33
        $this->capacity = max($this->square($capacity), $this->capacity);
34
    }
35
36
    /**
37
     * Called when capacity should be increased to accommodate new values.
38
     */
39
    protected function increaseCapacity()
40
    {
41
        $this->capacity = $this->square(
42
            max(
43
                count($this) + 1,
44
                $this->capacity * $this->getGrowthFactor()
45
            )
46
        );
47
    }
48
49
    /**
50
     * @param int $total
51
     */
52
    protected function ensureCapacity(int $total)
53
    {
54
        while ($total > $this->capacity()) {
55
            $this->increaseCapacity();
56
        }
57
    }
58
}
59