jsbind/
text.rs

1use crate::utils::*;
2use crate::{any::Any, array::Uint8Array};
3use alloc::string::String;
4
5/// JavaScript `TextEncoder` (`new TextEncoder()`).
6#[derive(Clone, Debug, PartialEq, PartialOrd)]
7#[repr(transparent)]
8pub struct TextEncoder {
9    inner: emlite::Val,
10}
11bind!(TextEncoder);
12impl_dyn_cast!(TextEncoder);
13
14impl Default for TextEncoder {
15    fn default() -> Self {
16        Self::new()
17    }
18}
19
20impl TextEncoder {
21    /// `new TextEncoder()` (always UTF-8 in browsers/Node).
22    pub fn new() -> Self {
23        emlite::Val::global("TextEncoder").new(&[]).as_::<Self>()
24    }
25
26    /// `encoder.encode(str)` → `Uint8Array`
27    pub fn encode(&self, s: &str) -> Uint8Array {
28        self.inner.call("encode", &[s.into()]).as_::<Uint8Array>()
29    }
30
31    /// `encoder.encodeInto(src, dst)` → `{ read, written }`
32    pub fn encode_into(&self, src: &str, dst: &mut Uint8Array) -> (usize, usize) {
33        let res = self
34            .inner
35            .call("encodeInto", &[src.into(), dst.clone().into()]);
36        let read = res.get("read").as_::<u32>() as usize;
37        let written = res.get("written").as_::<u32>() as usize;
38        (read, written)
39    }
40}
41
42/// JavaScript `TextDecoder`
43#[derive(Clone, Debug, PartialEq, PartialOrd)]
44#[repr(transparent)]
45pub struct TextDecoder {
46    inner: emlite::Val,
47}
48bind!(TextDecoder);
49impl_dyn_cast!(TextDecoder);
50
51impl TextDecoder {
52    /// `new TextDecoder(label?, options?)`
53    pub fn new(label: Option<String>, opts: Option<&Any>) -> Self {
54        let ctor = emlite::Val::global("TextDecoder");
55        match (label, opts) {
56            (Some(l), Some(o)) => ctor.new(&[l.into(), o.clone()]).as_::<Self>(),
57            (Some(l), None) => ctor.new(&[l.into()]).as_::<Self>(),
58            (None, Some(o)) => ctor.new(&[o.clone()]).as_::<Self>(),
59            (None, None) => ctor.new(&[]).as_::<Self>(),
60        }
61    }
62
63    /// `decoder.decode(input)` – UTF-8 → `String`.
64    pub fn decode(&self, bytes: &Uint8Array) -> Option<String> {
65        self.inner.call("decode", &[bytes.clone().into()]).as_()
66    }
67}