Skip to content

Commit

Permalink
feat: ffi for char classing
Browse files Browse the repository at this point in the history
  • Loading branch information
tris203 committed May 31, 2024
1 parent f893367 commit c401966
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 8 deletions.
29 changes: 29 additions & 0 deletions lua/precognition/ffi.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
local M = {}

---@return ffi.namespace*
function M.load()
if not _G.precog_C then
local ffi = require("ffi")
local ok, err = pcall(
ffi.cdef,
[[
int utf_class(const int c);
]]
)
---@diagnostic disable-next-line: need-check-nil
if not ok then
error(err)
end
_G.precog_C = ffi.C
end
return _G.precog_C
end

return setmetatable(M, {
__index = function(_, key)
return M.load()[key]
end,
__newindex = function(_, k, v)
M.load()[k] = v
end,
})
18 changes: 10 additions & 8 deletions lua/precognition/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ M.char_classes = {
whitespace = 0,
other = 1,
word = 2,
emoji = 3,
}

---@param char string
Expand All @@ -14,18 +15,19 @@ function M.char_class(char, big_word)
assert(type(big_word) == "boolean", "big_word must be a boolean")
local cc = M.char_classes
local byte = string.byte(char)
if byte == nil then
return cc.other
end
if char == " " or char == "\t" or char == "\0" then
return cc.whitespace
end

if byte and byte < 0x100 then
if char == " " or char == "\t" or char == "\0" then
return cc.whitespace
end
if char == "_" or char:match("%w") then
return big_word and cc.other or cc.word
end
local c_class = require("precognition.ffi").utf_class(byte)
if big_word and c_class ~= 0 then
return cc.other
end

return cc.other -- scary unicode edge cases go here
return c_class
end

---@param bufnr? integer
Expand Down

0 comments on commit c401966

Please sign in to comment.