liblevenshtein 4.0.0.rc.4

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5e0447f4c670e2d48cb721bfb330831b320ef57f3580feb840ef9adc364be2e8
4
+ data.tar.gz: b0786629ebef0234f71b2447407382223c41d1ecdd74b3855698c8606b59f9d6
5
+ SHA512:
6
+ metadata.gz: ca25c7833979b3bfb28c27482df10b0b66d27c1579f82428fb5546cec1d17d733144410c75d5954ca4a258ecd10c91a44c279128c94191f0afbf2f1d8a703b9e
7
+ data.tar.gz: 37f91fceaa43d5b75e9690a59cac3d8d63e2b701e32b31c64957f69b847810ac2be57c2d6d60b6cc628babc20b154bf3a47ed0b34817d9a9eed480c25fb9b8dd
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,146 @@
1
+ # Vinary Tree liblevenshtein for Ruby
2
+
3
+ This gem supports maintained Ruby 3.3 through the latest Ruby release. Queries
4
+ are one-shot `Enumerable` objects backed by a native cursor; only a bounded
5
+ batch is leased and each yielded `Match` owns its term. A query captures its
6
+ dictionary revision at construction and can outlive the source dictionary.
7
+
8
+ Any modular dictionary gem can implement `with_resource { |context, vtable| }
9
+ to participate in O(1) retained-resource handoff. The libdictenstein gem does
10
+ so without serialization or an object-format conversion.
11
+
12
+ Set `LIBLEVENSHTEIN_LIBRARY` for a source-tree build. Release gems contain the
13
+ platform shared library under `lib/vinary_tree/native/<platform>/`; a system
14
+ installation remains a supported loader fallback.
15
+
16
+ <!-- BEGIN GENERATED BINDING OPERATIONS; DO NOT EDIT -->
17
+
18
+ ## Support and package contract
19
+
20
+ | Property | Contract |
21
+ |---|---|
22
+ | Binding | Ruby |
23
+ | Languages/runtime | Ruby 3.3+ |
24
+ | Support tier | Tier 2 |
25
+ | Distribution | RubyGems package `liblevenshtein` |
26
+ | Native boundary | Ruby Fiddle calls the stable C ABI; modular producers yield the two-word resource without serialization. |
27
+ | Canonical facade source | [`bindings/ruby/lib/vinary_tree/liblevenshtein`](../../bindings/ruby/lib/vinary_tree/liblevenshtein) |
28
+
29
+ The support tier controls release gating, not semantic quality: every tier has
30
+ the same snapshot, ownership, status, and ABI compatibility laws. Consult the
31
+ [binding architecture](../../docs/language-bindings.md) before implementing a custom provider
32
+ and the [family hub](../../docs/bindings/README.md) when combining independently packaged projects.
33
+
34
+ ![The host-language facade crosses one project ABI and retains a versioned family resource rather than sharing Rust object layouts.](../../docs/diagrams/bindings/three-layer-architecture.svg)
35
+
36
+ ## Executable example and verification
37
+
38
+ The repository's canonical executable example is
39
+ [`bindings/ruby/test/test_liblevenshtein.rb`](../../bindings/ruby/test/test_liblevenshtein.rb). It exercises the same public package a user
40
+ installs and is run by the binding CI with:
41
+
42
+ ```sh
43
+ ruby -Ibindings/ruby/lib bindings/ruby/test/test_liblevenshtein.rb
44
+ ```
45
+
46
+ Examples deliberately construct or receive resources through public project
47
+ packages. They never import private Rust modules, depend on object layout, or
48
+ reach behind the stable C/resource ABIs.
49
+
50
+ ## Public API and data model
51
+
52
+ The idiomatic facade groups the stable surface into these concepts:
53
+
54
+ | Concept | Semantics |
55
+ |---|---|
56
+ | Dictionary resource | A retained `vt.dictionary.v1` capability. Construction and mutation belong to a producer such as libdictenstein. |
57
+ | Transducer | Immutable query configuration plus a retained dictionary provider; construction is constant-time with respect to dictionary size. |
58
+ | Query cursor | A one-shot traversal over the immutable dictionary revision captured at query start. |
59
+ | Match/batch | Owned matches are stable host values; a borrowed batch is valid only inside its documented callback or lease interval. |
60
+
61
+ Ruby strings use explicit encoding rules; byte strings and integer arrays select non-Unicode domains. Empty terms, embedded zero bytes, non-ASCII text, and the full
62
+ unsigned 64-bit identifier range are represented explicitly; no facade may use
63
+ a sentinel value that removes a valid input from the domain.
64
+
65
+ For the exhaustive native function contract—including exact preconditions,
66
+ returnable statuses, complexity, and thread-safety—use the
67
+ [`llev_*` C ABI reference](../../docs/bindings/c-abi-reference.md). The facade
68
+ source linked above is the authoritative idiomatic symbol inventory; its
69
+ exhaustive coverage is governed by [`bindings/api-surface-map.json`](../../bindings/api-surface-map.json) and the [generated completeness matrix](../../bindings/conformance/completeness-matrix.tsv).
70
+
71
+ ## Ownership, snapshots, and resource handoff
72
+
73
+ Prefer block forms and `ensure { cursor.close }`; finalizers only prevent permanent leaks.
74
+
75
+ A transducer retains the provider resource, and a query retains the revision
76
+ visible at query start. Closing the original dictionary or publishing later
77
+ mutations cannot invalidate that query. Acquisition either completes with one
78
+ owned retain or fails with no ownership transfer. Teardown order is therefore
79
+ free across dictionary, transducer, and completed query handles.
80
+
81
+ Borrowed results are intentionally lexical. Copy data that must outlive the
82
+ callback; retaining a raw address, slice, memory segment, or foreign pointer is
83
+ an API violation even when the next operation happens to reuse the same arena.
84
+
85
+ ## Errors and failure containment
86
+
87
+ Non-OK statuses become typed Ruby exceptions exposing the status symbol and native diagnostic.
88
+
89
+ Malformed utf-8, unsupported unit domains, incompatible resource versions, closed handles, invalid bounds, allocation failures, provider faults, and contained rust panics are distinct failures. Never parse diagnostic prose to
90
+ branch on an error: inspect the typed status/exception first and treat the
91
+ message as human context. Diagnostics must be copied before another native
92
+ call on the same thread.
93
+
94
+ ## Concurrency and reentrancy
95
+
96
+ Separate native handles are reentrant. Enumerate one cursor on one fiber/thread and never retain callback-scoped buffers.
97
+
98
+ Snapshot capture is a linearization point, not a dictionary-wide query lock.
99
+ First-party immutable snapshots can be walked concurrently. A foreign provider
100
+ that does not advertise parallel callbacks is serialized at its callback gate;
101
+ the host language must not add a weaker promise.
102
+
103
+ ## Performance and marshalling
104
+
105
+ - Reuse transducers for repeated queries against the same resource.
106
+ - Prefer streaming cursors to whole-result materialization.
107
+ - Prefer batch/reducer APIs when per-match boundary crossings dominate.
108
+ - Keep Unicode, byte, and token domains explicit to avoid transcoding.
109
+ - Measure native, WASM, and WASI paths independently; they have different
110
+ startup and marshalling costs but identical query semantics.
111
+
112
+ No host wrapper should cache unbounded query results. Applications that add a
113
+ memo use a revision key and a hard entry/weight bound; eviction may be
114
+ approximate because all values remain derivable from the retained snapshot.
115
+
116
+ ## Security model
117
+
118
+ Treat a foreign resource provider and all user-controlled queries as untrusted
119
+ inputs. Validate lengths before allocation, preserve paging bounds, reject
120
+ unknown enum values, contain callbacks/panics at the boundary, and never trust
121
+ capability flags until interface negotiation succeeds. The normative duties
122
+ are in the [binding trust model](../../docs/security/binding-trust-model.md).
123
+
124
+ ## Compatibility and troubleshooting
125
+
126
+ The project ABI revision, family ABI version, interface identity/version,
127
+ package version, and umbrella-runtime version are independent counters. Follow
128
+ the [ABI evolution policy](https://github.com/vinary-tree/vinary-tree-interop/blob/master/docs/abi-evolution.md); never infer compatibility from a
129
+ package version alone.
130
+
131
+ When loading fails, check—in order—the documented runtime/toolchain version,
132
+ CPU/OS artifact, native-access permission, loader search path, dependent
133
+ interop package pin, and process-wide JavaScript runtime identity. When a query
134
+ fails after construction, report the typed status and copied diagnostic before
135
+ reducing the case to the smallest dictionary/query pair.
136
+
137
+ ## Maintainer checklist
138
+
139
+ 1. Update the machine-readable binding model before changing a public symbol.
140
+ 2. Regenerate headers/constants and the API coverage matrix.
141
+ 3. Extend the canonical executable example and negative-path tests.
142
+ 4. Run the language package, snapshot, leak, property, and cross-project suites.
143
+ 5. Verify package staging contains this guide and uses coherent sibling pins.
144
+ 6. Render diagrams headlessly and run the documentation/link/math gates.
145
+
146
+ <!-- END GENERATED BINDING OPERATIONS -->
@@ -0,0 +1,92 @@
1
+ require "fiddle/import"
2
+ require "rbconfig"
3
+
4
+ module VinaryTree
5
+ module Liblevenshtein
6
+ module Native
7
+ extend Fiddle::Importer
8
+
9
+ def self.library_candidates
10
+ explicit = ENV["LIBLEVENSHTEIN_LIBRARY"]
11
+ os, extension, filename = case RbConfig::CONFIG["host_os"]
12
+ when /darwin/ then ["darwin", "dylib", "libliblevenshtein.dylib"]
13
+ when /mswin|mingw/ then ["windows", "dll", "liblevenshtein.dll"]
14
+ else ["linux", "so", "libliblevenshtein.so"]
15
+ end
16
+ cpu = case RbConfig::CONFIG["host_cpu"]
17
+ when /x86_64|amd64/ then "x64"
18
+ when /aarch64|arm64/ then "arm64"
19
+ else RbConfig::CONFIG["host_cpu"]
20
+ end
21
+ platform = "#{os}-#{cpu}"
22
+ bundled = File.expand_path("native/#{platform}/#{filename}", __dir__)
23
+ [explicit, bundled, filename, "liblevenshtein.#{extension}"].compact
24
+ end
25
+
26
+ loaded = library_candidates.find do |candidate|
27
+ begin
28
+ dlload candidate
29
+ true
30
+ rescue Fiddle::DLError
31
+ false
32
+ end
33
+ end
34
+ raise Fiddle::DLError, "unable to load liblevenshtein (tried #{library_candidates.join(', ')})" unless loaded
35
+
36
+ VtResource = struct ["void* context", "void* vtable"]
37
+ Match = struct [
38
+ "void* term_data", "size_t term_len", "size_t byte_len",
39
+ "size_t distance", "uint64_t id", "uint32_t unit_domain",
40
+ "uint8_t has_id", "uint8_t reserved[3]"
41
+ ]
42
+ Batch = struct ["void* matches", "size_t len", "uint64_t generation"]
43
+ OwnedString = struct ["void* data", "size_t len"]
44
+
45
+ extern "const char* llev_last_error_message(void)"
46
+ extern "size_t llev_distance(const char*, size_t, const char*, size_t)"
47
+ extern "size_t llev_distance_threshold(const char*, size_t, const char*, size_t, size_t)"
48
+ extern "size_t llev_damerau_distance(const char*, size_t, const char*, size_t)"
49
+ extern "size_t llev_damerau_distance_threshold(const char*, size_t, const char*, size_t, size_t)"
50
+ extern "size_t llev_true_damerau_distance(const char*, size_t, const char*, size_t)"
51
+ extern "size_t llev_true_damerau_distance_threshold(const char*, size_t, const char*, size_t, size_t)"
52
+ extern "uint32_t llev_transducer_new(const void*, uint32_t, void*)"
53
+ extern "void llev_transducer_free(void*)"
54
+ extern "uint32_t llev_transducer_query_utf8(void*, const char*, size_t, size_t, uint32_t, void*)"
55
+ extern "uint32_t llev_transducer_query_bytes(void*, const void*, size_t, size_t, uint32_t, void*)"
56
+ extern "uint32_t llev_transducer_query_u64(void*, const void*, size_t, size_t, uint32_t, void*)"
57
+ extern "uint32_t llev_query_cursor_next_batch(void*, size_t, void*)"
58
+ extern "uint32_t llev_query_cursor_release_batch(void*, uint64_t)"
59
+ extern "uint32_t llev_query_cursor_free(void*)"
60
+ extern "uint32_t llev_phonetic_pattern_compile_regex(const char*, size_t, void*)"
61
+ extern "uint32_t llev_phonetic_pattern_compile_llre(const char*, size_t, void*)"
62
+ extern "void llev_phonetic_pattern_free(void*)"
63
+ extern "uint32_t llev_phonetic_pattern_size(void*, void*, void*)"
64
+ extern "uint32_t llev_phonetic_pattern_matches(void*, const char*, size_t, void*)"
65
+ extern "uint32_t llev_transducer_query_pattern(void*, void*, uint8_t, void*)"
66
+ extern "uint32_t llev_phonetic_rules_parse(const char*, size_t, void*)"
67
+ extern "uint32_t llev_phonetic_rules_builtin(uint32_t, void*)"
68
+ extern "void llev_phonetic_rules_free(void*)"
69
+ extern "uint32_t llev_phonetic_rules_len(void*, void*)"
70
+ extern "uint32_t llev_phonetic_rules_apply(void*, const char*, size_t, void*)"
71
+ extern "void llev_owned_string_free(void*)"
72
+
73
+ module_function
74
+
75
+ def pointer_output
76
+ Fiddle::Pointer.malloc(Fiddle::SIZEOF_VOIDP, Fiddle::RUBY_FREE)
77
+ end
78
+
79
+ def read_pointer(output)
80
+ output[0, Fiddle::SIZEOF_VOIDP].unpack1("J")
81
+ end
82
+
83
+ def size_output
84
+ Fiddle::Pointer.malloc(Fiddle::SIZEOF_SIZE_T, Fiddle::RUBY_FREE)
85
+ end
86
+
87
+ def read_size(output)
88
+ output[0, Fiddle::SIZEOF_SIZE_T].unpack1("J")
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,5 @@
1
+ module VinaryTree
2
+ module Liblevenshtein
3
+ VERSION = "4.0.0.rc.4"
4
+ end
5
+ end
@@ -0,0 +1,287 @@
1
+ require "thread"
2
+ require_relative "liblevenshtein/version"
3
+ require_relative "liblevenshtein/native"
4
+
5
+ module VinaryTree
6
+ module Liblevenshtein
7
+ OK = 0
8
+ END_STATUS = 1
9
+ BYTE_DOMAIN = 1
10
+ UNICODE_DOMAIN = 2
11
+ U64_DOMAIN = 3
12
+
13
+ class Error < StandardError
14
+ attr_reader :status
15
+ def initialize(status)
16
+ @status = status
17
+ super("liblevenshtein status #{status}: #{Native.llev_last_error_message.to_s}")
18
+ end
19
+ end
20
+
21
+ def self.check(status)
22
+ raise Error, status unless status == OK
23
+ end
24
+
25
+ class << self
26
+ def distance(source, target) = Native.llev_distance(source.b, source.bytesize, target.b, target.bytesize)
27
+ def distance_threshold(source, target, threshold) = Native.llev_distance_threshold(source.b, source.bytesize, target.b, target.bytesize, threshold)
28
+ def damerau_distance(source, target) = Native.llev_damerau_distance(source.b, source.bytesize, target.b, target.bytesize)
29
+ def damerau_distance_threshold(source, target, threshold) = Native.llev_damerau_distance_threshold(source.b, source.bytesize, target.b, target.bytesize, threshold)
30
+ def true_damerau_distance(source, target) = Native.llev_true_damerau_distance(source.b, source.bytesize, target.b, target.bytesize)
31
+ def true_damerau_distance_threshold(source, target, threshold) = Native.llev_true_damerau_distance_threshold(source.b, source.bytesize, target.b, target.bytesize, threshold)
32
+ end
33
+
34
+ Match = Data.define(:term, :distance, :id, :domain)
35
+
36
+ module Finalizer
37
+ module_function
38
+ def for(box, function)
39
+ proc do
40
+ pointer = box[0]
41
+ function.call(pointer) unless pointer.nil? || pointer.zero?
42
+ box[0] = 0
43
+ rescue StandardError
44
+ nil
45
+ end
46
+ end
47
+ end
48
+
49
+ # A lifetime gate that permits concurrent native calls and only coordinates
50
+ # close with in-flight operations. It never serializes ordinary reads.
51
+ class ConcurrentHandle
52
+ def initialize(pointer, releaser)
53
+ @pointer = pointer
54
+ @releaser = releaser
55
+ @active = 0
56
+ @closing = false
57
+ @mutex = Mutex.new
58
+ @condition = ConditionVariable.new
59
+ end
60
+
61
+ def with_pointer
62
+ pointer = @mutex.synchronize do
63
+ raise IOError, "native handle is closed" if @closing || @pointer.zero?
64
+ @active += 1
65
+ @pointer
66
+ end
67
+ yield pointer
68
+ ensure
69
+ @mutex.synchronize do
70
+ @active -= 1
71
+ @condition.broadcast if @active.zero?
72
+ end if pointer
73
+ end
74
+
75
+ def close
76
+ pointer = @mutex.synchronize do
77
+ return 0 if @pointer.zero?
78
+ @closing = true
79
+ @condition.wait(@mutex) until @active.zero?
80
+ result = @pointer
81
+ @pointer = 0
82
+ result
83
+ end
84
+ @releaser.call(pointer) unless pointer.zero?
85
+ pointer
86
+ end
87
+
88
+ def self.finalizer(handle) = proc { handle.close rescue nil }
89
+ end
90
+
91
+ class Transducer
92
+ STANDARD = 0
93
+ TRANSPOSITION = 1
94
+ MERGE_AND_SPLIT = 2
95
+ DAMERAU_LEVENSHTEIN = 3
96
+
97
+ def initialize(dictionary, algorithm: STANDARD)
98
+ raise ArgumentError, "dictionary must respond to with_resource" unless dictionary.respond_to?(:with_resource)
99
+ output = Native.pointer_output
100
+ dictionary.with_resource do |context, vtable|
101
+ resource = Native::VtResource.malloc
102
+ resource.context = context
103
+ resource.vtable = vtable
104
+ Liblevenshtein.check(Native.llev_transducer_new(resource, algorithm, output))
105
+ end
106
+ @handle = ConcurrentHandle.new(Native.read_pointer(output), Native.method(:llev_transducer_free))
107
+ ObjectSpace.define_finalizer(self, ConcurrentHandle.finalizer(@handle))
108
+ end
109
+
110
+ def query(text, maximum_distance, order: 0)
111
+ start_query(:llev_transducer_query_utf8, text.b, maximum_distance, order)
112
+ end
113
+
114
+ def query_bytes(bytes, maximum_distance)
115
+ start_query(:llev_transducer_query_bytes, bytes.b, maximum_distance, 0)
116
+ end
117
+
118
+ def query_u64(tokens, maximum_distance)
119
+ packed = tokens.pack("Q*")
120
+ start_query(:llev_transducer_query_u64, packed, maximum_distance, 0, tokens.length)
121
+ end
122
+
123
+ def query_pattern(pattern, maximum_distance)
124
+ with_pointer do |pointer|
125
+ pattern.__send__(:with_pointer) do |pattern_pointer|
126
+ output = Native.pointer_output
127
+ Liblevenshtein.check(Native.llev_transducer_query_pattern(pointer, pattern_pointer, maximum_distance, output))
128
+ Query.new(Native.read_pointer(output))
129
+ end
130
+ end
131
+ end
132
+
133
+ def close
134
+ @handle.close
135
+ ObjectSpace.undefine_finalizer(self)
136
+ nil
137
+ end
138
+
139
+ private
140
+
141
+ def with_pointer
142
+ @handle.with_pointer { |pointer| yield pointer }
143
+ end
144
+
145
+ def start_query(function, input, maximum_distance, order, units = input.bytesize)
146
+ with_pointer do |pointer|
147
+ output = Native.pointer_output
148
+ Liblevenshtein.check(Native.public_send(function, pointer, input, units, maximum_distance, order, output))
149
+ Query.new(Native.read_pointer(output))
150
+ end
151
+ end
152
+ end
153
+
154
+ class Query
155
+ include Enumerable
156
+ BATCH_SIZE = 256
157
+
158
+ def initialize(pointer)
159
+ @box = [pointer]
160
+ @claimed = false
161
+ @mutex = Mutex.new
162
+ ObjectSpace.define_finalizer(self, Finalizer.for(@box, proc { |value| Native.llev_query_cursor_free(value) }))
163
+ end
164
+
165
+ def each
166
+ return enum_for(__method__) unless block_given?
167
+ @mutex.synchronize do
168
+ raise IOError, "query is one-shot" if @claimed
169
+ @claimed = true
170
+ end
171
+ begin
172
+ loop do
173
+ batch = Native::Batch.malloc
174
+ status = Native.llev_query_cursor_next_batch(@box[0], BATCH_SIZE, batch)
175
+ break if status == END_STATUS
176
+ Liblevenshtein.check(status)
177
+ begin
178
+ batch.len.times do |index|
179
+ item = Native::Match.new(batch.matches + index * Native::Match.size)
180
+ yield materialize(item)
181
+ end
182
+ ensure
183
+ Liblevenshtein.check(Native.llev_query_cursor_release_batch(@box[0], batch.generation))
184
+ end
185
+ end
186
+ ensure
187
+ close
188
+ end
189
+ end
190
+
191
+ def close
192
+ @mutex.synchronize do
193
+ return if @box[0].zero?
194
+ Liblevenshtein.check(Native.llev_query_cursor_free(@box[0]))
195
+ @box[0] = 0
196
+ ObjectSpace.undefine_finalizer(self)
197
+ end
198
+ end
199
+
200
+ private
201
+
202
+ def materialize(item)
203
+ pointer = Fiddle::Pointer.new(item.term_data)
204
+ term = case item.unit_domain
205
+ when BYTE_DOMAIN then pointer[0, item.byte_len].b
206
+ when UNICODE_DOMAIN then pointer[0, item.byte_len].dup.force_encoding(Encoding::UTF_8)
207
+ when U64_DOMAIN then pointer[0, item.term_len * 8].unpack("Q*")
208
+ else raise IOError, "unknown native term domain #{item.unit_domain}"
209
+ end
210
+ Match.new(term, item.distance, item.has_id.zero? ? nil : item.id, item.unit_domain)
211
+ end
212
+ end
213
+
214
+ class PhoneticPattern
215
+ def self.compile_regex(source) = compile(source, false)
216
+ def self.compile_llre(source) = compile(source, true)
217
+ def self.compile(source, llre)
218
+ output = Native.pointer_output
219
+ status = llre ? Native.llev_phonetic_pattern_compile_llre(source.b, source.bytesize, output) : Native.llev_phonetic_pattern_compile_regex(source.b, source.bytesize, output)
220
+ Liblevenshtein.check(status)
221
+ new(Native.read_pointer(output))
222
+ end
223
+
224
+ def initialize(pointer)
225
+ @handle = ConcurrentHandle.new(pointer, Native.method(:llev_phonetic_pattern_free))
226
+ ObjectSpace.define_finalizer(self, ConcurrentHandle.finalizer(@handle))
227
+ end
228
+ def matches?(text)
229
+ with_pointer do |pointer|
230
+ output = Fiddle::Pointer.malloc(1, Fiddle::RUBY_FREE)
231
+ Liblevenshtein.check(Native.llev_phonetic_pattern_matches(pointer, text.b, text.bytesize, output))
232
+ output[0].positive?
233
+ end
234
+ end
235
+ def size
236
+ with_pointer do |pointer|
237
+ states = Native.size_output; transitions = Native.size_output
238
+ Liblevenshtein.check(Native.llev_phonetic_pattern_size(pointer, states, transitions))
239
+ [Native.read_size(states), Native.read_size(transitions)]
240
+ end
241
+ end
242
+ def close
243
+ @handle.close; ObjectSpace.undefine_finalizer(self); nil
244
+ end
245
+ private
246
+ def with_pointer
247
+ @handle.with_pointer { |pointer| yield pointer }
248
+ end
249
+ end
250
+
251
+ class PhoneticRuleSet
252
+ ENGLISH_ORTHOGRAPHY = 0
253
+ ENGLISH_PHONETIC = 1
254
+ def self.parse(source)
255
+ output = Native.pointer_output; Liblevenshtein.check(Native.llev_phonetic_rules_parse(source.b, source.bytesize, output)); new(Native.read_pointer(output))
256
+ end
257
+ def self.builtin(kind)
258
+ output = Native.pointer_output; Liblevenshtein.check(Native.llev_phonetic_rules_builtin(kind, output)); new(Native.read_pointer(output))
259
+ end
260
+ def initialize(pointer)
261
+ @handle = ConcurrentHandle.new(pointer, Native.method(:llev_phonetic_rules_free))
262
+ ObjectSpace.define_finalizer(self, ConcurrentHandle.finalizer(@handle))
263
+ end
264
+ def length
265
+ with_pointer do |pointer|
266
+ output = Native.size_output; Liblevenshtein.check(Native.llev_phonetic_rules_len(pointer, output)); Native.read_size(output)
267
+ end
268
+ end
269
+ def apply(text)
270
+ with_pointer do |pointer|
271
+ output = Native::OwnedString.malloc
272
+ Liblevenshtein.check(Native.llev_phonetic_rules_apply(pointer, text.b, text.bytesize, output))
273
+ begin Fiddle::Pointer.new(output.data)[0, output.len].force_encoding(Encoding::UTF_8)
274
+ ensure Native.llev_owned_string_free(output)
275
+ end
276
+ end
277
+ end
278
+ def close
279
+ @handle.close; ObjectSpace.undefine_finalizer(self); nil
280
+ end
281
+ private
282
+ def with_pointer
283
+ @handle.with_pointer { |pointer| yield pointer }
284
+ end
285
+ end
286
+ end
287
+ end
metadata ADDED
@@ -0,0 +1,53 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: liblevenshtein
3
+ version: !ruby/object:Gem::Version
4
+ version: 4.0.0.rc.4
5
+ platform: ruby
6
+ authors:
7
+ - Dylon Edwards
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Idiomatic Ruby bindings to Vinary Tree's high-performance liblevenshtein
13
+ native ABI
14
+ email:
15
+ - dylon.devo@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/vinary_tree/liblevenshtein.rb
23
+ - lib/vinary_tree/liblevenshtein/native.rb
24
+ - lib/vinary_tree/liblevenshtein/native/darwin-arm64/libliblevenshtein.dylib
25
+ - lib/vinary_tree/liblevenshtein/native/linux-arm64/libliblevenshtein.so
26
+ - lib/vinary_tree/liblevenshtein/native/linux-x64/libliblevenshtein.so
27
+ - lib/vinary_tree/liblevenshtein/native/windows-x64/liblevenshtein.dll
28
+ - lib/vinary_tree/liblevenshtein/version.rb
29
+ homepage: https://github.com/vinary-tree/liblevenshtein-rust
30
+ licenses:
31
+ - Apache-2.0
32
+ metadata:
33
+ source_code_uri: https://github.com/vinary-tree/liblevenshtein-rust
34
+ changelog_uri: https://github.com/vinary-tree/liblevenshtein-rust/blob/main/CHANGELOG.md
35
+ rubygems_mfa_required: 'true'
36
+ rdoc_options: []
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '3.3'
44
+ required_rubygems_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ requirements: []
50
+ rubygems_version: 3.7.0.dev
51
+ specification_version: 4
52
+ summary: Snapshot-consistent streaming Levenshtein search
53
+ test_files: []