Skip to main content

JsString

Struct JsString 

Source
pub struct JsString(/* private fields */);
Expand description

ECMAScript strings are sequences of UTF-16 code units, not UTF-8 scalar values. Compact Latin-1/UTF-16 leaves and bounded ropes mirror QuickJS’s current representation while preserving lone surrogates.

Implementations§

Source§

impl JsString

Source

pub const MAX_LEN: usize

QuickJS reserves 30 bits for a string’s UTF-16 code-unit length.

Source

pub fn downgrade(&self) -> WeakJsString

Source

pub fn same_representation(&self, other: &Self) -> bool

Source

pub fn content_hash(&self) -> u32

Source

pub fn checked_length_with_limit( current: usize, additional: usize, limit: usize, ) -> Result<usize, JsStringError>

Source

pub fn checked_length( current: usize, additional: usize, ) -> Result<usize, JsStringError>

Source

pub fn try_from_utf8(value: &str) -> Result<Self, JsStringError>

Construct a dynamically supplied UTF-8 string while enforcing QuickJS’s 30-bit UTF-16 length limit.

§Errors

Returns JsStringError::TooLong when the decoded value exceeds Self::MAX_LEN. Recoverable allocator failure remains a separate parity gap.

Source

pub fn try_from_bytes(value: &[u8]) -> Result<Self, JsStringError>

Decode the byte-oriented input accepted by QuickJS JS_NewStringLen.

This is deliberately not Rust’s strict or standard lossy UTF-8 decoder. Three-byte surrogate encodings are preserved as UTF-16 code units, non-BMP scalars become surrogate pairs, and malformed sequences use QuickJS’s release-pinned replacement-and-skip algorithm. Embedded NUL bytes are ordinary U+0000 code units because the input length is explicit.

§Errors

Returns JsStringError::TooLong when the decoded value exceeds Self::MAX_LEN UTF-16 code units. Recoverable allocation failure for String storage remains a separate parity gap.

Source

