@cantoo/pdf-lib
Version:
Create and modify PDF files with JavaScript
105 lines • 3.71 kB
JavaScript
import { NumberParsingError } from '../errors.js';
import CharCodes from '../syntax/CharCodes.js';
import { IsDigit, IsNumeric } from '../syntax/Numeric.js';
import { IsWhitespace } from '../syntax/Whitespace.js';
import { charFromCode } from '../../utils/index.js';
const { Newline, CarriageReturn } = CharCodes;
// TODO: Throw error if eof is reached before finishing object parse...
class BaseParser {
constructor(bytes, capNumbers = false) {
this.bytes = bytes;
this.capNumbers = capNumbers;
}
parseRawInt() {
let value = '';
while (!this.bytes.done()) {
const byte = this.bytes.peek();
if (!IsDigit[byte])
break;
value += charFromCode(this.bytes.next());
}
const numberValue = Number(value);
if (!value || !isFinite(numberValue)) {
throw new NumberParsingError(this.bytes.position(), value);
}
return numberValue;
}
// TODO: Maybe handle exponential format?
// TODO: Compare performance of string concatenation to charFromCode(...bytes)
parseRawNumber() {
let value = '';
// Parse integer-part, the leading (+ | - | . | 0-9)
while (!this.bytes.done()) {
const byte = this.bytes.peek();
if (!IsNumeric[byte])
break;
value += charFromCode(this.bytes.next());
if (byte === CharCodes.Period)
break;
}
// Parse decimal-part, the trailing (0-9)
while (!this.bytes.done()) {
const byte = this.bytes.peek();
if (!IsDigit[byte])
break;
value += charFromCode(this.bytes.next());
}
const numberValue = Number(value);
if (!value || !isFinite(numberValue)) {
throw new NumberParsingError(this.bytes.position(), value);
}
if (numberValue > Number.MAX_SAFE_INTEGER) {
if (this.capNumbers) {
const msg = `Parsed number that is too large for some PDF readers: ${value}, using Number.MAX_SAFE_INTEGER instead.`;
console.warn(msg);
return Number.MAX_SAFE_INTEGER;
}
else {
const msg = `Parsed number that is too large for some PDF readers: ${value}, not capping.`;
console.warn(msg);
}
}
return numberValue;
}
skipWhitespace() {
while (!this.bytes.done() && IsWhitespace[this.bytes.peek()]) {
this.bytes.next();
}
}
skipLine() {
while (!this.bytes.done()) {
const byte = this.bytes.peek();
if (byte === Newline || byte === CarriageReturn)
return;
this.bytes.next();
}
}
skipComment() {
if (this.bytes.peek() !== CharCodes.Percent)
return false;
while (!this.bytes.done()) {
const byte = this.bytes.peek();
if (byte === Newline || byte === CarriageReturn)
return true;
this.bytes.next();
}
return true;
}
skipWhitespaceAndComments() {
this.skipWhitespace();
while (this.skipComment())
this.skipWhitespace();
}
matchKeyword(keyword) {
const initialOffset = this.bytes.offset();
for (let idx = 0, len = keyword.length; idx < len; idx++) {
if (this.bytes.done() || this.bytes.next() !== keyword[idx]) {
this.bytes.moveTo(initialOffset);
return false;
}
}
return true;
}
}
export default BaseParser;
//# sourceMappingURL=BaseParser.js.map