Completed
Push — master ( e0916e...38b230 )
by Rudi
05:33
created

Capacity::allocate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Ds\Traits;
3
4
/**
5
 * Capacity
6
 *
7
 * @package Ds\Traits
8
 */
9
trait Capacity
10
{
11
    /**
12
     * @var int
13
     */
14
    private $capacity = self::MIN_CAPACITY;
15
16
    /**
17
     * Returns the current capacity.
18
     *
19
     * @return int
20
     */
21
    public function capacity(): int
22
    {
23
        return $this->capacity;
24
    }
25
26
    /**
27
     * Ensures that enough memory is allocated for a specified capacity. This
28
     * potentially reduces the number of reallocations as the size increases.
29
     *
30
     * @param int $capacity The number of values for which capacity should be
31
     *                      allocated. Capacity will stay the same if this value
32
     *                      is less than or equal to the current capacity.
33
     */
34
    public function allocate(int $capacity)
35
    {
36
        $this->capacity = max($capacity, $this->capacity);
37
    }
38
39
    /**
40
     * Increase Capacity
41
     */
42
    abstract protected function increaseCapacity();
43
44
    /**
45
     * Adjust Capacity
46
     */
47
    private function adjustCapacity()
48
    {
49
        $size = count($this);
50
51
        if ($size >= $this->capacity) {
52
            $this->increaseCapacity();
53
54
        } else {
55
            if ($size < $this->capacity / 4) {
56
                $this->capacity = max(self::MIN_CAPACITY, $this->capacity / 2);
57
            }
58
        }
59
    }
60
}
61