Skip to main content

Wtf8

Struct Wtf8 

Source
pub struct Wtf8 { /* private fields */ }
Expand description

A JavaScript string’s bytes, in WTF-8.

A JS string is a sequence of UTF-16 code units, and that sequence may contain an unpaired surrogate: String.fromCharCode(0xD800) produces exactly one, and "\uD800".length is 1. Rust’s String cannot represent that, so the bytes here are WTF-8 — ordinary UTF-8, except that a code unit with no partner is written as the three-byte sequence UTF-8 would use for U+D800..U+DFFF.

§The encoding is canonical, and that is load-bearing

A surrogate pair is written as the single four-byte sequence of the astral code point it spells, never as two three-byte sequences. Without that rule the bytes of "\uD800" + "\uDC00" would differ from the bytes of "\u{10000}" while the two strings are observably identical — same length, same charCodeAt at every index — and every equality, property key and switch arm in the engine would disagree with the language.

The canonical form makes byte equality exactly code-unit equality, which is what lets a property key be compared without decoding it.

Implementations§

Source§

impl Wtf8

Source

pub fn new(text: impl Into<String>) -> Wtf8

Wrap a Rust string, which is valid UTF-8 by construction.

Source

pub fn from_rc_str(text: &str) -> Wtf8

Build from a &str without copying it.

Wtf8::new takes impl Into<String>, which copies. A property atom is a &str that already lives in the compiled code and outlives every use of the key, so sharing the bytes is free — and this is on the path of every property access.

Source

pub fn from_parts(bytes: Vec<u8>, valid: bool) -> Wtf8

Build from bytes that are already WTF-8, with valid saying whether they contain an unpaired surrogate.

Used by the rope’s flattening path, which has just concatenated children whose validity it knows.

Source

pub fn allocated_bytes(&self) -> usize

Whether the bytes are valid UTF-8, i.e. the string has no unpaired surrogate. The bytes this string is holding on to — the buffer’s capacity when it owns one.

A Vec doubles, so a string built by 200,000 appends holds up to twice its length; the heap accounting must charge for what is really allocated, not for what is used.

Source

pub fn is_valid(&self) -> bool

Whether the text is well-formed — no unpaired surrogate.

The one thing the bytes alone cannot answer without decoding, so it is computed once at construction.

Source

pub fn from_code_points(points: &[u32]) -> Wtf8

Build from code points, folding astral ones into the pair they spell.

The inverse of Wtf8::code_point_values: a value in 0xD800..=0xDFFF is taken to be a lone surrogate rather than an error, because that is what a code point list from this type can legitimately contain.

Source

pub fn from_wtf8_bytes(bytes: &[u8]) -> Option<Wtf8>

Build from UTF-16 code units, which is the form a JS string really has.

An unpaired surrogate survives; a pair is folded into its astral code point. Decode WTF-8 bytes, canonicalising them.

The strict counterpart of Wtf8::as_bytes, for text that came from outside the process: a serialised bytecode blob carries atoms and string constants as raw bytes, and one of them may be an unpaired surrogate. String::from_utf8 would reject it, which is why this exists rather than from.

None for bytes that are not WTF-8 at all — a truncated sequence, a stray continuation byte, or an overlong encoding. The code units are then re-encoded through Wtf8::from_units, so the result is canonical even if the input wrote a surrogate pair as two three-byte sequences.

Source

pub fn from_units(units: &[u16]) -> Wtf8

Build from UTF-16 code units, which is the form a JS string really has.

A surrogate pair is folded into the astral code point it spells, so the result is canonical: this is where the encoding’s invariant is enforced, and therefore the only place that has to know about it.

Source

pub fn as_str(&self) -> Option<&str>

The text, when it is valid UTF-8.

None only for a string containing an unpaired surrogate — there is no &str for one. Callers that only need to display or compare use Wtf8::to_string_lossy.

Source

pub fn to_string_lossy(&self) -> Cow<'_, str>

The text with unpaired surrogates replaced by U+FFFD.

Borrowed, and therefore free, for the ordinary string that has no surrogate.

Source

pub fn as_bytes(&self) -> &[u8] ⓘ

The WTF-8 bytes. Two Wtf8s are equal exactly when these are.

Source

pub fn to_units(&self) -> Vec<u16>

The UTF-16 code units, which is what indexing and charCodeAt count.

Source

pub fn utf16_len(&self) -> usize

Length in UTF-16 code units, which is what String.prototype.length reports.

