Debian Codegraph @

third_party/rust/mapped_hyph/src/ffi.rs

raw
1 // Copyright 2019-2020 Mozilla Foundation. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use std::slice;
11 use std::str;
12 use std::ffi::CStr;
13 use std::fs::File;
14 use std::io::Read;
15 use std::os::raw::c_char;
16 use std::str::Utf8Error;
17
18 use memmap2::Mmap;
19
20 use super::Hyphenator;
21
22 /// Opaque type representing a hyphenation dictionary loaded from a file,
23 /// for use in FFI function signatures.
24 pub struct HyphDic;
25
26 /// Opaque type representing a compiled dictionary in a memory buffer.
27 pub struct CompiledData;
28
29 // Helper to convert word and hyphen buffer parameters from raw C pointer/length
30 // pairs to the Rust types expected by mapped_hyph.
31 unsafe fn params_from_c<'a>(word: *const c_char, word_len: u32,
32 hyphens: *mut u8, hyphens_len: u32) ->
33 (Result<&'a str, Utf8Error>, &'a mut [u8]) {
34 (str::from_utf8(slice::from_raw_parts(word as *const u8, word_len as usize)),
35 slice::from_raw_parts_mut(hyphens, hyphens_len as usize))
36 }
37
38 /// C-callable function to load a hyphenation dictionary from a file at `path`.
39 ///
40 /// Returns null on failure.
41 ///
42 /// This does not fully validate that the file contains usable hyphenation
43 /// data, it only opens the file (read-only) and mmap's it into memory, and
44 /// does some minimal sanity-checking that it *might* be valid.
45 ///
46 /// The returned `HyphDic` must be released with `mapped_hyph_free_dictionary`.
47 ///
48 /// # Safety
49 /// The given `path` must be a valid pointer to a NUL-terminated (C-style)
50 /// string.
51 #[no_mangle]
52 pub unsafe extern "C" fn mapped_hyph_load_dictionary(path: *const c_char) -> *const HyphDic {
53 let path_str = match CStr::from_ptr(path).to_str() {
54 Ok(str) => str,
55 Err(_) => return std::ptr::null(),
56 };
57 let hyph = Box::new(match super::load_file(path_str) {
58 Some(dic) => dic,
59 _ => return std::ptr::null(),
60 });
61 Box::into_raw(hyph) as *const HyphDic
62 }
63
64 /// C-callable function to free a hyphenation dictionary
65 /// that was loaded by `mapped_hyph_load_dictionary`.
66 ///
67 /// # Safety
68 /// The `dic` parameter must be a `HyphDic` pointer obtained from
69 /// `mapped_hyph_load_dictionary`, and not previously freed.
70 #[no_mangle]
71 pub unsafe extern "C" fn mapped_hyph_free_dictionary(dic: *mut HyphDic) {
72 Box::from_raw(dic);
73 }
74
75 /// C-callable function to find hyphenation values for a given `word`,
76 /// using a dictionary loaded via `mapped_hyph_load_dictionary`.
77 ///
78 /// The `word` must be UTF-8-encoded, and is `word_len` bytes (not characters)
79 /// long.
80 ///
81 /// Caller must supply the `hyphens` output buffer for results; its size is
82 /// given in `hyphens_len`.
83 /// It should be at least `word_len` elements long.
84 ///
85 /// Returns -1 if `word` is not valid UTF-8, or the output `hyphens` buffer is
86 /// too small.
87 /// Otherwise returns the number of potential hyphenation positions found.
88 ///
89 /// # Panics
90 /// This function may panic if the given dictionary is not valid.
91 ///
92 /// # Safety
93 /// The `dic` parameter must be a `HyphDic` pointer obtained from
94 /// `mapped_hyph_load_dictionary`.
95 ///
96 /// The `word` and `hyphens` parameter must be valid pointers to memory buffers
97 /// of at least the respective sizes `word_len` and `hyphens_len`.
98 #[no_mangle]
99 pub unsafe extern "C" fn mapped_hyph_find_hyphen_values_dic(dic: *const HyphDic,
100 word: *const c_char, word_len: u32,
101 hyphens: *mut u8, hyphens_len: u32) -> i32 {
102 if word_len > hyphens_len {
103 return -1;
104 }
105 let (word_str, hyphen_buf) = params_from_c(word, word_len, hyphens, hyphens_len);
106 if word_str.is_err() {
107 return -1;
108 }
109 Hyphenator::new(&*(dic as *const Mmap))
110 .find_hyphen_values(word_str.unwrap(), hyphen_buf) as i32
111 }
112
113 /// C-callable function to find hyphenation values for a given `word`,
114 /// using a dictionary loaded and owned by the caller.
115 ///
116 /// The dictionary is supplied as a raw memory buffer `dic_buf` of size
117 /// `dic_len`.
118 ///
119 /// The `word` must be UTF-8-encoded, and is `word_len` bytes (not characters)
120 /// long.
121 ///
122 /// Caller must supply the `hyphens` output buffer for results; its size is
123 /// given in `hyphens_len`.
124 /// It should be at least `word_len` elements long.
125 ///
126 /// Returns -1 if `word` is not valid UTF-8, or the output `hyphens` buffer is
127 /// too small.
128 /// Otherwise returns the number of potential hyphenation positions found.
129 ///
130 /// # Panics
131 /// This function may panic if the given dictionary is not valid.
132 ///
133 /// # Safety
134 /// The `dic_buf` parameter must be a valid pointer to a memory block of size
135 /// at least `dic_len`.
136 ///
137 /// The `word` and `hyphens` parameter must be valid pointers to memory buffers
138 /// of at least the respective sizes `word_len` and `hyphens_len`.
139 #[no_mangle]
140 pub unsafe extern "C" fn mapped_hyph_find_hyphen_values_raw(dic_buf: *const u8, dic_len: u32,
141 word: *const c_char, word_len: u32,
142 hyphens: *mut u8, hyphens_len: u32) -> i32 {
143 if word_len > hyphens_len {
144 return -1;
145 }
146 let (word_str, hyphen_buf) = params_from_c(word, word_len, hyphens, hyphens_len);
147 if word_str.is_err() {
148 return -1;
149 }
150 Hyphenator::new(slice::from_raw_parts(dic_buf, dic_len as usize))
151 .find_hyphen_values(word_str.unwrap(), hyphen_buf) as i32
152 }
153
154 /// C-callable function to check if a given memory buffer `dic_buf` of size
155 /// `dic_len` is potentially usable as a hyphenation dictionary.
156 ///
157 /// Returns `true` if the given memory buffer looks like it may be a valid
158 /// hyphenation dictionary, `false` if it is clearly not usable.
159 ///
160 /// # Safety
161 /// The `dic_buf` parameter must be a valid pointer to a memory block of size
162 /// at least `dic_len`.
163 #[no_mangle]
164 pub unsafe extern "C" fn mapped_hyph_is_valid_hyphenator(dic_buf: *const u8, dic_len: u32) -> bool {
165 if dic_buf.is_null() {
166 return false;
167 }
168 let dic = Hyphenator::new(slice::from_raw_parts(dic_buf, dic_len as usize));
169 dic.is_valid_hyphenator()
170 }
171
172 /// C-callable function to free a CompiledData object created by
173 /// a `mapped_hyph_compile_...` function (below).
174 ///
175 /// # Safety
176 /// The `data` parameter must be a `CompiledData` pointer obtained from
177 /// a `mapped_hyph_compile_...` function, and not previously freed.
178 #[no_mangle]
179 pub unsafe extern "C" fn mapped_hyph_free_compiled_data(data: *mut CompiledData) {
180 Box::from_raw(data);
181 }
182
183 // Helper for the compilation functions (from either memory buffer or file path).
184 fn compile_and_wrap<T: Read>(input: T, compress: bool) -> *const CompiledData {
185 let mut compiled: Vec<u8> = vec![];
186 if super::builder::compile(input, &mut compiled, compress).is_err() {
187 return std::ptr::null();
188 }
189 compiled.shrink_to_fit();
190
191 // Create a persistent heap reference to the compiled data, and return a pointer to it.
192 Box::into_raw(Box::new(compiled)) as *const CompiledData
193 }
194
195 /// C-callable function to compile hyphenation patterns from `pattern_buf` and return
196 /// the compiled data in a memory buffer, suitable to be stored somewhere or passed
197 /// to `mapped_hyph_find_hyphen_values_raw` to perform hyphenation.
198 ///
199 /// The returned `CompiledData` must be released with `mapped_hyph_free_compiled_data`.
200 ///
201 /// # Safety
202 /// The `pattern_buf` parameter must be a valid pointer to a memory block of size
203 /// at least `pattern_len`.
204 #[no_mangle]
205 pub unsafe extern "C" fn mapped_hyph_compile_buffer(pattern_buf: *const u8, pattern_len: u32, compress: bool) -> *const CompiledData {
206 compile_and_wrap(slice::from_raw_parts(pattern_buf, pattern_len as usize), compress)
207 }
208
209 /// C-callable function to compile hyphenation patterns from a file to a memory buffer.
210 ///
211 /// The returned `CompiledData` must be released with `mapped_hyph_free_compiled_data`.
212 ///
213 /// # Safety
214 /// The given `path` must be a valid pointer to a NUL-terminated (C-style) string.
215 #[no_mangle]
216 pub unsafe extern "C" fn mapped_hyph_compile_file(path: *const c_char, compress: bool) -> *const CompiledData {
217 // Try to open the file at the given path, returning null on failure.
218 let path_str = match CStr::from_ptr(path).to_str() {
219 Ok(str) => str,
220 Err(_) => return std::ptr::null(),
221 };
222 let in_file = match File::open(path_str) {
223 Ok(file) => file,
224 Err(_) => return std::ptr::null(),
225 };
226 compile_and_wrap(&in_file, compress)
227 }
228
229 /// Get the size of the compiled table buffer in a `CompiledData` object.
230 ///
231 /// # Safety
232 /// The `data` parameter must be a `CompiledData` pointer obtained from
233 /// a `mapped_hyph_compile_...` function, and not previously freed.
234 #[no_mangle]
235 pub unsafe extern "C" fn mapped_hyph_compiled_data_size(data: *const CompiledData) -> u32 {
236 (&*(data as *const Vec<u8>)).len() as u32
237 }
238
239 /// Get a pointer to the raw data held by a `CompiledData` object.
240 ///
241 /// # Safety
242 /// The `data` parameter must be a `CompiledData` pointer obtained from
243 /// a `mapped_hyph_compile_...` function, and not previously freed.
244 ///
245 /// The returned pointer only remains valid as long as the `CompiledData` has not
246 /// been released (by passing it to `mapped_hyph_free_compiled_data`).
247 #[no_mangle]
248 pub unsafe extern "C" fn mapped_hyph_compiled_data_ptr(data: *const CompiledData) -> *const u8 {
249 (&*(data as *const Vec<u8>)).as_ptr()
250 }