2022-10-07 00:37:21 -04:00
|
|
|
package funkin.util;
|
|
|
|
|
|
|
|
import haxe.Json;
|
2023-05-30 16:21:24 -04:00
|
|
|
import haxe.io.Bytes;
|
2022-10-07 00:37:21 -04:00
|
|
|
import thx.semver.Version;
|
|
|
|
|
2023-03-18 15:47:23 -04:00
|
|
|
typedef ScoreInput =
|
|
|
|
{
|
|
|
|
var d:Int; // Key pressed
|
|
|
|
var l:Int; // Duration
|
|
|
|
var t:Int; // Start timestamp
|
|
|
|
}
|
|
|
|
|
2022-10-07 00:37:21 -04:00
|
|
|
class SerializerUtil
|
|
|
|
{
|
2023-01-22 22:25:45 -05:00
|
|
|
static final INDENT_CHAR = "\t";
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert a Haxe object to a JSON string.
|
|
|
|
**/
|
|
|
|
public static function toJSON(input:Dynamic, ?pretty:Bool = true):String
|
|
|
|
{
|
|
|
|
return Json.stringify(input, replacer, pretty ? INDENT_CHAR : null);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-06-08 16:30:45 -04:00
|
|
|
* Convert a JSON string to a Haxe object of the chosen type.
|
2023-01-22 22:25:45 -05:00
|
|
|
*/
|
|
|
|
public static function fromJSONTyped<T>(input:String, type:Class<T>):T
|
|
|
|
{
|
|
|
|
return cast Json.parse(input);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert a JSON string to a Haxe object.
|
|
|
|
*/
|
|
|
|
public static function fromJSON(input:String):Dynamic
|
|
|
|
{
|
2023-08-11 14:00:38 -04:00
|
|
|
try
|
|
|
|
{
|
|
|
|
return Json.parse(input);
|
|
|
|
}
|
|
|
|
catch (e)
|
|
|
|
{
|
|
|
|
trace('An error occurred while parsing JSON from string data');
|
|
|
|
trace(e);
|
|
|
|
return null;
|
|
|
|
}
|
2023-01-22 22:25:45 -05:00
|
|
|
}
|
|
|
|
|
2023-05-30 16:21:24 -04:00
|
|
|
/**
|
|
|
|
* Convert a JSON byte array to a Haxe object.
|
|
|
|
*/
|
|
|
|
public static function fromJSONBytes(input:Bytes):Dynamic
|
|
|
|
{
|
2023-06-10 03:59:25 -04:00
|
|
|
try
|
|
|
|
{
|
|
|
|
return Json.parse(input.toString());
|
|
|
|
}
|
|
|
|
catch (e:Dynamic)
|
|
|
|
{
|
|
|
|
trace('An error occurred while parsing JSON from byte data');
|
|
|
|
trace(e);
|
|
|
|
return null;
|
|
|
|
}
|
2023-05-30 16:21:24 -04:00
|
|
|
}
|
|
|
|
|
2023-01-22 22:25:45 -05:00
|
|
|
/**
|
|
|
|
* Customize how certain types are serialized when converting to JSON.
|
|
|
|
*/
|
|
|
|
static function replacer(key:String, value:Dynamic):Dynamic
|
|
|
|
{
|
|
|
|
// Hacky because you can't use `isOfType` on a struct.
|
|
|
|
if (key == "version")
|
|
|
|
{
|
|
|
|
if (Std.isOfType(value, String)) return value;
|
|
|
|
|
|
|
|
// Stringify Version objects.
|
|
|
|
var valueVersion:thx.semver.Version = cast value;
|
|
|
|
var result = '${valueVersion.major}.${valueVersion.minor}.${valueVersion.patch}';
|
|
|
|
if (valueVersion.hasPre) result += '-${valueVersion.pre}';
|
|
|
|
if (valueVersion.hasBuild) result += '+${valueVersion.build}';
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Else, return the value as-is.
|
|
|
|
return value;
|
|
|
|
}
|
2022-10-07 00:37:21 -04:00
|
|
|
}
|