Skip to main content

rquickjs_core/value/
string.rs

1use crate::{qjs, util::Sealed, Ctx, Error, Result, StdString, Value};
2use core::{
3    ffi::c_char,
4    marker::PhantomData,
5    mem::{self, ManuallyDrop},
6    ptr::NonNull,
7    slice, str,
8};
9
10/// Rust representation of a JavaScript string.
11#[derive(Debug, Clone, PartialEq, Hash)]
12#[repr(transparent)]
13pub struct String<'js>(pub(crate) Value<'js>);
14
15impl<'js> String<'js> {
16    /// Convert the JavaScript string to a Rust string.
17    pub fn to_string(&self) -> Result<StdString> {
18        let string = self.clone().to_cstring()?.validate()?;
19        Ok(string.as_str().into())
20    }
21
22    /// Convert the JavaScript string to a Rust string, replacing invalid UTF-8
23    /// sequences with the Unicode replacement character (`U+FFFD`).
24    pub fn to_string_lossy(&self) -> Result<StdString> {
25        let string = self.clone().to_cstring()?;
26        Ok(StdString::from_utf8_lossy(string.as_bytes()).into_owned())
27    }
28
29    /// Convert the Javascript string to a Javascript C string.
30    pub fn to_cstring(self) -> Result<CString<'js>> {
31        CString::from_string(self)
32    }
33
34    /// Create a new JavaScript string from an Rust string.
35    pub fn from_str(ctx: Ctx<'js>, s: &str) -> Result<Self> {
36        let len = s.len();
37        let ptr = s.as_ptr();
38        Ok(unsafe {
39            let js_val = qjs::JS_NewStringLen(ctx.as_ptr(), ptr as _, len as _);
40            let js_val = ctx.handle_exception(js_val)?;
41            String::from_js_value(ctx, js_val)
42        })
43    }
44}
45
46/// Encoding marker for a JavaScript C string.
47pub trait CStringEncoding: Sealed + 'static {}
48
49/// A JavaScript C string validated as WTF-8.
50#[derive(Debug, Clone, Copy)]
51pub struct Wtf8;
52impl Sealed for Wtf8 {}
53impl CStringEncoding for Wtf8 {}
54
55/// A JavaScript C string validated as UTF-8.
56#[derive(Debug, Clone, Copy)]
57pub struct Utf8;
58impl Sealed for Utf8 {}
59impl CStringEncoding for Utf8 {}
60
61/// Rust representation of a JavaScript C string.
62///
63/// QuickJS strings may contain WTF-8. The default `CString<'js, Wtf8>` exposes
64/// bytes only; call [`CString::validate`] to obtain a `CString<'js, Utf8>` with
65/// access to UTF-8 string slices.
66#[derive(Debug)]
67pub struct CString<'js, E: CStringEncoding = Wtf8> {
68    ptr: NonNull<c_char>,
69    len: usize,
70    ctx: Ctx<'js>,
71    _encoding: PhantomData<E>,
72}
73
74impl<'js> CString<'js> {
75    /// Create a new JavaScript C string from a JavaScript string.
76    pub fn from_string(string: String<'js>) -> Result<Self> {
77        let mut len = mem::MaybeUninit::uninit();
78        // SAFETY: The pointer points to a JSString content which is ref counted
79        let ptr = unsafe {
80            qjs::JS_ToCStringLen(string.0.ctx.as_ptr(), len.as_mut_ptr(), string.as_raw())
81        };
82        if ptr.is_null() {
83            // Might not ever happen but I am not 100% sure
84            // so just incase check it.
85            return Err(Error::Unknown);
86        }
87        let len = unsafe { len.assume_init() };
88        Ok(Self {
89            ptr: unsafe { NonNull::new_unchecked(ptr as *mut _) },
90            len,
91            ctx: string.0.ctx.clone(),
92            _encoding: PhantomData,
93        })
94    }
95
96    /// Validate the bytes as UTF-8 without copying the string.
97    ///
98    /// Returns an error if the string contains invalid UTF-8.
99    pub fn validate(self) -> Result<CString<'js, Utf8>> {
100        str::from_utf8(self.as_bytes())?;
101        let this = ManuallyDrop::new(self);
102        Ok(CString {
103            ptr: this.ptr,
104            len: this.len,
105            // SAFETY: `this` will not be dropped; ownership of its context is transferred.
106            ctx: unsafe { core::ptr::read(&this.ctx) },
107            _encoding: PhantomData,
108        })
109    }
110}
111
112impl<'js, E: CStringEncoding> CString<'js, E> {
113    /// Create a JavaScript string value in the given context, preserving WTF-8.
114    pub fn to_value(&self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
115        // SAFETY: The pointer is valid for `len` bytes, and QuickJS accepts WTF-8.
116        unsafe {
117            let value = qjs::JS_NewStringLen(ctx.as_ptr(), self.as_ptr(), self.len() as _);
118            let value = ctx.handle_exception(value)?;
119            Ok(Value::from_js_value(ctx.clone(), value))
120        }
121    }
122
123    /// Extracts the bytes of this string, excluding the trailing NUL.
124    pub fn as_bytes(&self) -> &[u8] {
125        // SAFETY: The allocation remains alive until this CString is dropped.
126        unsafe { slice::from_raw_parts(self.ptr.as_ptr().cast(), self.len) }
127    }
128
129    /// Converts a `CString` to a raw pointer.
130    pub fn as_ptr(&self) -> *const c_char {
131        self.ptr.as_ptr() as *const _
132    }
133
134    /// Returns the length of this `CString`, in bytes (not chars or graphemes).
135    pub fn len(&self) -> usize {
136        self.len
137    }
138
139    /// Returns `true` if this `CString` has a length of zero, and `false` otherwise.
140    pub fn is_empty(&self) -> bool {
141        self.len == 0
142    }
143}
144
145impl<'js> CString<'js, Utf8> {
146    /// Extracts a string slice containing the entire validated `CString`.
147    pub fn as_str(&self) -> &str {
148        // SAFETY: Only UTF-8 validation can construct this specialization.
149        unsafe { str::from_utf8_unchecked(self.as_bytes()) }
150    }
151}
152
153impl<'js, E: CStringEncoding> Drop for CString<'js, E> {
154    fn drop(&mut self) {
155        unsafe { qjs::JS_FreeCString(self.ctx.as_ptr(), self.ptr.as_ptr()) };
156    }
157}
158impl<'js> AsRef<str> for CString<'js, Utf8> {
159    fn as_ref(&self) -> &str {
160        self.as_str()
161    }
162}
163#[cfg(feature = "std")]
164impl<'js> AsRef<std::path::Path> for CString<'js, Utf8> {
165    fn as_ref(&self) -> &std::path::Path {
166        std::path::Path::new(self.as_str())
167    }
168}
169impl<'js> core::ops::Deref for CString<'js, Utf8> {
170    type Target = str;
171
172    fn deref(&self) -> &Self::Target {
173        self.as_str()
174    }
175}
176#[cfg(feature = "std")]
177impl<'js> AsRef<std::ffi::OsStr> for CString<'js, Utf8> {
178    fn as_ref(&self) -> &std::ffi::OsStr {
179        self.as_str().as_ref()
180    }
181}
182impl<'js, E: CStringEncoding> AsRef<[u8]> for CString<'js, E> {
183    fn as_ref(&self) -> &[u8] {
184        self.as_bytes()
185    }
186}
187impl<'js, E: CStringEncoding, Other: CStringEncoding> PartialEq<CString<'js, Other>>
188    for CString<'js, E>
189{
190    fn eq(&self, other: &CString<'js, Other>) -> bool {
191        self.as_bytes() == other.as_bytes()
192    }
193}
194impl<'js, E: CStringEncoding> Eq for CString<'js, E> {}
195impl<'js, E: CStringEncoding> core::hash::Hash for CString<'js, E> {
196    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
197        core::hash::Hash::hash(self.as_bytes(), state)
198    }
199}
200
201#[cfg(test)]
202mod test {
203    use crate::{prelude::*, *};
204    #[test]
205    fn from_javascript() {
206        test_with(|ctx| {
207            let s: String = ctx.eval(" 'foo bar baz' ").unwrap();
208            assert_eq!(s.to_string().unwrap(), "foo bar baz");
209        });
210    }
211
212    #[test]
213    fn string_conversions() {
214        test_with(|ctx| {
215            let string: String = ctx.eval(r#""hello\u0000\u{1f600}""#).unwrap();
216            let cstring = string.clone().to_cstring().unwrap();
217            assert_eq!(string.to_string().unwrap(), "hello\0😀");
218            assert_eq!(string.to_string_lossy().unwrap(), "hello\0😀");
219            let owned = CString::from_string(string).unwrap();
220            assert_eq!(cstring, owned);
221            assert_eq!(cstring.as_bytes(), "hello\0😀".as_bytes());
222
223            let invalid: String = ctx.eval(r#""\ud800""#).unwrap();
224            assert!(matches!(invalid.to_string(), Err(Error::Utf8(_))));
225            assert_eq!(
226                invalid.clone().to_cstring().unwrap().as_bytes(),
227                &[0xed, 0xa0, 0x80]
228            );
229            assert!(invalid.to_string_lossy().is_ok());
230        });
231    }
232
233    #[test]
234    fn to_string_lossy() {
235        test_with(|ctx| {
236            for (source, expected) in [
237                (r#""""#, ""),
238                (r#""hello\u0000\u{1f600}""#, "hello\0😀"),
239                (r#""a\ud800b\udfffc""#, "a���b���c"),
240                (r#""\ud83d\ude00""#, "😀"),
241            ] {
242                let string: String = ctx.eval(source).unwrap();
243                assert_eq!(string.to_string_lossy().unwrap(), expected);
244            }
245        });
246    }
247
248    #[test]
249    fn to_javascript() {
250        test_with(|ctx| {
251            let string = String::from_str(ctx.clone(), "foo").unwrap();
252            let func: Function = ctx.eval("x =>  x + 'bar'").unwrap();
253            let text: StdString = (string,).apply(&func).unwrap();
254            assert_eq!(text, "foobar".to_string());
255        });
256    }
257
258    #[test]
259    fn from_javascript_c() {
260        test_with(|ctx| {
261            let s: CString<Utf8> = ctx.eval(" 'foo bar baz' ").unwrap();
262            assert_eq!(s.as_str(), "foo bar baz");
263        });
264    }
265
266    #[test]
267    fn cstring_validation() {
268        test_with(|ctx| {
269            let string: CString = ctx.eval(r#""hello\u0000\u{1f600}""#).unwrap();
270            let expected = "hello\0😀";
271            assert_eq!(string.as_bytes(), expected.as_bytes());
272            assert_eq!(AsRef::<[u8]>::as_ref(&string), expected.as_bytes());
273            assert_eq!(string.len(), expected.len());
274            assert!(!string.is_empty());
275            let ptr = string.as_ptr();
276            let validated = string.validate().unwrap();
277            assert_eq!(validated.as_ptr(), ptr);
278            assert_eq!(validated.as_str(), expected);
279            assert_eq!(validated.as_bytes(), expected.as_bytes());
280            assert_eq!(AsRef::<str>::as_ref(&validated), expected);
281            assert_eq!(&*validated, expected);
282
283            let empty: CString = ctx.eval("''").unwrap();
284            assert!(empty.is_empty());
285            assert_eq!(empty.validate().unwrap().as_str(), "");
286        });
287    }
288
289    #[test]
290    fn cstring_lone_surrogates() {
291        test_with(|ctx| {
292            for (source, bytes) in [
293                (r#""\ud800""#, &[0xed, 0xa0, 0x80][..]),
294                (r#""\udfff""#, &[0xed, 0xbf, 0xbf][..]),
295            ] {
296                let string: CString = ctx.eval(source).unwrap();
297                assert_eq!(string.as_bytes(), bytes);
298                assert_eq!(AsRef::<[u8]>::as_ref(&string), bytes);
299                assert!(matches!(string.validate(), Err(Error::Utf8(_))));
300                assert!(matches!(
301                    ctx.eval::<CString<Utf8>, _>(source),
302                    Err(Error::Utf8(_))
303                ));
304            }
305        });
306    }
307
308    #[test]
309    fn cstring_wtf8_round_trip() {
310        test_with(|ctx| {
311            for source in [r#""\ud800""#, r#""\udfff""#, r#""a\u0000\ud800\u{1f600}z""#] {
312                let string: CString = ctx.eval(source).unwrap();
313                let value = (&string).into_js(&ctx).unwrap();
314                let borrowed: CString = CString::from_js(&ctx, value).unwrap();
315                assert_eq!(borrowed.as_bytes(), string.as_bytes());
316
317                let value = string.into_js(&ctx).unwrap();
318                let owned: CString = CString::from_js(&ctx, value).unwrap();
319                assert_eq!(owned.as_bytes(), borrowed.as_bytes());
320            }
321        });
322    }
323
324    #[test]
325    fn cstring_equality_and_hash() {
326        use core::hash::{Hash, Hasher};
327
328        test_with(|ctx| {
329            let raw: CString = ctx.eval("'hello'").unwrap();
330            let validated: CString<Utf8> = ctx.eval("'hello'").unwrap();
331            assert_eq!(raw, validated);
332            let mut raw_hash = std::collections::hash_map::DefaultHasher::new();
333            let mut validated_hash = std::collections::hash_map::DefaultHasher::new();
334            raw.hash(&mut raw_hash);
335            validated.hash(&mut validated_hash);
336            assert_eq!(raw_hash.finish(), validated_hash.finish());
337        });
338    }
339
340    #[test]
341    fn to_javascript_c() {
342        test_with(|ctx| {
343            let string = String::from_str(ctx.clone(), "foo")
344                .unwrap()
345                .to_cstring()
346                .unwrap();
347            let func: Function = ctx.eval("x =>  x + 'bar'").unwrap();
348            let text: StdString = (string,).apply(&func).unwrap();
349            assert_eq!(text, "foobar".to_string());
350
351            let validated: CString<Utf8> = ctx.eval("'foo'").unwrap();
352            let text: StdString = (&validated,).apply(&func).unwrap();
353            assert_eq!(text, "foobar");
354            let text: StdString = (validated,).apply(&func).unwrap();
355            assert_eq!(text, "foobar");
356        });
357    }
358
359    #[test]
360    fn rope_string() {
361        test_with(|ctx| {
362            let val: Value = ctx
363                .eval(
364                    r#"
365                    let s = "";
366                    for (let i = 0; i < 10000; i++) s += "Line " + i + "\n";
367                    s
368                "#,
369                )
370                .unwrap();
371
372            assert_eq!(val.type_of(), Type::String);
373            assert!(val.is_string());
374            assert!(val.as_string().is_some());
375
376            let s: StdString = val.as_string().unwrap().to_string().unwrap();
377            assert!(s.starts_with("Line 0\n"));
378            assert!(s.contains("Line 999\n"));
379            assert!(s.len() > 8000);
380        });
381    }
382}