scie_onig.rs 1.9 KB
Newer Older
P
Phodal Huang 已提交
1 2
//
//
3 4 5
use std::ptr::null_mut;
use onig::{Syntax, EncodedChars};
use std::sync::Mutex;
6
use crate::scanner::old::scie_error::ScieOnigError;
P
Phodal Huang 已提交
7

8 9
lazy_static! {
    static ref REGEX_NEW_MUTEX: Mutex<()> = Mutex::new(());
P
Phodal Huang 已提交
10 11
}

12 13 14 15 16 17 18
bitflags! {
    pub struct ScieOnigOptions: onig_sys::OnigOptionType {
        const REGEX_OPTION_NONE
            = onig_sys::ONIG_OPTION_NONE;
    }
}

P
Phodal Huang 已提交
19 20 21
pub struct ScieOnig {
    raw: onig_sys::OnigRegex,
}
22

P
Phodal Huang 已提交
23
impl ScieOnig {
24
    pub fn demo_new(pattern: &str) -> Result<Self, ScieOnigError> {
25 26 27 28 29 30
        let option = ScieOnigOptions::REGEX_OPTION_NONE;
        let syntax = Syntax::default();

        // `onig_new`.
        let mut reg: onig_sys::OnigRegex = null_mut();
        let reg_ptr = &mut reg as *mut onig_sys::OnigRegex;
P
Phodal Huang 已提交
31

32 33 34 35 36 37 38 39
        // We can use this later to get an error message to pass back
        // if regex creation fails.
        let mut error = onig_sys::OnigErrorInfo {
            enc: null_mut(),
            par: null_mut(),
            par_end: null_mut(),
        };

P
Phodal Huang 已提交
40
        let err = unsafe {
41 42 43 44 45 46 47 48 49 50 51
            // Grab a lock to make sure that `onig_new` isn't called by
            // more than one thread at a time.
            let _guard = REGEX_NEW_MUTEX.lock().unwrap();
            onig_sys::onig_new(
                reg_ptr,
                pattern.start_ptr(),
                pattern.limit_ptr(),
                option.bits(),
                pattern.encoding(),
                syntax as *const Syntax as *mut Syntax as *mut onig_sys::OnigSyntaxType,
                &mut error,
P
Phodal Huang 已提交
52
            )
53
        };
P
Phodal Huang 已提交
54 55 56 57 58 59

        if err == onig_sys::ONIG_NORMAL as i32 {
            Ok(ScieOnig { raw: reg })
        } else {
            Err(ScieOnigError::from_code_and_info(err, &error))
        }
P
Phodal Huang 已提交
60
    }
P
Phodal Huang 已提交
61 62 63
    pub fn create_onig_scanner(_sources: Vec<String>) {

    }
P
Phodal Huang 已提交
64 65
}

66 67 68

#[cfg(test)]
mod tests {
69
    use crate::scanner::old::scie_onig::ScieOnig;
70 71 72

    #[test]
    fn it_works() {
P
Phodal Huang 已提交
73
        let _result = ScieOnig::demo_new(r"^");
74 75 76
        assert!(true)
    }
}