Skip to main content

mirascript_vm/value/types/
string.rs

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