Type punning confusion

  • From: Finn Wilcox <finnw@xxxxxxxxxxx>
  • To: LuaJIT mailing list <luajit@xxxxxxxxxxxxx>
  • Date: Wed, 06 Nov 2013 21:40:51 +0000

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Is this a legitimate use of type punning via a union?
The assert fails shortly after entering the compiled loop (next time
the i<32 branch is taken.)  Is this related to aliasing rules?  Are
there caveats when using a union for type punning?  Or is it that I
should not be comparing a cdata value type to itself? (That seems to
work most of the time.)
It works with -joff, or if I create 2 unions and ffi.copy() from one
to the other.
- --

local ffi = require 'ffi'

assert(ffi.abi 'le')
local s = ffi.new [[
  union {
    int64_t q;
    struct { int32_t lo, hi; };
  }
]]

local function oneBit(i)
  i = bit.band(i, 63)
  s.q = 0
  if i < 32 then
    s.lo = bit.rol(1, i)
  else
    s.hi = bit.rol(1, i-32)
  end
  return s.q
end

for i = 1, 999 do
  assert(oneBit(i) == oneBit(i))
end
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.18 (Darwin)
Comment: GPGTools - http://gpgtools.org
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iQEcBAEBAgAGBQJSerdjAAoJEHp3pOlF38H/AL4H/12gCuED+ceQogJXrl2opjJB
B+fW0b8T8t+REdj4ay1O7BjhdYRv3zMPnYxdEQeg1W04oyc1gUUGssLxLIEMrodz
1hPlrKrb45iaCINArhVREXkCeq0IEI/TdPP4FWQdGsJ5+1ArccZAGvcLSQSiVpYn
IHeLOIoH++3BsbierJPtAWbp/BZR5WR9CKMwLEWCgVFK7VfgpN9JPn/gE6+RmS8g
Mt+rgP0RVJpZjfwgSurFq/fkOvU3heMBb3If/xqmzsXSF4lHlwxYlxg5Mxt6EJat
yHrjTf9bgd4OFI7myXqIEUWUqXNj1KMyHXAO8m6vOhKwyyySUEVK2FzM0xnWlAw=
=EUAA
-----END PGP SIGNATURE-----

Other related posts: