robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

bfredlMerge pull request #39736 from bfredl/odod8275b7b491

master
4.0 KiB152 linesraw
1---@diagnostic disable: no-unknown
2-- HASHY McHASHFACE
3
4local M = {}
5_G.d = M
6
7local function setdefault(table, key)
8  local val = table[key]
9  if val == nil then
10    val = {}
11    table[key] = val
12  end
13  return val
14end
15
16function M.build_pos_hash(strings)
17  local len_buckets = {}
18  local maxlen = 0
19  for _, s in ipairs(strings) do
20    table.insert(setdefault(len_buckets, #s), s)
21    if #s > maxlen then
22      maxlen = #s
23    end
24  end
25
26  local len_pos_buckets = {}
27  local worst_buck_size = 0
28
29  for len = 1, maxlen do
30    local strs = len_buckets[len]
31    if strs then
32      -- the best position so far generates `best_bucket`
33      -- with `minsize` worst case collisions
34      local bestpos, minsize, best_bucket = nil, #strs * 2, nil
35      for pos = 1, len do
36        local try_bucket = {}
37        for _, str in ipairs(strs) do
38          local poschar = string.sub(str, pos, pos)
39          table.insert(setdefault(try_bucket, poschar), str)
40        end
41        local maxsize = 1
42        for _, pos_strs in pairs(try_bucket) do
43          maxsize = math.max(maxsize, #pos_strs)
44        end
45        if maxsize < minsize then
46          bestpos = pos
47          minsize = maxsize
48          best_bucket = try_bucket
49        end
50      end
51      len_pos_buckets[len] = { bestpos, best_bucket }
52      worst_buck_size = math.max(worst_buck_size, minsize)
53    end
54  end
55  return len_pos_buckets, maxlen, worst_buck_size
56end
57
58function M.switcher(put, tab, maxlen, worst_buck_size, icase)
59  local neworder = {} --- @type string[]
60  put '  switch (len) {\n'
61  local bucky = worst_buck_size > 1
62  for len = 1, maxlen do
63    local vals = tab[len]
64    if vals then
65      put('    case ' .. len .. ': ')
66      local pos, posbuck = unpack(vals)
67      local keys = vim.tbl_keys(posbuck)
68      if #keys > 1 then
69        table.sort(keys)
70        put('switch (str[' .. (pos - 1) .. ']) {\n')
71        for _, c in ipairs(keys) do
72          local buck = posbuck[c]
73          local startidx = #neworder
74          vim.list_extend(neworder, buck)
75          local endidx = #neworder
76          if icase and c:upper() ~= c:lower() then
77            put(("      case '%s': case '%s': "):format(c:upper(), c:lower()))
78          else
79            put(("      case '%s': "):format(c))
80          end
81          if len == 1 then
82            put('return ' .. startidx .. ';\n')
83          else
84            put('low = ' .. startidx .. '; ')
85            if bucky then
86              put('high = ' .. endidx .. '; ')
87            end
88            put 'break;\n'
89          end
90        end
91        put '      default: break;\n'
92        put '    }\n    '
93      else
94        local startidx = #neworder
95        table.insert(neworder, posbuck[keys[1]][1])
96        local endidx = #neworder
97        put('low = ' .. startidx .. '; ')
98        if bucky then
99          put('high = ' .. endidx .. '; ')
100        end
101      end
102      put 'break;\n'
103    end
104  end
105  put '    default: break;\n'
106  put '  }\n'
107  return neworder
108end
109
110--- @param icase? boolean generate a case-insensitive hash function.
111---                       `strings` must not have mixed case when using this.
112function M.hashy_hash(name, strings, access, icase)
113  local stats = {}
114  local put = function(str)
115    table.insert(stats, str)
116  end
117  local len_pos_buckets, maxlen, worst_buck_size = M.build_pos_hash(strings)
118  put('int ' .. name .. '_hash(const char *str, size_t len)\n{\n')
119  if maxlen == 1 then
120    put('\n') -- nothing
121  elseif worst_buck_size > 1 then
122    put('  int low = 0, high = 0;\n')
123  else
124    put('  int low = -1;\n')
125  end
126  local neworder = M.switcher(put, len_pos_buckets, maxlen, worst_buck_size, icase)
127  if maxlen == 1 then
128    put([[
129  return -1;
130]])
131  elseif worst_buck_size > 1 then
132    put(([[
133  for (int i = low; i < high; i++) {
134    if (!%s(str, %s, len)) {
135      return i;
136    }
137  }
138  return -1;
139]]):format(icase and 'vim_strnicmp_asc' or 'memcmp', access('i')))
140  else
141    put(([[
142  if (low < 0 || %s(str, %s, len) != 0) {
143    return -1;
144  }
145  return low;
146]]):format(icase and 'vim_strnicmp_asc' or 'memcmp', access('low')))
147  end
148  put '}\n\n'
149  return neworder, table.concat(stats)
150end
151
152return M