mtcute/packages/wasm/tests/zlib.test.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

import { beforeAll, describe, expect, it } from 'vitest'
2023-11-04 06:44:18 +03:00
import { inflateSync } from 'zlib'
2023-11-29 20:31:18 +03:00
import { utf8Decode, utf8EncodeToBuffer } from '@mtcute/tl-runtime'
2023-11-04 06:44:18 +03:00
import { __getWasm, deflateMaxSize, initAsync } from '../src/index.js'
beforeAll(async () => {
2023-11-04 06:44:18 +03:00
await initAsync()
})
2023-11-29 20:31:18 +03:00
function inflateSyncWrap(data: Uint8Array) {
if (import.meta.env.TEST_ENV === 'browser') {
// @ts-expect-error fucking crutch because @jspm/core uses Buffer.isBuffer for some reason
data._isBuffer = true
return new Uint8Array(inflateSync(data))
}
return inflateSync(data)
}
2023-11-04 06:44:18 +03:00
describe('zlib deflate', () => {
it('should add zlib headers', () => {
2023-11-29 20:31:18 +03:00
const res = deflateMaxSize(utf8EncodeToBuffer('hello world'), 100)
2023-11-04 06:44:18 +03:00
expect(res).not.toBeNull()
expect(res!.slice(0, 2)).toEqual(new Uint8Array([0x78, 0x9c]))
2023-11-04 06:44:18 +03:00
})
it('should return null if compressed data is larger than size', () => {
2023-11-29 20:31:18 +03:00
const res = deflateMaxSize(utf8EncodeToBuffer('hello world'), 1)
2023-11-04 06:44:18 +03:00
expect(res).toBeNull()
2023-11-04 06:44:18 +03:00
})
it('should correctly deflate', () => {
const data = Array.from({ length: 1000 }, () => 'a').join('')
2023-11-29 20:31:18 +03:00
const res = deflateMaxSize(utf8EncodeToBuffer(data), 100)
2023-11-04 06:44:18 +03:00
expect(res).not.toBeNull()
expect(res!.length).toBeLessThan(100)
2023-11-29 20:31:18 +03:00
expect(inflateSyncWrap(res!)).toEqual(utf8EncodeToBuffer(data))
2023-11-04 06:44:18 +03:00
})
it('should not leak memory', () => {
const memSize = __getWasm().memory.buffer.byteLength
for (let i = 0; i < 100; i++) {
const data = Array.from({ length: 1000 }, () => 'a').join('')
2023-11-29 20:31:18 +03:00
const deflated = deflateMaxSize(utf8EncodeToBuffer(data), 100)
2023-11-04 06:44:18 +03:00
2023-11-29 20:31:18 +03:00
const res = inflateSyncWrap(deflated!)
2023-11-04 06:44:18 +03:00
2023-11-29 20:31:18 +03:00
expect(utf8Decode(res)).toEqual(data)
2023-11-04 06:44:18 +03:00
}
expect(__getWasm().memory.buffer.byteLength).toEqual(memSize)
2023-11-04 06:44:18 +03:00
})
})