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

SquaredCapacity   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 52
ccs 0
cts 23
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A square() 0 4 1
A allocate() 0 4 1
A increaseCapacity() 0 9 1
A ensureCapacity() 0 6 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