Skip to main content

mlua/
string.rs

1//! Lua string handling.
2//!
3//! This module provides types for working with Lua strings from Rust.
4
5use std::borrow::Borrow;
6use std::hash::{Hash, Hasher};
7use std::ops::Deref;
8use std::os::raw::{c_int, c_void};
9use std::{cmp, fmt, mem, slice, str};
10
11use crate::error::{Error, Result};
12use crate::state::Lua;
13use crate::traits::IntoLua;
14use crate::types::{LuaType, ValueRef};
15use crate::value::Value;
16
17#[cfg(feature = "serde")]
18use {
19    serde::ser::{Serialize, Serializer},
20    std::result::Result as StdResult,
21};
22
23/// Handle to an internal Lua string.
24///
25/// Unlike Rust strings, Lua strings may not be valid UTF-8.
26#[derive(Clone, PartialEq)]
27pub struct LuaString(pub(crate) ValueRef);
28
29impl LuaString {
30    /// Get a [`BorrowedStr`] if the Lua string is valid UTF-8.
31    ///
32    /// The returned `BorrowedStr` holds a strong reference to the Lua state to guarantee the
33    /// validity of the underlying data.
34    ///
35    /// # Examples
36    ///
37    /// ```
38    /// # use mlua::{Lua, LuaString, Result};
39    /// # fn main() -> Result<()> {
40    /// # let lua = Lua::new();
41    /// let globals = lua.globals();
42    ///
43    /// let version: LuaString = globals.get("_VERSION")?;
44    /// assert!(version.to_str()?.contains("Lua"));
45    ///
46    /// let non_utf8: LuaString = lua.load(r#"  "test\255"  "#).eval()?;
47    /// assert!(non_utf8.to_str().is_err());
48    /// # Ok(())
49    /// # }
50    /// ```
51    #[inline]
52    pub fn to_str(&self) -> Result<BorrowedStr> {
53        BorrowedStr::try_from(self)
54    }
55
56    /// Converts this Lua string to a [`String`].
57    ///
58    /// Any non-Unicode sequences are replaced with [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
59    ///
60    /// This method returns [`String`] instead of [`Cow<'_, str>`] because lifetime cannot be
61    /// bound to a weak Lua object.
62    ///
63    /// [U+FFFD]: std::char::REPLACEMENT_CHARACTER
64    /// [`Cow<'_, str>`]: std::borrow::Cow
65    ///
66    /// # Examples
67    ///
68    /// ```
69    /// # use mlua::{Lua, Result};
70    /// # fn main() -> Result<()> {
71    /// let lua = Lua::new();
72    ///
73    /// let s = lua.create_string(b"test\xff")?;
74    /// assert_eq!(s.to_string_lossy(), "test\u{fffd}");
75    /// # Ok(())
76    /// # }
77    /// ```
78    #[inline]
79    pub fn to_string_lossy(&self) -> String {
80        String::from_utf8_lossy(&self.as_bytes()).into_owned()
81    }
82
83    /// Returns an object that implements [`Display`] for safely printing a [`LuaString`] that may
84    /// contain non-Unicode data.
85    ///
86    /// This may perform lossy conversion.
87    ///
88    /// [`Display`]: fmt::Display
89    pub fn display(&self) -> impl fmt::Display + '_ {
90        Display(self)
91    }
92
93    /// Get the bytes that make up this string.
94    ///
95    /// The returned `BorrowedStr` holds a strong reference to the Lua state to guarantee the
96    /// validity of the underlying data. The data will not contain the terminating null byte, but
97    /// will contain any null bytes embedded into the Lua string.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// # use mlua::{Lua, LuaString, Result};
103    /// # fn main() -> Result<()> {
104    /// # let lua = Lua::new();
105    /// let non_utf8: LuaString = lua.load(r#"  "test\255"  "#).eval()?;
106    /// assert!(non_utf8.to_str().is_err());    // oh no :(
107    /// assert_eq!(non_utf8.as_bytes(), &b"test\xff"[..]);
108    /// # Ok(())
109    /// # }
110    /// ```
111    #[inline]
112    pub fn as_bytes(&self) -> BorrowedBytes {
113        BorrowedBytes::from(self)
114    }
115
116    /// Get the bytes that make up this string, including the trailing null byte.
117    pub fn as_bytes_with_nul(&self) -> BorrowedBytes {
118        let BorrowedBytes { buf, vref, _lua } = BorrowedBytes::from(self);
119        // Include the trailing null byte (it's always present but excluded by default)
120        let buf = unsafe { slice::from_raw_parts((*buf).as_ptr(), (*buf).len() + 1) };
121        BorrowedBytes { buf, vref, _lua }
122    }
123
124    // Does not return the terminating null byte
125    unsafe fn to_slice(&self) -> (&[u8], Lua) {
126        let lua = self.0.lua.upgrade();
127        let slice = {
128            let rawlua = lua.lock();
129            let ref_thread = rawlua.ref_thread();
130
131            mlua_debug_assert!(
132                ffi::lua_type(ref_thread, self.0.index) == ffi::LUA_TSTRING,
133                "string ref is not string type"
134            );
135
136            // This will not trigger a 'm' error, because the reference is guaranteed to be of
137            // string type
138            let mut size = 0;
139            let data = ffi::lua_tolstring(ref_thread, self.0.index, &mut size);
140            slice::from_raw_parts(data as *const u8, size)
141        };
142        (slice, lua)
143    }
144
145    /// Converts this Lua string to a generic C pointer.
146    ///
147    /// There is no way to convert the pointer back to its original value.
148    ///
149    /// Typically this function is used only for hashing and debug information.
150    #[inline]
151    pub fn to_pointer(&self) -> *const c_void {
152        // In Lua < 5.4 (excluding Luau), string pointers are NULL
153        // Use alternative approach
154        let lua = self.0.lua.lock();
155        unsafe { ffi::lua_tostring(lua.ref_thread(), self.0.index) as *const c_void }
156    }
157}
158
159impl fmt::Debug for LuaString {
160    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
161        let bytes = self.as_bytes();
162        // Check if the string is valid utf8
163        if let Ok(s) = str::from_utf8(&bytes) {
164            return s.fmt(f);
165        }
166
167        // Format as bytes
168        write!(f, "b")?;
169        <bstr::BStr as fmt::Debug>::fmt(bstr::BStr::new(&bytes), f)
170    }
171}
172
173// Lua strings are basically `&[u8]` slices, so implement `PartialEq` for anything resembling that.
174//
175// This makes our `LuaString` comparable with `Vec<u8>`, `[u8]`, `&str` and `String`.
176//
177// The only downside is that this disallows a comparison with `Cow<str>`, as that only implements
178// `AsRef<str>`, which collides with this impl. Requiring `AsRef<str>` would fix that, but limit us
179// in other ways.
180impl<T> PartialEq<T> for LuaString
181where
182    T: AsRef<[u8]> + ?Sized,
183{
184    fn eq(&self, other: &T) -> bool {
185        self.as_bytes() == other.as_ref()
186    }
187}
188
189impl Eq for LuaString {}
190
191impl<T> PartialOrd<T> for LuaString
192where
193    T: AsRef<[u8]> + ?Sized,
194{
195    fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
196        <[u8]>::partial_cmp(&self.as_bytes(), other.as_ref())
197    }
198}
199
200impl PartialOrd for LuaString {
201    fn partial_cmp(&self, other: &LuaString) -> Option<cmp::Ordering> {
202        Some(self.cmp(other))
203    }
204}
205
206impl Ord for LuaString {
207    fn cmp(&self, other: &LuaString) -> cmp::Ordering {
208        self.as_bytes().cmp(&other.as_bytes())
209    }
210}
211
212impl Hash for LuaString {
213    fn hash<H: Hasher>(&self, state: &mut H) {
214        self.as_bytes().hash(state);
215    }
216}
217
218#[cfg(feature = "serde")]
219impl Serialize for LuaString {
220    fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
221    where
222        S: Serializer,
223    {
224        match self.to_str() {
225            Ok(s) => serializer.serialize_str(&s),
226            Err(_) => serializer.serialize_bytes(&self.as_bytes()),
227        }
228    }
229}
230
231struct Display<'a>(&'a LuaString);
232
233impl fmt::Display for Display<'_> {
234    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
235        let bytes = self.0.as_bytes();
236        <bstr::BStr as fmt::Display>::fmt(bstr::BStr::new(&bytes), f)
237    }
238}
239
240/// A borrowed string (`&str`) that holds a strong reference to the Lua state.
241pub struct BorrowedStr {
242    // `buf` points to a readonly memory managed by Lua
243    pub(crate) buf: &'static str,
244    pub(crate) vref: ValueRef,
245    pub(crate) _lua: Lua,
246}
247
248impl Deref for BorrowedStr {
249    type Target = str;
250
251    #[inline(always)]
252    fn deref(&self) -> &str {
253        self.buf
254    }
255}
256
257impl Borrow<str> for BorrowedStr {
258    #[inline(always)]
259    fn borrow(&self) -> &str {
260        self.buf
261    }
262}
263
264impl AsRef<str> for BorrowedStr {
265    #[inline(always)]
266    fn as_ref(&self) -> &str {
267        self.buf
268    }
269}
270
271impl Hash for BorrowedStr {
272    fn hash<H: Hasher>(&self, state: &mut H) {
273        self.buf.hash(state);
274    }
275}
276
277impl fmt::Display for BorrowedStr {
278    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279        self.buf.fmt(f)
280    }
281}
282
283impl fmt::Debug for BorrowedStr {
284    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
285        self.buf.fmt(f)
286    }
287}
288
289impl<T> PartialEq<T> for BorrowedStr
290where
291    T: AsRef<str>,
292{
293    fn eq(&self, other: &T) -> bool {
294        self.buf == other.as_ref()
295    }
296}
297
298impl Eq for BorrowedStr {}
299
300impl<T> PartialOrd<T> for BorrowedStr
301where
302    T: AsRef<str>,
303{
304    fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
305        self.buf.partial_cmp(other.as_ref())
306    }
307}
308
309impl Ord for BorrowedStr {
310    fn cmp(&self, other: &Self) -> cmp::Ordering {
311        self.buf.cmp(other.buf)
312    }
313}
314
315impl TryFrom<&LuaString> for BorrowedStr {
316    type Error = Error;
317
318    #[inline]
319    fn try_from(value: &LuaString) -> Result<Self> {
320        let BorrowedBytes { buf, vref, _lua } = BorrowedBytes::from(value);
321        let buf =
322            str::from_utf8(buf).map_err(|e| Error::from_lua_conversion("string", "&str", e.to_string()))?;
323        Ok(Self { buf, vref, _lua })
324    }
325}
326
327/// A borrowed byte slice (`&[u8]`) that holds a strong reference to the Lua state.
328pub struct BorrowedBytes {
329    // `buf` points to a readonly memory managed by Lua
330    pub(crate) buf: &'static [u8],
331    pub(crate) vref: ValueRef,
332    pub(crate) _lua: Lua,
333}
334
335impl Deref for BorrowedBytes {
336    type Target = [u8];
337
338    #[inline(always)]
339    fn deref(&self) -> &[u8] {
340        self.buf
341    }
342}
343
344impl Borrow<[u8]> for BorrowedBytes {
345    #[inline(always)]
346    fn borrow(&self) -> &[u8] {
347        self.buf
348    }
349}
350
351impl AsRef<[u8]> for BorrowedBytes {
352    #[inline(always)]
353    fn as_ref(&self) -> &[u8] {
354        self.buf
355    }
356}
357
358impl Hash for BorrowedBytes {
359    fn hash<H: Hasher>(&self, state: &mut H) {
360        self.buf.hash(state);
361    }
362}
363
364impl fmt::Debug for BorrowedBytes {
365    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
366        self.buf.fmt(f)
367    }
368}
369
370impl<T> PartialEq<T> for BorrowedBytes
371where
372    T: AsRef<[u8]>,
373{
374    fn eq(&self, other: &T) -> bool {
375        self.buf == other.as_ref()
376    }
377}
378
379impl Eq for BorrowedBytes {}
380
381impl<T> PartialOrd<T> for BorrowedBytes
382where
383    T: AsRef<[u8]>,
384{
385    fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
386        self.buf.partial_cmp(other.as_ref())
387    }
388}
389
390impl Ord for BorrowedBytes {
391    fn cmp(&self, other: &Self) -> cmp::Ordering {
392        self.buf.cmp(other.buf)
393    }
394}
395
396impl<'a> IntoIterator for &'a BorrowedBytes {
397    type Item = &'a u8;
398    type IntoIter = slice::Iter<'a, u8>;
399
400    fn into_iter(self) -> Self::IntoIter {
401        self.iter()
402    }
403}
404
405impl From<&LuaString> for BorrowedBytes {
406    #[inline]
407    fn from(value: &LuaString) -> Self {
408        let (buf, _lua) = unsafe { value.to_slice() };
409        let vref = value.0.clone();
410        // SAFETY: The `buf` is valid for the lifetime of the Lua state and occupied slot index
411        let buf = unsafe { mem::transmute::<&[u8], &'static [u8]>(buf) };
412        Self { buf, vref, _lua }
413    }
414}
415
416struct WrappedString<T: AsRef<[u8]>>(T);
417
418impl LuaString {
419    /// Wraps bytes, returning an opaque type that implements [`IntoLua`] trait.
420    ///
421    /// This function uses [`Lua::create_string`] under the hood.
422    pub fn wrap(data: impl AsRef<[u8]>) -> impl IntoLua {
423        WrappedString(data)
424    }
425}
426
427impl<T: AsRef<[u8]>> IntoLua for WrappedString<T> {
428    fn into_lua(self, lua: &Lua) -> Result<Value> {
429        lua.create_string(self.0).map(Value::String)
430    }
431}
432
433impl LuaType for LuaString {
434    const TYPE_ID: c_int = ffi::LUA_TSTRING;
435}
436
437#[cfg(test)]
438mod assertions {
439    use super::*;
440
441    #[cfg(not(feature = "send"))]
442    static_assertions::assert_not_impl_any!(LuaString: Send);
443    #[cfg(feature = "send")]
444    static_assertions::assert_impl_all!(LuaString: Send, Sync);
445    #[cfg(feature = "send")]
446    static_assertions::assert_impl_all!(BorrowedBytes: Send, Sync);
447    #[cfg(feature = "send")]
448    static_assertions::assert_impl_all!(BorrowedStr: Send, Sync);
449}