-
Notifications
You must be signed in to change notification settings - Fork 328
/
Copy pathstring.rs
1181 lines (1076 loc) · 35.2 KB
/
string.rs
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::HandleScope;
use crate::Isolate;
use crate::Local;
use crate::String;
use crate::binding::v8__String__kMaxLength;
use crate::support::Opaque;
use crate::support::char;
use crate::support::int;
use crate::support::size_t;
use std::borrow::Cow;
use std::convert::TryInto;
use std::default::Default;
use std::ffi::c_void;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ptr::NonNull;
use std::slice;
unsafe extern "C" {
fn v8__String__Empty(isolate: *mut Isolate) -> *const String;
fn v8__String__NewFromUtf8(
isolate: *mut Isolate,
data: *const char,
new_type: NewStringType,
length: int,
) -> *const String;
fn v8__String__NewFromOneByte(
isolate: *mut Isolate,
data: *const u8,
new_type: NewStringType,
length: int,
) -> *const String;
fn v8__String__NewFromTwoByte(
isolate: *mut Isolate,
data: *const u16,
new_type: NewStringType,
length: int,
) -> *const String;
fn v8__String__Length(this: *const String) -> int;
fn v8__String__Utf8Length(this: *const String, isolate: *mut Isolate) -> int;
fn v8__String__Write(
this: *const String,
isolate: *mut Isolate,
buffer: *mut u16,
start: int,
length: int,
options: WriteOptions,
) -> int;
fn v8__String__Write_v2(
this: *const String,
isolate: *mut Isolate,
offset: u32,
length: u32,
buffer: *mut u16,
flags: int,
);
fn v8__String__WriteOneByte(
this: *const String,
isolate: *mut Isolate,
buffer: *mut u8,
start: int,
length: int,
options: WriteOptions,
) -> int;
fn v8__String__WriteOneByte_v2(
this: *const String,
isolate: *mut Isolate,
offset: u32,
length: u32,
buffer: *mut u8,
flags: int,
);
fn v8__String__WriteUtf8(
this: *const String,
isolate: *mut Isolate,
buffer: *mut char,
length: int,
nchars_ref: *mut int,
options: WriteOptions,
) -> int;
fn v8__String__WriteUtf8_v2(
this: *const String,
isolate: *mut Isolate,
buffer: *mut char,
capacity: size_t,
flags: int,
processed_characters_return: *mut size_t,
) -> int;
fn v8__String__GetExternalStringResource(
this: *const String,
) -> *mut ExternalStringResource;
fn v8__String__GetExternalStringResourceBase(
this: *const String,
encoding: *mut Encoding,
) -> *mut ExternalStringResourceBase;
fn v8__String__NewExternalOneByteConst(
isolate: *mut Isolate,
onebyte_const: *const OneByteConst,
) -> *const String;
fn v8__String__NewExternalOneByteStatic(
isolate: *mut Isolate,
buffer: *const char,
length: int,
) -> *const String;
fn v8__String__NewExternalOneByte(
isolate: *mut Isolate,
buffer: *mut char,
length: size_t,
free: unsafe extern "C" fn(*mut char, size_t),
) -> *const String;
fn v8__String__NewExternalTwoByteStatic(
isolate: *mut Isolate,
buffer: *const u16,
length: int,
) -> *const String;
#[allow(dead_code)]
fn v8__String__IsExternal(this: *const String) -> bool;
fn v8__String__IsExternalOneByte(this: *const String) -> bool;
fn v8__String__IsExternalTwoByte(this: *const String) -> bool;
#[allow(dead_code)]
fn v8__String__IsOneByte(this: *const String) -> bool;
fn v8__String__ContainsOnlyOneByte(this: *const String) -> bool;
fn v8__ExternalOneByteStringResource__data(
this: *const ExternalOneByteStringResource,
) -> *const char;
fn v8__ExternalOneByteStringResource__length(
this: *const ExternalOneByteStringResource,
) -> size_t;
fn v8__String__ValueView__CONSTRUCT(
buf: *mut ValueView,
isolate: *mut Isolate,
string: *const String,
);
fn v8__String__ValueView__DESTRUCT(this: *mut ValueView);
fn v8__String__ValueView__is_one_byte(this: *const ValueView) -> bool;
fn v8__String__ValueView__data(this: *const ValueView) -> *const c_void;
fn v8__String__ValueView__length(this: *const ValueView) -> int;
}
#[derive(PartialEq, Debug)]
#[repr(C)]
pub enum Encoding {
Unknown = 0x1,
TwoByte = 0x2,
OneByte = 0x8,
}
#[repr(C)]
pub struct ExternalStringResource(Opaque);
#[repr(C)]
pub struct ExternalStringResourceBase(Opaque);
#[repr(C)]
/// An external, one-byte string resource.
/// This corresponds with `v8::String::ExternalOneByteStringResource`.
///
/// Note: The data contained in a one-byte string resource is guaranteed to be
/// Latin-1 data. It is not safe to assume that it is valid UTF-8, as Latin-1
/// only has commonality with UTF-8 in the ASCII range and differs beyond that.
pub struct ExternalOneByteStringResource(Opaque);
impl ExternalOneByteStringResource {
/// Returns a pointer to the data owned by this resource.
/// This pointer is valid as long as the resource is alive.
/// The data is guaranteed to be Latin-1.
pub fn data(&self) -> *const char {
unsafe { v8__ExternalOneByteStringResource__data(self) }
}
/// Returns the length of the data owned by this resource.
pub fn length(&self) -> usize {
unsafe { v8__ExternalOneByteStringResource__length(self) }
}
/// Returns the data owned by this resource as a string slice.
/// The data is guaranteed to be Latin-1.
pub fn as_bytes(&self) -> &[u8] {
let len = self.length();
if len == 0 {
&[]
} else {
// SAFETY: We know this is Latin-1
unsafe { std::slice::from_raw_parts(self.data().cast(), len) }
}
}
}
/// A static ASCII string resource for usage in V8, created at build time.
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct OneByteConst {
vtable: *const OneByteConstNoOp,
cached_data: *const char,
length: usize,
}
impl OneByteConst {
/// `const` function that returns this string as a string reference.
#[inline(always)]
pub const fn as_str(&self) -> &str {
if self.length == 0 {
""
} else {
// SAFETY: We know this is ASCII and length > 0
unsafe {
std::str::from_utf8_unchecked(std::slice::from_raw_parts(
self.cached_data as _,
self.length,
))
}
}
}
}
impl AsRef<str> for OneByteConst {
#[inline(always)]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<[u8]> for OneByteConst {
#[inline(always)]
fn as_ref(&self) -> &[u8] {
self.as_str().as_bytes()
}
}
impl std::ops::Deref for OneByteConst {
type Target = str;
#[inline(always)]
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
// SAFETY: The vtable for OneByteConst is an immutable static and all
// of the included functions are thread-safe, the cached_data pointer
// is never changed and points to a static ASCII string, and the
// length is likewise never changed. Thus, it is safe to share the
// OneByteConst across threads. This means that multiple isolates
// can use the same OneByteConst statics simultaneously.
unsafe impl Sync for OneByteConst {}
unsafe extern "C" fn one_byte_const_no_op(_this: *const OneByteConst) {}
unsafe extern "C" fn one_byte_const_is_cacheable(
_this: *const OneByteConst,
) -> bool {
true
}
unsafe extern "C" fn one_byte_const_data(
this: *const OneByteConst,
) -> *const char {
// SAFETY: Only called from C++ with a valid OneByteConst pointer.
unsafe { (*this).cached_data }
}
unsafe extern "C" fn one_byte_const_length(this: *const OneByteConst) -> usize {
// SAFETY: Only called from C++ with a valid OneByteConst pointer.
unsafe { (*this).length }
}
unsafe extern "C" fn one_byte_const_unaccount(
_this: *const OneByteConst,
_isolate: *mut Isolate,
) {
}
unsafe extern "C" fn one_byte_const_estimate_memory_usage(
_this: *const OneByteConst,
) -> size_t {
usize::MAX // ExternalStringResource::kDefaultMemoryEstimate
}
unsafe extern "C" fn one_byte_const_estimate_shared_memory_usage(
_this: *const OneByteConst,
_recorder: *mut (),
) {
}
type OneByteConstNoOp = unsafe extern "C" fn(*const OneByteConst);
type OneByteConstIsCacheable =
unsafe extern "C" fn(*const OneByteConst) -> bool;
type OneByteConstData =
unsafe extern "C" fn(*const OneByteConst) -> *const char;
type OneByteConstLength = unsafe extern "C" fn(*const OneByteConst) -> usize;
type OneByteConstUnaccount =
unsafe extern "C" fn(*const OneByteConst, *mut Isolate);
type OneByteConstEstimateMemoryUsage =
unsafe extern "C" fn(*const OneByteConst) -> size_t;
type OneByteConstEstimateSharedMemoryUsage =
unsafe extern "C" fn(*const OneByteConst, *mut ());
#[repr(C)]
struct OneByteConstVtable {
#[cfg(target_family = "windows")]
// In SysV / Itanium ABI -0x10 offset of the vtable
// tells how many bytes the vtable pointer pointing to
// this vtable is offset from the base class. For
// single inheritance this is always 0.
_offset_to_top: usize,
// In Itanium ABI the -0x08 offset contains the type_info
// pointer, and in MSVC it contains the RTTI Complete Object
// Locator pointer. V8 is normally compiled with `-fno-rtti`
// meaning that this pointer is a nullptr on both
// Itanium and MSVC.
_typeinfo: *const (),
// After the metadata fields come the virtual function
// pointers. The vtable pointer in a class instance points
// to the first virtual function pointer, making this
// the 0x00 offset of the table.
// The order of the virtual function pointers is determined
// by their order of declaration in the classes.
delete1: OneByteConstNoOp,
// In SysV / Itanium ABI, a class vtable includes the
// deleting destructor and the compete object destructor.
// In MSVC, it only includes the deleting destructor.
#[cfg(not(target_family = "windows"))]
delete2: OneByteConstNoOp,
is_cacheable: OneByteConstIsCacheable,
unaccount: OneByteConstUnaccount,
estimate_memory_usage: OneByteConstEstimateMemoryUsage,
estimate_shared_memory_usage: OneByteConstEstimateSharedMemoryUsage,
dispose: OneByteConstNoOp,
lock: OneByteConstNoOp,
unlock: OneByteConstNoOp,
data: OneByteConstData,
length: OneByteConstLength,
}
const ONE_BYTE_CONST_VTABLE: OneByteConstVtable = OneByteConstVtable {
#[cfg(target_family = "windows")]
_offset_to_top: 0,
_typeinfo: std::ptr::null(),
delete1: one_byte_const_no_op,
#[cfg(not(target_family = "windows"))]
delete2: one_byte_const_no_op,
is_cacheable: one_byte_const_is_cacheable,
unaccount: one_byte_const_unaccount,
estimate_memory_usage: one_byte_const_estimate_memory_usage,
estimate_shared_memory_usage: one_byte_const_estimate_shared_memory_usage,
dispose: one_byte_const_no_op,
lock: one_byte_const_no_op,
unlock: one_byte_const_no_op,
data: one_byte_const_data,
length: one_byte_const_length,
};
#[repr(C)]
#[derive(Debug, Default)]
pub enum NewStringType {
#[default]
Normal,
Internalized,
}
bitflags! {
#[derive(Clone, Copy, Default)]
#[repr(transparent)]
pub struct WriteOptions: int {
const NO_OPTIONS = 0;
const HINT_MANY_WRITES_EXPECTED = 1;
const NO_NULL_TERMINATION = 2;
const PRESERVE_ONE_BYTE_NULL = 4;
// Used by WriteUtf8 to replace orphan surrogate code units with the
// unicode replacement character. Needs to be set to guarantee valid UTF-8
// output.
const REPLACE_INVALID_UTF8 = 8;
}
}
bitflags! {
#[derive(Clone, Copy, Default)]
#[repr(transparent)]
pub struct WriteFlags: int {
const kNullTerminate = crate::binding::v8_String_WriteFlags_kNullTerminate as _;
const kReplaceInvalidUtf8 = crate::binding::v8_String_WriteFlags_kReplaceInvalidUtf8 as _;
}
}
impl String {
/// The maximum length (in bytes) of a buffer that a v8::String can be built
/// from. Attempting to create a v8::String from a larger buffer will result
/// in None being returned.
pub const MAX_LENGTH: usize = v8__String__kMaxLength as _;
#[inline(always)]
pub fn empty<'s>(scope: &mut HandleScope<'s, ()>) -> Local<'s, String> {
// FIXME(bnoordhuis) v8__String__Empty() is infallible so there
// is no need to box up the result, only to unwrap it again.
unsafe { scope.cast_local(|sd| v8__String__Empty(sd.get_isolate_ptr())) }
.unwrap()
}
/// Allocates a new string from UTF-8 data. Only returns an empty value when
/// length > kMaxLength
#[inline(always)]
pub fn new_from_utf8<'s>(
scope: &mut HandleScope<'s, ()>,
buffer: &[u8],
new_type: NewStringType,
) -> Option<Local<'s, String>> {
if buffer.is_empty() {
return Some(Self::empty(scope));
}
let buffer_len = buffer.len().try_into().ok()?;
unsafe {
scope.cast_local(|sd| {
v8__String__NewFromUtf8(
sd.get_isolate_ptr(),
buffer.as_ptr() as *const char,
new_type,
buffer_len,
)
})
}
}
/// Allocates a new string from Latin-1 data. Only returns an empty value when
/// length > kMaxLength.
#[inline(always)]
pub fn new_from_one_byte<'s>(
scope: &mut HandleScope<'s, ()>,
buffer: &[u8],
new_type: NewStringType,
) -> Option<Local<'s, String>> {
let buffer_len = buffer.len().try_into().ok()?;
unsafe {
scope.cast_local(|sd| {
v8__String__NewFromOneByte(
sd.get_isolate_ptr(),
buffer.as_ptr(),
new_type,
buffer_len,
)
})
}
}
/// Allocates a new string from UTF-16 data. Only returns an empty value when
/// length > kMaxLength.
#[inline(always)]
pub fn new_from_two_byte<'s>(
scope: &mut HandleScope<'s, ()>,
buffer: &[u16],
new_type: NewStringType,
) -> Option<Local<'s, String>> {
let buffer_len = buffer.len().try_into().ok()?;
unsafe {
scope.cast_local(|sd| {
v8__String__NewFromTwoByte(
sd.get_isolate_ptr(),
buffer.as_ptr(),
new_type,
buffer_len,
)
})
}
}
/// Returns the number of characters (UTF-16 code units) in this string.
#[inline(always)]
pub fn length(&self) -> usize {
unsafe { v8__String__Length(self) as usize }
}
/// Returns the number of bytes in the UTF-8 encoded representation of this
/// string.
#[inline(always)]
pub fn utf8_length(&self, scope: &mut Isolate) -> usize {
unsafe { v8__String__Utf8Length(self, scope) as usize }
}
/// Writes the contents of the string to an external buffer, as 16-bit
/// (UTF-16) character codes.
#[inline(always)]
#[deprecated = "Use `v8::String::write_v2` instead"]
pub fn write(
&self,
scope: &mut Isolate,
buffer: &mut [u16],
start: usize,
options: WriteOptions,
) -> usize {
unsafe {
v8__String__Write(
self,
scope,
buffer.as_mut_ptr(),
start.try_into().unwrap_or(int::MAX),
buffer.len().try_into().unwrap_or(int::MAX),
options,
) as usize
}
}
/// Writes the contents of the string to an external buffer, as 16-bit
/// (UTF-16) character codes.
#[inline(always)]
pub fn write_v2(
&self,
scope: &mut Isolate,
offset: u32,
buffer: &mut [u16],
flags: WriteFlags,
) {
unsafe {
v8__String__Write_v2(
self,
scope,
offset,
self.length().min(buffer.len()) as _,
buffer.as_mut_ptr(),
flags.bits(),
)
}
}
/// Writes the contents of the string to an external buffer, as one-byte
/// (Latin-1) characters.
#[inline(always)]
#[deprecated = "Use `v8::String::write_one_byte_v2` instead."]
pub fn write_one_byte(
&self,
scope: &mut Isolate,
buffer: &mut [u8],
start: usize,
options: WriteOptions,
) -> usize {
unsafe {
v8__String__WriteOneByte(
self,
scope,
buffer.as_mut_ptr(),
start.try_into().unwrap_or(int::MAX),
buffer.len().try_into().unwrap_or(int::MAX),
options,
) as usize
}
}
/// Writes the contents of the string to an external buffer, as one-byte
/// (Latin-1) characters.
#[inline(always)]
pub fn write_one_byte_v2(
&self,
scope: &mut Isolate,
offset: u32,
buffer: &mut [u8],
flags: WriteFlags,
) {
unsafe {
v8__String__WriteOneByte_v2(
self,
scope,
offset,
self.length().min(buffer.len()) as _,
buffer.as_mut_ptr(),
flags.bits(),
)
}
}
/// Writes the contents of the string to an external [`MaybeUninit`] buffer, as one-byte
/// (Latin-1) characters.
#[inline(always)]
#[deprecated = "Use `v8::String::write_one_byte_uninit_v2` instead."]
pub fn write_one_byte_uninit(
&self,
scope: &mut Isolate,
buffer: &mut [MaybeUninit<u8>],
start: usize,
options: WriteOptions,
) -> usize {
unsafe {
v8__String__WriteOneByte(
self,
scope,
buffer.as_mut_ptr() as *mut u8,
start.try_into().unwrap_or(int::MAX),
buffer.len().try_into().unwrap_or(int::MAX),
options,
) as usize
}
}
/// Writes the contents of the string to an external [`MaybeUninit`] buffer, as one-byte
/// (Latin-1) characters.
#[inline(always)]
pub fn write_one_byte_uninit_v2(
&self,
scope: &mut Isolate,
offset: u32,
buffer: &mut [MaybeUninit<u8>],
flags: WriteFlags,
) {
unsafe {
v8__String__WriteOneByte_v2(
self,
scope,
offset,
self.length().min(buffer.len()) as _,
buffer.as_mut_ptr() as _,
flags.bits(),
)
}
}
/// Writes the contents of the string to an external buffer, as UTF-8.
#[inline(always)]
#[deprecated = "Use `v8::String::write_utf8_v2` instead."]
pub fn write_utf8(
&self,
scope: &mut Isolate,
buffer: &mut [u8],
nchars_ref: Option<&mut usize>,
options: WriteOptions,
) -> usize {
unsafe {
// SAFETY:
// We assume that v8 will overwrite the buffer without de-initializing any byte in it.
// So the type casting of the buffer is safe.
let buffer = {
let len = buffer.len();
let data = buffer.as_mut_ptr().cast();
slice::from_raw_parts_mut(data, len)
};
#[allow(deprecated)]
self.write_utf8_uninit(scope, buffer, nchars_ref, options)
}
}
/// Writes the contents of the string to an external buffer, as UTF-8.
#[inline(always)]
pub fn write_utf8_v2(
&self,
scope: &mut Isolate,
buffer: &mut [u8],
flags: WriteFlags,
processed_characters_return: Option<&mut usize>,
) -> usize {
unsafe {
// SAFETY:
// We assume that v8 will overwrite the buffer without de-initializing any byte in it.
// So the type casting of the buffer is safe.
let buffer = {
let len = buffer.len();
let data = buffer.as_mut_ptr().cast();
slice::from_raw_parts_mut(data, len)
};
self.write_utf8_uninit_v2(
scope,
buffer,
flags,
processed_characters_return,
)
}
}
/// Writes the contents of the string to an external [`MaybeUninit`] buffer, as UTF-8.
#[deprecated = "Use `v8::String::write_utf8_uninit_v2` instead."]
pub fn write_utf8_uninit(
&self,
scope: &mut Isolate,
buffer: &mut [MaybeUninit<u8>],
nchars_ref: Option<&mut usize>,
options: WriteOptions,
) -> usize {
let mut nchars_ref_int: int = 0;
let bytes = unsafe {
v8__String__WriteUtf8(
self,
scope,
buffer.as_mut_ptr() as *mut char,
buffer.len().try_into().unwrap_or(int::MAX),
&mut nchars_ref_int,
options,
)
};
if let Some(r) = nchars_ref {
*r = nchars_ref_int as usize;
}
bytes as usize
}
/// Writes the contents of the string to an external [`MaybeUninit`] buffer, as UTF-8.
pub fn write_utf8_uninit_v2(
&self,
scope: &mut Isolate,
buffer: &mut [MaybeUninit<u8>],
flags: WriteFlags,
processed_characters_return: Option<&mut usize>,
) -> usize {
let bytes = unsafe {
v8__String__WriteUtf8_v2(
self,
scope,
buffer.as_mut_ptr() as _,
buffer.len(),
flags.bits(),
processed_characters_return
.map(|p| p as *mut _)
.unwrap_or(std::ptr::null_mut()),
)
};
bytes as usize
}
// Convenience function not present in the original V8 API.
#[inline(always)]
pub fn new<'s>(
scope: &mut HandleScope<'s, ()>,
value: &str,
) -> Option<Local<'s, String>> {
Self::new_from_utf8(scope, value.as_ref(), NewStringType::Normal)
}
/// Compile-time function to create an external string resource.
/// The buffer is checked to contain only ASCII characters.
#[inline(always)]
pub const fn create_external_onebyte_const(
buffer: &'static [u8],
) -> OneByteConst {
// Assert that the buffer contains only ASCII, and that the
// length is less or equal to (64-bit) v8::String::kMaxLength.
assert!(buffer.is_ascii() && buffer.len() <= ((1 << 29) - 24));
OneByteConst {
vtable: &ONE_BYTE_CONST_VTABLE.delete1,
cached_data: buffer.as_ptr() as *const char,
length: buffer.len(),
}
}
/// Compile-time function to create an external string resource which
/// skips the ASCII and length checks.
///
/// ## Safety
///
/// The passed in buffer must contain only ASCII data. Note that while V8
/// allows OneByte string resources to contain Latin-1 data, the OneByteConst
/// struct does not allow it.
#[inline(always)]
pub const unsafe fn create_external_onebyte_const_unchecked(
buffer: &'static [u8],
) -> OneByteConst {
OneByteConst {
vtable: &ONE_BYTE_CONST_VTABLE.delete1,
cached_data: buffer.as_ptr() as *const char,
length: buffer.len(),
}
}
/// Creates a v8::String from a `&'static OneByteConst`
/// which is guaranteed to be ASCII.
///
/// Note that OneByteConst guarantees ASCII even though V8 would allow
/// OneByte string resources to contain Latin-1.
#[inline(always)]
pub fn new_from_onebyte_const<'s>(
scope: &mut HandleScope<'s, ()>,
onebyte_const: &'static OneByteConst,
) -> Option<Local<'s, String>> {
unsafe {
scope.cast_local(|sd| {
v8__String__NewExternalOneByteConst(sd.get_isolate_ptr(), onebyte_const)
})
}
}
/// Creates a v8::String from a `&'static [u8]`,
/// must be Latin-1 or ASCII, not UTF-8!
#[inline(always)]
pub fn new_external_onebyte_static<'s>(
scope: &mut HandleScope<'s, ()>,
buffer: &'static [u8],
) -> Option<Local<'s, String>> {
let buffer_len = buffer.len().try_into().ok()?;
unsafe {
scope.cast_local(|sd| {
v8__String__NewExternalOneByteStatic(
sd.get_isolate_ptr(),
buffer.as_ptr() as *const char,
buffer_len,
)
})
}
}
/// Creates a `v8::String` from owned bytes.
/// The bytes must be Latin-1 or ASCII.
/// V8 will take ownership of the buffer and free it when the string is garbage collected.
#[inline(always)]
pub fn new_external_onebyte<'s>(
scope: &mut HandleScope<'s, ()>,
buffer: Box<[u8]>,
) -> Option<Local<'s, String>> {
let buffer_len = buffer.len();
unsafe {
scope.cast_local(|sd| {
v8__String__NewExternalOneByte(
sd.get_isolate_ptr(),
Box::into_raw(buffer).cast::<char>(),
buffer_len,
free_rust_external_onebyte,
)
})
}
}
/// Creates a `v8::String` from owned bytes, length, and a custom destructor.
/// The bytes must be Latin-1 or ASCII.
/// V8 will take ownership of the buffer and free it when the string is garbage collected.
///
/// SAFETY: `buffer` must be owned (valid for the lifetime of the string), and
/// `destructor` must be a valid function pointer that can free the buffer.
/// The destructor will be called with the buffer and length when the string is garbage collected.
#[inline(always)]
pub unsafe fn new_external_onebyte_raw<'s>(
scope: &mut HandleScope<'s, ()>,
buffer: *mut char,
buffer_len: usize,
destructor: unsafe extern "C" fn(*mut char, usize),
) -> Option<Local<'s, String>> {
unsafe {
scope.cast_local(|sd| {
v8__String__NewExternalOneByte(
sd.get_isolate_ptr(),
buffer,
buffer_len,
destructor,
)
})
}
}
/// Creates a v8::String from a `&'static [u16]`.
#[inline(always)]
pub fn new_external_twobyte_static<'s>(
scope: &mut HandleScope<'s, ()>,
buffer: &'static [u16],
) -> Option<Local<'s, String>> {
let buffer_len = buffer.len().try_into().ok()?;
unsafe {
scope.cast_local(|sd| {
v8__String__NewExternalTwoByteStatic(
sd.get_isolate_ptr(),
buffer.as_ptr(),
buffer_len,
)
})
}
}
/// Get the ExternalStringResource for an external string.
///
/// Returns None if is_external() doesn't return true.
pub fn get_external_string_resource(
&self,
) -> Option<NonNull<ExternalStringResource>> {
NonNull::new(unsafe { v8__String__GetExternalStringResource(self) })
}
/// Get the ExternalOneByteStringResource for an external one-byte string.
///
/// Returns None if is_external_onebyte() doesn't return true.
pub fn get_external_onebyte_string_resource(
&self,
) -> Option<NonNull<ExternalOneByteStringResource>> {
let (base, encoding) = self.get_external_string_resource_base();
let base = base?;
if encoding != Encoding::OneByte {
return None;
}
Some(base.cast())
}
/// Get the ExternalStringResourceBase for an external string.
/// Note this is just the base class, and isn't very useful on its own.
/// You'll want to downcast to one of its subclasses, for instance
/// with `get_external_onebyte_string_resource`.
pub fn get_external_string_resource_base(
&self,
) -> (Option<NonNull<ExternalStringResourceBase>>, Encoding) {
let mut encoding = Encoding::Unknown;
(
NonNull::new(unsafe {
v8__String__GetExternalStringResourceBase(self, &mut encoding)
}),
encoding,
)
}
/// True if string is external
#[inline(always)]
pub fn is_external(&self) -> bool {
// TODO: re-enable on next v8-release
// Right now it fallbacks to Value::IsExternal, which is incorrect
// See: https://source.chromium.org/chromium/_/chromium/v8/v8.git/+/1dd8624b524d14076160c1743f7da0b20fbe68e0
// unsafe { v8__String__IsExternal(self) }
// Fallback for now (though functionally identical)
self.is_external_onebyte() || self.is_external_twobyte()
}
/// True if string is external & one-byte
/// (e.g: created with new_external_onebyte_static)
#[inline(always)]
pub fn is_external_onebyte(&self) -> bool {
unsafe { v8__String__IsExternalOneByte(self) }
}
/// True if string is external & two-byte
/// (e.g: created with new_external_twobyte_static)
#[inline(always)]
pub fn is_external_twobyte(&self) -> bool {
unsafe { v8__String__IsExternalTwoByte(self) }
}
/// Will return true if and only if string is known for certain to contain only one-byte data,
/// ie: Latin-1, a.k.a. ISO-8859-1 code points. Doesn't read the string so can return false
/// negatives, and a return value of false does not mean this string is not one-byte data.
///
/// For a method that will not return false negatives at the cost of
/// potentially reading the entire string, use [`contains_only_onebyte()`].
///
/// [`contains_only_onebyte()`]: String::contains_only_onebyte
#[inline(always)]
pub fn is_onebyte(&self) -> bool {
unsafe { v8__String__IsOneByte(self) }
}
/// True if the string contains only one-byte data.
/// Will read the entire string in some cases.
#[inline(always)]
pub fn contains_only_onebyte(&self) -> bool {
unsafe { v8__String__ContainsOnlyOneByte(self) }
}
/// Creates a copy of a [`crate::String`] in a [`std::string::String`].
/// Convenience function not present in the original V8 API.
pub fn to_rust_string_lossy(
&self,
scope: &mut Isolate,
) -> std::string::String {
let len_utf16 = self.length();
// No need to allocate or do any work for zero-length strings
if len_utf16 == 0 {
return std::string::String::new();
}
let len_utf8 = self.utf8_length(scope);
// If len_utf8 == len_utf16 and the string is one-byte, we can take the fast memcpy path. This is true iff the
// string is 100% 7-bit ASCII.
if self.is_onebyte() && len_utf8 == len_utf16 {
unsafe {
// Create an uninitialized buffer of `capacity` bytes. We need to be careful here to avoid
// accidentally creating a slice of u8 which would be invalid.
let layout = std::alloc::Layout::from_size_align(len_utf16, 1).unwrap();
let data = std::alloc::alloc(layout) as *mut MaybeUninit<u8>;
let buffer = std::ptr::slice_from_raw_parts_mut(data, len_utf16);
// Write to this MaybeUninit buffer, assuming we're going to fill this entire buffer
self.write_one_byte_uninit_v2(
scope,
0,
&mut *buffer,
WriteFlags::kReplaceInvalidUtf8,
);
// Return an owned string from this guaranteed now-initialized data
let buffer = data as *mut u8;
return std::string::String::from_raw_parts(
buffer, len_utf16, len_utf16,
);
}
}
// SAFETY: This allocates a buffer manually using the default allocator using the string's capacity.
// We have a large number of invariants to uphold, so please check changes to this code carefully
unsafe {
// Create an uninitialized buffer of `capacity` bytes. We need to be careful here to avoid