artichoke_backend/
platform_string.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use std::borrow::Cow;

use artichoke_core::convert::TryConvertMut;
use scolapasta_path::ConvertBytesError;
use spinoso_exception::ArgumentError;

use crate::core::ClassRegistry;
use crate::error::{Error, RubyException};
use crate::sys;
use crate::Artichoke;

impl RubyException for ConvertBytesError {
    fn message(&self) -> Cow<'_, [u8]> {
        Cow::Borrowed(b"invalid byte sequence")
    }

    fn name(&self) -> Cow<'_, str> {
        "ArgumentError".into()
    }

    fn vm_backtrace(&self, interp: &mut Artichoke) -> Option<Vec<Vec<u8>>> {
        let _ = interp;
        None
    }

    fn as_mrb_value(&self, interp: &mut Artichoke) -> Option<sys::mrb_value> {
        let message = interp.try_convert_mut(self.message()).ok()?;
        let value = interp.new_instance::<ArgumentError>(&[message]).ok().flatten()?;
        Some(value.inner())
    }
}

impl From<ConvertBytesError> for Error {
    fn from(exception: ConvertBytesError) -> Self {
        let err: Box<dyn RubyException> = Box::new(exception);
        Self::from(err)
    }
}

#[cfg(test)]
mod tests {
    use super::ConvertBytesError;
    use crate::error::{Error, RubyException};

    #[test]
    fn box_convert() {
        // Prevents regressing on a stack overflow caused by a mutual recursion.
        let err = Error::from(ConvertBytesError::new());
        assert_eq!(err.name(), "ArgumentError");
    }
}