use rong::*;
#[js_export]
pub struct TextEncoder {}
#[js_class]
impl TextEncoder {
#[js_method(constructor)]
pub fn new() -> Self {
Self {}
}
#[js_method(getter, enumerable)]
pub fn encoding(&self) -> String {
"utf-8".to_string()
}
#[js_method]
pub fn encode(&self, ctx: JSContext, input: JSValue) -> JSResult<JSTypedArray> {
let input = if input.is_undefined() || input.is_null() {
String::new()
} else {
input.try_into::<String>()?
};
let bytes = input.as_bytes();
let buffer = JSArrayBuffer::from_bytes(&ctx, bytes)?;
JSTypedArray::from_array_buffer::<u8>(&ctx, buffer, 0, Some(bytes.len()))
}
#[js_method(rename = "encodeInto")]
pub fn encode_into(&self, ctx: JSContext, input: String, dest: JSObject) -> JSResult<JSObject> {
if let Some(typed_array) = JSTypedArray::from_object(dest) {
if typed_array.kind() == JSTypedArrayKind::Uint8 {
let buffer_len = typed_array.byte_length();
let mut buffer = typed_array.buffer()?;
let buffer_data = buffer.as_mut_slice();
let input_bytes = input.as_bytes();
let bytes_to_write = std::cmp::min(buffer_len, input_bytes.len());
buffer_data[..bytes_to_write].copy_from_slice(&input_bytes[..bytes_to_write]);
let result = JSObject::new(&ctx);
result.set("read", bytes_to_write as f64)?;
result.set("written", bytes_to_write as f64)?;
return Ok(result);
}
}
Err(HostError::new(
rong::error::E_INVALID_ARG,
"The \"dest\" argument must be an instance of Uint8Array.",
)
.with_name("TypeError")
.into())
}
}
impl Default for TextEncoder {
fn default() -> Self {
Self::new()
}
}
pub(crate) fn init(ctx: &JSContext) -> JSResult<()> {
ctx.register_class::<TextEncoder>()?;
Ok(())
}