[英]How to deflate a TypedArray uzing zlib in node.js?
For some Int32Array a
, I have tried this: 对于一些Int32Array a
,我试过这个:
var d = zlib.deflateSync(new Buffer(a));
But when I do 但是,当我这样做
var b = new Int32Array(zlib.inflateSync(d));
I get b
which is different than a
. 我得到的b
与a
不同。
I am aware of idea of turning the array into a string before deflating. 我知道在缩小之前将数组转换为字符串的想法。 This is just not memory efficient. 这不是内存效率。
Is there a way to do this efficiently? 有没有办法有效地做到这一点?
The main problem here is not in deflating and inflating, as those two actions just transfer data from one Buffer
element to another Buffer
element, and vice versa, as expected. 这里的主要问题不是放气和膨胀,因为这两个动作只是将数据从一个Buffer
元素传输到另一个Buffer
元素,反之亦然。 Problem here is how to transfer typed array (eg Int32Array
) to Buffer
, and from Buffer
back to typed array. 这里的问题是如何将类型化数组(例如Int32Array
)传输到Buffer
,以及从Buffer
传输回类型化数组。 To do that we have to deal with Buffer
, ArrayBuffer
, and typed arrays here. 要做到这一点,我们必须在这里处理Buffer
, ArrayBuffer
和typed数组。
Let's have Int32Array
a
to start with: 让我们以Int32Array
a
开头:
var a = new Int32Array([3,-2,258]);
If you create a Buffer
from this typed array directly with var b = new Buffer(b);
如果使用var b = new Buffer(b);
直接从这个类型化数组创建一个Buffer
var b = new Buffer(b);
, you will get a buffer which contain 3 bytes instead of 12 (each element in Int32Array
has 4 bytes), which means you will lose some information. ,您将获得一个缓冲区,该缓冲区包含3个字节而不是12个字节( Int32Array
每个元素都有4个字节),这意味着您将丢失一些信息。 The right way to do this is to create Buffer
from ArrayBuffer
. 正确的方法是从ArrayBuffer
创建Buffer
。 You can do it like so: 你可以这样做:
var b = new Buffer(a.buffer);
That way you get a Buffer
which contains 12 bytes. 这样,您将获得一个包含12个字节的Buffer
。 Now it is easy to deflate and inflate this buffer b
: 现在很容易收缩和膨胀这个缓冲区b
:
var c = zlib.deflateSync(b);
var d = zlib.inflateSync(c);
Now buffers d
and b
contain the same elements. 现在缓冲区d
和b
包含相同的元素。 Nothing special about this. 没什么特别的。
Now if you create Int32Array
directly from Buffer
d
, you will get 4 times more elements that you should because each byte in the Buffer
d
will be mapped to one element in Int32Array
. 现在,如果直接从Buffer
d
创建Int32Array
,您将得到的元素要多4倍,因为Buffer
d
中的每个字节都将映射到Int32Array
一个元素。 To overcome this problem, we will use Uint8Array
: 要解决这个问题,我们将使用Uint8Array
:
var e = new Uint8Array(d);
We used Uint8Array
just to map each byte of the buffer d
to one byte of an typed array of which we now have access to its ArrayBuffer
. 我们使用Uint8Array
只是将缓冲区d
每个字节映射到类型化数组的一个字节,现在可以访问该类型化数组的ArrayBuffer
。 The last step is to create the final Int32Array
from ArrayBuffer
of typed array e
: 最后一步是从类型为数组e
ArrayBuffer
创建最终的Int32Array
:
var f = new Int32Array(e.buffer);
Finally we have f
that looks the same as a
. 最后我们看到f
看起来和a
。
Note that some steps above depend on Endianness . 请注意,上述某些步骤取决于Endianness 。 If you do all this on the same machine you should be fine with the steps above. 如果你在同一台机器上完成所有这些操作,你可以按照上述步骤进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.