fix(workspace): fast check svg buffer (#5032)

This commit is contained in:
EYHN 2023-11-22 14:53:33 +00:00
parent 06203498da
commit e8616acfe4
No known key found for this signature in database
GPG Key ID: 46C9E26A75AB276C
2 changed files with 45 additions and 1 deletions

View File

@ -0,0 +1,13 @@
import { Buffer } from 'node:buffer';
import { describe, expect, test } from 'vitest';
import { isSvgBuffer } from '../util';
describe('isSvgBuffer', () => {
test('basic', async () => {
expect(isSvgBuffer(Buffer.from('<svg></svg>'))).toBe(true);
expect(isSvgBuffer(Buffer.from(' \n\r\t<svg></svg>'))).toBe(true);
expect(isSvgBuffer(Buffer.from('<123>'))).toBe(false);
});
});

View File

@ -1,8 +1,39 @@
import isSvg from 'is-svg';
function fastCheckIsNotSvg(buffer: Uint8Array) {
// check first non-whitespace character is not '<svg'
for (let i = 0; i < buffer.length; i++) {
const ch = buffer[i];
// skip whitespace
if (
ch === 0x20 /* \s */ ||
ch === 0x09 /* \t */ ||
ch === 0x0b /* \v */ ||
ch === 0x0c /* \f */ ||
ch === 0x0a /* \n */ ||
ch === 0x0d /* \r */ ||
ch === 0xa0
) {
continue;
}
return !(
buffer[i] === /* '<' */ 0x3c &&
buffer[i + 1] === /* 's' */ 0x73 &&
buffer[i + 2] === /* 'v' */ 0x76 &&
buffer[i + 3] === /* 'g' */ 0x67
);
}
return true;
}
// this has a overhead of converting to string for testing if it is svg.
// is there a more performant way?
export function isSvgBuffer(buffer: Uint8Array) {
if (fastCheckIsNotSvg(buffer)) {
return false;
}
const decoder = new TextDecoder('utf-8');
const str = decoder.decode(buffer);
return isSvg(str);