1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use crate::any::Any;
use crate::utils::*;
use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
macro_rules! declare_string {
($name:ident) => {
#[doc = concat!("Wrapper for WebIDL `", stringify!($name), "`.\n\n")]
#[derive(Clone, Debug, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct $name {
inner: emlite::Val,
}
bind!($name);
impl From<$name> for Option<String> {
fn from(s: $name) -> Self {
s.as_::<Self>()
}
}
impl From<$name> for Option<Vec<u16>> {
fn from(s: $name) -> Self {
s.as_::<Self>()
}
}
impl From<&str> for $name {
fn from(s: &str) -> Self {
emlite::Val::from(s).as_::<Self>()
}
}
impl From<String> for $name {
fn from(s: String) -> Self {
emlite::Val::from(&s).as_::<Self>()
}
}
impl From<&[u16]> for $name {
fn from(s: &[u16]) -> Self {
emlite::Val::from(s).as_::<Self>()
}
}
impl From<Vec<u16>> for $name {
fn from(s: Vec<u16>) -> Self {
emlite::Val::from(s).as_::<Self>()
}
}
impl From<&Vec<u16>> for $name {
fn from(s: &Vec<u16>) -> Self {
emlite::Val::from(s).as_::<Self>()
}
}
// impl AsRef<str> for $name {
// fn as_ref(&self) -> &str {
// self.as_str().unwrap_or("")
// }
// }
impl crate::prelude::DynCast for $name {
#[inline]
fn instanceof(val: &Any) -> bool {
let ctor = emlite::Val::global("String");
val.instanceof(ctor)
}
#[inline]
fn unchecked_from_val(v: emlite::Val) -> Self {
v.as_::<Self>() // zero-cost new-type cast
}
#[inline]
fn unchecked_from_val_ref(v: &emlite::Val) -> &Self {
unsafe { &*(v as *const emlite::Val as *const Self) }
}
#[inline]
fn unchecked_from_val_mut(v: &mut emlite::Val) -> &mut Self {
unsafe { &mut *(v as *mut emlite::Val as *mut Self) }
}
}
impl $name {
/// Create a new JavaScript string from UTF-16 data.
pub fn from_utf16(utf16: &[u16]) -> Self {
Self::from(utf16)
}
/// Create a new JavaScript string from UTF-16 Vec.
pub fn from_utf16_vec(utf16: Vec<u16>) -> Self {
Self::from(utf16)
}
/// Convert a Rust String to a JavaScript string via UTF-16.
/// This can be useful when you want to ensure UTF-16 encoding path.
pub fn from_string_via_utf16(s: &str) -> Self {
let utf16: Vec<u16> = s.encode_utf16().collect();
Self::from_utf16(&utf16)
}
/// `len() == 0` convenience.
pub fn is_empty(&self) -> bool {
self.length() == 0
}
/// Borrow the JavaScript string as `&str` (UTF‑8 view).
pub fn as_string(&self) -> Option<String> {
self.inner.as_::<Option<String>>()
}
/// Borrow the JavaScript string as `&str` (UTF‑8 view).
pub fn to_std_string(&self) -> Option<String> {
self.inner.as_::<Option<String>>()
}
/// Extract the JavaScript string as UTF-16 Vec<u16>.
pub fn to_utf16(&self) -> Option<Vec<u16>> {
self.inner.as_::<Option<Vec<u16>>>()
}
/// Converts UTF-16 Vec<u16> to Rust String, if possible.
pub fn utf16_to_string(utf16: &[u16]) -> Result<String, core::char::DecodeUtf16Error> {
char::decode_utf16(utf16.iter().cloned()).collect()
}
/// Extracts UTF-16 data and converts to Rust String.
pub fn to_string_from_utf16(&self) -> Option<String> {
self.to_utf16()
.and_then(|utf16| Self::utf16_to_string(&utf16).ok())
}
/// Number of UTF-16 code units (`JSString.length`).
pub fn length(&self) -> usize {
self.inner.get("length").as_::<usize>()
}
/// Returns the 16-bit code unit at `idx` (like `charCodeAt`).
pub fn char_code_at(&self, idx: usize) -> Option<u16> {
let v = self.inner.call("charCodeAt", &[idx.into()]);
if v.is_undefined() {
None
} else {
Some(v.as_::<u16>())
}
}
pub fn set(&self, idx: usize, val: char) {
if idx < self.length() {
self.inner.set(idx, val as u32);
}
}
/// [`String.prototype.at`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/at)
pub fn at(&self, idx: isize) -> Option<Self> {
let v = self.inner.call("at", &[idx.into()]);
if v.is_undefined() {
None
} else {
Some(v.as_::<Self>())
}
}
/// [`String.prototype.codePointAt`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
pub fn code_point_at(&self, idx: usize) -> Option<u32> {
let v = self.inner.call("codePointAt", &[idx.into()]);
if v.is_undefined() {
None
} else {
Some(v.as_::<u32>())
}
}
/// [`String.prototype.concat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/concat)
pub fn concat(&self, rhs: &Self) -> Self {
self.inner
.call("concat", &[rhs.clone().into()])
.as_::<Self>()
}
/// [`String.prototype.endsWith`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith)
pub fn ends_with(&self, pat: &str) -> bool {
self.inner.call("endsWith", &[pat.into()]).as_::<bool>()
}
/// [`String.prototype.includes`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/includes)
pub fn includes(&self, pat: &str) -> bool {
self.inner.call("includes", &[pat.into()]).as_::<bool>()
}
/// [`String.prototype.indexOf`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf)
/// Returns `None` when not found.
pub fn index_of(&self, pat: &str) -> Option<usize> {
let n = self.inner.call("indexOf", &[pat.into()]).as_::<i32>();
if n == -1 { None } else { Some(n as usize) }
}
/// [`String.prototype.isWellFormed`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/isWellFormed)
pub fn is_well_formed(&self) -> bool {
self.inner.call("isWellFormed", &[]).as_::<bool>()
}
/// [`String.prototype.lastIndexOf`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf)
pub fn last_index_of(&self, pat: &str) -> Option<usize> {
let n = self.inner.call("lastIndexOf", &[pat.into()]).as_::<i32>();
if n == -1 { None } else { Some(n as usize) }
}
/// [`String.prototype.localeCompare`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare)
pub fn locale_compare(&self, other: &str) -> i32 {
self.inner
.call("localeCompare", &[other.into()])
.as_::<i32>()
}
/// [`String.prototype.match`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/match)
pub fn match_(&self, pat: &Any) -> Any {
self.inner.call("match", &[pat.clone()])
}
/// [`String.prototype.matchAll`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll)
pub fn match_all(&self, pat: &Any) -> Any {
self.inner.call("matchAll", &[pat.clone()])
}
/// [`String.prototype.normalize`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
pub fn normalize(&self, form: Option<String>) -> Self {
match form {
Some(f) => self.inner.call("normalize", &[f.into()]),
None => self.inner.call("normalize", &[]),
}
.as_::<Self>()
}
/// [`String.prototype.padEnd`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd)
pub fn pad_end(&self, target_len: usize, pad: Option<String>) -> Self {
match pad {
Some(p) => self.inner.call("padEnd", &[target_len.into(), p.into()]),
None => self.inner.call("padEnd", &[target_len.into()]),
}
.as_::<Self>()
}
/// [`String.prototype.padStart`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)
pub fn pad_start(&self, target_len: usize, pad: Option<String>) -> Self {
match pad {
Some(p) => self.inner.call("padStart", &[target_len.into(), p.into()]),
None => self.inner.call("padStart", &[target_len.into()]),
}
.as_::<Self>()
}
/// [`String.prototype.repeat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/repeat)
pub fn repeat(&self, count: usize) -> Self {
self.inner.call("repeat", &[count.into()]).as_::<Self>()
}
/// [`String.prototype.replace`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
pub fn replace(&self, pat: &Any, repl: &Any) -> Self {
self.inner
.call("replace", &[pat.clone(), repl.clone()])
.as_::<Self>()
}
/// [`String.prototype.replaceAll`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll)
pub fn replace_all(&self, pat: &Any, repl: &Any) -> Self {
self.inner
.call("replaceAll", &[pat.clone(), repl.clone()])
.as_::<Self>()
}
/// [`String.prototype.search`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/search)
pub fn search(&self, pat: &Any) -> isize {
self.inner.call("search", &[pat.clone()]).as_::<i32>() as isize
}
/// [`String.prototype.slice`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/slice)
pub fn slice(&self, start: isize, end: Option<isize>) -> Self {
match end {
Some(e) => self.inner.call("slice", &[start.into(), e.into()]),
None => self.inner.call("slice", &[start.into()]),
}
.as_::<Self>()
}
/// [`String.prototype.split`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/split)
pub fn split(&self, sep: &str) -> crate::array::TypedArray<Self> {
self.inner
.call("split", &[sep.into()])
.as_::<crate::array::TypedArray<Self>>()
}
/// [`String.prototype.startsWith`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith)
pub fn starts_with(&self, pat: &str) -> bool {
self.inner.call("startsWith", &[pat.into()]).as_::<bool>()
}
/// [`String.prototype.substring`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/substring)
pub fn substring(&self, start: usize, end: Option<usize>) -> Self {
match end {
Some(e) => self.inner.call("substring", &[start.into(), e.into()]),
None => self.inner.call("substring", &[start.into()]),
}
.as_::<Self>()
}
/// [`String.prototype.toLocaleLowerCase`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase)
pub fn to_locale_lower_case(&self) -> Self {
self.inner.call("toLocaleLowerCase", &[]).as_::<Self>()
}
/// [`String.prototype.toLocaleUpperCase`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleUpperCase)
pub fn to_locale_upper_case(&self) -> Self {
self.inner.call("toLocaleUpperCase", &[]).as_::<Self>()
}
/// [`String.prototype.toLowerCase`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase)
pub fn to_lower_case(&self) -> Self {
self.inner.call("toLowerCase", &[]).as_::<Self>()
}
/// [`String.prototype.toUpperCase`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase)
pub fn to_upper_case(&self) -> Self {
self.inner.call("toUpperCase", &[]).as_::<Self>()
}
/// [`String.prototype.toWellFormed`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toWellFormed)
pub fn to_well_formed(&self) -> Self {
self.inner.call("toWellFormed", &[]).as_::<Self>()
}
/// [`String.prototype.trim`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/trim)
pub fn trim(&self) -> Self {
self.inner.call("trim", &[]).as_::<Self>()
}
/// [`String.prototype.trimEnd`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd)
pub fn trim_end(&self) -> Self {
self.inner.call("trimEnd", &[]).as_::<Self>()
}
/// [`String.prototype.trimStart`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart)
pub fn trim_start(&self) -> Self {
self.inner.call("trimStart", &[]).as_::<Self>()
}
pub fn substr(&self, from: isize, length: Option<isize>) -> Self {
match length {
Some(l) => self.inner.call("substr", &[from.into(), l.into()]),
None => self.inner.call("substr", &[from.into()]),
}
.as_::<Self>()
}
pub fn value_of(&self) -> Self {
self.inner.call("valueOf", &[]).as_::<Self>()
}
/// Gets character at specified index
/// @param i character index
/// @returns character at index as String
pub fn char_at(&self, i: usize) -> Self {
self.inner.call("charAt", &[i.into()]).as_::<Self>()
}
/// Converts string to C string
/// @returns pointer to null-terminated C string
/// Note: This returns the UTF-8 representation as a String since we can't return raw pointers
pub fn c_str(&self) -> Option<String> {
self.to_std_string()
}
/// Gets the byte length of the string in UTF-8 encoding
/// @returns number of bytes in UTF-8 representation
pub fn byte_len(&self) -> usize {
if let Some(s) = self.as_string() {
s.len()
} else {
0
}
}
/// Converts to string representation
/// @returns string representation
pub fn to_string(&self) -> Self {
self.inner.call("toString", &[]).as_::<Self>()
}
}
impl core::fmt::Display for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if let Some(s) = self.as_string() {
f.write_str(&s)
} else {
f.write_str("undefined")
}
}
}
impl core::ops::Add for $name {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
self.call("concat", &[rhs.into()]).as_::<Self>()
}
}
impl PartialEq<str> for $name {
fn eq(&self, other: &str) -> bool {
self.as_string() == Some(other.to_string())
}
}
};
}
declare_string!(JsString);