【发布时间】:2016-07-19 10:08:45
【问题描述】:
我和我的朋友前段时间研究过这个问题。它适用于 js-ctypes。在 Linux 中,有这些宏用于处理将文件描述符(uint32)列表添加到字节数组:FD_SET 和 FD_IS_SET。文档在这里 - http://linux.die.net/man/2/select
我想知道是否有人能够检查我是否做对了,或者是否有人知道有人在 javascript 中做过这件事?我需要完成对大端和小端的 32 位/64 位支持,但如果它已经存在,我很乐意看到它,因为我们在处理这个问题时有很多不确定性。
这是代码,fd_set_get_idx 是这一切所基于的辅助函数。
var MACROS = {
fd_set_set: function(fdset, fd) {
let { elem8, bitpos8 } = MACROS.fd_set_get_idx(fd);
console.info('elem8:', elem8.toString());
console.info('bitpos8:', bitpos8.toString());
fdset[elem8] = 1 << bitpos8;
},
fd_set_isset: function(fdset, fd) {
let { elem8, bitpos8 } = MACROS.fd_set_get_idx(fd);
console.info('elem8:', elem8.toString());
console.info('bitpos8:', bitpos8.toString());
return !!(fdset[elem8] & (1 << bitpos8));
},
fd_set_get_idx: function(fd) {
if (osname == 'darwin' /*is_mac*/) {
// We have an array of int32. This should hopefully work on Darwin
// 32 and 64 bit.
let elem32 = Math.floor(fd / 32);
let bitpos32 = fd % 32;
let elem8 = elem32 * 8;
let bitpos8 = bitpos32;
if (bitpos8 >= 8) { // 8
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 16
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 24
bitpos8 -= 8;
elem8++;
}
return {'elem8': elem8, 'bitpos8': bitpos8};
} else { // else if (osname == 'linux' /*is_linux*/) { // removed the else if so this supports bsd and solaris now
// :todo: add 32bit support
// Unfortunately, we actually have an array of long ints, which is
// a) platform dependent and b) not handled by typed arrays. We manually
// figure out which byte we should be in. We assume a 64-bit platform
// that is little endian (aka x86_64 linux).
let elem64 = Math.floor(fd / 64);
let bitpos64 = fd % 64;
let elem8 = elem64 * 8;
let bitpos8 = bitpos64;
if (bitpos8 >= 8) { // 8
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 16
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 24
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 32
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 40
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 48
bitpos8 -= 8;
elem8++;
}
if (bitpos8 >= 8) { // 56
bitpos8 -= 8;
elem8++;
}
return {'elem8': elem8, 'bitpos8': bitpos8};
}
}
};
【问题讨论】:
-
好老的
>>、<<和&、|有什么问题 -
另外,可以在那里使用
for循环... -
我不明白你是想模仿
FD_XXX函数还是必须遵守某些规定。 JS,特别是 ES6,如果你想使用它们,有 DataView 和 typed arrays。无论如何,如果FD_SET(i, set)的语义只是set[i] = i,我认为从头开始以任何字节序或大小实现它都没有任何问题。你能澄清一下吗?这个fdset[elem8] = 1 << bitpos8也可能是错误的。 -
非常感谢 @Margaret 和 Anti - 是的,我们试图模仿
FD_XXX,不符合任何规定。老实说,这是几年前的事了,如果语义正确,我不记得了。我不认为是,因为我刚才使用这个时,上面代码中的索引idx是不同的。 (这就是为什么我在这个问题中添加了 linux 和 c 的标签。我知道它可能会被关闭,但我没有其他人可以问谁有这种知识。我所有的技能都允许使用这些功能)
标签: javascript c linux macros jsctypes