mecab_sys/model.rs
1use super::ffi;
2use super::{Error, Lattice, Tagger};
3use super::{LcAttr, RcAttr};
4
5use std::ffi::CStr;
6use std::ptr::NonNull;
7
8/// A thread-safe, shared MeCab model. It wraps C `mecab_model_t`.
9pub struct Model {
10 pub(crate) inner: NonNull<ffi::mecab_model_t>,
11}
12
13impl Model {
14 /// Returns the raw pointer to the underlying [`mecab_model_t`](ffi::mecab_model_t).
15 ///
16 /// The pointer is guaranteed to be [`NonNull`].
17 pub fn as_ptr(&self) -> *mut ffi::mecab_model_t {
18 self.inner.as_ptr()
19 }
20
21 /// Creates a new [`Model`] from a CLI argument string.
22 ///
23 /// It wraps `mecab_model_new2()`, the wrapper of `MeCab::Model::create(arg)`.
24 ///
25 /// ```
26 /// # fn new_model() {
27 /// use mecab_sys::Model;
28 ///
29 /// let model = Model::from_cli_arg(c"-d /path/to/your/dict -r /path/to/dictrc").unwrap();
30 /// # }
31 /// ```
32 pub fn from_cli_arg(arg: &CStr) -> Result<Self, Error> {
33 unsafe {
34 let inner = ffi::mecab_model_new2(arg.as_ptr());
35 NonNull::new(inner)
36 .map(|inner| Self { inner })
37 .ok_or_else(Error::global)
38 }
39 }
40
41 /// Creates a new [`Tagger`] from this model. It is the alias of [`Tagger::new()`].
42 pub fn new_tagger(&self) -> Result<Tagger<'_>, Error> {
43 Tagger::new(self)
44 }
45
46 /// Creates a new [`Lattice`] from this model. It is the alias of [`Lattice::new()`].
47 pub fn new_lattice(&self) -> Result<Lattice<'_>, Error> {
48 Lattice::new(self)
49 }
50
51 /// Returns the transition cost between two attribute IDs.
52 ///
53 /// It wraps `mecab_model_transition_cost()`, the wrapper of `MeCab::Model::transition_cost()`.
54 pub fn transition_cost(&self, rc_attr: RcAttr, lc_attr: LcAttr) -> i32 {
55 unsafe {
56 ffi::mecab_model_transition_cost(self.as_ptr(), rc_attr.to_raw(), lc_attr.to_raw())
57 }
58 }
59}
60
61impl Drop for Model {
62 fn drop(&mut self) {
63 unsafe {
64 ffi::mecab_model_destroy(self.as_ptr());
65 }
66 }
67}
68
69unsafe impl Sync for Model {}
70unsafe impl Send for Model {}