-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKat.js
127 lines (122 loc) · 3.4 KB
/
Kat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
* @Package Kat
* @Author 陆之岇(kraity)
* @Studio 南博网络科技工作室
* @GitHub https://github.com/krait-team/kat-php
* @Version 1.0.0
* @Description Data exchange format
*/
let Parser = require('./Parser');
module.exports = class Kat {
/**
*
* @param object
* @returns {string}
*/
static encode(object) {
return this._encode(null, object);
}
/**
*
* @param name
* @param object
* @returns {string}
*/
static _encode(name, object) {
let kat = [];
this.__encode(kat, name, object);
return kat.join('');
}
/**
*
* @param kat
* @param name
* @param object
* @private
*/
static __encode(kat, name, object) {
if (object == null) {
kat.push('n');
if (name != null) {
kat.push(':' + name);
}
kat.push('()');
} else if (object instanceof Error) {
kat.push('E');
if (name != null) {
kat.push(':' + name);
}
kat.push('{i:code(' + (object.code == null ? 0 : object.code) + ')s:msg(' + object.message + ')}');
} else if (object instanceof Array) {
kat.push('A');
if (name != null) {
kat.push(':' + name);
}
kat.push('{');
for (let i = 0, len = object.length; i < len; i++) {
this.__encode(kat, null, object[i]);
}
kat.push('}');
} else if (object instanceof Object) {
kat.push('M');
if (name != null) {
kat.push(':' + name);
}
kat.push('{');
for (let key in object) {
this.__encode(kat, key, object[key]);
}
kat.push('}');
} else {
switch (typeof object) {
case 'string': {
kat.push('s');
if (name != null) {
kat.push(':' + name);
}
kat.push('(' + object.replace(/([()^])/g, "^$1") + ')');
break;
}
case 'number': {
let obj = object.toString(), larger = object > 2147483647;
kat.push(obj.indexOf('.') === -1 ? (larger ? 'l' : 'i') : (larger ? 'd' : 'f'));
if (name != null) {
kat.push(':' + name);
}
kat.push(`(${obj})`);
break;
}
case 'boolean': {
kat.push('b');
if (name != null) {
kat.push(':' + name);
}
kat.push('(' + (object ? '1' : '0') + ')');
break;
}
default: {
kat.push('n');
if (name != null) {
kat.push(':' + name);
}
kat.push('()');
}
}
}
}
/**
*
* @param kat
* @returns {*}
*/
static decode(kat) {
switch (kat.charCodeAt(0)) {
case 91:
case 123:
return JSON.parse(kat);
}
let parser = new Parser();
parser.read(kat);
return parser.export();
}
}