neon::types

Struct JsString

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

The type of JavaScript string primitives.

§Example

// Create a string:
let s = cx.string("hello 🥹");

// Call console.log(s):
cx.global::<JsObject>("console")?.method(&mut cx, "log")?.arg(s)?.exec()?;

Implementations§

Source§

impl JsString

Source

pub fn size<'a, C: Context<'a>>(&self, cx: &mut C) -> usize

Returns the size of the UTF-8 representation of this string, measured in 8-bit code units.

Equivalent to self.value(cx).len() (but more efficient).

§Example

The string "hello 🥹" encodes as 10 bytes in UTF-8:

  • 6 bytes for "hello " (including the space).
  • 4 bytes for the emoji "🥹".
let str = cx.string("hello 🥹");
assert_eq!(10, str.size(&mut cx));
Source

pub fn size_utf16<'a, C: Context<'a>>(&self, cx: &mut C) -> usize

Returns the size of the UTF-16 representation of this string, measured in 16-bit code units.

Equivalent to self.to_utf16(cx).len() (but more efficient).

§Example

The string "hello 🥹" encodes as 8 code units in UTF-16:

  • 6 u16s for "hello " (including the space).
  • 2 u16s for the emoji "🥹".
let str = cx.string("hello 🥹");
assert_eq!(8, str.size_utf16(&mut cx));
Source

pub fn value<'a, C: Context<'a>>(&self, cx: &mut C) -> String

Convert this JavaScript string into a Rust String.

§Example

This example function expects a single JavaScript string as argument and prints it out.

fn print_string(mut cx: FunctionContext) -> JsResult<JsUndefined> {
    let s = cx.argument::<JsString>(0)?.value(&mut cx);
    println!("JavaScript string contents: {}", s);

    Ok(cx.undefined())
}
Source

pub fn to_utf16<'a, C: Context<'a>>(&self, cx: &mut C) -> Vec<u16>

Convert this JavaScript string into a Vec<u16> encoded as UTF-16.

The returned vector is guaranteed to be valid UTF-16, so libraries that handle UTF-16-encoded strings can assume the content to be valid.

§Example

This example function expects a single JavaScript string as argument and prints it out as a raw vector of u16s.

fn print_string_as_utf16(mut cx: FunctionContext) -> JsResult<JsUndefined> {
    let s = cx.argument::<JsString>(0)?.to_utf16(&mut cx);
    println!("JavaScript string as raw UTF-16: {:?}", s);

    Ok(cx.undefined())
}

This next example function also expects a single JavaScript string as argument and converts to a Vec<u16>, but utilizes the widestring crate to handle the vector as a typical string.

use widestring::Utf16String;

fn print_with_widestring(mut cx: FunctionContext) -> JsResult<JsUndefined> {
    let s = cx.argument::<JsString>(0)?.to_utf16(&mut cx);

    // The returned vector is guaranteed to be valid UTF-16, so we can
    // safely skip the validation step.
    let s = unsafe { Utf16String::from_vec_unchecked(s) };

    println!("JavaScript string as UTF-16: {}", s);

    Ok(cx.undefined())
}
Source

pub fn new<'a, C: Context<'a>, S: AsRef<str>>( cx: &mut C, val: S, ) -> Handle<'a, JsString>

Creates a new JsString value from a Rust string by copying its contents.

This method panics if the string is longer than the maximum string size allowed by the JavaScript engine.

§Example
let str = JsString::new(&mut cx, "hello 🥹");
assert_eq!(10, str.size(&mut cx));

See also: Context::string

Source

pub fn try_new<'a, C: Context<'a>, S: AsRef<str>>( cx: &mut C, val: S, ) -> StringResult<'a>

Tries to create a new JsString value from a Rust string by copying its contents.

Returns Err(StringOverflow) if the string is longer than the maximum string size allowed by the JavaScript engine.

§Example

This example tries to construct a JavaScript string from a Rust string of unknown length, and on overflow generates an alternate truncated string with a suffix ("[…]") to indicate the truncation.

let s = match JsString::try_new(&mut cx, str) {
    Ok(s) => s,
    Err(_) => cx.string(format!("{}[…]", &str[0..32])),
};

Trait Implementations§

Source§

impl Debug for JsString

Source§

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

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

impl Value for JsString

Source§

fn to_string<'cx, C: Context<'cx>>(&self, cx: &mut C) -> JsResult<'cx, JsString>

Source§

fn as_value<'cx, C: Context<'cx>>(&self, _: &mut C) -> Handle<'cx, JsValue>

Source§

fn to_raw(&self) -> Value

Available on crate feature sys only.
Get a raw reference to the wrapped Node-API value.
Source§

unsafe fn from_raw<'cx, C: Context<'cx>>( cx: &C, value: Value, ) -> Handle<'cx, Self>

Available on crate feature sys only.
Creates a value from a raw Node-API value. 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> 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.