<commit_before>local ray_hits = {}
local function worldRayCastCallback(fixture, x, y, xn, yn, fraction)
  table.insert(ray_hits, {
    object = fixture:getUserData(),
    x = x,
    y = y,
    xn = xn,
    yn = yn,
    fraction = fraction
  })
  return 1
end

local function rayCast(world, x1, y1, x2, y2, callback)
  ray_hits = {}
  world:rayCast(x1, y1, x2, y2, worldRayCastCallback)
  return ray_hits
end

local function rayCastClosest(world, x1, y1, x2, y2, callback)
  rayCast(world, x1, y1, x2, y2, callback)
  if #ray_hits > 0 then
    local closest_hit = ray_hits[1]
    for i,hit in ipairs(ray_hits) do
      if hit.fraction < closest_hit.fraction then
        closest_hit = hit
      end
    end

    return closest_hit
  else
    return nil
  end
end

return rayCastClosest<commit_msg>optimize raycasts<commit_after>local ray_hits = {}
local num_hits = 0

-- Private constructor.
local function new(x, y, fraction)
  return setmetatable({
    x = x,
    y = y,
    fraction = fraction
  })
end

-- Do the check to see if JIT is enabled. If so use the optimized FFI structs.
local status, ffi
if type(jit) == "table" and jit.status() then
  status, ffi = pcall(require, "ffi")
  if status then
    ffi.cdef "typedef struct { double x, y, fraction; } ray_hit;"
    new = ffi.typeof("ray_hit")
  end
end

local function worldRayCastCallback(fixture, x, y, xn, yn, fraction)
  num_hits = num_hits + 1
  ray_hits[num_hits] = new(x, y, fraction)
  return 1
end

local function rayCastClosest(world, x1, y1, x2, y2)
  num_hits = 0
  world:rayCast(x1, y1, x2, y2, worldRayCastCallback)
  if num_hits > 0 then
    local closest_hit = ray_hits[1]
    for i=1,num_hits do
      local hit = ray_hits[i]
      if hit.fraction < closest_hit.fraction then
        closest_hit = hit
      end
    end

    return closest_hit
  else
    return nil
  end
end

return rayCastClosest
{'fraction_non_alphanumeric': 0.09498399146211313, 'fraction_numerical': 0.01814300960512273, 'mean_word_length': 3.1390728476821192, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '740940', 'n_tokens_mistral': 726, 'n_tokens_neox': 709, 'n_words': 213}