lua-users home
lua-l archive

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



Mike Pall kirjoitti 4.9.2005 kello 16.32:

Hi,

Asko Kauppi wrote:

n.b. normally the only place where enums are defined (within LuaX)
are the C modules. This comes from the simple reason that any
bitfields normally are used only in contact with C code.  In Lua only
world, there are other ways.


IMHO writing a C function for every bitfield I want to use
is not the way to go. Most of the bitfields I have are really
N bit integers and not enumerations. Of course bitfields are
a low-level approach, but they _are_ more generic. :-)

Hmm.. perhaps my (re)use of the enum name is misleading here. :)

Let's see your examples the way I'd have them (all features should build on practical samples, that's GOOD..:)


A simple example:

  local function wputd(n)
    if n < 0 then
      n = n + 4294967296
    end
    local r = n % 256
    n = (n - r) / 256
    wputb(r)
    r = n % 256
    n = (n - r) / 256
    wputb(r)
    r = n % 256
    n = (n - r) / 256
    wputb(r, n)
  end

Why oh why can't I simply write:

  local function wputd(n)
    wputb(bitfield(n, 0,8, 8,8, 16,8, 24,8))
  end

You're right; your use seems really to involve bitops on plain integers. For C API usage cases, that is not the issue: there the bitfields have both value and "type".

Let's have a go still:

Considering 'n' would be an "enum" with masks set up appropriately, the above would become:

local function wputd( n )
    wputb( n(MASK_000000FF) )
    wputb( n(MASK_0000FF00) )
    wputb( n(MASK_00FF0000) )
    wputb( n(MASK_FF000000) )
end

Call is overriden to provide the binary and (scaled to bit 0) of the value itself, and the mask. I consider this easy to read.

-ak


I spare you the code for some of the more uglier examples
like splitting the ModRM and SIB bytes of an x86 opcode. :-)

And I really don't want to write things like this anymore:

  local opcode = op == "movzx" and 4023 or 4031

But rather:

  local opcode = op == "movzx" and 0x0fb7 or 0x0fbf

local opcode = op == "movzx" and hex'0fb7' or hex'0fbf'

(as many others have pointed out... but you're right, it's sorta slow)


Just so this doesn't sound like a rant about a specific
application: dealing with some network protocols (like DNS
or TLS) is really, really ugly without hex numbers and
bitfields. Don't tell me I have to write this in C ...

Bye,
     Mike