Completed
Push — master ( 5856c5...90f7ba )
by Rudi
05:12
created

SquaredCapacity::square()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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 213
    private function square(int $capacity): int
19
    {
20 213
        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 30
    public function allocate(int $capacity)
32
    {
33 30
        $this->capacity = max($this->square($capacity), $this->capacity);
34 30
    }
35
36
    /**
37
     * Called when capacity should be increased to accommodate new values.
38
     */
39 183
    protected function increaseCapacity()
40
    {
41 183
        $this->capacity = $this->square(max(count($this), $this->capacity + 1));
42 183
    }
43
}
44