1
|
|
|
<?php |
2
|
|
|
namespace Ds\Traits; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* Common to structures that deal with an internal capacity. While none of the |
6
|
|
|
* PHP implementations actually make use of a capacity, it's important to keep |
7
|
|
|
* consistent with the extension. |
8
|
|
|
*/ |
9
|
|
|
trait Capacity |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var int internal capacity |
13
|
|
|
*/ |
14
|
|
|
private $capacity = self::MIN_CAPACITY; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Returns the current capacity. |
18
|
|
|
* |
19
|
|
|
* @return int |
20
|
|
|
*/ |
21
|
63 |
|
public function capacity(): int |
22
|
|
|
{ |
23
|
63 |
|
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
|
12 |
|
public function allocate(int $capacity) |
35
|
|
|
{ |
36
|
12 |
|
$this->capacity = max($capacity, $this->capacity); |
37
|
12 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Called when capacity should be increased to accommodate new values. |
41
|
|
|
*/ |
42
|
|
|
abstract protected function increaseCapacity(); |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Adjusts the structure's capacity according to its current size. |
46
|
|
|
*/ |
47
|
1922 |
|
private function adjustCapacity() |
48
|
|
|
{ |
49
|
1922 |
|
$size = count($this); |
50
|
|
|
|
51
|
|
|
// Automatically truncate the allocated buffer when the size of the |
52
|
|
|
// structure drops low enough. |
53
|
1922 |
|
if ($size < $this->capacity / 4) { |
54
|
1306 |
|
$this->capacity = max(self::MIN_CAPACITY, $this->capacity / 2); |
55
|
|
|
} else { |
56
|
|
|
|
57
|
|
|
// Also check if we should increase capacity when the size changes. |
58
|
1201 |
|
if ($size >= $this->capacity) { |
59
|
264 |
|
$this->increaseCapacity(); |
60
|
|
|
} |
61
|
|
|
} |
62
|
1922 |
|
} |
63
|
|
|
} |
64
|
|
|
|