QML 的底层实现之 JavaScript 变量编码

QML 的底层实现之 JavaScript 变量编码

QML 是基于 ECMA-262(JavaScript),通过 Qt 的机制进行拓展的高级编程语言。下面会简单讲讲 JavaScript 变量是如何在 C++ 中定义的。

先看如下一段话:

We use two different ways of encoding JS values. One for 32bit and one for 64bit systems.

In both cases, we use 8 bytes for a value and a different variant of NaN boxing. A Double NaN (actually -qNaN)
is indicated by a number that has the top 13 bits set. The other values are usually set to 0 by the
processor, and are thus free for us to store other data. We keep pointers in there for managed objects,
and encode the other types using the free space given to use by the unused bits for NaN values. This also
works for pointers on 64 bit systems, as they all currently only have 48 bits of addressable memory.

On 32bit, we store doubles as doubles. All other values, have the high 32bits set to a value that
will make the number a NaN. The Masks below are used for encoding the other types.

On 64 bit, we xor Doubles with (0xffff8000 << 32). That has the effect that no doubles will get encoded
with the 13 highest bits all 0. We are now using special values for bits 14-17 to encode our values. These
can be used, as the highest valid pointer on a 64 bit system is 2^48-1.

If they are all 0, we have a pointer to a Managed object. If bit 14 is set we have an integer.
This makes testing for pointers and numbers very fast (we have a number if any of the highest 14 bits is set).

Bit 15-17 is then used to encode other immediates.

大意如下:

使用两种不同的方式对 JS 值进行编码,一种是 32 位,一种是 64 位。

在这两种情况下,使用 8 字节(int64)保存一个值或者一个包装了非数字变量的变体。使用前 13 个 bit 来标定 -qNaN,其他位一般置为零以便使用。在后 51 位中可以保存被管理对象的指针或者其他值,这是适用 64 位操作系统,因为现有的 64 位操作系统,一般只是用 48 位(2^48-1)进行寻址,这意味着有多余的 16 位( 2^16+1 )是不会被使用的。

在 32 位系统上,直接将双精度浮点数进行保存。高 32 位配合位遮罩保存不同的非数字变量,例如 int 和指针。

在 64 位上,通过 0xffff8000 << 32 这个位遮罩存取浮点数,这样的效果是,不直接对双精度进行编码,最高的 13 位直接置为零。现在可以使用 14~17 位对其他值进行编码,在64位系统上的最高有效指针是2 ^ 48-1。

如果最高的 14 位全为零,那么低 48 位保存的是一个指针,如果第 14 位置为 1,保存的便是一个整数。这让数字和指针在运算过程中变得十分快速。(最高的 14 位中,任意一位为 1,保存的便是整数)

然后使用 15-17 位来编码其他立即数。

总结一下,就是使用 int64 作为 JavaScript 运行的 var,这个 var 可以保存数字或者指针。

代码在这里 qv4value_p.h

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值