优化跳过性能

This commit is contained in:
2020-12-19 15:17:13 +08:00
parent 4c4be41f8b
commit 89470252e7
3 changed files with 100 additions and 44 deletions

View File

@ -47,22 +47,18 @@ abstract class ReaderInterface
*/
abstract public function moveToNextToken(): bool;
/**
* 跳过当前行
* @return bool
* @author Jerry Yan <792602257@qq.com>
* @date 2020/12/17 15:43
*/
abstract public function skipCurrentLine(): bool;
abstract protected function getBetween(int $start = 0, int $end = 0): string;
/**
* 从当前位置跳到结束位置
* @param string $end
* @return bool
* @param string[] $chars
* @param int|null $startAt
* @param string $matched
* @return int|null
* @author Jerry Yan <792602257@qq.com>
* @date 2020/12/17 15:43
*/
abstract public function skipUntil(string $end = "*/"): bool;
abstract public function findNextChars(array $chars, int $startAt = null, string &$matched = ""): ?int;
/**
* 重置读取器
@ -113,15 +109,84 @@ abstract class ReaderInterface
return $this->currentToken;
}
protected function moveCursorToNextChar(): void
/**
* 跳过当前行
* @return bool
* @author Jerry Yan <792602257@qq.com>
* @date 2020/12/17 15:43
*/
public function skipCurrentLine(): bool
{
$this->currentPosition++;
$_ = $this->moveCursorToNextLine();
if ($_ === false) return false;
return $this->moveToNextToken();
}
protected function moveCursorToNextLine(int $chars = 1): void
/**
* 移动Cursor至下一字符
* @param int $charLength
* @author Jerry Yan <792602257@qq.com>
* @date 2020/12/19 15:05
*/
protected function moveCursorToNextChar(int $charLength = 1): void
{
$this->currentPosition += $chars;
$this->currentPosition += $charLength;
}
/**
* 移动Cursor至下一行
* @param int|null $newPos 下一行位置,不提供则手动检测
* @return bool
* @author Jerry Yan <792602257@qq.com>
* @date 2020/12/19 15:05
*/
protected function moveCursorToNextLine(int $newPos = null): bool
{
if ($newPos === null) {
$curPos = $this->currentPosition;
$newPos = $this->findNextChars(["\r\n", "\r", "\n"], $curPos);
if ($newPos === null) return false;
$this->nextPosition = $newPos;
}
$this->moveCursorToNextChar($newPos - $this->currentPosition);
$this->currentLineDelta = $this->currentPosition;
$this->currentLine++;
return true;
}
/**
* Cursor向后移动多少字符
* @param int $length 字符长度
* @return bool 是否成功
* @author Jerry Yan <792602257@qq.com>
* @date 2020/12/19 15:13
*/
protected function moveCursorAfter(int $length): bool
{
$lastLinePos = $pos = $this->currentPosition;
$end = $pos + $length;
while ($pos < $end) {
$pos = $this->findNextChars(["\r\n", "\r", "\n"], $pos);
if ($pos === null || $pos > $end) break;
$this->moveCursorToNextLine($pos);
$lastLinePos = $pos;
}
$this->moveCursorToNextChar($end - $lastLinePos);
return true;
}
/**
* 移动到新的位置
* @param int $newPos
* @return bool
* @author Jerry Yan <792602257@qq.com>
* @date 2020/12/19 15:14
*/
protected function moveCursorTo(int $newPos): bool
{
// TODO: Forward Or Backward
$this->moveCursorAfter($newPos - $this->currentPosition);
return false;
}
}