On Tue, May 31, 2011 at 11:51 PM, bofh <goodb...@gmail.com> wrote: > This is interesting. I would really appreciate it very much if you don't > mind elaborating a bit more for a non-programmer? Thanks!
The general idea which I believe is used by JS engines is to notice that javascript has two datatypes, floating point doubles and everything else (string, array, ...). A NaN is represented as the high 13 bits set to 1, meaning the bottom 51 can be used to store something else. Like a pointer to a string or array, plus some bits for type information and garbage collection. This makes your math code fast because it doesn't need to follow a pointer every time you add two numbers. It causes trouble because if you're lazy, you just assume all pointers (up to 64 bits) will fit in the limited space (maybe 44-48 bits), and then things break. Or you request the OS only give you low addresses (MAP_32BIT). Or you allocate a big block and manage it yourself, so you know all the pointers are close together. The technique is an old one. Usually, you'd store pointers, but reserve the low bit to mark integers. This has the effect of only giving you 31 bit integers. Javascript is based around doubles, so they did things in reverse and store doubles, but reserve special NaN patterns for pointers. I was first made aware of the NaN technique because it's used by luajit.