Skip to content
This repository has been archived by the owner on Jun 9, 2024. It is now read-only.

Commit

Permalink
chore: updated majority of function structures to follow result-orien…
Browse files Browse the repository at this point in the history
…ted flow
  • Loading branch information
scarletquasar committed Sep 25, 2023
1 parent 3632889 commit e6d775c
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 58 deletions.
10 changes: 5 additions & 5 deletions projects/core/logic/api/modules/server/server-basic-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ async function requestAsync(
method: string = "GET",
body: Record<string, any> = {},
headers: Record<string, any> = {}
): Promise<HttpResponse> {
): Promise<Result<Error, HttpResponse>> {
const serializedBodyResult = serialize(body);
const serializedHeadersResult = serialize(headers);

Expand All @@ -46,22 +46,22 @@ async function requestAsync(
headers
));

return new Response(
return Result.right(new Response(
rawResult.Body ?? "",
rawResult.Headers ?? {},
rawResult.Latency ?? 0,
rawResult.StatusCode ?? 599,
rawResult.Ok ?? false
);
));
}

return new Response(
return Result.right(new Response(
"Invalid body or header values",
{},
0,
400,
false
);
));
}

function createHost(options = {
Expand Down
35 changes: 18 additions & 17 deletions projects/core/logic/api/modules/stdlib/encoding-core.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
class TextDecoder {
decode(octets: number[]) {
import { Result } from "./functional-core";

class ByteEncoding {
private memo: Record<string, number[]>;

fromOctets(bytes: number[]): Result<Error, string> {
let string = "";
let i = 0;
while (i < octets.length) {
let octet = octets[i];
while (i < bytes.length) {
let octet = bytes[i];

const getDataFromOctet = (octet: number) => ({
[<any>true]: { bytesNeeded: 0, codePoint: 0 },
Expand All @@ -15,32 +19,29 @@ class TextDecoder {

let { bytesNeeded, codePoint } = getDataFromOctet(octet);

if (octets.length - i - bytesNeeded > 0) {
if (bytes.length - i - bytesNeeded > 0) {
let k = 0;
while (k < bytesNeeded) {
octet = octets[i + k + 1];
octet = bytes[i + k + 1];
codePoint = (codePoint << 6) | (octet & 0x3F);
k += 1;
}
}
else {
codePoint = 0xFFFD;
bytesNeeded = octets.length - i;
bytesNeeded = bytes.length - i;
}

string += String.fromCodePoint(codePoint);
i += bytesNeeded + 1;
}

return string;
return Result.right(string);
}
}

class TextEncoder {
_memo: Record<string, number[]> = {};
encode(string: string) {
if(this._memo[string]) {
return this._memo[string];
toOctets(string: string): Result<Error, number[]> {
if(this.memo[string]) {
return Result.right(this.memo[string]);
}

const octets = [];
Expand Down Expand Up @@ -73,9 +74,9 @@ class TextEncoder {
i += codePoint >= 0x10000 ? 2 : 1;
}

this._memo[string] = octets;
return octets;
this.memo[string] = octets;
return Result.right(octets);
}
}

export { TextDecoder, TextEncoder }
export { ByteEncoding }
7 changes: 5 additions & 2 deletions projects/core/logic/api/modules/stdlib/encryption-core.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { interopCache } from "logic/runtime/interop-cache-core"
import { UUID } from "types/internal/generic-types";
import { Result } from "./functional-core";

function newUuid(type: "v4" = "v4"): UUID {
function newUuid(type: "v4" = "v4"): Result<Error, UUID> {
switch(type) {
case "v4":
return interopCache.guid.newGuid();
return Result.right(interopCache.guid.newGuid());
default:
return Result.left(new Error("Invalid UUID type"));
}
}

Expand Down
14 changes: 7 additions & 7 deletions projects/core/logic/api/modules/stdlib/environment-core.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { interopCache } from "logic/runtime/interop-cache-core";
import { Result } from "./functional-core";

function getArgs() {
return interopCache.environment.getCommandLineArgs();
function getArgs(): Result<Error, string[]> {
return Result.right(interopCache.environment.getCommandLineArgs());
}

function getCurrentDir() {
return interopCache.environment.currentDirectory;
function getCurrentDir(): Result<Error, string> {
return Result.right(interopCache.environment.currentDirectory);
}

function getEnvVar(key: string): Result<Error, string> {
Expand All @@ -23,13 +23,13 @@ function getEnvVar(key: string): Result<Error, string> {
return Result.right(result);
}

function getEnvVars(): Record<string, string> {
return interopCache.environment.getEnvironmentVariables();
function getEnvVars(): Result<Error, Record<string, string>> {
return Result.right(interopCache.environment.getEnvironmentVariables());
}

function setEnvVar(key: string, value: string | number | boolean | bigint) {
const finalValue = value.toString();
interopCache.environment.setEnvironmentVariable(key, finalValue);
return Result.right(interopCache.environment.setEnvironmentVariable(key, finalValue));
}

export { getArgs, getCurrentDir, getEnvVar, getEnvVars, setEnvVar }
12 changes: 5 additions & 7 deletions projects/core/logic/api/modules/stdlib/json-core.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
import { Result } from "./functional-core";

function deserialize<T>(json: string) {
function deserialize<T>(json: string): Result<Error, T> {
try {
const value = JSON.parse(json);
const result = Result.right(value);
return result as T;
return Result.right(value);
}
catch(e) {
return Result.left(e);
}
}

function serialize<T>(target: T) {
function serialize<T>(target: T): Result<Error, string> {
try {
const value = JSON.stringify(target);
const result = Result.right(value);
return result as Result<Error, string>;
return Result.right(value);
}
catch(e) {
return Result.left(e) as Result<Error, string>;
return Result.left(e);
}
}

Expand Down
4 changes: 3 additions & 1 deletion projects/core/logic/api/modules/stdlib/process-core.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { interopCache } from "logic/runtime/interop-cache-core";
import { Result } from "./functional-core";

function exit(exitCode: number) {
function exit(exitCode = 0): Result<Error, never> {
interopCache.process.exit(exitCode);
return Result.left(new Error("Failed to finish the current process")) as Result<Error, never>;
}

function getPid(): number {
Expand Down
10 changes: 5 additions & 5 deletions projects/core/logic/api/modules/stdlib/stdlib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ import { getArgs, getCurrentDir, getEnvVar, getEnvVars, setEnvVar } from "./envi
import { Result } from "./functional-core";
import { deserialize, serialize } from "./json-core";
import { exit, getPid } from "./process-core";
import { Moment } from "./time-core";
import { TextDecoder, TextEncoder } from "./encoding-core";
import { Moment, now } from "./time-core";
import { ByteEncoding } from "./encoding-core";
import { newUuid } from "./encryption-core";

const stdlib = {
encoding: {
TextDecoder,
TextEncoder
ByteEncoding,
},
json: {
serialize,
deserialize
},
time: {
Moment
Moment,
now
},
environment: {
getArgs,
Expand Down
31 changes: 19 additions & 12 deletions projects/core/logic/api/modules/stdlib/time-core.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Result } from "./functional-core";

type MomentArguments = {
year?: number;
month?: number;
Expand Down Expand Up @@ -71,20 +73,25 @@ class Moment {
if (shouldThrow) throw new Error("Invalid values for making a time representation.");
}

copyWith(args: MomentArguments) {
new(modifiers: MomentArguments) {
return new Moment({
year: this._year + args.year ?? 0,
month: this._month + args.month ?? 1,
day: this._day + args.day ?? 0,
hour: this._hour + args.hour ?? 0,
minute: this._minute + args.minute ?? 0,
second: this._second + args.second ?? 0,
millisecond: this._millisecond + args.millisecond ?? 0,
microsecond: this._microsecond + args.microsecond ?? 0,
nanosecond: this._nanosecond + args.nanosecond ?? 0,
timezoneModifier: args.timezoneModifier ?? 0,
year: this._year + modifiers.year ?? 0,
month: this._month + modifiers.month ?? 1,
day: this._day + modifiers.day ?? 0,
hour: this._hour + modifiers.hour ?? 0,
minute: this._minute + modifiers.minute ?? 0,
second: this._second + modifiers.second ?? 0,
millisecond: this._millisecond + modifiers.millisecond ?? 0,
microsecond: this._microsecond + modifiers.microsecond ?? 0,
nanosecond: this._nanosecond + modifiers.nanosecond ?? 0,
timezoneModifier: modifiers.timezoneModifier ?? 0,
});
}
}

export { Moment }
function now(): Result<Error, Moment> {
const moment = new Moment(new Date(performance.now()));
return Result.right(moment);
}

export { Moment, now }
2 changes: 1 addition & 1 deletion projects/core/logic/runtime/interop-cache-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const interopCache = {
setEnvironmentVariable: getStaticMethod<void>("System:Environment:SetEnvironmentVariable")
},
process: {
exit: getStaticMethod<never>("System:Environment:Exit"),
exit: _$internalBinding["ProcessExit"],
getCurrentProcess: getStaticMethod<any>("System.Diagnostics:Process:GetCurrentProcess")
},
guid: {
Expand Down
4 changes: 3 additions & 1 deletion projects/native/MelonRuntime.Core/Library/BindingsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using MelonRuntime.WebServices.Entities;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Dynamic;

namespace MelonRuntime.Core.Library
Expand Down Expand Up @@ -50,7 +51,8 @@ public IDictionary<string, object> GetBindings()
GetTimeBindings(),
new()
{
["NewGuid"] = new Func<string>(() => Guid.NewGuid().ToString())
["NewGuid"] = new Func<string>(() => Guid.NewGuid().ToString()),
["ProcessExit"] = new Action<int>((code) => Environment.Exit(code))
}
};

Expand Down

0 comments on commit e6d775c

Please sign in to comment.