Struct neon::types::JsString

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

The type of JavaScript string primitives.

§Example

// Extract the console.log function:
let console: Handle<JsObject> = cx.global("console")?;
let log: Handle<JsFunction> = console.get(&mut cx, "log")?;

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

// Call console.log(s):
log.call_with(&cx).arg(s).exec(&mut cx)?;

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, U> TryFrom<U> for T
where U: Into<T>,

§

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

§

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.