mirror of
https://github.com/toeverything/AFFiNE.git
synced 2024-11-26 17:03:46 +03:00
fix(workspace): fast check svg buffer (#5032)
This commit is contained in:
parent
06203498da
commit
e8616acfe4
13
packages/frontend/workspace/src/blob/__tests__/util.spec.ts
Normal file
13
packages/frontend/workspace/src/blob/__tests__/util.spec.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
@ -1,8 +1,39 @@
|
|||||||
import isSvg from 'is-svg';
|
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.
|
// 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) {
|
export function isSvgBuffer(buffer: Uint8Array) {
|
||||||
|
if (fastCheckIsNotSvg(buffer)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
const decoder = new TextDecoder('utf-8');
|
const decoder = new TextDecoder('utf-8');
|
||||||
const str = decoder.decode(buffer);
|
const str = decoder.decode(buffer);
|
||||||
return isSvg(str);
|
return isSvg(str);
|
||||||
|
Loading…
Reference in New Issue
Block a user