rufio 1.5.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +86 -0
  3. data/README.md +18 -6
  4. data/README_ja.md +18 -6
  5. data/Rakefile +5 -0
  6. data/SECURITY.md +16 -8
  7. data/docs/csv_cell_preview_design_ja.md +682 -0
  8. data/docs/guide.md +115 -20
  9. data/docs/guide_ja.md +116 -21
  10. data/docs/image_preview_design_ja.md +335 -0
  11. data/docs/native_fuzzy_search_design_ja.md +684 -0
  12. data/examples/config.rb +23 -0
  13. data/info/help.md +32 -18
  14. data/info/keybindings.md +43 -11
  15. data/info/welcome.md +4 -6
  16. data/lib/rufio/background_status.rb +7 -0
  17. data/lib/rufio/bookmark_controller.rb +0 -45
  18. data/lib/rufio/clipboard.rb +162 -0
  19. data/lib/rufio/command_locator.rb +49 -0
  20. data/lib/rufio/config.rb +7 -4
  21. data/lib/rufio/config_loader.rb +66 -11
  22. data/lib/rufio/csv_table_source.rb +125 -0
  23. data/lib/rufio/encoding_detector.rb +152 -0
  24. data/lib/rufio/file_operation_controller.rb +41 -0
  25. data/lib/rufio/file_preview.rb +92 -19
  26. data/lib/rufio/fuzzy_candidate_block.rb +131 -0
  27. data/lib/rufio/fuzzy_file_source.rb +180 -0
  28. data/lib/rufio/fuzzy_search.rb +327 -0
  29. data/lib/rufio/fuzzy_search_session.rb +426 -0
  30. data/lib/rufio/graphics_layer.rb +223 -0
  31. data/lib/rufio/health_checker.rb +27 -32
  32. data/lib/rufio/help_menu.rb +16 -10
  33. data/lib/rufio/image_preview_view.rb +421 -0
  34. data/lib/rufio/image_source.rb +158 -0
  35. data/lib/rufio/keybind_handler.rb +21 -34
  36. data/lib/rufio/kitty_graphics.rb +128 -0
  37. data/lib/rufio/native/aarch64-linux-gnu/librufio_zig.so +0 -0
  38. data/lib/rufio/native/aarch64-linux-musl/librufio_zig.so +0 -0
  39. data/lib/rufio/native/aarch64-macos/librufio_zig.dylib +0 -0
  40. data/lib/rufio/native/aarch64-windows/rufio_zig.dll +0 -0
  41. data/lib/rufio/native/x86_64-linux-gnu/librufio_zig.so +0 -0
  42. data/lib/rufio/native/x86_64-linux-musl/librufio_zig.so +0 -0
  43. data/lib/rufio/native/x86_64-macos/librufio_zig.dylib +0 -0
  44. data/lib/rufio/native/x86_64-windows/rufio_zig.dll +0 -0
  45. data/lib/rufio/native_content_search.rb +44 -8
  46. data/lib/rufio/native_image.rb +177 -0
  47. data/lib/rufio/native_scanner_zig.rb +39 -0
  48. data/lib/rufio/navigation_controller.rb +47 -16
  49. data/lib/rufio/preview_registry.rb +86 -0
  50. data/lib/rufio/preview_view.rb +363 -0
  51. data/lib/rufio/renderer.rb +8 -8
  52. data/lib/rufio/screen.rb +38 -1
  53. data/lib/rufio/search_prompt.rb +50 -0
  54. data/lib/rufio/search_screen.rb +680 -0
  55. data/lib/rufio/sheet_picker.rb +87 -0
  56. data/lib/rufio/sqlite_table_source.rb +205 -0
  57. data/lib/rufio/tab_mode_manager.rb +1 -3
  58. data/lib/rufio/table_cursor.rb +117 -0
  59. data/lib/rufio/table_document.rb +261 -0
  60. data/lib/rufio/table_layout.rb +231 -0
  61. data/lib/rufio/table_preview_view.rb +376 -0
  62. data/lib/rufio/table_query.rb +240 -0
  63. data/lib/rufio/table_source.rb +46 -0
  64. data/lib/rufio/terminal_graphics.rb +168 -0
  65. data/lib/rufio/terminal_ui.rb +74 -60
  66. data/lib/rufio/text_utils.rb +27 -0
  67. data/lib/rufio/ui_renderer.rb +380 -17
  68. data/lib/rufio/version.rb +1 -1
  69. data/lib/rufio/xlsx_table_source.rb +112 -0
  70. data/lib/rufio.rb +21 -1
  71. data/lib_zig/rufio_native/Makefile +21 -5
  72. data/lib_zig/rufio_native/build.zig +18 -0
  73. data/lib_zig/rufio_native/src/fuzzy.zig +520 -0
  74. data/lib_zig/rufio_native/src/fuzzy_test.zig +212 -0
  75. data/lib_zig/rufio_native/src/image.zig +525 -0
  76. data/lib_zig/rufio_native/src/image_bmp.zig +111 -0
  77. data/lib_zig/rufio_native/src/image_jpeg.zig +878 -0
  78. data/lib_zig/rufio_native/src/image_png.zig +561 -0
  79. data/lib_zig/rufio_native/src/image_resize.zig +170 -0
  80. data/lib_zig/rufio_native/src/image_test.zig +401 -0
  81. data/lib_zig/rufio_native/src/main.zig +28 -0
  82. data/lib_zig/rufio_native/src/search.zig +260 -64
  83. data/lib_zig/rufio_native/src/search_test.zig +35 -0
  84. data/lib_zig/rufio_native/src/testdata/alpha.png +0 -0
  85. data/lib_zig/rufio_native/src/testdata/gradient.bmp +0 -0
  86. data/lib_zig/rufio_native/src/testdata/gradient.jpg +0 -0
  87. data/lib_zig/rufio_native/src/testdata/gradient.png +0 -0
  88. data/retag.sh +4 -4
  89. metadata +44 -5
  90. data/lib/rufio/global_search.rb +0 -412
  91. data/lib/rufio/search_controller.rb +0 -92
  92. data/lib_zig/rufio_native/src/main.zig.sync +0 -205
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rufio
4
+ # 候補のまとまりを Ruby の行(Hash)にせず、表示名を NUL で終端して連結した 1 本のバイト列で持つ。
5
+ # FuzzySearchSession はこのバイト列をそのままインデックスに登録し、上位の結果になった候補だけ
6
+ # entry(index) で行を作る。ソースは each_batch で行の配列の代わりにこのブロックを渡せる。
7
+ #
8
+ # ブロックは作成後に変わらないので、セッションとキャッシュが同じものを共有できる。
9
+ # rows は (index, text) から行を作る呼び出し可能オブジェクトで、同じ引数には同じ内容を返すこと。
10
+ class FuzzyCandidateBlock
11
+ include Enumerable
12
+
13
+ SEPARATOR = "\0".b.freeze
14
+ MAX_TEXT_BYTES = 65_536
15
+ TEXT_ROW = ->(_index, text) { { text: text } }
16
+
17
+ attr_reader :packed, :size
18
+
19
+ # 表示名を 1 件ずつ詰めてブロックを作る
20
+ class Builder
21
+ attr_reader :size
22
+
23
+ def initialize
24
+ @buffer = +''.b
25
+ @size = 0
26
+ end
27
+
28
+ def empty?
29
+ @size.zero?
30
+ end
31
+
32
+ # text は NUL を含まない正しい UTF-8(バイト列として渡してもよい)。追加した候補の番号を返す
33
+ def add(text)
34
+ raise ArgumentError, 'Candidate text too long' if text.bytesize > MAX_TEXT_BYTES
35
+
36
+ @buffer << text << SEPARATOR
37
+ @size += 1
38
+ @size - 1
39
+ end
40
+
41
+ def build(rows = nil)
42
+ FuzzyCandidateBlock.new(@buffer, @size, rows: rows, checked: true)
43
+ end
44
+ end
45
+
46
+ # 「接頭辞 + 表示名」がそのままパスになるファイル候補の行 { text:, path: } を作る。
47
+ # 表示名を scrub した等でパスを組み立て直せない候補だけ、exceptions に元のパスを持つ。
48
+ class PathRows
49
+ def initialize(prefix, encoding, exceptions = nil)
50
+ @prefix = prefix
51
+ @encoding = encoding
52
+ @exceptions = exceptions
53
+ freeze
54
+ end
55
+
56
+ def call(index, text)
57
+ path = @exceptions && @exceptions[index]
58
+ { text: text, path: path || (@prefix + text.b).force_encoding(@encoding).freeze }
59
+ end
60
+ end
61
+
62
+ # packed: 「表示名 NUL」を size 件連結したもの。checked: true は Builder が詰めた(確認済みの)場合だけ指定する
63
+ def initialize(packed, size, rows: nil, checked: false)
64
+ raise ArgumentError, 'Expected packed candidate text' unless packed.is_a?(String) && size.is_a?(Integer)
65
+
66
+ @packed = packed.frozen? && packed.encoding == Encoding::BINARY ? packed : packed.b.freeze
67
+ @size = size
68
+ @rows = rows || TEXT_ROW
69
+ @offsets = nil
70
+ return if checked
71
+
72
+ unless @packed.count(SEPARATOR) == size && (size.zero? ? @packed.empty? : @packed.end_with?(SEPARATOR)) &&
73
+ @packed.dup.force_encoding(Encoding::UTF_8).valid_encoding?
74
+ raise ArgumentError, 'Invalid packed candidate text'
75
+ end
76
+ end
77
+
78
+ def empty?
79
+ @size.zero?
80
+ end
81
+
82
+ alias length size
83
+
84
+ def text(index)
85
+ raise IndexError, "index #{index} outside of candidate block" unless index.is_a?(Integer) && index >= 0 && index < @size
86
+
87
+ start = offsets[index]
88
+ finish = index + 1 < @size ? offsets[index + 1] : @packed.bytesize
89
+ @packed.byteslice(start, finish - start - 1).force_encoding(Encoding::UTF_8).freeze
90
+ end
91
+
92
+ # 凍結した行(文字列も凍結)を返す。呼ぶたびに作るので、必要な候補だけに使う
93
+ def entry(index)
94
+ row = @rows.call(index, text(index))
95
+ row.each_value { |value| value.freeze if value.is_a?(String) }
96
+ row.freeze
97
+ end
98
+
99
+ def texts
100
+ list = @packed.split(SEPARATOR, -1)
101
+ list.pop
102
+ list.each { |item| item.force_encoding(Encoding::UTF_8).freeze }
103
+ end
104
+
105
+ # 全件の行を作る(テストや、行の配列しか扱えない利用者向け)
106
+ def each
107
+ return enum_for(:each) { @size } unless block_given?
108
+
109
+ @size.times { |index| yield entry(index) }
110
+ self
111
+ end
112
+
113
+ alias to_ary to_a
114
+
115
+ private
116
+
117
+ # 各表示名の開始バイト位置。結果に出す候補が初めて出たときに数え、以後は使い回す(全ブロック分を先に数えない)。
118
+ #複数のスレッドが同時に数えても同じ内容になる
119
+ def offsets
120
+ @offsets ||= begin
121
+ list = Array.new(@size)
122
+ position = 0
123
+ @size.times do |index|
124
+ list[index] = position
125
+ position = @packed.index(SEPARATOR, position) + 1
126
+ end
127
+ list
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'native_content_search'
4
+ require_relative 'fuzzy_candidate_block'
5
+
6
+ module Rufio
7
+ # Produces display labels and original paths separately. A source belongs to
8
+ # its producer thread, including creation and destruction of the native scan.
9
+ # Batches are FuzzyCandidateBlock: packed labels, with { text:, path: } rows built on demand.
10
+ class FuzzyFileSource
11
+ BATCH_SIZE = 256
12
+ # Zig の走査は 1 回の取り出しで多くのファイルを返すので、大きめのブロックにまとめて登録回数を減らす
13
+ BLOCK_SIZE = 4096
14
+
15
+ def initialize(root, native: true)
16
+ @root = File.expand_path(root).freeze
17
+ @prefix = @root.end_with?(File::SEPARATOR) ? @root : @root + File::SEPARATOR
18
+ @native = native
19
+ end
20
+
21
+ def each_batch(cancelled:, on_error:)
22
+ return if cancelled.call
23
+ raise Errno::ENOTDIR, @root unless File.directory?(@root)
24
+
25
+ if @native && ENV['RUFIO_NATIVE_SEARCH'] != '0' && NativeContentSearch.labels_available?
26
+ scan_labels(cancelled, on_error) { |batch| yield batch }
27
+ elsif @native && ENV['RUFIO_NATIVE_SEARCH'] != '0' && NativeContentSearch.files_available?
28
+ scan_native(cancelled, on_error) { |batch| yield batch }
29
+ else
30
+ scan_ruby(cancelled, on_error) { |batch| yield batch }
31
+ end
32
+ end
33
+
34
+ private
35
+
36
+ # 1 ブロック分の候補を詰める。Hash や凍結した文字列を候補ごとに作らず、表示名だけを連結する。
37
+ # パスは「ルート/表示名」から組み立て直せるので、scrub した・エンコーディングが違う候補だけ別に持つ。
38
+ class Batch
39
+ def initialize(prefix, on_error)
40
+ @prefix = prefix
41
+ @binary_prefix = prefix.b.freeze
42
+ @on_error = on_error
43
+ reset
44
+ end
45
+
46
+ def size
47
+ @builder.size
48
+ end
49
+
50
+ def add(path)
51
+ relative = path.delete_prefix(@prefix)
52
+ text = relative.encoding == Encoding::UTF_8 ? relative : relative.dup.force_encoding(Encoding::UTF_8)
53
+ scrubbed = !text.valid_encoding?
54
+ text = text.scrub if scrubbed
55
+ if text.bytesize > FuzzyCandidateBlock::MAX_TEXT_BYTES || text.include?("\0")
56
+ @on_error.call("#{text[0, 200]}: file name cannot be searched")
57
+ return
58
+ end
59
+
60
+ @encoding ||= path.encoding
61
+ index = @builder.add(text)
62
+ return unless scrubbed || path.encoding != @encoding || relative.bytesize == path.bytesize
63
+
64
+ (@exceptions ||= {})[index] = path.frozen? ? path : path.dup.freeze
65
+ end
66
+
67
+ # 詰めた候補をブロックにして取り出す。空なら nil
68
+ def take
69
+ return if @builder.empty?
70
+
71
+ block = @builder.build(FuzzyCandidateBlock::PathRows.new(@binary_prefix, @encoding, @exceptions&.freeze))
72
+ reset
73
+ block
74
+ end
75
+
76
+ private
77
+
78
+ def reset
79
+ @builder = FuzzyCandidateBlock::Builder.new
80
+ @exceptions = nil
81
+ @encoding = nil
82
+ end
83
+ end
84
+
85
+ # Zig が相対パスのラベル列を返す場合は、Ruby でファイルごとの文字列を作らずにそのままブロックにする
86
+ def scan_labels(cancelled, on_error)
87
+ scanner = NativeContentSearch.new(roots: [@root], labels: true)
88
+ rows = FuzzyCandidateBlock::PathRows.new(@prefix.b.freeze, Encoding.find('filesystem'))
89
+ batch = Batch.new(@prefix, on_error)
90
+ packed = +''.b
91
+ count = 0
92
+ limit = BATCH_SIZE
93
+ emit = lambda do
94
+ next if count.zero?
95
+
96
+ yield FuzzyCandidateBlock.new(packed.freeze, count, rows: rows, checked: true)
97
+ packed = +''.b
98
+ count = 0
99
+ limit = [limit * 2, BLOCK_SIZE].min
100
+ end
101
+ scanner.each_batch(cancelled: cancelled) do |events|
102
+ events.each do |kind, _root_index, value, size|
103
+ break if cancelled.call
104
+
105
+ case kind
106
+ when :labels
107
+ packed << value
108
+ count += size
109
+ emit.call if count >= limit
110
+ when :file then batch.add(value) # UTF-8 でない名前
111
+ when :error then on_error.call(value)
112
+ end
113
+ end
114
+ break if cancelled.call
115
+
116
+ emit.call
117
+ block = batch.take
118
+ yield block if block
119
+ end
120
+ ensure
121
+ scanner&.close
122
+ end
123
+
124
+ def scan_native(cancelled, on_error)
125
+ scanner = NativeContentSearch.new(roots: [@root])
126
+ batch = Batch.new(@prefix, on_error)
127
+ # 最初の結果を早く出すため小さいブロックから始め、倍々に大きくする
128
+ limit = BATCH_SIZE
129
+ scanner.each_batch(cancelled: cancelled, max_events: BLOCK_SIZE) do |events|
130
+ events.each do |kind, _root_index, path|
131
+ break if cancelled.call
132
+
133
+ if kind == :file
134
+ batch.add(path)
135
+ if batch.size >= limit
136
+ yield batch.take
137
+ limit = [limit * 2, BLOCK_SIZE].min
138
+ end
139
+ elsif kind == :error
140
+ on_error.call(path)
141
+ end
142
+ end
143
+ block = batch.take
144
+ yield block if block && !cancelled.call
145
+ end
146
+ ensure
147
+ scanner&.close
148
+ end
149
+
150
+ def scan_ruby(cancelled, on_error)
151
+ pending = [@root]
152
+ batch = Batch.new(@prefix, on_error)
153
+ until pending.empty? || cancelled.call
154
+ directory = pending.pop
155
+ begin
156
+ Dir.each_child(directory) do |name|
157
+ break if cancelled.call
158
+
159
+ path = File.join(directory, name)
160
+ begin
161
+ stat = File.lstat(path)
162
+ if stat.directory?
163
+ pending << path
164
+ elsif stat.file? || (stat.symlink? && File.file?(path))
165
+ batch.add(path)
166
+ yield batch.take if batch.size >= BATCH_SIZE
167
+ end
168
+ rescue SystemCallError, IOError => e
169
+ on_error.call("#{path}: #{e.message}")
170
+ end
171
+ end
172
+ rescue SystemCallError, IOError => e
173
+ on_error.call("#{directory}: #{e.message}")
174
+ end
175
+ end
176
+ block = batch.take
177
+ yield block if block && !cancelled.call
178
+ end
179
+ end
180
+ end
@@ -0,0 +1,327 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fiddle'
4
+ require 'fiddle/import'
5
+ require 'thread'
6
+ require_relative 'native_scanner'
7
+ require_relative 'native_scanner_zig'
8
+
9
+ module Rufio
10
+ # Persistent candidate index. No subprocesses; native and Ruby return the same
11
+ # scores and UTF-8 byte offsets. A session serializes access to its native handle.
12
+ # A query that extends the previous one (the previous query is a subsequence of it)
13
+ # only scores the previous matches plus candidates added since; see #scanned.
14
+ class FuzzySearch
15
+ MAX_QUERY_BYTES = 1024
16
+ MAX_CANDIDATE_BYTES = 65_536
17
+ MAX_RESULTS = 10_000
18
+ NEGATIVE = -(1 << 60)
19
+ SEPARATORS = [47, 92, 95, 45, 46, 32].freeze
20
+
21
+ attr_reader :total_matches
22
+
23
+ # Candidates scored by the last query. nil when an older native library cannot report it.
24
+ attr_reader :scanned
25
+
26
+ def initialize(native: true, library: nil)
27
+ @mutex = Mutex.new
28
+ @closed = false
29
+ @total_matches = 0
30
+ @candidates = []
31
+ @previous_query = nil
32
+ @previous_ids = nil
33
+ @previous_count = 0
34
+ @scanned = 0
35
+ if native && ENV['RUFIO_NATIVE_FUZZY'] != '0'
36
+ @api = load_api(library || NativeScannerZigFFI.library_path)
37
+ @handle = @api.core_fuzzy_create if @api
38
+ raise NoMemoryError, 'Cannot create fuzzy index' if @handle == 0
39
+ ObjectSpace.define_finalizer(self, self.class.finalizer(@api, @handle)) if @api
40
+ end
41
+ end
42
+
43
+ def self.finalizer(api, handle)
44
+ proc { api.core_fuzzy_destroy(handle) }
45
+ end
46
+
47
+ def native?
48
+ !@api.nil?
49
+ end
50
+
51
+ def add(candidates)
52
+ @mutex.synchronize do
53
+ ensure_open!
54
+ strings = candidates.map { |text| validate_text(text, MAX_CANDIDATE_BYTES) }
55
+ if native?
56
+ unless strings.empty?
57
+ packed = strings.join("\0") + "\0"
58
+ check_status(@api.core_fuzzy_add(@handle, packed, packed.bytesize))
59
+ end
60
+ else
61
+ @candidates.concat(strings.map { |text| prepare(text) })
62
+ end
63
+ end
64
+ self
65
+ end
66
+
67
+ # 「候補 NUL」を連結した 1 本のバイト列をそのまま登録する(add(packed.split("\0")) と同じ結果)。
68
+ # 候補ごとの Ruby 文字列を作らないので、件数が多いときは add より速い。
69
+ def add_packed(packed)
70
+ @mutex.synchronize do
71
+ ensure_open!
72
+ raise ArgumentError, 'Expected packed candidates' unless packed.is_a?(String)
73
+ next if packed.empty?
74
+ raise ArgumentError, 'Packed candidates must end with NUL' unless packed.end_with?("\0")
75
+
76
+ if native?
77
+ # UTF-8 と長さは Zig 側が全件を確認し、1 件でも不正なら何も登録しない
78
+ check_status(@api.core_fuzzy_add(@handle, packed, packed.bytesize))
79
+ else
80
+ strings = packed.b.split("\0".b, -1)
81
+ strings.pop
82
+ prepared = strings.map { |text| prepare(validate_text(text.force_encoding(Encoding::UTF_8), MAX_CANDIDATE_BYTES)) }
83
+ @candidates.concat(prepared)
84
+ end
85
+ end
86
+ self
87
+ end
88
+
89
+ # positions: 一致位置を求める上位の件数(既定は limit)。それより後の結果の :positions は nil になり、
90
+ # 表示するときに FuzzySearch.positions で求める(同じ結果になる)。
91
+ def query(text, limit: 100, positions: nil)
92
+ @mutex.synchronize do
93
+ ensure_open!
94
+ text = validate_text(text, MAX_QUERY_BYTES)
95
+ raise ArgumentError, 'Invalid result limit' unless limit.is_a?(Integer) && limit.between?(0, MAX_RESULTS)
96
+
97
+ positions = limit if positions.nil?
98
+ raise ArgumentError, 'Invalid position limit' unless positions.is_a?(Integer) && positions >= 0
99
+
100
+ positions = [positions, limit].min
101
+ native? ? query_native(text, limit, positions) : query_ruby(text, limit, positions)
102
+ end
103
+ end
104
+
105
+ # text の中で query が一致する位置(UTF-8 の先頭バイトオフセット)。query の結果と同じ位置を返す。
106
+ # 一致しなければ nil
107
+ def self.positions(text, query)
108
+ (@position_engine ||= new(native: false)).send(:positions_for, text, query)
109
+ end
110
+
111
+ def close
112
+ @mutex.synchronize do
113
+ return if @closed
114
+
115
+ if native?
116
+ ObjectSpace.undefine_finalizer(self)
117
+ @api.core_fuzzy_destroy(@handle)
118
+ end
119
+ @candidates.clear
120
+ @closed = true
121
+ end
122
+ end
123
+
124
+ private
125
+
126
+ def ensure_open!
127
+ raise IOError, 'Fuzzy index is closed' if @closed
128
+ end
129
+
130
+ def validate_text(text, max_bytes)
131
+ raise ArgumentError, 'Expected UTF-8 text' unless text.is_a?(String)
132
+
133
+ # Candidates are usually UTF-8 already; copying each one only to relabel it is wasted work.
134
+ utf8 = text.encoding == Encoding::UTF_8 ? text : text.dup.force_encoding(Encoding::UTF_8)
135
+ unless utf8.valid_encoding? && !utf8.include?("\0") && utf8.bytesize <= max_bytes
136
+ raise ArgumentError, 'Invalid UTF-8, NUL, or text too long'
137
+ end
138
+ utf8
139
+ end
140
+
141
+ def load_api(path)
142
+ return unless path && File.file?(path)
143
+
144
+ Module.new do
145
+ extend Fiddle::Importer
146
+ dlload path
147
+ extern 'uint64_t core_fuzzy_create()'
148
+ extern 'int32_t core_fuzzy_add(uint64_t, const char*, size_t)'
149
+ extern 'int32_t core_fuzzy_query(uint64_t, const char*, size_t, uint32_t)'
150
+ extern 'void* core_fuzzy_results(uint64_t, void*)'
151
+ extern 'void core_fuzzy_destroy(uint64_t)'
152
+ begin
153
+ extern 'uint64_t core_fuzzy_scanned(uint64_t)'
154
+ rescue Fiddle::DLError
155
+ nil # 1.6.0 development builds before narrowing
156
+ end
157
+ begin
158
+ extern 'int32_t core_fuzzy_query_positions(uint64_t, const char*, size_t, uint32_t, uint32_t)'
159
+ rescue Fiddle::DLError
160
+ nil # 1.6.0 development builds before position limits: every result gets positions
161
+ end
162
+ end
163
+ rescue Fiddle::DLError
164
+ nil
165
+ end
166
+
167
+ def check_status(status)
168
+ raise ArgumentError, 'Native fuzzy search rejected input' if status == -1
169
+ raise NoMemoryError, 'Native fuzzy search allocation failed' if status != 0
170
+ end
171
+
172
+ def query_native(text, limit, position_limit)
173
+ status = if position_limit < limit && @api.respond_to?(:core_fuzzy_query_positions)
174
+ @api.core_fuzzy_query_positions(@handle, text, text.bytesize, limit, position_limit)
175
+ else
176
+ @api.core_fuzzy_query(@handle, text, text.bytesize, limit)
177
+ end
178
+ check_status(status)
179
+ length = Fiddle::Pointer.malloc(Fiddle::SIZEOF_SIZE_T, Fiddle::RUBY_FREE)
180
+ pointer = @api.core_fuzzy_results(@handle, length)
181
+ bytes = length[0, Fiddle::SIZEOF_SIZE_T].unpack1(Fiddle::SIZEOF_SIZE_T == 8 ? 'Q' : 'L')
182
+ data = pointer.to_str(bytes)
183
+ @scanned = @api.respond_to?(:core_fuzzy_scanned) ? @api.core_fuzzy_scanned(@handle) : nil
184
+ @total_matches, count = data.unpack('Q<L<')
185
+ offset = 12
186
+ Array.new(count) do |rank|
187
+ id, score, size = data.byteslice(offset, 20).unpack('Q<q<L<')
188
+ positions = size.zero? && !text.empty? && rank >= position_limit ? nil : data.byteslice(offset + 20, size * 4).unpack('L<*')
189
+ offset += 20 + size * 4
190
+ { id: id, score: score, positions: positions }
191
+ end
192
+ end
193
+
194
+ def fold(codepoint)
195
+ codepoint.between?(65, 90) ? codepoint + 32 : codepoint
196
+ end
197
+
198
+ def prepare(text)
199
+ chars = text.codepoints
200
+ basename = (chars.rindex { |c| c == 47 || c == 92 } || -1) + 1
201
+ bytes = 0
202
+ offsets = chars.map do |char|
203
+ position = bytes
204
+ bytes += char.chr(Encoding::UTF_8).bytesize
205
+ position
206
+ end
207
+ bonuses = chars.each_index.map do |i|
208
+ boundary = i.zero? || SEPARATORS.include?(chars[i - 1]) ||
209
+ (chars[i - 1].between?(97, 122) && chars[i].between?(65, 90))
210
+ 16 + (i >= basename ? 8 : 0) + (boundary ? 8 : 0) + (i == basename ? 8 : 0)
211
+ end
212
+ [chars.map { |c| fold(c) }, offsets, bonuses]
213
+ end
214
+
215
+ # Two rolling rows for scoring; only retained candidates need backtracking.
216
+ def score(candidate, query, trace: false)
217
+ chars, offsets, bonuses = candidate
218
+ return [0, []] if query.empty?
219
+ return if query.length > chars.length
220
+
221
+ matched = 0
222
+ chars.each do |char|
223
+ matched += 1 if char == query[matched]
224
+ break if matched == query.length
225
+ end
226
+ return unless matched == query.length
227
+
228
+ previous = Array.new(chars.length, NEGATIVE)
229
+ parents = []
230
+ query.each_with_index do |char, row|
231
+ current = Array.new(chars.length, NEGATIVE)
232
+ parent = trace ? Array.new(chars.length, -1) : nil
233
+ prefix_score = NEGATIVE
234
+ prefix_index = -1
235
+ chars.each_index do |i|
236
+ if i >= 2 && previous[i - 2] != NEGATIVE && previous[i - 2] + i - 2 > prefix_score
237
+ prefix_score = previous[i - 2] + i - 2
238
+ prefix_index = i - 2
239
+ end
240
+ next unless chars[i] == char
241
+
242
+ if row.zero?
243
+ current[i] = bonuses[i]
244
+ else
245
+ value = prefix_score == NEGATIVE ? NEGATIVE : prefix_score - i + 1
246
+ source = prefix_index
247
+ if i > 0 && previous[i - 1] != NEGATIVE && previous[i - 1] + 24 > value
248
+ value = previous[i - 1] + 24
249
+ source = i - 1
250
+ end
251
+ next if value == NEGATIVE
252
+
253
+ current[i] = value + bonuses[i]
254
+ parent[i] = source if trace
255
+ end
256
+ end
257
+ parents << parent if trace
258
+ previous = current
259
+ end
260
+ best = previous.max
261
+ return if best == NEGATIVE
262
+
263
+ positions = []
264
+ if trace
265
+ index = previous.index(best)
266
+ (query.length - 1).downto(0) do |row|
267
+ positions << offsets[index]
268
+ index = parents[row][index]
269
+ end
270
+ positions.reverse!
271
+ end
272
+ [best - chars.length + (query.length == chars.length ? 64 : 0), positions]
273
+ end
274
+
275
+ def subsequence?(small, large)
276
+ matched = 0
277
+ large.each { |char| matched += 1 if matched < small.length && char == small[matched] }
278
+ matched == small.length
279
+ end
280
+
281
+ def positions_for(text, query)
282
+ raise ArgumentError, 'Expected UTF-8 text' unless text.is_a?(String) && query.is_a?(String)
283
+
284
+ folded = query.codepoints.map { |c| fold(c) }
285
+ return [] if folded.empty?
286
+
287
+ matched = score(prepare(text), folded, trace: true)
288
+ matched && matched[1]
289
+ end
290
+
291
+ def query_ruby(text, limit, position_limit)
292
+ query = text.codepoints.map { |c| fold(c) }
293
+ narrow = @previous_query && !query.empty? && subsequence?(@previous_query, query)
294
+ ids = narrow ? @previous_ids + (@previous_count...@candidates.length).to_a : (0...@candidates.length)
295
+ @scanned = ids.size
296
+ @previous_query = nil
297
+ matched_ids = []
298
+ @total_matches = 0
299
+ # Bounded sorted list: the fallback favors simplicity, while Zig uses a heap.
300
+ best = []
301
+ ids.each do |id|
302
+ candidate = @candidates[id]
303
+ matched = score(candidate, query)
304
+ next unless matched
305
+
306
+ matched_ids << id
307
+ @total_matches += 1
308
+ next if limit.zero?
309
+
310
+ key = [-matched[0], id]
311
+ at = best.bsearch_index { |item| ([-item[:score], item[:id]] <=> key) > 0 } || best.length
312
+ next if at >= limit
313
+
314
+ best.insert(at, { id: id, score: matched[0] })
315
+ best.pop if best.length > limit
316
+ end
317
+ unless query.empty?
318
+ @previous_query = query
319
+ @previous_ids = matched_ids
320
+ @previous_count = @candidates.length
321
+ end
322
+ best.each_with_index do |item, rank|
323
+ item[:positions] = rank < position_limit || query.empty? ? score(@candidates[item[:id]], query, trace: true)[1] : nil
324
+ end
325
+ end
326
+ end
327
+ end