topazcube 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ const browserFormat = 'gzip'
2
+
3
+ const MIN_COMPRESSED_BUFFER_SIZE = 256
4
+
5
+ export async function compress(buffer) {
6
+ if (buffer.byteLength <= MIN_COMPRESSED_BUFFER_SIZE) return buffer
7
+ if (typeof CompressionStream !== 'undefined') {
8
+ const cs = new CompressionStream(browserFormat)
9
+ const compressed = await new Response(
10
+ new Blob([buffer]).stream().pipeThrough(cs)
11
+ ).arrayBuffer()
12
+ return compressed
13
+ } else {
14
+ throw new Error('CompressionStream not supported')
15
+ }
16
+ }
17
+
18
+ export async function decompress(buffer) {
19
+ if (typeof DecompressionStream !== 'undefined') {
20
+ try {
21
+ const ds = new DecompressionStream(browserFormat)
22
+ const decompressed = await new Response(
23
+ new Blob([buffer]).stream().pipeThrough(ds)
24
+ ).arrayBuffer()
25
+ //console.log(` ${buffer.byteLength} -> ${decompressed.byteLength}`)
26
+ return decompressed
27
+ } catch (e) {
28
+ //console.error('Decompression failed:', e)
29
+ return buffer
30
+ }
31
+ } else {
32
+ throw new Error('DecompressionStream not supported')
33
+ }
34
+ }
@@ -0,0 +1,39 @@
1
+ import { promisify } from 'util'
2
+ import { gzip, gunzip, constants } from 'zlib'
3
+
4
+ const MIN_COMPRESSED_BUFFER_SIZE = 256
5
+ const MAX_COMPRESSED_BUFFER_SIZE = 999999
6
+
7
+ const lib_compress = promisify(gzip)
8
+ const lib_decompress = promisify(gunzip)
9
+
10
+ export async function compress(buffer) {
11
+ if (buffer.byteLength <= MIN_COMPRESSED_BUFFER_SIZE || buffer.byteLength >= MAX_COMPRESSED_BUFFER_SIZE) return buffer
12
+ try {
13
+ let t1 = Date.now()
14
+ let cbytes = await lib_compress(buffer, {
15
+ level: constants.Z_BEST_SPEED
16
+ })
17
+ let t2 = Date.now()
18
+ let cbuffer = Buffer.from(cbytes)
19
+ let t3 = Date.now()
20
+
21
+ //console.log(`Node compression ${buffer.byteLength} -> ${cbuffer.byteLength}, time: ${t2 - t1}ms`)
22
+
23
+ return cbuffer
24
+ } catch (error) {
25
+ console.error('Error compressing buffer:', error)
26
+ return buffer
27
+ }
28
+ }
29
+
30
+ export async function decompress(buffer) {
31
+ try {
32
+ let cbytes = await lib_decompress(buffer)
33
+ let cbuffer = Buffer.from(cbytes)
34
+ return cbuffer
35
+ } catch (error) {
36
+ console.error('Error decompressing buffer:', error)
37
+ return buffer
38
+ }
39
+ }