ewts/lib.rs
1//!
2//! A little wrapper around core rust ewts conversion library, usable in C/C++/Cython code.
3//! Or anywhere a C-code can be called.
4//! See [example](https://github.com/emgyrz/ewts-rs/tree/master/ewts-c/examples)
5//! and [test code](https://github.com/emgyrz/ewts-rs/blob/master/bench/cpp_bench.cpp).
6//! Also see for details [here](https://github.com/emgyrz/ewts-rs/tree/master/ewts-c).
7//!
8//! It is part of set of apps/libs called **ewts-rs**.
9//!
10//! See more [here](https://github.com/emgyrz/ewts-rs)
11//!
12//! # Example
13//! ```cpp
14//! // some C++ file
15//! // ...
16//! uintptr_t converter_ptr = create_ewts_converter();
17//!
18//! const char * converted_str = ewts_to_unicode(converter_ptr, "rgyu ");
19//! // "རྒྱུ་"
20//! // ...
21//! ```
22//!
23use std::ffi::{c_char, CStr, CString};
24
25use ewts::EwtsConverter;
26
27///
28/// Creates `EwtsConverter` and returns its pointer
29///
30#[no_mangle]
31pub extern "C" fn create_ewts_converter() -> usize {
32 let wrapper = EwtsConverter::create();
33 Box::into_raw(Box::new(wrapper)) as usize
34}
35
36///
37/// Frees `EwtsConverter`.
38/// Gets pointer to EwtsConverter instance
39///
40/// # Safety
41/// The `ewts_converter_ptr` should be pointer returned from `create_ewts_converter()` fn.
42///
43#[no_mangle]
44pub unsafe extern "C" fn free_ewts_converter(ewts_converter_ptr: usize) {
45 let _ = Box::from_raw(ewts_converter_ptr as *mut EwtsConverter);
46}
47
48///
49/// Converts EWTS-string to Tibetan unicode string.
50///
51/// # Example
52/// ```cpp
53/// // some C++ file
54/// uintptr_t converter_ptr = create_ewts_converter();
55/// const char * converted_str = ewts_to_unicode(converter_ptr, "rgyu ");
56/// // "རྒྱུ་"
57/// ```
58///
59/// # Safety
60/// The `ewts_converter_ptr` should be pointer returned from `create_ewts_converter()` fn.
61/// And `ewts_src` should be a valid pointer to the string
62///
63#[no_mangle]
64pub unsafe extern "C" fn ewts_to_unicode(ewts_converter_ptr: usize, ewts_src: *const c_char) -> *const c_char {
65 let c_str = CStr::from_ptr(ewts_src);
66 let str_slice: &str = c_str.to_str().unwrap();
67 let converter = (ewts_converter_ptr as *mut EwtsConverter).as_ref().unwrap();
68 let result = converter.ewts_to_unicode(str_slice);
69 let c_string = CString::new(result).unwrap();
70 c_string.into_raw()
71}
72
73/// As a precaution
74///
75/// # Safety
76/// The ptr should be a pointer to the string returned from convert function
77#[no_mangle]
78pub unsafe extern "C" fn free_ewts_string(ptr: *const c_char) {
79 let _ = CString::from_raw(ptr as *mut _);
80}