Skip to main content

mirascript_vm/value/types/
string.rs

1use super::MiraValue;
2use crate::{Result, Runtime, value::arena::MiraManageable};
3
4impl MiraValue {
5    /// Create a `MiraValue` representing a static string.
6    #[inline]
7    pub const fn str(value: &'static &'static str) -> Self {
8        Self::StaticStr(value)
9    }
10
11    /// Allocate an owned string in a Runtime and return its value handle.
12    #[inline]
13    pub fn new_string(value: impl Into<String>, runtime: &mut Runtime) -> Result<Self> {
14        runtime.insert_string(value).map(Self::String)
15    }
16
17    /// Return whether this value is a static or arena-managed string.
18    #[inline]
19    pub const fn is_string(&self) -> bool {
20        matches!(self, Self::String(_) | Self::StaticStr(_))
21    }
22
23    /// Borrow this value's string payload from its owning Runtime.
24    #[inline]
25    pub fn as_str<'s>(&self, runtime: &'s Runtime) -> Result<Option<&'s str>> {
26        match self {
27            Self::String(handle) => runtime.get_string(*handle).map(Some),
28            Self::StaticStr(value) => Ok(Some(value)),
29            _ => Ok(None),
30        }
31    }
32}
33
34impl From<&'static &'static str> for MiraValue {
35    #[inline]
36    fn from(value: &'static &'static str) -> Self {
37        Self::StaticStr(value)
38    }
39}
40
41impl From<&'static &'static str> for MiraManageable {
42    #[inline]
43    fn from(value: &'static &'static str) -> Self {
44        std::convert::Into::<MiraValue>::into(value).into()
45    }
46}