Repository navigation
Expand file tree
/
Copy pathEfficientLineCols.php
More file actions
101 lines (85 loc) · 2.8 KB
/
Copy pathEfficientLineCols.php
File metadata and controls
101 lines (85 loc) · 2.8 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
<?php
namespace Phpactor\TextDocument;
use OutOfBoundsException;
use RuntimeException;
/**
* Efficiently compute line/col positions for batches of byte offsets.
*
* This class accepts a list of byte offsets and a text document. It will
* iterate over the text document _once_ indexing the line/col position of the
* byte offset.
*/
final class EfficientLineCols
{
/**
* @param array<int,LineCol> $positions
*/
private function __construct(private array $positions)
{
}
/**
* Initialize the converter with the list of byte offsets to be converted.
*
* For converting to LSP positions there is a flag to return the character
* offset.Note that, like the line/col number, this is 1 based.
* @param list<int> $byteOffsetInts
*/
public static function fromByteOffsetInts(
string $text,
array $byteOffsetInts,
bool $charOffset = false
): self {
sort($byteOffsetInts);
$lines = preg_split('{(' . LineCol::NEWLINE_PATTERN . ')}', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
if (false === $lines) {
throw new RuntimeException(
'Failed to preg-split text into lines'
);
}
$offset = 0;
$lineNb = 0;
$byteOffset = array_shift($byteOffsetInts);
if (null === $byteOffset) {
return new EfficientLineCols([]);
}
$positions = [];
foreach ($lines as $lineOrDelim) {
$lineOrDelim = (string)$lineOrDelim;
if ((bool)preg_match('{(' . LineCol::NEWLINE_PATTERN . ')}', (string)$lineOrDelim)) {
$offset += strlen($lineOrDelim);
continue;
}
$lineNb++;
$start = $offset;
$end = $offset + strlen($lineOrDelim);
while ($byteOffset >= $start && $byteOffset <= $end) {
$section = substr(
$lineOrDelim,
0,
$byteOffset - $start
);
$positions[$byteOffset] = new LineCol(
$lineNb,
$charOffset ? strlen($section) + 1 : mb_strlen($section) + 1
);
$byteOffset = array_shift($byteOffsetInts);
if (null === $byteOffset) {
break;
}
}
$offset = $end;
}
/** @var array<int,LineCol> $positions */
return new EfficientLineCols($positions);
}
public function get(int $offset): LineCol
{
if (!isset($this->positions[$offset])) {
throw new OutOfBoundsException(sprintf(
'Pre-computed position not known for offset: %s',
$offset
));
}
return $this->positions[$offset];
}
}