Repository navigation
Expand file tree
/
Copy pathCapacity.php
More file actions
109 lines (98 loc) · 2.72 KB
/
Copy pathCapacity.php
File metadata and controls
109 lines (98 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
namespace Ds\Traits;
/**
* Common to structures that deal with an internal capacity. While none of the
* PHP implementations actually make use of a capacity, it's important to keep
* consistent with the extension.
*/
trait Capacity
{
/**
* @var integer internal capacity
*/
private $capacity = self::MIN_CAPACITY;
/**
* Returns the current capacity.
*
* @return int
*/
public function capacity(): int
{
return $this->capacity;
}
/**
* Ensures that enough memory is allocated for a specified capacity. This
* potentially reduces the number of reallocations as the size increases.
*
* @param int $capacity The number of values for which capacity should be
* allocated. Capacity will stay the same if this value
* is less than or equal to the current capacity.
*/
public function allocate(int $capacity)
{
$this->capacity = max($capacity, $this->capacity);
}
/**
* @return float the structures growth factor.
*/
protected function getGrowthFactor(): float
{
return 2;
}
/**
* @return float to multiply by when decreasing capacity.
*/
protected function getDecayFactor(): float
{
return 0.5;
}
/**
* @return float the ratio between size and capacity when capacity should be
* decreased.
*/
protected function getTruncateThreshold(): float
{
return 0.25;
}
/**
* Checks and adjusts capacity if required.
*/
protected function checkCapacity()
{
if ($this->shouldIncreaseCapacity()) {
$this->increaseCapacity();
} else {
if ($this->shouldDecreaseCapacity()) {
$this->decreaseCapacity();
}
}
}
/**
* Called when capacity should be increased to accommodate new values.
*/
protected function increaseCapacity()
{
$this->capacity = max($this->count(), $this->capacity * $this->getGrowthFactor());
}
/**
* Called when capacity should be decrease if it drops below a threshold.
*/
protected function decreaseCapacity()
{
$this->capacity = max(self::MIN_CAPACITY, $this->capacity * $this->getDecayFactor());
}
/**
* @return bool whether capacity should be increased.
*/
protected function shouldDecreaseCapacity(): bool
{
return count($this) <= $this->capacity * $this->getTruncateThreshold();
}
/**
* @return bool whether capacity should be increased.
*/
protected function shouldIncreaseCapacity(): bool
{
return count($this) >= $this->capacity;
}
}