kernelsauce / turbo

Turbo is a framework built for LuaJIT 2 to simplify the task of building fast and scalable network applications. It uses a event-driven, non-blocking, no thread design to deliver excellent performance and minimal footprint to high-load applications while also providing excellent support for embedded uses.
http://turbo.readthedocs.io/
Apache License 2.0
528 stars 84 forks source link

Bug in util.strcasecmp() ? #141

Closed jfcap closed 10 years ago

jfcap commented 10 years ago

IMHO util.strcasecmp function is bugged

 util.strcasecmp('aaa','aba')==0 ??? 
-- Fast string case agnostic comparison
function util.strcasecmp(str1, str2)
    local r = 0;
    local b1,b2
    local i
    local len = ((#str1 > #str2) and #str1) or #str2 -- get the longer length

    for i = 1,len do

        b1,b2 = string.byte(str1,i), string.byte(str2,i)
        if b1 == nil then return -1 end
        if b2 == nil then return 1 end
        -- convert b1 and b2 to lower case
        b1 = ((b1 > 0x40) and (b1 < 0x5b) and bit.bor(b1,0x60)) or b1
        b2 = ((b2 > 0x40) and (b2 < 0x5b) and bit.bor(b2,0x60)) or b2
        r = b1 - b2
        -- add here something like : if r~=0 then return r end
    end

    return r
end
kernelsauce commented 10 years ago

This is something that was added by https://github.com/jsolman (Jeff).

I did not test this thing out as most of his code seems fine. I propose we just use the libc version which is already defined in cdef.lua, which probably also are faster:

 int strcasecmp(const char *s1, const char *s2);

so basically:

  function util.strcasecmp(str1, str2)
      return tonumber(ffi.C.strcasecmp(str1, str2))
  end

  --or for added safety:
  function util.strcasecmp(str1, str2)
      assert(type(str1)=="string" and type(str2)=="string", "Invalid arguments.")
      return tonumber(ffi.C.strcasecmp(str1, str2))
  end

Any reasons not to do this jsolman?

kernelsauce commented 10 years ago

Fixed now.

jsolman commented 10 years ago

Sorry for introducing that bug, it did need to break the loop if r ~=0. I must not have tested it properly myself.

jsolman commented 10 years ago

I don't know if it is actually faster or not, might depend on your libc, but since it is available might as well have used it as you did.