سؤال

I'm binding a third-party C API that uses string statuses a lot. E.g. (pseudocode):

ffi.cdef [[
  struct Reply { char * str; size_t len };
  Reply * doSomething();
  void freeReply(Reply * p);
]]

Most often str would be an "OK" string.

What is the fastest way to check that?

I would like to avoid string interning here:

local reply = ffi.gc(ffi.C.doSomething, ffi.C.freeReply)
assert(ffi.string(reply.str, reply.len) == "OK")
هل كانت مفيدة؟

المحلول

Not sure it is that much faster. What I would try is to call the strncmp from the standard C library.

Something like this:

ffi.cdef [[
  int strncmp ( const char * str1, const char * str2, size_t num );
]]

local ok = ffi.new("char[3]", "ok")

local reply = ffi.gc(ffi.C.doSomething, ffi.C.freeReply)
assert(ffi.C.strncmp(ok, reply.str, reply.len) == 0)

You may also try to first check that reply.len is 2 and then call memcmp instead of strncmp. It may be a little faster.

نصائح أخرى

This is going to be the fastest while not prettiest way in LuaJIT for a short string.

local reply = ffi.gc(ffi.C.doSomething, ffi.C.freeReply)
assert(reply.str[0] == 79 and  -- 79 = 'O' = string.byte("O")
       reply.str[1] == 75 and -- 75 = 'K'
       reply.str[2] == 0 )
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top