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

SquaredCapacity   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 1
dl 0
loc 37
ccs 8
cts 8
cp 1
rs 10
c 0
b 0
f 0

3 Methods

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