pub fn from_static(value: &'static str) -> Self

Construct one of the engine’s trusted static table/literal strings. Dynamic host input must use Self::try_from_utf8.

Source

pub fn try_from_utf16( units: impl IntoIterator<Item = u16>, ) -> Result<Self, JsStringError>

Construct a dynamically supplied UTF-16 string while enforcing QuickJS’s 30-bit code-unit length limit.

The iterator is consumed only after its lower size bound is validated; a dishonest or unbounded upper hint is never used for an enormous eager allocation.

§Errors

Returns JsStringError::TooLong when the value exceeds Self::MAX_LEN. Recoverable allocator failure remains a separate parity gap.

Source

pub fn try_from_utf16_with_limit( units: impl IntoIterator<Item = u16>, max_len: usize, ) -> Result<Self, JsStringError>

Source

pub fn from_owned_latin1(units: Vec<u8>) -> Self

Adopt a checked narrow result buffer without collecting its contents a second time. Callers must have enforced Self::MAX_LEN.

Source

pub fn from_fresh_decimal_u32(value: u32) -> Self

Materialize QuickJS’s JS_AtomToString result for one tagged integer atom. The returned narrow String deliberately owns a fresh representation on every call; routing this spelling through an atom or constant pool would make QuickJS’s representation identity observable.

Source

pub fn try_from_latin1(units: &[u8]) -> Result<Self, JsStringError>

A copy of Latin-1 code units.

§Errors

Returns JsStringError::TooLong past Self::MAX_LEN.

Source

pub fn try_from_utf16_slice(units: &[u16]) -> Result<Self, JsStringError>

A copy of UTF-16 code units, stored narrow when every unit fits in a byte.

§Errors

Returns JsStringError::TooLong past Self::MAX_LEN.

Source

pub fn from_owned_utf16(units: Vec<u16>) -> Self

Adopt a checked wide result buffer without collecting its contents a second time. Callers must have enforced Self::MAX_LEN.

Source

pub fn from_code_unit(unit: u16) -> Self

Build the compact one-code-unit form used by String exotic indices and character methods, equivalent to QuickJS’s js_new_string_char.

Source

pub fn len(&self) -> usize

Source

pub fn is_empty(&self) -> bool

Source

pub fn utf16_units(&self) -> impl ExactSizeIterator<Item = u16> + '_

Source

pub fn code_unit_at(&self, index: usize) -> Option<u16>

Return one UTF-16 code unit without decoding or normalizing surrogate pairs. This is the equivalent of QuickJS’s string_get fast path.

Source

pub fn code_point_at(&self, index: usize) -> Option<u32>

Return the code point beginning at one UTF-16 code-unit index. A lead surrogate is combined only with an immediately following trail surrogate; every other code unit is returned unchanged.

Source

pub fn is_well_formed(&self) -> bool

Whether every surrogate participates in a valid UTF-16 pair.

Source

pub fn to_well_formed(&self) -> Self

Replace each unpaired surrogate with U+FFFD. Well-formed strings retain their existing compact allocation, matching QuickJS’s no-copy path.

Source

pub fn is_wide(&self) -> bool

Source

pub fn is_flat(&self) -> bool

Source

pub fn for_each_flat_leaf(&self, visitor: impl FnMut(&Self))

Visit the current flat leaves in logical order without linearizing a rope. QuickJS’s diagnostic String printer decodes each leaf independently, so surrogate pairs do not cross a live rope boundary. A previously linearized rope exposes its replacement flat value as one leaf, matching QuickJS’s in-place flat + empty transition.

Source

pub fn linearize(&self) -> Self

Return a compact flat string, caching the result on a rope. This is the safe-Rust equivalent of QuickJS js_linearize_string_rope.

Source

pub fn sub_string(&self, start: usize, end: usize) -> Self

Copy one validated UTF-16 code-unit range with QuickJS js_sub_string representation rules. Ropes are linearized once, a full-range request reuses that flat handle, Latin-1 ranges copy their bytes directly, and UTF-16 ranges scan only the selected units before choosing a single Latin-1 or UTF-16 allocation.

Source

pub fn repeat_with_limit( &self, count: usize, max_len: usize, ) -> Result<Self, JsStringError>

Repeat one linearized String into the single flat allocation produced by QuickJS js_string_repeat. The checked product uses the caller-supplied limit so native white-box tests can exercise the length failure without attempting a near-gigabyte allocation.

Source

pub fn pad_with_limit( &self, target_len: usize, filler: Option<&Self>, pad_at_end: bool, max_len: usize, ) -> Result<Self, JsStringError>

Build the one flat result of pinned QuickJS js_string_pad while retaining its narrow-first StringBuffer behavior. A wide code unit triggers one fallible widening reservation at the point it is copied; unused wide units in a truncated filler therefore do not widen the result.

Source

pub fn trim_whitespace( &self, trim_start: bool, trim_end: bool, ) -> Result<Self, JsStringError>

Trim the selected ends with pinned QuickJS js_string_trim and js_sub_string representation rules. Full-range and empty results do not enter or consume the partial-substring reservation path; a partial wide range narrows when every retained UTF-16 code unit fits Latin-1.

Source

pub fn try_concat(&self, other: &Self) -> Result<Self, JsStringError>

Concatenate with QuickJS’s short-flat/rope thresholds, bounded depth, Fibonacci rebalance and 30-bit length cap.

§Errors

Returns JsStringError::TooLong when the result would exceed Self::MAX_LEN UTF-16 code units.

Source

pub fn concat_owned(self, other: &Self) -> Result<Self, JsStringError>

Append to an exclusively owned compatible flat buffer. Shared strings and ropes retain the ordinary concatenation representation rules. The same short-flat thresholds apply even to an exclusively owned buffer.

§Errors

Rejects lengths above MAX_LEN and reports reservation failure.

Source

pub fn try_to_wtf8_bytes(&self) -> Result<Vec<u8>, TryReserveError>

Encode the byte slice exposed by QuickJS JS_ToCStringLen2 when its cesu8 flag is false.

Valid surrogate pairs become standard four-byte UTF-8. Unpaired surrogates are deliberately retained as three-byte WTF-8 sequences. Embedded U+0000 is returned as an ordinary zero byte; the terminating C NUL owned by QuickJS is not part of its reported length and is therefore not included in this safe Rust byte vector. As in QuickJS, converting a rope caches its flat representation on the shared String identity.

§Errors

Returns TryReserveError if the output buffer cannot be reserved.

Source

pub fn try_append_wtf8_bytes( &self, output: &mut Vec<u8>, ) -> Result<(), TryReserveError>

Append the WTF-8 bytes exposed by JS_ToCStringLen2(..., false) to an existing buffer while preserving the same rope-linearization side effect as Self::try_to_wtf8_bytes.

Source

pub fn try_to_cesu8_bytes(&self) -> Result<Vec<u8>, TryReserveError>

Encode the byte slice exposed by QuickJS JS_ToCStringLen2 when its cesu8 flag is true.

Every UTF-16 code unit is encoded independently, so a valid surrogate pair occupies two three-byte CESU-8 sequences. Embedded U+0000 is retained and no trailing C NUL is included in the returned vector. Rope conversion has the same shared flat-cache transition as the WTF-8 path.

§Errors

Returns TryReserveError if the output buffer cannot be reserved.

Source

pub fn wtf8_bytes(&self) -> impl Iterator<Item = u8>

Source

pub fn push_c_string_to(&self, output: &mut NativeErrorMessage)

Source

pub fn push_atom_get_str_to(&self, output: &mut NativeErrorMessage)

Reproduce JS_AtomGetStr(..., char buf[64], 64) as consumed by a C %s native-error argument. Narrow all-ASCII atoms bypass the scratch buffer; every other text atom is encoded one UTF-16 code unit at a time and stops before starting a unit once 58 bytes have already been written.

Source

pub fn to_utf8_lossy(&self) -> String

Lossy conversion is suitable for terminal diagnostics. It must not be used for language-level string comparison or indexing.

Trait Implementations§

Source§

impl Clone for JsString

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for JsString

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for JsString

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for JsString

Source§

impl From<JsString> for Value

Source§

fn from(value: JsString) -> Self

Converts to this type from the input type.
Source§

impl FromJs for JsString

ToString.

Source§

fn from_js(js: &mut impl Js, value: Value) -> JsResult<Self>

Source§

impl Hash for JsString

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl IntoJs for JsString

Source§

fn into_js(self, _: &mut impl Js) -> JsResult<Value>

Source§

impl PartialEq for JsString

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.