Skip to main content

mirascript_vm/value/types/
string.rs

1use crate::{MiraError, MiraHandle, MiraType, Result, Runtime, TryFromMira};
2
3use super::{
4    MiraValue, MiraValueKind, Payload,
5    value::{RawValue, ValueTag},
6};
7
8impl MiraValue {
9    /// Create a [`MiraValue`] representing a static string.
10    #[inline]
11    pub fn str(value: &'static &'static str) -> Self {
12        Self::from_raw(RawValue::from_tagged(
13            ValueTag::StaticStr,
14            Payload::from_address(std::ptr::from_ref(value)).to_bytes(),
15        ))
16    }
17
18    /// Create a [`MiraValue`] representing a string value.
19    #[inline]
20    pub const fn string(value: MiraHandle<String>) -> Self {
21        Self::handle(ValueTag::String, value)
22    }
23
24    /// Return whether this value is a static or arena-managed string.
25    #[inline]
26    pub fn is_string(&self) -> bool {
27        matches!(self.value_type(), MiraType::String)
28    }
29
30    /// Borrow this value's string payload from its owning Runtime.
31    #[inline]
32    pub fn as_str<'s>(&self, runtime: &'s Runtime) -> Result<Option<&'s str>> {
33        match self.kind() {
34            MiraValueKind::String(handle) => runtime.get_string(handle).map(Some),
35            MiraValueKind::StaticStr(value) => Ok(Some(value)),
36            _ => Ok(None),
37        }
38    }
39
40    /// Borrow this value's string payload from its owning Runtime.
41    #[inline]
42    pub fn as_str_unchecked<'s>(&self, runtime: &'s Runtime) -> &'s str {
43        self.as_str(runtime)
44            .expect("Runtime error")
45            .expect("Value is not a string")
46    }
47}
48
49impl From<&'static &'static str> for MiraValue {
50    #[inline]
51    fn from(value: &'static &'static str) -> Self {
52        Self::str(value)
53    }
54}
55
56impl<'a> TryFromMira<'a> for &'a str {
57    fn from_mira(runtime: &'a Runtime, value: MiraValue) -> Result<Self> {
58        let str = value.as_str(runtime)?;
59        str.ok_or_else(|| MiraError::conversion_type("&str", value.value_type()))
60    }
61}
62
63impl TryFromMira<'_> for String {
64    fn from_mira(runtime: &Runtime, value: MiraValue) -> Result<Self> {
65        let str = value.as_str(runtime)?;
66        str.map(str::to_owned)
67            .ok_or_else(|| MiraError::conversion_type("String", value.value_type()))
68    }
69}