Counted from the encoding rather than by decoding, so it does not allocate: a four-byte sequence is a surrogate pair and therefore two units, everything else is one.

Source

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

The code unit at index, or None past the end.

Source

pub fn is_empty(&self) -> bool

Whether the string is empty.

Source

pub fn unit_at(&self, index: usize) -> Option<Wtf8>

One code unit as a string, which is what s[i] yields.

A single unit, not a code point: "\u{1F600}"[0] is the lone high surrogate, because indexing a string in JS works on code units.

Source

pub fn slice_units(&self, start: usize, end: usize) -> Wtf8

The code units start..end, re-encoded canonically.

Source

pub fn code_points(&self) -> Vec<Wtf8>

One element per code point, which is how a string is iterated.

Iteration and indexing disagree on purpose: [...str] splits an astral character into one element while str[0] splits it into half a surrogate pair.

Source

pub fn concat(&self, other: &Wtf8) -> Wtf8

Concatenate, keeping the encoding canonical.

Byte concatenation is already canonical except where a high surrogate at the end of self meets a low surrogate at the start of other: those two must fold into one astral sequence, or the result would be a different string from the one the language says + produces.

Source

pub fn append_in_place(&mut self, other: &Wtf8) -> Option<usize>

Append other to this string in place, when the buffer is unshared.

Returns the number of bytes added, or None when the append could not be done in place. That is the whole point of [Bytes::Owned]: s += t in a loop is a copy of the entire string per iteration unless the buffer can grow, which is why the reference has JS_ConcatStringInPlace — and why string:concat was the slowest case in the suite (0.06×) before this.

Three conditions, each one a correctness requirement rather than a heuristic:

  • The bytes must be owned and unshared. Rc::get_mut answers that; a shared buffer belongs to another visible string and appending to it would change that string too.
  • The two must not meet at a surrogate boundary. Byte concatenation is already canonical except where a high surrogate at the end meets a low surrogate at the start, and there the result would be a different string from the one + builds. Falling back is cheap and always correct.
  • valid must stay right, which the caller-facing wrapper re-derives from the two inputs.
Source

pub fn code_point_values(&self) -> Vec<u32>

The code points the regular expression engine matches against.

This is Wtf8::code_points flattened to u32, with a lone surrogate kept as its own value rather than becoming U+FFFD: \p{Cs} has to match it, and no char can hold it. A valid pair is one code point, so an offset into this list is still a code point boundary.

Trait Implementations§

Source§

impl Clone for Wtf8

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 Wtf8

Source§

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

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

impl Default for Wtf8

Source§

fn default() -> Wtf8

The empty string, which is also what a missing atom’s text is.

Source§

impl Eq for Wtf8

Source§

impl Hash for Wtf8

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 PartialEq for Wtf8

Source§

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

Byte equality, which the canonical encoding makes equal to code-unit equality.

1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl PartialEq<&str> for Wtf8

Source§

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

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

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

Inequality operator !=. Read more
Source§

impl PartialEq<str> for Wtf8

Comparing against a &str literal, which is exact rather than approximate.

A Wtf8 holding an unpaired surrogate has no &str form at all, so it can never equal one; the comparison is as_str() == Some(other) and cannot conflate two different strings. Without this, every key == "prototype" in the parser would have to spell out the Option and the reason for it at each site.

Source§

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

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

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

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl !Send for Wtf8

§

impl !Sync for Wtf8

§

impl Forget for Wtf8

§

impl Freeze for Wtf8
where *const RcInner<[u8]> is !null: Freeze, PhantomData<RcInner<[u8]>>: Freeze, *const RcInner<Vec<u8>> is !null: Freeze, PhantomData<RcInner<Vec<u8>>>: Freeze,

§

impl Move for Wtf8

§

impl RefUnwindSafe for Wtf8

§

impl Unpin for Wtf8
where Rc<[u8]>: Unpin, Rc<Vec<u8>>: Unpin,

§

impl UnsafeUnpin for Wtf8
where *const RcInner<[u8]> is !null: UnsafeUnpin, PhantomData<RcInner<[u8]>>: UnsafeUnpin, *const RcInner<Vec<u8>> is !null: UnsafeUnpin, PhantomData<RcInner<Vec<u8>>>: UnsafeUnpin,

§

impl UnwindSafe for Wtf8
where Rc<[u8]>: UnwindSafe, Rc<Vec<u8>>: UnwindSafe,

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, 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.