Passed
Push — 1.x ( 7cd7c5...aa2bc9 )
by Ulises Jeremias
02:24
created

SquaredCapacity::allocate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php namespace Mbh\Collection\Traits;
2
3
/**
4
 * MBHFramework
5
 *
6
 * @link      https://github.com/MBHFramework/mbh-framework
7
 * @copyright Copyright (c) 2017 Ulises Jeremias Cornejo Fandos
8
 * @license   https://github.com/MBHFramework/mbh-framework/blob/master/LICENSE (MIT License)
9
 */
10
11
 /**
12
  * Common to structures that require a capacity which is a power of two.
13
  */
14
trait SquaredCapacity
15
{
16
    use Capacity;
17
18
    /**
19
     * Rounds an integer to the next power of two if not already a power of two.
20
     *
21
     * @param int $capacity
22
     *
23
     * @return int
24
     */
25
    private function square(int $capacity): int
26
    {
27
        return pow(2, ceil(log($capacity, 2)));
28
    }
29
30
    /**
31
     * Ensures that enough memory is allocated for a specified capacity. This
32
     * potentially reduces the number of reallocations as the size increases.
33
     *
34
     * @param int $capacity The number of values for which capacity should be
35
     *                      allocated. Capacity will stay the same if this value
36
     *                      is less than or equal to the current capacity.
37
     */
38
    public function allocate(int $capacity)
39
    {
40
        $this->capacity = max($this->square($capacity), $this->capacity);
0 ignored issues
show
Bug Best Practice introduced by
The property capacity does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
41
    }
42
43
    /**
44
     * Called when capacity should be increased to accommodate new values.
45
     */
46
    protected function increaseCapacity()
47
    {
48
        $this->capacity = $this->square(max($this->count() + 1, $this->capacity * $this->getGrowthFactor()));
0 ignored issues
show
Bug Best Practice introduced by
The property capacity does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
49
    }
50
51
    /**
52
     * Gets the size of the array.
53
     *
54
     * @return int
55
     */
56
    abstract protected function count(): int;
57
}
58