Skip to content

Commit f6c0cf1

Browse files
atoa & btoa global functions
1 parent 558dc4b commit f6c0cf1

File tree

2 files changed

+37
-11
lines changed

2 files changed

+37
-11
lines changed

src/encoding/mod.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ use crate::{
1515
},
1616
};
1717

18-
use self::encoder::{bytes_from_hex, bytes_to_hex_string, Encoder};
18+
use self::encoder::{
19+
bytes_from_b64, bytes_from_hex, bytes_to_b64_string, bytes_to_hex_string, Encoder,
20+
};
1921

2022
pub struct HexModule;
2123

@@ -139,9 +141,21 @@ impl StringBuilder {
139141
}
140142
}
141143

144+
pub fn atob<'js>(ctx: Ctx<'js>, encoded_value: String) -> Result<String> {
145+
let vec = bytes_from_b64(encoded_value.as_bytes()).or_throw(&ctx)?;
146+
Ok(unsafe { String::from_utf8_unchecked(vec) })
147+
}
148+
149+
pub fn btoa(value: String) -> String {
150+
bytes_to_b64_string(value.as_bytes())
151+
}
152+
142153
pub fn init(ctx: &Ctx<'_>) -> Result<()> {
143154
let globals = ctx.globals();
144155

156+
globals.set("atob", Func::from(atob))?;
157+
globals.set("btoa", Func::from(btoa))?;
158+
145159
Class::<TextEncoder>::define(&globals)?;
146160
Class::<TextDecoder>::define(&globals)?;
147161
Class::<StringBuilder>::define(&globals)?;

tests/encoding.test.ts

+22-10
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,28 @@
11
import hex from "hex";
22

3-
it("should encode/decode text", () => {
4-
let hello = "hello";
5-
const encoded = new TextEncoder().encode(hello);
6-
const decoded = new TextDecoder().decode(encoded);
3+
describe("hex", () => {
4+
it("should encode/decode text", () => {
5+
let hello = "hello";
6+
const encoded = new TextEncoder().encode(hello);
7+
const decoded = new TextDecoder().decode(encoded);
78

8-
assert.equal(decoded, hello);
9-
});
9+
assert.equal(decoded, hello);
10+
});
11+
12+
it("should encode/decode hex", () => {
13+
const byteArray = new TextEncoder().encode("hello");
14+
const encoded = hex.encode(byteArray);
1015

11-
it("should encode/decode hex", () => {
12-
const byteArray = new TextEncoder().encode("hello");
13-
const encoded = hex.encode(byteArray);
16+
assert.equal(encoded, "68656c6c6f");
17+
});
18+
});
1419

15-
assert.equal(encoded, "68656c6c6f");
20+
describe("atoa & btoa", () => {
21+
it("btoa/atob", () => {
22+
const text = "Hello, world!";
23+
const encodedData = btoa(text);
24+
assert.equal(encodedData, "SGVsbG8sIHdvcmxkIQ==");
25+
const decodedData = atob(encodedData);
26+
assert.equal(decodedData, text);
27+
});
1628
});

0 commit comments

Comments
 (0)