lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Thu, Oct 1, 2020 at 8:50 AM Andrew Gierth
<andrew@tao11.riddles.org.uk> wrote:

> The spec allows [...]

Note that the original claim was about "ANSI C", i.e., C89. Where
union-based type punning is implementation-defined.

On the other hand, I do not think that adding volatile would change
that, i.e., make it standard rather than implementation-defined.

Moreover, in C++ union-based type punning is undefined behavior, and
since the Lua source code intends to be consumable as C++, this is a
problem that volatile does not correctly address, either.

I believe memcpy() is the only way that would be truly portable with
all those things considered.

The code in str_unpack() might look like:

      case Kfloat: {
        char buff[sizeof (double)]; /* instead of volatile Ftypes u; */
        lua_Number num;
        copywithendian(buff, data + pos, size, h.islittle);
        if (size == sizeof(u.f)) { float f; memcpy(&f, buff, sizeof
f); num = (lua_Number)f; }
        else if (size == sizeof(u.d)) { double d; memcpy(&d, buff,
sizeof d); num = (lua_Number)d; }
        else memcpy(&num, buff, sizeof num);
        lua_pushnumber(L, num);
        break;
      }

Cheers,
V.