SquaredCapacity::square()   A
last analyzed

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\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
     * @inheritDoc
20
     */
21
    protected $capacity = self::MIN_CAPACITY;
22
23
    /**
24
     * Rounds an integer to the next power of two if not already a power of two.
25
     *
26
     * @param int $capacity
27
     *
28
     * @return int
29
     */
30
    private function square(int $capacity): int
31
    {
32
        return pow(2, ceil(log($capacity, 2)));
33
    }
34
35
    /**
36
     * Ensures that enough memory is allocated for a specified capacity. This
37
     * potentially reduces the number of reallocations as the size increases.
38
     *
39
     * @param int $capacity The number of values for which capacity should be
40
     *                      allocated. Capacity will stay the same if this value
41
     *                      is less than or equal to the current capacity.
42
     */
43
    public function allocate(int $capacity)
44
    {
45
        $this->capacity = max($this->square($capacity), $this->capacity);
46
    }
47
48
    /**
49
     * Called when capacity should be increased to accommodate new values.
50
     */
51
    protected function increaseCapacity()
52
    {
53
        $this->capacity = $this->square(max($this->count() + 1, $this->capacity * $this->getGrowthFactor()));
54
    }
55
56
    /**
57
     * Gets the size of the array.
58
     *
59
     * @return int
60
     */
61
    abstract protected function count(): int;
62
}
63