From 2cfdd8e335e62d5a3e8f26f2a480181a159ef3e1 Mon Sep 17 00:00:00 2001 From: TopchetoEU <36534413+TopchetoEU@users.noreply.github.com> Date: Sat, 25 Nov 2023 19:12:56 +0200 Subject: [PATCH] feat: add utf8 encoding and decoding --- .../topchetoeu/jscript/lib/EncodingLib.java | 20 +++++++++++++++++++ src/me/topchetoeu/jscript/lib/Internals.java | 1 + 2 files changed, 21 insertions(+) create mode 100644 src/me/topchetoeu/jscript/lib/EncodingLib.java diff --git a/src/me/topchetoeu/jscript/lib/EncodingLib.java b/src/me/topchetoeu/jscript/lib/EncodingLib.java new file mode 100644 index 0000000..3f7a495 --- /dev/null +++ b/src/me/topchetoeu/jscript/lib/EncodingLib.java @@ -0,0 +1,20 @@ +package me.topchetoeu.jscript.lib; + +import me.topchetoeu.jscript.engine.Context; +import me.topchetoeu.jscript.engine.values.ArrayValue; +import me.topchetoeu.jscript.engine.values.Values; +import me.topchetoeu.jscript.interop.Native; + +@Native("Encoding") +public class EncodingLib { + @Native public static ArrayValue encode(String value) { + var res = new ArrayValue(); + for (var el : value.getBytes()) res.set(null, res.size(), (int)el); + return res; + } + @Native public static String decode(Context ctx, ArrayValue raw) { + var res = new byte[raw.size()]; + for (var i = 0; i < raw.size(); i++) res[i] = (byte)Values.toNumber(ctx, raw.get(i)); + return new String(res); + } +} diff --git a/src/me/topchetoeu/jscript/lib/Internals.java b/src/me/topchetoeu/jscript/lib/Internals.java index 9247779..1409289 100644 --- a/src/me/topchetoeu/jscript/lib/Internals.java +++ b/src/me/topchetoeu/jscript/lib/Internals.java @@ -119,6 +119,7 @@ public class Internals { glob.define(null, "Math", false, wp.getNamespace(MathLib.class)); glob.define(null, "JSON", false, wp.getNamespace(JSONLib.class)); + glob.define(null, "Encoding", false, wp.getNamespace(EncodingLib.class)); glob.define(null, "Date", false, wp.getConstr(DateLib.class)); glob.define(null, "Object", false, wp.getConstr(ObjectLib.class));