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

58 lines
1.7 KiB
TypeScript
Raw Normal View History

import { beforeAll, describe, expect, it } from 'vitest'
2023-11-04 06:44:18 +03:00
import { gzipSync } 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, gunzip, 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 gzipSyncWrap(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(gzipSync(data))
}
return gzipSync(data)
}
2023-11-04 06:44:18 +03:00
describe('gunzip', () => {
it('should correctly read zlib headers', () => {
const wasm = __getWasm()
2023-11-29 20:31:18 +03:00
const data = gzipSyncWrap(utf8EncodeToBuffer('hello world'))
2023-11-04 06:44:18 +03:00
const inputPtr = wasm.__malloc(data.length)
new Uint8Array(wasm.memory.buffer).set(data, inputPtr)
expect(wasm.libdeflate_gzip_get_output_size(inputPtr, data.length)).toEqual(11)
2023-11-04 06:44:18 +03:00
})
it('should correctly inflate', () => {
const data = Array.from({ length: 1000 }, () => 'a').join('')
2023-11-29 20:31:18 +03:00
const res = gzipSyncWrap(utf8EncodeToBuffer(data))
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(gunzip(res)).toEqual(new Uint8Array(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 = gzipSyncWrap(utf8EncodeToBuffer(data))
2023-11-04 06:44:18 +03:00
const res = gunzip(deflated)
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
})
})